dexie-cloud-addon 4.4.6 → 4.4.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modern/DXCWebSocketStatus.d.ts +1 -1
- package/dist/modern/DexieCloudAPI.d.ts +1 -1
- package/dist/modern/authentication/AuthPersistedContext.d.ts +2 -2
- package/dist/modern/currentUserEmitter.d.ts +3 -3
- package/dist/modern/db/entities/Member.d.ts +3 -3
- package/dist/modern/db/entities/PersistedSyncState.d.ts +1 -1
- package/dist/modern/db/entities/Role.d.ts +3 -3
- package/dist/modern/default-ui/Dialog.d.ts +1 -1
- package/dist/modern/default-ui/index.d.ts +5 -5
- package/dist/modern/dexie-cloud-addon.js +653 -531
- package/dist/modern/dexie-cloud-addon.js.map +1 -1
- package/dist/modern/dexie-cloud-addon.min.js +1 -1
- package/dist/modern/dexie-cloud-addon.min.js.map +1 -1
- package/dist/modern/dexie-cloud-client.d.ts +1 -1
- package/dist/modern/helpers/BroadcastedAndLocalEvent.d.ts +2 -2
- package/dist/modern/helpers/getSyncableTables.d.ts +3 -3
- package/dist/modern/helpers/resolveText.d.ts +1 -1
- package/dist/modern/middleware-helpers/guardedTable.d.ts +1 -1
- package/dist/modern/service-worker.js +655 -533
- package/dist/modern/service-worker.js.map +1 -1
- package/dist/modern/service-worker.min.js +1 -1
- package/dist/modern/service-worker.min.js.map +1 -1
- package/dist/modern/sync/BlobDownloadTracker.d.ts +7 -4
- package/dist/modern/sync/extractRealm.d.ts +1 -1
- package/dist/modern/sync/getTablesToSyncify.d.ts +2 -2
- package/dist/modern/sync/isSyncNeeded.d.ts +1 -1
- package/dist/modern/sync/messageConsumerIsReady.d.ts +1 -1
- package/dist/modern/sync/modifyLocalObjectsWithNewUserId.d.ts +3 -3
- package/dist/modern/sync/numUnsyncedMutations.d.ts +1 -1
- package/dist/modern/sync/performGuardedJob.d.ts +1 -1
- package/dist/modern/sync/registerSyncEvent.d.ts +1 -1
- package/dist/modern/sync/triggerSync.d.ts +2 -2
- package/dist/modern/types/DXCUserInteraction.d.ts +2 -2
- package/dist/modern/types/SyncState.d.ts +2 -2
- package/dist/modern/types/TXExpandos.d.ts +1 -1
- package/dist/modern/updateSchemaFromOptions.d.ts +2 -2
- package/dist/modern/verifyConfig.d.ts +1 -1
- package/dist/modern/verifySchema.d.ts +1 -1
- package/dist/modern/yjs/YTable.d.ts +3 -3
- package/dist/modern/yjs/getUpdatesTable.d.ts +2 -2
- package/dist/modern/yjs/reopenDocSignal.d.ts +2 -2
- package/dist/umd/dexie-cloud-addon.js +661 -539
- package/dist/umd/dexie-cloud-addon.js.map +1 -1
- package/dist/umd/dexie-cloud-addon.min.js +1 -1
- package/dist/umd/dexie-cloud-addon.min.js.map +1 -1
- package/dist/umd/service-worker.js +663 -541
- package/dist/umd/service-worker.js.map +1 -1
- package/dist/umd/service-worker.min.js +1 -1
- package/dist/umd/service-worker.min.js.map +1 -1
- package/package.json +2 -2
|
@@ -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{l(r.next(e))}catch(e){i(e)}}function c(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,c)}l((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 c(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),c("next"),c("throw"),c("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),r[Symbol.asyncIterator]=function(){return this},r;function c(e,t){s[e]&&(r[e]=function(t){return new Promise(function(n,r){i.push([e,t,n,r])>1||l(e,t)})},t&&(r[e]=t(r[e])))}function l(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){l("next",e)}function u(e){l("throw",e)}function d(e,t){e(t),i.shift(),i.length&&l(i[0][0],i[0][1])}}function l(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=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{toString:a}={};const u={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}};class d{constructor(e,t){this.buf=e,this.type=t}}var h;const f=Symbol.for("TSONRef");class p{constructor(e,t,n,r){this.type=e,this.ref=t,this.size=n,this.contentType=r,this[h]=!0,Object.freeze(this)}async resolve(){if(!p.resolver)throw new Error("TSONRef.resolver not configured. Set TSONRef.resolver to a function that fetches blobs.");const e=await p.resolver(this);return this.reconstruct(e)}reconstruct(e){const t=(t,n)=>{if(e.byteLength%t!==0)throw new RangeError(`Buffer length ${e.byteLength} is not aligned to ${t} bytes for ${n}`)};switch(this.type){case"ArrayBuffer":default:return e;case"Uint8Array":return new Uint8Array(e);case"Blob":return new Blob([e],{type:this.contentType});case"Int8Array":return new Int8Array(e);case"Uint8ClampedArray":return new Uint8ClampedArray(e);case"Int16Array":return t(2,"Int16Array"),new Int16Array(e);case"Uint16Array":return t(2,"Uint16Array"),new Uint16Array(e);case"Int32Array":return t(4,"Int32Array"),new Int32Array(e);case"Uint32Array":return t(4,"Uint32Array"),new Uint32Array(e);case"Float32Array":return t(4,"Float32Array"),new Float32Array(e);case"Float64Array":return t(8,"Float64Array"),new Float64Array(e);case"BigInt64Array":return t(8,"BigInt64Array"),new BigInt64Array(e);case"BigUint64Array":return t(8,"BigUint64Array"),new BigUint64Array(e)}}static isTSONRef(e){return null!==e&&"object"==typeof e&&f in e&&!0===e[f]}static isTSONRefData(e){return null!==e&&"object"==typeof e&&"$ref"in e&&"$t"in e&&"$size"in e}static fromData(e){return new p(e.$t,e.$ref,e.$size,e.$ct)}toJSON(){const e={$t:this.type,$ref:this.ref,$size:this.size};return this.contentType&&(e.$ct=this.contentType),e}}function g(e){const t=new XMLHttpRequest;t.overrideMimeType("text/plain; charset=x-user-defined");const n=URL.createObjectURL(e);try{if(t.open("GET",n,!1),t.send(),200!==t.status&&0!==t.status)throw new Error("Bad Blob access: "+t.status);return t.responseText}finally{URL.revokeObjectURL(n)}}h=f,p.TYPE_SYMBOL=f,p.resolver=null;const y={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)}},m={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},b={Set:{replace:e=>({$t:"Set",v:Array.from(e)}),revive:({v:e})=>new Set(e)}},v={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}},w="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0,_=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce((e,t)=>({...e,[t]:{replace:(e,n,r)=>{const s=e.buffer,i=0===e.byteOffset&&e.byteLength===s.byteLength?s:s.slice(e.byteOffset,e.byteOffset+e.byteLength);return{$t:t,v:r.ArrayBuffer.replace(i,n,r).v}},revive:({v:e},n,r)=>{const s=w[t];return s&&new s(r.ArrayBuffer.revive({v:e},n,r))}}}),{}),k="fromBase64"in Uint8Array,S="toBase64"in Uint8Array.prototype,x="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):k?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},E="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):S?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,Array.from(r)))}return btoa(n.join(""))};function C(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=O[e[n]];return t}(E(e))}function A(e){return x(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+=I[e[n]];return t}(e))}const I={"-":"=",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:"+","|":"/"},O={};for(const e of Object.keys(I))O[I[e]]=e;const D={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:C(e)}),revive:({v:e})=>{const t=A(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};function j(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}const T={Blob:{test:(e,t)=>"Blob"===t||e instanceof d,replace:e=>({$t:"Blob",v:E(e instanceof d?e.buf:j(g(e))),type:e.type}),revive:({type:e,v:t})=>{const n=x(t),r=n.buffer.byteLength===n.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);return"undefined"!=typeof Blob?new Blob([new Uint8Array(r)],{type:e}):new d(r,e)}}},U={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:E(j(g(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const s=x(t),i=s.buffer.byteLength===s.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);return new File([new Uint8Array(i)],n,{type:e,lastModified:new Date(r).getTime()})}}},P={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},L="undefined"!=typeof crypto?crypto.getRandomValues.bind(crypto):e=>{for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())};let R=0;const $={}.hasOwnProperty;function M(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)M(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var o=t.substr(0,i),c=t.substr(i+1);if(""===c)void 0===n?Array.isArray(e)?isNaN(parseInt(o))||e.splice(parseInt(o),1):delete e[o]:e[o]=n;else{var l=e[o];l&&function(e,t){return $.call(e,t)}(e,o)||(l=e[o]={}),M(l,c,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const B="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=N)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function N(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(W))}function W(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(W)}function z(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))M(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 K(e,t){for(const{table:n,muts:r}of t)for(const t of r)z(e,n,t)}const V=Math.floor,H=Math.abs,J=(e,t)=>e<t?e:t,q=(e,t)=>e>t?e:t,Y=e=>0!==e?e<0:1/e<0,G=64,Q=128,X=127,Z=Number.MAX_SAFE_INTEGER,ee=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&V(e)===e),te=()=>new Set,ne=e=>e[e.length-1],re=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},se=Array.from,ie=Array.isArray,oe=/^\s*/g,ce=/([A-Z])/g,le=(e,t)=>(e=>e.replace(oe,""))(e.replace(ce,e=>`${t}${(e=>e.toLowerCase())(e)}`)),ae="undefined"!=typeof TextEncoder?new TextEncoder:null,ue=ae?e=>ae.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 de="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});de&&1===de.decode(new Uint8Array).length&&(de=null);class he{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const fe=()=>new he,pe=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},ge=(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},ye=ge,me=(e,t)=>{for(;t>X;)ge(e,Q|X&t),t=V(t/128);ge(e,X&t)},be=(e,t)=>{const n=Y(t);for(n&&(t=-t),ge(e,(t>63?Q:0)|(n?G:0)|63&t),t=V(t/64);t>0;)ge(e,(t>X?Q:0)|X&t),t=V(t/128)},ve=new Uint8Array(3e4),we=ve.length/3,_e=ae&&ae.encodeInto?(e,t)=>{if(t.length<we){const n=ae.encodeInto(t,ve).written||0;me(e,n);for(let t=0;t<n;t++)ge(e,ve[t])}else Se(e,ue(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;me(e,r);for(let t=0;t<r;t++)ge(e,n.codePointAt(t))},ke=(e,t)=>{const n=e.cbuf.length,r=e.cpos,s=J(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(q(2*n,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)},Se=(e,t)=>{me(e,t.byteLength),ke(e,t)},xe=(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*q(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Ee=(e,t)=>xe(e,8).setBigUint64(0,t,!1),Ce=new DataView(new ArrayBuffer(4)),Ae=(e,t)=>{switch(typeof t){case"string":ge(e,119),_e(e,t);break;case"number":ee(t)&&H(t)<=2147483647?(ge(e,125),be(e,t)):(n=t,Ce.setFloat32(0,n),Ce.getFloat32(0)===n?(ge(e,124),((e,t)=>{xe(e,4).setFloat32(0,t,!1)})(e,t)):(ge(e,123),((e,t)=>{xe(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":ge(e,122),((e,t)=>{xe(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)ge(e,126);else if(ie(t)){ge(e,117),me(e,t.length);for(let n=0;n<t.length;n++)Ae(e,t[n])}else if(t instanceof Uint8Array)ge(e,116),Se(e,t);else{ge(e,118);const n=Object.keys(t);me(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];_e(e,s),Ae(e,t[s])}}break;case"boolean":ge(e,t?120:121);break;default:ge(e,127)}var n};class Ie extends he{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&me(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Oe=e=>{e.count>0&&(be(e.encoder,1===e.count?e.s:-e.s),e.count>1&&me(e.encoder,e.count-2))};class De{constructor(){this.encoder=new he,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Oe(this),this.count=1,this.s=e)}toUint8Array(){return Oe(this),pe(this.encoder)}}const je=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);be(e.encoder,t),e.count>1&&me(e.encoder,e.count-2)}};class Te{constructor(){this.encoder=new he,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(je(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return je(this),pe(this.encoder)}}class Ue{constructor(){this.sarr=[],this.s="",this.lensE=new De}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 he;return this.sarr.push(this.s),this.s="",_e(e,this.sarr.join("")),ke(e,this.lensE.toUint8Array()),pe(e)}}const Pe=e=>new Error(e),Le=()=>{throw Pe("Method unimplemented")},Re=()=>{throw Pe("Unexpected case")},$e=Pe("Unexpected end of array"),Me=Pe("Integer out of Range");class Be{constructor(e){this.arr=e,this.pos=0}}const Ne=e=>new Be(e),Fe=e=>e.pos!==e.arr.length,We=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,Ke(e)),ze=e=>e.arr[e.pos++],Ke=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<Q)return t;if(t>Z)throw Me}throw $e},Ve=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const s=(t&G)>0?-1:1;if(0===(t&Q))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<Q)return s*n;if(n>Z)throw Me}throw $e},He=de?e=>de.decode(We(e)):e=>{let t=Ke(e);if(0===t)return"";{let n=String.fromCodePoint(ze(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(ze(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))}},Je=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},qe=e=>Je(e,8).getBigUint64(0,!1),Ye=[e=>{},e=>null,Ve,e=>Je(e,4).getFloat32(0,!1),e=>Je(e,8).getFloat64(0,!1),e=>Je(e,8).getBigInt64(0,!1),e=>!1,e=>!0,He,e=>{const t=Ke(e),n={};for(let r=0;r<t;r++){n[He(e)]=Ge(e)}return n},e=>{const t=Ke(e),n=[];for(let r=0;r<t;r++)n.push(Ge(e));return n},We],Ge=e=>Ye[127-ze(e)](e);class Qe extends Be{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=Ke(this)+1:this.count=-1),this.count--,this.s}}class Xe extends Be{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=Ve(this);const e=Y(this.s);this.count=1,e&&(this.s=-this.s,this.count=Ke(this)+2)}return this.count--,this.s}}class Ze extends Be{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=Ve(this),t=1&e;this.diff=V(e/2),this.count=1,t&&(this.count=Ke(this)+2)}return this.s+=this.diff,this.count--,this.s}}class et{constructor(e){this.decoder=new Xe(e),this.str=He(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*tt(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 c=0;for(;c<o.byteLength;)switch(t){case 0:if(c+4>o.byteLength){for(const e of o.slice(c)){if(4===r)break;n[r++]=e,++c}if(r<4)break}else if(r>0&&r<4)for(const e of o.slice(c,c+4-r))n[r++]=e,++c;case 1:i=4===r?new DataView(n.buffer,0,4).getUint32(0,!1):e.getUint32(c,!1),r?r=0:c+=4;case 2:if(c>=o.byteLength){t=2;break}if(c+i>o.byteLength)s.push(o.slice(c)),i-=o.byteLength-c,t=2,c=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(c,c+i),t),s=[],yield e}else yield o.slice(c,c+i);c+=i,t=0}}}}function nt(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t._bt&&"string"==typeof t.ref&&void 0===t.v}function rt(e,t=new WeakSet){return null!=e&&(!!nt(e)||"object"==typeof e&&(!t.has(e)&&(t.add(e),!(e instanceof Date||e instanceof RegExp||e instanceof Blob)&&(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(Array.isArray(e)?e.some(e=>rt(e,t)):e.constructor===Object&&Object.values(e).some(e=>rt(e,t)))))))}function st(e,t){return s(this,arguments,void 0,function*(e,t,n=[],r="",s=new WeakMap,i){if(null==e)return e;if(nt(e)){const s=function(e,t){if("string"===t._bt)return(new TextDecoder).decode(e);const n=e.buffer.byteLength===e.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);switch(t._bt){case"Blob":return new Blob([new Uint8Array(n)],{type:t.ct||""});case"ArrayBuffer":return n;case"Uint8Array":default:return e;case"Int8Array":return new Int8Array(n);case"Uint8ClampedArray":return new Uint8ClampedArray(n);case"Int16Array":return new Int16Array(n);case"Uint16Array":return new Uint16Array(n);case"Int32Array":return new Int32Array(n);case"Uint32Array":return new Uint32Array(n);case"Float32Array":return new Float32Array(n);case"Float64Array":return new Float64Array(n);case"BigInt64Array":return new BigInt64Array(n);case"BigUint64Array":return new BigUint64Array(n);case"DataView":return new DataView(n)}}(yield i.download(e,t),e);return n.push({keyPath:r,data:s,ref:e.ref}),s}if(Array.isArray(e)){if(s.has(e))return s.get(e);const o=[];s.set(e,o);for(let c=0;c<e.length;c++){const l=r?`${r}.${c}`:`${c}`;o.push(yield st(e[c],t,n,l,s,i))}return o}if("object"==typeof e&&e.constructor===Object){if(s.has(e))return s.get(e);const o={};s.set(e,o);for(const[c,l]of Object.entries(e)){if("_hasBlobRefs"===c)continue;const e=r?`${r}.${c}`:c;o[c]=yield st(l,t,n,e,s,i)}return o}return e})}function it(e){return"object"==typeof e&&null!==e&&1===e._hasBlobRefs}function ot(e){return Object.entries(e.cloud.schema||{}).filter(([,{markedForSync:e}])=>e).map(([t])=>e.tables.find(({name:e})=>e===t)).filter(e=>!!e)}function ct(e,t){e.value!==t&&e.next(t)}function lt(e,i){const o=n.from(t.liveQuery(()=>s(this,void 0,void 0,function*(){let t=0,n=0;const r=ot(e);return yield e.dx.transaction("r",r,e=>s(this,void 0,void 0,function*(){e.idbtrans.disableBlobResolve=!0;for(const e of r){if(!!!e.schema.idxByName._hasBlobRefs)continue;const r=yield e.where("_hasBlobRefs").equals(1).toArray();for(const e of r){const r=at(e);t+=r.length,n+=r.reduce((e,t)=>e+(t.size||0),0)}}})),{blobsRemaining:t,bytesRemaining:n}})));return n.combineLatest([o,i]).pipe(r.map(([e,t])=>({isDownloading:t&&e.blobsRemaining>0,blobsRemaining:e.blobsRemaining,bytesRemaining:e.bytesRemaining})),r.share({resetOnRefCountZero:()=>n.timer(2e3)}))}function at(e){const t=[];return function e(n){if(null!=n&&"object"==typeof n)if(p.isTSONRef(n))t.push({ref:n.ref,size:n.size});else{if(function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&"string"==typeof t.ref&&"number"==typeof t.size&&void 0===t._bt}(n)){const e=n;return void t.push({ref:e.ref,size:e.size})}nt(n)?t.push({ref:n.ref,size:n.size||0}):Array.isArray(n)?n.forEach(e):n.constructor===Object&&Object.values(n).forEach(e)}}(e),t}let ut=!1;function dt(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){ut||(ut=!0)}})}function ht(e,t){e.cloud.usingServiceWorker?dt(e,t):e.localSyncEvent.next({purpose:t})}class ft extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}const pt=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="#666666" stroke-width="2"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M22 6L12 13 2 6"/></svg>')}`;function gt(e){return{name:"provider",value:e.name,displayName:`Continue with ${e.displayName}`,iconUrl:e.iconUrl,styleHint:e.type}}function yt(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 mt(e,t,...n){return yt(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function bt(e,t,n,r){return s(this,void 0,void 0,function*(){let s=n||"",i=!0;for(;!s||!/^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$/.test(s);){const n=[];i&&r&&n.push(r),s&&n.push({type:"error",messageCode:"INVALID_EMAIL",message:"Please enter a valid email address",messageParams:{}}),i=!1,s=(yield yt(e,{type:"email",title:t,alerts:n,fields:{email:{type:"email",placeholder:"you@somedomain.com"}}})).email}return s})}function vt(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 yt(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return s})}class wt extends Error{constructor(e){super(`OAuth redirect initiated for provider: ${e}`),this.name="OAuthRedirectError",this.provider=e}}class _t extends Error{constructor(e){super(e.message),this.code=e.code}get name(){return"PolicyRejectionError"}}function kt(e){return"object"==typeof e&&null!==e&&"string"==typeof e.code&&"string"==typeof e.message}const St=1e3;function xt(e){return s(this,void 0,void 0,function*(){var t,n,r;const s=yield e.getCurrentUser(),{accessToken:i,accessTokenExpiration:o,refreshToken:c,refreshTokenExpiration:l,claims:a}=s;if(!i)return null;if((null!==(t=null==o?void 0:o.getTime())&&void 0!==t?t:1/0)>Date.now()+3e5&&"ok"===((null===(n=s.license)||void 0===n?void 0:n.status)||"ok"))return s;if(!c)throw new Error("Refresh token missing");if((null!==(r=null==l?void 0:l.getTime())&&void 0!==r?r:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield Ct(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 Et(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 Ct(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 c=function(e){const t=E(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:c,hints:i});if("error"===t.type)throw new ft(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 yt(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:t.alerts})),e}catch(e){if(e instanceof wt||"OAuthRedirectError"===(null==e?void 0:e.name))throw e;if(e instanceof _t||"PolicyRejectionError"===(null==e?void 0:e.name))throw e;if(e instanceof ft)throw yield mt(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){if("undefined"!=typeof navigator&&!navigator.onLine)n="You seem to be offline. Please connect to the internet and try again.";else if("undefined"==typeof location||!t.debug&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname)n="Could not connect to server. Please verify the connection.",yield mt(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch(()=>{});else{const e=`npx dexie-cloud whitelist ${location.origin}`;n=`Could not connect to server. Please verify that your origin '${location.origin}' is whitelisted using \`npx dexie-cloud whitelist\``,yield mt(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{},copyText:e}).catch(()=>{})}}throw e}})}(n,r,i,o)})}function Ct(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=E(i),c={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:o,signing_algorithm:r,time_stamp:n},l=yield fetch(`${e}/token`,{body:JSON.stringify(c),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==l.status)throw new Error(`RefreshToken: Status ${l.status} from ${e}/token`);const a=yield l.json();if("error"===a.type)throw new ft(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 At=new WeakMap;class It{constructor(e,t){At.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then(n=>new It(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)}))}save(){return s(this,void 0,void 0,function*(){At.get(this).table("$logins").put(this)})}}const Ot={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(Ot),Object.freeze(Ot.claims)}catch(h){}function Dt(e,t){return n.firstValueFrom(n.from(e).pipe(n.filter(t)))}function jt(e){return s(this,void 0,void 0,function*(){const t=yield Tt(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 yt(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 Tt(e,{deleteUnsyncedData:!0})}})}function Tt(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 Dt(e.cloud.currentUser,e=>e.userId===Ot.userId),yield e.cloud.sync({purpose:"pull",wait:!0})),n})}class Ut extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}const Pt={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 Lt extends Error{constructor(e,t,n){super(n||Pt[e]),this.name="OAuthError",this.code=e,this.provider=t}get userMessage(){return Pt[this.code]||this.message}}const Rt={providers:[],otpEnabled:!0};function $t(e){return s(this,arguments,void 0,function*(e,t=!0){if(!t)return Rt;try{const t=yield fetch(`${e}/auth-providers`,{method:"GET",headers:{Accept:"application/json"},mode:"cors"});return 404===t.status?Rt:t.ok?yield t.json():Rt}catch(e){return Rt}})}function Mt(e){if("undefined"==typeof window)throw new Error("OAuth redirect requires a browser environment");const t=function(e){const t=new URL(`${e.databaseUrl}/oauth/login/${e.provider}`),n=e.redirectUri||("undefined"!=typeof window?window.location.href:"");return n&&t.searchParams.set("redirect_uri",n),t.toString()}(e);window.location.href=t}function Bt(e){const{userInteraction:n}=e.cloud;function r(i,o){return s(this,arguments,void 0,function*({public_key:i,hints:o},c){var l,a;let u;const d=null===(l=e.cloud.options)||void 0===l?void 0:l.databaseUrl;if(!d)throw new Error("No database URL given.");const h=null==o?void 0:o.intent;if((null==o?void 0:o.oauthCode)&&o.provider)try{return yield function(e){return s(this,void 0,void 0,function*(){const{databaseUrl:t,code:n,publicKey:r,scopes:s=["ACCESS_DB"],intent:i}=e,o=Object.assign({grant_type:"authorization_code",code:n,public_key:r,scopes:s},void 0!==i?{intent:i}:{});try{const e=yield fetch(`${t}/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),mode:"cors"});if(!e.ok){const t=yield e.text().catch(()=>e.statusText);if(403===e.status)try{const e=JSON.parse(t);if(kt(e))throw new _t(e)}catch(e){if(e instanceof _t)throw e}if(400===e.status||401===e.status)try{const e=JSON.parse(t);if("error"===e.type){if("INVALID_OTP"===e.messageCode)throw new Lt("expired_code",void 0,e.message);throw new ft(e)}}catch(e){if(e instanceof Lt||e instanceof ft)throw e}throw new Lt("provider_error",void 0,`Token exchange failed: ${e.status} ${t}`)}const n=yield e.json();if("error"===n.type)throw new ft(n);if("tokens"!==n.type)throw new Lt("provider_error",void 0,`Unexpected response type: ${n.type}`);return n}catch(e){if(e instanceof Lt||e instanceof ft)throw e;if(e instanceof TypeError)throw new Lt("network_error");throw e}})}({databaseUrl:d,code:o.oauthCode,publicKey:i,scopes:["ACCESS_DB"],intent:h})}catch(e){if(e instanceof _t)return yield r({public_key:i,hints:void 0},Ft(e));throw e}if(null==o?void 0:o.provider){if(c)return yield r({public_key:i,hints:void 0},c);let t;throw o.redirectPath&&(/^https?:\/\//i.test(o.redirectPath)?t=o.redirectPath:"undefined"!=typeof window&&window.location?t=new URL(o.redirectPath,window.location.href).toString():"undefined"!=typeof location&&location.href&&(t=new URL(o.redirectPath,location.href).toString())),Nt(e,o.provider,t),new wt(o.provider)}if("demo"===(null==o?void 0:o.grant_type)){u={demo_user:yield bt(n,"Enter a demo user email",(null==o?void 0:o.email)||(null==o?void 0:o.userId),c),grant_type:"demo",scopes:["ACCESS_DB"],public_key:i}}else if((null==o?void 0:o.otpId)&&o.otp){if(c)return yield mt(n,"Access Denied",c),yield r({public_key:i,hints:void 0},c);u={grant_type:"otp",otp_id:o.otpId,otp:o.otp,scopes:["ACCESS_DB"],public_key:i}}else if("otp"===(null==o?void 0:o.grant_type)||(null==o?void 0:o.email)){const e=(null==o?void 0:o.email)||(yield bt(n,"Enter email address",void 0,c));u=/@demo.local$/.test(e)?{demo_user:e,grant_type:"demo",scopes:["ACCESS_DB"],public_key:i}:Object.assign({email:e,grant_type:"otp",scopes:["ACCESS_DB"]},void 0!==h?{intent:h}:{})}else{const r=!1!==(null===(a=e.cloud.options)||void 0===a?void 0:a.socialAuth),l=yield $t(d,r);if(l.providers.length>0){const r=c?[c]:[],i=yield function(e,n,r){return s(this,arguments,void 0,function*(e,n,r,s="Choose login method",i=[]){const o=[...n.map(gt)];return r&&o.push({name:"otp",value:"email",displayName:"Continue with email",iconUrl:pt,styleHint:"otp"}),new Promise((n,r)=>{const c={type:"generic",title:s,alerts:i,options:o,fields:{},submitLabel:"",cancelLabel:"Cancel",onSubmit:t=>{e.next(void 0),n("otp"in t?{type:"otp"}:"provider"in t?{type:"provider",provider:t.provider}:{type:"otp"})},onCancel:()=>{e.next(void 0),r(new t.AbortError("User cancelled"))}};e.next(c)})})}(n,l.providers,l.otpEnabled,"Sign in",r);if("provider"===i.type)throw Nt(e,i.provider),new wt(i.provider)}const f=yield bt(n,"Enter email address",null==o?void 0:o.email,0===l.providers.length?c:void 0);u=/@demo.local$/.test(f)?{demo_user:f,grant_type:"demo",scopes:["ACCESS_DB"],public_key:i}:Object.assign({email:f,grant_type:"otp",scopes:["ACCESS_DB"]},void 0!==h?{intent:h}:{})}const f=yield fetch(`${d}/token`,{body:JSON.stringify(u),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==f.status){const e=yield Wt(f);if(e)return yield r({public_key:i,hints:void 0},e);const t=yield f.text();throw yield mt(n,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:t,messageParams:{}}).catch(()=>{}),new Ut(f,t)}const p=yield f.json();if("tokens"===p.type||"error"===p.type)return p;if("otp"===u.grant_type&&"email"in u){if("otp-sent"!==p.type)throw new Error(`Unexpected response from ${d}/token`);const e=yield vt(n,u.email),t=Object.assign(Object.assign({},u),{otp:e||"",otp_id:p.otp_id,public_key:i});let s=yield fetch(`${d}/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 vt(n,u.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),s=yield fetch(`${d}/token`,{body:JSON.stringify(t),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==s.status){const e=yield Wt(s);if(e)return yield r({public_key:i,hints:void 0},e);const t=yield s.text();throw new Ut(s,t)}return yield s.json()}throw new Error(`Unexpected response from ${d}/token`)})}return({public_key:e,hints:t})=>r({public_key:e,hints:t})}function Nt(e,t,n){var r,s;const i=null===(r=e.cloud.options)||void 0===r?void 0:r.databaseUrl;if(!i)throw new Error("No database URL given.");Mt({databaseUrl:i,provider:t,redirectUri:n||(null===(s=e.cloud.options)||void 0===s?void 0:s.oauthRedirectUri)||("undefined"!=typeof location?location.href:void 0)})}function Ft(e){return{type:"error",messageCode:e.code,message:e.message,messageParams:{}}}function Wt(e){return s(this,void 0,void 0,function*(){if(403!==e.status)return null;try{const t=yield e.clone().json();if(kt(t))return Ft(new _t(t))}catch(e){}return null})}function zt(e,...t){globalThis.console[e](...t)}function Kt(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 xt(e),!1}const o=new It(e,{claims:{},lastLogin:new Date(0)});try{yield Et(e.cloud.options.databaseUrl,o,e.cloud.options.fetchTokens||Bt(e),e.cloud.userInteraction,t)}catch(e){if("OAuthRedirectError"===e.name)return!1;throw e}return i!==Ot.userId&&o.userId!==i&&(yield jt(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&&(zt("debug","Login context property names:",Object.keys(t)),zt("debug","Login context property names:",Object.keys(t)),zt("debug","Login context:",t),zt("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})),yield Dt(e.cloud.currentUser,e=>e.userId===t.userId)})}(e,o),ht(e,"pull"),o.userId!==i})}const Vt={},Ht="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;Ht&&Ht.ready.then(e=>Vt.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 Jt{constructor(e){this.name=e}subscribe(e){if(!Ht)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 Ht.addEventListener("message",t),()=>Ht.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})):Vt.registration&&(null===(t=Vt.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const qt=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class Yt extends n.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new Jt(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){qt.has(e)?qt.get(e).push(t):qt.set(e,[t])}(`lbc-${e}`,r);try{t instanceof Jt?i=t.subscribe(e=>n.next(e)):t.addEventListener("message",s)}catch(e){}return()=>{!function(e,t){const n=qt.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof Jt?i():t.removeEventListener("message",s)}}),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=qt.get(e.type);t&&t.forEach(t=>{try{t(e)}catch(e){}})}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function Gt(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 E(s)})}function Qt(e){return`$${e}_mutations`}function Xt(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 Zt=[].concat;function en(e){return Zt.apply([],e)}function tn(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=Xt(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=en(i).sort((e,t)=>e.mut.txid===t.mut.txid?e.mut.opNo-t.mut.opNo:e.mut.ts-t.mut.ts),c=[];let l=null,a=null;for(const{table:e,mut:t}of o)l&&l.table===e&&a===t.txid?l.muts.push(t):(l={table:e,muts:[t]},a=t.txid,c.push(l));return c})}function nn(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 rn="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class sn{toString(){return this.v}constructor(e){this.v=e}}const on=rn?{}:{bigint:{test:e=>e instanceof sn,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new sn(e)}},cn=Object.assign(Object.assign(Object.assign(Object.assign({},P),on),U),{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)}}}),ln=function(...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 u;let i=n.get(r);if(void 0!==i)return i;const o=(s=e,a.call(s).slice(8,-1)),c=Object.entries(t).find(([t,n])=>n?.test?.(e,o)??t===o);return i=c?.[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:u),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=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})}}}(_,D,T,y,m,b,v,cn);function an(e,n,r){const s=[];for(let i of r){const{table:r,muts:o}=i,c=e.tables.find(e=>e.name===r);if(!c)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:l}=c;let a=i;o.forEach((e,r)=>{const s=!l.outbound&&("upsert"===e.type||"insert"===e.type);e.keys.forEach((e,o)=>{if(Array.isArray(e)){a===i&&(a=un(i,s));const t=a.muts[r],n=JSON.stringify(e);t.keys[o]=n}else if("#"===e[0]){a===i&&(a=un(i,s));const c=a.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const u=`${e}:${n.userId}`;c.keys[o]=u,s&&t.setByKeyPath(c.values[o],l.keyPath,u)}})}),s.push(a)}return s}function un(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 dn=new WeakMap;function hn(e){return s(this,void 0,void 0,function*(){var t,n;const r=(null!==(n=null===(t=dn.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 fn(e,t,n,r,i,o,c,l,a){return s(this,void 0,void 0,function*(){const s={Accept:"application/json","Content-Type":"application/tson"},u=yield xt(i),d=null==u?void 0:u.accessToken;d&&(s.Authorization=`Bearer ${d}`);const h={v:3,dbID:null==n?void 0:n.remoteDbId,clientIdentity:l,schema:c||{},lastPull:n?{serverRevision:n.serverRevision,yServerRevision:n.yServerRevision,realms:n.realms,inviteRealms:n.inviteRealms}:void 0,baseRevs:r,changes:an(i.dx.core.schema,a,e),y:t,dxcv:i.cloud.version};i.syncStateChangedEvent.next({phase:"pushing"});const f=ln.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));dn.set(e,new Date(Date.now()+1e3*t))}else dn.delete(e)}}(i,p),!p.ok)throw new Ut(p);switch(p.headers.get("content-type")){case"application/x-bison":case"application/x-bison-stream":throw new Error("BISON format no longer supported. Server should send application/json.");default:{const e=yield p.text();return ln.parse(e)}}})}function pn(e){if(null==e?void 0:e.cancelled)throw new t.AbortError("Operation was cancelled")}let gn=!1;function yn(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 mn(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 bn(e,n,r){return s(this,void 0,void 0,function*(){const s=yield e.bulkGet(n),i=[],o=[];n.forEach((n,c)=>{const l=s[c];if(l){for(const[s,i]of Object.entries(r[c]))if(s===e.schema.primKey.keyPath){if(0!==t.cmp(i,n))throw new Error("Cannot change primary key")}else t.setByKeyPath(l,s,i);i.push(n),o.push(l)}}),yield null==e.schema.primKey.keyPath?e.bulkPut(o,i):e.bulkPut(o)})}function vn(e){null!==e&&"object"==typeof e&&e.constructor===Object&&rt(e)&&(e._hasBlobRefs=1)}function wn(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":n.values.forEach(vn),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":n.values.forEach(vn),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":if(!i.outbound&&i.keyPath)for(const e of n.changeSpecs)t.delByKeyPath(e,i.keyPath);yield bn(e,r,n.changeSpecs);break;case"delete":yield e.bulkDelete(r)}}}})}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(gn=navigator.onLine,self.addEventListener("online",()=>gn=!0),self.addEventListener("offline",()=>gn=!1));const _n="dexie-cloud-syncer";function kn(e,t){return e.where("i").between(t,1/0,!0).toArray()}const Sn=()=>new Map,xn=e=>{const t=Sn();return e.forEach((e,n)=>{t.set(n,e)}),t},En=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r};class Cn{constructor(){this._observers=Sn()}on(e,t){return En(this._observers,e,te).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 se((this._observers.get(e)||Sn()).values()).forEach(e=>e(...t))}destroy(){this._observers=Sn()}}class An{constructor(){this._observers=Sn()}on(e,t){En(this._observers,e,te).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 se((this._observers.get(e)||Sn()).values()).forEach(e=>e(...t))}destroy(){this._observers=Sn()}}const In=crypto.getRandomValues.bind(crypto),On=()=>In(new Uint32Array(1))[0],Dn=[1e7]+-1e3+-4e3+-8e3+-1e11,jn=()=>Dn.replace(/[018]/g,e=>(e^On()&15>>e/4).toString(16)),Tn=Date.now,Un=e=>new Promise(e);Promise.all.bind(Promise);const Pn=e=>void 0===e?null:e;let Ln=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},Rn=!0;try{"undefined"!=typeof localStorage&&localStorage&&(Ln=localStorage,Rn=!1)}catch(yl){}const $n=Ln,Mn=Object.assign,Bn=Object.keys,Nn=e=>Bn(e).length,Fn=e=>Bn(e).length,Wn=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),zn=Object.freeze,Kn=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||Kn(e[t])}return zn(e)},Vn=Symbol("Equality"),Hn=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Hn(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[Vn])return e[Vn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(const n of e.keys())if(!t.has(n)||!Jn(e.get(n),t.get(n)))return!1;break;case Object:if(Nn(e)!==Nn(t))return!1;for(const n in e)if(!Wn(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},qn="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let Yn;const Gn=e=>(()=>{if(void 0===Yn)if(qn){Yn=Sn();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&Yn.set(t,""),t=r):null!==t&&(Yn.set(t,r),t=null)}null!==t&&Yn.set(t,"")}else"object"==typeof location?(Yn=Sn(),(location.search||"?").slice(1).split("&").forEach(e=>{if(0!==e.length){const[t,n]=e.split("=");Yn.set(`--${le(t,"-")}`,n),Yn.set(`-${le(t,"-")}`,n)}})):Yn=Sn();return Yn})().has(e),Qn=e=>Pn(qn?process.env[e.toUpperCase().replaceAll("-","_")]:$n.getItem(e)),Xn=e=>Gn("--"+e)||null!==Qn(e);Xn("production");var Zn;qn&&(Zn=process.env.FORCE_COLOR,["true","1","2"].includes(Zn))||!Gn("--no-colors")&&!Xn("no-color")&&(!qn||process.stdout.isTTY)&&(!qn||Gn("--color")||null!==Qn("COLORTERM")||(Qn("TERM")||"").includes("color"));class er{constructor(e,t){this.left=e,this.right=t}}const tr=(e,t)=>new er(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const nr=Symbol,rr=nr(),sr=nr(),ir=nr(),or=nr(),cr=nr(),lr=nr(),ar=nr(),ur=nr(),dr=nr(),hr=(tr("font-weight","bold"),tr("font-weight","normal"),tr("color","blue"),tr("color","green"),tr("color","grey"),tr("color","red"),tr("color","purple"),tr("color","orange"),tr("color","black"),te()),fr=e=>({[Symbol.iterator](){return this},next:e}),pr=(e,t)=>fr(()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});class gr{constructor(e,t){this.clock=e,this.len=t}}class yr{constructor(){this.clients=new Map}}const mr=(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])Zr(e,s,o.clock,o.len,n)}}),br=(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=V((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)},vr=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=q(r.len,s.clock+s.len-r.clock):(n<t&&(e[n]=s),n++)}e.length=n})},wr=(e,t,n,r)=>{En(e.clients,t,()=>[]).push(new gr(n,r))},_r=(e,t)=>{me(e.restEncoder,t.clients.size),se(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),me(e.restEncoder,t);const r=n.length;me(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},kr=(e,t,n)=>{const r=new yr,s=Ke(e.restDecoder);for(let i=0;i<s;i++){e.resetDsCurVal();const s=Ke(e.restDecoder),i=Ke(e.restDecoder),o=n.clients.get(s)||[],c=Hr(n,s);for(let n=0;n<i;n++){const n=e.readDsClock(),i=n+e.readDsLen();if(n<c){c<i&&wr(r,s,c,i-c);let e=qr(o,n),l=o[e];for(!l.deleted&&l.id.clock<n&&(o.splice(e+1,0,Pi(t,l,n-l.id.clock)),e++);e<o.length&&(l=o[e++],l.id.clock<i);)l.deleted||(i<l.id.clock+l.length&&o.splice(e,0,Pi(t,l,i-l.id.clock)),l.delete(t))}else wr(r,s,n,i-n)}}if(r.clients.size>0){const e=new Dr;return me(e.restEncoder,0),_r(e,r),e.toUint8Array()}return null},Sr=On;class xr extends Cn{constructor({guid:e=jn(),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=Sr(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Kr,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=Un(e=>{this.on("load",()=>{this.isLoaded=!0,e(this)})});const c=()=>Un(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=c()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;null===e||this.shouldLoad||is(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(se(this.subdocs).map(e=>e.guid))}transact(e,t=null){return is(this,e,t)}get(e,t=xs){const n=En(this.share,e,()=>{const e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==xs&&r!==t){if(r===xs){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,Ws)}getText(e=""){return this.get(e,oi)}getMap(e=""){return this.get(e,Ks)}getXmlElement(e=""){return this.get(e,ai)}getXmlFragment(e=""){return this.get(e,li)}toJSON(){const e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,se(this.subdocs).forEach(e=>e.destroy());const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new xr({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,is(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 Er{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Ke(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Ke(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Cr extends Er{constructor(e){super(e),this.keys=[],Ke(e),this.keyClockDecoder=new Ze(We(e)),this.clientDecoder=new Xe(We(e)),this.leftClockDecoder=new Ze(We(e)),this.rightClockDecoder=new Ze(We(e)),this.infoDecoder=new Qe(We(e),ze),this.stringDecoder=new et(We(e)),this.parentInfoDecoder=new Qe(We(e),ze),this.typeRefDecoder=new Xe(We(e)),this.lenDecoder=new Xe(We(e))}readLeftID(){return new Br(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Br(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 Ge(this.restDecoder)}readBuf(){return We(this.restDecoder)}readJSON(){return Ge(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 Ar{constructor(){this.restEncoder=fe()}toUint8Array(){return pe(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){me(this.restEncoder,e)}writeDsLen(e){me(this.restEncoder,e)}}class Ir extends Ar{writeLeftID(e){me(this.restEncoder,e.client),me(this.restEncoder,e.clock)}writeRightID(e){me(this.restEncoder,e.client),me(this.restEncoder,e.clock)}writeClient(e){me(this.restEncoder,e)}writeInfo(e){ye(this.restEncoder,e)}writeString(e){_e(this.restEncoder,e)}writeParentInfo(e){me(this.restEncoder,e?1:0)}writeTypeRef(e){me(this.restEncoder,e)}writeLen(e){me(this.restEncoder,e)}writeAny(e){Ae(this.restEncoder,e)}writeBuf(e){Se(this.restEncoder,e)}writeJSON(e){_e(this.restEncoder,JSON.stringify(e))}writeKey(e){_e(this.restEncoder,e)}}class Or{constructor(){this.restEncoder=fe(),this.dsCurrVal=0}toUint8Array(){return pe(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,me(this.restEncoder,t)}writeDsLen(e){0===e&&Re(),me(this.restEncoder,e-1),this.dsCurrVal+=e}}class Dr extends Or{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Te,this.clientEncoder=new De,this.leftClockEncoder=new Te,this.rightClockEncoder=new Te,this.infoEncoder=new Ie(ye),this.stringEncoder=new Ue,this.parentInfoEncoder=new Ie(ye),this.typeRefEncoder=new De,this.lenEncoder=new De}toUint8Array(){const e=fe();return me(e,0),Se(e,this.keyClockEncoder.toUint8Array()),Se(e,this.clientEncoder.toUint8Array()),Se(e,this.leftClockEncoder.toUint8Array()),Se(e,this.rightClockEncoder.toUint8Array()),Se(e,pe(this.infoEncoder)),Se(e,this.stringEncoder.toUint8Array()),Se(e,pe(this.parentInfoEncoder)),Se(e,this.typeRefEncoder.toUint8Array()),Se(e,this.lenEncoder.toUint8Array()),ke(e,pe(this.restEncoder)),pe(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){Ae(this.restEncoder,e)}writeBuf(e){Se(this.restEncoder,e)}writeJSON(e){Ae(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 jr=(e,t,n)=>{const r=new Map;n.forEach((e,n)=>{Hr(t,n)>e&&r.set(n,e)}),Vr(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),me(e.restEncoder,r.size),se(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{((e,t,n,r)=>{r=q(r,t[0].id.clock);const s=qr(t,r);me(e.restEncoder,t.length-s),e.writeClient(n),me(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)})},Tr=(e,t,n,r=new Cr(e))=>is(t,e=>{e.local=!1;let t=!1;const n=e.doc,s=n.store,i=((e,t)=>{const n=Sn(),r=Ke(e.restDecoder);for(let s=0;s<r;s++){const r=Ke(e.restDecoder),s=new Array(r),i=e.readClient();let o=Ke(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 pi(Fr(i,o),t),o+=t;break}case 10:{const t=Ke(e.restDecoder);s[n]=new Mi(Fr(i,o),t),o+=t;break}default:{const c=!(192&r),l=new Li(Fr(i,o),null,(r&Q)===Q?e.readLeftID():null,null,(r&G)===G?e.readRightID():null,c?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,!c||32&~r?null:e.readString(),Ri(e,r));s[n]=l,o+=l.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let s=se(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 c=new Kr,l=new Map,a=(e,t)=>{const n=l.get(e);(null==n||n>t)&&l.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--,c.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):c.clients.set(t,[e]),s=s.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==Mi){const s=En(d,u.id.client,()=>Hr(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,Hr(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(c.clients.size>0){const e=new Dr;return jr(e,c,new Map),me(e.restEncoder,0),{missing:l,update:e.toUint8Array()}}return null})(e,s,i),c=s.pendingStructs;if(c){for(const[e,n]of c.missing)if(n<Hr(s,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=c.missing.get(e);(null==n||n>t)&&c.missing.set(e,t)}c.update=us([c.update,o.update])}}else s.pendingStructs=o;const l=kr(r,e,s);if(s.pendingDs){const t=new Cr(Ne(s.pendingDs));Ke(t.restDecoder);const n=kr(t,e,s);s.pendingDs=l&&n?us([l,n]):l||n}else s.pendingDs=l;if(t){const t=s.pendingStructs.update;s.pendingStructs=null,Ur(e.doc,t)}},n,!1),Ur=(e,t,n,r=Cr)=>{const s=Ne(t);Tr(s,e,n,new r(s))};class Pr{constructor(){this.l=[]}}const Lr=()=>new Pr,Rr=(e,t)=>e.l.push(t),$r=(e,t)=>{const n=e.l;n.length;e.l=n.filter(e=>t!==e),e.l.length},Mr=(e,t,n)=>Hn(e.l,[t,n]);class Br{constructor(e,t){this.client=e,this.clock=t}}const Nr=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,Fr=(e,t)=>new Br(e,t),Wr=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!br(t.ds,e.id),zr=(e,t)=>{const n=En(e.meta,zr,te),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<Hr(r,n)&&Qr(e,Fr(n,t))}),mr(e,t.ds,e=>{}),n.add(t))};class Kr{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Vr=e=>{const t=new Map;return e.clients.forEach((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},Hr=(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 Re()}n.push(t)},qr=(e,t)=>{let n=0,r=e.length-1,s=e[r],i=s.id.clock;if(i===t)return r;let o=V(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=V((n+r)/2)}throw Re()},Yr=(e,t)=>{const n=e.clients.get(t.client);return n[qr(n,t.clock)]},Gr=(e,t,n)=>{const r=qr(t,n),s=t[r];return s.id.clock<n&&s instanceof Li?(t.splice(r+1,0,Pi(e,s,n-s.id.clock)),r+1):r},Qr=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[Gr(e,n,t.clock)]},Xr=(e,t,n)=>{const r=t.clients.get(n.client),s=qr(r,n.clock),i=r[s];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pi&&r.splice(s+1,0,Pi(e,i,n.clock-i.id.clock+1)),i},Zr=(e,t,n,r,s)=>{if(0===r)return;const i=n+r;let o,c=Gr(e,t,n);do{o=t[c++],i<o.id.clock+o.length&&Gr(e,t,i),s(o)}while(c<t.length&&t[c].id.clock<i)};class es{constructor(e,t,n){this.doc=e,this.deleteSet=new yr,this.beforeState=Vr(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const ts=(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))&&(vr(t.deleteSet),((e,t)=>{jr(e,t.doc.store,t.beforeState)})(e,t),_r(e,t.deleteSet),!0),ns=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&En(e.changed,t,te).add(n)},rs=(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 Li&&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},ss=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,s=r.store,i=n.deleteSet,o=n._mergeStructs;try{vr(i),n.afterState=Vr(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach((t,r)=>e.push(()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((e,t)=>{t._dEH.l.length>0&&(null===t._item||!t._item.deleted)&&((e=e.filter(e=>null===e.target._item||!e.target._item.deleted)).forEach(e=>{e.currentTarget=t,e._path=null}),e.sort((e,t)=>e.path.length-t.path.length),Mr(t._dEH,e,n))})}),e.push(()=>r.emit("afterTransaction",[n,r])),Hn(e,[]),n._needFormattingCleanup&&ri(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=qr(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 Li&&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=J(r.length-1,1+qr(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+rs(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=q(qr(e,r),1);for(let t=e.length-1;t>=n;)t-=1+rs(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=qr(r,n);i+1<r.length&&rs(r,i+1)>1||i>0&&rs(r,i)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{hr.forEach(t=>t.print(e))})(ur,rr,"[yjs] ",sr,lr,"Changed the client-id because another client seems to be using it."),r.clientID=Sr()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new Ir;ts(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new Dr;ts(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:a}=n;(c.size>0||a.size>0||l.size>0)&&(c.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:l,added:c,removed:a},r,n]),a.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):ss(e,t+1)}}},is=(e,t,n=null,r=!0)=>{const s=e._transactionCleanups;let i=!1,o=null;null===e._transaction&&(i=!0,e._transaction=new es(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&&ss(s,0)}}return o};class os{constructor(e,t){this.gen=function*(e){const t=Ke(e.restDecoder);for(let n=0;n<t;n++){const t=Ke(e.restDecoder),n=e.readClient();let r=Ke(e.restDecoder);for(let s=0;s<t;s++){const t=e.readInfo();if(10===t){const t=Ke(e.restDecoder);yield new Mi(Fr(n,r),t),r+=t}else if(31&t){const s=!(192&t),i=new Li(Fr(n,r),null,(t&Q)===Q?e.readLeftID():null,null,(t&G)===G?e.readRightID():null,s?e.readParentInfo()?e.readString():e.readLeftID():null,!s||32&~t?null:e.readString(),Ri(e,t));yield i,r+=i.length}else{const t=e.readLen();yield new pi(Fr(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===Mi);return this.curr}}class cs{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const ls=(e,t=Or,n=Cr)=>{const r=new t,s=new os(new n(Ne(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++,me(r.restEncoder,t),me(r.restEncoder,o)),t=i.id.client,o=0,n=0!==i.id.clock),i.constructor===Mi&&(n=!0),n||(o=i.id.clock+i.length);0!==o&&(e++,me(r.restEncoder,t),me(r.restEncoder,o));const c=fe();return me(c,e),((e,t)=>{ke(e,pe(t))})(c,r.restEncoder),r.restEncoder=c,r.toUint8Array()}return me(r.restEncoder,0),r.toUint8Array()},as=(e,t)=>{if(e.constructor===pi){const{client:n,clock:r}=e.id;return new pi(Fr(n,r+t),e.length-t)}if(e.constructor===Mi){const{client:n,clock:r}=e.id;return new Mi(Fr(n,r+t),e.length-t)}{const n=e,{client:r,clock:s}=n.id;return new Li(Fr(r,s+t),null,Fr(r,s+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},us=(e,t=Cr,n=Dr)=>{if(1===e.length)return e[0];const r=e.map(e=>new t(Ne(e)));let s=r.map(e=>new os(e,!0)),i=null;const o=new n,c=new cs(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===Mi?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)hs(c,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===Mi)i.struct.length=n.id.clock+n.length-i.struct.id.clock;else{hs(c,i.struct,i.offset);const e=n.id.clock-i.struct.id.clock-i.struct.length;i={struct:new Mi(Fr(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===Mi?i.struct.length-=t:n=as(n,t)),i.struct.mergeWith(n)||(hs(c,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!==Mi;n=e.next())hs(c,i.struct,i.offset),i={struct:n,offset:0}}null!==i&&(hs(c,i.struct,i.offset),i=null),fs(c);const l=r.map(e=>(e=>{const t=new yr,n=Ke(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=Ke(e.restDecoder),r=Ke(e.restDecoder);if(r>0){const s=En(t.clients,n,()=>[]);for(let t=0;t<r;t++)s.push(new gr(e.readDsClock(),e.readDsLen()))}}return t})(e)),a=(e=>{const t=new yr;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++)re(i,e[t].clients.get(s)||[]);t.clients.set(s,i)}});return vr(t),t})(l);return _r(o,a),o.toUint8Array()},ds=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:pe(e.encoder.restEncoder)}),e.encoder.restEncoder=fe(),e.written=0)},hs=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ds(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),me(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},fs=e=>{ds(e);const t=e.encoder.restEncoder;me(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];me(t,r.written),ke(t,r.restEncoder)}},ps="You must not compute changes after the event-handler fired.";class gs{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=ys(this.currentTarget,this.target))}deletes(e){return br(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw Pe(ps);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=ne(e.content.getContent())}else null!==e&&this.deletes(e)?(s="update",i=ne(e.content.getContent())):(s="add",i=void 0)}else{if(!this.deletes(r))return;s="delete",i=ne(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 Pe(ps);const t=this.target,n=te(),r=te(),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 ys=(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},ms=()=>{((...e)=>{e.unshift(ur),hr.forEach(t=>t.print(e))})("Invalid access: Add Yjs type to a document before reading data.")};let bs=0;class vs{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=bs++}}const ws=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=bs++},_s=(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)=>H(t-e.index)<H(t-n.index)?e:n);let r=e._start,s=0;for(null!==n&&(r=n.p,s=n.index,(e=>{e.timestamp=bs++})(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&&H(n.index-s)<r.parent.length/80?(ws(n,r,s),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return ws(r,t,n),r}{const r=new vs(t,n);return e.push(r),r}})(e._searchMarker,r,s)},ks=(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=q(t,s.index+n))}},Ss=(e,t,n)=>{const r=e,s=t.changedParentTypes;for(;En(s,e,()=>[]).push(n),null!==e._item;)e=e._item.parent;Mr(r._eH,n,t)};class xs{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Lr(),this._dEH=Lr(),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){Rr(this._eH,e)}observeDeep(e){Rr(this._dEH,e)}unobserve(e){$r(this._eH,e)}unobserveDeep(e){$r(this._dEH,e)}toJSON(){}}const Es=(e,t,n)=>{e.doc??ms(),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},Cs=e=>{e.doc??ms();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},As=(e,t)=>{let n=0,r=e._start;for(e.doc??ms();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}},Is=(e,t)=>{const n=[];return As(e,(r,s)=>{n.push(t(r,s,e))}),n},Os=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}}}},Ds=(e,t)=>{e.doc??ms();const n=_s(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}},js=(e,t,n,r)=>{let s=n;const i=e.doc,o=i.clientID,c=i.store,l=null===n?t._start:n.right;let a=[];const u=()=>{a.length>0&&(s=new Li(Fr(o,Hr(c,o)),s,s&&s.lastId,l,l&&l.id,t,null,new Si(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 Li(Fr(o,Hr(c,o)),s,s&&s.lastId,l,l&&l.id,t,null,new gi(new Uint8Array(n))),s.integrate(e,0);break;case xr:s=new Li(Fr(o,Hr(c,o)),s,s&&s.lastId,l,l&&l.id,t,null,new bi(n)),s.integrate(e,0);break;default:if(!(n instanceof xs))throw new Error("Unexpected content type in insert operation");s=new Li(Fr(o,Hr(c,o)),s,s&&s.lastId,l,l&&l.id,t,null,new Ui(n)),s.integrate(e,0)}}}),u()},Ts=()=>Pe("Length exceeded!"),Us=(e,t,n,r)=>{if(n>t._length)throw Ts();if(0===n)return t._searchMarker&&ks(t._searchMarker,n,r.length),js(e,t,null,r);const s=n,i=_s(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&&Qr(e,Fr(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&ks(t._searchMarker,s,r.length),js(e,t,o,r)},Ps=(e,t,n,r)=>{if(0===r)return;const s=n,i=r,o=_s(t,n);let c=t._start;for(null!==o&&(c=o.p,n-=o.index);null!==c&&n>0;c=c.right)!c.deleted&&c.countable&&(n<c.length&&Qr(e,Fr(c.id.client,c.id.clock+n)),n-=c.length);for(;r>0&&null!==c;)c.deleted||(r<c.length&&Qr(e,Fr(c.id.client,c.id.clock+r)),c.delete(e),r-=c.length),c=c.right;if(r>0)throw Ts();t._searchMarker&&ks(t._searchMarker,s,-i+r)},Ls=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},Rs=(e,t,n,r)=>{const s=t._map.get(n)||null,i=e.doc,o=i.clientID;let c;if(null==r)c=new Si([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:c=new Si([r]);break;case Uint8Array:c=new gi(r);break;case xr:c=new bi(r);break;default:if(!(r instanceof xs))throw new Error("Unexpected content type");c=new Ui(r)}new Li(Fr(o,Hr(i.store,o)),s,s&&s.lastId,null,null,t,n,c).integrate(e,0)},$s=(e,t)=>{e.doc??ms();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},Ms=e=>{const t={};return e.doc??ms(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},Bs=(e,t)=>{e.doc??ms();const n=e._map.get(t);return void 0!==n&&!n.deleted},Ns=e=>{return e.doc??ms(),t=e._map.entries(),n=e=>!e[1].deleted,fr(()=>{let e;do{e=t.next()}while(!e.done&&!n(e.value));return e});var t,n};class Fs extends gs{}class Ws extends xs{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new Ws;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ws}clone(){const e=new Ws;return e.insert(0,this.toArray().map(e=>e instanceof xs?e.clone():e)),e}get length(){return this.doc??ms(),this._length}_callObserver(e,t){super._callObserver(e,t),Ss(this,e,new Fs(this,e))}insert(e,t){null!==this.doc?is(this.doc,n=>{Us(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?is(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;js(e,t,r,n)})(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?is(this.doc,n=>{Ps(n,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return Ds(this,e)}toArray(){return Cs(this)}slice(e=0,t=this.length){return Es(this,e,t)}toJSON(){return this.map(e=>e instanceof xs?e.toJSON():e)}map(e){return Is(this,e)}forEach(e){As(this,e)}[Symbol.iterator](){return Os(this)}_write(e){e.writeTypeRef(Ci)}}class zs extends gs{constructor(e,t,n){super(e,t),this.keysChanged=n}}class Ks extends xs{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 Ks}clone(){const e=new Ks;return this.forEach((t,n)=>{e.set(n,t instanceof xs?t.clone():t)}),e}_callObserver(e,t){Ss(this,e,new zs(this,e,t))}toJSON(){this.doc??ms();const e={};return this._map.forEach((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof xs?r.toJSON():r}}),e}get size(){return[...Ns(this)].length}keys(){return pr(Ns(this),e=>e[0])}values(){return pr(Ns(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return pr(Ns(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??ms(),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?is(this.doc,t=>{Ls(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?is(this.doc,n=>{Rs(n,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return $s(this,e)}has(e){return Bs(this,e)}clear(){null!==this.doc?is(this.doc,e=>{this.forEach(function(t,n,r){Ls(e,r,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Ai)}}const Vs=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&((e,t)=>e===t||Fn(e)===Fn(t)&&((e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0})(e,(e,n)=>(void 0!==e||Wn(t,n))&&t[n]===e))(e,t);class Hs{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&Re(),this.right.content.constructor===wi)this.right.deleted||Gs(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===wi)t.right.deleted||Gs(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&Qr(e,Fr(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},qs=(e,t,n,r)=>{const s=new Map,i=r?_s(t,n):null;if(i){const t=new Hs(i.p.left,i.p,i.index,s);return Js(e,t,n-i.index)}{const r=new Hs(null,t._start,0,s);return Js(e,r,n)}},Ys=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===wi&&Vs(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const s=e.doc,i=s.clientID;r.forEach((r,o)=>{const c=n.left,l=n.right,a=new Li(Fr(i,Hr(s.store,i)),c,c&&c.lastId,l,l&&l.id,t,null,new wi(o,r));a.integrate(e,0),n.right=a,n.forward()})},Gs=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},Qs=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===wi&&Vs(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Xs=(e,t,n,r)=>{const s=e.doc,i=s.clientID,o=new Map;for(const c in r){const l=r[c],a=n.currentAttributes.get(c)??null;if(!Vs(a,l)){o.set(c,a);const{left:r,right:u}=n;n.right=new Li(Fr(i,Hr(s.store,i)),r,r&&r.lastId,u,u&&u.id,t,null,new wi(c,l)),n.right.integrate(e,0),n.forward()}}return o},Zs=(e,t,n,r,s)=>{n.currentAttributes.forEach((e,t)=>{void 0===s[t]&&(s[t]=null)});const i=e.doc,o=i.clientID;Qs(n,s);const c=Xs(e,t,n,s),l=r.constructor===String?new xi(r):r instanceof xs?new Ui(r):new vi(r);let{left:a,right:u,index:d}=n;t._searchMarker&&ks(t._searchMarker,n.index,l.getLength()),u=new Li(Fr(o,Hr(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,l),u.integrate(e,0),n.right=u,n.index=d,n.forward(),Ys(e,t,n,c)},ei=(e,t,n,r,s)=>{const i=e.doc,o=i.clientID;Qs(n,s);const c=Xs(e,t,n,s);e:for(;null!==n.right&&(r>0||c.size>0&&(n.right.deleted||n.right.content.constructor===wi));){if(!n.right.deleted)switch(n.right.content.constructor){case wi:{const{key:t,value:i}=n.right.content,o=s[t];if(void 0!==o){if(Vs(o,i))c.delete(t);else{if(0===r)break e;c.set(t,i)}n.right.delete(e)}else n.currentAttributes.set(t,i);break}default:r<n.right.length&&Qr(e,Fr(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 Li(Fr(o,Hr(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new xi(s)),n.right.integrate(e,0),n.forward()}Ys(e,t,n,c)},ti=(e,t,n,r,s)=>{let i=t;const o=Sn();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===wi){const e=i.content;o.set(e.key,e)}i=i.right}let c=0,l=!1;for(;t!==i;){if(n===t&&(l=!0),!t.deleted){const n=t.content;switch(n.constructor){case wi:{const{key:i,value:a}=n,u=r.get(i)??null;o.get(i)===n&&u!==a||(t.delete(e),c++,l||(s.get(i)??null)!==a||u===a||(null===u?s.delete(i):s.set(i,u))),l||t.deleted||Gs(s,n);break}}}t=t.right}return c},ni=e=>{let t=0;return is(e.doc,n=>{let r=e._start,s=e._start,i=Sn();const o=xn(i);for(;s;){if(!1===s.deleted)if(s.content.constructor===wi)Gs(o,s.content);else t+=ti(n,r,s,i,o),i=xn(o),r=s;s=s.right}}),t},ri=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&&Zr(e,n.store.clients.get(r),i,s,e=>{e.deleted||e.content.constructor!==wi||e.constructor===pi||t.add(e.parent)})}is(n,n=>{mr(e,e.deleteSet,e=>{if(e instanceof pi||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===wi?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===wi){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)});for(const e of t)ni(e)})},si=(e,t,n)=>{const r=n,s=xn(t.currentAttributes),i=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case Ui:case vi:case xi:n<t.right.length&&Qr(e,Fr(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}i&&ti(e,i,t.right,s,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&ks(o._searchMarker,t.index,-r+n),t};class ii extends gs{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=[];is(e,e=>{const n=new Map,r=new Map;let s=this.target._start,i=null;const o={};let c="",l=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 c||c.length>0)&&(e={insert:c},n.size>0&&(e.attributes={},n.forEach((t,n)=>{null!==t&&(e.attributes[n]=t)}))),c="";break;case"retain":l>0&&(e={retain:l},(e=>{for(const t in e)return!1;return!0})(o)||(e.attributes=Mn({},o))),l=0}e&&t.push(e),i=null}};for(;null!==s;){switch(s.content.constructor){case Ui:case vi:this.adds(s)?this.deletes(s)||(u(),i="insert",c=s.content.getContent()[0],u()):this.deletes(s)?("delete"!==i&&(u(),i="delete"),a+=1):s.deleted||("retain"!==i&&(u(),i="retain"),l+=1);break;case xi:this.adds(s)?this.deletes(s)||("insert"!==i&&(u(),i="insert"),c+=s.content.str):this.deletes(s)?("delete"!==i&&(u(),i="delete"),a+=s.length):s.deleted||("retain"!==i&&(u(),i="retain"),l+=s.length);break;case wi:{const{key:t,value:c}=s.content;if(this.adds(s)){if(!this.deletes(s)){const l=n.get(t)??null;Vs(l,c)?null!==c&&s.delete(e):("retain"===i&&u(),Vs(c,r.get(t)??null)?delete o[t]:o[t]=c)}}else if(this.deletes(s)){r.set(t,c);const e=n.get(t)??null;Vs(e,c)||("retain"===i&&u(),o[t]=e)}else if(!s.deleted){r.set(t,c);const n=o[t];void 0!==n&&(Vs(n,c)?null!==n&&s.delete(e):("retain"===i&&u(),null===c?delete o[t]:o[t]=c))}s.deleted||("insert"===i&&u(),Gs(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 oi extends xs{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??ms(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){}this._pending=null}_copy(){return new oi}clone(){const e=new oi;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new ii(this,e,t);Ss(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??ms();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===xi&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?is(this.doc,n=>{const r=new Hs(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)&&Zs(n,this,r,o,i.attributes||{})}else void 0!==i.retain?ei(n,this,r,i.retain,i.attributes||{}):void 0!==i.delete&&si(n,r,i.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,n){this.doc??ms();const r=[],s=new Map,i=this.doc;let o="",c=this._start;function l(){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!==c;){if(Wr(c,e)||void 0!==t&&Wr(c,t))switch(c.content.constructor){case xi:{const r=s.get("ychange");void 0===e||Wr(c,e)?void 0===t||Wr(c,t)?void 0!==r&&(l(),s.delete("ychange")):void 0!==r&&r.user===c.id.client&&"added"===r.type||(l(),s.set("ychange",n?n("added",c.id):{type:"added"})):void 0!==r&&r.user===c.id.client&&"removed"===r.type||(l(),s.set("ychange",n?n("removed",c.id):{type:"removed"})),o+=c.content.str;break}case Ui:case vi:{l();const e={insert:c.content.getContent()[0]};if(s.size>0){const t={};e.attributes=t,s.forEach((e,n)=>{t[n]=e})}r.push(e);break}case wi:Wr(c,e)&&(l(),Gs(s,c.content))}c=c.right}l()};return e||t?is(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?is(r,r=>{const s=qs(r,this,e,!n);n||(n={},s.currentAttributes.forEach((e,t)=>{n[t]=e})),Zs(r,this,s,t,n)}):this._pending.push(()=>this.insert(e,t,n))}insertEmbed(e,t,n){const r=this.doc;null!==r?is(r,r=>{const s=qs(r,this,e,!n);Zs(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?is(n,n=>{si(n,qs(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?is(r,r=>{const s=qs(r,this,e,!1);null!==s.right&&ei(r,this,s,t,n)}):this._pending.push(()=>this.format(e,t,n))}removeAttribute(e){null!==this.doc?is(this.doc,t=>{Ls(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){null!==this.doc?is(this.doc,n=>{Rs(n,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return $s(this,e)}getAttributes(){return Ms(this)}_write(e){e.writeTypeRef(Ii)}}class ci{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??ms()}[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!==ai&&t.constructor!==li||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 li extends xs{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 li}clone(){const e=new li;return e.insert(0,this.toArray().map(e=>e instanceof xs?e.clone():e)),e}get length(){return this.doc??ms(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new ci(this,e)}querySelector(e){e=e.toUpperCase();const t=new ci(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),se(new ci(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Ss(this,e,new ui(this,t,e))}toString(){return Is(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),As(this,s=>{r.insertBefore(s.toDOM(e,t,n),null)}),r}insert(e,t){null!==this.doc?is(this.doc,n=>{Us(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)is(this.doc,n=>{const r=e&&e instanceof xs?e._item:e;js(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 Pe("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?is(this.doc,n=>{Ps(n,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return Cs(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Ds(this,e)}slice(e=0,t=this.length){return Es(this,e,t)}forEach(e){As(this,e)}_write(e){e.writeTypeRef(Di)}}class ai extends li{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 ai(this.nodeName)}clone(){const e=new ai(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 xs?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?is(this.doc,t=>{Ls(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?is(this.doc,n=>{Rs(n,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return $s(this,e)}hasAttribute(e){return Bs(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&&Wr(s,t)&&(n[r]=s.content.getContent()[s.length-1])}),n})(this,e):Ms(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 As(this,s=>{r.appendChild(s.toDOM(e,t,n))}),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Oi),e.writeKey(this.nodeName)}}class ui extends gs{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 di extends Ks{constructor(e){super(),this.hookName=e}_copy(){return new di(this.hookName)}clone(){const e=new di(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(ji),e.writeKey(this.hookName)}}class hi extends oi{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 hi}clone(){const e=new hi;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(Ti)}}class fi{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 pi extends fi{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 gi{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new gi(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 yi{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new yi(this.len)}splice(e){const t=new yi(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){wr(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 mi=(e,t)=>new xr({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class bi{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 bi(mi(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 vi{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new vi(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 wi{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new wi(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 _i{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new _i(this.arr)}splice(e){const t=new _i(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 ki="development"===Qn("node_env");class Si{constructor(e){this.arr=e,ki&&Kn(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Si(this.arr)}splice(e){const t=new Si(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 xi{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new xi(this.str)}splice(e){const t=new xi(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 Ei=[e=>new Ws,e=>new Ks,e=>new oi,e=>new ai(e.readKey()),e=>new li,e=>new di(e.readKey()),e=>new hi],Ci=0,Ai=1,Ii=2,Oi=3,Di=4,ji=5,Ti=6;class Ui{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Ui(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 Pi=(e,t,n)=>{const{client:r,clock:s}=t.id,i=new Li(Fr(r,s+n),t,Fr(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=Fr(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 Li extends fi{constructor(e,t,n,r,s,i,o,c){super(e,c.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=s,this.parent=i,this.parentSub=o,this.redone=null,this.content=c,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>=Hr(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Hr(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Br&&this.id.client!==this.parent.client&&this.parent.clock>=Hr(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Xr(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Qr(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===pi||this.right&&this.right.constructor===pi)this.parent=null;else if(this.parent){if(this.parent.constructor===Br){const e=Yr(t,this.parent);e.constructor===pi?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===Li?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Li&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Xr(e,e.doc.store,Fr(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),Nr(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(Nr(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!s.has(Yr(e.doc.store,t.origin)))break;r.has(Yr(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),ns(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new pi(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:Fr(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Nr(e.origin,this.lastId)&&this.right===e&&Nr(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(),wr(e.deleteSet,this.id.client,this.id.clock,this.length),ns(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Re();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[qr(r,t.id.clock)]=n})(e,this,new pi(this.id,this.length)):this.content=new yi(this.length)}write(e,t){const n=t>0?Fr(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,s=this.parentSub,i=31&this.content.getRef()|(null===n?0:Q)|(null===r?0:G)|(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 Re()})(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===Br?(e.writeParentInfo(!1),e.writeLeftID(t)):Re();null!==s&&e.writeString(s)}this.content.write(e,t)}}const Ri=(e,t)=>$i[31&t](e),$i=[()=>{Re()},e=>new yi(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 _i(n)},e=>new gi(e.readBuf()),e=>new xi(e.readString()),e=>new vi(e.readJSON()),e=>new wi(e.readKey(),e.readJSON()),e=>new Ui(Ei[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Si(n)},e=>new bi(mi(e.readString(),e.readAny())),()=>{Re()}];class Mi extends fi{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){Re()}write(e,t){e.writeInfo(10),me(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const Bi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},Ni="__ $YJS$ __";function Fi(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}Bi[Ni],Bi[Ni]=!0;const Wi=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=Hi(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=Hi(n,r,s),o=null===(t=this.cache[i])||void 0===t?void 0:t.deref();o&&Wi.unregister(o),this.cache[i]=new WeakRef(e),Wi.register(e,{cache:this.cache,key:i},e)},delete(e){Wi.unregister(e);const t=Hi(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 Ki=new WeakSet;function Vi(e){if(Ki.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function Hi(e,t,n){return`${e}[${t}].${n}`}const{getByKeyPath:Ji}=t.Dexie;let qi=null;function Yi(e){qi=e}function Gi(){}const Qi=new WeakMap;function Xi(){return t.Dexie.Events(null,"load","sync","error")}class Zi{static getOrCreateDocument(e,t,n,r){var s,i;const o=zi(e),c=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(!c)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 xr({meta:{db:e,updatesTable:s,parentProp:r,parentTable:n,parentId:i}}),t.add(o),o.on("destroy",()=>{Ki.add(o),t.delete(o)}),o)}(e,o,t,n,c,r)}static load(e,t){var n;let r=Qi.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 Zi(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,Qi.set(e,r)),r}static release(e){if(!e||Ki.has(e))return;const t=Qi.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(Zi.on("beforeunload").fire(this)).finally(()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())})}static for(e){return Qi.get(e)}static get currentUpdateRow(){return qi}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise((e,n)=>{this.doc?this.doc.isLoaded?e():this._error?n(this._error):Ki.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):Ki.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=Xi(),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]=()=>Zi.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`);Vi(e),this.stopObserving=function(e,n,r,s,i,o){let c=0,l=!0;const a=t.liveQuery(()=>{Vi(n);const e=r.table(i);return Promise.all([(c>0?e.where("i").between(c,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&&(c=t[t.length-1].i),0!==r.length?(Vi(n),t.length>0&&is(n,()=>{t.forEach(e=>{try{Yi(e),Ur(n,e.u)}finally{Yi(null)}})},e,!1),l&&(l=!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===c-1&&++c}).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),Zi.on("new").fire(this)}destroy(){var e;Qi.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=Xi(),this.cleanupHandlers.forEach(e=>e())}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function eo(e,n){return s(this,void 0,void 0,function*(){var r;const i={};let o,c=!1;for(const l of e)try{switch(l.type){case"u-s":{const e=Fi(n,l.table,l.prop);if(e){const t={k:l.k,u:l.u};l.r&&(t.r=l.r,o=l.r),i[e.name]=yield e.add(t)}break}case"u-ack":{const e=Fi(n,l.table,l.prop);e&&(yield n.transaction("rw",e,t=>s(this,void 0,void 0,function*(){let n=yield t.table(e.name).get(_n);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:_n}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,l.i+1)}))})));break}case"u-reject":{const e=Fi(n,l.table,l.prop);if(!e)break;const s=null===(r=yield e.get(l.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(l.i).filter(e=>0===t.cmp(e.k,s)&&!(1&~(e.f||0))).delete()));const r=Zi.getDocCache(n.dx).find(l.table,s,l.prop);r&&r.destroy()}break}case"in-sync":{const e=Zi.getDocCache(n.dx).find(l.table,l.k,l.prop);e&&!e.isSynced&&e.emit("sync",[!0,e]);break}case"y-complete-sync-done":o=l.yServerRev;break;case"outdated-server-rev":c=!0}}catch(e){}return{receivedUntils:i,resyncNeeded:c,yServerRevision:o}})}Zi.on=t.Dexie.Events(null,{new:[function(e,t){return e===Gi?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===Gi?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)}}]}),Zi.getDocCache=zi,t.Dexie.DexieYProvider?Zi=t.Dexie.DexieYProvider||Zi:t.Dexie.DexieYProvider=Zi;const to=new Map,no=new Set(["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","DataView"]),ro=new Set(["Blob","File","ArrayBuffer",...no]);function so(e){return Object.prototype.toString.call(e).slice(8,-1)}function io(e){if("object"!==typeof e||null===e)return!1;const t=so(e);return!!ro.has(t)&&("Blob"===t||"File"===t||e.byteLength>=4096)}function oo(e,t,n){return s(this,void 0,void 0,function*(){const r=yield t();if(!r)throw new Error("Failed to load access token for blob upload");const s=function(){const e=new Uint8Array(18),t=new Uint8Array(e.buffer,0,6),n=Date.now();R>=n?++R:R=n,t[0]=R/1099511627776,t[1]=R/4294967296,t[2]=R/16777216,t[3]=R/65536,t[4]=R/256,t[5]=R;const r=new Uint8Array(e.buffer,6);return L(r),C(e)}(),i=`${e}/blob/${s}`;let o,c,l;const a=function(e){const t=so(e);return"Blob"===t||"File"===t?"Blob":"ArrayBuffer"===t?"ArrayBuffer":t}(n),u=so(n);if("Blob"===u||"File"===u)o=n,c=n.type||"application/octet-stream",l=n.size;else if("ArrayBuffer"===u)o=n,c="application/octet-stream",l=n.byteLength;else{if(!no.has(u))throw new Error(`Unsupported blob type: ${u}`);{const e=n,t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),o=t,c="application/octet-stream",l=e.byteLength}}const d=`${i}?ct=${encodeURIComponent(c)}`,h=yield fetch(d,{method:"PUT",headers:{Authorization:`Bearer ${r}`,"Content-Type":c},body:o});if(!h.ok){if(404===h.status||405===h.status)return null;throw new Error(`Failed to upload blob: ${h.status} ${h.statusText}`)}const f=yield h.json();return Object.assign({_bt:a,ref:f.ref,size:l},"Blob"===a?{ct:c}:{})})}function co(e,t,n){return s(this,arguments,void 0,function*(e,t,n,r=32768){const s={dirty:!1},i=yield lo(e,t,n,r,s);return s.dirty&&"object"==typeof i&&null!==i&&i.constructor===Object&&(i._hasBlobRefs=1),i})}function lo(e,t,n){return s(this,arguments,void 0,function*(e,t,n,r=32768,s={dirty:!1},i=new WeakSet){if(null==e)return e;if("string"==typeof e&&e.length>r&&r!==1/0){if(!1===to.get(t))return e;const r=new Blob([e],{type:"text/plain;charset=utf-8"}),i=yield oo(t,n,r);return null===i?(to.set(t,!1),e):(to.set(t,!0),s.dirty=!0,Object.assign(Object.assign({},i),{_bt:"string"}))}if(io(e)){if(!1===to.get(t))return e;const r=yield oo(t,n,e);return null===r?(to.set(t,!1),e):(to.set(t,!0),s.dirty=!0,r)}if("object"!=typeof e)return e;if(i.has(e))return e;if(i.add(e),Array.isArray(e)){const o=[];for(const c of e)o.push(yield lo(c,t,n,r,s,i));return o}const o=Object.getPrototypeOf(e);if(o!==Object.prototype&&null!==o)return e;const c={};for(const[o,l]of Object.entries(e))c[o]=yield lo(l,t,n,r,s,i);return c})}function ao(e,t,n){return s(this,arguments,void 0,function*(e,t,n,r=32768){switch(e.type){case"insert":case"upsert":{const s=yield Promise.all(e.values.map(e=>co(e,t,n,r)));return Object.assign(Object.assign({},e),{values:s})}case"update":{const s=yield Promise.all(e.changeSpecs.map(e=>co(e,t,n,r)));return Object.assign(Object.assign({},e),{changeSpecs:s})}case"modify":{const s=yield co(e.changeSpec,t,n,r);return Object.assign(Object.assign({},e),{changeSpec:s})}default:return e}})}function uo(e,t){switch(e.type){case"insert":case"upsert":return e.values.some(e=>ho(e,t));case"update":return e.changeSpecs.some(e=>ho(e,t));case"modify":return ho(e.changeSpec,t);default:return!1}}function ho(e,t,n=new WeakSet){if(null==e)return!1;if("string"==typeof e&&e.length>t&&t!==1/0)return!0;if(io(e))return!0;if("object"!=typeof e)return!1;if(n.has(e))return!1;if(n.add(e),Array.isArray(e))return e.some(e=>ho(e,t,n));const r=Object.getPrototypeOf(e);return(r===Object.prototype||null===r)&&Object.values(e).some(e=>ho(e,t,n))}function fo(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 xt(e),u={"Content-Type":"application/json",Accept:"application/octet-stream"};a&&(u.Authorization=`Bearer ${a.accessToken}`);const d=yield fetch(`${n}/y/download`,{body:ln.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){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()}}}(d),tt,function(r){return c(this,arguments,function*(){var i,c,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=Fi(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=l(r);!(i=(y=yield o(b.next())).done);m=!0){u=y.value,m=!1;const e=new Be(u);for(;Fe(e);)switch(ze(e)){case 1:yield o(g(!0)),d=He(e);break;case 2:yield o(g(!1)),h=He(e),f=He(e);break;case 3:{const t=Ge(e),n=We(e);p.push({k:t,u:n});break}}yield o(g(!1))}}catch(e){c={error:e}}finally{try{m||i||!(a=b.return)||(yield o(a.call(b)))}finally{if(c)throw c.error}}yield o(g(!0))}catch(e){throw e instanceof t.DexieError||(yield o(g(!1))),e}})})})}const po=new WeakMap;function go(e){var n,r,s,i;let o=po.get(e);if(o&&o.expiration>Date.now()+3e5)return Promise.resolve(o.accessToken);const c=e.cloud.currentUser.value;return c&&c.accessToken&&(null!==(r=null===(n=c.accessTokenExpiration)||void 0===n?void 0:n.getTime())&&void 0!==r?r:1/0)>Date.now()+3e5?(po.set(e,{accessToken:c.accessToken,expiration:null!==(i=null===(s=c.accessTokenExpiration)||void 0===s?void 0:s.getTime())&&void 0!==i?i:1/0}),Promise.resolve(c.accessToken)):t.ignoreTransaction(()=>xt(e).then(t=>{var n,r;return(null==t?void 0:t.accessToken)&&po.set(e,{accessToken:t.accessToken,expiration:null!==(r=null===(n=t.accessTokenExpiration)||void 0===n?void 0:n.getTime())&&void 0!==r?r:1/0}),(null==t?void 0:t.accessToken)||null}))}const yo="currentSyncWorker";function mo(e,t,n,r){return bo(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):gn&&(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 mo(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:gn?"error":"offline",error:new Error(""+(null==i?void 0:i.message)||i)}),Promise.reject(i))}))}function bo(e,t,n){return s(this,arguments,void 0,function*(e,t,n,{isInitialSync:r,cancelToken:i,justCheckIfNeeded:o,purpose:c}={isInitialSync:!1}){var l,a,u;if(!(null===(l=e.cloud.options)||void 0===l?void 0:l.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:d}=t,h=yield e.getCurrentUser(),f=h.isLoggedIn?ot(e):[],p=f.map(t=>e.table(Qt(t.name))),g=yield e.getPersistedSyncState(),y=h.isLoggedIn,m=y?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return ot(e).filter(e=>!n.includes(e.name))}(e,g):[];pn(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!==Ot.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!==Ot.userId||(e.owner=t.userId)}):yield n.toCollection().modify(e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==Ot.userId||(e.owner=t.userId),e.realmId&&e.realmId!==Ot.userId||(e.realmId=t.userId))}))})}(m,h,null==g?void 0:g.realms)})),pn(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=>f.some(t=>t.name===e.tableName));let o=yield tn(p,e);const c=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(_n),c=(null==o?void 0:o.unsentFrom)||1,l=(null==o?void 0:o.receivedUntil)||0,a=Math.min(c,l+1),u=yield kn(i,a);u.length>0&&(r[i.name]=u[u.length-1].i);const d={};for(const e of u){const t=!(1&~(e.f||0));if(t&&e.i<c)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 c=1===i.length?i[0]:us(i);if(r)n.push({type:"u-c",table:s.name,prop:t.prop,k:e,u:c,i:o});else{const r=ls(c);n.push({type:"sv",table:s.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}})}(e,f);if(pn(i),b){const e=[...(null==g?void 0:g.realms)||[],...(null==g?void 0:g.inviteRealms)||[]],l=yield function(e,t,n,r){return s(this,void 0,void 0,function*(){const i=`upload-${nn(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],c=(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)}),l=yield c.toArray();if(l.length>0){const n={type:"upsert",values:l,keys:l.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,h,n,e);return pn(i),o=o.concat(l),[o,t,r,c]}return[o,t,r,c]})),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"===c&&!x)return!1;const E=mn(v,null==w?void 0:w.latestRevisions),C=(null==w?void 0:w.clientIdentity)||B(16);let A=v;const I=null!==(u=null===(a=e.cloud.options)||void 0===a?void 0:a.maxStringLength)&&void 0!==u?u:32768,O=function(e,t=32768){for(const n of e)for(const e of n.muts)if(uo(e,t))return!0;return!1}(v,I);O&&(A=yield function(e,t,n){return s(this,arguments,void 0,function*(e,t,n,r=32768){const s=[];for(const i of e){const e=[];for(const s of i.muts){const i=yield ao(s,t,n,r);e.push(i)}s.push({table:i.table,muts:e})}return s})}(v,d,()=>go(e),I)),pn(i);const D=yield fn(A,k,w,_,e,d,n,C,h),{done:j,newSyncState:T}=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))D.schema[e]&&(n[e]=D.schema[e]);yield e.$syncState.put(n,"schema");const r=yield tn(p,e,{since:E});for(const t of p){const n=Xt(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()])}mn(r,E),yield yn(e,n,E,D.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:[],c=new Set(t.realms),l=new Set(t.realms.concat(t.inviteRealms));for(const e of i)c.has(e)||(s.add(e),l.has(e)||r.add(e));for(const e of o.concat(i))l.has(e)||r.add(e);if(r.size>0||s.size>0){const t=ot(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,D,i);const o=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:C};y&&(o.syncedTables=f.map(e=>e.name).concat(m.map(e=>e.name))),o.latestRevisions=E,o.remoteDbId=D.dbId,o.initiallySynced=!0,o.realms=D.realms,o.inviteRealms=D.inviteRealms,o.serverRevision=D.serverRevision,o.yServerRevision=D.serverRevision,o.timestamp=new Date,delete o.error;const c=vo(D.changes,r);if(yield wn(c,e),D.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:r}=yield eo(D.yMessages,e);r&&(o.yServerRevision=r),yield function(e,t,n){return s(this,void 0,void 0,function*(){var r,i,o,c,l;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!==(l=null!==(c=null==t?void 0:t.receivedUntil)&&void 0!==c?c:(yield n.table(e).where("i").between(1,1/0).reverse().limit(1).primaryKeys())[0])&&void 0!==l?l:0;yield n.transaction("rw",e,()=>s(this,void 0,void 0,function*(){const t=yield n.table(e).get(_n);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:_n,unsentFrom:r,receivedUntil:i})}))}})}(S,t,e),n&&(o.yDownloadedRealms={})}return e.$syncState.put(o,"syncState"),{done:0===r.length,newSyncState:o}}));if(!j)return yield hn(e),yield bo(e,t,n,{isInitialSync:r,cancelToken:i});const U=Object.values(n).some(e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length}),P=!!D.yMessages;if(U&&P)try{yield fo(e,d,T)}catch(e){}return e.syncCompleteEvent.next(),!1})}function vo(e,t){const n={};K(n,e);const r={};return K(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))M(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 wo(e){const i=[],o=new n.BehaviorSubject(!0),c=new n.BehaviorSubject(null);let l=!1,a=new Array(10).fill(0);return c.subscribe(()=>s(this,void 0,void 0,function*(){if(!l&&i.length>0){l=!0,a.shift(),a.push(Date.now()),o.next(!1);try{yield function(){return s(this,void 0,void 0,function*(){for(var o,c,l,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 Ct(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===(c=null==i?void 0:i.inviteRealms)||void 0===c?void 0:c.includes(h.realm))||(yield e.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(l=null==i?void 0:i.realms)||void 0===l?void 0:l.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)){ht(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!1;if(h.baseRev!==s.serverRevision)return"string"!=typeof h.baseRev||"bigint"!=typeof s.serverRevision&&"object"!=typeof s.serverRevision||ht(e,"pull"),!1;if((yield t.waitFor(Gt(s)))!==h.realmSetHash)return ht(e,"pull"),!1;let o=[];if(i.isLoggedIn){const t=ot(e).map(t=>e.table(Qt(t.name)));o=yield tn(t,e)}if(h.changes.length>0){const t=vo(h.changes,o);yield wn(t,e)}return s.latestRevisions=mn(o,s.latestRevisions),s.serverRevision=h.newRev,yield yn(e,r,s.latestRevisions,h.newRev),yield e.$syncState.put(s,"syncState"),!0})))&&h.changes.length>0&&e.syncCompleteEvent.next();break}}catch(e){}}})}()}finally{a[a.length-1]-a[0]<1e4&&(yield new Promise(e=>setTimeout(e,1e3))),l=!1,o.next(!0)}}})),{enqueue:function(e){i.push(e),c.next(null)},readyToServe:o}}class _o{constructor(e){this.inFlight=new Map,this.db=e}download(e,t){let n=this.inFlight.get(e.ref);return n||(n=go(this.db).then(n=>{if(!n)throw new Error("No access token available for blob download");return function(e,t,n){return s(this,void 0,void 0,function*(){const r=`${t}/blob/${e.ref}`,s=yield fetch(r,{headers:{Authorization:`Bearer ${n}`}});if(!s.ok)throw new Error(`Failed to download blob ${e.ref}: ${s.status} ${s.statusText}`);const i=yield s.arrayBuffer();return new Uint8Array(i)})}(e,t,n)}).finally(()=>this.inFlight.delete(e.ref)),this.inFlight.set(e.ref,n)),n}}const ko=new WeakMap,So={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let xo=0;function Eo(e){"vip"in e&&(e=e.vip);let t=ko.get(e);if(!t){const r=new n.Subject;let s=new Yt(`syncstatechanged-${e.name}`),i=new Yt(`synccomplete-${e.name}`);r.id=++xo;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},get cloud(){return 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 c={getCurrentUser:()=>t.$logins.toArray().then(e=>e.find(e=>e.isLoggedIn)||Ot),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=Co(n.schema.primKey.keyPath));return e}),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){s=new Yt(`syncstatechanged-${e.name}`),i=new Yt(`synccomplete-${e.name}`)}};Object.assign(t,c),t.messageConsumer=wo(t),t.messageProducer=new n.Subject,t.blobDownloadTracker=new _o(t),ko.set(e,t)}return t}function Co(e){return"string"==typeof e?e:e?"["+[].join.call(e,"+")+"]":""}const Ao="undefined"!=typeof InstallTrigger,Io="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),Oo=Io?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,Do=Io&&Oo<=605||Ao,jo="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:To}={};function Uo(e){return To.call(e).slice(8,-1)}function Po(e,t){var n;return"delete"===t.type?t.keys:(null===(n=t.keys)||void 0===n?void 0:n.slice())||t.values.map(e.extractKey)}function Lo(e,t){return(1&t?e[0].toUpperCase():e[0].toLowerCase())+(2&t?e[1].toUpperCase():e[1].toLowerCase())+(4&t?e[2].toUpperCase():e[2].toLowerCase())}const Ro=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;function $o(e){return e>="A"&&e<="Z"}let Mo=0;function Bo(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),s=Date.now();Mo>=s?++Mo:Mo=s,r[0]=Mo/1099511627776,r[1]=Mo/4294967296,r[2]=Mo/16777216,r[3]=Mo/65536,r[4]=Mo/256,r[5]=Mo;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+C(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 c=n.trans;if("versionchange"===c.mode&&(c.disableChangeTracking=!0,c.disableAccessControl=!0),c.disableChangeTracking)return s.mutate(n);if("add"===n.type||"put"===n.type){const c=null===(i=e.cloud.schema)||void 0===i?void 0:i[r];if(null==c?void 0:c.generatedGlobalId){if((null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!e.initiallySynced){const e=Po(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 c=Po(s.schema.primaryKey,n);return c.forEach((l,a)=>{if(void 0===l){const r=n.values[a].realmId||e.cloud.currentUserId,l=r.substr(r.length-3);c[a]=Bo(i,l),s.schema.primaryKey.outbound||(o||(o=n.values.slice()),o[a]=t.deepClone(o[a]),t.setByKeyPath(o[a],s.schema.primaryKey.keyPath,c[a]))}else if("string"!=typeof l||!l.startsWith(i)&&!l.startsWith("#"+i))throw new t.ConstraintError(`The ID "${l}" 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:c,values:o||n.values}))}(n,c.idPrefix)}if(null==c?void 0:c.markedForSync){Po(s.schema.primaryKey,n).forEach((e,n)=>{if(!F(e)){const n=Array.isArray(e)?e.map(Uo).join(","):Uo(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 Fo=0;function Wo(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 zo(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 Ko=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 Ho({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=>Qt(e));i=r.transaction([...t,...e],s)}else i=r.transaction(t,s);if("readwrite"===s){i.txid=nn(16),i.opCount=0,i.currentUser=e.value,Ko.value.add(i),Ko.next(Ko.value);const t=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",t),i.removeEventListener("abort",t),Ko.value.delete(i),Ko.next(Ko.value)},r=()=>{i.mutationsAdded&&!Vo(n)&&ht(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,c=o.get(e);return c?function(e){const t="$lock"+ ++Fo;return Object.assign(Object.assign({},e),{count:Wo(e.count,t),get:Wo(e.get,t),getMany:Wo(e.getMany,t),openCursor:Wo(e.openCursor,t),query:Wo(e.query,t),mutate:zo(e.mutate,t)})}(Object.assign(Object.assign({},s),{mutate:t=>{var r,o,c;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===(c=a.currentUser)||void 0===c?void 0:c.isLoggedIn)?"deleteRange"===t.type?s.query({query:{range:t.range,index:i.primaryKey},trans:t.trans,values:!1}).then(e=>l({type:"delete",keys:e.result,trans:t.trans,criteria:{index:null,range:t.range}})):l(t):s.mutate(t):s.mutate(t)}})):s;function l(r){var o,l;const a=r.trans,u=null===(l=null===(o=n.cloud.options)||void 0===o?void 0:o.unsyncedProperties)||void 0===l?void 0:l[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 l="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&&(l=l.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=l.length;n<s;++n)r.hasKey(l[n])&&(e.push(l[n]),t.push(y[n]));l=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:l,criteria:_,txid:d,userId:h}:"add"===r.type?{type:"insert",ts:w,opNo:p,keys:l,txid:d,userId:h,values:y}:v&&b?{type:"upsert",ts:w,opNo:p,keys:l,values:y,changeSpecs:b.changeSpecs.filter((e,t)=>!o[t]),txid:d,userId:h}:_&&m?{type:"modify",ts:w,opNo:p,keys:l,criteria:_,changeSpec:m,txid:d,userId:h}:m?{type:"update",ts:w,opNo:p,keys:l,changeSpecs:l.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:l,values:y,txid:d,userId:h};return"isAdditionalChunk"in r&&r.isAdditionalChunk&&(k.isAdditionalChunk=!0),l.length>0||_?c.mutate({type:"add",trans:a,values:[k]}).then(()=>(a.mutationsAdded=!0,e)):e})}}})}}}class Jo{constructor(e){this.queue=[],this.isProcessing=!1,this.db=e}saveBlobs(e,t,n){this.queue.push({tableName:e,primaryKey:t,resolvedBlobs:n}),this.startConsumer()}startConsumer(){this.isProcessing||(this.isProcessing=!0,setTimeout(()=>{this.processQueue()},0))}processQueue(){const e=this.queue.shift();e?this.db.transaction("rw",e.tableName,n=>{const r=n.idbtrans;r.disableChangeTracking=!0,r.disableAccessControl=!0,r.disableBlobResolve=!0;const s={};for(const t of e.resolvedBlobs)s[t.keyPath]=t.data;n.table(e.tableName).update(e.primaryKey,n=>{for(const r of e.resolvedBlobs){const e=t.getByKeyPath(n,r.keyPath);if(void 0!==e&&nt(e)){if(e.ref!==r.ref)return;t.setByKeyPath(n,r.keyPath,r.data)}}delete n._hasBlobRefs})}).catch(e=>{}).finally(()=>this.processQueue()):this.isProcessing=!1}}function qo(e){return{stack:"dbcore",name:"blobResolve",level:2,create(n){const r=new Jo(e);return Object.assign(Object.assign({},n),{table(s){var i;if(!e.cloud)return n.table(s);const o=null===(i=e.cloud.options)||void 0===i?void 0:i.databaseUrl,c=n.table(s);return s.startsWith("$")?c:Object.assign(Object.assign({},c),{get(t){var n;return(null===(n=t.trans)||void 0===n?void 0:n.disableBlobResolve)?c.get(t):c.get(t).then(n=>n&&it(n)?Yo(c,t.trans,t.key,n,r,e):n)},getMany(n){var s;return(null===(s=n.trans)||void 0===s?void 0:s.disableBlobResolve)?c.getMany(n):c.getMany(n).then(s=>{const i=s.some(e=>e&&it(e));return i?t.Promise.all(s.map((t,s)=>t&&it(t)?Yo(c,n.trans,n.keys[s],t,r,e):t)):s})},query(n){var s;return(null===(s=n.trans)||void 0===s?void 0:s.disableBlobResolve)?c.query(n):c.query(n).then(s=>{if(!s.result||!Array.isArray(s.result))return s;const i=s.result.some(e=>e&&it(e));return i?t.Promise.all(s.result.map(t=>t&&it(t)?Yo(c,n.trans,void 0,t,r,e):t)).then(e=>Object.assign(Object.assign({},s),{result:e})):s})},openCursor(t){var n;return(null===(n=t.trans)||void 0===n?void 0:n.disableBlobResolve)?c.openCursor(t):c.openCursor(t).then(n=>n&&t.values&&o?function(e,t,n,r){const s=Object.create(e,{value:{value:e.value,enumerable:!0,writable:!0},start:{value:i=>e.start(()=>{const o=e.value;if(!o||!it(o))return s.value=o,void i();Yo(t,e.trans,e.primaryKey,o,n,r,!0).then(e=>{s.value=e,i()},e=>{s.value=o,i()})})}});return s}(n,c,r,e):n)}})}})}}}function Yo(e,n,r,s,i,o,c=!1){var l;try{const a=t.currentTransaction,u="readonly"===(null==a?void 0:a.mode),d=!0===(null==a?void 0:a.explicit),h=a&&!(u&&!d&&!c),f=(null===(l=o.cloud.options)||void 0===l?void 0:l.databaseUrl)||"",p=[],g=st(s,f,p,"",new WeakMap,o.blobDownloadTracker);return(h?t.waitFor(g):t.Promise.resolve(g)).then(o=>{const c=e.schema.primaryKey,l=void 0!==r?r:c.keyPath?t.getByKeyPath(s,c.keyPath):void 0;return void 0!==l&&(u?i.saveBlobs(e.name,l,p):e.mutate({type:"put",keys:[l],values:[o],trans:n}).catch(e=>{})),o}).catch(e=>s)}catch(e){return t.Promise.resolve(s)}}function Go(e,t){return function(n,r){var s;const i=Object.assign(Object.assign({},So),n);Object.keys(So).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=So[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(So[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={}),c=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)(Ro.test(e[t])||$o(e[t]))&&(n+=e[t].toLowerCase());for(;t.has(n);){if(/\d/g.test(n)){if(n=n.substr(0,n.length-1)+(n[n.length-1]+1),!(n.length>3))continue;n=n.substr(0,3)}else if(n.length<3){n+="2";continue}let e=1,r=n;for(;t.has(r)&&e<8;)r=Lo(n,e),++e;if(e<8)n=r;else{let e=n.charCodeAt(2)+1&127;n=n.substr(0,2)+String.fromCharCode(e)}}return n}(e,c),c.add(r.idPrefix)),/^\$/.test(e)||(i[`$${e}_mutations`]="++rev",r.markedForSync=!0,i[e].includes("_hasBlobRefs")||(i[e]+=",_hasBlobRefs")),r.deleted&&(r.deleted=!1)):(r.deleted=!0,r.markedForSync=!1,i[`$${e}_mutations`]=null)});const l=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 l}}function Qo(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,n):n()}const Xo=new n.BehaviorSubject(!0),Zo=new n.BehaviorSubject(!0);Xo.pipe(r.switchMap(e=>e?n.of(!0):n.of(!1).pipe(r.delay(2e4))),r.distinctUntilChanged()).subscribe(Zo);const ec="undefined"!=typeof document?n.fromEvent(document,"visibilitychange"):n.of({}),tc=ec.pipe(r.filter(()=>"hidden"===document.visibilityState)),nc=ec.pipe(r.filter(()=>"visible"===document.visibilityState)),rc="undefined"!=typeof window?n.merge(nc,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),tc,rc).pipe(r.map(()=>"visible"===document.visibilityState),r.tap(e=>{Xo.value!==e&&Xo.next(e)}),r.switchMap(e=>e?n.of(0).pipe(r.delay(16e4),r.tap(()=>Xo.next(!1))):n.of(0))).subscribe(()=>{});class sc extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}const ic=new WeakMap,oc=3e4;class cc extends An{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=Tn();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&&oc<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&lc(this,t,"timeout")},V(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:Tn()});const i=[],o=[],c=[],l=[];null===e?l.push(t):null==s?null!=e&&i.push(t):(o.push(t),Jn(s,e)||c.push(t)),(i.length>0||c.length>0||l.length>0)&&this.emit("change",[{added:i,updated:c,removed:l},"local"]),this.emit("update",[{added:i,updated:o,removed:l},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}}const lc=(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:Tn()})}r.push(s)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},ac=new WeakMap;function uc(e){let t=ac.get(e);return t||(t=new n.Subject,ac.set(e,t)),t}class dc extends n.Observable{constructor(e,t,n,r,s,i,o,c){super(l=>new fc(e,t,n,r,s,c,l,i,o))}}let hc=0;class fc extends n.Subscription{constructor(e,t,n,r,s,i,o,c,l){super(()=>this.teardown()),this.id=++hc,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=c,this.webSocketStatus=l,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 sc);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","3"),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?ln.parse(e.data):function(e){const t=new Be(e),n=He(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:He(t)};const r=He(t),s=He(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:s,i:Number(qe(t))};default:{const e=Ge(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:We(t)};case"doc-open":return{type:n,table:r,prop:s,k:e,serverRev:Ge(t),sv:Ge(t)};case"sv":return{type:n,table:r,prop:s,k:e,sv:We(t)};case"u-c":return{type:n,table:r,prop:s,k:e,u:We(t),i:Number(qe(t))};case"u-s":return{type:n,table:r,prop:s,k:e,u:We(t),r:t.pos<t.arr.length&&He(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=Zi.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>ic.get(e))(e);n&&((e,t,n)=>{const r=Ne(t),s=Tn(),i=[],o=[],c=[],l=[],a=Ke(r);for(let t=0;t<a;t++){const t=Ke(r);let n=Ke(r);const a=JSON.parse(He(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?l.push(t):null!==a&&(Jn(a,d)||c.push(t),o.push(t)))}(i.length>0||c.length>0||l.length>0)&&e.emit("change",[{added:i,updated:c,removed:l},n]),(i.length>0||o.length>0||l.length>0)&&e.emit("update",[{added:i,updated:o,removed:l},n])})(n,t.u,"server")}}else if("pong"===t.type);else if("doc-open"===t.type){const e=Zi.getDocCache(this.db.dx).find(t.table,t.k,t.prop);e&&uc(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?eo([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=Fi(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(_n,{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(ln.stringify(e))):null===(n=this.ws)||void 0===n||n.send(function(e){const t=new he;switch(_e(t,e.type),"table"in e&&_e(t,e.table),"prop"in e&&_e(t,e.prop),e.type){case"u-ack":case"u-reject":Ee(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":_e(t,e.yServerRev);break;default:switch(Ae(t,e.k),e.type){case"aware":Se(t,e.u);break;case"doc-open":Ae(t,e.serverRev),Ae(t,e.sv);break;case"doc-close":break;case"sv":Se(t,e.sv);break;case"u-c":Se(t,e.u),Ee(t,BigInt(e.i));break;case"u-s":Se(t,e.u),_e(t,e.r||"")}}return pe(t)}(e)))})),this.user.isLoggedIn&&!Vo(this.db)&&this.subscriptions.add(function(e){const r=en(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 c=e.table(o);return n.from(c.get(_n)).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 kn(c,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 pc extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function gc(e){return s(this,void 0,void 0,function*(){var e;yield(e=3e3,new Promise(t=>setTimeout(t,e))),yield n.firstValueFrom(rc)})}function yc(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 mo(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))})}const mc=new WeakMap;function bc(e,t,n,r){const i=mc.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 bc(e,t,n,r)})}}const o=function(){return s(this,void 0,void 0,function*(){try{yield hn(e),yield Qo(e,yo,()=>mo(e,t,n,r)),mc.delete(e)}catch(t){throw mc.delete(e),t}})}();return mc.set(e,{promise:o,pull:"push"!==(null==r?void 0:r.purpose)}),o}function vc(e,t,n){let r=null,s={cancelled:!1},i=0,o=0;function c(r=1){setTimeout(()=>{const h=l?"pull":"push";l=!1,a=!1,o=Date.now(),bc(e,t,n,{cancelToken:s,retryImmediatelyOnFetchError:!0,purpose:h}).then(()=>{if(s.cancelled)d();else if(l||a)return c();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]*St;i=Date.now()+e,o=0,setTimeout(()=>c(r+1),e)}else u=!1,i=0,o=0})},0)}let l=!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&&(l=!0),"push"===e&&(a=!0),u?i||o>0&&Date.now():(u=!0,c()))})(e||"pull")})},stop:d}}function wc(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var _c,kc,Sc,xc,Ec,Cc,Ac,Ic,Oc,Dc,jc,Tc={},Uc=[],Pc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Lc=Array.isArray;function Rc(e,t){for(var n in t)e[n]=t[n];return e}function $c(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Mc(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?_c.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 Bc(e,o,r,s,null)}function Bc(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?++Sc:s,__i:-1,__u:0};return null==s&&null!=kc.vnode&&kc.vnode(i),i}function Nc(e){return e.children}function Fc(e,t){this.props=e,this.context=t}function Wc(e,t){if(null==t)return e.__?Wc(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?Wc(e):null}function zc(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 zc(e)}}function Kc(e){(!e.__d&&(e.__d=!0)&&xc.push(e)&&!Vc.__r++||Ec!=kc.debounceRendering)&&((Ec=kc.debounceRendering)||Cc)(Vc)}function Vc(){for(var e,t,n,r,s,i,o,c=1;xc.length;)xc.length>c&&xc.sort(Ac),e=xc.shift(),c=xc.length,e.__d&&(n=void 0,r=void 0,s=(r=(t=e).__v).__e,i=[],o=[],t.__P&&((n=Rc({},r)).__v=r.__v+1,kc.vnode&&kc.vnode(n),Xc(t.__P,n,r,t.__n,t.__P.namespaceURI,32&r.__u?[s]:null,i,null==s?Wc(r):s,!!(32&r.__u),o),n.__v=r.__v,n.__.__k[n.__i]=n,el(i,n,o),r.__e=r.__=null,n.__e!=s&&zc(n)));Vc.__r=0}function Hc(e,t,n,r,s,i,o,c,l,a,u){var d,h,f,p,g,y,m,b=r&&r.__k||Uc,v=t.length;for(l=function(e,t,n,r,s){var i,o,c,l,a,u=n.length,d=u,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]=Bc(null,o,null,null,null):Lc(o)?o=e.__k[i]=Bc(Nc,{children:o},null,null,null):null==o.constructor&&o.__b>0?o=e.__k[i]=Bc(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[i]=o,l=i+h,o.__=e,o.__b=e.__b+1,-1!=(a=o.__i=qc(o,n,l,d))&&(d--,(c=n[a])&&(c.__u|=2)),null==c||null==c.__v?(-1==a&&(s>u?h--:s<u&&h++),"function"!=typeof o.type&&(o.__u|=4)):a!=l&&(a==l-1?h--:a==l+1?h++:(a>l?h--:h++,o.__u|=4))):e.__k[i]=null;if(d)for(i=0;i<u;i++)null!=(c=n[i])&&!(2&c.__u)&&(c.__e==r&&(r=Wc(c)),sl(c,c));return r}(n,t,b,l,v),d=0;d<v;d++)null!=(f=n.__k[d])&&(h=-1==f.__i?Tc:b[f.__i]||Tc,f.__i=d,y=Xc(e,f,h,s,i,o,c,l,a,u),p=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&rl(h.ref,null,f),u.push(f.ref,f.__c||p,f)),null==g&&null!=p&&(g=p),(m=!!(4&f.__u))||h.__k===f.__k?l=Jc(f,l,e,m):"function"==typeof f.type&&void 0!==y?l=y:p&&(l=p.nextSibling),f.__u&=-7);return n.__e=g,l}function Jc(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=Jc(s[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=Wc(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function qc(e,t,n,r){var s,i,o,c=e.key,l=e.type,a=t[n],u=null!=a&&!(2&a.__u);if(null===a&&null==c||u&&c==a.key&&l==a.type)return n;if(r>(u?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)&&c==a.key&&l==a.type)return o;return-1}function Yc(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||Pc.test(t)?n:n+"px"}function Gc(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||Yc(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Yc(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])i=t!=(t=t.replace(Ic,"$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=Oc,e.addEventListener(t,i?jc:Dc,i)):e.removeEventListener(t,i?jc:Dc,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 Qc(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t.t)t.t=Oc++;else if(t.t<n.u)return;return n(kc.event?kc.event(t):t)}}}function Xc(e,t,n,r,s,i,o,c,l,a){var u,d,h,f,p,g,y,m,b,v,w,_,k,S,x,E,C,A=t.type;if(null!=t.constructor)return null;128&n.__u&&(l=!!(32&n.__u),i=[c=t.__e=n.__e]),(u=kc.__b)&&u(t);e:if("function"==typeof A)try{if(m=t.props,b="prototype"in A&&A.prototype.render,v=(u=A.contextType)&&r[u.__c],w=u?v?v.props.value:u.__:r,n.__c?y=(d=t.__c=n.__c).__=d.__E:(b?t.__c=d=new A(m,w):(t.__c=d=new Fc(m,w),d.constructor=A,d.render=il),v&&v.sub(d),d.state||(d.state={}),d.__n=r,h=d.__d=!0,d.__h=[],d._sb=[]),b&&null==d.__s&&(d.__s=d.state),b&&null!=A.getDerivedStateFromProps&&(d.__s==d.state&&(d.__s=Rc({},d.__s)),Rc(d.__s,A.getDerivedStateFromProps(m,d.__s))),f=d.props,p=d.state,d.__v=t,h)b&&null==A.getDerivedStateFromProps&&null!=d.componentWillMount&&d.componentWillMount(),b&&null!=d.componentDidMount&&d.__h.push(d.componentDidMount);else{if(b&&null==A.getDerivedStateFromProps&&m!==f&&null!=d.componentWillReceiveProps&&d.componentWillReceiveProps(m,w),t.__v==n.__v||!d.__e&&null!=d.shouldComponentUpdate&&!1===d.shouldComponentUpdate(m,d.__s,w)){for(t.__v!=n.__v&&(d.props=m,d.state=d.__s,d.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(e){e&&(e.__=t)}),_=0;_<d._sb.length;_++)d.__h.push(d._sb[_]);d._sb=[],d.__h.length&&o.push(d);break e}null!=d.componentWillUpdate&&d.componentWillUpdate(m,d.__s,w),b&&null!=d.componentDidUpdate&&d.__h.push(function(){d.componentDidUpdate(f,p,g)})}if(d.context=w,d.props=m,d.__P=e,d.__e=!1,k=kc.__r,S=0,b){for(d.state=d.__s,d.__d=!1,k&&k(t),u=d.render(d.props,d.state,d.context),x=0;x<d._sb.length;x++)d.__h.push(d._sb[x]);d._sb=[]}else do{d.__d=!1,k&&k(t),u=d.render(d.props,d.state,d.context),d.state=d.__s}while(d.__d&&++S<25);d.state=d.__s,null!=d.getChildContext&&(r=Rc(Rc({},r),d.getChildContext())),b&&!h&&null!=d.getSnapshotBeforeUpdate&&(g=d.getSnapshotBeforeUpdate(f,p)),E=u,null!=u&&u.type===Nc&&null==u.key&&(E=tl(u.props.children)),c=Hc(e,Lc(E)?E:[E],t,n,r,s,i,o,c,l,a),d.base=t.__e,t.__u&=-161,d.__h.length&&o.push(d),y&&(d.__E=d.__=null)}catch(e){if(t.__v=null,l||null!=i)if(e.then){for(t.__u|=l?160:128;c&&8==c.nodeType&&c.nextSibling;)c=c.nextSibling;i[i.indexOf(c)]=null,t.__e=c}else{for(C=i.length;C--;)$c(i[C]);Zc(t)}else t.__e=n.__e,t.__k=n.__k,e.then||Zc(t);kc.__e(e,t,n)}else null==i&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=nl(n.__e,t,n,r,s,i,o,l,a);return(u=kc.diffed)&&u(t),128&t.__u?void 0:c}function Zc(e){e&&e.__c&&(e.__c.__e=!0),e&&e.__k&&e.__k.forEach(Zc)}function el(e,t,n){for(var r=0;r<n.length;r++)rl(n[r],n[++r],n[++r]);kc.__c&&kc.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){kc.__e(e,t.__v)}})}function tl(e){return"object"!=typeof e||null==e||e.__b&&e.__b>0?e:Lc(e)?e.map(tl):Rc({},e)}function nl(e,t,n,r,s,i,o,c,l){var a,u,d,h,f,p,g,y=n.props||Tc,m=t.props,b=t.type;if("svg"==b?s="http://www.w3.org/2000/svg":"math"==b?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==!!b&&(b?f.localName==b:3==f.nodeType)){e=f,i[a]=null;break}if(null==e){if(null==b)return document.createTextNode(m);e=document.createElementNS(s,b,m.is&&m),c&&(kc.__m&&kc.__m(t,i),c=!1),i=null}if(null==b)y===m||c&&e.data==m||(e.data=m);else{if(i=i&&_c.call(e.childNodes),!c&&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)d=f;else if(!(a in m)){if("value"==a&&"defaultValue"in m||"checked"==a&&"defaultChecked"in m)continue;Gc(e,a,null,f,s)}for(a in m)f=m[a],"children"==a?h=f:"dangerouslySetInnerHTML"==a?u=f:"value"==a?p=f:"checked"==a?g=f:c&&"function"!=typeof f||y[a]===f||Gc(e,a,f,y[a],s);if(u)c||d&&(u.__html==d.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(d&&(e.innerHTML=""),Hc("template"==t.type?e.content:e,Lc(h)?h:[h],t,n,r,"foreignObject"==b?"http://www.w3.org/1999/xhtml":s,i,o,i?i[0]:n.__k&&Wc(n,0),c,l),null!=i)for(a=i.length;a--;)$c(i[a]);c||(a="value","progress"==b&&null==p?e.removeAttribute("value"):null!=p&&(p!==e[a]||"progress"==b&&!p||"option"==b&&p!=y[a])&&Gc(e,a,p,y[a],s),a="checked",null!=g&&g!=e[a]&&Gc(e,a,g,y[a],s))}return e}function rl(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){kc.__e(e,n)}}function sl(e,t,n){var r,s;if(kc.unmount&&kc.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||rl(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){kc.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(s=0;s<r.length;s++)r[s]&&sl(r[s],t,n||"function"!=typeof e.type);n||$c(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),kc.__&&kc.__(e,t),r=!1?null:t.__k,s=[],i=[],Xc(t,e=t.__k=Mc(Nc,null,[e]),r||Tc,Tc,t.namespaceURI,r?null:t.firstChild?_c.call(t.childNodes):null,s,r?r.__e:t.firstChild,false,i),el(s,e,i)}_c=Uc.slice,kc={__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}},Sc=0,Fc.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=Rc({},this.state),"function"==typeof e&&(e=e(Rc({},n),this.props)),e&&Rc(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),Kc(this))},Fc.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Kc(this))},Fc.prototype.render=Nc,xc=[],Cc="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ac=function(e,t){return e.__v.__b-t.__v.__b},Vc.__r=0,Ic=/(PointerCapture)$|Capture$/i,Oc=0,Dc=Qc(!1),jc=Qc(!0);const cl={Alert:{error:{color:"red",fontWeight:"bold"},warning:{color:"#f80",fontWeight:"bold"},info:{color:"black"}},Darken:{position:"fixed",top:0,left:0,opacity:.5,backgroundColor:"#000",width:"100vw",height:"100vh",zIndex:150,webkitBackdropFilter:"blur(2px)",backdropFilter:"blur(2px)"},DialogOuter:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:150,alignItems:"center",display:"flex",justifyContent:"center",padding:"16px",boxSizing:"border-box"},DialogInner:{position:"relative",color:"#222",backgroundColor:"#fff",padding:"24px",marginBottom:"2em",maxWidth:"400px",width:"100%",maxHeight:"90%",overflowY:"auto",border:"3px solid #3d3d5d",borderRadius:"8px",boxShadow:"0 0 80px 10px #666",fontFamily:"sans-serif",boxSizing:"border-box"},Input:{height:"35px",width:"100%",maxWidth:"100%",borderColor:"#ccf4",outline:"none",fontSize:"16px",padding:"8px",boxSizing:"border-box",backgroundColor:"#f9f9f9",borderRadius:"4px",border:"1px solid #ccc",marginTop:"6px",fontFamily:"inherit"},Button:{padding:"10px 20px",margin:"0 4px",border:"1px solid #d1d5db",borderRadius:"6px",backgroundColor:"#ffffff",cursor:"pointer",fontSize:"14px",fontWeight:"500",color:"#374151",transition:"all 0.2s ease"},PrimaryButton:{padding:"10px 20px",margin:"0 4px",border:"1px solid #3b82f6",borderRadius:"6px",backgroundColor:"#3b82f6",color:"white",cursor:"pointer",fontSize:"14px",fontWeight:"500",transition:"all 0.2s ease"},ButtonsDiv:{display:"flex",justifyContent:"flex-end",gap:"12px",marginTop:"24px",paddingTop:"20px"},Label:{display:"block",marginBottom:"12px",fontSize:"14px",fontWeight:"500",color:"#333"},WindowHeader:{margin:"0 0 20px 0",fontSize:"18px",fontWeight:"600",color:"#333",borderBottom:"1px solid #eee",paddingBottom:"10px"},ProviderButton:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",padding:"12px 16px",marginBottom:"10px",border:"1px solid #d1d5db",borderRadius:"6px",backgroundColor:"#ffffff",cursor:"pointer",fontSize:"14px",fontWeight:"500",color:"#374151",transition:"all 0.2s ease",gap:"12px"},ProviderButtonIcon:{width:"20px",height:"20px",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},ProviderButtonText:{flex:1,textAlign:"left"},ProviderGoogle:{backgroundColor:"#ffffff",border:"1px solid #dadce0",color:"#3c4043"},ProviderGitHub:{backgroundColor:"#ffffff",border:"1px solid #dadce0",color:"#181717"},ProviderMicrosoft:{backgroundColor:"#ffffff",border:"1px solid #dadce0",color:"#5e5e5e"},ProviderApple:{backgroundColor:"#000000",border:"1px solid #000000",color:"#ffffff"},ProviderCustom:{backgroundColor:"#ffffff",border:"1px solid #dadce0",color:"#181717"},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"},CopyButton:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"4px 10px",marginTop:"8px",border:"1px solid #d1d5db",borderRadius:"4px",backgroundColor:"#f9fafb",cursor:"pointer",fontSize:"12px",fontWeight:"500",color:"#374151",transition:"all 0.15s ease",fontFamily:"monospace"},CopyButtonCopied:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"4px 10px",marginTop:"8px",border:"1px solid #22c55e",borderRadius:"4px",backgroundColor:"#f0fdf4",cursor:"default",fontSize:"12px",fontWeight:"500",color:"#16a34a",fontFamily:"monospace"}};function ll({children:e,className:t}){return Mc("div",{className:`dexie-dialog ${t||""}`},Mc("div",{style:cl.Darken}),Mc("div",{style:cl.DialogOuter},Mc("div",{style:cl.DialogInner},e)))}var al,ul,dl,hl,fl=0,pl=[],gl=kc,yl=gl.__b,ml=gl.__r,bl=gl.diffed,vl=gl.__c,wl=gl.unmount,_l=gl.__;function kl(e,t){gl.__h&&gl.__h(ul,e,fl||t),fl=0;var n=ul.__H||(ul.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Sl(e){return fl=1,function(e,t){var n=kl(al++,2);if(n.t=e,!n.__c&&(n.__=[Tl(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=ul,!ul.__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};ul.__f=!0;var s=ul.shouldComponentUpdate,i=ul.componentWillUpdate;ul.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)},ul.shouldComponentUpdate=r}return n.__N||n.__}(Tl,e)}function xl(e,t){var n=kl(al++,4);!gl.__s&&jl(n.__H,t)&&(n.__=e,n.u=t,ul.__h.push(n))}function El(e){return fl=5,function(e,t){var n=kl(al++,7);return jl(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}(function(){return{current:e}},[])}function Cl(){for(var e;e=pl.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Ol),e.__H.__h.forEach(Dl),e.__H.__h=[]}catch(t){e.__H.__h=[],gl.__e(t,e.__v)}}gl.__b=function(e){ul=null,yl&&yl(e)},gl.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),_l&&_l(e,t)},gl.__r=function(e){ml&&ml(e),al=0;var t=(ul=e.__c).__H;t&&(dl===ul?(t.__h=[],ul.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.forEach(Ol),t.__h.forEach(Dl),t.__h=[],al=0)),dl=ul},gl.diffed=function(e){bl&&bl(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==pl.push(t)&&hl===gl.requestAnimationFrame||((hl=gl.requestAnimationFrame)||Il)(Cl)),t.__H.__.forEach(function(e){e.u&&(e.__H=e.u),e.u=void 0})),dl=ul=null},gl.__c=function(e,t){t.some(function(e){try{e.__h.forEach(Ol),e.__h=e.__h.filter(function(e){return!e.__||Dl(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],gl.__e(n,e.__v)}}),vl&&vl(e,t)},gl.unmount=function(e){wl&&wl(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(e){try{Ol(e)}catch(e){t=e}}),n.__H=void 0,t&&gl.__e(t,n.__v))};var Al="function"==typeof requestAnimationFrame;function Il(e){var t,n=function(){clearTimeout(r),Al&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Al&&(t=requestAnimationFrame(n))}function Ol(e){var t=ul,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),ul=t}function Dl(e){var t=ul;e.__c=e.__(),ul=t}function jl(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Tl(e,t){return"function"==typeof t?t(e):t}function Ul({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,e=>n[e.substring(1,e.length-1)])}function Pl({option:e,onClick:t}){const{displayName:n,iconUrl:r,styleHint:s}=e,i=function(e){const t=Object.assign({},cl.ProviderButton);if(!e)return t;switch(e){case"google":return Object.assign(Object.assign({},t),cl.ProviderGoogle);case"github":return Object.assign(Object.assign({},t),cl.ProviderGitHub);case"microsoft":return Object.assign(Object.assign({},t),cl.ProviderMicrosoft);case"apple":return Object.assign(Object.assign({},t),cl.ProviderApple);case"otp":return Object.assign({},cl.OtpButton);case"custom-oauth2":return Object.assign(Object.assign({},t),cl.ProviderCustom);default:return t}}(s);return Mc("button",{type:"button",style:i,onClick:t,class:"dxc-option-btn"+(s?` dxc-option-${s}`:""),"aria-label":n},r&&Mc("img",{src:r,alt:"",style:cl.ProviderButtonIcon,"aria-hidden":"true"}),Mc("span",{style:cl.ProviderButtonText},n))}function Ll(){return Mc("div",{style:cl.Divider},Mc("div",{style:cl.DividerLine}),Mc("span",{style:cl.DividerText},"or"),Mc("div",{style:cl.DividerLine}))}function Rl({title:e,alerts:t,fields:n,options:r,submitLabel:s,cancelLabel:i,onCancel:o,onSubmit:c}){const[l,a]=Sl({}),u=El(null);xl(()=>{var e;return null===(e=u.current)||void 0===e?void 0:e.focus()},[]);const d=Object.entries(n||{}),h=d.length>0,f=r&&r.length>0,p=new Map;if(r)for(const e of r){const t=p.get(e.name)||[];t.push(e),p.set(e.name,t)}const g=p.size>1,y=e=>{c({[e.name]:e.value})};return Mc(ll,{className:"dxc-login-dlg"},Mc(Nc,null,Mc("h3",{style:cl.WindowHeader},e),t.map((e,t)=>Mc("div",{key:t},Mc("p",{style:cl.Alert[e.type]},Ul(e)),e.copyText&&Mc($l,{text:e.copyText}))),f&&Mc("div",{class:"dxc-options"},g?Array.from(p.entries()).map(([e,t],n)=>Mc(Nc,{key:e},n>0&&Mc(Ll,null),t.map(e=>Mc(Pl,{key:`${e.name}-${e.value}`,option:e,onClick:()=>y(e)})))):r.map(e=>Mc(Pl,{key:`${e.name}-${e.value}`,option:e,onClick:()=>y(e)}))),f&&h&&Mc(Ll,null),h&&Mc("form",{onSubmit:e=>{e.preventDefault(),c(l)}},d.map(([e,{type:t,label:n,placeholder:r}],s)=>Mc("label",{style:cl.Label,key:s},n?`${n}: `:"",Mc("input",{ref:0===s?u:void 0,type:t,name:e,autoComplete:"on",style:cl.Input,autoFocus:!0,placeholder:r,value:l[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({},l),{[e]:s});a(i),"otp"===t&&8===(null==s?void 0:s.trim().length)&&c(i)}}))))),Mc("div",{style:cl.ButtonsDiv},Mc(Nc,null,s&&(h||!f&&!h)&&Mc("button",{type:"submit",style:cl.PrimaryButton,onClick:()=>c(l)},s),i&&Mc("button",{style:cl.Button,onClick:o},i))))}function $l({text:e}){const[t,n]=Sl(!1),r=El(null);xl(()=>()=>{null!==r.current&&clearTimeout(r.current)},[]);const s=()=>{null!==r.current&&clearTimeout(r.current),n(!0),r.current=setTimeout(()=>{r.current=null,n(!1)},2e3)};return Mc("button",{type:"button",style:t?cl.CopyButtonCopied:cl.CopyButton,onClick:()=>{var t;"undefined"!=typeof navigator&&(null===(t=navigator.clipboard)||void 0===t?void 0:t.writeText)?navigator.clipboard.writeText(e).then(s).catch(()=>{Ml(e,s)}):Ml(e,s)},title:"Copy to clipboard"},t?"✓ Copied!":`📋 ${e}`)}function Ml(e,t){const n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select();const r=document.execCommand("copy");document.body.removeChild(n),r&&t()}class Bl extends Fc{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?Mc(Rl,Object.assign({},t)):null}}function Nl(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const Fl=Nl(e=>new n.BehaviorSubject(Object.assign(Object.assign({},Ot),{isLoading:!0})));function Wl(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 zl=Nl(e=>Wl(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})),{})),Kl=Nl(e=>Wl(Fl(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 Vl(...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 Hl=Nl(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}(Wl(n.combineLatest([Kl(e._novip),zl(e._novip)]).pipe(r.map(([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r}))),{selfMembers:[],realms:[],userId:Ot.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=en(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:"*"}:Vl(...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 Jl{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 ql=Nl(e=>{const i=Fl(e._novip).pipe(r.switchMap(n=>t.liveQuery(()=>e.members.where({email:n.email||""}).toArray()))),o=Hl(e._novip),c=Kl(e._novip);return Wl(n.combineLatest([i,c,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,{}),c=n.selfMembers.reduce(i,o);return Object.values(c).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 Yl(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:c}=o.meta||{};if(!(null===(i=e.cloud.schema)||void 0===i?void 0:i[c].markedForSync))return;let l;Object.defineProperty(r,"awareness",{get:()=>l||(l=function(e,r,i){const{parentTable:o,parentId:c,parentProp:l,updatesTable:a}=r.meta,u=new cc(r),d=uc(r);return u.on("update",({added:t,updated:n,removed:s},c)=>{const a=t.concat(n).concat(s),d=e.cloud.currentUser.value;if("server"!==c&&d.isLoggedIn&&!Vo(e)){const t=((e,t,n=e.states)=>{const r=t.length,s=fe();me(s,r);for(let i=0;i<r;i++){const r=t[i],o=n.get(r)||null,c=e.meta.get(r).clock;me(s,r),me(s,c),_e(s,JSON.stringify(o))}return pe(s)})(u,a);e.messageProducer.next({type:"aware",table:o,prop:l,k:r.meta.parentId,u:t}),i.destroyed&&e.messageProducer.next({type:"doc-close",table:o,prop:l,k:r.meta.parentId})}}),u.on("destroy",()=>{lc(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(_n),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:l,k:c,serverRev:p},y=yield d.where("i").between(f,1/0,!1).filter(e=>0===t.cmp(e.k,c)&&!(1&(e.f||0))).toArray();if(!i.destroyed&&u===n&&r){if(y.length>0){const e=us(y.map(e=>e.u)),t=ls(e);g.sv=t}e.messageProducer.next(g)}})}i.addCleanupHandler(h)})})(),u}(e,o,r),ic.set(o,l),l)})}}function Gl(e){const t="undefined"!=typeof window?window.location.href:"";if(!t)return null;const n=new URL(t).searchParams.get("dxc-auth");if(!n)return null;let r;try{const e=function(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/");return atob(t)}(n);r=JSON.parse(e)}catch(e){return null}const{code:s,provider:i,state:o,error:c}=r;if(c){if(c.toLowerCase().includes("access_denied")||c.toLowerCase().includes("access denied"))throw new Lt("access_denied",i,c);if(c.toLowerCase().includes("email")&&c.toLowerCase().includes("verif"))throw new Lt("email_not_verified",i,c);throw new Lt("provider_error",i,c)}return s&&i&&o?{code:s,provider:i,state:o}:null}function Ql(){var e;if("undefined"==typeof window||!(null===(e=window.history)||void 0===e?void 0:e.replaceState))return;const t=new URL(window.location.href);if(!t.searchParams.has("dxc-auth"))return;t.searchParams.delete("dxc-auth");const n=t.pathname+(t.searchParams.toString()?`?${t.searchParams.toString()}`:"")+t.hash;window.history.replaceState(null,"",n)}const Xl={},Zl=new WeakMap,ea=na("tx"),ta=na("unload");function na(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=Zi.getOrCreateDocument(t,s,i,n);try{const t=Zi.load(e);yield t.whenLoaded;for(const t of r)yield t(e,n)}catch(e){null==e||e.name}finally{Zi.release(e)}}})}(e).finally(()=>{t=null})},0))})},enqueue(e,t,n,s,i){const o=`${e.name}:${t}:${n}:${s}`;let c=r.get(o);c||(c={db:e,parentTable:t,parentId:n,prop:s,triggers:new Set},r.set(o,c)),c.triggers.add(i)}}}function ra(){ea.run()}function sa(){ta.run()}const ia={nameSuffix:!0};function oa(e){const i=e.name,o=Fl(e),c=[];let l=!1,a=null,u=null,d=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,y,m,b,v,w,_,k,S;h=!1;const x=Eo(e);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(i=x.cloud.options)||void 0===i?void 0:i.customLoginGui)||c.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),ol(Mc(Bl,{db:e.vip}),n)):addEventListener("DOMContentLoaded",()=>{t||(document.body.appendChild(n),ol(Mc(Bl,{db:e.vip}),n))}),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(e))),x.cloud.isServiceWorkerDB||c.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 Xo.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"})),Fl(e.dx._novip),Zo]).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:c,progress:l}=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:c,progress:l,status:gn?a:"offline",license:"ok"}}))}(x).subscribe(e.cloud.syncState)),c.push(x.syncCompleteEvent.subscribe(p));if("eager"===(null!==(m=null===(y=x.cloud.options)||void 0===y?void 0:y.blobMode)&&void 0!==m?m:"eager")){let e=null;const n=()=>{e||(e=t.ignoreTransaction(()=>function(e,n,r){return s(this,void 0,void 0,function*(){var i;const o=e=>{},c=ot(e);let l=!1;for(const e of c)try{if(!e.schema.idxByName._hasBlobRefs)continue;if((yield e.where("_hasBlobRefs").equals(1).count())>0){l=!0;break}}catch(e){}if(l){ct(n,!0);try{c.length,c.map(e=>e.name).join(", ");for(const n of c){null==r||r.aborted;try{if(!n.schema.indexes.some(e=>"_hasBlobRefs"===e.name))continue;const c=yield n.where("_hasBlobRefs").equals(1).toArray();o((n.name,c.length));const l=null===(i=e.cloud.options)||void 0===i?void 0:i.databaseUrl;if(!l)throw new Error("Database URL is required to download blobs");const a=6,u=n.schema.primKey,d=c.filter(e=>!!it(e)&&void 0!==(u.keyPath?t.getByKeyPath(e,u.keyPath):void 0));let h=0;const f=()=>s(this,void 0,void 0,function*(){for(;h<d.length;){null==r||r.aborted;const s=d[h++],i=t.getByKeyPath(s,u.keyPath);try{const t=[];yield st(s,l,t,"",new WeakMap,e.blobDownloadTracker);const r={_hasBlobRefs:void 0};for(const e of t)r[e.keyPath]=e.data;o((n.name,t.length)),yield n.update(i,r)}catch(e){}}}),p=[];for(let e=0;e<Math.min(a,d.length);e++)p.push(f());yield Promise.all(p)}catch(e){}}}finally{ct(n,!1)}}})}(x,g)).catch(e=>{}).finally(()=>{e=null}))};setTimeout(n,0),c.push(x.syncCompleteEvent.subscribe(n))}x.tables.every(e=>e.core)||function(){throw new t.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const E="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[C,A]=yield x.transaction("rw",x.$syncState,()=>s(this,void 0,void 0,function*(){var e,t;const{options:n,schema:r}=x.cloud,[s,i,o]=yield Promise.all([x.getOptions(),x.getSchema(),x.getPersistedSyncState()]);if(l){if(!s||JSON.stringify(s)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,delete e.awarenessProtocol,yield x.$syncState.put(e,"options")}}else x.cloud.options=s||null;if((null===(e=x.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&E.length>0&&!Do?x.cloud.usingServiceWorker=!0:((null===(t=x.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&x.cloud.isServiceWorkerDB,x.cloud.usingServiceWorker=!1),wc(r,x.cloud.options),wc(i,x.cloud.options),r){if(!i||JSON.stringify(i)!==JSON.stringify(r)){const e=i||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]=Object.assign({},n)}yield x.$syncState.put(e,"schema"),Object.assign(r,e)}}else x.cloud.schema=i||null;return[null==o?void 0:o.initiallySynced,null==o?void 0:o.realms]}));if(C&&x.setInitiallySynced(!0),function(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`)}}(x),f(),!x.cloud.isServiceWorkerDB){c.push(t.liveQuery(()=>x.getCurrentUser().then(e=>!e.isLoggedIn&&"undefined"!=typeof location&&/dxc-auth\=/.test(location.search)?Object.assign(Object.assign({},e),{isLoading:!0}):e)).subscribe(o)),c.push(t.liveQuery(()=>x.getPersistedSyncState()).subscribe(x.cloud.persistedSyncState)),yield n.firstValueFrom(n.combineLatest([o.pipe(r.skip(1),r.take(1)),x.cloud.persistedSyncState.pipe(r.skip(1),r.take(1))]));const e=Yl(x);Zi.on.new.subscribe(e),x.dx.once("close",()=>{Zi.on.new.unsubscribe(e)})}let I=!1,O=yield x.getCurrentUser();if(u&&!x.cloud.isServiceWorkerDB){const e=u;u=null;try{yield mt(x.cloud.userInteraction,"Authentication Error",{type:"error",messageCode:"GENERIC_ERROR",message:e.message,messageParams:{provider:e.provider||"unknown"}}),Ql()}catch(e){}}if(a&&!x.cloud.isServiceWorkerDB){const{code:e,provider:t}=a;a=null;try{I=yield Kt(x,{oauthCode:e,provider:t}),O=yield x.getCurrentUser(),Ql()}catch(e){}}const D=null===(b=x.cloud.options)||void 0===b?void 0:b.requireAuth;D&&(x.cloud.isServiceWorkerDB?yield n.firstValueFrom(o.pipe(r.filter(e=>!!e.isLoggedIn),r.take(1))):"object"==typeof D?(!O.isLoggedIn||D.userId&&O.userId!==D.userId||D.email&&O.email!==D.email)&&(I=yield Kt(x,D)):O.isLoggedIn||(I=yield Kt(x))),!O.isLoggedIn||A&&A.includes(O.userId)||(I=!0),d&&d.stop(),d=null,f();const j=(null===(v=x.cloud.options)||void 0===v?void 0:v.databaseUrl)&&(!C||I);j&&(yield function(e,t,n){return s(this,void 0,void 0,function*(){yield Qo(e,yo,()=>mo(e,t,n,{isInitialSync:!0}))})}(x,x.cloud.options,x.cloud.schema),x.setInitiallySynced(!0)),f(),x.cloud.usingServiceWorker&&(null===(w=x.cloud.options)||void 0===w?void 0:w.databaseUrl)?(j||dt(x,"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){}})}(x).catch(()=>{})):(null===(_=x.cloud.options)||void 0===_?void 0:_.databaseUrl)&&x.cloud.schema&&!x.cloud.isServiceWorkerDB&&(d=vc(x,x.cloud.options,x.cloud.schema),d.start(),j||ht(x,"push")),f(),x.cloud.isServiceWorkerDB||c.push(n.fromEvent(self,"online").subscribe(()=>{x.syncStateChangedEvent.next({phase:"not-in-sync"}),Vo(x)||ht(x,"push")}),n.fromEvent(self,"offline").subscribe(()=>{x.syncStateChangedEvent.next({phase:"offline"})})),!(null===(k=x.cloud.options)||void 0===k?void 0:k.databaseUrl)||(null===(S=x.cloud.options)||void 0===S?void 0:S.disableWebSocket)||jo||c.push(function(e){var t;if(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl))throw new Error("No database URL to connect WebSocket to");const i=e.messageConsumer.readyToServe.pipe(r.filter(e=>e),r.switchMap(()=>e.cloud.persistedSyncState.pipe(r.filter(e=>!(!e||!e.serverRevision)),r.take(1))),r.switchMap(e=>s(this,void 0,void 0,function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield Gt(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])=>Zo.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 Gt(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 dc(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 Ct(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 pc?n.throwError(()=>s):n.from(gc()).pipe(r.switchMap(()=>t())))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(x))})}(e)}catch(e){}}),!0);let h=!1;function f(){if(h)throw new t.DatabaseClosedError}e.once("close",()=>{c.forEach(e=>e.unsubscribe()),c.splice(0,c.length),h=!0,d&&d.stop(),d=null,o.next(Ot)});const p=new n.Subject,g=new n.BehaviorSubject(!1);var y;e.cloud={version:"4.4.6",options:Object.assign({},ia),schema:null,get currentUserId(){return o.value.userId||Ot.userId},currentUser:o,syncState:new n.BehaviorSubject({phase:"initial",status:"not-started"}),events:{syncComplete:p},persistedSyncState:new n.BehaviorSubject(void 0),blobProgress:lt(Eo(e),g),userInteraction:new n.BehaviorSubject(void 0),webSocketStatus:new n.BehaviorSubject("not-started"),login(t){return s(this,void 0,void 0,function*(){const n=Eo(e);yield n.cloud.sync(),yield Kt(n,t)})},invites:ql(e),roles:zl(e),configure(t){if(void 0!==t.maxStringLength&&t.maxStringLength!==1/0&&(!Number.isFinite(t.maxStringLength)||t.maxStringLength<100||t.maxStringLength>32768))throw new Error(`maxStringLength must be Infinity or a finite number in [100, 32768]. Got: ${t.maxStringLength}`);if(t=e.cloud.options=Object.assign(Object.assign({},e.cloud.options),t),l=!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)}`,Eo(e).reconfigure()),wc(e.cloud.schema,e.cloud.options),"undefined"!=typeof window&&window.location)try{const e=Gl();e&&(a={code:e.code,provider:e.provider})}catch(e){e instanceof Lt&&(u=e)}},logout(){return s(this,arguments,void 0,function*({force:t}={}){t?yield Tt(Eo(e),{deleteUnsyncedData:!0}):yield jt(Eo(e))})},getAuthProviders(){return s(this,void 0,void 0,function*(){const t=e.cloud.options;if(!(null==t?void 0:t.databaseUrl))throw new Error("Dexie Cloud not configured. Call db.cloud.configure() first.");const n=!1!==t.socialAuth;return $t(t.databaseUrl,n)})},sync(){return s(this,arguments,void 0,function*({wait:i,purpose:o}={wait:!0,purpose:"push"}){var c;void 0===i&&(i=!0);const l=Eo(e);if("ok"!==((null===(c=l.cloud.currentUser.value.license)||void 0===c?void 0:c.status)||"ok")&&(yield xt(l)),"pull"===o){const e=l.cloud.persistedSyncState.value;if(ht(l,o),i){const t=yield n.firstValueFrom(l.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 yc(l)){const e=l.cloud.persistedSyncState.value;ht(l,o),i&&(yield n.firstValueFrom(n.from(t.liveQuery(()=>s(this,void 0,void 0,function*(){const t=yield yc(l),n=yield l.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=Hl(e),c=t=>{const r=t[i||e.cloud.currentUserId];return r?new Jl(r.permissions,n,void 0===i||i===e.cloud.currentUserId||s===e.cloud.currentUserId):new Jl({},n,!s||s===e.cloud.currentUserId)},l=o.pipe(r.map(c));return l.getValue=()=>c(o.getValue()),l}(e._novip,t,n)},e.Version.prototype._parseStoresSpec=t.override(e.Version.prototype._parseStoresSpec,t=>Go(t,e)),e.Table.prototype.newId=function({colocateWith:t}={}){const n=t&&t.substr(t.length-3);return Bo(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(qo(Eo(e))),e.use(Ho({currentUserObservable:e.cloud.currentUser,db:Eo(e)})),e.use((y=Eo(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,c,l;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:Ot.userId;if((null===(o=null===(i=y.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===(l=(c=n.schema.primaryKey).extractKey)||void 0===l?void 0:l.call(c,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(Eo(e)))}oa.version="4.4.6",t.Cloud=oa,e.default=oa,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}`);Xl[o]={trigger:r,parentTable:e.name,prop:n};const c=e.db._novip;let l=Zl.get(c);l||(l=(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=>Xl[e])?(s.addEventListener("complete",ra),s):s},table:r=>{const s=n.table(r),i=Xl[r];if(!i)return s;const{trigger:o,parentTable:c,prop:l}=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=Zi.getDocCache(e).find(c,n,l);(s&&(null===(r=Zi.for(s))||void 0===r?void 0:r.refCount)?ta:ea).enqueue(e,c,n,l,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)ea.enqueue(e,c,t.from,l,o)})}return s.mutate(n)}})}})}))(c),Zl.set(c,l)),c.use(l),Zi.on("beforeunload",sa)},e.dexieCloud=oa,e.getTiedObjectId=function(e){return e.startsWith("rlm~")?e.substr(4):null},e.getTiedRealmId=function(e){return"rlm~"+e},e.resolveText=Ul,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{l(r.next(e))}catch(e){i(e)}}function c(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,c)}l((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 c(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),c("next"),c("throw"),c("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),r[Symbol.asyncIterator]=function(){return this},r;function c(e,t){s[e]&&(r[e]=function(t){return new Promise(function(n,r){i.push([e,t,n,r])>1||l(e,t)})},t&&(r[e]=t(r[e])))}function l(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){l("next",e)}function u(e){l("throw",e)}function d(e,t){e(t),i.shift(),i.length&&l(i[0][0],i[0][1])}}function l(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=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{toString:a}={};const u={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}};class d{constructor(e,t){this.buf=e,this.type=t}}var h;const f=Symbol.for("TSONRef");class p{constructor(e,t,n,r){this.type=e,this.ref=t,this.size=n,this.contentType=r,this[h]=!0,Object.freeze(this)}async resolve(){if(!p.resolver)throw new Error("TSONRef.resolver not configured. Set TSONRef.resolver to a function that fetches blobs.");const e=await p.resolver(this);return this.reconstruct(e)}reconstruct(e){const t=(t,n)=>{if(e.byteLength%t!==0)throw new RangeError(`Buffer length ${e.byteLength} is not aligned to ${t} bytes for ${n}`)};switch(this.type){case"ArrayBuffer":default:return e;case"Uint8Array":return new Uint8Array(e);case"Blob":return new Blob([e],{type:this.contentType});case"Int8Array":return new Int8Array(e);case"Uint8ClampedArray":return new Uint8ClampedArray(e);case"Int16Array":return t(2,"Int16Array"),new Int16Array(e);case"Uint16Array":return t(2,"Uint16Array"),new Uint16Array(e);case"Int32Array":return t(4,"Int32Array"),new Int32Array(e);case"Uint32Array":return t(4,"Uint32Array"),new Uint32Array(e);case"Float32Array":return t(4,"Float32Array"),new Float32Array(e);case"Float64Array":return t(8,"Float64Array"),new Float64Array(e);case"BigInt64Array":return t(8,"BigInt64Array"),new BigInt64Array(e);case"BigUint64Array":return t(8,"BigUint64Array"),new BigUint64Array(e)}}static isTSONRef(e){return null!==e&&"object"==typeof e&&f in e&&!0===e[f]}static isTSONRefData(e){return null!==e&&"object"==typeof e&&"$ref"in e&&"$t"in e&&"$size"in e}static fromData(e){return new p(e.$t,e.$ref,e.$size,e.$ct)}toJSON(){const e={$t:this.type,$ref:this.ref,$size:this.size};return this.contentType&&(e.$ct=this.contentType),e}}function g(e){const t=new XMLHttpRequest;t.overrideMimeType("text/plain; charset=x-user-defined");const n=URL.createObjectURL(e);try{if(t.open("GET",n,!1),t.send(),200!==t.status&&0!==t.status)throw new Error("Bad Blob access: "+t.status);return t.responseText}finally{URL.revokeObjectURL(n)}}h=f,p.TYPE_SYMBOL=f,p.resolver=null;const y={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)}},m={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},b={Set:{replace:e=>({$t:"Set",v:Array.from(e)}),revive:({v:e})=>new Set(e)}},v={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}},w="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0,_=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce((e,t)=>({...e,[t]:{replace:(e,n,r)=>{const s=e.buffer,i=0===e.byteOffset&&e.byteLength===s.byteLength?s:s.slice(e.byteOffset,e.byteOffset+e.byteLength);return{$t:t,v:r.ArrayBuffer.replace(i,n,r).v}},revive:({v:e},n,r)=>{const s=w[t];return s&&new s(r.ArrayBuffer.revive({v:e},n,r))}}}),{}),k="fromBase64"in Uint8Array,S="toBase64"in Uint8Array.prototype,x="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):k?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},E="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):S?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,Array.from(r)))}return btoa(n.join(""))};function C(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=O[e[n]];return t}(E(e))}function A(e){return x(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+=I[e[n]];return t}(e))}const I={"-":"=",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:"+","|":"/"},O={};for(const e of Object.keys(I))O[I[e]]=e;const D={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:C(e)}),revive:({v:e})=>{const t=A(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};function j(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}const T={Blob:{test:(e,t)=>"Blob"===t||e instanceof d,replace:e=>({$t:"Blob",v:E(e instanceof d?e.buf:j(g(e))),type:e.type}),revive:({type:e,v:t})=>{const n=x(t),r=n.buffer.byteLength===n.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);return"undefined"!=typeof Blob?new Blob([new Uint8Array(r)],{type:e}):new d(r,e)}}},U={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:E(j(g(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const s=x(t),i=s.buffer.byteLength===s.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);return new File([new Uint8Array(i)],n,{type:e,lastModified:new Date(r).getTime()})}}},P={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},L="undefined"!=typeof crypto?crypto.getRandomValues.bind(crypto):e=>{for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())};let R=0;const $={}.hasOwnProperty;function M(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)M(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var o=t.substr(0,i),c=t.substr(i+1);if(""===c)void 0===n?Array.isArray(e)?isNaN(parseInt(o))||e.splice(parseInt(o),1):delete e[o]:e[o]=n;else{var l=e[o];l&&function(e,t){return $.call(e,t)}(e,o)||(l=e[o]={}),M(l,c,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const B="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=N)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function N(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(W))}function W(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(W)}function z(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))M(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 K(e,t){for(const{table:n,muts:r}of t)for(const t of r)z(e,n,t)}const V=Math.floor,H=Math.abs,J=(e,t)=>e<t?e:t,q=(e,t)=>e>t?e:t,Y=e=>0!==e?e<0:1/e<0,G=64,Q=128,X=127,Z=Number.MAX_SAFE_INTEGER,ee=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&V(e)===e),te=()=>new Set,ne=e=>e[e.length-1],re=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},se=Array.from,ie=Array.isArray,oe=/^\s*/g,ce=/([A-Z])/g,le=(e,t)=>(e=>e.replace(oe,""))(e.replace(ce,e=>`${t}${(e=>e.toLowerCase())(e)}`)),ae="undefined"!=typeof TextEncoder?new TextEncoder:null,ue=ae?e=>ae.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 de="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});de&&1===de.decode(new Uint8Array).length&&(de=null);class he{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const fe=()=>new he,pe=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},ge=(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},ye=ge,me=(e,t)=>{for(;t>X;)ge(e,Q|X&t),t=V(t/128);ge(e,X&t)},be=(e,t)=>{const n=Y(t);for(n&&(t=-t),ge(e,(t>63?Q:0)|(n?G:0)|63&t),t=V(t/64);t>0;)ge(e,(t>X?Q:0)|X&t),t=V(t/128)},ve=new Uint8Array(3e4),we=ve.length/3,_e=ae&&ae.encodeInto?(e,t)=>{if(t.length<we){const n=ae.encodeInto(t,ve).written||0;me(e,n);for(let t=0;t<n;t++)ge(e,ve[t])}else Se(e,ue(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;me(e,r);for(let t=0;t<r;t++)ge(e,n.codePointAt(t))},ke=(e,t)=>{const n=e.cbuf.length,r=e.cpos,s=J(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(q(2*n,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)},Se=(e,t)=>{me(e,t.byteLength),ke(e,t)},xe=(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*q(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Ee=(e,t)=>xe(e,8).setBigUint64(0,t,!1),Ce=new DataView(new ArrayBuffer(4)),Ae=(e,t)=>{switch(typeof t){case"string":ge(e,119),_e(e,t);break;case"number":ee(t)&&H(t)<=2147483647?(ge(e,125),be(e,t)):(n=t,Ce.setFloat32(0,n),Ce.getFloat32(0)===n?(ge(e,124),((e,t)=>{xe(e,4).setFloat32(0,t,!1)})(e,t)):(ge(e,123),((e,t)=>{xe(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":ge(e,122),((e,t)=>{xe(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)ge(e,126);else if(ie(t)){ge(e,117),me(e,t.length);for(let n=0;n<t.length;n++)Ae(e,t[n])}else if(t instanceof Uint8Array)ge(e,116),Se(e,t);else{ge(e,118);const n=Object.keys(t);me(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];_e(e,s),Ae(e,t[s])}}break;case"boolean":ge(e,t?120:121);break;default:ge(e,127)}var n};class Ie extends he{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&me(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Oe=e=>{e.count>0&&(be(e.encoder,1===e.count?e.s:-e.s),e.count>1&&me(e.encoder,e.count-2))};class De{constructor(){this.encoder=new he,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Oe(this),this.count=1,this.s=e)}toUint8Array(){return Oe(this),pe(this.encoder)}}const je=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);be(e.encoder,t),e.count>1&&me(e.encoder,e.count-2)}};class Te{constructor(){this.encoder=new he,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(je(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return je(this),pe(this.encoder)}}class Ue{constructor(){this.sarr=[],this.s="",this.lensE=new De}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 he;return this.sarr.push(this.s),this.s="",_e(e,this.sarr.join("")),ke(e,this.lensE.toUint8Array()),pe(e)}}const Pe=e=>new Error(e),Le=()=>{throw Pe("Method unimplemented")},Re=()=>{throw Pe("Unexpected case")},$e=Pe("Unexpected end of array"),Me=Pe("Integer out of Range");class Be{constructor(e){this.arr=e,this.pos=0}}const Ne=e=>new Be(e),Fe=e=>e.pos!==e.arr.length,We=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,Ke(e)),ze=e=>e.arr[e.pos++],Ke=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<Q)return t;if(t>Z)throw Me}throw $e},Ve=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const s=(t&G)>0?-1:1;if(0===(t&Q))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<Q)return s*n;if(n>Z)throw Me}throw $e},He=de?e=>de.decode(We(e)):e=>{let t=Ke(e);if(0===t)return"";{let n=String.fromCodePoint(ze(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(ze(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))}},Je=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},qe=e=>Je(e,8).getBigUint64(0,!1),Ye=[e=>{},e=>null,Ve,e=>Je(e,4).getFloat32(0,!1),e=>Je(e,8).getFloat64(0,!1),e=>Je(e,8).getBigInt64(0,!1),e=>!1,e=>!0,He,e=>{const t=Ke(e),n={};for(let r=0;r<t;r++){n[He(e)]=Ge(e)}return n},e=>{const t=Ke(e),n=[];for(let r=0;r<t;r++)n.push(Ge(e));return n},We],Ge=e=>Ye[127-ze(e)](e);class Qe extends Be{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=Ke(this)+1:this.count=-1),this.count--,this.s}}class Xe extends Be{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=Ve(this);const e=Y(this.s);this.count=1,e&&(this.s=-this.s,this.count=Ke(this)+2)}return this.count--,this.s}}class Ze extends Be{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=Ve(this),t=1&e;this.diff=V(e/2),this.count=1,t&&(this.count=Ke(this)+2)}return this.s+=this.diff,this.count--,this.s}}class et{constructor(e){this.decoder=new Xe(e),this.str=He(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*tt(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 c=0;for(;c<o.byteLength;)switch(t){case 0:if(c+4>o.byteLength){for(const e of o.slice(c)){if(4===r)break;n[r++]=e,++c}if(r<4)break}else if(r>0&&r<4)for(const e of o.slice(c,c+4-r))n[r++]=e,++c;case 1:i=4===r?new DataView(n.buffer,0,4).getUint32(0,!1):e.getUint32(c,!1),r?r=0:c+=4;case 2:if(c>=o.byteLength){t=2;break}if(c+i>o.byteLength)s.push(o.slice(c)),i-=o.byteLength-c,t=2,c=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(c,c+i),t),s=[],yield e}else yield o.slice(c,c+i);c+=i,t=0}}}}function nt(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t._bt&&"string"==typeof t.ref&&void 0===t.v}function rt(e,t=new WeakSet){return null!=e&&(!!nt(e)||"object"==typeof e&&(!t.has(e)&&(t.add(e),!(e instanceof Date||e instanceof RegExp||e instanceof Blob)&&(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(Array.isArray(e)?e.some(e=>rt(e,t)):e.constructor===Object&&Object.values(e).some(e=>rt(e,t)))))))}function st(e,t){return s(this,arguments,void 0,function*(e,t,n=[],r="",s=new WeakMap,i){if(null==e)return e;if(nt(e)){const s=function(e,t){if("string"===t._bt)return(new TextDecoder).decode(e);const n=e.buffer.byteLength===e.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);switch(t._bt){case"Blob":return new Blob([new Uint8Array(n)],{type:t.ct||""});case"ArrayBuffer":return n;case"Uint8Array":default:return e;case"Int8Array":return new Int8Array(n);case"Uint8ClampedArray":return new Uint8ClampedArray(n);case"Int16Array":return new Int16Array(n);case"Uint16Array":return new Uint16Array(n);case"Int32Array":return new Int32Array(n);case"Uint32Array":return new Uint32Array(n);case"Float32Array":return new Float32Array(n);case"Float64Array":return new Float64Array(n);case"BigInt64Array":return new BigInt64Array(n);case"BigUint64Array":return new BigUint64Array(n);case"DataView":return new DataView(n)}}(yield i.download(e,t),e);return n.push({keyPath:r,data:s,ref:e.ref}),s}if(Array.isArray(e)){if(s.has(e))return s.get(e);const o=[];s.set(e,o);for(let c=0;c<e.length;c++){const l=r?`${r}.${c}`:`${c}`;o.push(yield st(e[c],t,n,l,s,i))}return o}if("object"==typeof e&&e.constructor===Object){if(s.has(e))return s.get(e);const o={};s.set(e,o);for(const[c,l]of Object.entries(e)){if("_hasBlobRefs"===c)continue;const e=r?`${r}.${c}`:c;o[c]=yield st(l,t,n,e,s,i)}return o}return e})}function it(e){return"object"==typeof e&&null!==e&&1===e._hasBlobRefs}function ot(e){return Object.entries(e.cloud.schema||{}).filter(([,{markedForSync:e}])=>e).map(([t])=>e.tables.find(({name:e})=>e===t)).filter(e=>!!e)}function ct(e,t){e.value!==t&&e.next(t)}function lt(e,i){const o=n.from(t.liveQuery(()=>s(this,void 0,void 0,function*(){let t=0,n=0;const r=ot(e);return yield e.dx.transaction("r",r,e=>s(this,void 0,void 0,function*(){e.idbtrans.disableBlobResolve=!0;for(const e of r){if(!!!e.schema.idxByName._hasBlobRefs)continue;const r=yield e.where("_hasBlobRefs").equals(1).toArray();for(const e of r){const r=at(e);t+=r.length,n+=r.reduce((e,t)=>e+(t.size||0),0)}}})),{blobsRemaining:t,bytesRemaining:n}})));return n.combineLatest([o,i]).pipe(r.map(([e,t])=>({isDownloading:t&&e.blobsRemaining>0,blobsRemaining:e.blobsRemaining,bytesRemaining:e.bytesRemaining})),r.share({resetOnRefCountZero:()=>n.timer(2e3)}))}function at(e){const t=[];return function e(n){if(null!=n&&"object"==typeof n)if(p.isTSONRef(n))t.push({ref:n.ref,size:n.size});else{if(function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&"string"==typeof t.ref&&"number"==typeof t.size&&void 0===t._bt}(n)){const e=n;return void t.push({ref:e.ref,size:e.size})}nt(n)?t.push({ref:n.ref,size:n.size||0}):Array.isArray(n)?n.forEach(e):n.constructor===Object&&Object.values(n).forEach(e)}}(e),t}let ut=!1;function dt(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){ut||(ut=!0)}})}function ht(e,t){e.cloud.usingServiceWorker?dt(e,t):e.localSyncEvent.next({purpose:t})}class ft extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}const pt=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="#666666" stroke-width="2"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M22 6L12 13 2 6"/></svg>')}`;function gt(e){return{name:"provider",value:e.name,displayName:`Continue with ${e.displayName}`,iconUrl:e.iconUrl,styleHint:e.type}}function yt(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 mt(e,t,...n){return yt(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function bt(e,t,n,r){return s(this,void 0,void 0,function*(){let s=n||"",i=!0;for(;!s||!/^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$/.test(s);){const n=[];i&&r&&n.push(r),s&&n.push({type:"error",messageCode:"INVALID_EMAIL",message:"Please enter a valid email address",messageParams:{}}),i=!1,s=(yield yt(e,{type:"email",title:t,alerts:n,fields:{email:{type:"email",placeholder:"you@somedomain.com"}}})).email}return s})}function vt(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 yt(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return s})}class wt extends Error{constructor(e){super(`OAuth redirect initiated for provider: ${e}`),this.name="OAuthRedirectError",this.provider=e}}class _t extends Error{constructor(e){super(e.message),this.code=e.code}get name(){return"PolicyRejectionError"}}function kt(e){return"object"==typeof e&&null!==e&&"string"==typeof e.code&&"string"==typeof e.message}const St=1e3;function xt(e){return s(this,void 0,void 0,function*(){var t,n,r;const s=yield e.getCurrentUser(),{accessToken:i,accessTokenExpiration:o,refreshToken:c,refreshTokenExpiration:l,claims:a}=s;if(!i)return null;if((null!==(t=null==o?void 0:o.getTime())&&void 0!==t?t:1/0)>Date.now()+3e5&&"ok"===((null===(n=s.license)||void 0===n?void 0:n.status)||"ok"))return s;if(!c)throw new Error("Refresh token missing");if((null!==(r=null==l?void 0:l.getTime())&&void 0!==r?r:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield Ct(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 Et(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 Ct(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 c=function(e){const t=E(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:c,hints:i});if("error"===t.type)throw new ft(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 yt(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:t.alerts})),e}catch(e){if(e instanceof wt||"OAuthRedirectError"===(null==e?void 0:e.name))throw e;if(e instanceof _t||"PolicyRejectionError"===(null==e?void 0:e.name))throw e;if(e instanceof ft)throw yield mt(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){if("undefined"!=typeof navigator&&!navigator.onLine)n="You seem to be offline. Please connect to the internet and try again.";else if("undefined"==typeof location||!t.debug&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname)n="Could not connect to server. Please verify the connection.",yield mt(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch(()=>{});else{const e=`npx dexie-cloud whitelist ${location.origin}`;n=`Could not connect to server. Please verify that your origin '${location.origin}' is whitelisted using \`npx dexie-cloud whitelist\``,yield mt(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{},copyText:e}).catch(()=>{})}}throw e}})}(n,r,i,o)})}function Ct(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=E(i),c={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:o,signing_algorithm:r,time_stamp:n},l=yield fetch(`${e}/token`,{body:JSON.stringify(c),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==l.status)throw new Error(`RefreshToken: Status ${l.status} from ${e}/token`);const a=yield l.json();if("error"===a.type)throw new ft(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 At=new WeakMap;class It{constructor(e,t){At.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then(n=>new It(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)}))}save(){return s(this,void 0,void 0,function*(){At.get(this).table("$logins").put(this)})}}const Ot={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(Ot),Object.freeze(Ot.claims)}catch(h){}function Dt(e,t){return n.firstValueFrom(n.from(e).pipe(n.filter(t)))}function jt(e){return s(this,void 0,void 0,function*(){const t=yield Tt(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 yt(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 Tt(e,{deleteUnsyncedData:!0})}})}function Tt(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 Dt(e.cloud.currentUser,e=>e.userId===Ot.userId),yield e.cloud.sync({purpose:"pull",wait:!0})),n})}class Ut extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}const Pt={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 Lt extends Error{constructor(e,t,n){super(n||Pt[e]),this.name="OAuthError",this.code=e,this.provider=t}get userMessage(){return Pt[this.code]||this.message}}const Rt={providers:[],otpEnabled:!0};function $t(e){return s(this,arguments,void 0,function*(e,t=!0){if(!t)return Rt;try{const t=yield fetch(`${e}/auth-providers`,{method:"GET",headers:{Accept:"application/json"},mode:"cors"});return 404===t.status?Rt:t.ok?yield t.json():Rt}catch(e){return Rt}})}function Mt(e){if("undefined"==typeof window)throw new Error("OAuth redirect requires a browser environment");const t=function(e){const t=new URL(`${e.databaseUrl}/oauth/login/${e.provider}`),n=e.redirectUri||("undefined"!=typeof window?window.location.href:"");return n&&t.searchParams.set("redirect_uri",n),t.toString()}(e);window.location.href=t}function Bt(e){const{userInteraction:n}=e.cloud;function r(i,o){return s(this,arguments,void 0,function*({public_key:i,hints:o},c){var l,a;let u;const d=null===(l=e.cloud.options)||void 0===l?void 0:l.databaseUrl;if(!d)throw new Error("No database URL given.");const h=null==o?void 0:o.intent;if((null==o?void 0:o.oauthCode)&&o.provider)try{return yield function(e){return s(this,void 0,void 0,function*(){const{databaseUrl:t,code:n,publicKey:r,scopes:s=["ACCESS_DB"],intent:i}=e,o=Object.assign({grant_type:"authorization_code",code:n,public_key:r,scopes:s},void 0!==i?{intent:i}:{});try{const e=yield fetch(`${t}/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),mode:"cors"});if(!e.ok){const t=yield e.text().catch(()=>e.statusText);if(403===e.status)try{const e=JSON.parse(t);if(kt(e))throw new _t(e)}catch(e){if(e instanceof _t)throw e}if(400===e.status||401===e.status)try{const e=JSON.parse(t);if("error"===e.type){if("INVALID_OTP"===e.messageCode)throw new Lt("expired_code",void 0,e.message);throw new ft(e)}}catch(e){if(e instanceof Lt||e instanceof ft)throw e}throw new Lt("provider_error",void 0,`Token exchange failed: ${e.status} ${t}`)}const n=yield e.json();if("error"===n.type)throw new ft(n);if("tokens"!==n.type)throw new Lt("provider_error",void 0,`Unexpected response type: ${n.type}`);return n}catch(e){if(e instanceof Lt||e instanceof ft)throw e;if(e instanceof TypeError)throw new Lt("network_error");throw e}})}({databaseUrl:d,code:o.oauthCode,publicKey:i,scopes:["ACCESS_DB"],intent:h})}catch(e){if(e instanceof _t)return yield r({public_key:i,hints:void 0},Ft(e));throw e}if(null==o?void 0:o.provider){if(c)return yield r({public_key:i,hints:void 0},c);let t;throw o.redirectPath&&(/^https?:\/\//i.test(o.redirectPath)?t=o.redirectPath:"undefined"!=typeof window&&window.location?t=new URL(o.redirectPath,window.location.href).toString():"undefined"!=typeof location&&location.href&&(t=new URL(o.redirectPath,location.href).toString())),Nt(e,o.provider,t),new wt(o.provider)}if("demo"===(null==o?void 0:o.grant_type)){u={demo_user:yield bt(n,"Enter a demo user email",(null==o?void 0:o.email)||(null==o?void 0:o.userId),c),grant_type:"demo",scopes:["ACCESS_DB"],public_key:i}}else if((null==o?void 0:o.otpId)&&o.otp){if(c)return yield mt(n,"Access Denied",c),yield r({public_key:i,hints:void 0},c);u={grant_type:"otp",otp_id:o.otpId,otp:o.otp,scopes:["ACCESS_DB"],public_key:i}}else if("otp"===(null==o?void 0:o.grant_type)||(null==o?void 0:o.email)){const e=(null==o?void 0:o.email)||(yield bt(n,"Enter email address",void 0,c));u=/@demo.local$/.test(e)?{demo_user:e,grant_type:"demo",scopes:["ACCESS_DB"],public_key:i}:Object.assign({email:e,grant_type:"otp",scopes:["ACCESS_DB"]},void 0!==h?{intent:h}:{})}else{const r=!1!==(null===(a=e.cloud.options)||void 0===a?void 0:a.socialAuth),l=yield $t(d,r);if(l.providers.length>0){const r=c?[c]:[],i=yield function(e,n,r){return s(this,arguments,void 0,function*(e,n,r,s="Choose login method",i=[]){const o=[...n.map(gt)];return r&&o.push({name:"otp",value:"email",displayName:"Continue with email",iconUrl:pt,styleHint:"otp"}),new Promise((n,r)=>{const c={type:"generic",title:s,alerts:i,options:o,fields:{},submitLabel:"",cancelLabel:"Cancel",onSubmit:t=>{e.next(void 0),n("otp"in t?{type:"otp"}:"provider"in t?{type:"provider",provider:t.provider}:{type:"otp"})},onCancel:()=>{e.next(void 0),r(new t.AbortError("User cancelled"))}};e.next(c)})})}(n,l.providers,l.otpEnabled,"Sign in",r);if("provider"===i.type)throw Nt(e,i.provider),new wt(i.provider)}const f=yield bt(n,"Enter email address",null==o?void 0:o.email,0===l.providers.length?c:void 0);u=/@demo.local$/.test(f)?{demo_user:f,grant_type:"demo",scopes:["ACCESS_DB"],public_key:i}:Object.assign({email:f,grant_type:"otp",scopes:["ACCESS_DB"]},void 0!==h?{intent:h}:{})}const f=yield fetch(`${d}/token`,{body:JSON.stringify(u),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==f.status){const e=yield Wt(f);if(e)return yield r({public_key:i,hints:void 0},e);const t=yield f.text();throw yield mt(n,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:t,messageParams:{}}).catch(()=>{}),new Ut(f,t)}const p=yield f.json();if("tokens"===p.type||"error"===p.type)return p;if("otp"===u.grant_type&&"email"in u){if("otp-sent"!==p.type)throw new Error(`Unexpected response from ${d}/token`);const e=yield vt(n,u.email),t=Object.assign(Object.assign({},u),{otp:e||"",otp_id:p.otp_id,public_key:i});let s=yield fetch(`${d}/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 vt(n,u.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),s=yield fetch(`${d}/token`,{body:JSON.stringify(t),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==s.status){const e=yield Wt(s);if(e)return yield r({public_key:i,hints:void 0},e);const t=yield s.text();throw new Ut(s,t)}return yield s.json()}throw new Error(`Unexpected response from ${d}/token`)})}return({public_key:e,hints:t})=>r({public_key:e,hints:t})}function Nt(e,t,n){var r,s;const i=null===(r=e.cloud.options)||void 0===r?void 0:r.databaseUrl;if(!i)throw new Error("No database URL given.");Mt({databaseUrl:i,provider:t,redirectUri:n||(null===(s=e.cloud.options)||void 0===s?void 0:s.oauthRedirectUri)||("undefined"!=typeof location?location.href:void 0)})}function Ft(e){return{type:"error",messageCode:e.code,message:e.message,messageParams:{}}}function Wt(e){return s(this,void 0,void 0,function*(){if(403!==e.status)return null;try{const t=yield e.clone().json();if(kt(t))return Ft(new _t(t))}catch(e){}return null})}function zt(e,...t){globalThis.console[e](...t)}function Kt(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 xt(e),!1}const o=new It(e,{claims:{},lastLogin:new Date(0)});try{yield Et(e.cloud.options.databaseUrl,o,e.cloud.options.fetchTokens||Bt(e),e.cloud.userInteraction,t)}catch(e){if("OAuthRedirectError"===e.name)return!1;throw e}return i!==Ot.userId&&o.userId!==i&&(yield jt(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&&(zt("debug","Login context property names:",Object.keys(t)),zt("debug","Login context property names:",Object.keys(t)),zt("debug","Login context:",t),zt("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})),yield Dt(e.cloud.currentUser,e=>e.userId===t.userId)})}(e,o),ht(e,"pull"),o.userId!==i})}const Vt={},Ht="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;Ht&&Ht.ready.then(e=>Vt.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 Jt{constructor(e){this.name=e}subscribe(e){if(!Ht)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 Ht.addEventListener("message",t),()=>Ht.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})):Vt.registration&&(null===(t=Vt.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const qt=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class Yt extends n.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new Jt(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){qt.has(e)?qt.get(e).push(t):qt.set(e,[t])}(`lbc-${e}`,r);try{t instanceof Jt?i=t.subscribe(e=>n.next(e)):t.addEventListener("message",s)}catch(e){}return()=>{!function(e,t){const n=qt.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof Jt?i():t.removeEventListener("message",s)}}),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=qt.get(e.type);t&&t.forEach(t=>{try{t(e)}catch(e){}})}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function Gt(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 E(s)})}function Qt(e){return`$${e}_mutations`}function Xt(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 Zt=[].concat;function en(e){return Zt.apply([],e)}function tn(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=Xt(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=en(i).sort((e,t)=>e.mut.txid===t.mut.txid?e.mut.opNo-t.mut.opNo:e.mut.ts-t.mut.ts),c=[];let l=null,a=null;for(const{table:e,mut:t}of o)l&&l.table===e&&a===t.txid?l.muts.push(t):(l={table:e,muts:[t]},a=t.txid,c.push(l));return c})}function nn(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 rn="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class sn{toString(){return this.v}constructor(e){this.v=e}}const on=rn?{}:{bigint:{test:e=>e instanceof sn,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new sn(e)}},cn=Object.assign(Object.assign(Object.assign(Object.assign({},P),on),U),{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)}}}),ln=function(...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 u;let i=n.get(r);if(void 0!==i)return i;const o=(s=e,a.call(s).slice(8,-1)),c=Object.entries(t).find(([t,n])=>n?.test?.(e,o)??t===o);return i=c?.[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:u),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=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})}}}(_,D,T,y,m,b,v,cn);function an(e,n,r){const s=[];for(let i of r){const{table:r,muts:o}=i,c=e.tables.find(e=>e.name===r);if(!c)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:l}=c;let a=i;o.forEach((e,r)=>{const s=!l.outbound&&("upsert"===e.type||"insert"===e.type);e.keys.forEach((e,o)=>{if(Array.isArray(e)){a===i&&(a=un(i,s));const t=a.muts[r],n=JSON.stringify(e);t.keys[o]=n}else if("#"===e[0]){a===i&&(a=un(i,s));const c=a.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const u=`${e}:${n.userId}`;c.keys[o]=u,s&&t.setByKeyPath(c.values[o],l.keyPath,u)}})}),s.push(a)}return s}function un(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 dn=new WeakMap;function hn(e){return s(this,void 0,void 0,function*(){var t,n;const r=(null!==(n=null===(t=dn.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 fn(e,t,n,r,i,o,c,l,a){return s(this,void 0,void 0,function*(){const s={Accept:"application/json","Content-Type":"application/tson"},u=yield xt(i),d=null==u?void 0:u.accessToken;d&&(s.Authorization=`Bearer ${d}`);const h={v:3,dbID:null==n?void 0:n.remoteDbId,clientIdentity:l,schema:c||{},lastPull:n?{serverRevision:n.serverRevision,yServerRevision:n.yServerRevision,realms:n.realms,inviteRealms:n.inviteRealms}:void 0,baseRevs:r,changes:an(i.dx.core.schema,a,e),y:t,dxcv:i.cloud.version};i.syncStateChangedEvent.next({phase:"pushing"});const f=ln.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));dn.set(e,new Date(Date.now()+1e3*t))}else dn.delete(e)}}(i,p),!p.ok)throw new Ut(p);switch(p.headers.get("content-type")){case"application/x-bison":case"application/x-bison-stream":throw new Error("BISON format no longer supported. Server should send application/json.");default:{const e=yield p.text();return ln.parse(e)}}})}function pn(e){if(null==e?void 0:e.cancelled)throw new t.AbortError("Operation was cancelled")}let gn=!1;function yn(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 mn(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 bn(e,n,r){return s(this,void 0,void 0,function*(){const s=yield e.bulkGet(n),i=[],o=[];n.forEach((n,c)=>{const l=s[c];if(l){for(const[s,i]of Object.entries(r[c]))if(s===e.schema.primKey.keyPath){if(0!==t.cmp(i,n))throw new Error("Cannot change primary key")}else t.setByKeyPath(l,s,i);i.push(n),o.push(l)}}),yield null==e.schema.primKey.keyPath?e.bulkPut(o,i):e.bulkPut(o)})}function vn(e){null!==e&&"object"==typeof e&&e.constructor===Object&&rt(e)&&(e._hasBlobRefs=1)}function wn(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":n.values.forEach(vn),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":n.values.forEach(vn),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":if(!i.outbound&&i.keyPath)for(const e of n.changeSpecs)t.delByKeyPath(e,i.keyPath);yield bn(e,r,n.changeSpecs);break;case"delete":yield e.bulkDelete(r)}}}})}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(gn=navigator.onLine,self.addEventListener("online",()=>gn=!0),self.addEventListener("offline",()=>gn=!1));const _n="dexie-cloud-syncer";function kn(e,t){return e.where("i").between(t,1/0,!0).toArray()}const Sn=()=>new Map,xn=e=>{const t=Sn();return e.forEach((e,n)=>{t.set(n,e)}),t},En=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r};class Cn{constructor(){this._observers=Sn()}on(e,t){return En(this._observers,e,te).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 se((this._observers.get(e)||Sn()).values()).forEach(e=>e(...t))}destroy(){this._observers=Sn()}}class An{constructor(){this._observers=Sn()}on(e,t){En(this._observers,e,te).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 se((this._observers.get(e)||Sn()).values()).forEach(e=>e(...t))}destroy(){this._observers=Sn()}}const In=crypto.getRandomValues.bind(crypto),On=()=>In(new Uint32Array(1))[0],Dn=[1e7]+-1e3+-4e3+-8e3+-1e11,jn=()=>Dn.replace(/[018]/g,e=>(e^On()&15>>e/4).toString(16)),Tn=Date.now,Un=e=>new Promise(e);Promise.all.bind(Promise);const Pn=e=>void 0===e?null:e;let Ln=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},Rn=!0;try{"undefined"!=typeof localStorage&&localStorage&&(Ln=localStorage,Rn=!1)}catch(yl){}const $n=Ln,Mn=Object.assign,Bn=Object.keys,Nn=e=>Bn(e).length,Fn=e=>Bn(e).length,Wn=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),zn=Object.freeze,Kn=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||Kn(e[t])}return zn(e)},Vn=Symbol("Equality"),Hn=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Hn(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[Vn])return e[Vn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(const n of e.keys())if(!t.has(n)||!Jn(e.get(n),t.get(n)))return!1;break;case Object:if(Nn(e)!==Nn(t))return!1;for(const n in e)if(!Wn(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},qn="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let Yn;const Gn=e=>(()=>{if(void 0===Yn)if(qn){Yn=Sn();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&Yn.set(t,""),t=r):null!==t&&(Yn.set(t,r),t=null)}null!==t&&Yn.set(t,"")}else"object"==typeof location?(Yn=Sn(),(location.search||"?").slice(1).split("&").forEach(e=>{if(0!==e.length){const[t,n]=e.split("=");Yn.set(`--${le(t,"-")}`,n),Yn.set(`-${le(t,"-")}`,n)}})):Yn=Sn();return Yn})().has(e),Qn=e=>Pn(qn?process.env[e.toUpperCase().replaceAll("-","_")]:$n.getItem(e)),Xn=e=>Gn("--"+e)||null!==Qn(e);Xn("production");var Zn;qn&&(Zn=process.env.FORCE_COLOR,["true","1","2"].includes(Zn))||!Gn("--no-colors")&&!Xn("no-color")&&(!qn||process.stdout.isTTY)&&(!qn||Gn("--color")||null!==Qn("COLORTERM")||(Qn("TERM")||"").includes("color"));class er{constructor(e,t){this.left=e,this.right=t}}const tr=(e,t)=>new er(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const nr=Symbol,rr=nr(),sr=nr(),ir=nr(),or=nr(),cr=nr(),lr=nr(),ar=nr(),ur=nr(),dr=nr(),hr=(tr("font-weight","bold"),tr("font-weight","normal"),tr("color","blue"),tr("color","green"),tr("color","grey"),tr("color","red"),tr("color","purple"),tr("color","orange"),tr("color","black"),te()),fr=e=>({[Symbol.iterator](){return this},next:e}),pr=(e,t)=>fr(()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});class gr{constructor(e,t){this.clock=e,this.len=t}}class yr{constructor(){this.clients=new Map}}const mr=(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])Zr(e,s,o.clock,o.len,n)}}),br=(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=V((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)},vr=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=q(r.len,s.clock+s.len-r.clock):(n<t&&(e[n]=s),n++)}e.length=n})},wr=(e,t,n,r)=>{En(e.clients,t,()=>[]).push(new gr(n,r))},_r=(e,t)=>{me(e.restEncoder,t.clients.size),se(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),me(e.restEncoder,t);const r=n.length;me(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},kr=(e,t,n)=>{const r=new yr,s=Ke(e.restDecoder);for(let i=0;i<s;i++){e.resetDsCurVal();const s=Ke(e.restDecoder),i=Ke(e.restDecoder),o=n.clients.get(s)||[],c=Hr(n,s);for(let n=0;n<i;n++){const n=e.readDsClock(),i=n+e.readDsLen();if(n<c){c<i&&wr(r,s,c,i-c);let e=qr(o,n),l=o[e];for(!l.deleted&&l.id.clock<n&&(o.splice(e+1,0,Pi(t,l,n-l.id.clock)),e++);e<o.length&&(l=o[e++],l.id.clock<i);)l.deleted||(i<l.id.clock+l.length&&o.splice(e,0,Pi(t,l,i-l.id.clock)),l.delete(t))}else wr(r,s,n,i-n)}}if(r.clients.size>0){const e=new Dr;return me(e.restEncoder,0),_r(e,r),e.toUint8Array()}return null},Sr=On;class xr extends Cn{constructor({guid:e=jn(),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=Sr(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Kr,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=Un(e=>{this.on("load",()=>{this.isLoaded=!0,e(this)})});const c=()=>Un(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=c()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;null===e||this.shouldLoad||is(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(se(this.subdocs).map(e=>e.guid))}transact(e,t=null){return is(this,e,t)}get(e,t=xs){const n=En(this.share,e,()=>{const e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==xs&&r!==t){if(r===xs){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,Ws)}getText(e=""){return this.get(e,oi)}getMap(e=""){return this.get(e,Ks)}getXmlElement(e=""){return this.get(e,ai)}getXmlFragment(e=""){return this.get(e,li)}toJSON(){const e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,se(this.subdocs).forEach(e=>e.destroy());const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new xr({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,is(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 Er{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Ke(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Ke(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Cr extends Er{constructor(e){super(e),this.keys=[],Ke(e),this.keyClockDecoder=new Ze(We(e)),this.clientDecoder=new Xe(We(e)),this.leftClockDecoder=new Ze(We(e)),this.rightClockDecoder=new Ze(We(e)),this.infoDecoder=new Qe(We(e),ze),this.stringDecoder=new et(We(e)),this.parentInfoDecoder=new Qe(We(e),ze),this.typeRefDecoder=new Xe(We(e)),this.lenDecoder=new Xe(We(e))}readLeftID(){return new Br(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Br(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 Ge(this.restDecoder)}readBuf(){return We(this.restDecoder)}readJSON(){return Ge(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 Ar{constructor(){this.restEncoder=fe()}toUint8Array(){return pe(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){me(this.restEncoder,e)}writeDsLen(e){me(this.restEncoder,e)}}class Ir extends Ar{writeLeftID(e){me(this.restEncoder,e.client),me(this.restEncoder,e.clock)}writeRightID(e){me(this.restEncoder,e.client),me(this.restEncoder,e.clock)}writeClient(e){me(this.restEncoder,e)}writeInfo(e){ye(this.restEncoder,e)}writeString(e){_e(this.restEncoder,e)}writeParentInfo(e){me(this.restEncoder,e?1:0)}writeTypeRef(e){me(this.restEncoder,e)}writeLen(e){me(this.restEncoder,e)}writeAny(e){Ae(this.restEncoder,e)}writeBuf(e){Se(this.restEncoder,e)}writeJSON(e){_e(this.restEncoder,JSON.stringify(e))}writeKey(e){_e(this.restEncoder,e)}}class Or{constructor(){this.restEncoder=fe(),this.dsCurrVal=0}toUint8Array(){return pe(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,me(this.restEncoder,t)}writeDsLen(e){0===e&&Re(),me(this.restEncoder,e-1),this.dsCurrVal+=e}}class Dr extends Or{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Te,this.clientEncoder=new De,this.leftClockEncoder=new Te,this.rightClockEncoder=new Te,this.infoEncoder=new Ie(ye),this.stringEncoder=new Ue,this.parentInfoEncoder=new Ie(ye),this.typeRefEncoder=new De,this.lenEncoder=new De}toUint8Array(){const e=fe();return me(e,0),Se(e,this.keyClockEncoder.toUint8Array()),Se(e,this.clientEncoder.toUint8Array()),Se(e,this.leftClockEncoder.toUint8Array()),Se(e,this.rightClockEncoder.toUint8Array()),Se(e,pe(this.infoEncoder)),Se(e,this.stringEncoder.toUint8Array()),Se(e,pe(this.parentInfoEncoder)),Se(e,this.typeRefEncoder.toUint8Array()),Se(e,this.lenEncoder.toUint8Array()),ke(e,pe(this.restEncoder)),pe(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){Ae(this.restEncoder,e)}writeBuf(e){Se(this.restEncoder,e)}writeJSON(e){Ae(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 jr=(e,t,n)=>{const r=new Map;n.forEach((e,n)=>{Hr(t,n)>e&&r.set(n,e)}),Vr(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),me(e.restEncoder,r.size),se(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{((e,t,n,r)=>{r=q(r,t[0].id.clock);const s=qr(t,r);me(e.restEncoder,t.length-s),e.writeClient(n),me(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)})},Tr=(e,t,n,r=new Cr(e))=>is(t,e=>{e.local=!1;let t=!1;const n=e.doc,s=n.store,i=((e,t)=>{const n=Sn(),r=Ke(e.restDecoder);for(let s=0;s<r;s++){const r=Ke(e.restDecoder),s=new Array(r),i=e.readClient();let o=Ke(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 pi(Fr(i,o),t),o+=t;break}case 10:{const t=Ke(e.restDecoder);s[n]=new Mi(Fr(i,o),t),o+=t;break}default:{const c=!(192&r),l=new Li(Fr(i,o),null,(r&Q)===Q?e.readLeftID():null,null,(r&G)===G?e.readRightID():null,c?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,!c||32&~r?null:e.readString(),Ri(e,r));s[n]=l,o+=l.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let s=se(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 c=new Kr,l=new Map,a=(e,t)=>{const n=l.get(e);(null==n||n>t)&&l.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--,c.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):c.clients.set(t,[e]),s=s.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==Mi){const s=En(d,u.id.client,()=>Hr(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,Hr(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(c.clients.size>0){const e=new Dr;return jr(e,c,new Map),me(e.restEncoder,0),{missing:l,update:e.toUint8Array()}}return null})(e,s,i),c=s.pendingStructs;if(c){for(const[e,n]of c.missing)if(n<Hr(s,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=c.missing.get(e);(null==n||n>t)&&c.missing.set(e,t)}c.update=us([c.update,o.update])}}else s.pendingStructs=o;const l=kr(r,e,s);if(s.pendingDs){const t=new Cr(Ne(s.pendingDs));Ke(t.restDecoder);const n=kr(t,e,s);s.pendingDs=l&&n?us([l,n]):l||n}else s.pendingDs=l;if(t){const t=s.pendingStructs.update;s.pendingStructs=null,Ur(e.doc,t)}},n,!1),Ur=(e,t,n,r=Cr)=>{const s=Ne(t);Tr(s,e,n,new r(s))};class Pr{constructor(){this.l=[]}}const Lr=()=>new Pr,Rr=(e,t)=>e.l.push(t),$r=(e,t)=>{const n=e.l;n.length;e.l=n.filter(e=>t!==e),e.l.length},Mr=(e,t,n)=>Hn(e.l,[t,n]);class Br{constructor(e,t){this.client=e,this.clock=t}}const Nr=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,Fr=(e,t)=>new Br(e,t),Wr=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!br(t.ds,e.id),zr=(e,t)=>{const n=En(e.meta,zr,te),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<Hr(r,n)&&Qr(e,Fr(n,t))}),mr(e,t.ds,e=>{}),n.add(t))};class Kr{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Vr=e=>{const t=new Map;return e.clients.forEach((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},Hr=(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 Re()}n.push(t)},qr=(e,t)=>{let n=0,r=e.length-1,s=e[r],i=s.id.clock;if(i===t)return r;let o=V(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=V((n+r)/2)}throw Re()},Yr=(e,t)=>{const n=e.clients.get(t.client);return n[qr(n,t.clock)]},Gr=(e,t,n)=>{const r=qr(t,n),s=t[r];return s.id.clock<n&&s instanceof Li?(t.splice(r+1,0,Pi(e,s,n-s.id.clock)),r+1):r},Qr=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[Gr(e,n,t.clock)]},Xr=(e,t,n)=>{const r=t.clients.get(n.client),s=qr(r,n.clock),i=r[s];return n.clock!==i.id.clock+i.length-1&&i.constructor!==pi&&r.splice(s+1,0,Pi(e,i,n.clock-i.id.clock+1)),i},Zr=(e,t,n,r,s)=>{if(0===r)return;const i=n+r;let o,c=Gr(e,t,n);do{o=t[c++],i<o.id.clock+o.length&&Gr(e,t,i),s(o)}while(c<t.length&&t[c].id.clock<i)};class es{constructor(e,t,n){this.doc=e,this.deleteSet=new yr,this.beforeState=Vr(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const ts=(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))&&(vr(t.deleteSet),((e,t)=>{jr(e,t.doc.store,t.beforeState)})(e,t),_r(e,t.deleteSet),!0),ns=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&En(e.changed,t,te).add(n)},rs=(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 Li&&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},ss=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,s=r.store,i=n.deleteSet,o=n._mergeStructs;try{vr(i),n.afterState=Vr(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach((t,r)=>e.push(()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((e,t)=>{t._dEH.l.length>0&&(null===t._item||!t._item.deleted)&&((e=e.filter(e=>null===e.target._item||!e.target._item.deleted)).forEach(e=>{e.currentTarget=t,e._path=null}),e.sort((e,t)=>e.path.length-t.path.length),Mr(t._dEH,e,n))})}),e.push(()=>r.emit("afterTransaction",[n,r])),Hn(e,[]),n._needFormattingCleanup&&ri(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=qr(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 Li&&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=J(r.length-1,1+qr(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+rs(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=q(qr(e,r),1);for(let t=e.length-1;t>=n;)t-=1+rs(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=qr(r,n);i+1<r.length&&rs(r,i+1)>1||i>0&&rs(r,i)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{hr.forEach(t=>t.print(e))})(ur,rr,"[yjs] ",sr,lr,"Changed the client-id because another client seems to be using it."),r.clientID=Sr()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new Ir;ts(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new Dr;ts(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:a}=n;(c.size>0||a.size>0||l.size>0)&&(c.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:l,added:c,removed:a},r,n]),a.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):ss(e,t+1)}}},is=(e,t,n=null,r=!0)=>{const s=e._transactionCleanups;let i=!1,o=null;null===e._transaction&&(i=!0,e._transaction=new es(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&&ss(s,0)}}return o};class os{constructor(e,t){this.gen=function*(e){const t=Ke(e.restDecoder);for(let n=0;n<t;n++){const t=Ke(e.restDecoder),n=e.readClient();let r=Ke(e.restDecoder);for(let s=0;s<t;s++){const t=e.readInfo();if(10===t){const t=Ke(e.restDecoder);yield new Mi(Fr(n,r),t),r+=t}else if(31&t){const s=!(192&t),i=new Li(Fr(n,r),null,(t&Q)===Q?e.readLeftID():null,null,(t&G)===G?e.readRightID():null,s?e.readParentInfo()?e.readString():e.readLeftID():null,!s||32&~t?null:e.readString(),Ri(e,t));yield i,r+=i.length}else{const t=e.readLen();yield new pi(Fr(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===Mi);return this.curr}}class cs{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const ls=(e,t=Or,n=Cr)=>{const r=new t,s=new os(new n(Ne(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++,me(r.restEncoder,t),me(r.restEncoder,o)),t=i.id.client,o=0,n=0!==i.id.clock),i.constructor===Mi&&(n=!0),n||(o=i.id.clock+i.length);0!==o&&(e++,me(r.restEncoder,t),me(r.restEncoder,o));const c=fe();return me(c,e),((e,t)=>{ke(e,pe(t))})(c,r.restEncoder),r.restEncoder=c,r.toUint8Array()}return me(r.restEncoder,0),r.toUint8Array()},as=(e,t)=>{if(e.constructor===pi){const{client:n,clock:r}=e.id;return new pi(Fr(n,r+t),e.length-t)}if(e.constructor===Mi){const{client:n,clock:r}=e.id;return new Mi(Fr(n,r+t),e.length-t)}{const n=e,{client:r,clock:s}=n.id;return new Li(Fr(r,s+t),null,Fr(r,s+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},us=(e,t=Cr,n=Dr)=>{if(1===e.length)return e[0];const r=e.map(e=>new t(Ne(e)));let s=r.map(e=>new os(e,!0)),i=null;const o=new n,c=new cs(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===Mi?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)hs(c,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===Mi)i.struct.length=n.id.clock+n.length-i.struct.id.clock;else{hs(c,i.struct,i.offset);const e=n.id.clock-i.struct.id.clock-i.struct.length;i={struct:new Mi(Fr(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===Mi?i.struct.length-=t:n=as(n,t)),i.struct.mergeWith(n)||(hs(c,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!==Mi;n=e.next())hs(c,i.struct,i.offset),i={struct:n,offset:0}}null!==i&&(hs(c,i.struct,i.offset),i=null),fs(c);const l=r.map(e=>(e=>{const t=new yr,n=Ke(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=Ke(e.restDecoder),r=Ke(e.restDecoder);if(r>0){const s=En(t.clients,n,()=>[]);for(let t=0;t<r;t++)s.push(new gr(e.readDsClock(),e.readDsLen()))}}return t})(e)),a=(e=>{const t=new yr;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++)re(i,e[t].clients.get(s)||[]);t.clients.set(s,i)}});return vr(t),t})(l);return _r(o,a),o.toUint8Array()},ds=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:pe(e.encoder.restEncoder)}),e.encoder.restEncoder=fe(),e.written=0)},hs=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ds(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),me(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},fs=e=>{ds(e);const t=e.encoder.restEncoder;me(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];me(t,r.written),ke(t,r.restEncoder)}},ps="You must not compute changes after the event-handler fired.";class gs{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=ys(this.currentTarget,this.target))}deletes(e){return br(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw Pe(ps);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=ne(e.content.getContent())}else null!==e&&this.deletes(e)?(s="update",i=ne(e.content.getContent())):(s="add",i=void 0)}else{if(!this.deletes(r))return;s="delete",i=ne(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 Pe(ps);const t=this.target,n=te(),r=te(),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 ys=(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},ms=()=>{((...e)=>{e.unshift(ur),hr.forEach(t=>t.print(e))})("Invalid access: Add Yjs type to a document before reading data.")};let bs=0;class vs{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=bs++}}const ws=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=bs++},_s=(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)=>H(t-e.index)<H(t-n.index)?e:n);let r=e._start,s=0;for(null!==n&&(r=n.p,s=n.index,(e=>{e.timestamp=bs++})(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&&H(n.index-s)<r.parent.length/80?(ws(n,r,s),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return ws(r,t,n),r}{const r=new vs(t,n);return e.push(r),r}})(e._searchMarker,r,s)},ks=(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=q(t,s.index+n))}},Ss=(e,t,n)=>{const r=e,s=t.changedParentTypes;for(;En(s,e,()=>[]).push(n),null!==e._item;)e=e._item.parent;Mr(r._eH,n,t)};class xs{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Lr(),this._dEH=Lr(),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){Rr(this._eH,e)}observeDeep(e){Rr(this._dEH,e)}unobserve(e){$r(this._eH,e)}unobserveDeep(e){$r(this._dEH,e)}toJSON(){}}const Es=(e,t,n)=>{e.doc??ms(),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},Cs=e=>{e.doc??ms();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},As=(e,t)=>{let n=0,r=e._start;for(e.doc??ms();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}},Is=(e,t)=>{const n=[];return As(e,(r,s)=>{n.push(t(r,s,e))}),n},Os=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}}}},Ds=(e,t)=>{e.doc??ms();const n=_s(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}},js=(e,t,n,r)=>{let s=n;const i=e.doc,o=i.clientID,c=i.store,l=null===n?t._start:n.right;let a=[];const u=()=>{a.length>0&&(s=new Li(Fr(o,Hr(c,o)),s,s&&s.lastId,l,l&&l.id,t,null,new Si(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 Li(Fr(o,Hr(c,o)),s,s&&s.lastId,l,l&&l.id,t,null,new gi(new Uint8Array(n))),s.integrate(e,0);break;case xr:s=new Li(Fr(o,Hr(c,o)),s,s&&s.lastId,l,l&&l.id,t,null,new bi(n)),s.integrate(e,0);break;default:if(!(n instanceof xs))throw new Error("Unexpected content type in insert operation");s=new Li(Fr(o,Hr(c,o)),s,s&&s.lastId,l,l&&l.id,t,null,new Ui(n)),s.integrate(e,0)}}}),u()},Ts=()=>Pe("Length exceeded!"),Us=(e,t,n,r)=>{if(n>t._length)throw Ts();if(0===n)return t._searchMarker&&ks(t._searchMarker,n,r.length),js(e,t,null,r);const s=n,i=_s(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&&Qr(e,Fr(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&ks(t._searchMarker,s,r.length),js(e,t,o,r)},Ps=(e,t,n,r)=>{if(0===r)return;const s=n,i=r,o=_s(t,n);let c=t._start;for(null!==o&&(c=o.p,n-=o.index);null!==c&&n>0;c=c.right)!c.deleted&&c.countable&&(n<c.length&&Qr(e,Fr(c.id.client,c.id.clock+n)),n-=c.length);for(;r>0&&null!==c;)c.deleted||(r<c.length&&Qr(e,Fr(c.id.client,c.id.clock+r)),c.delete(e),r-=c.length),c=c.right;if(r>0)throw Ts();t._searchMarker&&ks(t._searchMarker,s,-i+r)},Ls=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},Rs=(e,t,n,r)=>{const s=t._map.get(n)||null,i=e.doc,o=i.clientID;let c;if(null==r)c=new Si([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:c=new Si([r]);break;case Uint8Array:c=new gi(r);break;case xr:c=new bi(r);break;default:if(!(r instanceof xs))throw new Error("Unexpected content type");c=new Ui(r)}new Li(Fr(o,Hr(i.store,o)),s,s&&s.lastId,null,null,t,n,c).integrate(e,0)},$s=(e,t)=>{e.doc??ms();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},Ms=e=>{const t={};return e.doc??ms(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},Bs=(e,t)=>{e.doc??ms();const n=e._map.get(t);return void 0!==n&&!n.deleted},Ns=e=>{return e.doc??ms(),t=e._map.entries(),n=e=>!e[1].deleted,fr(()=>{let e;do{e=t.next()}while(!e.done&&!n(e.value));return e});var t,n};class Fs extends gs{}class Ws extends xs{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new Ws;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ws}clone(){const e=new Ws;return e.insert(0,this.toArray().map(e=>e instanceof xs?e.clone():e)),e}get length(){return this.doc??ms(),this._length}_callObserver(e,t){super._callObserver(e,t),Ss(this,e,new Fs(this,e))}insert(e,t){null!==this.doc?is(this.doc,n=>{Us(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?is(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;js(e,t,r,n)})(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?is(this.doc,n=>{Ps(n,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return Ds(this,e)}toArray(){return Cs(this)}slice(e=0,t=this.length){return Es(this,e,t)}toJSON(){return this.map(e=>e instanceof xs?e.toJSON():e)}map(e){return Is(this,e)}forEach(e){As(this,e)}[Symbol.iterator](){return Os(this)}_write(e){e.writeTypeRef(Ci)}}class zs extends gs{constructor(e,t,n){super(e,t),this.keysChanged=n}}class Ks extends xs{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 Ks}clone(){const e=new Ks;return this.forEach((t,n)=>{e.set(n,t instanceof xs?t.clone():t)}),e}_callObserver(e,t){Ss(this,e,new zs(this,e,t))}toJSON(){this.doc??ms();const e={};return this._map.forEach((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof xs?r.toJSON():r}}),e}get size(){return[...Ns(this)].length}keys(){return pr(Ns(this),e=>e[0])}values(){return pr(Ns(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return pr(Ns(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??ms(),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?is(this.doc,t=>{Ls(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?is(this.doc,n=>{Rs(n,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return $s(this,e)}has(e){return Bs(this,e)}clear(){null!==this.doc?is(this.doc,e=>{this.forEach(function(t,n,r){Ls(e,r,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Ai)}}const Vs=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&((e,t)=>e===t||Fn(e)===Fn(t)&&((e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0})(e,(e,n)=>(void 0!==e||Wn(t,n))&&t[n]===e))(e,t);class Hs{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&Re(),this.right.content.constructor===wi)this.right.deleted||Gs(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===wi)t.right.deleted||Gs(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&Qr(e,Fr(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},qs=(e,t,n,r)=>{const s=new Map,i=r?_s(t,n):null;if(i){const t=new Hs(i.p.left,i.p,i.index,s);return Js(e,t,n-i.index)}{const r=new Hs(null,t._start,0,s);return Js(e,r,n)}},Ys=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===wi&&Vs(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const s=e.doc,i=s.clientID;r.forEach((r,o)=>{const c=n.left,l=n.right,a=new Li(Fr(i,Hr(s.store,i)),c,c&&c.lastId,l,l&&l.id,t,null,new wi(o,r));a.integrate(e,0),n.right=a,n.forward()})},Gs=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},Qs=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===wi&&Vs(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Xs=(e,t,n,r)=>{const s=e.doc,i=s.clientID,o=new Map;for(const c in r){const l=r[c],a=n.currentAttributes.get(c)??null;if(!Vs(a,l)){o.set(c,a);const{left:r,right:u}=n;n.right=new Li(Fr(i,Hr(s.store,i)),r,r&&r.lastId,u,u&&u.id,t,null,new wi(c,l)),n.right.integrate(e,0),n.forward()}}return o},Zs=(e,t,n,r,s)=>{n.currentAttributes.forEach((e,t)=>{void 0===s[t]&&(s[t]=null)});const i=e.doc,o=i.clientID;Qs(n,s);const c=Xs(e,t,n,s),l=r.constructor===String?new xi(r):r instanceof xs?new Ui(r):new vi(r);let{left:a,right:u,index:d}=n;t._searchMarker&&ks(t._searchMarker,n.index,l.getLength()),u=new Li(Fr(o,Hr(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,l),u.integrate(e,0),n.right=u,n.index=d,n.forward(),Ys(e,t,n,c)},ei=(e,t,n,r,s)=>{const i=e.doc,o=i.clientID;Qs(n,s);const c=Xs(e,t,n,s);e:for(;null!==n.right&&(r>0||c.size>0&&(n.right.deleted||n.right.content.constructor===wi));){if(!n.right.deleted)switch(n.right.content.constructor){case wi:{const{key:t,value:i}=n.right.content,o=s[t];if(void 0!==o){if(Vs(o,i))c.delete(t);else{if(0===r)break e;c.set(t,i)}n.right.delete(e)}else n.currentAttributes.set(t,i);break}default:r<n.right.length&&Qr(e,Fr(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 Li(Fr(o,Hr(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new xi(s)),n.right.integrate(e,0),n.forward()}Ys(e,t,n,c)},ti=(e,t,n,r,s)=>{let i=t;const o=Sn();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===wi){const e=i.content;o.set(e.key,e)}i=i.right}let c=0,l=!1;for(;t!==i;){if(n===t&&(l=!0),!t.deleted){const n=t.content;switch(n.constructor){case wi:{const{key:i,value:a}=n,u=r.get(i)??null;o.get(i)===n&&u!==a||(t.delete(e),c++,l||(s.get(i)??null)!==a||u===a||(null===u?s.delete(i):s.set(i,u))),l||t.deleted||Gs(s,n);break}}}t=t.right}return c},ni=e=>{let t=0;return is(e.doc,n=>{let r=e._start,s=e._start,i=Sn();const o=xn(i);for(;s;){if(!1===s.deleted)if(s.content.constructor===wi)Gs(o,s.content);else t+=ti(n,r,s,i,o),i=xn(o),r=s;s=s.right}}),t},ri=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&&Zr(e,n.store.clients.get(r),i,s,e=>{e.deleted||e.content.constructor!==wi||e.constructor===pi||t.add(e.parent)})}is(n,n=>{mr(e,e.deleteSet,e=>{if(e instanceof pi||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===wi?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===wi){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)});for(const e of t)ni(e)})},si=(e,t,n)=>{const r=n,s=xn(t.currentAttributes),i=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case Ui:case vi:case xi:n<t.right.length&&Qr(e,Fr(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}i&&ti(e,i,t.right,s,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&ks(o._searchMarker,t.index,-r+n),t};class ii extends gs{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=[];is(e,e=>{const n=new Map,r=new Map;let s=this.target._start,i=null;const o={};let c="",l=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 c||c.length>0)&&(e={insert:c},n.size>0&&(e.attributes={},n.forEach((t,n)=>{null!==t&&(e.attributes[n]=t)}))),c="";break;case"retain":l>0&&(e={retain:l},(e=>{for(const t in e)return!1;return!0})(o)||(e.attributes=Mn({},o))),l=0}e&&t.push(e),i=null}};for(;null!==s;){switch(s.content.constructor){case Ui:case vi:this.adds(s)?this.deletes(s)||(u(),i="insert",c=s.content.getContent()[0],u()):this.deletes(s)?("delete"!==i&&(u(),i="delete"),a+=1):s.deleted||("retain"!==i&&(u(),i="retain"),l+=1);break;case xi:this.adds(s)?this.deletes(s)||("insert"!==i&&(u(),i="insert"),c+=s.content.str):this.deletes(s)?("delete"!==i&&(u(),i="delete"),a+=s.length):s.deleted||("retain"!==i&&(u(),i="retain"),l+=s.length);break;case wi:{const{key:t,value:c}=s.content;if(this.adds(s)){if(!this.deletes(s)){const l=n.get(t)??null;Vs(l,c)?null!==c&&s.delete(e):("retain"===i&&u(),Vs(c,r.get(t)??null)?delete o[t]:o[t]=c)}}else if(this.deletes(s)){r.set(t,c);const e=n.get(t)??null;Vs(e,c)||("retain"===i&&u(),o[t]=e)}else if(!s.deleted){r.set(t,c);const n=o[t];void 0!==n&&(Vs(n,c)?null!==n&&s.delete(e):("retain"===i&&u(),null===c?delete o[t]:o[t]=c))}s.deleted||("insert"===i&&u(),Gs(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 oi extends xs{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??ms(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){}this._pending=null}_copy(){return new oi}clone(){const e=new oi;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new ii(this,e,t);Ss(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??ms();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===xi&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?is(this.doc,n=>{const r=new Hs(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)&&Zs(n,this,r,o,i.attributes||{})}else void 0!==i.retain?ei(n,this,r,i.retain,i.attributes||{}):void 0!==i.delete&&si(n,r,i.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,n){this.doc??ms();const r=[],s=new Map,i=this.doc;let o="",c=this._start;function l(){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!==c;){if(Wr(c,e)||void 0!==t&&Wr(c,t))switch(c.content.constructor){case xi:{const r=s.get("ychange");void 0===e||Wr(c,e)?void 0===t||Wr(c,t)?void 0!==r&&(l(),s.delete("ychange")):void 0!==r&&r.user===c.id.client&&"added"===r.type||(l(),s.set("ychange",n?n("added",c.id):{type:"added"})):void 0!==r&&r.user===c.id.client&&"removed"===r.type||(l(),s.set("ychange",n?n("removed",c.id):{type:"removed"})),o+=c.content.str;break}case Ui:case vi:{l();const e={insert:c.content.getContent()[0]};if(s.size>0){const t={};e.attributes=t,s.forEach((e,n)=>{t[n]=e})}r.push(e);break}case wi:Wr(c,e)&&(l(),Gs(s,c.content))}c=c.right}l()};return e||t?is(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?is(r,r=>{const s=qs(r,this,e,!n);n||(n={},s.currentAttributes.forEach((e,t)=>{n[t]=e})),Zs(r,this,s,t,n)}):this._pending.push(()=>this.insert(e,t,n))}insertEmbed(e,t,n){const r=this.doc;null!==r?is(r,r=>{const s=qs(r,this,e,!n);Zs(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?is(n,n=>{si(n,qs(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?is(r,r=>{const s=qs(r,this,e,!1);null!==s.right&&ei(r,this,s,t,n)}):this._pending.push(()=>this.format(e,t,n))}removeAttribute(e){null!==this.doc?is(this.doc,t=>{Ls(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){null!==this.doc?is(this.doc,n=>{Rs(n,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return $s(this,e)}getAttributes(){return Ms(this)}_write(e){e.writeTypeRef(Ii)}}class ci{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??ms()}[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!==ai&&t.constructor!==li||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 li extends xs{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 li}clone(){const e=new li;return e.insert(0,this.toArray().map(e=>e instanceof xs?e.clone():e)),e}get length(){return this.doc??ms(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new ci(this,e)}querySelector(e){e=e.toUpperCase();const t=new ci(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),se(new ci(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Ss(this,e,new ui(this,t,e))}toString(){return Is(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),As(this,s=>{r.insertBefore(s.toDOM(e,t,n),null)}),r}insert(e,t){null!==this.doc?is(this.doc,n=>{Us(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)is(this.doc,n=>{const r=e&&e instanceof xs?e._item:e;js(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 Pe("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?is(this.doc,n=>{Ps(n,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return Cs(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Ds(this,e)}slice(e=0,t=this.length){return Es(this,e,t)}forEach(e){As(this,e)}_write(e){e.writeTypeRef(Di)}}class ai extends li{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 ai(this.nodeName)}clone(){const e=new ai(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 xs?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?is(this.doc,t=>{Ls(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?is(this.doc,n=>{Rs(n,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return $s(this,e)}hasAttribute(e){return Bs(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&&Wr(s,t)&&(n[r]=s.content.getContent()[s.length-1])}),n})(this,e):Ms(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 As(this,s=>{r.appendChild(s.toDOM(e,t,n))}),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Oi),e.writeKey(this.nodeName)}}class ui extends gs{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 di extends Ks{constructor(e){super(),this.hookName=e}_copy(){return new di(this.hookName)}clone(){const e=new di(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(ji),e.writeKey(this.hookName)}}class hi extends oi{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 hi}clone(){const e=new hi;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(Ti)}}class fi{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 pi extends fi{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 gi{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new gi(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 yi{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new yi(this.len)}splice(e){const t=new yi(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){wr(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 mi=(e,t)=>new xr({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class bi{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 bi(mi(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 vi{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new vi(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 wi{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new wi(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 _i{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new _i(this.arr)}splice(e){const t=new _i(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 ki="development"===Qn("node_env");class Si{constructor(e){this.arr=e,ki&&Kn(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Si(this.arr)}splice(e){const t=new Si(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 xi{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new xi(this.str)}splice(e){const t=new xi(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 Ei=[e=>new Ws,e=>new Ks,e=>new oi,e=>new ai(e.readKey()),e=>new li,e=>new di(e.readKey()),e=>new hi],Ci=0,Ai=1,Ii=2,Oi=3,Di=4,ji=5,Ti=6;class Ui{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Ui(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 Pi=(e,t,n)=>{const{client:r,clock:s}=t.id,i=new Li(Fr(r,s+n),t,Fr(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=Fr(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 Li extends fi{constructor(e,t,n,r,s,i,o,c){super(e,c.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=s,this.parent=i,this.parentSub=o,this.redone=null,this.content=c,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>=Hr(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Hr(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Br&&this.id.client!==this.parent.client&&this.parent.clock>=Hr(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Xr(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Qr(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===pi||this.right&&this.right.constructor===pi)this.parent=null;else if(this.parent){if(this.parent.constructor===Br){const e=Yr(t,this.parent);e.constructor===pi?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===Li?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Li&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Xr(e,e.doc.store,Fr(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),Nr(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(Nr(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!s.has(Yr(e.doc.store,t.origin)))break;r.has(Yr(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),ns(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new pi(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:Fr(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Nr(e.origin,this.lastId)&&this.right===e&&Nr(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(),wr(e.deleteSet,this.id.client,this.id.clock,this.length),ns(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Re();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[qr(r,t.id.clock)]=n})(e,this,new pi(this.id,this.length)):this.content=new yi(this.length)}write(e,t){const n=t>0?Fr(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,s=this.parentSub,i=31&this.content.getRef()|(null===n?0:Q)|(null===r?0:G)|(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 Re()})(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===Br?(e.writeParentInfo(!1),e.writeLeftID(t)):Re();null!==s&&e.writeString(s)}this.content.write(e,t)}}const Ri=(e,t)=>$i[31&t](e),$i=[()=>{Re()},e=>new yi(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 _i(n)},e=>new gi(e.readBuf()),e=>new xi(e.readString()),e=>new vi(e.readJSON()),e=>new wi(e.readKey(),e.readJSON()),e=>new Ui(Ei[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Si(n)},e=>new bi(mi(e.readString(),e.readAny())),()=>{Re()}];class Mi extends fi{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){Re()}write(e,t){e.writeInfo(10),me(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const Bi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},Ni="__ $YJS$ __";function Fi(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}Bi[Ni],Bi[Ni]=!0;const Wi=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=Hi(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=Hi(n,r,s),o=null===(t=this.cache[i])||void 0===t?void 0:t.deref();o&&Wi.unregister(o),this.cache[i]=new WeakRef(e),Wi.register(e,{cache:this.cache,key:i},e)},delete(e){Wi.unregister(e);const t=Hi(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 Ki=new WeakSet;function Vi(e){if(Ki.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function Hi(e,t,n){return`${e}[${t}].${n}`}const{getByKeyPath:Ji}=t.Dexie;let qi=null;function Yi(e){qi=e}function Gi(){}const Qi=new WeakMap;function Xi(){return t.Dexie.Events(null,"load","sync","error")}class Zi{static getOrCreateDocument(e,t,n,r){var s,i;const o=zi(e),c=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(!c)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 xr({meta:{db:e,updatesTable:s,parentProp:r,parentTable:n,parentId:i}}),t.add(o),o.on("destroy",()=>{Ki.add(o),t.delete(o)}),o)}(e,o,t,n,c,r)}static load(e,t){var n;let r=Qi.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 Zi(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,Qi.set(e,r)),r}static release(e){if(!e||Ki.has(e))return;const t=Qi.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(Zi.on("beforeunload").fire(this)).finally(()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())})}static for(e){return Qi.get(e)}static get currentUpdateRow(){return qi}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise((e,n)=>{this.doc?this.doc.isLoaded?e():this._error?n(this._error):Ki.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):Ki.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=Xi(),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]=()=>Zi.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`);Vi(e),this.stopObserving=function(e,n,r,s,i,o){let c=0,l=!0;const a=t.liveQuery(()=>{Vi(n);const e=r.table(i);return Promise.all([(c>0?e.where("i").between(c,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&&(c=t[t.length-1].i),0!==r.length?(Vi(n),t.length>0&&is(n,()=>{t.forEach(e=>{try{Yi(e),Ur(n,e.u)}finally{Yi(null)}})},e,!1),l&&(l=!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===c-1&&++c}).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),Zi.on("new").fire(this)}destroy(){var e;Qi.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=Xi(),this.cleanupHandlers.forEach(e=>e())}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function eo(e,n){return s(this,void 0,void 0,function*(){var r;const i={};let o,c=!1;for(const l of e)try{switch(l.type){case"u-s":{const e=Fi(n,l.table,l.prop);if(e){const t={k:l.k,u:l.u};l.r&&(t.r=l.r,o=l.r),i[e.name]=yield e.add(t)}break}case"u-ack":{const e=Fi(n,l.table,l.prop);e&&(yield n.transaction("rw",e,t=>s(this,void 0,void 0,function*(){let n=yield t.table(e.name).get(_n);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:_n}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,l.i+1)}))})));break}case"u-reject":{const e=Fi(n,l.table,l.prop);if(!e)break;const s=null===(r=yield e.get(l.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(l.i).filter(e=>0===t.cmp(e.k,s)&&!(1&~(e.f||0))).delete()));const r=Zi.getDocCache(n.dx).find(l.table,s,l.prop);r&&r.destroy()}break}case"in-sync":{const e=Zi.getDocCache(n.dx).find(l.table,l.k,l.prop);e&&!e.isSynced&&e.emit("sync",[!0,e]);break}case"y-complete-sync-done":o=l.yServerRev;break;case"outdated-server-rev":c=!0}}catch(e){}return{receivedUntils:i,resyncNeeded:c,yServerRevision:o}})}Zi.on=t.Dexie.Events(null,{new:[function(e,t){return e===Gi?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===Gi?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)}}]}),Zi.getDocCache=zi,t.Dexie.DexieYProvider?Zi=t.Dexie.DexieYProvider||Zi:t.Dexie.DexieYProvider=Zi;const to=new Map,no=new Set(["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","DataView"]),ro=new Set(["Blob","File","ArrayBuffer",...no]);function so(e){return Object.prototype.toString.call(e).slice(8,-1)}function io(e){if("object"!==typeof e||null===e)return!1;const t=so(e);return!!ro.has(t)&&("Blob"===t||"File"===t||e.byteLength>=4096)}function oo(e,t,n){return s(this,void 0,void 0,function*(){const r=yield t();if(!r)throw new Error("Failed to load access token for blob upload");const s=function(){const e=new Uint8Array(18),t=new Uint8Array(e.buffer,0,6),n=Date.now();R>=n?++R:R=n,t[0]=R/1099511627776,t[1]=R/4294967296,t[2]=R/16777216,t[3]=R/65536,t[4]=R/256,t[5]=R;const r=new Uint8Array(e.buffer,6);return L(r),C(e)}(),i=`${e}/blob/${s}`;let o,c,l;const a=function(e){const t=so(e);return"Blob"===t||"File"===t?"Blob":"ArrayBuffer"===t?"ArrayBuffer":t}(n),u=so(n);if("Blob"===u||"File"===u)o=n,c=n.type||"application/octet-stream",l=n.size;else if("ArrayBuffer"===u)o=n,c="application/octet-stream",l=n.byteLength;else{if(!no.has(u))throw new Error(`Unsupported blob type: ${u}`);{const e=n,t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),o=t,c="application/octet-stream",l=e.byteLength}}const d=`${i}?ct=${encodeURIComponent(c)}`,h=yield fetch(d,{method:"PUT",headers:{Authorization:`Bearer ${r}`,"Content-Type":c},body:o});if(!h.ok){if(404===h.status||405===h.status)return null;throw new Error(`Failed to upload blob: ${h.status} ${h.statusText}`)}const f=yield h.json();return Object.assign({_bt:a,ref:f.ref,size:l},"Blob"===a?{ct:c}:{})})}function co(e,t,n){return s(this,arguments,void 0,function*(e,t,n,r=32768){const s={dirty:!1},i=yield lo(e,t,n,r,s);return s.dirty&&"object"==typeof i&&null!==i&&i.constructor===Object&&(i._hasBlobRefs=1),i})}function lo(e,t,n){return s(this,arguments,void 0,function*(e,t,n,r=32768,s={dirty:!1},i=new WeakSet){if(null==e)return e;if("string"==typeof e&&e.length>r&&r!==1/0){if(!1===to.get(t))return e;const r=new Blob([e],{type:"text/plain;charset=utf-8"}),i=yield oo(t,n,r);return null===i?(to.set(t,!1),e):(to.set(t,!0),s.dirty=!0,Object.assign(Object.assign({},i),{_bt:"string"}))}if(io(e)){if(!1===to.get(t))return e;const r=yield oo(t,n,e);return null===r?(to.set(t,!1),e):(to.set(t,!0),s.dirty=!0,r)}if("object"!=typeof e)return e;if(i.has(e))return e;if(i.add(e),Array.isArray(e)){const o=[];for(const c of e)o.push(yield lo(c,t,n,r,s,i));return o}const o=Object.getPrototypeOf(e);if(o!==Object.prototype&&null!==o)return e;const c={};for(const[o,l]of Object.entries(e))c[o]=yield lo(l,t,n,r,s,i);return c})}function ao(e,t,n){return s(this,arguments,void 0,function*(e,t,n,r=32768){switch(e.type){case"insert":case"upsert":{const s=yield Promise.all(e.values.map(e=>co(e,t,n,r)));return Object.assign(Object.assign({},e),{values:s})}case"update":{const s=yield Promise.all(e.changeSpecs.map(e=>co(e,t,n,r)));return Object.assign(Object.assign({},e),{changeSpecs:s})}case"modify":{const s=yield co(e.changeSpec,t,n,r);return Object.assign(Object.assign({},e),{changeSpec:s})}default:return e}})}function uo(e,t){switch(e.type){case"insert":case"upsert":return e.values.some(e=>ho(e,t));case"update":return e.changeSpecs.some(e=>ho(e,t));case"modify":return ho(e.changeSpec,t);default:return!1}}function ho(e,t,n=new WeakSet){if(null==e)return!1;if("string"==typeof e&&e.length>t&&t!==1/0)return!0;if(io(e))return!0;if("object"!=typeof e)return!1;if(n.has(e))return!1;if(n.add(e),Array.isArray(e))return e.some(e=>ho(e,t,n));const r=Object.getPrototypeOf(e);return(r===Object.prototype||null===r)&&Object.values(e).some(e=>ho(e,t,n))}function fo(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 xt(e),u={"Content-Type":"application/json",Accept:"application/octet-stream"};a&&(u.Authorization=`Bearer ${a.accessToken}`);const d=yield fetch(`${n}/y/download`,{body:ln.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){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()}}}(d),tt,function(r){return c(this,arguments,function*(){var i,c,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=Fi(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=l(r);!(i=(y=yield o(b.next())).done);m=!0){u=y.value,m=!1;const e=new Be(u);for(;Fe(e);)switch(ze(e)){case 1:yield o(g(!0)),d=He(e);break;case 2:yield o(g(!1)),h=He(e),f=He(e);break;case 3:{const t=Ge(e),n=We(e);p.push({k:t,u:n});break}}yield o(g(!1))}}catch(e){c={error:e}}finally{try{m||i||!(a=b.return)||(yield o(a.call(b)))}finally{if(c)throw c.error}}yield o(g(!0))}catch(e){throw e instanceof t.DexieError||(yield o(g(!1))),e}})})})}const po=new WeakMap;function go(e){var n,r,s,i;let o=po.get(e);if(o&&o.expiration>Date.now()+3e5)return Promise.resolve(o.accessToken);const c=e.cloud.currentUser.value;return c&&c.accessToken&&(null!==(r=null===(n=c.accessTokenExpiration)||void 0===n?void 0:n.getTime())&&void 0!==r?r:1/0)>Date.now()+3e5?(po.set(e,{accessToken:c.accessToken,expiration:null!==(i=null===(s=c.accessTokenExpiration)||void 0===s?void 0:s.getTime())&&void 0!==i?i:1/0}),Promise.resolve(c.accessToken)):(null==c?void 0:c.isLoggedIn)?t.ignoreTransaction(()=>xt(e).then(t=>{var n,r;return(null==t?void 0:t.accessToken)&&po.set(e,{accessToken:t.accessToken,expiration:null!==(r=null===(n=t.accessTokenExpiration)||void 0===n?void 0:n.getTime())&&void 0!==r?r:1/0}),(null==t?void 0:t.accessToken)||null})):Promise.resolve(null)}const yo="currentSyncWorker";function mo(e,t,n,r){return bo(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):gn&&(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 mo(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:gn?"error":"offline",error:new Error(""+(null==i?void 0:i.message)||i)}),Promise.reject(i))}))}function bo(e,t,n){return s(this,arguments,void 0,function*(e,t,n,{isInitialSync:r,cancelToken:i,justCheckIfNeeded:o,purpose:c}={isInitialSync:!1}){var l,a,u;if(!(null===(l=e.cloud.options)||void 0===l?void 0:l.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:d}=t,h=yield e.getCurrentUser(),f=h.isLoggedIn?ot(e):[],p=f.map(t=>e.table(Qt(t.name))),g=yield e.getPersistedSyncState(),y=h.isLoggedIn,m=y?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return ot(e).filter(e=>!n.includes(e.name))}(e,g):[];pn(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!==Ot.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!==Ot.userId||(e.owner=t.userId)}):yield n.toCollection().modify(e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==Ot.userId||(e.owner=t.userId),e.realmId&&e.realmId!==Ot.userId||(e.realmId=t.userId))}))})}(m,h,null==g?void 0:g.realms)})),pn(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=>f.some(t=>t.name===e.tableName));let o=yield tn(p,e);const c=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(_n),c=(null==o?void 0:o.unsentFrom)||1,l=(null==o?void 0:o.receivedUntil)||0,a=Math.min(c,l+1),u=yield kn(i,a);u.length>0&&(r[i.name]=u[u.length-1].i);const d={};for(const e of u){const t=!(1&~(e.f||0));if(t&&e.i<c)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 c=1===i.length?i[0]:us(i);if(r)n.push({type:"u-c",table:s.name,prop:t.prop,k:e,u:c,i:o});else{const r=ls(c);n.push({type:"sv",table:s.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}})}(e,f);if(pn(i),b){const e=[...(null==g?void 0:g.realms)||[],...(null==g?void 0:g.inviteRealms)||[]],l=yield function(e,t,n,r){return s(this,void 0,void 0,function*(){const i=`upload-${nn(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],c=(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)}),l=yield c.toArray();if(l.length>0){const n={type:"upsert",values:l,keys:l.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,h,n,e);return pn(i),o=o.concat(l),[o,t,r,c]}return[o,t,r,c]})),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"===c&&!x)return!1;const E=mn(v,null==w?void 0:w.latestRevisions),C=(null==w?void 0:w.clientIdentity)||B(16);let A=v;const I=null!==(u=null===(a=e.cloud.options)||void 0===a?void 0:a.maxStringLength)&&void 0!==u?u:32768,O=function(e,t=32768){for(const n of e)for(const e of n.muts)if(uo(e,t))return!0;return!1}(v,I);O&&(A=yield function(e,t,n){return s(this,arguments,void 0,function*(e,t,n,r=32768){const s=[];for(const i of e){const e=[];for(const s of i.muts){const i=yield ao(s,t,n,r);e.push(i)}s.push({table:i.table,muts:e})}return s})}(v,d,()=>go(e),I)),pn(i);const D=yield fn(A,k,w,_,e,d,n,C,h),{done:j,newSyncState:T}=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))D.schema[e]&&(n[e]=D.schema[e]);yield e.$syncState.put(n,"schema");const r=yield tn(p,e,{since:E});for(const t of p){const n=Xt(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()])}mn(r,E),yield yn(e,n,E,D.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:[],c=new Set(t.realms),l=new Set(t.realms.concat(t.inviteRealms));for(const e of i)c.has(e)||(s.add(e),l.has(e)||r.add(e));for(const e of o.concat(i))l.has(e)||r.add(e);if(r.size>0||s.size>0){const t=ot(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,D,i);const o=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:C};y&&(o.syncedTables=f.map(e=>e.name).concat(m.map(e=>e.name))),o.latestRevisions=E,o.remoteDbId=D.dbId,o.initiallySynced=!0,o.realms=D.realms,o.inviteRealms=D.inviteRealms,o.serverRevision=D.serverRevision,o.yServerRevision=D.serverRevision,o.timestamp=new Date,delete o.error;const c=vo(D.changes,r);if(yield wn(c,e),D.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:r}=yield eo(D.yMessages,e);r&&(o.yServerRevision=r),yield function(e,t,n){return s(this,void 0,void 0,function*(){var r,i,o,c,l;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!==(l=null!==(c=null==t?void 0:t.receivedUntil)&&void 0!==c?c:(yield n.table(e).where("i").between(1,1/0).reverse().limit(1).primaryKeys())[0])&&void 0!==l?l:0;yield n.transaction("rw",e,()=>s(this,void 0,void 0,function*(){const t=yield n.table(e).get(_n);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:_n,unsentFrom:r,receivedUntil:i})}))}})}(S,t,e),n&&(o.yDownloadedRealms={})}return e.$syncState.put(o,"syncState"),{done:0===r.length,newSyncState:o}}));if(!j)return yield hn(e),yield bo(e,t,n,{isInitialSync:r,cancelToken:i});const U=Object.values(n).some(e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length}),P=!!D.yMessages;if(U&&P)try{yield fo(e,d,T)}catch(e){}return e.syncCompleteEvent.next(),!1})}function vo(e,t){const n={};K(n,e);const r={};return K(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))M(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 wo(e){const i=[],o=new n.BehaviorSubject(!0),c=new n.BehaviorSubject(null);let l=!1,a=new Array(10).fill(0);return c.subscribe(()=>s(this,void 0,void 0,function*(){if(!l&&i.length>0){l=!0,a.shift(),a.push(Date.now()),o.next(!1);try{yield function(){return s(this,void 0,void 0,function*(){for(var o,c,l,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 Ct(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===(c=null==i?void 0:i.inviteRealms)||void 0===c?void 0:c.includes(h.realm))||(yield e.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(l=null==i?void 0:i.realms)||void 0===l?void 0:l.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)){ht(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!1;if(h.baseRev!==s.serverRevision)return"string"!=typeof h.baseRev||"bigint"!=typeof s.serverRevision&&"object"!=typeof s.serverRevision||ht(e,"pull"),!1;if((yield t.waitFor(Gt(s)))!==h.realmSetHash)return ht(e,"pull"),!1;let o=[];if(i.isLoggedIn){const t=ot(e).map(t=>e.table(Qt(t.name)));o=yield tn(t,e)}if(h.changes.length>0){const t=vo(h.changes,o);yield wn(t,e)}return s.latestRevisions=mn(o,s.latestRevisions),s.serverRevision=h.newRev,yield yn(e,r,s.latestRevisions,h.newRev),yield e.$syncState.put(s,"syncState"),!0})))&&h.changes.length>0&&e.syncCompleteEvent.next();break}}catch(e){}}})}()}finally{a[a.length-1]-a[0]<1e4&&(yield new Promise(e=>setTimeout(e,1e3))),l=!1,o.next(!0)}}})),{enqueue:function(e){i.push(e),c.next(null)},readyToServe:o}}class _o{constructor(e){this.inFlight=new Map,this.db=e}download(e,t){let n=this.inFlight.get(e.ref);return n||(n=go(this.db).then(n=>function(e,t,n){return s(this,void 0,void 0,function*(){const r=`${t}/blob/${e.ref}`,s={};n&&(s.Authorization=`Bearer ${n}`);const i=yield fetch(r,{headers:s});if(!i.ok)throw new Error(`Failed to download blob ${e.ref}: ${i.status} ${i.statusText}`);const o=yield i.arrayBuffer();return new Uint8Array(o)})}(e,t,n)).finally(()=>this.inFlight.delete(e.ref)),this.inFlight.set(e.ref,n)),n}}const ko=new WeakMap,So={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let xo=0;function Eo(e){"vip"in e&&(e=e.vip);let t=ko.get(e);if(!t){const r=new n.Subject;let s=new Yt(`syncstatechanged-${e.name}`),i=new Yt(`synccomplete-${e.name}`);r.id=++xo;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},get cloud(){return 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 c={getCurrentUser:()=>t.$logins.toArray().then(e=>e.find(e=>e.isLoggedIn)||Ot),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=Co(n.schema.primKey.keyPath));return e}),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){s=new Yt(`syncstatechanged-${e.name}`),i=new Yt(`synccomplete-${e.name}`)}};Object.assign(t,c),t.messageConsumer=wo(t),t.messageProducer=new n.Subject,t.blobDownloadTracker=new _o(t),ko.set(e,t)}return t}function Co(e){return"string"==typeof e?e:e?"["+[].join.call(e,"+")+"]":""}const Ao="undefined"!=typeof InstallTrigger,Io="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),Oo=Io?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,Do=Io&&Oo<=605||Ao,jo="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:To}={};function Uo(e){return To.call(e).slice(8,-1)}function Po(e,t){var n;return"delete"===t.type?t.keys:(null===(n=t.keys)||void 0===n?void 0:n.slice())||t.values.map(e.extractKey)}function Lo(e,t){return(1&t?e[0].toUpperCase():e[0].toLowerCase())+(2&t?e[1].toUpperCase():e[1].toLowerCase())+(4&t?e[2].toUpperCase():e[2].toLowerCase())}const Ro=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;function $o(e){return e>="A"&&e<="Z"}let Mo=0;function Bo(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),s=Date.now();Mo>=s?++Mo:Mo=s,r[0]=Mo/1099511627776,r[1]=Mo/4294967296,r[2]=Mo/16777216,r[3]=Mo/65536,r[4]=Mo/256,r[5]=Mo;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+C(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 c=n.trans;if("versionchange"===c.mode&&(c.disableChangeTracking=!0,c.disableAccessControl=!0),c.disableChangeTracking)return s.mutate(n);if("add"===n.type||"put"===n.type){const c=null===(i=e.cloud.schema)||void 0===i?void 0:i[r];if(null==c?void 0:c.generatedGlobalId){if((null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!e.initiallySynced){const e=Po(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 c=Po(s.schema.primaryKey,n);return c.forEach((l,a)=>{if(void 0===l){const r=n.values[a].realmId||e.cloud.currentUserId,l=r.substr(r.length-3);c[a]=Bo(i,l),s.schema.primaryKey.outbound||(o||(o=n.values.slice()),o[a]=t.deepClone(o[a]),t.setByKeyPath(o[a],s.schema.primaryKey.keyPath,c[a]))}else if("string"!=typeof l||!l.startsWith(i)&&!l.startsWith("#"+i))throw new t.ConstraintError(`The ID "${l}" 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:c,values:o||n.values}))}(n,c.idPrefix)}if(null==c?void 0:c.markedForSync){Po(s.schema.primaryKey,n).forEach((e,n)=>{if(!F(e)){const n=Array.isArray(e)?e.map(Uo).join(","):Uo(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 Fo=0;function Wo(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 zo(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 Ko=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 Ho({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=>Qt(e));i=r.transaction([...t,...e],s)}else i=r.transaction(t,s);if("readwrite"===s){i.txid=nn(16),i.opCount=0,i.currentUser=e.value,Ko.value.add(i),Ko.next(Ko.value);const t=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",t),i.removeEventListener("abort",t),Ko.value.delete(i),Ko.next(Ko.value)},r=()=>{i.mutationsAdded&&!Vo(n)&&ht(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,c=o.get(e);return c?function(e){const t="$lock"+ ++Fo;return Object.assign(Object.assign({},e),{count:Wo(e.count,t),get:Wo(e.get,t),getMany:Wo(e.getMany,t),openCursor:Wo(e.openCursor,t),query:Wo(e.query,t),mutate:zo(e.mutate,t)})}(Object.assign(Object.assign({},s),{mutate:t=>{var r,o,c;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===(c=a.currentUser)||void 0===c?void 0:c.isLoggedIn)?"deleteRange"===t.type?s.query({query:{range:t.range,index:i.primaryKey},trans:t.trans,values:!1}).then(e=>l({type:"delete",keys:e.result,trans:t.trans,criteria:{index:null,range:t.range}})):l(t):s.mutate(t):s.mutate(t)}})):s;function l(r){var o,l;const a=r.trans,u=null===(l=null===(o=n.cloud.options)||void 0===o?void 0:o.unsyncedProperties)||void 0===l?void 0:l[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 l="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&&(l=l.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=l.length;n<s;++n)r.hasKey(l[n])&&(e.push(l[n]),t.push(y[n]));l=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:l,criteria:_,txid:d,userId:h}:"add"===r.type?{type:"insert",ts:w,opNo:p,keys:l,txid:d,userId:h,values:y}:v&&b?{type:"upsert",ts:w,opNo:p,keys:l,values:y,changeSpecs:b.changeSpecs.filter((e,t)=>!o[t]),txid:d,userId:h}:_&&m?{type:"modify",ts:w,opNo:p,keys:l,criteria:_,changeSpec:m,txid:d,userId:h}:m?{type:"update",ts:w,opNo:p,keys:l,changeSpecs:l.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:l,values:y,txid:d,userId:h};return"isAdditionalChunk"in r&&r.isAdditionalChunk&&(k.isAdditionalChunk=!0),l.length>0||_?c.mutate({type:"add",trans:a,values:[k]}).then(()=>(a.mutationsAdded=!0,e)):e})}}})}}}class Jo{constructor(e){this.queue=[],this.isProcessing=!1,this.db=e}saveBlobs(e,t,n){this.queue.push({tableName:e,primaryKey:t,resolvedBlobs:n}),this.startConsumer()}startConsumer(){this.isProcessing||(this.isProcessing=!0,setTimeout(()=>{this.processQueue()},0))}processQueue(){const e=this.queue.shift();e?this.db.transaction("rw",e.tableName,n=>{const r=n.idbtrans;r.disableChangeTracking=!0,r.disableAccessControl=!0,r.disableBlobResolve=!0;const s={};for(const t of e.resolvedBlobs)s[t.keyPath]=t.data;n.table(e.tableName).update(e.primaryKey,n=>{for(const r of e.resolvedBlobs){const e=t.getByKeyPath(n,r.keyPath);if(void 0!==e&&nt(e)){if(e.ref!==r.ref)return;t.setByKeyPath(n,r.keyPath,r.data)}}delete n._hasBlobRefs})}).catch(e=>{}).finally(()=>this.processQueue()):this.isProcessing=!1}}function qo(e){return{stack:"dbcore",name:"blobResolve",level:2,create(n){const r=new Jo(e);return Object.assign(Object.assign({},n),{table(s){var i;if(!e.cloud)return n.table(s);const o=null===(i=e.cloud.options)||void 0===i?void 0:i.databaseUrl,c=n.table(s);return s.startsWith("$")?c:Object.assign(Object.assign({},c),{get(t){var n;return(null===(n=t.trans)||void 0===n?void 0:n.disableBlobResolve)?c.get(t):c.get(t).then(n=>n&&it(n)?Yo(c,t.trans,t.key,n,r,e):n)},getMany(n){var s;return(null===(s=n.trans)||void 0===s?void 0:s.disableBlobResolve)?c.getMany(n):c.getMany(n).then(s=>{const i=s.some(e=>e&&it(e));return i?t.Promise.all(s.map((t,s)=>t&&it(t)?Yo(c,n.trans,n.keys[s],t,r,e):t)):s})},query(n){var s;return(null===(s=n.trans)||void 0===s?void 0:s.disableBlobResolve)?c.query(n):c.query(n).then(s=>{if(!s.result||!Array.isArray(s.result))return s;const i=s.result.some(e=>e&&it(e));return i?t.Promise.all(s.result.map(t=>t&&it(t)?Yo(c,n.trans,void 0,t,r,e):t)).then(e=>Object.assign(Object.assign({},s),{result:e})):s})},openCursor(t){var n;return(null===(n=t.trans)||void 0===n?void 0:n.disableBlobResolve)?c.openCursor(t):c.openCursor(t).then(n=>n&&t.values&&o?function(e,t,n,r){const s=Object.create(e,{value:{value:e.value,enumerable:!0,writable:!0},start:{value:i=>e.start(()=>{const o=e.value;if(!o||!it(o))return s.value=o,void i();Yo(t,e.trans,e.primaryKey,o,n,r,!0).then(e=>{s.value=e,i()},e=>{s.value=o,i()})})}});return s}(n,c,r,e):n)}})}})}}}function Yo(e,n,r,s,i,o,c=!1){var l;try{const a=t.currentTransaction,u="readonly"===(null==a?void 0:a.mode),d=!0===(null==a?void 0:a.explicit),h=a&&!(u&&!d&&!c),f=(null===(l=o.cloud.options)||void 0===l?void 0:l.databaseUrl)||"",p=[],g=st(s,f,p,"",new WeakMap,o.blobDownloadTracker);return(h?t.waitFor(g):t.Promise.resolve(g)).then(o=>{const c=e.schema.primaryKey,l=void 0!==r?r:c.keyPath?t.getByKeyPath(s,c.keyPath):void 0;return void 0!==l&&(u?i.saveBlobs(e.name,l,p):e.mutate({type:"put",keys:[l],values:[o],trans:n}).catch(e=>{})),o}).catch(e=>s)}catch(e){return t.Promise.resolve(s)}}function Go(e,t){return function(n,r){var s;const i=Object.assign(Object.assign({},So),n);Object.keys(So).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=So[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(So[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={}),c=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)(Ro.test(e[t])||$o(e[t]))&&(n+=e[t].toLowerCase());for(;t.has(n);){if(/\d/g.test(n)){if(n=n.substr(0,n.length-1)+(n[n.length-1]+1),!(n.length>3))continue;n=n.substr(0,3)}else if(n.length<3){n+="2";continue}let e=1,r=n;for(;t.has(r)&&e<8;)r=Lo(n,e),++e;if(e<8)n=r;else{let e=n.charCodeAt(2)+1&127;n=n.substr(0,2)+String.fromCharCode(e)}}return n}(e,c),c.add(r.idPrefix)),/^\$/.test(e)||(i[`$${e}_mutations`]="++rev",r.markedForSync=!0,i[e].includes("_hasBlobRefs")||(i[e]+=",_hasBlobRefs")),r.deleted&&(r.deleted=!1)):(r.deleted=!0,r.markedForSync=!1,i[`$${e}_mutations`]=null)});const l=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 l}}function Qo(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,n):n()}const Xo=new n.BehaviorSubject(!0),Zo=new n.BehaviorSubject(!0);Xo.pipe(r.switchMap(e=>e?n.of(!0):n.of(!1).pipe(r.delay(2e4))),r.distinctUntilChanged()).subscribe(Zo);const ec="undefined"!=typeof document?n.fromEvent(document,"visibilitychange"):n.of({}),tc=ec.pipe(r.filter(()=>"hidden"===document.visibilityState)),nc=ec.pipe(r.filter(()=>"visible"===document.visibilityState)),rc="undefined"!=typeof window?n.merge(nc,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),tc,rc).pipe(r.map(()=>"visible"===document.visibilityState),r.tap(e=>{Xo.value!==e&&Xo.next(e)}),r.switchMap(e=>e?n.of(0).pipe(r.delay(16e4),r.tap(()=>Xo.next(!1))):n.of(0))).subscribe(()=>{});class sc extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}const ic=new WeakMap,oc=3e4;class cc extends An{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=Tn();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&&oc<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&lc(this,t,"timeout")},V(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:Tn()});const i=[],o=[],c=[],l=[];null===e?l.push(t):null==s?null!=e&&i.push(t):(o.push(t),Jn(s,e)||c.push(t)),(i.length>0||c.length>0||l.length>0)&&this.emit("change",[{added:i,updated:c,removed:l},"local"]),this.emit("update",[{added:i,updated:o,removed:l},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}}const lc=(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:Tn()})}r.push(s)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},ac=new WeakMap;function uc(e){let t=ac.get(e);return t||(t=new n.Subject,ac.set(e,t)),t}class dc extends n.Observable{constructor(e,t,n,r,s,i,o,c){super(l=>new fc(e,t,n,r,s,c,l,i,o))}}let hc=0;class fc extends n.Subscription{constructor(e,t,n,r,s,i,o,c,l){super(()=>this.teardown()),this.id=++hc,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=c,this.webSocketStatus=l,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 sc);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","3"),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?ln.parse(e.data):function(e){const t=new Be(e),n=He(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:He(t)};const r=He(t),s=He(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:s,i:Number(qe(t))};default:{const e=Ge(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:We(t)};case"doc-open":return{type:n,table:r,prop:s,k:e,serverRev:Ge(t),sv:Ge(t)};case"sv":return{type:n,table:r,prop:s,k:e,sv:We(t)};case"u-c":return{type:n,table:r,prop:s,k:e,u:We(t),i:Number(qe(t))};case"u-s":return{type:n,table:r,prop:s,k:e,u:We(t),r:t.pos<t.arr.length&&He(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=Zi.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>ic.get(e))(e);n&&((e,t,n)=>{const r=Ne(t),s=Tn(),i=[],o=[],c=[],l=[],a=Ke(r);for(let t=0;t<a;t++){const t=Ke(r);let n=Ke(r);const a=JSON.parse(He(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?l.push(t):null!==a&&(Jn(a,d)||c.push(t),o.push(t)))}(i.length>0||c.length>0||l.length>0)&&e.emit("change",[{added:i,updated:c,removed:l},n]),(i.length>0||o.length>0||l.length>0)&&e.emit("update",[{added:i,updated:o,removed:l},n])})(n,t.u,"server")}}else if("pong"===t.type);else if("doc-open"===t.type){const e=Zi.getDocCache(this.db.dx).find(t.table,t.k,t.prop);e&&uc(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?eo([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=Fi(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(_n,{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(ln.stringify(e))):null===(n=this.ws)||void 0===n||n.send(function(e){const t=new he;switch(_e(t,e.type),"table"in e&&_e(t,e.table),"prop"in e&&_e(t,e.prop),e.type){case"u-ack":case"u-reject":Ee(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":_e(t,e.yServerRev);break;default:switch(Ae(t,e.k),e.type){case"aware":Se(t,e.u);break;case"doc-open":Ae(t,e.serverRev),Ae(t,e.sv);break;case"doc-close":break;case"sv":Se(t,e.sv);break;case"u-c":Se(t,e.u),Ee(t,BigInt(e.i));break;case"u-s":Se(t,e.u),_e(t,e.r||"")}}return pe(t)}(e)))})),this.user.isLoggedIn&&!Vo(this.db)&&this.subscriptions.add(function(e){const r=en(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 c=e.table(o);return n.from(c.get(_n)).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 kn(c,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 pc extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function gc(e){return s(this,void 0,void 0,function*(){var e;yield(e=3e3,new Promise(t=>setTimeout(t,e))),yield n.firstValueFrom(rc)})}function yc(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 mo(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))})}const mc=new WeakMap;function bc(e,t,n,r){const i=mc.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 bc(e,t,n,r)})}}const o=function(){return s(this,void 0,void 0,function*(){try{yield hn(e),yield Qo(e,yo,()=>mo(e,t,n,r)),mc.delete(e)}catch(t){throw mc.delete(e),t}})}();return mc.set(e,{promise:o,pull:"push"!==(null==r?void 0:r.purpose)}),o}function vc(e,t,n){let r=null,s={cancelled:!1},i=0,o=0;function c(r=1){setTimeout(()=>{const h=l?"pull":"push";l=!1,a=!1,o=Date.now(),bc(e,t,n,{cancelToken:s,retryImmediatelyOnFetchError:!0,purpose:h}).then(()=>{if(s.cancelled)d();else if(l||a)return c();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]*St;i=Date.now()+e,o=0,setTimeout(()=>c(r+1),e)}else u=!1,i=0,o=0})},0)}let l=!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&&(l=!0),"push"===e&&(a=!0),u?i||o>0&&Date.now():(u=!0,c()))})(e||"pull")})},stop:d}}function wc(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var _c,kc,Sc,xc,Ec,Cc,Ac,Ic,Oc,Dc,jc,Tc={},Uc=[],Pc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Lc=Array.isArray;function Rc(e,t){for(var n in t)e[n]=t[n];return e}function $c(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Mc(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?_c.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 Bc(e,o,r,s,null)}function Bc(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?++Sc:s,__i:-1,__u:0};return null==s&&null!=kc.vnode&&kc.vnode(i),i}function Nc(e){return e.children}function Fc(e,t){this.props=e,this.context=t}function Wc(e,t){if(null==t)return e.__?Wc(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?Wc(e):null}function zc(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 zc(e)}}function Kc(e){(!e.__d&&(e.__d=!0)&&xc.push(e)&&!Vc.__r++||Ec!=kc.debounceRendering)&&((Ec=kc.debounceRendering)||Cc)(Vc)}function Vc(){for(var e,t,n,r,s,i,o,c=1;xc.length;)xc.length>c&&xc.sort(Ac),e=xc.shift(),c=xc.length,e.__d&&(n=void 0,r=void 0,s=(r=(t=e).__v).__e,i=[],o=[],t.__P&&((n=Rc({},r)).__v=r.__v+1,kc.vnode&&kc.vnode(n),Xc(t.__P,n,r,t.__n,t.__P.namespaceURI,32&r.__u?[s]:null,i,null==s?Wc(r):s,!!(32&r.__u),o),n.__v=r.__v,n.__.__k[n.__i]=n,el(i,n,o),r.__e=r.__=null,n.__e!=s&&zc(n)));Vc.__r=0}function Hc(e,t,n,r,s,i,o,c,l,a,u){var d,h,f,p,g,y,m,b=r&&r.__k||Uc,v=t.length;for(l=function(e,t,n,r,s){var i,o,c,l,a,u=n.length,d=u,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]=Bc(null,o,null,null,null):Lc(o)?o=e.__k[i]=Bc(Nc,{children:o},null,null,null):null==o.constructor&&o.__b>0?o=e.__k[i]=Bc(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[i]=o,l=i+h,o.__=e,o.__b=e.__b+1,-1!=(a=o.__i=qc(o,n,l,d))&&(d--,(c=n[a])&&(c.__u|=2)),null==c||null==c.__v?(-1==a&&(s>u?h--:s<u&&h++),"function"!=typeof o.type&&(o.__u|=4)):a!=l&&(a==l-1?h--:a==l+1?h++:(a>l?h--:h++,o.__u|=4))):e.__k[i]=null;if(d)for(i=0;i<u;i++)null!=(c=n[i])&&!(2&c.__u)&&(c.__e==r&&(r=Wc(c)),sl(c,c));return r}(n,t,b,l,v),d=0;d<v;d++)null!=(f=n.__k[d])&&(h=-1==f.__i?Tc:b[f.__i]||Tc,f.__i=d,y=Xc(e,f,h,s,i,o,c,l,a,u),p=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&rl(h.ref,null,f),u.push(f.ref,f.__c||p,f)),null==g&&null!=p&&(g=p),(m=!!(4&f.__u))||h.__k===f.__k?l=Jc(f,l,e,m):"function"==typeof f.type&&void 0!==y?l=y:p&&(l=p.nextSibling),f.__u&=-7);return n.__e=g,l}function Jc(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=Jc(s[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=Wc(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function qc(e,t,n,r){var s,i,o,c=e.key,l=e.type,a=t[n],u=null!=a&&!(2&a.__u);if(null===a&&null==c||u&&c==a.key&&l==a.type)return n;if(r>(u?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)&&c==a.key&&l==a.type)return o;return-1}function Yc(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||Pc.test(t)?n:n+"px"}function Gc(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||Yc(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Yc(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])i=t!=(t=t.replace(Ic,"$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=Oc,e.addEventListener(t,i?jc:Dc,i)):e.removeEventListener(t,i?jc:Dc,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 Qc(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t.t)t.t=Oc++;else if(t.t<n.u)return;return n(kc.event?kc.event(t):t)}}}function Xc(e,t,n,r,s,i,o,c,l,a){var u,d,h,f,p,g,y,m,b,v,w,_,k,S,x,E,C,A=t.type;if(null!=t.constructor)return null;128&n.__u&&(l=!!(32&n.__u),i=[c=t.__e=n.__e]),(u=kc.__b)&&u(t);e:if("function"==typeof A)try{if(m=t.props,b="prototype"in A&&A.prototype.render,v=(u=A.contextType)&&r[u.__c],w=u?v?v.props.value:u.__:r,n.__c?y=(d=t.__c=n.__c).__=d.__E:(b?t.__c=d=new A(m,w):(t.__c=d=new Fc(m,w),d.constructor=A,d.render=il),v&&v.sub(d),d.state||(d.state={}),d.__n=r,h=d.__d=!0,d.__h=[],d._sb=[]),b&&null==d.__s&&(d.__s=d.state),b&&null!=A.getDerivedStateFromProps&&(d.__s==d.state&&(d.__s=Rc({},d.__s)),Rc(d.__s,A.getDerivedStateFromProps(m,d.__s))),f=d.props,p=d.state,d.__v=t,h)b&&null==A.getDerivedStateFromProps&&null!=d.componentWillMount&&d.componentWillMount(),b&&null!=d.componentDidMount&&d.__h.push(d.componentDidMount);else{if(b&&null==A.getDerivedStateFromProps&&m!==f&&null!=d.componentWillReceiveProps&&d.componentWillReceiveProps(m,w),t.__v==n.__v||!d.__e&&null!=d.shouldComponentUpdate&&!1===d.shouldComponentUpdate(m,d.__s,w)){for(t.__v!=n.__v&&(d.props=m,d.state=d.__s,d.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(e){e&&(e.__=t)}),_=0;_<d._sb.length;_++)d.__h.push(d._sb[_]);d._sb=[],d.__h.length&&o.push(d);break e}null!=d.componentWillUpdate&&d.componentWillUpdate(m,d.__s,w),b&&null!=d.componentDidUpdate&&d.__h.push(function(){d.componentDidUpdate(f,p,g)})}if(d.context=w,d.props=m,d.__P=e,d.__e=!1,k=kc.__r,S=0,b){for(d.state=d.__s,d.__d=!1,k&&k(t),u=d.render(d.props,d.state,d.context),x=0;x<d._sb.length;x++)d.__h.push(d._sb[x]);d._sb=[]}else do{d.__d=!1,k&&k(t),u=d.render(d.props,d.state,d.context),d.state=d.__s}while(d.__d&&++S<25);d.state=d.__s,null!=d.getChildContext&&(r=Rc(Rc({},r),d.getChildContext())),b&&!h&&null!=d.getSnapshotBeforeUpdate&&(g=d.getSnapshotBeforeUpdate(f,p)),E=u,null!=u&&u.type===Nc&&null==u.key&&(E=tl(u.props.children)),c=Hc(e,Lc(E)?E:[E],t,n,r,s,i,o,c,l,a),d.base=t.__e,t.__u&=-161,d.__h.length&&o.push(d),y&&(d.__E=d.__=null)}catch(e){if(t.__v=null,l||null!=i)if(e.then){for(t.__u|=l?160:128;c&&8==c.nodeType&&c.nextSibling;)c=c.nextSibling;i[i.indexOf(c)]=null,t.__e=c}else{for(C=i.length;C--;)$c(i[C]);Zc(t)}else t.__e=n.__e,t.__k=n.__k,e.then||Zc(t);kc.__e(e,t,n)}else null==i&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=nl(n.__e,t,n,r,s,i,o,l,a);return(u=kc.diffed)&&u(t),128&t.__u?void 0:c}function Zc(e){e&&e.__c&&(e.__c.__e=!0),e&&e.__k&&e.__k.forEach(Zc)}function el(e,t,n){for(var r=0;r<n.length;r++)rl(n[r],n[++r],n[++r]);kc.__c&&kc.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){kc.__e(e,t.__v)}})}function tl(e){return"object"!=typeof e||null==e||e.__b&&e.__b>0?e:Lc(e)?e.map(tl):Rc({},e)}function nl(e,t,n,r,s,i,o,c,l){var a,u,d,h,f,p,g,y=n.props||Tc,m=t.props,b=t.type;if("svg"==b?s="http://www.w3.org/2000/svg":"math"==b?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==!!b&&(b?f.localName==b:3==f.nodeType)){e=f,i[a]=null;break}if(null==e){if(null==b)return document.createTextNode(m);e=document.createElementNS(s,b,m.is&&m),c&&(kc.__m&&kc.__m(t,i),c=!1),i=null}if(null==b)y===m||c&&e.data==m||(e.data=m);else{if(i=i&&_c.call(e.childNodes),!c&&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)d=f;else if(!(a in m)){if("value"==a&&"defaultValue"in m||"checked"==a&&"defaultChecked"in m)continue;Gc(e,a,null,f,s)}for(a in m)f=m[a],"children"==a?h=f:"dangerouslySetInnerHTML"==a?u=f:"value"==a?p=f:"checked"==a?g=f:c&&"function"!=typeof f||y[a]===f||Gc(e,a,f,y[a],s);if(u)c||d&&(u.__html==d.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(d&&(e.innerHTML=""),Hc("template"==t.type?e.content:e,Lc(h)?h:[h],t,n,r,"foreignObject"==b?"http://www.w3.org/1999/xhtml":s,i,o,i?i[0]:n.__k&&Wc(n,0),c,l),null!=i)for(a=i.length;a--;)$c(i[a]);c||(a="value","progress"==b&&null==p?e.removeAttribute("value"):null!=p&&(p!==e[a]||"progress"==b&&!p||"option"==b&&p!=y[a])&&Gc(e,a,p,y[a],s),a="checked",null!=g&&g!=e[a]&&Gc(e,a,g,y[a],s))}return e}function rl(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){kc.__e(e,n)}}function sl(e,t,n){var r,s;if(kc.unmount&&kc.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||rl(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){kc.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(s=0;s<r.length;s++)r[s]&&sl(r[s],t,n||"function"!=typeof e.type);n||$c(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),kc.__&&kc.__(e,t),r=!1?null:t.__k,s=[],i=[],Xc(t,e=t.__k=Mc(Nc,null,[e]),r||Tc,Tc,t.namespaceURI,r?null:t.firstChild?_c.call(t.childNodes):null,s,r?r.__e:t.firstChild,false,i),el(s,e,i)}_c=Uc.slice,kc={__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}},Sc=0,Fc.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=Rc({},this.state),"function"==typeof e&&(e=e(Rc({},n),this.props)),e&&Rc(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),Kc(this))},Fc.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Kc(this))},Fc.prototype.render=Nc,xc=[],Cc="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ac=function(e,t){return e.__v.__b-t.__v.__b},Vc.__r=0,Ic=/(PointerCapture)$|Capture$/i,Oc=0,Dc=Qc(!1),jc=Qc(!0);const cl={Alert:{error:{color:"red",fontWeight:"bold"},warning:{color:"#f80",fontWeight:"bold"},info:{color:"black"}},Darken:{position:"fixed",top:0,left:0,opacity:.5,backgroundColor:"#000",width:"100vw",height:"100vh",zIndex:150,webkitBackdropFilter:"blur(2px)",backdropFilter:"blur(2px)"},DialogOuter:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:150,alignItems:"center",display:"flex",justifyContent:"center",padding:"16px",boxSizing:"border-box"},DialogInner:{position:"relative",color:"#222",backgroundColor:"#fff",padding:"24px",marginBottom:"2em",maxWidth:"400px",width:"100%",maxHeight:"90%",overflowY:"auto",border:"3px solid #3d3d5d",borderRadius:"8px",boxShadow:"0 0 80px 10px #666",fontFamily:"sans-serif",boxSizing:"border-box"},Input:{height:"35px",width:"100%",maxWidth:"100%",borderColor:"#ccf4",outline:"none",fontSize:"16px",padding:"8px",boxSizing:"border-box",backgroundColor:"#f9f9f9",borderRadius:"4px",border:"1px solid #ccc",marginTop:"6px",fontFamily:"inherit"},Button:{padding:"10px 20px",margin:"0 4px",border:"1px solid #d1d5db",borderRadius:"6px",backgroundColor:"#ffffff",cursor:"pointer",fontSize:"14px",fontWeight:"500",color:"#374151",transition:"all 0.2s ease"},PrimaryButton:{padding:"10px 20px",margin:"0 4px",border:"1px solid #3b82f6",borderRadius:"6px",backgroundColor:"#3b82f6",color:"white",cursor:"pointer",fontSize:"14px",fontWeight:"500",transition:"all 0.2s ease"},ButtonsDiv:{display:"flex",justifyContent:"flex-end",gap:"12px",marginTop:"24px",paddingTop:"20px"},Label:{display:"block",marginBottom:"12px",fontSize:"14px",fontWeight:"500",color:"#333"},WindowHeader:{margin:"0 0 20px 0",fontSize:"18px",fontWeight:"600",color:"#333",borderBottom:"1px solid #eee",paddingBottom:"10px"},ProviderButton:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",padding:"12px 16px",marginBottom:"10px",border:"1px solid #d1d5db",borderRadius:"6px",backgroundColor:"#ffffff",cursor:"pointer",fontSize:"14px",fontWeight:"500",color:"#374151",transition:"all 0.2s ease",gap:"12px"},ProviderButtonIcon:{width:"20px",height:"20px",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},ProviderButtonText:{flex:1,textAlign:"left"},ProviderGoogle:{backgroundColor:"#ffffff",border:"1px solid #dadce0",color:"#3c4043"},ProviderGitHub:{backgroundColor:"#ffffff",border:"1px solid #dadce0",color:"#181717"},ProviderMicrosoft:{backgroundColor:"#ffffff",border:"1px solid #dadce0",color:"#5e5e5e"},ProviderApple:{backgroundColor:"#000000",border:"1px solid #000000",color:"#ffffff"},ProviderCustom:{backgroundColor:"#ffffff",border:"1px solid #dadce0",color:"#181717"},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"},CopyButton:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"4px 10px",marginTop:"8px",border:"1px solid #d1d5db",borderRadius:"4px",backgroundColor:"#f9fafb",cursor:"pointer",fontSize:"12px",fontWeight:"500",color:"#374151",transition:"all 0.15s ease",fontFamily:"monospace"},CopyButtonCopied:{display:"inline-flex",alignItems:"center",gap:"4px",padding:"4px 10px",marginTop:"8px",border:"1px solid #22c55e",borderRadius:"4px",backgroundColor:"#f0fdf4",cursor:"default",fontSize:"12px",fontWeight:"500",color:"#16a34a",fontFamily:"monospace"}};function ll({children:e,className:t}){return Mc("div",{className:`dexie-dialog ${t||""}`},Mc("div",{style:cl.Darken}),Mc("div",{style:cl.DialogOuter},Mc("div",{style:cl.DialogInner},e)))}var al,ul,dl,hl,fl=0,pl=[],gl=kc,yl=gl.__b,ml=gl.__r,bl=gl.diffed,vl=gl.__c,wl=gl.unmount,_l=gl.__;function kl(e,t){gl.__h&&gl.__h(ul,e,fl||t),fl=0;var n=ul.__H||(ul.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Sl(e){return fl=1,function(e,t){var n=kl(al++,2);if(n.t=e,!n.__c&&(n.__=[Tl(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=ul,!ul.__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};ul.__f=!0;var s=ul.shouldComponentUpdate,i=ul.componentWillUpdate;ul.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)},ul.shouldComponentUpdate=r}return n.__N||n.__}(Tl,e)}function xl(e,t){var n=kl(al++,4);!gl.__s&&jl(n.__H,t)&&(n.__=e,n.u=t,ul.__h.push(n))}function El(e){return fl=5,function(e,t){var n=kl(al++,7);return jl(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}(function(){return{current:e}},[])}function Cl(){for(var e;e=pl.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Ol),e.__H.__h.forEach(Dl),e.__H.__h=[]}catch(t){e.__H.__h=[],gl.__e(t,e.__v)}}gl.__b=function(e){ul=null,yl&&yl(e)},gl.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),_l&&_l(e,t)},gl.__r=function(e){ml&&ml(e),al=0;var t=(ul=e.__c).__H;t&&(dl===ul?(t.__h=[],ul.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.forEach(Ol),t.__h.forEach(Dl),t.__h=[],al=0)),dl=ul},gl.diffed=function(e){bl&&bl(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==pl.push(t)&&hl===gl.requestAnimationFrame||((hl=gl.requestAnimationFrame)||Il)(Cl)),t.__H.__.forEach(function(e){e.u&&(e.__H=e.u),e.u=void 0})),dl=ul=null},gl.__c=function(e,t){t.some(function(e){try{e.__h.forEach(Ol),e.__h=e.__h.filter(function(e){return!e.__||Dl(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],gl.__e(n,e.__v)}}),vl&&vl(e,t)},gl.unmount=function(e){wl&&wl(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(e){try{Ol(e)}catch(e){t=e}}),n.__H=void 0,t&&gl.__e(t,n.__v))};var Al="function"==typeof requestAnimationFrame;function Il(e){var t,n=function(){clearTimeout(r),Al&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Al&&(t=requestAnimationFrame(n))}function Ol(e){var t=ul,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),ul=t}function Dl(e){var t=ul;e.__c=e.__(),ul=t}function jl(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Tl(e,t){return"function"==typeof t?t(e):t}function Ul({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,e=>n[e.substring(1,e.length-1)])}function Pl({option:e,onClick:t}){const{displayName:n,iconUrl:r,styleHint:s}=e,i=function(e){const t=Object.assign({},cl.ProviderButton);if(!e)return t;switch(e){case"google":return Object.assign(Object.assign({},t),cl.ProviderGoogle);case"github":return Object.assign(Object.assign({},t),cl.ProviderGitHub);case"microsoft":return Object.assign(Object.assign({},t),cl.ProviderMicrosoft);case"apple":return Object.assign(Object.assign({},t),cl.ProviderApple);case"otp":return Object.assign({},cl.OtpButton);case"custom-oauth2":return Object.assign(Object.assign({},t),cl.ProviderCustom);default:return t}}(s);return Mc("button",{type:"button",style:i,onClick:t,class:"dxc-option-btn"+(s?` dxc-option-${s}`:""),"aria-label":n},r&&Mc("img",{src:r,alt:"",style:cl.ProviderButtonIcon,"aria-hidden":"true"}),Mc("span",{style:cl.ProviderButtonText},n))}function Ll(){return Mc("div",{style:cl.Divider},Mc("div",{style:cl.DividerLine}),Mc("span",{style:cl.DividerText},"or"),Mc("div",{style:cl.DividerLine}))}function Rl({title:e,alerts:t,fields:n,options:r,submitLabel:s,cancelLabel:i,onCancel:o,onSubmit:c}){const[l,a]=Sl({}),u=El(null);xl(()=>{var e;return null===(e=u.current)||void 0===e?void 0:e.focus()},[]);const d=Object.entries(n||{}),h=d.length>0,f=r&&r.length>0,p=new Map;if(r)for(const e of r){const t=p.get(e.name)||[];t.push(e),p.set(e.name,t)}const g=p.size>1,y=e=>{c({[e.name]:e.value})};return Mc(ll,{className:"dxc-login-dlg"},Mc(Nc,null,Mc("h3",{style:cl.WindowHeader},e),t.map((e,t)=>Mc("div",{key:t},Mc("p",{style:cl.Alert[e.type]},Ul(e)),e.copyText&&Mc($l,{text:e.copyText}))),f&&Mc("div",{class:"dxc-options"},g?Array.from(p.entries()).map(([e,t],n)=>Mc(Nc,{key:e},n>0&&Mc(Ll,null),t.map(e=>Mc(Pl,{key:`${e.name}-${e.value}`,option:e,onClick:()=>y(e)})))):r.map(e=>Mc(Pl,{key:`${e.name}-${e.value}`,option:e,onClick:()=>y(e)}))),f&&h&&Mc(Ll,null),h&&Mc("form",{onSubmit:e=>{e.preventDefault(),c(l)}},d.map(([e,{type:t,label:n,placeholder:r}],s)=>Mc("label",{style:cl.Label,key:s},n?`${n}: `:"",Mc("input",{ref:0===s?u:void 0,type:t,name:e,autoComplete:"on",style:cl.Input,autoFocus:!0,placeholder:r,value:l[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({},l),{[e]:s});a(i),"otp"===t&&8===(null==s?void 0:s.trim().length)&&c(i)}}))))),Mc("div",{style:cl.ButtonsDiv},Mc(Nc,null,s&&(h||!f&&!h)&&Mc("button",{type:"submit",style:cl.PrimaryButton,onClick:()=>c(l)},s),i&&Mc("button",{style:cl.Button,onClick:o},i))))}function $l({text:e}){const[t,n]=Sl(!1),r=El(null);xl(()=>()=>{null!==r.current&&clearTimeout(r.current)},[]);const s=()=>{null!==r.current&&clearTimeout(r.current),n(!0),r.current=setTimeout(()=>{r.current=null,n(!1)},2e3)};return Mc("button",{type:"button",style:t?cl.CopyButtonCopied:cl.CopyButton,onClick:()=>{var t;"undefined"!=typeof navigator&&(null===(t=navigator.clipboard)||void 0===t?void 0:t.writeText)?navigator.clipboard.writeText(e).then(s).catch(()=>{Ml(e,s)}):Ml(e,s)},title:"Copy to clipboard"},t?"✓ Copied!":`📋 ${e}`)}function Ml(e,t){const n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select();const r=document.execCommand("copy");document.body.removeChild(n),r&&t()}class Bl extends Fc{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?Mc(Rl,Object.assign({},t)):null}}function Nl(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const Fl=Nl(e=>new n.BehaviorSubject(Object.assign(Object.assign({},Ot),{isLoading:!0})));function Wl(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 zl=Nl(e=>Wl(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})),{})),Kl=Nl(e=>Wl(Fl(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 Vl(...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 Hl=Nl(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}(Wl(n.combineLatest([Kl(e._novip),zl(e._novip)]).pipe(r.map(([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r}))),{selfMembers:[],realms:[],userId:Ot.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=en(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:"*"}:Vl(...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 Jl{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 ql=Nl(e=>{const i=Fl(e._novip).pipe(r.switchMap(n=>t.liveQuery(()=>e.members.where({email:n.email||""}).toArray()))),o=Hl(e._novip),c=Kl(e._novip);return Wl(n.combineLatest([i,c,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,{}),c=n.selfMembers.reduce(i,o);return Object.values(c).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 Yl(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:c}=o.meta||{};if(!(null===(i=e.cloud.schema)||void 0===i?void 0:i[c].markedForSync))return;let l;if(Object.getOwnPropertyDescriptor(r,"awareness")){const e=r.awareness;e&&(e.destroy(),ic.delete(o))}Object.defineProperty(r,"awareness",{configurable:!0,get:()=>l||(l=function(e,r,i){const{parentTable:o,parentId:c,parentProp:l,updatesTable:a}=r.meta,u=new cc(r),d=uc(r);return u.on("update",({added:t,updated:n,removed:s},c)=>{const a=t.concat(n).concat(s),d=e.cloud.currentUser.value;if("server"!==c&&d.isLoggedIn&&!Vo(e)){const t=((e,t,n=e.states)=>{const r=t.length,s=fe();me(s,r);for(let i=0;i<r;i++){const r=t[i],o=n.get(r)||null,c=e.meta.get(r).clock;me(s,r),me(s,c),_e(s,JSON.stringify(o))}return pe(s)})(u,a);e.messageProducer.next({type:"aware",table:o,prop:l,k:r.meta.parentId,u:t}),i.destroyed&&e.messageProducer.next({type:"doc-close",table:o,prop:l,k:r.meta.parentId})}}),u.on("destroy",()=>{lc(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(_n),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:l,k:c,serverRev:p},y=yield d.where("i").between(f,1/0,!1).filter(e=>0===t.cmp(e.k,c)&&!(1&(e.f||0))).toArray();if(!i.destroyed&&u===n&&r){if(y.length>0){const e=us(y.map(e=>e.u)),t=ls(e);g.sv=t}e.messageProducer.next(g)}})}i.addCleanupHandler(h)})})(),u}(e,o,r),ic.set(o,l),l)})}}function Gl(e){const t="undefined"!=typeof window?window.location.href:"";if(!t)return null;const n=new URL(t).searchParams.get("dxc-auth");if(!n)return null;let r;try{const e=function(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/");return atob(t)}(n);r=JSON.parse(e)}catch(e){return null}const{code:s,provider:i,state:o,error:c}=r;if(c){if(c.toLowerCase().includes("access_denied")||c.toLowerCase().includes("access denied"))throw new Lt("access_denied",i,c);if(c.toLowerCase().includes("email")&&c.toLowerCase().includes("verif"))throw new Lt("email_not_verified",i,c);throw new Lt("provider_error",i,c)}return s&&i&&o?{code:s,provider:i,state:o}:null}function Ql(){var e;if("undefined"==typeof window||!(null===(e=window.history)||void 0===e?void 0:e.replaceState))return;const t=new URL(window.location.href);if(!t.searchParams.has("dxc-auth"))return;t.searchParams.delete("dxc-auth");const n=t.pathname+(t.searchParams.toString()?`?${t.searchParams.toString()}`:"")+t.hash;window.history.replaceState(null,"",n)}const Xl={},Zl=new WeakMap,ea=na("tx"),ta=na("unload");function na(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=Zi.getOrCreateDocument(t,s,i,n);try{const t=Zi.load(e);yield t.whenLoaded;for(const t of r)yield t(e,n)}catch(e){null==e||e.name}finally{Zi.release(e)}}})}(e).finally(()=>{t=null})},0))})},enqueue(e,t,n,s,i){const o=`${e.name}:${t}:${n}:${s}`;let c=r.get(o);c||(c={db:e,parentTable:t,parentId:n,prop:s,triggers:new Set},r.set(o,c)),c.triggers.add(i)}}}function ra(){ea.run()}function sa(){ta.run()}const ia={nameSuffix:!0};function oa(e){const i=e.name,o=Fl(e),c=[];let l=!1,a=null,u=null,d=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,y,m,b,v,w,_,k,S;h=!1;const x=Eo(e);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(i=x.cloud.options)||void 0===i?void 0:i.customLoginGui)||c.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),ol(Mc(Bl,{db:e.vip}),n)):addEventListener("DOMContentLoaded",()=>{t||(document.body.appendChild(n),ol(Mc(Bl,{db:e.vip}),n))}),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(e))),x.cloud.isServiceWorkerDB||c.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 Xo.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"})),Fl(e.dx._novip),Zo]).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:c,progress:l}=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:c,progress:l,status:gn?a:"offline",license:"ok"}}))}(x).subscribe(e.cloud.syncState)),c.push(x.syncCompleteEvent.subscribe(p));if("eager"===(null!==(m=null===(y=x.cloud.options)||void 0===y?void 0:y.blobMode)&&void 0!==m?m:"eager")){let e=null;const n=()=>{e||(e=t.ignoreTransaction(()=>function(e,n,r){return s(this,void 0,void 0,function*(){var i;const o=e=>{},c=ot(e);let l=!1;for(const e of c)try{if(!e.schema.idxByName._hasBlobRefs)continue;if((yield e.where("_hasBlobRefs").equals(1).count())>0){l=!0;break}}catch(e){}if(l){ct(n,!0);try{c.length,c.map(e=>e.name).join(", ");for(const n of c){null==r||r.aborted;try{if(!n.schema.indexes.some(e=>"_hasBlobRefs"===e.name))continue;const c=yield n.where("_hasBlobRefs").equals(1).toArray();o((n.name,c.length));const l=null===(i=e.cloud.options)||void 0===i?void 0:i.databaseUrl;if(!l)throw new Error("Database URL is required to download blobs");const a=6,u=n.schema.primKey,d=c.filter(e=>!!it(e)&&void 0!==(u.keyPath?t.getByKeyPath(e,u.keyPath):void 0));let h=0;const f=()=>s(this,void 0,void 0,function*(){for(;h<d.length;){null==r||r.aborted;const s=d[h++],i=t.getByKeyPath(s,u.keyPath);try{const t=[];yield st(s,l,t,"",new WeakMap,e.blobDownloadTracker);const r={_hasBlobRefs:void 0};for(const e of t)r[e.keyPath]=e.data;o((n.name,t.length)),yield n.update(i,r)}catch(e){}}}),p=[];for(let e=0;e<Math.min(a,d.length);e++)p.push(f());yield Promise.all(p)}catch(e){}}}finally{ct(n,!1)}}})}(x,g)).catch(e=>{}).finally(()=>{e=null}))};setTimeout(n,0),c.push(x.syncCompleteEvent.subscribe(n))}x.tables.every(e=>e.core)||function(){throw new t.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const E="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[C,A]=yield x.transaction("rw",x.$syncState,()=>s(this,void 0,void 0,function*(){var e,t;const{options:n,schema:r}=x.cloud,[s,i,o]=yield Promise.all([x.getOptions(),x.getSchema(),x.getPersistedSyncState()]);if(l){if(!s||JSON.stringify(s)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,delete e.awarenessProtocol,yield x.$syncState.put(e,"options")}}else x.cloud.options=s||null;if((null===(e=x.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&E.length>0&&!Do?x.cloud.usingServiceWorker=!0:((null===(t=x.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&x.cloud.isServiceWorkerDB,x.cloud.usingServiceWorker=!1),wc(r,x.cloud.options),wc(i,x.cloud.options),r){if(!i||JSON.stringify(i)!==JSON.stringify(r)){const e=i||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]=Object.assign({},n)}yield x.$syncState.put(e,"schema"),Object.assign(r,e)}}else x.cloud.schema=i||null;return[null==o?void 0:o.initiallySynced,null==o?void 0:o.realms]}));if(C&&x.setInitiallySynced(!0),function(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`)}}(x),f(),!x.cloud.isServiceWorkerDB){c.push(t.liveQuery(()=>x.getCurrentUser().then(e=>!e.isLoggedIn&&"undefined"!=typeof location&&/dxc-auth\=/.test(location.search)?Object.assign(Object.assign({},e),{isLoading:!0}):e)).subscribe(o)),c.push(t.liveQuery(()=>x.getPersistedSyncState()).subscribe(x.cloud.persistedSyncState)),yield n.firstValueFrom(n.combineLatest([o.pipe(r.skip(1),r.take(1)),x.cloud.persistedSyncState.pipe(r.skip(1),r.take(1))]));const e=Yl(x);Zi.on.new.subscribe(e),x.dx.once("close",()=>{Zi.on.new.unsubscribe(e)})}let I=!1,O=yield x.getCurrentUser();if(u&&!x.cloud.isServiceWorkerDB){const e=u;u=null;try{yield mt(x.cloud.userInteraction,"Authentication Error",{type:"error",messageCode:"GENERIC_ERROR",message:e.message,messageParams:{provider:e.provider||"unknown"}}),Ql()}catch(e){}}if(a&&!x.cloud.isServiceWorkerDB){const{code:e,provider:t}=a;a=null;try{I=yield Kt(x,{oauthCode:e,provider:t}),O=yield x.getCurrentUser(),Ql()}catch(e){}}const D=null===(b=x.cloud.options)||void 0===b?void 0:b.requireAuth;D&&(x.cloud.isServiceWorkerDB?yield n.firstValueFrom(o.pipe(r.filter(e=>!!e.isLoggedIn),r.take(1))):"object"==typeof D?(!O.isLoggedIn||D.userId&&O.userId!==D.userId||D.email&&O.email!==D.email)&&(I=yield Kt(x,D)):O.isLoggedIn||(I=yield Kt(x))),!O.isLoggedIn||A&&A.includes(O.userId)||(I=!0),d&&d.stop(),d=null,f();const j=(null===(v=x.cloud.options)||void 0===v?void 0:v.databaseUrl)&&(!C||I);j&&(yield function(e,t,n){return s(this,void 0,void 0,function*(){yield Qo(e,yo,()=>mo(e,t,n,{isInitialSync:!0}))})}(x,x.cloud.options,x.cloud.schema),x.setInitiallySynced(!0)),f(),x.cloud.usingServiceWorker&&(null===(w=x.cloud.options)||void 0===w?void 0:w.databaseUrl)?(j||dt(x,"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){}})}(x).catch(()=>{})):(null===(_=x.cloud.options)||void 0===_?void 0:_.databaseUrl)&&x.cloud.schema&&!x.cloud.isServiceWorkerDB&&(d=vc(x,x.cloud.options,x.cloud.schema),d.start(),j||ht(x,"push")),f(),x.cloud.isServiceWorkerDB||c.push(n.fromEvent(self,"online").subscribe(()=>{x.syncStateChangedEvent.next({phase:"not-in-sync"}),Vo(x)||ht(x,"push")}),n.fromEvent(self,"offline").subscribe(()=>{x.syncStateChangedEvent.next({phase:"offline"})})),!(null===(k=x.cloud.options)||void 0===k?void 0:k.databaseUrl)||(null===(S=x.cloud.options)||void 0===S?void 0:S.disableWebSocket)||jo||c.push(function(e){var t;if(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl))throw new Error("No database URL to connect WebSocket to");const i=e.messageConsumer.readyToServe.pipe(r.filter(e=>e),r.switchMap(()=>e.cloud.persistedSyncState.pipe(r.filter(e=>!(!e||!e.serverRevision)),r.take(1))),r.switchMap(e=>s(this,void 0,void 0,function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield Gt(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])=>Zo.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 Gt(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 dc(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 Ct(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 pc?n.throwError(()=>s):n.from(gc()).pipe(r.switchMap(()=>t())))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(x))})}(e)}catch(e){}}),!0);let h=!1;function f(){if(h)throw new t.DatabaseClosedError}e.once("close",()=>{c.forEach(e=>e.unsubscribe()),c.splice(0,c.length),h=!0,d&&d.stop(),d=null,o.next(Ot)});const p=new n.Subject,g=new n.BehaviorSubject(!1);var y;e.cloud={version:"4.4.8",options:Object.assign({},ia),schema:null,get currentUserId(){return o.value.userId||Ot.userId},currentUser:o,syncState:new n.BehaviorSubject({phase:"initial",status:"not-started"}),events:{syncComplete:p},persistedSyncState:new n.BehaviorSubject(void 0),blobProgress:lt(Eo(e),g),userInteraction:new n.BehaviorSubject(void 0),webSocketStatus:new n.BehaviorSubject("not-started"),login(t){return s(this,void 0,void 0,function*(){const n=Eo(e);yield n.cloud.sync(),yield Kt(n,t)})},invites:ql(e),roles:zl(e),configure(t){if(void 0!==t.maxStringLength&&t.maxStringLength!==1/0&&(!Number.isFinite(t.maxStringLength)||t.maxStringLength<100||t.maxStringLength>32768))throw new Error(`maxStringLength must be Infinity or a finite number in [100, 32768]. Got: ${t.maxStringLength}`);if(t=e.cloud.options=Object.assign(Object.assign({},e.cloud.options),t),l=!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)}`,Eo(e).reconfigure()),wc(e.cloud.schema,e.cloud.options),"undefined"!=typeof window&&window.location)try{const e=Gl();e&&(a={code:e.code,provider:e.provider})}catch(e){e instanceof Lt&&(u=e)}},logout(){return s(this,arguments,void 0,function*({force:t}={}){t?yield Tt(Eo(e),{deleteUnsyncedData:!0}):yield jt(Eo(e))})},getAuthProviders(){return s(this,void 0,void 0,function*(){const t=e.cloud.options;if(!(null==t?void 0:t.databaseUrl))throw new Error("Dexie Cloud not configured. Call db.cloud.configure() first.");const n=!1!==t.socialAuth;return $t(t.databaseUrl,n)})},sync(){return s(this,arguments,void 0,function*({wait:i,purpose:o}={wait:!0,purpose:"push"}){var c;void 0===i&&(i=!0);const l=Eo(e);if("ok"!==((null===(c=l.cloud.currentUser.value.license)||void 0===c?void 0:c.status)||"ok")&&(yield xt(l)),"pull"===o){const e=l.cloud.persistedSyncState.value;if(ht(l,o),i){const t=yield n.firstValueFrom(l.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 yc(l)){const e=l.cloud.persistedSyncState.value;ht(l,o),i&&(yield n.firstValueFrom(n.from(t.liveQuery(()=>s(this,void 0,void 0,function*(){const t=yield yc(l),n=yield l.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=Hl(e),c=t=>{const r=t[i||e.cloud.currentUserId];return r?new Jl(r.permissions,n,void 0===i||i===e.cloud.currentUserId||s===e.cloud.currentUserId):new Jl({},n,!s||s===e.cloud.currentUserId)},l=o.pipe(r.map(c));return l.getValue=()=>c(o.getValue()),l}(e._novip,t,n)},e.Version.prototype._parseStoresSpec=t.override(e.Version.prototype._parseStoresSpec,t=>Go(t,e)),e.Table.prototype.newId=function({colocateWith:t}={}){const n=t&&t.substr(t.length-3);return Bo(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(qo(Eo(e))),e.use(Ho({currentUserObservable:e.cloud.currentUser,db:Eo(e)})),e.use((y=Eo(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,c,l;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:Ot.userId;if((null===(o=null===(i=y.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===(l=(c=n.schema.primaryKey).extractKey)||void 0===l?void 0:l.call(c,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(Eo(e)))}oa.version="4.4.8",t.Cloud=oa,e.default=oa,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}`);Xl[o]={trigger:r,parentTable:e.name,prop:n};const c=e.db._novip;let l=Zl.get(c);l||(l=(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=>Xl[e])?(s.addEventListener("complete",ra),s):s},table:r=>{const s=n.table(r),i=Xl[r];if(!i)return s;const{trigger:o,parentTable:c,prop:l}=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=Zi.getDocCache(e).find(c,n,l);(s&&(null===(r=Zi.for(s))||void 0===r?void 0:r.refCount)?ta:ea).enqueue(e,c,n,l,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)ea.enqueue(e,c,t.from,l,o)})}return s.mutate(n)}})}})}))(c),Zl.set(c,l)),c.use(l),Zi.on("beforeunload",sa)},e.dexieCloud=oa,e.getTiedObjectId=function(e){return e.startsWith("rlm~")?e.substr(4):null},e.getTiedRealmId=function(e){return"rlm~"+e},e.resolveText=Ul,Object.defineProperty(e,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=dexie-cloud-addon.min.js.map
|