| @@ -33,23 +33,23 @@ | ||
| 33 | 33 | return total; |
| 34 | 34 | }; |
| 35 | 35 | })(); |
| 36 | 36 | /* WCPOS_OPFS_TARGETED_RECOVERY */ |
| 37 | -(()=>{function $e(e){"@babel/helpers - typeof";return $e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$e(e)}function gn(e,t){if($e(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if($e(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function vn(e){var t=gn(e,"string");return $e(t)=="symbol"?t:t+""}function wn(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,vn(n.key),n)}}function xn(e,t,r){return t&&wn(e.prototype,t),r&&wn(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function Fe(e){return e[e.length-1]}function Nt(e){return Array.isArray(e)?e.slice(0):[e]}function bn(e,t){e=e.slice(0);for(var r=[];e.length;){var n=e.splice(0,t);r.push(n)}return r}function Mt(e){return Array.isArray(e)}function $t(e,t){var r=0,n=-1;for(var o of e){n=n+1;var a=t(o,n);if(a)r=r+1;else break}return r}function Sn(e){return Math.max(...e)}function Ie(e,t){return Ie=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Ie(e,t)}function _n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,Ie(e,t)}function Ft(e){return Ft=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Ft(e)}function On(e){try{return Function.toString.call(e).indexOf("[native code]")!==-1}catch{return typeof e=="function"}}function br(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(br=function(){return!!e})()}function En(e,t,r){if(br())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var o=new(e.bind.apply(e,n));return r&&Ie(o,r.prototype),o}function Dt(e){var t=typeof Map=="function"?new Map:void 0;return Dt=function(n){if(n===null||!On(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(n))return t.get(n);t.set(n,o)}function o(){return En(n,arguments,Ft(this).constructor)}return o.prototype=Object.create(n.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),Ie(o,n)},Dt(e)}var In={isDevMode(){return!1},deepFreezeWhenDevMode(e){return e},tunnelErrorMessage(e){return` | |
| 37 | +(()=>{function De(e){"@babel/helpers - typeof";return De=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},De(e)}function wn(e,t){if(De(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(De(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function xn(e){var t=wn(e,"string");return De(t)=="symbol"?t:t+""}function bn(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,xn(n.key),n)}}function Sn(e,t,r){return t&&bn(e.prototype,t),r&&bn(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function Le(e){return e[e.length-1]}function Lt(e){return Array.isArray(e)?e.slice(0):[e]}function _n(e,t){e=e.slice(0);for(var r=[];e.length;){var n=e.splice(0,t);r.push(n)}return r}function Ht(e){return Array.isArray(e)}function Bt(e,t){var r=0,n=-1;for(var o of e){n=n+1;var a=t(o,n);if(a)r=r+1;else break}return r}function En(e){return Math.max(...e)}function Ae(e,t){return Ae=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Ae(e,t)}function On(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,Ae(e,t)}function Wt(e){return Wt=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Wt(e)}function In(e){try{return Function.toString.call(e).indexOf("[native code]")!==-1}catch{return typeof e=="function"}}function Ir(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Ir=function(){return!!e})()}function Pn(e,t,r){if(Ir())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var o=new(e.bind.apply(e,n));return r&&Ae(o,r.prototype),o}function jt(e){var t=typeof Map=="function"?new Map:void 0;return jt=function(n){if(n===null||!In(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(n))return t.get(n);t.set(n,o)}function o(){return Pn(n,arguments,Wt(this).constructor)}return o.prototype=Object.create(n.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),Ae(o,n)},jt(e)}var An={isDevMode(){return!1},deepFreezeWhenDevMode(e){return e},tunnelErrorMessage(e){return` | |
| 38 | 38 | RxDB Error-Code: `+e+`. |
| 39 | 39 | Hint: Error messages are not included in RxDB core to reduce build size. |
| 40 | 40 | To show the full error messages and to ensure that you do not make any mistakes when using RxDB, |
| 41 | 41 | use the dev-mode plugin when you are in development mode: https://rxdb.info/dev-mode.html?console=error |
| 42 | - `}};function si(e){var t="";return Object.keys(e).length===0||(t+="-".repeat(20)+` | |
| 42 | + `}};function li(e){var t="";return Object.keys(e).length===0||(t+="-".repeat(20)+` | |
| 43 | 43 | `,t+=`Parameters: |
| 44 | 44 | `,t+=Object.keys(e).map(r=>{var n="[object Object]";try{r==="errors"?n=e[r].map(o=>JSON.stringify(o,Object.getOwnPropertyNames(o))):n=JSON.stringify(e[r],function(o,a){return a===void 0?null:a},2)}catch{}return r+": "+n}).join(` |
| 45 | 45 | `),t+=` |
| 46 | -`),t}function ui(e,t,r){return` | |
| 46 | +`),t}function pi(e,t,r){return` | |
| 47 | 47 | `+e+` |
| 48 | -`+si(r)}var ci=(function(e){function t(n,o,a={}){var i,s=ui(o,n,a);return i=e.call(this,s)||this,i.code=n,i.message=s,i.url=Pn(n),i.parameters=a,i.rxdb=!0,i}_n(t,e);var r=t.prototype;return r.toString=function(){return this.message},xn(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}])})(Dt(Error));function Pn(e){return"https://rxdb.info/errors.html?console=errors#"+e}function fi(e){return` | |
| 49 | -Find out more about this error here: `+Pn(e)+` | |
| 50 | -`}function Q(e,t){return new ci(e,In.tunnelErrorMessage(e)+fi(e),t)}var An=new Map;function Lt(e){var t=An.get(e);if(t)return t;var r=e.split("."),n=r.length;if(n===1)t=w=>w[e];else if(n===2){var o=r[0],a=r[1];t=w=>{var g=w[o];return g===void 0?g:g[a]}}else if(n===3){var i=r[0],s=r[1],u=r[2];t=w=>{var g=w[i];if(g===void 0)return g;var x=g[s];return x===void 0?x:x[u]}}else if(n===4){var c=r[0],f=r[1],p=r[2],l=r[3];t=w=>{var g=w[c];if(g===void 0)return g;var x=g[f];if(x===void 0)return x;var S=x[p];return S===void 0?S:S[l]}}else if(n===5){var m=r[0],h=r[1],d=r[2],y=r[3],v=r[4];t=w=>{var g=w[m];if(g===void 0)return g;var x=g[h];if(x===void 0)return x;var S=x[d];if(S===void 0)return S;var b=S[y];return b===void 0?b:b[v]}}else t=w=>{for(var g=w,x=0;x<n;++x)if(g=g[r[x]],g===void 0)return g;return g};return An.set(e,t),t}function _r(e){return{...e}}function Rn(e){return Object.keys(e)[0]}function Sr(e){if(!e||typeof e!="object")return e;if(Array.isArray(e)){for(var t=new Array(e.length),r=t.length;r--;)t[r]=Sr(e[r]);return t}if(typeof Blob<"u"&&e instanceof Blob)return e;var n={};for(var o in e)n[o]=Sr(e[o]);return n}var Tn=Sr;var Or=1;var Ht;function li(){if(Ht)return Ht;if(typeof crypto>"u"||typeof crypto.subtle>"u"||typeof crypto.subtle.digest!="function")throw Q("UT8",{args:{typeof_crypto:typeof crypto,typeof_crypto_subtle:typeof crypto?.subtle,typeof_crypto_subtle_digest:typeof crypto?.subtle?.digest}});return Ht=crypto.subtle.digest.bind(crypto.subtle),Ht}async function pi(e){var t;typeof Blob<"u"&&e instanceof Blob?t=await e.arrayBuffer():typeof e=="string"?t=new TextEncoder().encode(e):t=e;var r=await li()("SHA-256",t),n=Array.prototype.map.call(new Uint8Array(r),o=>("00"+o.toString(16)).slice(-2)).join("");return n}var kn=pi;function le(e=0){return new Promise(t=>setTimeout(t,e))}function Cn(e){return e&&typeof e.then=="function"?e:Promise.resolve(e)}var di=Promise.resolve(!0),Xu=Promise.resolve(!1),Yu=Promise.resolve(null),Er=Promise.resolve();var Nn=/\./g;var Mn="abcdefghijklmnopqrstuvwxyz";function $n(e=10){for(var t="",r=0;r<e;r++)t+=Mn.charAt(Math.floor(Math.random()*Mn.length));return t}function Fn(e){for(var t=0,r=e.length;t<r&&e.charCodeAt(t)===46;)t++;for(;r>t&&e.charCodeAt(r-1)===46;)r--;return t===0&&r===e.length?e:e.substring(t,r)}function mt(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var r,n;if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(n=r;n--!==0;)if(!mt(e[n],t[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var o=Object.keys(e);if(r=o.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;){var a=o[n];if(!Object.prototype.hasOwnProperty.call(t,a)||!mt(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}var mi=e=>{var t=typeof e;return e!==null&&(t==="object"||t==="function")},Bt=new Set(["__proto__","prototype","constructor"]),hi=new Set("0123456789");function yi(e){var t=[],r="",n="start",o=!1;for(var a of e)switch(a){case"\\":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd")throw new Error("Invalid character after an index");o&&(r+=a),n="property",o=!o;break}case".":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd"){n="property";break}if(o){o=!1,r+=a;break}if(Bt.has(r))return[];t.push(r),r="",n="property";break}case"[":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd"){n="index";break}if(o){o=!1,r+=a;break}if(n==="property"){if(Bt.has(r))return[];t.push(r),r=""}n="index";break}case"]":{if(n==="index"){t.push(Number.parseInt(r,10)),r="",n="indexEnd";break}if(n==="indexEnd")throw new Error("Invalid character after an index")}default:{if(n==="index"&&!hi.has(a))throw new Error("Invalid character in an index");if(n==="indexEnd")throw new Error("Invalid character after an index");n==="start"&&(n="property"),o&&(o=!1,r+="\\"),r+=a}}switch(o&&(r+="\\"),n){case"property":{if(Bt.has(r))return[];t.push(r);break}case"index":throw new Error("Index was not closed");case"start":{t.push("");break}}return t}function gi(e,t){if(typeof t!="number"&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function Dn(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!mi(e)||typeof t!="string")return r===void 0?e:r;if(!t.includes("[")&&!t.includes("\\")){for(var n=t.split("."),o=e,a=0;a<n.length;a++){var i=n[a];if(Bt.has(i))return r;if(o=o[i],o==null){if(a!==n.length-1)return r;break}}return o===void 0?r:o}var s=yi(t);if(s.length===0)return r;for(var u=0;u<s.length;u++){var c=s[u];if(gi(e,c)?e=u===s.length-1?void 0:null:e=e[c],e==null){if(u!==s.length-1)return r;break}}return e===void 0?r:e}function ht(e,t){var r=e.get(t);if(r===void 0)throw new Error("missing value from map "+t);return r}function Wt(e,t,r,n){var o=e.get(t);return o===void 0?(o=r(),e.set(t,o)):n&&n(o),o}function Ln(e){var t={name:e.name,message:e.message,rxdb:e.rxdb,parameters:e.parameters,extensions:e.extensions,code:e.code,url:e.url,stack:e.stack?e.stack.replace(/\n/g,` | |
| 51 | - `):void 0};return t}var jt=0,qt=0;function De(){var e=Date.now();return e>jt?(jt=e,qt=1):++qt===100&&(jt++,qt=1),jt+qt*.01}function vi(e){throw new Error("ensureNotFalsy() is falsy: "+(e||""))}function H(e,t){return e||vi(t),e}var Hn={bufferSize:1,refCount:!0};var Ge="17.4.0";var Bn=new WeakMap;function Le(e,t){var r=Bn.get(e),n=t;if(r){var o=r.get(n);if(o)return o}else r=new Map,Bn.set(e,r);var a=n;a=a.replace(Nn,".properties."),a="properties."+a,a=Fn(a);var i=Dn(e,a);return r.set(n,i),i}function ie(e){return typeof e=="string"?e:e.key}var Ir=function(e,t){return Ir=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},Ir(e,t)};function ye(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Ir(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}function Wn(e,t,r,n){function o(a){return a instanceof r?a:new r(function(i){i(a)})}return new(r||(r=Promise))(function(a,i){function s(f){try{c(n.next(f))}catch(p){i(p)}}function u(f){try{c(n.throw(f))}catch(p){i(p)}}function c(f){f.done?a(f.value):o(f.value).then(s,u)}c((n=n.apply(e,t||[])).next())})}function Ut(e,t){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},n,o,a,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=s(0),i.throw=s(1),i.return=s(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function s(c){return function(f){return u([c,f])}}function u(c){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(r=0)),r;)try{if(n=1,o&&(a=c[0]&2?o.return:c[0]?o.throw||((a=o.return)&&a.call(o),0):o.next)&&!(a=a.call(o,c[1])).done)return a;switch(o=0,a&&(c=[c[0]&2,a.value]),c[0]){case 0:case 1:a=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,o=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(a=r.trys,!(a=a.length>0&&a[a.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!a||c[1]>a[0]&&c[1]<a[3])){r.label=c[1];break}if(c[0]===6&&r.label<a[1]){r.label=a[1],a=c;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(c);break}a[2]&&r.ops.pop(),r.trys.pop();continue}c=t.call(e,r)}catch(f){c=[6,f],o=0}finally{n=a=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function be(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Pe(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,a=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)a.push(o.value)}catch(s){i={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a}function Ae(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,a;n<o;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}function He(e){return this instanceof He?(this.v=e,this):new He(e)}function jn(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(e,t||[]),o,a=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(m){return function(h){return Promise.resolve(h).then(m,p)}}function s(m,h){n[m]&&(o[m]=function(d){return new Promise(function(y,v){a.push([m,d,y,v])>1||u(m,d)})},h&&(o[m]=h(o[m])))}function u(m,h){try{c(n[m](h))}catch(d){l(a[0][3],d)}}function c(m){m.value instanceof He?Promise.resolve(m.value.v).then(f,p):l(a[0][2],m)}function f(m){u("next",m)}function p(m){u("throw",m)}function l(m,h){m(h),a.shift(),a.length&&u(a[0][0],a[0][1])}}function qn(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof be=="function"?be(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(a){r[a]=e[a]&&function(i){return new Promise(function(s,u){i=e[a](i),o(s,u,i.done,i.value)})}}function o(a,i,s,u){Promise.resolve(u).then(function(c){a({value:c,done:s})},i)}}function j(e){return typeof e=="function"}function Xe(e){var t=function(n){Error.call(n),n.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var Kt=Xe(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription: | |
| 48 | +`+li(r)}var di=(function(e){function t(n,o,a={}){var i,s=pi(o,n,a);return i=e.call(this,s)||this,i.code=n,i.message=s,i.url=Rn(n),i.parameters=a,i.rxdb=!0,i}On(t,e);var r=t.prototype;return r.toString=function(){return this.message},Sn(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}])})(jt(Error));function Rn(e){return"https://rxdb.info/errors.html?console=errors#"+e}function mi(e){return` | |
| 49 | +Find out more about this error here: `+Rn(e)+` | |
| 50 | +`}function z(e,t){return new di(e,An.tunnelErrorMessage(e)+mi(e),t)}var Tn=new Map;function qt(e){var t=Tn.get(e);if(t)return t;var r=e.split("."),n=r.length;if(n===1)t=w=>w[e];else if(n===2){var o=r[0],a=r[1];t=w=>{var y=w[o];return y===void 0?y:y[a]}}else if(n===3){var i=r[0],s=r[1],u=r[2];t=w=>{var y=w[i];if(y===void 0)return y;var x=y[s];return x===void 0?x:x[u]}}else if(n===4){var c=r[0],f=r[1],p=r[2],l=r[3];t=w=>{var y=w[c];if(y===void 0)return y;var x=y[f];if(x===void 0)return x;var b=x[p];return b===void 0?b:b[l]}}else if(n===5){var m=r[0],h=r[1],d=r[2],g=r[3],v=r[4];t=w=>{var y=w[m];if(y===void 0)return y;var x=y[h];if(x===void 0)return x;var b=x[d];if(b===void 0)return b;var S=b[g];return S===void 0?S:S[v]}}else t=w=>{for(var y=w,x=0;x<n;++x)if(y=y[r[x]],y===void 0)return y;return y};return Tn.set(e,t),t}function Ar(e){return{...e}}function kn(e){return Object.keys(e)[0]}function Pr(e){if(!e||typeof e!="object")return e;if(Array.isArray(e)){for(var t=new Array(e.length),r=t.length;r--;)t[r]=Pr(e[r]);return t}if(typeof Blob<"u"&&e instanceof Blob)return e;var n={};for(var o in e)n[o]=Pr(e[o]);return n}var Cn=Pr;var Rr=1;var Ut;function hi(){if(Ut)return Ut;if(typeof crypto>"u"||typeof crypto.subtle>"u"||typeof crypto.subtle.digest!="function")throw z("UT8",{args:{typeof_crypto:typeof crypto,typeof_crypto_subtle:typeof crypto?.subtle,typeof_crypto_subtle_digest:typeof crypto?.subtle?.digest}});return Ut=crypto.subtle.digest.bind(crypto.subtle),Ut}async function yi(e){var t;typeof Blob<"u"&&e instanceof Blob?t=await e.arrayBuffer():typeof e=="string"?t=new TextEncoder().encode(e):t=e;var r=await hi()("SHA-256",t),n=Array.prototype.map.call(new Uint8Array(r),o=>("00"+o.toString(16)).slice(-2)).join("");return n}var Nn=yi;function de(e=0){return new Promise(t=>setTimeout(t,e))}function Mn(e){return e&&typeof e.then=="function"?e:Promise.resolve(e)}var gi=Promise.resolve(!0),tc=Promise.resolve(!1),rc=Promise.resolve(null),Tr=Promise.resolve();var $n=/\./g;var Fn="abcdefghijklmnopqrstuvwxyz";function Dn(e=10){for(var t="",r=0;r<e;r++)t+=Fn.charAt(Math.floor(Math.random()*Fn.length));return t}function Ln(e){for(var t=0,r=e.length;t<r&&e.charCodeAt(t)===46;)t++;for(;r>t&&e.charCodeAt(r-1)===46;)r--;return t===0&&r===e.length?e:e.substring(t,r)}function gt(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var r,n;if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(n=r;n--!==0;)if(!gt(e[n],t[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var o=Object.keys(e);if(r=o.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;){var a=o[n];if(!Object.prototype.hasOwnProperty.call(t,a)||!gt(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}var vi=e=>{var t=typeof e;return e!==null&&(t==="object"||t==="function")},Kt=new Set(["__proto__","prototype","constructor"]),wi=new Set("0123456789");function xi(e){var t=[],r="",n="start",o=!1;for(var a of e)switch(a){case"\\":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd")throw new Error("Invalid character after an index");o&&(r+=a),n="property",o=!o;break}case".":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd"){n="property";break}if(o){o=!1,r+=a;break}if(Kt.has(r))return[];t.push(r),r="",n="property";break}case"[":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd"){n="index";break}if(o){o=!1,r+=a;break}if(n==="property"){if(Kt.has(r))return[];t.push(r),r=""}n="index";break}case"]":{if(n==="index"){t.push(Number.parseInt(r,10)),r="",n="indexEnd";break}if(n==="indexEnd")throw new Error("Invalid character after an index")}default:{if(n==="index"&&!wi.has(a))throw new Error("Invalid character in an index");if(n==="indexEnd")throw new Error("Invalid character after an index");n==="start"&&(n="property"),o&&(o=!1,r+="\\"),r+=a}}switch(o&&(r+="\\"),n){case"property":{if(Kt.has(r))return[];t.push(r);break}case"index":throw new Error("Index was not closed");case"start":{t.push("");break}}return t}function bi(e,t){if(typeof t!="number"&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function Hn(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!vi(e)||typeof t!="string")return r===void 0?e:r;if(!t.includes("[")&&!t.includes("\\")){for(var n=t.split("."),o=e,a=0;a<n.length;a++){var i=n[a];if(Kt.has(i))return r;if(o=o[i],o==null){if(a!==n.length-1)return r;break}}return o===void 0?r:o}var s=xi(t);if(s.length===0)return r;for(var u=0;u<s.length;u++){var c=s[u];if(bi(e,c)?e=u===s.length-1?void 0:null:e=e[c],e==null){if(u!==s.length-1)return r;break}}return e===void 0?r:e}function vt(e,t){var r=e.get(t);if(r===void 0)throw new Error("missing value from map "+t);return r}function zt(e,t,r,n){var o=e.get(t);return o===void 0?(o=r(),e.set(t,o)):n&&n(o),o}function Bn(e){var t={name:e.name,message:e.message,rxdb:e.rxdb,parameters:e.parameters,extensions:e.extensions,code:e.code,url:e.url,stack:e.stack?e.stack.replace(/\n/g,` | |
| 51 | + `):void 0};return t}var Qt=0,Vt=0;function He(){var e=Date.now();return e>Qt?(Qt=e,Vt=1):++Vt===100&&(Qt++,Vt=1),Qt+Vt*.01}function Si(e){throw new Error("ensureNotFalsy() is falsy: "+(e||""))}function B(e,t){return e||Si(t),e}var Wn={bufferSize:1,refCount:!0};var Ze="17.4.0";var jn=new WeakMap;function Be(e,t){var r=jn.get(e),n=t;if(r){var o=r.get(n);if(o)return o}else r=new Map,jn.set(e,r);var a=n;a=a.replace($n,".properties."),a="properties."+a,a=Ln(a);var i=Hn(e,a);return r.set(n,i),i}function ue(e){return typeof e=="string"?e:e.key}var kr=function(e,t){return kr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o])},kr(e,t)};function ve(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");kr(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}function qn(e,t,r,n){function o(a){return a instanceof r?a:new r(function(i){i(a)})}return new(r||(r=Promise))(function(a,i){function s(f){try{c(n.next(f))}catch(p){i(p)}}function u(f){try{c(n.throw(f))}catch(p){i(p)}}function c(f){f.done?a(f.value):o(f.value).then(s,u)}c((n=n.apply(e,t||[])).next())})}function Jt(e,t){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},n,o,a,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=s(0),i.throw=s(1),i.return=s(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function s(c){return function(f){return u([c,f])}}function u(c){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(r=0)),r;)try{if(n=1,o&&(a=c[0]&2?o.return:c[0]?o.throw||((a=o.return)&&a.call(o),0):o.next)&&!(a=a.call(o,c[1])).done)return a;switch(o=0,a&&(c=[c[0]&2,a.value]),c[0]){case 0:case 1:a=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,o=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(a=r.trys,!(a=a.length>0&&a[a.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!a||c[1]>a[0]&&c[1]<a[3])){r.label=c[1];break}if(c[0]===6&&r.label<a[1]){r.label=a[1],a=c;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(c);break}a[2]&&r.ops.pop(),r.trys.pop();continue}c=t.call(e,r)}catch(f){c=[6,f],o=0}finally{n=a=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function _e(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Re(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,a=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)a.push(o.value)}catch(s){i={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a}function Te(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,a;n<o;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}function We(e){return this instanceof We?(this.v=e,this):new We(e)}function Un(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(e,t||[]),o,a=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(m){return function(h){return Promise.resolve(h).then(m,p)}}function s(m,h){n[m]&&(o[m]=function(d){return new Promise(function(g,v){a.push([m,d,g,v])>1||u(m,d)})},h&&(o[m]=h(o[m])))}function u(m,h){try{c(n[m](h))}catch(d){l(a[0][3],d)}}function c(m){m.value instanceof We?Promise.resolve(m.value.v).then(f,p):l(a[0][2],m)}function f(m){u("next",m)}function p(m){u("throw",m)}function l(m,h){m(h),a.shift(),a.length&&u(a[0][0],a[0][1])}}function Kn(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof _e=="function"?_e(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(a){r[a]=e[a]&&function(i){return new Promise(function(s,u){i=e[a](i),o(s,u,i.done,i.value)})}}function o(a,i,s,u){Promise.resolve(u).then(function(c){a({value:c,done:s})},i)}}function j(e){return typeof e=="function"}function et(e){var t=function(n){Error.call(n),n.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var Gt=et(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription: | |
| 52 | 52 | `+r.map(function(n,o){return o+1+") "+n.toString()}).join(` |
| 53 | - `):"",this.name="UnsubscriptionError",this.errors=r}});function yt(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Ye=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,r,n,o,a;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var s=be(i),u=s.next();!u.done;u=s.next()){var c=u.value;c.remove(this)}}catch(d){t={error:d}}finally{try{u&&!u.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}else i.remove(this);var f=this.initialTeardown;if(j(f))try{f()}catch(d){a=d instanceof Kt?d.errors:[d]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var l=be(p),m=l.next();!m.done;m=l.next()){var h=m.value;try{Un(h)}catch(d){a=a??[],d instanceof Kt?a=Ae(Ae([],Pe(a)),Pe(d.errors)):a.push(d)}}}catch(d){n={error:d}}finally{try{m&&!m.done&&(o=l.return)&&o.call(l)}finally{if(n)throw n.error}}}if(a)throw new Kt(a)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)Un(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(t)}},e.prototype._hasParent=function(t){var r=this._parentage;return r===t||Array.isArray(r)&&r.includes(t)},e.prototype._addParent=function(t){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(t),r):r?[r,t]:t},e.prototype._removeParent=function(t){var r=this._parentage;r===t?this._parentage=null:Array.isArray(r)&&yt(r,t)},e.prototype.remove=function(t){var r=this._finalizers;r&&yt(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})();var Pr=Ye.EMPTY;function zt(e){return e instanceof Ye||e&&"closed"in e&&j(e.remove)&&j(e.add)&&j(e.unsubscribe)}function Un(e){j(e)?e():e.unsubscribe()}var pe={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Ze={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=Ze.delegate;return o?.setTimeout?o.setTimeout.apply(o,Ae([e,t],Pe(r))):setTimeout.apply(void 0,Ae([e,t],Pe(r)))},clearTimeout:function(e){var t=Ze.delegate;return(t?.clearTimeout||clearTimeout)(e)},delegate:void 0};function Qt(e){Ze.setTimeout(function(){var t=pe.onUnhandledError;if(t)t(e);else throw e})}function Ar(){}var Kn=(function(){return Rr("C",void 0,void 0)})();function zn(e){return Rr("E",void 0,e)}function Qn(e){return Rr("N",e,void 0)}function Rr(e,t,r){return{kind:e,value:t,error:r}}var Be=null;function et(e){if(pe.useDeprecatedSynchronousErrorHandling){var t=!Be;if(t&&(Be={errorThrown:!1,error:null}),e(),t){var r=Be,n=r.errorThrown,o=r.error;if(Be=null,n)throw o}}else e()}function Vn(e){pe.useDeprecatedSynchronousErrorHandling&&Be&&(Be.errorThrown=!0,Be.error=e)}var gt=(function(e){ye(t,e);function t(r){var n=e.call(this)||this;return n.isStopped=!1,r?(n.destination=r,zt(r)&&r.add(n)):n.destination=Si,n}return t.create=function(r,n,o){return new Se(r,n,o)},t.prototype.next=function(r){this.isStopped?kr(Qn(r),this):this._next(r)},t.prototype.error=function(r){this.isStopped?kr(zn(r),this):(this.isStopped=!0,this._error(r))},t.prototype.complete=function(){this.isStopped?kr(Kn,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(r){this.destination.next(r)},t.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(Ye);var wi=Function.prototype.bind;function Tr(e,t){return wi.call(e,t)}var xi=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var r=this.partialObserver;if(r.next)try{r.next(t)}catch(n){Vt(n)}},e.prototype.error=function(t){var r=this.partialObserver;if(r.error)try{r.error(t)}catch(n){Vt(n)}else Vt(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(r){Vt(r)}},e})(),Se=(function(e){ye(t,e);function t(r,n,o){var a=e.call(this)||this,i;if(j(r)||!r)i={next:r??void 0,error:n??void 0,complete:o??void 0};else{var s;a&&pe.useDeprecatedNextContext?(s=Object.create(r),s.unsubscribe=function(){return a.unsubscribe()},i={next:r.next&&Tr(r.next,s),error:r.error&&Tr(r.error,s),complete:r.complete&&Tr(r.complete,s)}):i=r}return a.destination=new xi(i),a}return t})(gt);function Vt(e){pe.useDeprecatedSynchronousErrorHandling?Vn(e):Qt(e)}function bi(e){throw e}function kr(e,t){var r=pe.onStoppedNotification;r&&Ze.setTimeout(function(){return r(e,t)})}var Si={closed:!0,next:Ar,error:bi,complete:Ar};var tt=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Jn(e){return e}function Gn(e){return e.length===0?Jn:e.length===1?e[0]:function(r){return e.reduce(function(n,o){return o(n)},r)}}var ge=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(t,r,n){var o=this,a=Oi(t)?t:new Se(t,r,n);return et(function(){var i=o,s=i.operator,u=i.source;a.add(s?s.call(a,u):u?o._subscribe(a):o._trySubscribe(a))}),a},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(r){t.error(r)}},e.prototype.forEach=function(t,r){var n=this;return r=Xn(r),new r(function(o,a){var i=new Se({next:function(s){try{t(s)}catch(u){a(u),i.unsubscribe()}},error:a,complete:o});n.subscribe(i)})},e.prototype._subscribe=function(t){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(t)},e.prototype[tt]=function(){return this},e.prototype.pipe=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Gn(t)(this)},e.prototype.toPromise=function(t){var r=this;return t=Xn(t),new t(function(n,o){var a;r.subscribe(function(i){return a=i},function(i){return o(i)},function(){return n(a)})})},e.create=function(t){return new e(t)},e})();function Xn(e){var t;return(t=e??pe.Promise)!==null&&t!==void 0?t:Promise}function _i(e){return e&&j(e.next)&&j(e.error)&&j(e.complete)}function Oi(e){return e&&e instanceof gt||_i(e)&&zt(e)}function Ei(e){return j(e?.lift)}function rt(e){return function(t){if(Ei(t))return t.lift(function(r){try{return e(r,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function Jt(e,t,r,n,o){return new Ii(e,t,r,n,o)}var Ii=(function(e){ye(t,e);function t(r,n,o,a,i,s){var u=e.call(this,r)||this;return u.onFinalize=i,u.shouldUnsubscribe=s,u._next=n?function(c){try{n(c)}catch(f){r.error(f)}}:e.prototype._next,u._error=a?function(c){try{a(c)}catch(f){r.error(f)}finally{this.unsubscribe()}}:e.prototype._error,u._complete=o?function(){try{o()}catch(c){r.error(c)}finally{this.unsubscribe()}}:e.prototype._complete,u}return t.prototype.unsubscribe=function(){var r;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&((r=this.onFinalize)===null||r===void 0||r.call(this))}},t})(gt);var Yn=Xe(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var Z=(function(e){ye(t,e);function t(){var r=e.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return t.prototype.lift=function(r){var n=new Zn(this,this);return n.operator=r,n},t.prototype._throwIfClosed=function(){if(this.closed)throw new Yn},t.prototype.next=function(r){var n=this;et(function(){var o,a;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=be(n.currentObservers),s=i.next();!s.done;s=i.next()){var u=s.value;u.next(r)}}catch(c){o={error:c}}finally{try{s&&!s.done&&(a=i.return)&&a.call(i)}finally{if(o)throw o.error}}}})},t.prototype.error=function(r){var n=this;et(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var o=n.observers;o.length;)o.shift().error(r)}})},t.prototype.complete=function(){var r=this;et(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.observers;n.length;)n.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(r){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,r)},t.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},t.prototype._innerSubscribe=function(r){var n=this,o=this,a=o.hasError,i=o.isStopped,s=o.observers;return a||i?Pr:(this.currentObservers=null,s.push(r),new Ye(function(){n.currentObservers=null,yt(s,r)}))},t.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,a=n.thrownError,i=n.isStopped;o?r.error(a):i&&r.complete()},t.prototype.asObservable=function(){var r=new ge;return r.source=this,r},t.create=function(r,n){return new Zn(r,n)},t})(ge);var Zn=(function(e){ye(t,e);function t(r,n){var o=e.call(this)||this;return o.destination=r,o.source=n,o}return t.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},t.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},t.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},t.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:Pr},t})(Z);var Cr={now:function(){return(Cr.delegate||Date).now()},delegate:void 0};var eo=(function(e){ye(t,e);function t(r,n,o){r===void 0&&(r=1/0),n===void 0&&(n=1/0),o===void 0&&(o=Cr);var a=e.call(this)||this;return a._bufferSize=r,a._windowTime=n,a._timestampProvider=o,a._buffer=[],a._infiniteTimeWindow=!0,a._infiniteTimeWindow=n===1/0,a._bufferSize=Math.max(1,r),a._windowTime=Math.max(1,n),a}return t.prototype.next=function(r){var n=this,o=n.isStopped,a=n._buffer,i=n._infiniteTimeWindow,s=n._timestampProvider,u=n._windowTime;o||(a.push(r),!i&&a.push(s.now()+u)),this._trimBuffer(),e.prototype.next.call(this,r)},t.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(r),o=this,a=o._infiniteTimeWindow,i=o._buffer,s=i.slice(),u=0;u<s.length&&!r.closed;u+=a?1:2)r.next(s[u]);return this._checkFinalizedStatuses(r),n},t.prototype._trimBuffer=function(){var r=this,n=r._bufferSize,o=r._timestampProvider,a=r._buffer,i=r._infiniteTimeWindow,s=(i?1:2)*n;if(n<1/0&&s<a.length&&a.splice(0,a.length-s),!i){for(var u=o.now(),c=0,f=1;f<a.length&&a[f]<=u;f+=2)c=f;c&&a.splice(0,c+1)}},t})(Z);var to=(function(e){return e&&typeof e.length=="number"&&typeof e!="function"});function ro(e){return j(e?.then)}function no(e){return j(e[tt])}function oo(e){return Symbol.asyncIterator&&j(e?.[Symbol.asyncIterator])}function ao(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Pi(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var io=Pi();function so(e){return j(e?.[io])}function uo(e){return jn(this,arguments,function(){var r,n,o,a;return Ut(this,function(i){switch(i.label){case 0:r=e.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,He(r.read())];case 3:return n=i.sent(),o=n.value,a=n.done,a?[4,He(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,He(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function co(e){return j(e?.getReader)}function Nr(e){if(e instanceof ge)return e;if(e!=null){if(no(e))return Ai(e);if(to(e))return Ri(e);if(ro(e))return Ti(e);if(oo(e))return fo(e);if(so(e))return ki(e);if(co(e))return Ci(e)}throw ao(e)}function Ai(e){return new ge(function(t){var r=e[tt]();if(j(r.subscribe))return r.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Ri(e){return new ge(function(t){for(var r=0;r<e.length&&!t.closed;r++)t.next(e[r]);t.complete()})}function Ti(e){return new ge(function(t){e.then(function(r){t.closed||(t.next(r),t.complete())},function(r){return t.error(r)}).then(null,Qt)})}function ki(e){return new ge(function(t){var r,n;try{for(var o=be(e),a=o.next();!a.done;a=o.next()){var i=a.value;if(t.next(i),t.closed)return}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}t.complete()})}function fo(e){return new ge(function(t){Ni(e,t).catch(function(r){return t.error(r)})})}function Ci(e){return fo(uo(e))}function Ni(e,t){var r,n,o,a;return Wn(this,void 0,void 0,function(){var i,s;return Ut(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),r=qn(e),u.label=1;case 1:return[4,r.next()];case 2:if(n=u.sent(),!!n.done)return[3,4];if(i=n.value,t.next(i),t.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return s=u.sent(),o={error:s},[3,11];case 6:return u.trys.push([6,,9,10]),n&&!n.done&&(a=r.return)?[4,a.call(r)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}var lo=Xe(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}});function nt(e,t){var r=typeof t=="object";return new Promise(function(n,o){var a=new Se({next:function(i){n(i),a.unsubscribe()},error:o,complete:function(){r?n(t.defaultValue):o(new lo)}});e.subscribe(a)})}function Mr(e,t){return rt(function(r,n){var o=0;r.subscribe(Jt(n,function(a){n.next(e.call(t,a,o++))}))})}function vt(e,t){return rt(function(r,n){var o=0;r.subscribe(Jt(n,function(a){return e.call(t,a,o++)&&n.next(a)}))})}function po(e){e===void 0&&(e={});var t=e.connector,r=t===void 0?function(){return new Z}:t,n=e.resetOnError,o=n===void 0?!0:n,a=e.resetOnComplete,i=a===void 0?!0:a,s=e.resetOnRefCountZero,u=s===void 0?!0:s;return function(c){var f,p,l,m=0,h=!1,d=!1,y=function(){p?.unsubscribe(),p=void 0},v=function(){y(),f=l=void 0,h=d=!1},w=function(){var g=f;v(),g?.unsubscribe()};return rt(function(g,x){m++,!d&&!h&&y();var S=l=l??r();x.add(function(){m--,m===0&&!d&&!h&&(p=$r(w,u))}),S.subscribe(x),!f&&m>0&&(f=new Se({next:function(b){return S.next(b)},error:function(b){d=!0,y(),p=$r(v,o,b),S.error(b)},complete:function(){h=!0,y(),p=$r(v,i),S.complete()}}),Nr(g).subscribe(f))})(c)}}function $r(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];if(t===!0){e();return}if(t!==!1){var o=new Se({next:function(){o.unsubscribe(),e()}});return Nr(t.apply(void 0,Ae([],Pe(r)))).subscribe(o)}}function Fr(e,t,r){var n,o,a,i,s=!1;return e&&typeof e=="object"?(n=e.bufferSize,i=n===void 0?1/0:n,o=e.windowTime,t=o===void 0?1/0:o,a=e.refCount,s=a===void 0?!1:a,r=e.scheduler):i=e??1/0,po({connector:function(){return new eo(i,t,r)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:s})}var X="\uFFFF",de=Number.MIN_SAFE_INTEGER;function mo(e,t){var r=t.selector,n=e.indexes?e.indexes.slice(0):[];t.index&&(n=[t.index]);var o=!!t.sort.find(f=>Object.values(f)[0]==="desc"),a=new Set;Object.keys(r).forEach(f=>{var p=Le(e,f);p&&(p.type==="boolean"||p.enum)&&Object.prototype.hasOwnProperty.call(r[f],"$eq")&&a.add(f)});var i=t.sort.map(f=>Object.keys(f)[0]),s=i.filter(f=>!a.has(f)).join(","),u=-1,c;if(n.forEach(f=>{var p=!0,l=!0,m=f.map(g=>{var x=r[g],S=x?Object.keys(x):[],b={};if(!x||!S.length){var R=l?de:X;b={startKey:R,endKey:p?X:de,inclusiveStart:!0,inclusiveEnd:!0}}else S.forEach(T=>{if(Gt.has(T)){var C=x[T],L=Li(T,C);b=Object.assign(b,L)}else if(T==="$in"){var J=Di(x[T]);J&&(b=Object.assign(b,J))}});typeof b.startKey>"u"&&(b.startKey=de),typeof b.endKey>"u"&&(b.endKey=X),typeof b.inclusiveStart>"u"&&(b.inclusiveStart=!0),typeof b.inclusiveEnd>"u"&&(b.inclusiveEnd=!0);var A=Le(e,g);return A&&(A.type==="number"||A.type==="integer")&&(!b.inclusiveStart&&typeof b.startKey=="number"&&typeof A.minimum=="number"&&b.startKey<A.minimum&&(b.inclusiveStart=!0),!b.inclusiveEnd&&typeof b.endKey=="number"&&typeof A.maximum=="number"&&b.endKey>A.maximum&&(b.inclusiveEnd=!0)),l&&!b.inclusiveStart&&(l=!1),p&&!b.inclusiveEnd&&(p=!1),b}),h=m.map(g=>g.startKey),d=m.map(g=>g.endKey),y;a.size===0?y=f.join(","):y=f.filter(g=>!a.has(g)).join(",");var v={index:f,startKeys:h,endKeys:d,inclusiveEnd:p,inclusiveStart:l,sortSatisfiedByIndex:!o&&s===y,selectorSatisfiedByIndex:Fi(f,t.selector,h,d)},w=Hi(e,t,v);(w>=u||t.index)&&(u=w,c=v)}),!c)throw Q("SNH",{query:t});return c}var Gt=new Set(["$eq","$gt","$gte","$lt","$lte"]),Mi=new Set(["$eq","$gt","$gte"]),$i=new Set(["$eq","$lt","$lte"]);function Fi(e,t,r,n){if(t.$and||t.$or)return!1;var o=Object.entries(t),a=new Set,i=new Set,s=!1,u=!1;for(var[c,f]of o){if(!e.includes(c))return!1;var p=Object.keys(f),l=0,m=void 0,h=0,d=void 0;for(var y of p){if(!Gt.has(y))return!1;Mi.has(y)&&(l++,m=y),$i.has(y)&&(h++,d=y)}if(l>1||h>1)return!1;if(m&&a.add(c),m!=="$eq"){if(s)return!1;s=!0}if(d&&i.add(c),d!=="$eq"){if(u)return!1;u=!0}}var v=0;for(var w of e){for(var g of[a,i]){if(!g.has(w)&&g.size>0)return!1;g.delete(w)}var x=r[v],S=n[v];if(x!==S&&a.size>0&&i.size>0)return!1;v++}return!0}function Di(e){if(!(!Array.isArray(e)||e.length===0)){var t=typeof e[0];if(!(t!=="string"&&t!=="number")){for(var r=e[0],n=e[0],o=0;o<e.length;o++){var a=e[o];if(typeof a!==t||t==="number"&&!isFinite(a))return;a<r&&(r=a),a>n&&(n=a)}return{startKey:r,endKey:n,inclusiveStart:!0,inclusiveEnd:!0}}}}function Li(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw Q("SNH")}}function Hi(e,t,r){var n=0,o=f=>{f>0&&(n=n+f)},a=10,i=$t(r.startKeys,f=>f!==de&&f!==X);o(i*a);var s=$t(r.endKeys,f=>f!==X&&f!==de);o(s*a);var u=$t(r.startKeys,(f,p)=>f===r.endKeys[p]);o(u*a*1.5);var c=r.sortSatisfiedByIndex?5:0;return o(c),n}function z(e,t){return e*16777619^t>>>0}function ho(e){if(Number.isNaN(e))return 2143289344;if(!Number.isFinite(e))return e>0?2139095040:4286578688;let t=Math.trunc(e),r=e-t,n=t|0;if(r!==0){let o=Math.floor(r*4294967296);n=z(n,o|0)}return n>>>0}function We(e){let t=0;for(let r=0;r<e.length;r++)t=z(t,e.charCodeAt(r));return t>>>0}function Bi(e){let t=0,r=e<0n,n=r?-e:e;if(n===0n)t=z(t,0);else for(;n>0n;){let o=Number(n&0xffn);t=z(t,o),n>>=8n}return z(t,+r)>>>0}function Wi(e){let t=We((e.name||"")+e.toString());return t=z(t,e.length),t>>>0}function ji(e){let t=0;for(let r=0;r<e.length;r++)t=z(t,e[r]);return t>>>0}function qi(e){let t=We(e.constructor.name),r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return t=z(t,ji(r)),t>>>0}function Ui(e,t){if(t.has(e))return 13;t.add(e);let r=1;for(let n=0;n<e.length;n++)r=z(r,Dr(e[n],t));return t.delete(e),r>>>0}function Ki(e,t){if(t.has(e))return 13;t.add(e);let r=Object.keys(e).sort(),n=We(e?.constructor?.name);for(let o of r)n=z(n,We(o)),n=z(n,Dr(e[o],t));return t.delete(e),n>>>0}var zi=[3735928559,305441741].map(e=>z(3,e)),Qi=z(1,0),Vi=z(2,0);function Dr(e,t){if(e===null)return Qi;switch(typeof e){case"undefined":return Vi;case"boolean":return zi[+e];case"number":return z(4,ho(e));case"string":return z(5,We(e));case"bigint":return z(6,Bi(e));case"function":return z(7,Wi(e));default:{if(ArrayBuffer.isView(e)&&!(e instanceof DataView))return z(12,qi(e));if(e instanceof Date)return z(10,ho(e.getTime()));if(e instanceof RegExp){let n=We(e.source);return z(11,z(n,We(e.flags)))}return Array.isArray(e)?z(8,Ui(e,t)):z(9,Ki(e,t))}}}function Lr(e){return Dr(e,new WeakSet)>>>0}var wt=class extends Error{},ot=Symbol("missing"),Ji="mingo: cycle detected while processing object/array",Re=e=>typeof e!="object"&&typeof e!="function"||e===null,go=e=>Re(e)||Oe(e)||me(e),yo={undefined:1,null:2,number:3,string:4,symbol:5,object:6,array:7,arraybuffer:8,boolean:9,date:10,regexp:11,function:12},we=(e,t)=>e<t?-1:e>t?1:0,Gi=(e,t)=>{let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),o=Math.min(r.length,n.length);for(let a=0;a<o;a++){let i=we(r[a],n[a]);if(i!==0)return i}return we(r.length,n.length)};function ve(e,t,r=!1){if(e===ot&&(e=void 0),t===ot&&(t=void 0),e===t||Object.is(e,t))return 0;let n=Ue(e),o=Ue(t),a=0;if(n===o)switch(n){case"number":case"string":case"boolean":return we(e,t);case"date":return we(+e,+t);case"regexp":return(a=we(e.source,t.source))?a:we(e.flags,t.flags);case"arraybuffer":return Gi(e,t);case"array":{let u=e.slice().sort(ve),c=t.slice().sort(ve),f=Math.min(u.length,c.length);for(let p=0;p<f;p++)if(a=ve(u[p],c[p]))return a;return we(u.length,c.length)}default:{if(n!=="object"&&e?.constructor===t?.constructor&&vo(e))return we(e.toString(),t.toString());let u=Object.keys(e).sort(),c=Object.keys(t).sort();if(a=ve(u,c))return a;for(let f of u)if(a=ve(e[f],t[f]))return a;return 0}}if(n=="undefined")return-1;if(o=="undefined")return 1;if(r){if(n=="array"){let u=e;if(!u.length)return-1;let c=u.slice().sort(ve);a=1;for(let f of c)if((a=Math.min(a,ve(f,t)))<0)return a;return a}if(o=="array"){let u=t;if(!u.length)return 1;let c=u.slice().sort(ve);a=-1;for(let f of c)if((a=Math.max(a,ve(e,f)))>0)return a;return a}}let i=yo[n]??Number.MAX_VALUE,s=yo[o]??Number.MAX_VALUE;return i!==s?we(i,s):we(n,o)}var oe=(e,t)=>ve(e,t,!0),vo=e=>e!=null&&e.toString!==Object.prototype.toString;function _e(e,t){if(e===t||Object.is(e,t))return!0;if(e===null||t===null||typeof e!=typeof t||typeof e!="object"||e.constructor!==t?.constructor)return!1;if(Oe(e))return Oe(t)&&+e==+t;if(me(e))return me(t)&&e.source===t.source&&e.flags===t.flags;if(M(e)&&M(t))return e.length===t.length&&e.every((i,s)=>_e(i,t[s]));if(e?.constructor!==Object&&vo(e))return e?.toString()===t?.toString();let r=e,n=t,o=Object.keys(r),a=Object.keys(n);return o.length!==a.length?!1:o.every(i=>se(n,i)&&_e(r[i],n[i]))}var qe=class e extends Map{#e=new Map;#t=t=>{let r=Lr(t);return[(this.#e.get(r)??[]).find(o=>_e(o,t)),r]};constructor(){super()}static init(){return new e}clear(){super.clear(),this.#e.clear()}delete(t){if(Re(t))return super.delete(t);let[r,n]=this.#t(t);return super.delete(r)?(this.#e.set(n,this.#e.get(n).filter(o=>!_e(o,r))),!0):!1}get(t){if(Re(t))return super.get(t);let[r,n]=this.#t(t);return super.get(r)}has(t){if(Re(t))return super.has(t);let[r,n]=this.#t(t);return super.has(r)}set(t,r){if(Re(t))return super.set(t,r);let[n,o]=this.#t(t);if(super.has(n))super.set(n,r);else{super.set(t,r);let a=this.#e.get(o)||[];a.push(t),this.#e.set(o,a)}return this}get size(){return super.size}};function $(e,t){if(!e)throw new wt(t)}var Hr=e=>{if(e==="__proto__"||e.startsWith("__proto__.")||e.endsWith(".__proto__")||e.includes(".__proto__."))throw new wt(`Accessing __proto__ is not allowed in selector: '${e}'.`)};function Ue(e){let t=typeof e;switch(t){case"number":case"string":case"boolean":case"undefined":case"function":case"symbol":return t}return e===null?"null":M(e)?"array":Oe(e)?"date":me(e)?"regexp":bo(e)?"arraybuffer":e?.constructor===Object?"object":e?.constructor?.name?.toLowerCase()??"object"}var xt=e=>typeof e=="boolean",re=e=>typeof e=="string";var G=e=>!Number.isNaN(e)&&typeof e=="number",Xi=Number.isInteger,M=Array.isArray,V=e=>Ue(e)==="object",wo=e=>!Re(e),Oe=e=>e instanceof Date,me=e=>e instanceof RegExp;var ne=e=>e==null,xo=(e,t=!0)=>!!e||t&&e==="",bt=e=>ne(e)||re(e)&&!e||M(e)&&e.length===0||V(e)&&Object.keys(e).length===0,ke=e=>M(e)?e:[e],se=(e,t,r="",n="")=>!!(e&&Object.prototype.hasOwnProperty.call(e,t)&&(r===""||Object.prototype.hasOwnProperty.call(e,r))&&(n===""||Object.prototype.hasOwnProperty.call(e,n))),bo=e=>typeof ArrayBuffer<"u"&&ArrayBuffer.isView(e),Xt=e=>{for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<48||e.charCodeAt(t)>57)return!1;return!0},Te=(e,t)=>{if(Re(e))return e;if(Oe(e))return new Date(e);if(me(e))return new RegExp(e);if(bo(e)){let r=e.constructor;return new r(e)}if(t instanceof WeakSet||(t=new WeakSet),t.has(e))throw new Error(Ji);t.add(e);try{if(M(e)){let r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=Te(e[n],t);return r}if(V(e)){let r={};for(let n of Object.keys(e))r[n]=Te(e[n],t);return r}}finally{t.delete(e)}return e};function St(e){if(e.length===0)return[];if(e.length===1)return e[0].slice();for(let n of e)if(n.length===0)return[];let t=[qe.init(),qe.init()],r=0;for(let n of e[e.length-1])t[0].set(n,!0);for(let n=e.length-2;n>=0;n--){for(let o=0;o<e[n].length;o++){let a=e[n][o];t[r].has(a)&&t[r^1].set(a,!0)}if(t[r^1].size===0)return[];t[r].clear(),r=r^1}return Array.from(t[r].keys())}function rr(e,t=1){let r=new Array;function n(o,a){for(let i=0,s=o.length;i<s;i++)M(o[i])&&(a>0||a<0)?n(o[i],Math.max(-1,a-1)):r.push(o[i])}return n(e,t),r}function Br(e){let t=qe.init();for(let r of e)t.set(r,!0);return Array.from(t.keys())}function Wr(e,t){if(e.length<1)return new Map;let r=qe.init();for(let n=0;n<e.length;n++){let o=e[n],a=t(o,n)??null,i=r.get(a);i?i.push(o):(i=[o],r.set(a,i))}return r}var Yi=new Set(Object.getOwnPropertyNames(Object.prototype).find(e=>e!=="__proto__"));function Yt(e,t){if(!(Re(e)||Number.isNaN(t)))return M(e)?e[typeof t=="number"?t:Number(t)]:!Yi.has(t)||se(e,t)?e[t]:void 0}function Zi(e,t){if(t<1)return e;for(;t--&&e.length===1&&M(e[0]);)e=e[0];return e}function Y(e,t,r){if(Hr(t),go(e))return e;if(!t.includes(".")&&!M(e))return Yt(e,t);let n=0;function o(i,s){let u=i,c=0,f=0;for(;f!==-1;){f=s.indexOf(".",c);let p=f===-1?s.substring(c):s.substring(c,f);if(!Xt(p)&&M(u)){if(c===0&&n>0)break;n+=1;let m=s.substring(c);u=u.reduce((h,d)=>{let y=o(d,m);return y!==void 0&&h.push(y),h},[]);break}else u=Yt(u,p);if(u===void 0)break;c+=p.length+1}return u}let a=o(e,t);return M(a)&&r?.unwrapArray?Zi(a,n):a}function je(e,t,r){r?.ignoreProto!==!0&&(Hr(t),r={...r,ignoreProto:!0});let n=t.indexOf("."),o=n==-1?t:t.substring(0,n),a=t.substring(n+1),i=n!=-1;if(M(e)){let c=Xt(o),f=c&&r?.preserveIndex?e.slice():[];if(c){let p=Number(o),l=Yt(e,o);i&&(l=je(l,a,r)),r?.preserveIndex?f[p]=l:f.push(l)}else for(let p of e){let l=je(p,t,r);r?.preserveMissing?f.push(l??ot):(l!=null||r?.preserveIndex)&&f.push(l)}return f}let s=r?.preserveKeys?{...e}:{},u=Yt(e,o);if(i&&(u=je(u,a,r)),u!==void 0)return s[o]=u,s}function Zt(e){if(M(e))for(let t=e.length-1;t>=0;t--)e[t]===ot?e.splice(t,1):Zt(e[t]);else if(V(e))for(let t of Object.keys(e))se(e,t)&&Zt(e[t])}function er(e,t,r,n){n?.ignoreProto!==!0&&(Hr(t),n={...n,ignoreProto:!0});let o=t.indexOf("."),a=o===-1?t:t.substring(0,o),i=t.substring(a.length+1);if(i.length===0)(V(e)||M(e)&&Xt(a))&&r(e,a);else{n?.buildGraph&&ne(e[a])&&(e[a]={});let s=e[a];if(!s)return;let u=i.indexOf("."),c=u===-1?i:i.substring(0,u),f=Xt(c);M(s)&&n?.descendArray&&!f?s.forEach((p=>er(p,i,r,n))):er(s,i,r,n)}}function Ke(e,t,r){er(e,t,(n,o)=>n[o]=r,{buildGraph:!0})}function jr(e,t,r){er(e,t,((n,o)=>{M(n)?n.splice(Number(o),1):V(n)&&delete n[o]}),r)}var he=e=>!!e&&e[0]==="$"&&/^\$[a-zA-Z0-9_]+$/.test(e);function ze(e){if(go(e))return me(e)?{$regex:e}:{$eq:e};if(wo(e)){if(!Object.keys(e).some(he))return{$eq:e};if(V(e)&&se(e,"$regex")){let t={...e};return t.$regex=new RegExp(e.$regex,e.$options),delete t.$options,t}}return e}var tr=class{constructor(){this.root={children:new Map,isTerminal:!1}}add(t){let r=t.split("."),n=this.root;for(let o of r){if(n.isTerminal)return!1;n.children.has(o)||n.children.set(o,{children:new Map,isTerminal:!1}),n=n.children.get(o)}return n.isTerminal||n.children.size?!1:n.isTerminal=!0}};var _t=(e=>(e[e.CLONE_OFF=0]="CLONE_OFF",e[e.CLONE_INPUT=1]="CLONE_INPUT",e[e.CLONE_OUTPUT=2]="CLONE_OUTPUT",e[e.CLONE_ALL=3]="CLONE_ALL",e))(_t||{}),xe=class e{constructor(t,r){this.options=t,this.#e=r?{...r}:{}}#e;static init(t){return t instanceof e?new e(t.options,t.#e):new e({idKey:"_id",scriptEnabled:!0,useStrictMode:!0,failOnError:!0,processingMode:0,...t,context:t?.context?Qe.from(t?.context):Qe.init()})}update(t){return Object.assign(this.#e,t,{timestamp:this.#e.timestamp,variables:{...this.#e?.variables,...t?.variables}}),this}get local(){return this.#e}get now(){let t=this.#e.timestamp??0;return t||(t=Date.now(),Object.assign(this.#e,{timestamp:t})),new Date(t)}get idKey(){return this.options.idKey}get collation(){return this.options?.collation}get processingMode(){return this.options?.processingMode}get useStrictMode(){return this.options?.useStrictMode}get scriptEnabled(){return this.options?.scriptEnabled}get failOnError(){return this.options?.failOnError}get collectionResolver(){return this.options?.collectionResolver}get jsonSchemaValidator(){return this.options?.jsonSchemaValidator}get variables(){return this.options?.variables}get context(){return this.options?.context}},Ce=(e=>(e.ACCUMULATOR="accumulator",e.EXPRESSION="expression",e.PIPELINE="pipeline",e.PROJECTION="projection",e.QUERY="query",e.WINDOW="window",e))(Ce||{}),Qe=class e{#e;constructor(){this.#e={accumulator:{},expression:{},pipeline:{},projection:{},query:{},window:{}}}static init(t={}){let r=new e;for(let n of Object.keys(t))r.#e[n]={...t[n]};return r}static from(...t){if(t.length===1)return e.init(t[0].#e);let r=new e;for(let n of t)for(let o of Object.values(Ce))r.addOps(o,n.#e[o]);return r}addOps(t,r){return this.#e[t]=Object.assign({},r,this.#e[t]),this}getOperator(t,r){return this.#e[t][r]??null}addAccumulatorOps(t){return this.addOps("accumulator",t)}addExpressionOps(t){return this.addOps("expression",t)}addQueryOps(t){return this.addOps("query",t)}addPipelineOps(t){return this.addOps("pipeline",t)}addProjectionOps(t){return this.addOps("projection",t)}addWindowOps(t){return this.addOps("window",t)}};function at(e,t,r){let n=!(r instanceof xe)||ne(r.local.root)?xe.init(r).update({root:e}):r;return nr(e,t,n)}var es=new Set(["$$ROOT","$$CURRENT","$$REMOVE","$$NOW"]);function nr(e,t,r){if(re(t)&&t.length>0&&t[0]==="$"){if(t==="$$KEEP"||t==="$$PRUNE"||t==="$$DESCEND")return t;let n=r.local.root,o=t.indexOf("."),a=o===-1?t:t.substring(0,o);if(es.has(a)){switch(a){case"$$ROOT":break;case"$$CURRENT":n=e;break;case"$$REMOVE":n=void 0;break;case"$$NOW":n=new Date(r.now);break}t=o===-1?"":t.substring(o+1)}else if(a.length>=2&&a[1]==="$"){n=Object.assign({},r.variables,{this:e},r?.local?.variables);let i=a.substring(2);$(se(n,i),`Use of undefined variable: ${i}`),t=t.substring(2)}else t=t.substring(1);return t===""?n:Y(n,t)}if(M(t)){let n=new Array(t.length);for(let o=0;o<t.length;o++)n[o]=nr(e,t[o],r);return n}if(V(t)){let n=Object.keys(t);if(he(n[0]))return $(n.length===1,"Expression must contain a single operator."),ts(e,t[n[0]],n[0],r);let o={};for(let a=0;a<n.length;a++)o[n[a]]=nr(e,t[n[a]],r);return o}return t}function ts(e,t,r,n){let o=n.context,a=o.getOperator("expression",r);if(a)return a(e,t,n);let i=o.getOperator("accumulator",r);return $(!!i,`accumulator '${r}' is not registered.`),M(e)||(e=nr(e,t,n),t=null),$(M(e),`arguments must resolve to array for ${r}.`),i(e,t,n)}function Ee(e){return new qr(e)}function So(...e){let t=0;return Ee(()=>{for(;t<e.length;){let r=e[t].next();if(!r.done)return r;t++}return{done:!0,value:void 0}})}function rs(e){return!!e&&typeof e=="object"&&typeof e?.next=="function"}function ns(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e[Symbol.iterator]=="function"}var qr=class{#e=[];#t=[];#r;#o=!1;constructor(t){let r;ns(t)?r=t[Symbol.iterator]():rs(t)?r=t:typeof t=="function"?r={next:t}:$(0,"mingo: iterator requires an iterable, generator or function");let n=-1;this.#r=()=>{for(;;){let{value:o,done:a}=r.next();if(a)return{done:a};let i=!0;n++;for(let s=0;s<this.#e.length;s++){let{op:u,fn:c}=this.#e[s],f=c(o,n);if(u==="map")o=f;else if(!f){i=!1;break}}if(i)return{value:o,done:a}}}}push(t,r){return this.#e.push({op:t,fn:r}),this}next(){return this.#r()}map(t){return this.push("map",t)}filter(t){return this.push("filter",t)}take(t){return $(t>=0,"value must be a non-negative integer"),this.filter(r=>t-- >0)}drop(t){return $(t>=0,"value must be a non-negative integer"),this.filter(r=>t--<=0)}transform(t){let r=this,n;return Ee(()=>(n||(n=t(r.collect())),n.next()))}collect(){for(;!this.#o;){let{done:t,value:r}=this.#r();t||this.#t.push(r),this.#o=t}return this.#t}each(t){for(let r=this.next();r.done!==!0;r=this.next())t(r.value)}reduce(t,r){let n=this.next();for(r===void 0&&!n.done&&(r=n.value,n=this.next());!n.done;)r=t(r,n.value),n=this.next();return r}size(){return this.collect().length}[Symbol.iterator](){return this}};function _o(e,t,r){return e.take(t)}var zl=Ee([]);function Ur(e,t,r=!0){let n={exclusions:[],inclusions:[],positional:0},o=Object.keys(e);$(o.length,"Invalid empty sub-projection");let a=t?.idKey,i=!1;for(let s of o){if(s.startsWith("$"))return $(!r&&o.length===1,`FieldPath field names may not start with '$', given '${s}'.`),n;s.endsWith(".$")&&n.positional++;let u=e[s];if(u===!1||G(u)&&u===0)s===a?i=!0:n.exclusions.push(s);else if(!V(u))n.inclusions.push(s);else{let c=Ur(u,t,!1);if(!c.inclusions.length&&!c.exclusions.length)n.inclusions.includes(s)||n.inclusions.push(s);else{for(let f of c.exclusions)n.exclusions.push(`${s}.${f}`);for(let f of c.inclusions)n.inclusions.push(`${s}.${f}`)}n.positional+=c.positional}$(!(n.exclusions.length&&n.inclusions.length),"Cannot do exclusion and inclusion in projection."),$(n.positional<=1,"Cannot specify more than one positional projection.")}if(i&&n.exclusions.push(a),r){let s=new tr;for(let u of n.exclusions)$(s.add(u),`Path collision at ${u}.`);for(let u of n.inclusions)$(s.add(u),`Path collision at ${u}.`);n.exclusions.sort(),n.inclusions.sort()}return n}var Kr="$project";function or(e,t,r){if(bt(t))return e;let n=Ur(t,r),o=os(t,xe.init(r),n);return e.map(o)}function os(e,t,r){let n=t.idKey,{exclusions:o,inclusions:a}=r,i={},s={preserveMissing:!0};for(let l of o)i[l]=(m,h)=>{jr(m,l,{descendArray:!0})};for(let l of a){let m=Y(e,l)??e[l];if(l.endsWith(".$")&&m===1){let h=t?.local?.condition??{};$(h,`${Kr}: positional operator '.$' requires array condition.`);let d=l.slice(0,-2);i[d]=ss(d,h,t);continue}if(M(m))i[l]=(h,d)=>{t.update({root:d});let y=m.map(v=>at(d,v,t)??null);Ke(h,l,y)};else if(G(m)||m===!0)i[l]=(h,d)=>{t.update({root:d});let y=je(d,l,s);Eo(h,y)};else if(!V(m))i[l]=(h,d)=>{t.update({root:d});let y=at(d,m,t);Ke(h,l,y)};else{let h=Object.keys(m);$(h.length===1&&he(h[0]),"Not a valid operator");let d=h[0],y=m[d],v=t.context.getOperator(Ce.PROJECTION,d);!v||d==="$slice"&&!ke(y).every(G)?i[l]=(g,x)=>{t.update({root:x});let S=at(x,m,t);Ke(g,l,S)}:i[l]=(g,x)=>{t.update({root:x});let S=v(x,y,l,t);Ke(g,l,S)}}}let u=o.length===1&&o.includes(n),c=!o.includes(n),f=!a.length,p=f&&u||f&&o.length&&!u;return l=>{let m={};p&&Object.assign(m,l);for(let h in i)i[h](m,l);return f||Zt(m),c&&!se(m,n)&&se(l,n)&&(m[n]=Y(l,n)),m}}var Oo=(e,t,r,n)=>{let o=Y(e,t);M(o)||(o=Y(o,r)),$(M(o),`${Kr}: field '${t}' must resolve to array`);let a=[];for(let i=0;i<o.length;i++)n({[r]:[o[i]]})&&a.push(i);return a},as=e=>(t=>!e(t)),is={$and:1,$or:1,$nor:1};function ss(e,t,r){let n=Object.entries(t).slice(),o={$and:[],$or:[]};for(let u=0;u<n.length;u++){let[c,f,p]=n[u];if(c===e||c.startsWith(e+".")){let l=ze(f),m=Object.keys(l)[0],h=l[m],d=r.context.getOperator(Ce.QUERY,m),y=c.substring(c.lastIndexOf(".")+1),v=d(y,h,r);!p||p==="$and"?o.$and.push([c,v,y]):p==="$nor"?o.$and.push([c,as(v),y]):p==="$or"&&o.$or.push([c,v,y])}else if(he(c)){$(!!is[c],`${Kr}: '${c}' is not allowed in this context`);for(let l of f)for(let m of Object.keys(l))n.push([m,l[m],c])}}let a=e.lastIndexOf("."),i=e.substring(0,a)||e,s=e.substring(a+1);return(u,c)=>{let f=[];for(let[m,h,d]of o.$and)f.push(Oo(c,m,d,h));if(o.$or.length){let m=[];for(let[h,d,y]of o.$or)m.push(...Oo(c,h,y,d));f.push(Br(m))}let p=St(f).sort()[0],l=Y(c,e)[p];i!=s&&!V(l)&&(l={[s]:l}),Ke(u,i,[l])}}function Eo(e,t){if(e===ot||ne(e))return t;if(ne(t))return e;let r=e,n=t;for(let o of Object.keys(t))r[o]=Eo(r[o],n[o]);return r}function Io(e,t,r){return $(t>=0,"$skip value must be a non-negative integer"),e.drop(t)}function ar(e,t,r){$(V(t)&&Object.keys(t).length>0,"$sort specification is invalid");let n=oe,o=r.collation;return V(o)&&re(o.locale)&&(n=cs(o)),e.transform(a=>{let i=Object.keys(t);for(let s of i.reverse()){let u=Wr(a,l=>Y(l,s)),c=Array.from(u.keys()),f=!1;if(n===oe){let l=!0,m=!0;for(let h of c)if(l&&=re(h),m&&=G(h),!l&&!m)break;if(f=l||m,l)c.sort();else if(m){let h=new Float64Array(c).sort();for(let d=0;d<h.length;d++)c[d]=h[d]}}f||c.sort(n),t[s]===-1&&c.reverse();let p=0;for(let l of c)for(let m of u.get(l))a[p++]=m;$(p==a.length,"bug: counter must match collection size.")}return Ee(a)})}var us={1:"base",2:"accent",3:"variant"};function cs(e){let t={sensitivity:us[e.strength||3],caseFirst:e.caseFirst==="off"?"false":e.caseFirst,numeric:e.numericOrdering||!1,ignorePunctuation:e.alternate==="shifted"};e.caseLevel===!0&&(t.sensitivity==="base"&&(t.sensitivity="case"),t.sensitivity==="accent"&&(t.sensitivity="variant"));let r=new Intl.Collator(e.locale,t);return(n,o)=>re(n)&&re(o)?r.compare(n,o):oe(n,o)}var Po={$sort:ar,$skip:Io,$limit:_o},ir=class{#e;#t;#r;#o;#i={};#n=null;#a=[];constructor(t,r,n,o){this.#e=t,this.#t=r,this.#r=n,this.#o=o}fetch(){if(this.#n)return this.#n;this.#n=Ee(this.#e).filter(this.#t);let t=this.#o.processingMode;t&_t.CLONE_INPUT&&this.#n.map(r=>Te(r));for(let r of Object.keys(Po))if(se(this.#i,r)){let n=Po[r];this.#n=n(this.#n,this.#i[r],this.#o)}return Object.keys(this.#r).length&&(this.#n=or(this.#n,this.#r,this.#o)),t&_t.CLONE_OUTPUT&&this.#n.map(r=>Te(r)),this.#n}fetchAll(){let t=Ee(Array.from(this.#a));return this.#a.length=0,So(t,this.fetch())}all(){return this.fetchAll().collect()}skip(t){return this.#i.$skip=t,this}limit(t){return this.#i.$limit=t,this}sort(t){return this.#i.$sort=t,this}collation(t){return this.#o={...this.#o,collation:t},this}next(){if(this.#a.length>0)return this.#a.pop();let t=this.fetch().next();if(!t.done)return t.value}hasNext(){if(this.#a.length>0)return!0;let t=this.fetch().next();return t.done?!1:(this.#a.push(t.value),!0)}[Symbol.iterator](){return this.fetchAll()}};var fs=new Set(["$and","$or","$nor","$expr","$jsonSchema"]),ue=class{#e;#t;#r;constructor(t,r){this.#t=Te(t),this.#r=xe.init(r).update({condition:t}),this.#e=[],this.compile()}compile(){$(V(this.#t),`query criteria must be an object: ${JSON.stringify(this.#t)}`);let t={};for(let r of Object.keys(this.#t)){let n=this.#t[r];if(r==="$where")$(this.#r.scriptEnabled,"$where operator requires 'scriptEnabled' option to be true."),Object.assign(t,{field:r,expr:n});else if(fs.has(r))this.processOperator(r,r,n);else{$(!he(r),`unknown top level operator: ${r}`);let o=ze(n);for(let a of Object.keys(o))this.processOperator(r,a,o[a])}t.field&&this.processOperator(t.field,t.field,t.expr)}}processOperator(t,r,n){let o=this.#r.context.getOperator(Ce.QUERY,r);$(!!o,`unknown query operator ${r}`),this.#e.push(o(t,n,this.#r))}test(t){return this.#e.every(r=>r(t))}find(t,r){return new ir(t,n=>this.test(n),r||{},this.#r)}};function ls(e,t){let r=a=>a,n=!0;for(let a of Object.keys(e))if(n&&=he(a)&&a!=="$and"&&a!=="$or"&&a!=="$nor",!n)break;n&&(e={field:e},r=a=>({field:a}));let o=new ue(e,t);return a=>o.test(r(a))}function q(e,t,r,n){let[o,a]=[-1,0];for(;(o=e.indexOf(".",o+1))!==-1;)a++;let i=xe.init(r).update({depth:a}),s={unwrapArray:!0};return n===Vr&&(t=ls(t,r)),u=>{let c=Y(u,e,s);return n(c,t,i)}}function zr(e,t,r){if(_e(e,t)||ne(e)&&ne(t))return!0;if(M(e)){let n=r?.local?.depth??1;return e.some(o=>_e(o,t))||rr(e,n).some(o=>_e(o,t))}return!1}function To(e,t,r){return!zr(e,t,r)}function Qr(e,t,r){return ne(e)?t.some(n=>n===null):St([ke(e),t]).length>0}function ko(e,t,r){return!Qr(e,t,r)}function Co(e,t,r){return sr(e,t,(n,o)=>oe(n,o)<0)}function No(e,t,r){return sr(e,t,(n,o)=>oe(n,o)<=0)}function Mo(e,t,r){return sr(e,t,(n,o)=>oe(n,o)>0)}function $o(e,t,r){return sr(e,t,(n,o)=>oe(n,o)>=0)}function Fo(e,t,r){return ke(e).some((n=>t.length===2&&n%t[0]===t[1]))}function Do(e,t,r){let n=ke(e),o=a=>re(a)&&xo(t.exec(a),r?.useStrictMode);return n.some(o)||rr(n,1).some(o)}function Lo(e,t,r){return Array.isArray(e)&&e.length===t}function Vr(e,t,r){if(M(e)&&!bt(e)){for(let n=0,o=e.length;n<o;n++)if(t(e[n]))return!0}return!1}var Ao=e=>e===null,ps={array:M,boolean:xt,bool:xt,date:Oe,number:G,int:G,long:G,double:G,decimal:G,null:Ao,object:V,regexp:me,regex:me,string:re,undefined:ne,1:G,2:re,3:V,4:M,6:ne,8:xt,9:Oe,10:Ao,11:me,16:G,18:G,19:G};function Ro(e,t,r){let n=ps[t];return n?n(e):!1}function Ho(e,t,r){return M(t)?t.findIndex(n=>Ro(e,n,r))>=0:Ro(e,t,r)}function sr(e,t,r){for(let n of ke(e))if(Ue(n)===Ue(t)&&r(n,t))return!0;return!1}var Bo=(e,t,r)=>q(e,t,r,Vr);var Wo=(e,t,r)=>q(e,t,r,Lo);var Jr=(e,t,r)=>q(e,t,r,zr);var Gr=(e,t,r)=>q(e,t,r,Mo);var Xr=(e,t,r)=>q(e,t,r,$o);var Yr=(e,t,r)=>q(e,t,r,Qr);var Zr=(e,t,r)=>q(e,t,r,Co);var en=(e,t,r)=>q(e,t,r,No);var tn=(e,t,r)=>q(e,t,r,To);var rn=(e,t,r)=>q(e,t,r,ko);var jo=(e,t,r)=>{let n=e.includes("."),o=!!t;if(!n||e.match(/\.\d+$/))return s=>Y(s,e)!==void 0===o;let a=e.substring(0,e.lastIndexOf(".")),i={preserveIndex:!0};return s=>{let u=je(s,e,i),c=Y(u,a);return M(c)?c.some(f=>f!==void 0)===o:c!==void 0===o}};var qo=(e,t,r)=>q(e,t,r,Ho);var Uo=(e,t,r)=>q(e,t,r,Fo);var Ko=(e,t,r)=>q(e,t,r,Do);var zo=(e,t,r)=>{$(M(t),"$and expects value to be an Array.");let n=t.map(o=>new ue(o,r));return o=>n.every(a=>a.test(o))};function ur(e,t,r){$(M(t),"Invalid expression. $or expects value to be an Array");let n=t.map(o=>new ue(o,r));return o=>n.some(a=>a.test(o))}function Qo(e,t,r){$(M(t),"Invalid expression. $nor expects value to be an array.");let n=ur("$or",t,r);return o=>!n(o)}function Vo(e,t,r){let n={};n[e]=ze(t);let o=new ue(n,r);return a=>!o.test(a)}var Jo=!1,Go;function Xo(e){return Jo||(Go=Qe.init({pipeline:{$sort:ar,$project:or},query:{$elemMatch:Bo,$eq:Jr,$nor:Qo,$exists:jo,$regex:Ko,$and:zo,$gt:Gr,$gte:Xr,$in:Yr,$lt:Zr,$lte:en,$ne:tn,$nin:rn,$mod:Uo,$not:Vo,$or:ur,$size:Wo,$type:qo}}),Jo=!0),new ue(e,{context:Go})}function Yo(e,t,r){var n=ie(e.primaryKey),o=Tn(t);if(typeof o.skip!="number"&&(o.skip=0),o.selector?(o.selector=o.selector,cr(o.selector)):o.selector={},o.index){var a=Nt(o.index);a.includes(n)||a.push(n),o.index=a}if(r&&!o.sort)o.sort=[{[n]:"asc"}];else if(o.sort){var p=o.sort.find(l=>Rn(l)===n);p||(o.sort=o.sort.slice(0),o.sort.push({[n]:"asc"}))}else if(o.index)o.sort=o.index.map(l=>({[l]:"asc"}));else{if(e.indexes){var i=new Set;Object.entries(o.selector).forEach(([l,m])=>{var h;typeof m=="object"&&m!==null?h=!!Object.keys(m).find(d=>Gt.has(d)):h=!0,h&&i.add(l)});var s=-1,u;e.indexes.forEach(l=>{var m=Mt(l)?l:[l],h=m.findIndex(y=>!i.has(y)),d=h===-1?m.length:h;d>0&&d>s&&(s=d,u=m)}),u&&(o.sort=u.map(l=>({[l]:"asc"})))}if(!o.sort)if(e.indexes&&e.indexes.length>0){var c=e.indexes[0],f=Mt(c)?c:[c];o.sort=f.map(l=>({[l]:"asc"}))}else o.sort=[{[n]:"asc"}]}return o}function Zo(e,t){if(!t.sort)throw Q("SNH",{query:t});var r=[];t.sort.forEach(o=>{var a=Object.keys(o)[0],i=Object.values(o)[0];r.push({key:a,direction:i,getValueFn:Lt(a)})});var n=(o,a)=>{for(var i=0;i<r.length;++i){var s=r[i],u=s.getValueFn(o),c=s.getValueFn(a);if(u!==c){var f=s.direction==="asc"?1:-1,p=typeof u;if(p===typeof c&&(p==="string"||p==="number"))return(u<c?-1:1)*f;var l=s.direction==="asc"?oe(u,c):oe(c,u);return l}}};return n}function ea(e,t){if(!t.sort)throw Q("SNH",{query:t});var r=Xo(t.selector),n=o=>r.test(o);return n}var ta=new Set(["$and","$or","$nor"]),ds=new Set(["$not"]);function ms(e){var t=Object.keys(e);return t.length===0?!1:t.some(r=>!r.startsWith("$"))?!0:t.some(r=>ta.has(r)||ds.has(r))}function cr(e){Object.entries(e).forEach(([t,r])=>{if(typeof r!="object"||r===null)e[t]={$eq:r};else if(ta.has(t)&&Array.isArray(r))r.forEach(o=>cr(o));else if(t==="$not"&&typeof r=="object")cr(r);else if(!t.startsWith("$")&&typeof r=="object"){var n=r;n.$elemMatch&&typeof n.$elemMatch=="object"&&ms(n.$elemMatch)&&cr(n.$elemMatch)}})}function ra(e,t){if(!t.sort)throw Q("SNH",{query:t});var r=mo(e,t);return{query:t,queryPlan:r}}var hs=$n(10),ys=0;function gs(){return hs+ ++ys}function oa(e,t,r,n,o,a,i){for(var s=!!e.schema.attachments,u=[],c=[],f=[],p=gs(),l={id:p,events:[],checkpoint:null,context:o},m=l.events,h=[],d=[],y=[],v=r.size>0,w,g=n.length,x=0;x<g;x++){var S=n[x],b=S.document,R=S.previous,A=b[t],T=b._deleted,C=R&&R._deleted,L=void 0;v&&(L=r.get(A));var J=void 0;if(L){var K=L._rev;if(!R||R&&K!==R._rev){var N={isError:!0,status:409,documentId:A,writeRow:S,documentInDb:L,context:o};f.push(N);continue}var F=s?na(S):S;if(s)if(T){if(R)for(var At=R._attachments,pn=Object.keys(At),mr=0;mr<pn.length;mr++){var dn=pn[mr];d.push({documentId:A,attachmentId:dn,digest:At[dn].digest})}}else{for(var Rt=b._attachments,Tt=Object.keys(Rt),hr=0;hr<Tt.length;hr++){var yr=Tt[hr],ni=Rt[yr],oi=R?R._attachments[yr]:void 0;if(!oi&&!ni.data){J={documentId:A,documentInDb:L,isError:!0,status:510,writeRow:S,attachmentId:yr,context:o};break}}if(!J){for(var gr=0;gr<Tt.length;gr++){var pt=Tt[gr],dt=Rt[pt],mn=R?R._attachments[pt]:void 0;if(!mn)h.push({documentId:A,attachmentId:pt,attachmentData:dt,digest:dt.digest});else{var ai=F.document._attachments[pt].digest;dt.data&&mn.digest!==ai&&y.push({documentId:A,attachmentId:pt,attachmentData:dt,digest:dt.digest})}}if(R)for(var hn=R._attachments,yn=Object.keys(hn),vr=0;vr<yn.length;vr++){var wr=yn[vr];Rt[wr]||d.push({documentId:A,attachmentId:wr,digest:hn[wr].digest})}}}J?f.push(J):(c.push(F),i&&i(b),w=F);var kt=void 0,xr=null,Ct=void 0;if(C&&!T)Ct="INSERT",kt=s?F.document:b;else if(R&&!C&&!T)Ct="UPDATE",kt=s?F.document:b,xr=R;else if(T)Ct="DELETE",kt=H(b),xr=R;else throw Q("SNH",{args:{writeRow:S}});var ii={documentId:A,documentData:kt,previousDocumentData:xr,operation:Ct};m.push(ii)}else{if(s)for(var _=b._attachments,O=Object.keys(_),I=0;I<O.length;I++){var E=O[I],k=_[E];k.data?h.push({documentId:A,attachmentId:E,attachmentData:k,digest:k.digest}):(J={documentId:A,isError:!0,status:510,writeRow:S,attachmentId:E,context:o},f.push(J))}var P=void 0;if(!J){var B=s?na(S):S;P=B,u.push(B),a&&a(b),w=B}if(!T){var U=b;s&&(U=P?P.document:nn(b));var W={documentId:A,operation:"INSERT",documentData:U,previousDocumentData:s&&R?nn(R):R};m.push(W)}}}return{bulkInsertDocs:u,bulkUpdateDocs:c,newestRow:w,errors:f,eventBulk:l,attachmentsAdd:h,attachmentsRemove:d,attachmentsUpdate:y}}function na(e){return{previous:e.previous,document:nn(e.document)}}function on(e){var t=e.data;if(!t)return e;var r={length:t.size,digest:e.digest,type:e.type};return r}function nn(e){var t=e._attachments;if(!t)return e;var r=!1;for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){r=!0;break}if(!r)return e;for(var o=_r(e),a={},i=Object.keys(t),s=0;s<i.length;s++){var u=i[s];a[u]=on(t[u])}return o._attachments=a,o}function aa(e){if(e.schema.keyCompression)throw Q("UT5",{args:{params:e}});if(vs(e.schema))throw Q("UT6",{args:{params:e}});if(e.schema.attachments&&e.schema.attachments.compression)throw Q("UT7",{args:{params:e}})}function vs(e){return!!(e.encrypted&&e.encrypted.length>0||e.attachments&&e.attachments.encrypted)}function ws(e,t,r){var n=ie(e.schema.primaryKey),o=r?r.lwt:Or,a=r?r.id:"";return Yo(e.schema,{selector:{$or:[{"_meta.lwt":{$gt:o}},{"_meta.lwt":{$eq:o},[n]:{$gt:r?a:""}}],"_meta.lwt":{$gte:o}},sort:[{"_meta.lwt":"asc"},{[n]:"asc"}],skip:0,limit:t})}async function ia(e,t,r){if(e.getChangedDocumentsSince)return e.getChangedDocumentsSince(t,r);var n=ie(e.schema.primaryKey),o=ra(e.schema,ws(e,t,r)),a=await e.query(o),i=a.documents,s=Fe(i);return{documents:i,checkpoint:s?{id:s[n],lwt:s._meta.lwt}:r||{id:"",lwt:0}}}function sa(e,t){var r=t.map(n=>{var o=Le(e,n);if(!o)throw Q("CI1",{fieldName:n});var a=o.type,i;(a==="number"||a==="integer")&&(i=sn(o));var s=Lt(n),u=o.maxLength?o.maxLength:0,c;if(a==="string")c=w=>{var g=s(w);return g||(g=""),g.padEnd(u," ")};else if(a==="boolean")c=w=>{var g=s(w);return g?"1":"0"};else{var f=i,p=f.minimum,l=f.maximum,m=f.roundedMinimum,h=f.nonDecimals,d=f.decimals,y=f.multiplier;d===0?c=w=>{var g=s(w);return typeof g>"u"&&(g=0),g<p&&(g=p),g>l&&(g=l),(Math.floor(g)-m).toString().padStart(h,"0")}:c=w=>{var g=s(w);typeof g>"u"&&(g=0),g<p&&(g=p),g>l&&(g=l);var x=Math.floor(g),S=Math.min(Math.round((g-x)*y),y-1),b=(x-m).toString().padStart(h,"0");return b+S.toString().padStart(d,"0")}}var v={fieldName:n,schemaPart:o,parsedLengths:i,getValue:s,getIndexStringPart:c};return v});return r}function ua(e,t){var r=sa(e,t),n=r.length,o=r.map(p=>p.getIndexStringPart);if(n===1)return o[0];if(n===2){var a=o[0],i=o[1];return p=>a(p)+i(p)}if(n===3){var s=o[0],u=o[1],c=o[2];return p=>s(p)+u(p)+c(p)}var f=function(p){for(var l="",m=0;m<n;++m)l+=o[m](p);return l};return f}function sn(e){var t=Math.floor(e.minimum),r=Math.ceil(e.maximum),n=e.multipleOf,o=r-t,a=o.toString().length,i=n.toString().split("."),s=0;return i.length>1&&(s=i[1].length),{minimum:t,maximum:r,nonDecimals:a,decimals:s,roundedMinimum:t,multiplier:Math.pow(10,s)}}function ca(e,t){var r=sa(e,t),n=0;return r.forEach(o=>{var a=o.schemaPart,i=a.type;if(i==="string")n+=a.maxLength;else if(i==="boolean")n+=1;else{var s=o.parsedLengths;n=n+s.nonDecimals+s.decimals}}),n}function ae(e,t){var r=e.slice(t*-1),n=r.trim();return n}function an(e,t){typeof t>"u"&&(t=0),t<e.minimum&&(t=e.minimum),t>e.maximum&&(t=e.maximum);var r=(Math.floor(t)-e.roundedMinimum).toString(),n=r.padStart(e.nonDecimals,"0");if(e.decimals>0){var o=e.multiplier,a=Math.min(Math.round((t-Math.floor(t))*o),o-1),i=a.toString();n+=i.padStart(e.decimals,"0")}return n}function Ne(e,t,r){var n="";return t.forEach((o,a)=>{var i=Le(e,o),s=r[a],u=i.type;switch(u){case"string":var c=H(i.maxLength,"maxLength not set");typeof s=="string"?s===X?n+="".padEnd(c,X):n+=s.padEnd(c," "):n+="".padEnd(c,"\0");break;case"boolean":if(s===null)n+="0";else if(s===de)n+="0";else if(s===X)n+="1";else{var f=s?"1":"0";n+=f}break;case"number":case"integer":var p=sn(i);if(s===null||s===de){var l="0";n+=l.repeat(p.nonDecimals+p.decimals)}else if(s===X)n+=an(p,p.maximum);else{var m=an(p,s);n+=m}break;default:throw Q("CI2",{type:u})}}),n}function it(e,t,r){var n="";return t.forEach((o,a)=>{var i=Le(e,o),s=r[a],u=i.type;switch(u){case"string":var c=H(i.maxLength,"maxLength not set");typeof s=="string"&&s!==X?n+=s.padEnd(c," "):s===de?n+="".padEnd(c,"\0"):n+="".padEnd(c,X);break;case"boolean":if(s===null||s===X)n+="1";else if(s===de)n+="0";else{var f=s?"1":"0";n+=f}break;case"number":case"integer":var p=sn(i);if(s===null||s===X){var l="9";n+=l.repeat(p.nonDecimals+p.decimals)}else if(s===de){var m="0";n+=m.repeat(p.nonDecimals+p.decimals)}else n+=an(p,s);break;default:throw Q("CI2",{type:u})}}),n}var Ot="17.4.0";var xs=!0;function fa(){if(xs&&Ge!==Ot)throw Q("SNH",{name:"Version mismatch detected",args:{rxdbVersion:Ge,rxdbPremiumVersion:Ot}})}globalThis.WCPOS_TASK_QUEUE_CONTAINMENT_PATCH=1;function bs(e,t){try{var r=e&&e.storageInstance,n=r?[r.databaseName,r.collectionName,"v"+(r.schema&&r.schema.version)].join("/"):"unknown",o=globalThis.__wcposOnStorageRunFailure;if(typeof o=="function"){o({target:n,error:t});return}console.error("[wcpos] storage task-queue run failed ("+n+")",t)}catch{}}function Ss(e,t){var r=t;Object.defineProperty(e,"queue",{configurable:!0,get:function(){return r},set:function(n){r=n&&typeof n.catch=="function"?n.catch(function(o){bs(e,o)}):n}})}var la=(function(){function e(r,n,o){this.instanceId=De(),this.queue=Er,Ss(this,Er),this.readTasks=[],this.writeTasks=[],this.readTaskAdded$=new Z,this.writeTaskAdded$=new Z,this.readQueueRunsInProgress=0,this.writeQueueRunsInProgress=0,this.lockId=r,this.abstractLock=n,this.beforeTaskReadOrWrite=o}var t=e.prototype;return t.setStorageInstance=function(r){this.storageInstance=r},t.runRead=function(r){return new Promise(((n,o)=>{this.readTasks.push((a=>r(a).then((i=>{n(i)})).catch((i=>o(i))))),this.readTaskAdded$.next(),this.triggerReadTasks()}))},t.triggerReadTasks=function(){this.readQueueRunsInProgress>2||(this.readQueueRunsInProgress=this.readQueueRunsInProgress+1,this.queue=this.queue.then((async()=>{this.readQueueRunsInProgress=this.readQueueRunsInProgress-1,this.readTasks.length!==0&&await this.abstractLock.request(this.lockId,(async()=>{try{var r={type:"READ",storageInstance:H(this.storageInstance),accessHandlers:new Map,touchedWriteDocuments:new Set,knownChangesContent:[]};await this.beforeTaskReadOrWrite(r);for(var n=!1;!n;){var o=this.readTasks;this.readTasks=[],o.length===1?await o[0](r):await Promise.all(o.map((a=>a(r)))),this.readTasks.length===0&&await Promise.race([le(10),nt(this.writeTaskAdded$),nt(this.readTaskAdded$)]),this.readTasks.length===0&&(n=!0)}}finally{r&&await this.cleanupAfterRun(r)}}))})).catch((r=>{throw console.log("ERROR TaskQueue.triggerReadTasks.queue errored:"),console.log(r),r})),this.queue.catch((()=>{})))},t.runWrite=function(r){var n=r.task;return new Promise(((o,a)=>{r.task=async i=>n(i).then((s=>(o(s),s))).catch((s=>{throw a(s),s})),this.writeTasks.push(r),this.writeTaskAdded$.next(),this.triggerWriteTasks()}))},t.triggerWriteTasks=function(){var r=this;this.writeQueueRunsInProgress>2||(this.writeQueueRunsInProgress=this.writeQueueRunsInProgress+1,this.queue=this.queue.then((async()=>{this.writeQueueRunsInProgress=this.writeQueueRunsInProgress-1,this.writeTasks.length!==0&&await this.abstractLock.request(this.lockId,(async()=>{if(this.writeTasks.length!==0)try{for(var n={type:"WRITE",storageInstance:H(this.storageInstance),accessHandlers:new Map,touchedWriteDocuments:new Set,knownChangesContent:[]},o=!1;!o;){var a=this.writeTasks;this.writeTasks=[];var i=async function(){var u=!0,c=s.primaryPath;s.documentWrites.length<20&&(s.documentWrites.find((f=>{var p=f.document[c];return n.touchedWriteDocuments.has(p)}))||(u=!1)),u&&await r.beforeTaskReadOrWrite(n),n.wholeDocumentsFileContent=void 0,await s.task(n)};for(var s of a)await i();this.writeTasks.length===0&&await Promise.race([le(10),nt(this.writeTaskAdded$),nt(this.readTaskAdded$)]),this.writeTasks.length===0&&(o=!0)}await this.beforeTaskReadOrWrite(n)}finally{n&&await this.cleanupAfterRun(n)}}))})).catch((n=>{throw console.log("ERROR TaskQueue.triggerWriteTasks.queue errored:"),console.error(n.stack||n),n})),this.queue.catch((()=>{})))},t.runCleanup=function(r){return new Promise(((n,o)=>{this.queue=this.queue.then((()=>this.abstractLock.request(this.lockId,(async()=>{try{var a={type:"CLEANUP",storageInstance:H(this.storageInstance),accessHandlers:new Map,touchedWriteDocuments:new Set,knownChangesContent:[]};await this.beforeTaskReadOrWrite(a),await r(a).then((i=>n(i))).catch((i=>o(i)))}finally{a&&await this.cleanupAfterRun(a)}})))),this.queue.catch((()=>{}))}))},t.runInit=function(r){return new Promise(((n,o)=>{this.queue=this.queue.then((()=>this.abstractLock.request(this.lockId,(async()=>{var a={type:"INIT",storageInstance:H(this.storageInstance),accessHandlers:new Map,touchedWriteDocuments:new Set,knownChangesContent:[]};return r(a).then((i=>n(i))).catch((i=>o(i))).then((()=>this.cleanupAfterRun(a)))})))),this.queue.catch((()=>{}))}))},t.cleanupAfterRun=async function(r){await Promise.all(Array.from(r.accessHandlers.values()).map((n=>n.then((o=>o.close())).catch((o=>{})))))},t.awaitIdle=async function(){for(;;){var r=this.queue;if(await this.queue,this.queue===r)return}},e})();function D(e,t){var r=t.accessHandlers.get(e);return r||(r=e.createAccessHandle(),t.accessHandlers.set(e,r)),r}function pa(e){return["rxdb","abstract-filesystem","task-queue-lock",e.databaseName,e.collectionName,e.schema.version].join("||")}globalThis.WCPOS_CHANGELOG_REPLAY_SAFETY_PATCH=3;var da=256*1024*1024,un=class extends Error{constructor(t){super("Changelog exceeds "+da+" bytes: "+t),this.name="WcposChangelogOversized",this.size=t}};async function _s(e,t){var r=await e.getSize();if(t&&r>da)throw new un(r);return e.read(0,r)}var ma=(function(){function e(r,n,o){this.indexStates=r,this.devMode=n,this.fileHandlePromise=o.then((a=>a.getFileHandle("changelog.txt",{create:!0}))),this.fileHandlePromise.catch((()=>{}))}var t=e.prototype;return t.getChangelogOperations=async function(r){var n=await this.fileHandlePromise,o=await D(n,r),a=await _s(o,this.__wcposSingleInstance),i=r.storageInstance._decode(a);this.__wcposLastRaw=i;var s=new Map;if(this.indexStates.forEach((l=>s.set(l.indexId,[]))),i.length===0)return s;for(var u=JSON.parse("["+i+"]"),c=0;c<u.length;c++){var f=u[c],p=f[0];s.get(p).push(f)}return s},t.addChangelogOperations=async function(r,n,o){if(n.length!==0){o=o||(await D(await this.fileHandlePromise,r)).getWritable();var a,i=JSON.stringify(n),s=i.substring(1,i.length-1);(a=r.knownChangelogFileSize?r.knownChangelogFileSize:await(await D(await this.fileHandlePromise,r)).getSize())>0&&(s=","+s);var u=r.storageInstance._encode(s),c=await o;await c.write(u,{at:a}),r.knownChangelogFileSize=a+u.byteLength,this.devMode&&await this.getChangelogOperations(r)}},t.empty=async function(r){var n=await this.fileHandlePromise,o=await D(n,r);await o.truncate(0),r.knownChangelogFileSize=0},e})();function fr(e,t,r,n,o){for(var a=n===void 0?0:n|0,i=o===void 0?e.length-1:o|0,s=i+1;a<=i;){var u=a+i>>>1;r(e[u],t)>=0?(s=u,i=u-1):a=u+1}return s}function Me(e,t,r,n,o){for(var a=n===void 0?0:n|0,i=o===void 0?e.length-1:o|0,s=i+1;a<=i;){var u=a+i>>>1;r(e[u],t)>0?(s=u,i=u-1):a=u+1}return s}function st(e,t,r,n,o){for(var a=n===void 0?0:n|0,i=o===void 0?e.length-1:o|0,s=a-1;a<=i;){var u=a+i>>>1;r(e[u],t)<0?(s=u,a=u+1):i=u-1}return s}function lr(e,t,r,n,o){for(var a=n===void 0?0:n|0,i=o===void 0?e.length-1:o|0,s=a-1;a<=i;){var u=a+i>>>1;r(e[u],t)<=0?(s=u,a=u+1):i=u-1}return s}function Et(e,t,r,n,o){for(var a=n===void 0?0:n|0,i=o===void 0?e.length-1:o|0;a<=i;){var s=a+i>>>1,u=r(e[s],t);if(u===0)return s;u<=0?a=s+1:i=s-1}return-1}function ha(e,t,r,n){var o=e.length,a=o-1,i=0;if(o===0)return e.push(t),0;for(var s;n<=a;)i=n+(a-n>>1),s=e[i],r(s,t)<=0?n=i+1:a=i-1;return r(s,t)<=0&&i++,e.splice(i,0,t),i}function ce(e){return e.join("||")}var Os=["_deleted","_meta.lwt"],Jd=ce(Os);globalThis.WCPOS_CHANGELOG_IDENTITY_PATCH=1;function Es(e,t,r){var n=e.rows,o=e.metaIdMap,a=t[3],i=t[1],s=r(a[0],e.primaryKeyLength),u=e.__wcposIndexStates;if(!o&&u&&(t[2]==="A"||t[2]==="R")){var c=u[0],f=c&&c.metaIdMap&&c.metaIdMap.get(s);if(!f||f[1]!==a[1]||f[2]!==a[2])return}function p(w,g){return w&&g&&w[0]===g[0]&&w[1]===g[1]&&w[2]===g[2]}function l(w,g){for(var x=0,S=w.length;x<S;){var b=Math.floor((x+S)/2);w[b][0]<g?x=b+1:S=b}return x}function m(w,g){var x=l(w,g);return w[x]&&w[x][0]===g?x:-1}function h(){var w=o&&o.get(s);if(!o&&!u){for(var g=0;g<n.length;g++)if(r(n[g][0],e.primaryKeyLength)===s){w=n[g];break}}return w&&w[0]!==a[0]}var d;if(t[2]==="A"){if(p(n[i],a))return;var y=i>=0&&i<=n.length&&(i===0||n[i-1][0]<a[0])&&(i===n.length||a[0]<=n[i][0]);if(d=y?i:l(n,a[0]),n[d]&&n[d][0]===a[0])n[d]=a;else{if(!y&&h())return;n.splice(d,0,a)}o&&o.set(s,a)}else if(t[2]==="D"||t[2]==="R")if(d=n[i]&&n[i][0]===a[0]?i:m(n,a[0]),t[2]==="D"){if(t[4]==="wcpos-exact"&&!p(n[d],a))for(d=l(n,a[0]);d<n.length&&n[d][0]===a[0]&&!p(n[d],a);d++);if(d<0||t[4]==="wcpos-exact"&&!p(n[d],a))return;var v=n[d];n.splice(d,1),o&&(o.get(s)===v||p(o.get(s),v))&&o.delete(s)}else{if(d>=0)n[d]=a;else{if(h())return;n.splice(l(n,a[0]),0,a)}o&&o.set(s,a)}else throw new Error("unknown operation key "+t[2])}var ga=(function(){function e(r,n,o,a){this.rows=[],this.indexId=r,this.index=n,this.schema=a,this.name=ce(this.index),this.fileHandlePromise=o.then((i=>i.getFileHandle(Is(r),{create:!0}))),this.fileHandlePromise.catch((()=>{})),this.getIndexableString=ua(this.schema,this.index),this.indexableStringLength=ca(this.schema,this.index),this.primaryPath=ie(this.schema.primaryKey),this.primaryKeyLength=H(this.schema.properties[this.primaryPath].maxLength),this.metaIdMap=r===0?new Map:void 0}var t=e.prototype;return t.initRead=async function(r){this.metaIdMap&&this.metaIdMap.clear();var n=await this.fileHandlePromise,o=await D(n,r),a=await o.read(0),i=r.storageInstance._decode(a);if(i.length!==0){var s=JSON.parse(i);if(this.metaIdMap)for(var u=this.primaryKeyLength,c=0;c<s.length;c++){var f=s[c],p=ae(f[0],u);this.metaIdMap.set(p,f)}this.rows=s}else this.rows=[]},t.persistInMemoryRows=async function(r){var n=await this.fileHandlePromise.then((p=>D(p,r))),o=this.rows.length>0?JSON.stringify(this.rows):"",a=await n,i=await a.getSize(),s=r.storageInstance._encode(o),u=!1,c=s.byteLength;i>c&&(u=!0,o=o.padEnd(i," "),s=r.storageInstance._encode(o));var f=await a.getWritable();await f.write(s,{at:0}),u&&await a.truncate(c)},t.runChangelogOperation=function(r){return Es(this,r,ae)},t.appendWriteOperations=function(r,n,o){for(var a=[],i=r.length,s=0;s<i;s++){var u=r[s],c=n[s],f=u.documentId,p=this.getIndexableString(u.documentData),l=u.previousDocumentData?this.getIndexableString(u.previousDocumentData):null,m=l?Et(this.rows,[l],ee):-1,h=[p,c[0],c[1]];this.metaIdMap&&this.metaIdMap.set(f,h),p===l?(this.rows[m]=h,o.push([this.indexId,m,"R",[p,c[0],c[1]]])):(u.previousDocumentData&&function(){var g=this.rows[m];this.rows.splice(m,1),o.push([this.indexId,m,"D",g,"wcpos-exact"])}.call(this),a.push(h))}for(var d=0,y=(a=a.sort(ya)).length,v=0;v<y;v++){var w=a[v];d=ha(this.rows,w,ya,d),o.push([this.indexId,d,"A",w])}return o},t.changeDocumentPosition=function(r,n){var o=this.getIndexableString(r),a=r[this.primaryPath],i=Et(this.rows,[o],ee),s=[o,n[0],n[1]];return this.rows[i]=s,this.metaIdMap&&this.metaIdMap.set(a,s),[this.indexId,i,"R",s]},e})();function ya(e,t){return e[0]<t[0]?-1:1}function Is(e){return"index-"+wa(e,5)+".txt"}function va(e){var t=ie(e.primaryKey),r=Nt(e.indexes?e.indexes:[]);(r=(r=Ps(r)).map((a=>a.slice(0)))).push(["_meta.lwt",t]),r.push(ut(t));var n=new Set,o=r.slice();return r=o.filter((a=>{var i=ce(a);return!n.has(i)&&(n.add(i),!0)}))}function Ps(e){return e.map((t=>({index:t,str:t.join(",")}))).sort(((t,r)=>t.str>r.str?1:t.str<r.str?-1:0)).map((t=>t.index))}async function ba(e,t,r,n){for(var o,a,i=[],s=[],u=0,c=o=e.knownDocumentFileSize?e.knownDocumentFileSize:await r.getSize(),f=t.length,p=0;p<f;p++){var l=t[p].documentData,m=JSON.stringify(l),h=c,d=e.storageInstance._encode(m);s.push(d);var y=d.byteLength;u+=y;var v=c+=y;i.push([h,v])}if(s.length===1)a=s[0];else{a=new Uint8Array(u);for(var w=0,g=0;g<s.length;g++){var x=s[g];a.set(x,w),w+=x.byteLength}}return e.knownDocumentFileSize=o+u,{documentPositions:i,writePromise:Cn(n).then((S=>S.write(a,{at:o})))}}async function fe(e,t,r,n){var o=[],a=bn(n,1e3);return await Promise.all(a.map((async i=>{var s=await Ve(e,t,r,i),u=JSON.parse(s);o=o.length===0?u:o.concat(u)}))),o}async function As(e,t,r,n){if(!t.wholeDocumentsFileContent){var o=.15;if(It(e)*o<n&&It(e)>1){var a=await r.read(0);t.wholeDocumentsFileContent=a}}}async function Ve(e,t,r,n){var o=n.length;o>2&&await As(e,r,t,o);var a=r.wholeDocumentsFileContent;if(a){for(var i="",s=0;s<o;s++){s>0&&(i+=",");var u=n[s][1],c=n[s][2],f=a.subarray(u,c);i+=r.storageInstance._decode(f)}return"["+i+"]"}var p=new Map,l=r.storageInstance._encode(","),m=o-1;if(o===1){var h=await xa(t,n,p);m+=h;var d=ht(p,n[0]);return"["+r.storageInstance._decode(d)+"]"}var y=ks(n,25);await Promise.all(y.map((async b=>{var R=await xa(t,b,p);m+=R})));for(var v=new Uint8Array(m),w=0,g=0;g<o;g++){var x=n[g],S=ht(p,x);v.set(S,w),w+=S.byteLength,g!==o-1&&(v.set(l,w),w+=l.byteLength)}return"["+r.storageInstance._decode(v)+"]"}async function xa(e,t,r){var n=t[0][1],o=Fe(t)[2],a=await e.read(n,o),i=0;if(t.length===1)i+=a.byteLength,r.set(t[0],a);else for(var s=0;s<t.length;s++){var u=t[s],c=a.slice(u[1]-n,u[2]-n);i+=c.byteLength,r.set(u,c)}return i}function Rs(e,t){return e[1]<t[1]?-1:e[1]>t[1]?1:0}function Ts(e,t){var r=[];if(e.length>=t)r=e.slice();else for(;r.length<t;){var n=Cs(e);r.push(n)}var o=0;return r.forEach((a=>o+=a[2]-a[1])),o/r.length}function ks(e,t){for(var r=e.slice(0).sort(Rs),n=Ts(e,5),o=[],a=[],i=0;i<r.length;i++){var s=r[i];if(a.length!==0){var u=Fe(a);s[1]-u[2]<t*n?a.push(s):(o.push(a),a=[s])}else a.push(s)}return a.length>0&&o.push(a),o}function Cs(e){return e[Math.floor(Math.random()*e.length)]}globalThis.WCPOS_CHANGELOG_INDEX_STATES_PATCH=1;function Ns(e){for(var t=0;t<e.length;t++)e[t].__wcposIndexStates=e;return e}globalThis.WCPOS_CHANGELOG_REPLAY_SAFETY_PATCH=3;function Ms(e){for(var t=3735928559,r=1103547991,n=0;n<e.length;n++){var o=e.charCodeAt(n);t=Math.imul(t^o,2654435761),r=Math.imul(r^o,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)+":"+e.length}async function $s(e){for(var t of e.accessHandlers.values()){var r=await t;r&&typeof r.flush=="function"&&await r.flush()}}function Fs(e,t){for(var r=null,n=0;n<e.length;n++){var o=e[n].rows;if(!Array.isArray(o))return"not-array:index-"+n;if(r===null)r=o.length;else if(o.length!==r)return"length-mismatch";for(var a=0;a<o.length;a++){var i=o[a];if(!Array.isArray(i))return"hole:index-"+n;if(typeof i[0]!="string"||!Number.isInteger(i[1])||!Number.isInteger(i[2])||i[1]>i[2])return"invalid-row:index-"+n;if(a>0&&o[a-1][0]>i[0])return"unsorted:index-"+n}}for(var s=e[0].rows,u=new Set,c=0;c<s.length;c++){var f=s[c][0].slice(-t);if(u.has(f))return"duplicate-primary";u.add(f)}return null}function Ds(e,t){for(var r of t.entries())for(var n=e[r[0]],o=n.rows,a=r[1],i=0;i<a.length;i++){var s=a[i],u=s[1],c=s[2],f=s[3];if(!Array.isArray(f)||typeof f[0]!="string")return"stale-changelog-op:malformed:index-"+r[0];if(c==="A"){if(!(u>=0&&u<=o.length)||u>0&&o[u-1][0]>f[0]||u<o.length&&o[u][0]<f[0])return"stale-changelog-op:A:index-"+r[0]}else if(!(u>=0&&u<o.length)||!Array.isArray(o[u])||o[u][0]!==f[0])return"stale-changelog-op:"+c+":index-"+r[0];n.runChangelogOperation(s)}return null}var Ls=8*1024*1024,Hs=512*1024*1024;function Bs(){var e=globalThis.__wcposRebuildWindowBytes;return{bytes:e&&e.bytes||Ls,max:e&&e.max||Hs}}async function Ws(e,t,r,n){for(var o=0,a=!1,i=!1,s=t;s<r;){for(var u=await e.read(s,Math.min(s+n,r)),c=0;c<u.length;c++){var f=u[c];if(a)i?i=!1:f===92?i=!0:f===34&&(a=!1);else if(f===34)a=!0;else if(f===123)o++;else if(f===125&&(o--,o===0))return s+c+1}s+=u.length}return-1}async function js(e){var t=e.reason,r=e.runState,n=e.docsAccessHandle,o=e.indexStates,a=e.changelog,i=e.stampHandle,s=e.decode,u=e.primaryPath,c=e.databaseName,f=e.collectionName,p;try{for(var l=await n.getSize(),m=new Map,h=Bs(),d=h.bytes,y=0,v=0;v<l;){for(var w=Math.min(v+d,l),g=await n.read(v,w),x=0;x<g.length;){if(g[x]!==123){x++;continue}for(var S=x,b=0,R=!1,A=!1,T=-1,C=S;C<g.length;C++){var L=g[C];if(R)A?A=!1:L===92?A=!0:L===34&&(R=!1);else if(L===34)R=!0;else if(L===123)b++;else if(L===125&&(b--,b===0)){T=C+1;break}}if(T<0){if(w<l){if(S>0){x=S;break}if(d<h.max){d=Math.min(d*2,h.max),x=0;break}var J=await Ws(n,v,l,h.bytes);if(J>0){y++,x=J-v,d=h.bytes;break}}x=S+1;continue}try{var _=JSON.parse(s(g.subarray(S,T)));if(!_||typeof _!="object"||!Object.prototype.hasOwnProperty.call(_,u)){x=S+1;continue}var O=parseInt(_._rev,10);Number.isNaN(O)&&(O=-1);var I=m.get(_[u]),E=v+S,k=v+T;(!I||O>I.revision||O===I.revision&&E>I.start)&&m.set(_[u],{doc:_,start:E,end:k,revision:O}),x=T,d=h.bytes}catch{x=S+1}}v+=x}p=Array.from(m.values());for(var P of o)P.rows=p.map(function(N){return[P.getIndexableString(N.doc),N.start,N.end]}).sort(function(N,F){return N[0]<F[0]?-1:1});for(var B of o)await B.persistInMemoryRows(r);await $s(r);for(var U of o)await U.initRead(r);await a.empty(r);var W=await D(i,r);await W.truncate(0)}catch(N){try{N.message="index rebuild failed ("+t+"): "+N.message}catch{}throw N}var K={db:c,col:f,reason:t,documents:p.length,skipped:y};console.warn("[wcpos] rebuilt storage indexes from documents.json",K),e.changelogBytes!==void 0&&typeof globalThis.__wcposOnStorageRecovery=="function"&&globalThis.__wcposOnStorageRecovery({kind:"changelog-oversized-rebuilt",target:c+"/"+f,bytes:e.changelogBytes,documents:p.length}),typeof globalThis.__wcposOnIndexRebuild=="function"&&globalThis.__wcposOnIndexRebuild({target:c+"/"+f,reason:t,documents:p.length,skipped:y})}async function _a(e,t,r){var n=e.getDirectory(),o=qs({databaseName:t.databaseName,collectionName:t.collectionName,schemaVersion:t.schema.version}),a=n.then((s=>s.getDirectoryHandle(o,{create:!0})));a.catch((()=>{}));var i=a.then((s=>s.getFileHandle("documents.json",{create:!0})));return i.catch((()=>{})),r.runInit((async s=>{var u=i.then((C=>D(C,s)));u.catch((()=>{}));var c=a.then((C=>C.getFileHandle("changes.json",{create:!0})));c.catch((()=>{}));var f=ie(t.schema.primaryKey),p=H(t.schema.properties[f].maxLength),l=Ns(va(t.schema).map(((C,L)=>new ga(L,C,a,t.schema)))),m=Sn(l.map((C=>C.indexableStringLength))),h=new ma(l,t.devMode,a),d=await u;if(h.__wcposSingleInstance=!t.multiInstance,await d.getSize()>0){var y=await(await a).getFileHandle("wcpos-changelog-baked.txt",{create:!0}),v=await D(y,s),w=null,g;try{var x=await Promise.allSettled(l.map((C=>C.initRead(s)))),S=x.find((C=>C.status==="rejected"));if(S)throw S.reason;var b=await h.getChangelogOperations(s),R=s.storageInstance._decode(await v.read(0));R!==""&&R===Ms(h.__wcposLastRaw)?w="stale-changelog-after-compaction":w=Ds(l,b),w||(w=Fs(l,p))}catch(C){if(C&&C.name==="WcposChangelogOversized"){if(t.multiInstance)throw C;g=C.size}w="boot-failed:"+(C&&C.message)}w!==null&&await js({reason:w,runState:s,docsAccessHandle:d,indexStates:l,changelog:h,stampHandle:y,decode:s.storageInstance._decode.bind(s.storageInstance),primaryPath:f,databaseName:t.databaseName,collectionName:t.collectionName,changelogBytes:g})}var A=t.multiInstance&&typeof BroadcastChannel<"u"?new BroadcastChannel(r.lockId):void 0;A&&A.unref&&A.unref();var T=new Z;return A&&(A.onmessage=C=>{var L=C.data;T.next(L)}),{params:t,taskQueue:r,indexStates:l,firstIdx:l[0],primaryPath:f,primaryKeyLength:p,root:await n,dirHandle:await a,changesFileHandle:await c,documentFileHandle:await i,changelog:h,maxIndexableStringLength:m,broadcastChannel:A,broadcastChannelMessages$:T}}))}function wa(e,t){return(e+"").padStart(t,typeof e=="number"?"0":" ")}function Sa(e){return e.replace(/\//g,"__")}function qs(e){return["rxdb",Sa(e.databaseName),Sa(e.collectionName),e.schemaVersion].join("-")}function It(e){return e.firstIdx.rows.length}function ee(e,t){return e[0]<t[0]?-1:e[0]===t[0]?0:1}async function Pt(e,t,r,n){if(t.broadcastChannel){var o={type:"event",eventBulks:n,changelogOperations:r,info:{db:e.databaseName,col:e.collectionName}};t.broadcastChannel.postMessage(o),await le(0)}}function ut(e){return["_deleted","_meta.lwt",e]}async function Oa(e,t){await le(120),t.wholeDocumentsFileContent=void 0;var r=await e.internals.statePromise,n=await D(r.documentFileHandle,t);for(var o of r.indexStates)for(var a of o.rows){var i=await Ve(r,n,t,[a]);try{JSON.parse(i)}catch(s){throw console.log("CANNOT PARSE JSON!! for index "+o.name+":"),console.log(JSON.stringify({indexName:o.name,indexId:o.indexId,indx:o.index,indexRow:a,json:i,indexes:r.indexStates.map((u=>u.metaIdMap?{name:u.name,rows:Array.from(u.metaIdMap?.entries())}:["no meta map fpr "+u.name+" id "+u.indexId])),relindex:o.rows},null,4)),s}}}function Ea(e,t){var r=Math.min(e.length,t);return Array.from(e.subarray(0,r)).map((n=>n.toString(16).padStart(2,"0"))).join(" ")}function Ia(e,t){if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){var r=new Uint8Array(e);return t?new Uint8Array(r):r}var n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return t?new Uint8Array(n):n}var Pa="[]";async function Aa(e,t,r,n){var o=await e.internals.statePromise;if(o.firstIdx.rows.length===0)return Pa;for(var a=D(o.documentFileHandle,n),i=o.firstIdx.metaIdMap,s=[],u=t.length,c=0;c<u;c++){var f=t[c],p=i.get(f);p&&(r||p[0][0]==="0")&&s.push(p)}if(s.length===0)return Pa;var l=await a;return await Ve(o,l,n,s)}async function Ra(e,t,r){var n=e.primaryPath,o=new Map,a=await e.internals.statePromise;if(a.firstIdx.rows.length===0)return o;for(var i=D(a.documentFileHandle,r),s=a.firstIdx.metaIdMap,u=[],c=t.length,f=0;f<c;f++){var p=t[f],l=s.get(p);l&&u.push(l)}if(u.length===0)return o;for(var m=await i,h=await fe(a,m,r,u),d=u.length,y=0;y<d;y++){var v=h[y],w=v[n];o.set(w,v)}return o}async function Ta(e,t,r,n){if(t.schema.attachments){var o=r.attachmentsAdd.concat(r.attachmentsUpdate);o.length!==0&&await Promise.all(o.map((async a=>{var i=await Ma(e,t,a.documentId,a.attachmentId,on(a.attachmentData).digest,!0),s=await D(i,e);await s.truncate(0);var u=new Uint8Array(await a.attachmentData.data.arrayBuffer()),c=await s.getWritable();await c.write(u,{at:0}),c.flush&&await c.flush()})))}}async function ka(e,t,r,n){if(t.schema.attachments){var o=[];n.forEach((a=>{a.events.forEach((i=>{i.previousDocumentData&&Object.keys(i.previousDocumentData._attachments).forEach((s=>{i.documentData._attachments[s]&&!i.documentData._deleted||o.push({documentId:i.documentId,attachmentId:s,digest:H(i.previousDocumentData)._attachments[s].digest})}))}))})),o.length!==0&&await Promise.all(o.map((async a=>{var i=await Na(a.documentId,a.attachmentId,a.digest);await r.dirHandle.removeEntry(i)})))}}async function Ca(e,t,r,n,o){var a=await Ma(e,t,r,n,o),i=await D(a,e),s=await i.read(0);return new Blob([s],{type:""})}async function Na(e,t,r){return"z-attachment-"+(await kn(e+"||"+t)).slice(0,20)+"-"+r.slice(0,20)+".txt"}var Us=new WeakMap;async function Ma(e,t,r,n,o,a=!1){var i=await t.internals.statePromise,s=await Na(r,n,o),u=Wt(Us,e,(()=>new Map));return Wt(u,s,(()=>i.dirHandle.getFileHandle(s,{create:a})))}globalThis.WCPOS_CHANGES_FILE_SALVAGE_PATCH=1;function Ks(e,t){for(var r=0,n=!1,o=!1,a=t;a<e.length;a++){var i=e[a];if(n){o?o=!1:i==="\\"?o=!0:i==='"'&&(n=!1);continue}if(i==='"')n=!0;else if(i==="{"||i==="[")r++;else if((i==="}"||i==="]")&&(r--,r===0))return a+1}return-1}function $a(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e)||e[r]!==t||typeof e._deleted!="boolean"||!e._meta||typeof e._meta.lwt!="number")return!1;if(!n)return!0;var o=e._attachments;if(!o||typeof o!="object"||Array.isArray(o))return!1;for(var a in o){var i=o[a];if(!i||typeof i!="object"||typeof i.digest!="string")return!1}return!0}function Da(e,t,r){if(!e||typeof e!="object"||Array.isArray(e)||!Array.isArray(e.events))return!1;for(var n=0;n<e.events.length;n++){var o=e.events[n];if(!o||typeof o.documentId!="string"||!$a(o.documentData,o.documentId,t,r)||o.previousDocumentData!==void 0&&o.previousDocumentData!==null&&!$a(o.previousDocumentData,o.documentId,t,r))return!1}return!0}function zs(e,t,r){for(var n=[],o=0;;){for(;o<e.length&&(e[o]===" "||e[o]===` | |
| 53 | + `):"",this.name="UnsubscriptionError",this.errors=r}});function wt(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var tt=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,r,n,o,a;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var s=_e(i),u=s.next();!u.done;u=s.next()){var c=u.value;c.remove(this)}}catch(d){t={error:d}}finally{try{u&&!u.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}else i.remove(this);var f=this.initialTeardown;if(j(f))try{f()}catch(d){a=d instanceof Gt?d.errors:[d]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var l=_e(p),m=l.next();!m.done;m=l.next()){var h=m.value;try{zn(h)}catch(d){a=a??[],d instanceof Gt?a=Te(Te([],Re(a)),Re(d.errors)):a.push(d)}}}catch(d){n={error:d}}finally{try{m&&!m.done&&(o=l.return)&&o.call(l)}finally{if(n)throw n.error}}}if(a)throw new Gt(a)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)zn(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(t)}},e.prototype._hasParent=function(t){var r=this._parentage;return r===t||Array.isArray(r)&&r.includes(t)},e.prototype._addParent=function(t){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(t),r):r?[r,t]:t},e.prototype._removeParent=function(t){var r=this._parentage;r===t?this._parentage=null:Array.isArray(r)&&wt(r,t)},e.prototype.remove=function(t){var r=this._finalizers;r&&wt(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})();var Cr=tt.EMPTY;function Xt(e){return e instanceof tt||e&&"closed"in e&&j(e.remove)&&j(e.add)&&j(e.unsubscribe)}function zn(e){j(e)?e():e.unsubscribe()}var me={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var rt={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=rt.delegate;return o?.setTimeout?o.setTimeout.apply(o,Te([e,t],Re(r))):setTimeout.apply(void 0,Te([e,t],Re(r)))},clearTimeout:function(e){var t=rt.delegate;return(t?.clearTimeout||clearTimeout)(e)},delegate:void 0};function Yt(e){rt.setTimeout(function(){var t=me.onUnhandledError;if(t)t(e);else throw e})}function Nr(){}var Qn=(function(){return Mr("C",void 0,void 0)})();function Vn(e){return Mr("E",void 0,e)}function Jn(e){return Mr("N",e,void 0)}function Mr(e,t,r){return{kind:e,value:t,error:r}}var je=null;function nt(e){if(me.useDeprecatedSynchronousErrorHandling){var t=!je;if(t&&(je={errorThrown:!1,error:null}),e(),t){var r=je,n=r.errorThrown,o=r.error;if(je=null,n)throw o}}else e()}function Gn(e){me.useDeprecatedSynchronousErrorHandling&&je&&(je.errorThrown=!0,je.error=e)}var xt=(function(e){ve(t,e);function t(r){var n=e.call(this)||this;return n.isStopped=!1,r?(n.destination=r,Xt(r)&&r.add(n)):n.destination=Ii,n}return t.create=function(r,n,o){return new Ee(r,n,o)},t.prototype.next=function(r){this.isStopped?Fr(Jn(r),this):this._next(r)},t.prototype.error=function(r){this.isStopped?Fr(Vn(r),this):(this.isStopped=!0,this._error(r))},t.prototype.complete=function(){this.isStopped?Fr(Qn,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(r){this.destination.next(r)},t.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(tt);var _i=Function.prototype.bind;function $r(e,t){return _i.call(e,t)}var Ei=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var r=this.partialObserver;if(r.next)try{r.next(t)}catch(n){Zt(n)}},e.prototype.error=function(t){var r=this.partialObserver;if(r.error)try{r.error(t)}catch(n){Zt(n)}else Zt(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(r){Zt(r)}},e})(),Ee=(function(e){ve(t,e);function t(r,n,o){var a=e.call(this)||this,i;if(j(r)||!r)i={next:r??void 0,error:n??void 0,complete:o??void 0};else{var s;a&&me.useDeprecatedNextContext?(s=Object.create(r),s.unsubscribe=function(){return a.unsubscribe()},i={next:r.next&&$r(r.next,s),error:r.error&&$r(r.error,s),complete:r.complete&&$r(r.complete,s)}):i=r}return a.destination=new Ei(i),a}return t})(xt);function Zt(e){me.useDeprecatedSynchronousErrorHandling?Gn(e):Yt(e)}function Oi(e){throw e}function Fr(e,t){var r=me.onStoppedNotification;r&&rt.setTimeout(function(){return r(e,t)})}var Ii={closed:!0,next:Nr,error:Oi,complete:Nr};var ot=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Xn(e){return e}function Yn(e){return e.length===0?Xn:e.length===1?e[0]:function(r){return e.reduce(function(n,o){return o(n)},r)}}var we=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(t,r,n){var o=this,a=Ai(t)?t:new Ee(t,r,n);return nt(function(){var i=o,s=i.operator,u=i.source;a.add(s?s.call(a,u):u?o._subscribe(a):o._trySubscribe(a))}),a},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(r){t.error(r)}},e.prototype.forEach=function(t,r){var n=this;return r=Zn(r),new r(function(o,a){var i=new Ee({next:function(s){try{t(s)}catch(u){a(u),i.unsubscribe()}},error:a,complete:o});n.subscribe(i)})},e.prototype._subscribe=function(t){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(t)},e.prototype[ot]=function(){return this},e.prototype.pipe=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Yn(t)(this)},e.prototype.toPromise=function(t){var r=this;return t=Zn(t),new t(function(n,o){var a;r.subscribe(function(i){return a=i},function(i){return o(i)},function(){return n(a)})})},e.create=function(t){return new e(t)},e})();function Zn(e){var t;return(t=e??me.Promise)!==null&&t!==void 0?t:Promise}function Pi(e){return e&&j(e.next)&&j(e.error)&&j(e.complete)}function Ai(e){return e&&e instanceof xt||Pi(e)&&Xt(e)}function Ri(e){return j(e?.lift)}function at(e){return function(t){if(Ri(t))return t.lift(function(r){try{return e(r,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function er(e,t,r,n,o){return new Ti(e,t,r,n,o)}var Ti=(function(e){ve(t,e);function t(r,n,o,a,i,s){var u=e.call(this,r)||this;return u.onFinalize=i,u.shouldUnsubscribe=s,u._next=n?function(c){try{n(c)}catch(f){r.error(f)}}:e.prototype._next,u._error=a?function(c){try{a(c)}catch(f){r.error(f)}finally{this.unsubscribe()}}:e.prototype._error,u._complete=o?function(){try{o()}catch(c){r.error(c)}finally{this.unsubscribe()}}:e.prototype._complete,u}return t.prototype.unsubscribe=function(){var r;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&((r=this.onFinalize)===null||r===void 0||r.call(this))}},t})(xt);var eo=et(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var ee=(function(e){ve(t,e);function t(){var r=e.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return t.prototype.lift=function(r){var n=new to(this,this);return n.operator=r,n},t.prototype._throwIfClosed=function(){if(this.closed)throw new eo},t.prototype.next=function(r){var n=this;nt(function(){var o,a;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var i=_e(n.currentObservers),s=i.next();!s.done;s=i.next()){var u=s.value;u.next(r)}}catch(c){o={error:c}}finally{try{s&&!s.done&&(a=i.return)&&a.call(i)}finally{if(o)throw o.error}}}})},t.prototype.error=function(r){var n=this;nt(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var o=n.observers;o.length;)o.shift().error(r)}})},t.prototype.complete=function(){var r=this;nt(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.observers;n.length;)n.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(r){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,r)},t.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},t.prototype._innerSubscribe=function(r){var n=this,o=this,a=o.hasError,i=o.isStopped,s=o.observers;return a||i?Cr:(this.currentObservers=null,s.push(r),new tt(function(){n.currentObservers=null,wt(s,r)}))},t.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,a=n.thrownError,i=n.isStopped;o?r.error(a):i&&r.complete()},t.prototype.asObservable=function(){var r=new we;return r.source=this,r},t.create=function(r,n){return new to(r,n)},t})(we);var to=(function(e){ve(t,e);function t(r,n){var o=e.call(this)||this;return o.destination=r,o.source=n,o}return t.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},t.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},t.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},t.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:Cr},t})(ee);var Dr={now:function(){return(Dr.delegate||Date).now()},delegate:void 0};var ro=(function(e){ve(t,e);function t(r,n,o){r===void 0&&(r=1/0),n===void 0&&(n=1/0),o===void 0&&(o=Dr);var a=e.call(this)||this;return a._bufferSize=r,a._windowTime=n,a._timestampProvider=o,a._buffer=[],a._infiniteTimeWindow=!0,a._infiniteTimeWindow=n===1/0,a._bufferSize=Math.max(1,r),a._windowTime=Math.max(1,n),a}return t.prototype.next=function(r){var n=this,o=n.isStopped,a=n._buffer,i=n._infiniteTimeWindow,s=n._timestampProvider,u=n._windowTime;o||(a.push(r),!i&&a.push(s.now()+u)),this._trimBuffer(),e.prototype.next.call(this,r)},t.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(r),o=this,a=o._infiniteTimeWindow,i=o._buffer,s=i.slice(),u=0;u<s.length&&!r.closed;u+=a?1:2)r.next(s[u]);return this._checkFinalizedStatuses(r),n},t.prototype._trimBuffer=function(){var r=this,n=r._bufferSize,o=r._timestampProvider,a=r._buffer,i=r._infiniteTimeWindow,s=(i?1:2)*n;if(n<1/0&&s<a.length&&a.splice(0,a.length-s),!i){for(var u=o.now(),c=0,f=1;f<a.length&&a[f]<=u;f+=2)c=f;c&&a.splice(0,c+1)}},t})(ee);var no=(function(e){return e&&typeof e.length=="number"&&typeof e!="function"});function oo(e){return j(e?.then)}function ao(e){return j(e[ot])}function io(e){return Symbol.asyncIterator&&j(e?.[Symbol.asyncIterator])}function so(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function ki(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var uo=ki();function co(e){return j(e?.[uo])}function fo(e){return Un(this,arguments,function(){var r,n,o,a;return Jt(this,function(i){switch(i.label){case 0:r=e.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,We(r.read())];case 3:return n=i.sent(),o=n.value,a=n.done,a?[4,We(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,We(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function lo(e){return j(e?.getReader)}function Lr(e){if(e instanceof we)return e;if(e!=null){if(ao(e))return Ci(e);if(no(e))return Ni(e);if(oo(e))return Mi(e);if(io(e))return po(e);if(co(e))return $i(e);if(lo(e))return Fi(e)}throw so(e)}function Ci(e){return new we(function(t){var r=e[ot]();if(j(r.subscribe))return r.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Ni(e){return new we(function(t){for(var r=0;r<e.length&&!t.closed;r++)t.next(e[r]);t.complete()})}function Mi(e){return new we(function(t){e.then(function(r){t.closed||(t.next(r),t.complete())},function(r){return t.error(r)}).then(null,Yt)})}function $i(e){return new we(function(t){var r,n;try{for(var o=_e(e),a=o.next();!a.done;a=o.next()){var i=a.value;if(t.next(i),t.closed)return}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}t.complete()})}function po(e){return new we(function(t){Di(e,t).catch(function(r){return t.error(r)})})}function Fi(e){return po(fo(e))}function Di(e,t){var r,n,o,a;return qn(this,void 0,void 0,function(){var i,s;return Jt(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),r=Kn(e),u.label=1;case 1:return[4,r.next()];case 2:if(n=u.sent(),!!n.done)return[3,4];if(i=n.value,t.next(i),t.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return s=u.sent(),o={error:s},[3,11];case 6:return u.trys.push([6,,9,10]),n&&!n.done&&(a=r.return)?[4,a.call(r)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}var mo=et(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}});function it(e,t){var r=typeof t=="object";return new Promise(function(n,o){var a=new Ee({next:function(i){n(i),a.unsubscribe()},error:o,complete:function(){r?n(t.defaultValue):o(new mo)}});e.subscribe(a)})}function Hr(e,t){return at(function(r,n){var o=0;r.subscribe(er(n,function(a){n.next(e.call(t,a,o++))}))})}function bt(e,t){return at(function(r,n){var o=0;r.subscribe(er(n,function(a){return e.call(t,a,o++)&&n.next(a)}))})}function ho(e){e===void 0&&(e={});var t=e.connector,r=t===void 0?function(){return new ee}:t,n=e.resetOnError,o=n===void 0?!0:n,a=e.resetOnComplete,i=a===void 0?!0:a,s=e.resetOnRefCountZero,u=s===void 0?!0:s;return function(c){var f,p,l,m=0,h=!1,d=!1,g=function(){p?.unsubscribe(),p=void 0},v=function(){g(),f=l=void 0,h=d=!1},w=function(){var y=f;v(),y?.unsubscribe()};return at(function(y,x){m++,!d&&!h&&g();var b=l=l??r();x.add(function(){m--,m===0&&!d&&!h&&(p=Br(w,u))}),b.subscribe(x),!f&&m>0&&(f=new Ee({next:function(S){return b.next(S)},error:function(S){d=!0,g(),p=Br(v,o,S),b.error(S)},complete:function(){h=!0,g(),p=Br(v,i),b.complete()}}),Lr(y).subscribe(f))})(c)}}function Br(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];if(t===!0){e();return}if(t!==!1){var o=new Ee({next:function(){o.unsubscribe(),e()}});return Lr(t.apply(void 0,Te([],Re(r)))).subscribe(o)}}function Wr(e,t,r){var n,o,a,i,s=!1;return e&&typeof e=="object"?(n=e.bufferSize,i=n===void 0?1/0:n,o=e.windowTime,t=o===void 0?1/0:o,a=e.refCount,s=a===void 0?!1:a,r=e.scheduler):i=e??1/0,ho({connector:function(){return new ro(i,t,r)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:s})}var Y="\uFFFF",he=Number.MIN_SAFE_INTEGER;function yo(e,t){var r=t.selector,n=e.indexes?e.indexes.slice(0):[];t.index&&(n=[t.index]);var o=!!t.sort.find(f=>Object.values(f)[0]==="desc"),a=new Set;Object.keys(r).forEach(f=>{var p=Be(e,f);p&&(p.type==="boolean"||p.enum)&&Object.prototype.hasOwnProperty.call(r[f],"$eq")&&a.add(f)});var i=t.sort.map(f=>Object.keys(f)[0]),s=i.filter(f=>!a.has(f)).join(","),u=-1,c;if(n.forEach(f=>{var p=!0,l=!0,m=f.map(y=>{var x=r[y],b=x?Object.keys(x):[],S={};if(!x||!b.length){var T=l?he:Y;S={startKey:T,endKey:p?Y:he,inclusiveStart:!0,inclusiveEnd:!0}}else b.forEach(C=>{if(tr.has(C)){var k=x[C],H=ji(C,k);S=Object.assign(S,H)}else if(C==="$in"){var V=Wi(x[C]);V&&(S=Object.assign(S,V))}});typeof S.startKey>"u"&&(S.startKey=he),typeof S.endKey>"u"&&(S.endKey=Y),typeof S.inclusiveStart>"u"&&(S.inclusiveStart=!0),typeof S.inclusiveEnd>"u"&&(S.inclusiveEnd=!0);var A=Be(e,y);return A&&(A.type==="number"||A.type==="integer")&&(!S.inclusiveStart&&typeof S.startKey=="number"&&typeof A.minimum=="number"&&S.startKey<A.minimum&&(S.inclusiveStart=!0),!S.inclusiveEnd&&typeof S.endKey=="number"&&typeof A.maximum=="number"&&S.endKey>A.maximum&&(S.inclusiveEnd=!0)),l&&!S.inclusiveStart&&(l=!1),p&&!S.inclusiveEnd&&(p=!1),S}),h=m.map(y=>y.startKey),d=m.map(y=>y.endKey),g;a.size===0?g=f.join(","):g=f.filter(y=>!a.has(y)).join(",");var v={index:f,startKeys:h,endKeys:d,inclusiveEnd:p,inclusiveStart:l,sortSatisfiedByIndex:!o&&s===g,selectorSatisfiedByIndex:Bi(f,t.selector,h,d)},w=qi(e,t,v);(w>=u||t.index)&&(u=w,c=v)}),!c)throw z("SNH",{query:t});return c}var tr=new Set(["$eq","$gt","$gte","$lt","$lte"]),Li=new Set(["$eq","$gt","$gte"]),Hi=new Set(["$eq","$lt","$lte"]);function Bi(e,t,r,n){if(t.$and||t.$or)return!1;var o=Object.entries(t),a=new Set,i=new Set,s=!1,u=!1;for(var[c,f]of o){if(!e.includes(c))return!1;var p=Object.keys(f),l=0,m=void 0,h=0,d=void 0;for(var g of p){if(!tr.has(g))return!1;Li.has(g)&&(l++,m=g),Hi.has(g)&&(h++,d=g)}if(l>1||h>1)return!1;if(m&&a.add(c),m!=="$eq"){if(s)return!1;s=!0}if(d&&i.add(c),d!=="$eq"){if(u)return!1;u=!0}}var v=0;for(var w of e){for(var y of[a,i]){if(!y.has(w)&&y.size>0)return!1;y.delete(w)}var x=r[v],b=n[v];if(x!==b&&a.size>0&&i.size>0)return!1;v++}return!0}function Wi(e){if(!(!Array.isArray(e)||e.length===0)){var t=typeof e[0];if(!(t!=="string"&&t!=="number")){for(var r=e[0],n=e[0],o=0;o<e.length;o++){var a=e[o];if(typeof a!==t||t==="number"&&!isFinite(a))return;a<r&&(r=a),a>n&&(n=a)}return{startKey:r,endKey:n,inclusiveStart:!0,inclusiveEnd:!0}}}}function ji(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw z("SNH")}}function qi(e,t,r){var n=0,o=f=>{f>0&&(n=n+f)},a=10,i=Bt(r.startKeys,f=>f!==he&&f!==Y);o(i*a);var s=Bt(r.endKeys,f=>f!==Y&&f!==he);o(s*a);var u=Bt(r.startKeys,(f,p)=>f===r.endKeys[p]);o(u*a*1.5);var c=r.sortSatisfiedByIndex?5:0;return o(c),n}function U(e,t){return e*16777619^t>>>0}function go(e){if(Number.isNaN(e))return 2143289344;if(!Number.isFinite(e))return e>0?2139095040:4286578688;let t=Math.trunc(e),r=e-t,n=t|0;if(r!==0){let o=Math.floor(r*4294967296);n=U(n,o|0)}return n>>>0}function qe(e){let t=0;for(let r=0;r<e.length;r++)t=U(t,e.charCodeAt(r));return t>>>0}function Ui(e){let t=0,r=e<0n,n=r?-e:e;if(n===0n)t=U(t,0);else for(;n>0n;){let o=Number(n&0xffn);t=U(t,o),n>>=8n}return U(t,+r)>>>0}function Ki(e){let t=qe((e.name||"")+e.toString());return t=U(t,e.length),t>>>0}function zi(e){let t=0;for(let r=0;r<e.length;r++)t=U(t,e[r]);return t>>>0}function Qi(e){let t=qe(e.constructor.name),r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return t=U(t,zi(r)),t>>>0}function Vi(e,t){if(t.has(e))return 13;t.add(e);let r=1;for(let n=0;n<e.length;n++)r=U(r,jr(e[n],t));return t.delete(e),r>>>0}function Ji(e,t){if(t.has(e))return 13;t.add(e);let r=Object.keys(e).sort(),n=qe(e?.constructor?.name);for(let o of r)n=U(n,qe(o)),n=U(n,jr(e[o],t));return t.delete(e),n>>>0}var Gi=[3735928559,305441741].map(e=>U(3,e)),Xi=U(1,0),Yi=U(2,0);function jr(e,t){if(e===null)return Xi;switch(typeof e){case"undefined":return Yi;case"boolean":return Gi[+e];case"number":return U(4,go(e));case"string":return U(5,qe(e));case"bigint":return U(6,Ui(e));case"function":return U(7,Ki(e));default:{if(ArrayBuffer.isView(e)&&!(e instanceof DataView))return U(12,Qi(e));if(e instanceof Date)return U(10,go(e.getTime()));if(e instanceof RegExp){let n=qe(e.source);return U(11,U(n,qe(e.flags)))}return Array.isArray(e)?U(8,Vi(e,t)):U(9,Ji(e,t))}}}function qr(e){return jr(e,new WeakSet)>>>0}var St=class extends Error{},st=Symbol("missing"),Zi="mingo: cycle detected while processing object/array",ke=e=>typeof e!="object"&&typeof e!="function"||e===null,wo=e=>ke(e)||Ie(e)||ye(e),vo={undefined:1,null:2,number:3,string:4,symbol:5,object:6,array:7,arraybuffer:8,boolean:9,date:10,regexp:11,function:12},be=(e,t)=>e<t?-1:e>t?1:0,es=(e,t)=>{let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),o=Math.min(r.length,n.length);for(let a=0;a<o;a++){let i=be(r[a],n[a]);if(i!==0)return i}return be(r.length,n.length)};function xe(e,t,r=!1){if(e===st&&(e=void 0),t===st&&(t=void 0),e===t||Object.is(e,t))return 0;let n=ze(e),o=ze(t),a=0;if(n===o)switch(n){case"number":case"string":case"boolean":return be(e,t);case"date":return be(+e,+t);case"regexp":return(a=be(e.source,t.source))?a:be(e.flags,t.flags);case"arraybuffer":return es(e,t);case"array":{let u=e.slice().sort(xe),c=t.slice().sort(xe),f=Math.min(u.length,c.length);for(let p=0;p<f;p++)if(a=xe(u[p],c[p]))return a;return be(u.length,c.length)}default:{if(n!=="object"&&e?.constructor===t?.constructor&&xo(e))return be(e.toString(),t.toString());let u=Object.keys(e).sort(),c=Object.keys(t).sort();if(a=xe(u,c))return a;for(let f of u)if(a=xe(e[f],t[f]))return a;return 0}}if(n=="undefined")return-1;if(o=="undefined")return 1;if(r){if(n=="array"){let u=e;if(!u.length)return-1;let c=u.slice().sort(xe);a=1;for(let f of c)if((a=Math.min(a,xe(f,t)))<0)return a;return a}if(o=="array"){let u=t;if(!u.length)return 1;let c=u.slice().sort(xe);a=-1;for(let f of c)if((a=Math.max(a,xe(e,f)))>0)return a;return a}}let i=vo[n]??Number.MAX_VALUE,s=vo[o]??Number.MAX_VALUE;return i!==s?be(i,s):be(n,o)}var ae=(e,t)=>xe(e,t,!0),xo=e=>e!=null&&e.toString!==Object.prototype.toString;function Oe(e,t){if(e===t||Object.is(e,t))return!0;if(e===null||t===null||typeof e!=typeof t||typeof e!="object"||e.constructor!==t?.constructor)return!1;if(Ie(e))return Ie(t)&&+e==+t;if(ye(e))return ye(t)&&e.source===t.source&&e.flags===t.flags;if(N(e)&&N(t))return e.length===t.length&&e.every((i,s)=>Oe(i,t[s]));if(e?.constructor!==Object&&xo(e))return e?.toString()===t?.toString();let r=e,n=t,o=Object.keys(r),a=Object.keys(n);return o.length!==a.length?!1:o.every(i=>ce(n,i)&&Oe(r[i],n[i]))}var Ke=class e extends Map{#e=new Map;#t=t=>{let r=qr(t);return[(this.#e.get(r)??[]).find(o=>Oe(o,t)),r]};constructor(){super()}static init(){return new e}clear(){super.clear(),this.#e.clear()}delete(t){if(ke(t))return super.delete(t);let[r,n]=this.#t(t);return super.delete(r)?(this.#e.set(n,this.#e.get(n).filter(o=>!Oe(o,r))),!0):!1}get(t){if(ke(t))return super.get(t);let[r,n]=this.#t(t);return super.get(r)}has(t){if(ke(t))return super.has(t);let[r,n]=this.#t(t);return super.has(r)}set(t,r){if(ke(t))return super.set(t,r);let[n,o]=this.#t(t);if(super.has(n))super.set(n,r);else{super.set(t,r);let a=this.#e.get(o)||[];a.push(t),this.#e.set(o,a)}return this}get size(){return super.size}};function $(e,t){if(!e)throw new St(t)}var Ur=e=>{if(e==="__proto__"||e.startsWith("__proto__.")||e.endsWith(".__proto__")||e.includes(".__proto__."))throw new St(`Accessing __proto__ is not allowed in selector: '${e}'.`)};function ze(e){let t=typeof e;switch(t){case"number":case"string":case"boolean":case"undefined":case"function":case"symbol":return t}return e===null?"null":N(e)?"array":Ie(e)?"date":ye(e)?"regexp":_o(e)?"arraybuffer":e?.constructor===Object?"object":e?.constructor?.name?.toLowerCase()??"object"}var _t=e=>typeof e=="boolean",ne=e=>typeof e=="string";var G=e=>!Number.isNaN(e)&&typeof e=="number",ts=Number.isInteger,N=Array.isArray,Q=e=>ze(e)==="object",bo=e=>!ke(e),Ie=e=>e instanceof Date,ye=e=>e instanceof RegExp;var oe=e=>e==null,So=(e,t=!0)=>!!e||t&&e==="",Et=e=>oe(e)||ne(e)&&!e||N(e)&&e.length===0||Q(e)&&Object.keys(e).length===0,Ne=e=>N(e)?e:[e],ce=(e,t,r="",n="")=>!!(e&&Object.prototype.hasOwnProperty.call(e,t)&&(r===""||Object.prototype.hasOwnProperty.call(e,r))&&(n===""||Object.prototype.hasOwnProperty.call(e,n))),_o=e=>typeof ArrayBuffer<"u"&&ArrayBuffer.isView(e),rr=e=>{for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<48||e.charCodeAt(t)>57)return!1;return!0},Ce=(e,t)=>{if(ke(e))return e;if(Ie(e))return new Date(e);if(ye(e))return new RegExp(e);if(_o(e)){let r=e.constructor;return new r(e)}if(t instanceof WeakSet||(t=new WeakSet),t.has(e))throw new Error(Zi);t.add(e);try{if(N(e)){let r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=Ce(e[n],t);return r}if(Q(e)){let r={};for(let n of Object.keys(e))r[n]=Ce(e[n],t);return r}}finally{t.delete(e)}return e};function Ot(e){if(e.length===0)return[];if(e.length===1)return e[0].slice();for(let n of e)if(n.length===0)return[];let t=[Ke.init(),Ke.init()],r=0;for(let n of e[e.length-1])t[0].set(n,!0);for(let n=e.length-2;n>=0;n--){for(let o=0;o<e[n].length;o++){let a=e[n][o];t[r].has(a)&&t[r^1].set(a,!0)}if(t[r^1].size===0)return[];t[r].clear(),r=r^1}return Array.from(t[r].keys())}function sr(e,t=1){let r=new Array;function n(o,a){for(let i=0,s=o.length;i<s;i++)N(o[i])&&(a>0||a<0)?n(o[i],Math.max(-1,a-1)):r.push(o[i])}return n(e,t),r}function Kr(e){let t=Ke.init();for(let r of e)t.set(r,!0);return Array.from(t.keys())}function zr(e,t){if(e.length<1)return new Map;let r=Ke.init();for(let n=0;n<e.length;n++){let o=e[n],a=t(o,n)??null,i=r.get(a);i?i.push(o):(i=[o],r.set(a,i))}return r}var rs=new Set(Object.getOwnPropertyNames(Object.prototype).find(e=>e!=="__proto__"));function nr(e,t){if(!(ke(e)||Number.isNaN(t)))return N(e)?e[typeof t=="number"?t:Number(t)]:!rs.has(t)||ce(e,t)?e[t]:void 0}function ns(e,t){if(t<1)return e;for(;t--&&e.length===1&&N(e[0]);)e=e[0];return e}function Z(e,t,r){if(Ur(t),wo(e))return e;if(!t.includes(".")&&!N(e))return nr(e,t);let n=0;function o(i,s){let u=i,c=0,f=0;for(;f!==-1;){f=s.indexOf(".",c);let p=f===-1?s.substring(c):s.substring(c,f);if(!rr(p)&&N(u)){if(c===0&&n>0)break;n+=1;let m=s.substring(c);u=u.reduce((h,d)=>{let g=o(d,m);return g!==void 0&&h.push(g),h},[]);break}else u=nr(u,p);if(u===void 0)break;c+=p.length+1}return u}let a=o(e,t);return N(a)&&r?.unwrapArray?ns(a,n):a}function Ue(e,t,r){r?.ignoreProto!==!0&&(Ur(t),r={...r,ignoreProto:!0});let n=t.indexOf("."),o=n==-1?t:t.substring(0,n),a=t.substring(n+1),i=n!=-1;if(N(e)){let c=rr(o),f=c&&r?.preserveIndex?e.slice():[];if(c){let p=Number(o),l=nr(e,o);i&&(l=Ue(l,a,r)),r?.preserveIndex?f[p]=l:f.push(l)}else for(let p of e){let l=Ue(p,t,r);r?.preserveMissing?f.push(l??st):(l!=null||r?.preserveIndex)&&f.push(l)}return f}let s=r?.preserveKeys?{...e}:{},u=nr(e,o);if(i&&(u=Ue(u,a,r)),u!==void 0)return s[o]=u,s}function or(e){if(N(e))for(let t=e.length-1;t>=0;t--)e[t]===st?e.splice(t,1):or(e[t]);else if(Q(e))for(let t of Object.keys(e))ce(e,t)&&or(e[t])}function ar(e,t,r,n){n?.ignoreProto!==!0&&(Ur(t),n={...n,ignoreProto:!0});let o=t.indexOf("."),a=o===-1?t:t.substring(0,o),i=t.substring(a.length+1);if(i.length===0)(Q(e)||N(e)&&rr(a))&&r(e,a);else{n?.buildGraph&&oe(e[a])&&(e[a]={});let s=e[a];if(!s)return;let u=i.indexOf("."),c=u===-1?i:i.substring(0,u),f=rr(c);N(s)&&n?.descendArray&&!f?s.forEach((p=>ar(p,i,r,n))):ar(s,i,r,n)}}function Qe(e,t,r){ar(e,t,(n,o)=>n[o]=r,{buildGraph:!0})}function Qr(e,t,r){ar(e,t,((n,o)=>{N(n)?n.splice(Number(o),1):Q(n)&&delete n[o]}),r)}var ge=e=>!!e&&e[0]==="$"&&/^\$[a-zA-Z0-9_]+$/.test(e);function Ve(e){if(wo(e))return ye(e)?{$regex:e}:{$eq:e};if(bo(e)){if(!Object.keys(e).some(ge))return{$eq:e};if(Q(e)&&ce(e,"$regex")){let t={...e};return t.$regex=new RegExp(e.$regex,e.$options),delete t.$options,t}}return e}var ir=class{constructor(){this.root={children:new Map,isTerminal:!1}}add(t){let r=t.split("."),n=this.root;for(let o of r){if(n.isTerminal)return!1;n.children.has(o)||n.children.set(o,{children:new Map,isTerminal:!1}),n=n.children.get(o)}return n.isTerminal||n.children.size?!1:n.isTerminal=!0}};var It=(e=>(e[e.CLONE_OFF=0]="CLONE_OFF",e[e.CLONE_INPUT=1]="CLONE_INPUT",e[e.CLONE_OUTPUT=2]="CLONE_OUTPUT",e[e.CLONE_ALL=3]="CLONE_ALL",e))(It||{}),Se=class e{constructor(t,r){this.options=t,this.#e=r?{...r}:{}}#e;static init(t){return t instanceof e?new e(t.options,t.#e):new e({idKey:"_id",scriptEnabled:!0,useStrictMode:!0,failOnError:!0,processingMode:0,...t,context:t?.context?Je.from(t?.context):Je.init()})}update(t){return Object.assign(this.#e,t,{timestamp:this.#e.timestamp,variables:{...this.#e?.variables,...t?.variables}}),this}get local(){return this.#e}get now(){let t=this.#e.timestamp??0;return t||(t=Date.now(),Object.assign(this.#e,{timestamp:t})),new Date(t)}get idKey(){return this.options.idKey}get collation(){return this.options?.collation}get processingMode(){return this.options?.processingMode}get useStrictMode(){return this.options?.useStrictMode}get scriptEnabled(){return this.options?.scriptEnabled}get failOnError(){return this.options?.failOnError}get collectionResolver(){return this.options?.collectionResolver}get jsonSchemaValidator(){return this.options?.jsonSchemaValidator}get variables(){return this.options?.variables}get context(){return this.options?.context}},Me=(e=>(e.ACCUMULATOR="accumulator",e.EXPRESSION="expression",e.PIPELINE="pipeline",e.PROJECTION="projection",e.QUERY="query",e.WINDOW="window",e))(Me||{}),Je=class e{#e;constructor(){this.#e={accumulator:{},expression:{},pipeline:{},projection:{},query:{},window:{}}}static init(t={}){let r=new e;for(let n of Object.keys(t))r.#e[n]={...t[n]};return r}static from(...t){if(t.length===1)return e.init(t[0].#e);let r=new e;for(let n of t)for(let o of Object.values(Me))r.addOps(o,n.#e[o]);return r}addOps(t,r){return this.#e[t]=Object.assign({},r,this.#e[t]),this}getOperator(t,r){return this.#e[t][r]??null}addAccumulatorOps(t){return this.addOps("accumulator",t)}addExpressionOps(t){return this.addOps("expression",t)}addQueryOps(t){return this.addOps("query",t)}addPipelineOps(t){return this.addOps("pipeline",t)}addProjectionOps(t){return this.addOps("projection",t)}addWindowOps(t){return this.addOps("window",t)}};function ut(e,t,r){let n=!(r instanceof Se)||oe(r.local.root)?Se.init(r).update({root:e}):r;return ur(e,t,n)}var os=new Set(["$$ROOT","$$CURRENT","$$REMOVE","$$NOW"]);function ur(e,t,r){if(ne(t)&&t.length>0&&t[0]==="$"){if(t==="$$KEEP"||t==="$$PRUNE"||t==="$$DESCEND")return t;let n=r.local.root,o=t.indexOf("."),a=o===-1?t:t.substring(0,o);if(os.has(a)){switch(a){case"$$ROOT":break;case"$$CURRENT":n=e;break;case"$$REMOVE":n=void 0;break;case"$$NOW":n=new Date(r.now);break}t=o===-1?"":t.substring(o+1)}else if(a.length>=2&&a[1]==="$"){n=Object.assign({},r.variables,{this:e},r?.local?.variables);let i=a.substring(2);$(ce(n,i),`Use of undefined variable: ${i}`),t=t.substring(2)}else t=t.substring(1);return t===""?n:Z(n,t)}if(N(t)){let n=new Array(t.length);for(let o=0;o<t.length;o++)n[o]=ur(e,t[o],r);return n}if(Q(t)){let n=Object.keys(t);if(ge(n[0]))return $(n.length===1,"Expression must contain a single operator."),as(e,t[n[0]],n[0],r);let o={};for(let a=0;a<n.length;a++)o[n[a]]=ur(e,t[n[a]],r);return o}return t}function as(e,t,r,n){let o=n.context,a=o.getOperator("expression",r);if(a)return a(e,t,n);let i=o.getOperator("accumulator",r);return $(!!i,`accumulator '${r}' is not registered.`),N(e)||(e=ur(e,t,n),t=null),$(N(e),`arguments must resolve to array for ${r}.`),i(e,t,n)}function Pe(e){return new Vr(e)}function Eo(...e){let t=0;return Pe(()=>{for(;t<e.length;){let r=e[t].next();if(!r.done)return r;t++}return{done:!0,value:void 0}})}function is(e){return!!e&&typeof e=="object"&&typeof e?.next=="function"}function ss(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e[Symbol.iterator]=="function"}var Vr=class{#e=[];#t=[];#r;#o=!1;constructor(t){let r;ss(t)?r=t[Symbol.iterator]():is(t)?r=t:typeof t=="function"?r={next:t}:$(0,"mingo: iterator requires an iterable, generator or function");let n=-1;this.#r=()=>{for(;;){let{value:o,done:a}=r.next();if(a)return{done:a};let i=!0;n++;for(let s=0;s<this.#e.length;s++){let{op:u,fn:c}=this.#e[s],f=c(o,n);if(u==="map")o=f;else if(!f){i=!1;break}}if(i)return{value:o,done:a}}}}push(t,r){return this.#e.push({op:t,fn:r}),this}next(){return this.#r()}map(t){return this.push("map",t)}filter(t){return this.push("filter",t)}take(t){return $(t>=0,"value must be a non-negative integer"),this.filter(r=>t-- >0)}drop(t){return $(t>=0,"value must be a non-negative integer"),this.filter(r=>t--<=0)}transform(t){let r=this,n;return Pe(()=>(n||(n=t(r.collect())),n.next()))}collect(){for(;!this.#o;){let{done:t,value:r}=this.#r();t||this.#t.push(r),this.#o=t}return this.#t}each(t){for(let r=this.next();r.done!==!0;r=this.next())t(r.value)}reduce(t,r){let n=this.next();for(r===void 0&&!n.done&&(r=n.value,n=this.next());!n.done;)r=t(r,n.value),n=this.next();return r}size(){return this.collect().length}[Symbol.iterator](){return this}};function Oo(e,t,r){return e.take(t)}var Gl=Pe([]);function Jr(e,t,r=!0){let n={exclusions:[],inclusions:[],positional:0},o=Object.keys(e);$(o.length,"Invalid empty sub-projection");let a=t?.idKey,i=!1;for(let s of o){if(s.startsWith("$"))return $(!r&&o.length===1,`FieldPath field names may not start with '$', given '${s}'.`),n;s.endsWith(".$")&&n.positional++;let u=e[s];if(u===!1||G(u)&&u===0)s===a?i=!0:n.exclusions.push(s);else if(!Q(u))n.inclusions.push(s);else{let c=Jr(u,t,!1);if(!c.inclusions.length&&!c.exclusions.length)n.inclusions.includes(s)||n.inclusions.push(s);else{for(let f of c.exclusions)n.exclusions.push(`${s}.${f}`);for(let f of c.inclusions)n.inclusions.push(`${s}.${f}`)}n.positional+=c.positional}$(!(n.exclusions.length&&n.inclusions.length),"Cannot do exclusion and inclusion in projection."),$(n.positional<=1,"Cannot specify more than one positional projection.")}if(i&&n.exclusions.push(a),r){let s=new ir;for(let u of n.exclusions)$(s.add(u),`Path collision at ${u}.`);for(let u of n.inclusions)$(s.add(u),`Path collision at ${u}.`);n.exclusions.sort(),n.inclusions.sort()}return n}var Gr="$project";function cr(e,t,r){if(Et(t))return e;let n=Jr(t,r),o=us(t,Se.init(r),n);return e.map(o)}function us(e,t,r){let n=t.idKey,{exclusions:o,inclusions:a}=r,i={},s={preserveMissing:!0};for(let l of o)i[l]=(m,h)=>{Qr(m,l,{descendArray:!0})};for(let l of a){let m=Z(e,l)??e[l];if(l.endsWith(".$")&&m===1){let h=t?.local?.condition??{};$(h,`${Gr}: positional operator '.$' requires array condition.`);let d=l.slice(0,-2);i[d]=ls(d,h,t);continue}if(N(m))i[l]=(h,d)=>{t.update({root:d});let g=m.map(v=>ut(d,v,t)??null);Qe(h,l,g)};else if(G(m)||m===!0)i[l]=(h,d)=>{t.update({root:d});let g=Ue(d,l,s);Po(h,g)};else if(!Q(m))i[l]=(h,d)=>{t.update({root:d});let g=ut(d,m,t);Qe(h,l,g)};else{let h=Object.keys(m);$(h.length===1&&ge(h[0]),"Not a valid operator");let d=h[0],g=m[d],v=t.context.getOperator(Me.PROJECTION,d);!v||d==="$slice"&&!Ne(g).every(G)?i[l]=(y,x)=>{t.update({root:x});let b=ut(x,m,t);Qe(y,l,b)}:i[l]=(y,x)=>{t.update({root:x});let b=v(x,g,l,t);Qe(y,l,b)}}}let u=o.length===1&&o.includes(n),c=!o.includes(n),f=!a.length,p=f&&u||f&&o.length&&!u;return l=>{let m={};p&&Object.assign(m,l);for(let h in i)i[h](m,l);return f||or(m),c&&!ce(m,n)&&ce(l,n)&&(m[n]=Z(l,n)),m}}var Io=(e,t,r,n)=>{let o=Z(e,t);N(o)||(o=Z(o,r)),$(N(o),`${Gr}: field '${t}' must resolve to array`);let a=[];for(let i=0;i<o.length;i++)n({[r]:[o[i]]})&&a.push(i);return a},cs=e=>(t=>!e(t)),fs={$and:1,$or:1,$nor:1};function ls(e,t,r){let n=Object.entries(t).slice(),o={$and:[],$or:[]};for(let u=0;u<n.length;u++){let[c,f,p]=n[u];if(c===e||c.startsWith(e+".")){let l=Ve(f),m=Object.keys(l)[0],h=l[m],d=r.context.getOperator(Me.QUERY,m),g=c.substring(c.lastIndexOf(".")+1),v=d(g,h,r);!p||p==="$and"?o.$and.push([c,v,g]):p==="$nor"?o.$and.push([c,cs(v),g]):p==="$or"&&o.$or.push([c,v,g])}else if(ge(c)){$(!!fs[c],`${Gr}: '${c}' is not allowed in this context`);for(let l of f)for(let m of Object.keys(l))n.push([m,l[m],c])}}let a=e.lastIndexOf("."),i=e.substring(0,a)||e,s=e.substring(a+1);return(u,c)=>{let f=[];for(let[m,h,d]of o.$and)f.push(Io(c,m,d,h));if(o.$or.length){let m=[];for(let[h,d,g]of o.$or)m.push(...Io(c,h,g,d));f.push(Kr(m))}let p=Ot(f).sort()[0],l=Z(c,e)[p];i!=s&&!Q(l)&&(l={[s]:l}),Qe(u,i,[l])}}function Po(e,t){if(e===st||oe(e))return t;if(oe(t))return e;let r=e,n=t;for(let o of Object.keys(t))r[o]=Po(r[o],n[o]);return r}function Ao(e,t,r){return $(t>=0,"$skip value must be a non-negative integer"),e.drop(t)}function fr(e,t,r){$(Q(t)&&Object.keys(t).length>0,"$sort specification is invalid");let n=ae,o=r.collation;return Q(o)&&ne(o.locale)&&(n=ds(o)),e.transform(a=>{let i=Object.keys(t);for(let s of i.reverse()){let u=zr(a,l=>Z(l,s)),c=Array.from(u.keys()),f=!1;if(n===ae){let l=!0,m=!0;for(let h of c)if(l&&=ne(h),m&&=G(h),!l&&!m)break;if(f=l||m,l)c.sort();else if(m){let h=new Float64Array(c).sort();for(let d=0;d<h.length;d++)c[d]=h[d]}}f||c.sort(n),t[s]===-1&&c.reverse();let p=0;for(let l of c)for(let m of u.get(l))a[p++]=m;$(p==a.length,"bug: counter must match collection size.")}return Pe(a)})}var ps={1:"base",2:"accent",3:"variant"};function ds(e){let t={sensitivity:ps[e.strength||3],caseFirst:e.caseFirst==="off"?"false":e.caseFirst,numeric:e.numericOrdering||!1,ignorePunctuation:e.alternate==="shifted"};e.caseLevel===!0&&(t.sensitivity==="base"&&(t.sensitivity="case"),t.sensitivity==="accent"&&(t.sensitivity="variant"));let r=new Intl.Collator(e.locale,t);return(n,o)=>ne(n)&&ne(o)?r.compare(n,o):ae(n,o)}var Ro={$sort:fr,$skip:Ao,$limit:Oo},lr=class{#e;#t;#r;#o;#i={};#n=null;#a=[];constructor(t,r,n,o){this.#e=t,this.#t=r,this.#r=n,this.#o=o}fetch(){if(this.#n)return this.#n;this.#n=Pe(this.#e).filter(this.#t);let t=this.#o.processingMode;t&It.CLONE_INPUT&&this.#n.map(r=>Ce(r));for(let r of Object.keys(Ro))if(ce(this.#i,r)){let n=Ro[r];this.#n=n(this.#n,this.#i[r],this.#o)}return Object.keys(this.#r).length&&(this.#n=cr(this.#n,this.#r,this.#o)),t&It.CLONE_OUTPUT&&this.#n.map(r=>Ce(r)),this.#n}fetchAll(){let t=Pe(Array.from(this.#a));return this.#a.length=0,Eo(t,this.fetch())}all(){return this.fetchAll().collect()}skip(t){return this.#i.$skip=t,this}limit(t){return this.#i.$limit=t,this}sort(t){return this.#i.$sort=t,this}collation(t){return this.#o={...this.#o,collation:t},this}next(){if(this.#a.length>0)return this.#a.pop();let t=this.fetch().next();if(!t.done)return t.value}hasNext(){if(this.#a.length>0)return!0;let t=this.fetch().next();return t.done?!1:(this.#a.push(t.value),!0)}[Symbol.iterator](){return this.fetchAll()}};var ms=new Set(["$and","$or","$nor","$expr","$jsonSchema"]),fe=class{#e;#t;#r;constructor(t,r){this.#t=Ce(t),this.#r=Se.init(r).update({condition:t}),this.#e=[],this.compile()}compile(){$(Q(this.#t),`query criteria must be an object: ${JSON.stringify(this.#t)}`);let t={};for(let r of Object.keys(this.#t)){let n=this.#t[r];if(r==="$where")$(this.#r.scriptEnabled,"$where operator requires 'scriptEnabled' option to be true."),Object.assign(t,{field:r,expr:n});else if(ms.has(r))this.processOperator(r,r,n);else{$(!ge(r),`unknown top level operator: ${r}`);let o=Ve(n);for(let a of Object.keys(o))this.processOperator(r,a,o[a])}t.field&&this.processOperator(t.field,t.field,t.expr)}}processOperator(t,r,n){let o=this.#r.context.getOperator(Me.QUERY,r);$(!!o,`unknown query operator ${r}`),this.#e.push(o(t,n,this.#r))}test(t){return this.#e.every(r=>r(t))}find(t,r){return new lr(t,n=>this.test(n),r||{},this.#r)}};function hs(e,t){let r=a=>a,n=!0;for(let a of Object.keys(e))if(n&&=ge(a)&&a!=="$and"&&a!=="$or"&&a!=="$nor",!n)break;n&&(e={field:e},r=a=>({field:a}));let o=new fe(e,t);return a=>o.test(r(a))}function q(e,t,r,n){let[o,a]=[-1,0];for(;(o=e.indexOf(".",o+1))!==-1;)a++;let i=Se.init(r).update({depth:a}),s={unwrapArray:!0};return n===Zr&&(t=hs(t,r)),u=>{let c=Z(u,e,s);return n(c,t,i)}}function Xr(e,t,r){if(Oe(e,t)||oe(e)&&oe(t))return!0;if(N(e)){let n=r?.local?.depth??1;return e.some(o=>Oe(o,t))||sr(e,n).some(o=>Oe(o,t))}return!1}function Co(e,t,r){return!Xr(e,t,r)}function Yr(e,t,r){return oe(e)?t.some(n=>n===null):Ot([Ne(e),t]).length>0}function No(e,t,r){return!Yr(e,t,r)}function Mo(e,t,r){return pr(e,t,(n,o)=>ae(n,o)<0)}function $o(e,t,r){return pr(e,t,(n,o)=>ae(n,o)<=0)}function Fo(e,t,r){return pr(e,t,(n,o)=>ae(n,o)>0)}function Do(e,t,r){return pr(e,t,(n,o)=>ae(n,o)>=0)}function Lo(e,t,r){return Ne(e).some((n=>t.length===2&&n%t[0]===t[1]))}function Ho(e,t,r){let n=Ne(e),o=a=>ne(a)&&So(t.exec(a),r?.useStrictMode);return n.some(o)||sr(n,1).some(o)}function Bo(e,t,r){return Array.isArray(e)&&e.length===t}function Zr(e,t,r){if(N(e)&&!Et(e)){for(let n=0,o=e.length;n<o;n++)if(t(e[n]))return!0}return!1}var To=e=>e===null,ys={array:N,boolean:_t,bool:_t,date:Ie,number:G,int:G,long:G,double:G,decimal:G,null:To,object:Q,regexp:ye,regex:ye,string:ne,undefined:oe,1:G,2:ne,3:Q,4:N,6:oe,8:_t,9:Ie,10:To,11:ye,16:G,18:G,19:G};function ko(e,t,r){let n=ys[t];return n?n(e):!1}function Wo(e,t,r){return N(t)?t.findIndex(n=>ko(e,n,r))>=0:ko(e,t,r)}function pr(e,t,r){for(let n of Ne(e))if(ze(n)===ze(t)&&r(n,t))return!0;return!1}var jo=(e,t,r)=>q(e,t,r,Zr);var qo=(e,t,r)=>q(e,t,r,Bo);var en=(e,t,r)=>q(e,t,r,Xr);var tn=(e,t,r)=>q(e,t,r,Fo);var rn=(e,t,r)=>q(e,t,r,Do);var nn=(e,t,r)=>q(e,t,r,Yr);var on=(e,t,r)=>q(e,t,r,Mo);var an=(e,t,r)=>q(e,t,r,$o);var sn=(e,t,r)=>q(e,t,r,Co);var un=(e,t,r)=>q(e,t,r,No);var Uo=(e,t,r)=>{let n=e.includes("."),o=!!t;if(!n||e.match(/\.\d+$/))return s=>Z(s,e)!==void 0===o;let a=e.substring(0,e.lastIndexOf(".")),i={preserveIndex:!0};return s=>{let u=Ue(s,e,i),c=Z(u,a);return N(c)?c.some(f=>f!==void 0)===o:c!==void 0===o}};var Ko=(e,t,r)=>q(e,t,r,Wo);var zo=(e,t,r)=>q(e,t,r,Lo);var Qo=(e,t,r)=>q(e,t,r,Ho);var Vo=(e,t,r)=>{$(N(t),"$and expects value to be an Array.");let n=t.map(o=>new fe(o,r));return o=>n.every(a=>a.test(o))};function dr(e,t,r){$(N(t),"Invalid expression. $or expects value to be an Array");let n=t.map(o=>new fe(o,r));return o=>n.some(a=>a.test(o))}function Jo(e,t,r){$(N(t),"Invalid expression. $nor expects value to be an array.");let n=dr("$or",t,r);return o=>!n(o)}function Go(e,t,r){let n={};n[e]=Ve(t);let o=new fe(n,r);return a=>!o.test(a)}var Xo=!1,Yo;function Zo(e){return Xo||(Yo=Je.init({pipeline:{$sort:fr,$project:cr},query:{$elemMatch:jo,$eq:en,$nor:Jo,$exists:Uo,$regex:Qo,$and:Vo,$gt:tn,$gte:rn,$in:nn,$lt:on,$lte:an,$ne:sn,$nin:un,$mod:zo,$not:Go,$or:dr,$size:qo,$type:Ko}}),Xo=!0),new fe(e,{context:Yo})}function ea(e,t,r){var n=ue(e.primaryKey),o=Cn(t);if(typeof o.skip!="number"&&(o.skip=0),o.selector?(o.selector=o.selector,mr(o.selector)):o.selector={},o.index){var a=Lt(o.index);a.includes(n)||a.push(n),o.index=a}if(r&&!o.sort)o.sort=[{[n]:"asc"}];else if(o.sort){var p=o.sort.find(l=>kn(l)===n);p||(o.sort=o.sort.slice(0),o.sort.push({[n]:"asc"}))}else if(o.index)o.sort=o.index.map(l=>({[l]:"asc"}));else{if(e.indexes){var i=new Set;Object.entries(o.selector).forEach(([l,m])=>{var h;typeof m=="object"&&m!==null?h=!!Object.keys(m).find(d=>tr.has(d)):h=!0,h&&i.add(l)});var s=-1,u;e.indexes.forEach(l=>{var m=Ht(l)?l:[l],h=m.findIndex(g=>!i.has(g)),d=h===-1?m.length:h;d>0&&d>s&&(s=d,u=m)}),u&&(o.sort=u.map(l=>({[l]:"asc"})))}if(!o.sort)if(e.indexes&&e.indexes.length>0){var c=e.indexes[0],f=Ht(c)?c:[c];o.sort=f.map(l=>({[l]:"asc"}))}else o.sort=[{[n]:"asc"}]}return o}function ta(e,t){if(!t.sort)throw z("SNH",{query:t});var r=[];t.sort.forEach(o=>{var a=Object.keys(o)[0],i=Object.values(o)[0];r.push({key:a,direction:i,getValueFn:qt(a)})});var n=(o,a)=>{for(var i=0;i<r.length;++i){var s=r[i],u=s.getValueFn(o),c=s.getValueFn(a);if(u!==c){var f=s.direction==="asc"?1:-1,p=typeof u;if(p===typeof c&&(p==="string"||p==="number"))return(u<c?-1:1)*f;var l=s.direction==="asc"?ae(u,c):ae(c,u);return l}}};return n}function ra(e,t){if(!t.sort)throw z("SNH",{query:t});var r=Zo(t.selector),n=o=>r.test(o);return n}var na=new Set(["$and","$or","$nor"]),gs=new Set(["$not"]);function vs(e){var t=Object.keys(e);return t.length===0?!1:t.some(r=>!r.startsWith("$"))?!0:t.some(r=>na.has(r)||gs.has(r))}function mr(e){Object.entries(e).forEach(([t,r])=>{if(typeof r!="object"||r===null)e[t]={$eq:r};else if(na.has(t)&&Array.isArray(r))r.forEach(o=>mr(o));else if(t==="$not"&&typeof r=="object")mr(r);else if(!t.startsWith("$")&&typeof r=="object"){var n=r;n.$elemMatch&&typeof n.$elemMatch=="object"&&vs(n.$elemMatch)&&mr(n.$elemMatch)}})}function oa(e,t){if(!t.sort)throw z("SNH",{query:t});var r=yo(e,t);return{query:t,queryPlan:r}}var ws=Dn(10),xs=0;function bs(){return ws+ ++xs}function ia(e,t,r,n,o,a,i){for(var s=!!e.schema.attachments,u=[],c=[],f=[],p=bs(),l={id:p,events:[],checkpoint:null,context:o},m=l.events,h=[],d=[],g=[],v=r.size>0,w,y=n.length,x=0;x<y;x++){var b=n[x],S=b.document,T=b.previous,A=S[t],C=S._deleted,k=T&&T._deleted,H=void 0;v&&(H=r.get(A));var V=void 0;if(H){var L=H._rev;if(!T||T&&L!==T._rev){var D={isError:!0,status:409,documentId:A,writeRow:b,documentInDb:H,context:o};f.push(D);continue}var M=s?aa(b):b;if(s)if(C){if(T)for(var K=T._attachments,se=Object.keys(K),wr=0;wr<se.length;wr++){var hn=se[wr];d.push({documentId:A,attachmentId:hn,digest:K[hn].digest})}}else{for(var Mt=S._attachments,$t=Object.keys(Mt),xr=0;xr<$t.length;xr++){var br=$t[xr],si=Mt[br],ui=T?T._attachments[br]:void 0;if(!ui&&!si.data){V={documentId:A,documentInDb:H,isError:!0,status:510,writeRow:b,attachmentId:br,context:o};break}}if(!V){for(var Sr=0;Sr<$t.length;Sr++){var ht=$t[Sr],yt=Mt[ht],yn=T?T._attachments[ht]:void 0;if(!yn)h.push({documentId:A,attachmentId:ht,attachmentData:yt,digest:yt.digest});else{var ci=M.document._attachments[ht].digest;yt.data&&yn.digest!==ci&&g.push({documentId:A,attachmentId:ht,attachmentData:yt,digest:yt.digest})}}if(T)for(var gn=T._attachments,vn=Object.keys(gn),_r=0;_r<vn.length;_r++){var Er=vn[_r];Mt[Er]||d.push({documentId:A,attachmentId:Er,digest:gn[Er].digest})}}}V?f.push(V):(c.push(M),i&&i(S),w=M);var Ft=void 0,Or=null,Dt=void 0;if(k&&!C)Dt="INSERT",Ft=s?M.document:S;else if(T&&!k&&!C)Dt="UPDATE",Ft=s?M.document:S,Or=T;else if(C)Dt="DELETE",Ft=B(S),Or=T;else throw z("SNH",{args:{writeRow:b}});var fi={documentId:A,documentData:Ft,previousDocumentData:Or,operation:Dt};m.push(fi)}else{if(s)for(var re=S._attachments,_=Object.keys(re),E=0;E<_.length;E++){var O=_[E],R=re[O];R.data?h.push({documentId:A,attachmentId:O,attachmentData:R,digest:R.digest}):(V={documentId:A,isError:!0,status:510,writeRow:b,attachmentId:O,context:o},f.push(V))}var I=void 0;if(!V){var P=s?aa(b):b;I=P,u.push(P),a&&a(S),w=P}if(!C){var W=S;s&&(W=I?I.document:cn(S));var J={documentId:A,operation:"INSERT",documentData:W,previousDocumentData:s&&T?cn(T):T};m.push(J)}}}return{bulkInsertDocs:u,bulkUpdateDocs:c,newestRow:w,errors:f,eventBulk:l,attachmentsAdd:h,attachmentsRemove:d,attachmentsUpdate:g}}function aa(e){return{previous:e.previous,document:cn(e.document)}}function fn(e){var t=e.data;if(!t)return e;var r={length:t.size,digest:e.digest,type:e.type};return r}function cn(e){var t=e._attachments;if(!t)return e;var r=!1;for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){r=!0;break}if(!r)return e;for(var o=Ar(e),a={},i=Object.keys(t),s=0;s<i.length;s++){var u=i[s];a[u]=fn(t[u])}return o._attachments=a,o}function sa(e){if(e.schema.keyCompression)throw z("UT5",{args:{params:e}});if(Ss(e.schema))throw z("UT6",{args:{params:e}});if(e.schema.attachments&&e.schema.attachments.compression)throw z("UT7",{args:{params:e}})}function Ss(e){return!!(e.encrypted&&e.encrypted.length>0||e.attachments&&e.attachments.encrypted)}function _s(e,t,r){var n=ue(e.schema.primaryKey),o=r?r.lwt:Rr,a=r?r.id:"";return ea(e.schema,{selector:{$or:[{"_meta.lwt":{$gt:o}},{"_meta.lwt":{$eq:o},[n]:{$gt:r?a:""}}],"_meta.lwt":{$gte:o}},sort:[{"_meta.lwt":"asc"},{[n]:"asc"}],skip:0,limit:t})}async function ua(e,t,r){if(e.getChangedDocumentsSince)return e.getChangedDocumentsSince(t,r);var n=ue(e.schema.primaryKey),o=oa(e.schema,_s(e,t,r)),a=await e.query(o),i=a.documents,s=Le(i);return{documents:i,checkpoint:s?{id:s[n],lwt:s._meta.lwt}:r||{id:"",lwt:0}}}function ca(e,t){var r=t.map(n=>{var o=Be(e,n);if(!o)throw z("CI1",{fieldName:n});var a=o.type,i;(a==="number"||a==="integer")&&(i=pn(o));var s=qt(n),u=o.maxLength?o.maxLength:0,c;if(a==="string")c=w=>{var y=s(w);return y||(y=""),y.padEnd(u," ")};else if(a==="boolean")c=w=>{var y=s(w);return y?"1":"0"};else{var f=i,p=f.minimum,l=f.maximum,m=f.roundedMinimum,h=f.nonDecimals,d=f.decimals,g=f.multiplier;d===0?c=w=>{var y=s(w);return typeof y>"u"&&(y=0),y<p&&(y=p),y>l&&(y=l),(Math.floor(y)-m).toString().padStart(h,"0")}:c=w=>{var y=s(w);typeof y>"u"&&(y=0),y<p&&(y=p),y>l&&(y=l);var x=Math.floor(y),b=Math.min(Math.round((y-x)*g),g-1),S=(x-m).toString().padStart(h,"0");return S+b.toString().padStart(d,"0")}}var v={fieldName:n,schemaPart:o,parsedLengths:i,getValue:s,getIndexStringPart:c};return v});return r}function fa(e,t){var r=ca(e,t),n=r.length,o=r.map(p=>p.getIndexStringPart);if(n===1)return o[0];if(n===2){var a=o[0],i=o[1];return p=>a(p)+i(p)}if(n===3){var s=o[0],u=o[1],c=o[2];return p=>s(p)+u(p)+c(p)}var f=function(p){for(var l="",m=0;m<n;++m)l+=o[m](p);return l};return f}function pn(e){var t=Math.floor(e.minimum),r=Math.ceil(e.maximum),n=e.multipleOf,o=r-t,a=o.toString().length,i=n.toString().split("."),s=0;return i.length>1&&(s=i[1].length),{minimum:t,maximum:r,nonDecimals:a,decimals:s,roundedMinimum:t,multiplier:Math.pow(10,s)}}function la(e,t){var r=ca(e,t),n=0;return r.forEach(o=>{var a=o.schemaPart,i=a.type;if(i==="string")n+=a.maxLength;else if(i==="boolean")n+=1;else{var s=o.parsedLengths;n=n+s.nonDecimals+s.decimals}}),n}function ie(e,t){var r=e.slice(t*-1),n=r.trim();return n}function ln(e,t){typeof t>"u"&&(t=0),t<e.minimum&&(t=e.minimum),t>e.maximum&&(t=e.maximum);var r=(Math.floor(t)-e.roundedMinimum).toString(),n=r.padStart(e.nonDecimals,"0");if(e.decimals>0){var o=e.multiplier,a=Math.min(Math.round((t-Math.floor(t))*o),o-1),i=a.toString();n+=i.padStart(e.decimals,"0")}return n}function $e(e,t,r){var n="";return t.forEach((o,a)=>{var i=Be(e,o),s=r[a],u=i.type;switch(u){case"string":var c=B(i.maxLength,"maxLength not set");typeof s=="string"?s===Y?n+="".padEnd(c,Y):n+=s.padEnd(c," "):n+="".padEnd(c,"\0");break;case"boolean":if(s===null)n+="0";else if(s===he)n+="0";else if(s===Y)n+="1";else{var f=s?"1":"0";n+=f}break;case"number":case"integer":var p=pn(i);if(s===null||s===he){var l="0";n+=l.repeat(p.nonDecimals+p.decimals)}else if(s===Y)n+=ln(p,p.maximum);else{var m=ln(p,s);n+=m}break;default:throw z("CI2",{type:u})}}),n}function ct(e,t,r){var n="";return t.forEach((o,a)=>{var i=Be(e,o),s=r[a],u=i.type;switch(u){case"string":var c=B(i.maxLength,"maxLength not set");typeof s=="string"&&s!==Y?n+=s.padEnd(c," "):s===he?n+="".padEnd(c,"\0"):n+="".padEnd(c,Y);break;case"boolean":if(s===null||s===Y)n+="1";else if(s===he)n+="0";else{var f=s?"1":"0";n+=f}break;case"number":case"integer":var p=pn(i);if(s===null||s===Y){var l="9";n+=l.repeat(p.nonDecimals+p.decimals)}else if(s===he){var m="0";n+=m.repeat(p.nonDecimals+p.decimals)}else n+=ln(p,s);break;default:throw z("CI2",{type:u})}}),n}var Pt="17.4.0";var Es=!0;function pa(){if(Es&&Ze!==Pt)throw z("SNH",{name:"Version mismatch detected",args:{rxdbVersion:Ze,rxdbPremiumVersion:Pt}})}globalThis.WCPOS_TASK_QUEUE_CONTAINMENT_PATCH=1;function Os(e,t){try{var r=e&&e.storageInstance,n=r?[r.databaseName,r.collectionName,"v"+(r.schema&&r.schema.version)].join("/"):"unknown",o=globalThis.__wcposOnStorageRunFailure;if(typeof o=="function"){o({target:n,error:t});return}console.error("[wcpos] storage task-queue run failed ("+n+")",t)}catch{}}function Is(e,t){var r=t;Object.defineProperty(e,"queue",{configurable:!0,get:function(){return r},set:function(n){r=n&&typeof n.catch=="function"?n.catch(function(o){Os(e,o)}):n}})}var da=(function(){function e(r,n,o){this.instanceId=He(),this.queue=Tr,Is(this,Tr),this.readTasks=[],this.writeTasks=[],this.readTaskAdded$=new ee,this.writeTaskAdded$=new ee,this.readQueueRunsInProgress=0,this.writeQueueRunsInProgress=0,this.lockId=r,this.abstractLock=n,this.beforeTaskReadOrWrite=o}var t=e.prototype;return t.setStorageInstance=function(r){this.storageInstance=r},t.runRead=function(r){return new Promise(((n,o)=>{this.readTasks.push((a=>r(a).then((i=>{n(i)})).catch((i=>o(i))))),this.readTaskAdded$.next(),this.triggerReadTasks()}))},t.triggerReadTasks=function(){this.readQueueRunsInProgress>2||(this.readQueueRunsInProgress=this.readQueueRunsInProgress+1,this.queue=this.queue.then((async()=>{this.readQueueRunsInProgress=this.readQueueRunsInProgress-1,this.readTasks.length!==0&&await this.abstractLock.request(this.lockId,(async()=>{try{var r={type:"READ",storageInstance:B(this.storageInstance),accessHandlers:new Map,touchedWriteDocuments:new Set,knownChangesContent:[]};await this.beforeTaskReadOrWrite(r);for(var n=!1;!n;){var o=this.readTasks;this.readTasks=[],o.length===1?await o[0](r):await Promise.all(o.map((a=>a(r)))),this.readTasks.length===0&&await Promise.race([de(10),it(this.writeTaskAdded$),it(this.readTaskAdded$)]),this.readTasks.length===0&&(n=!0)}}finally{r&&await this.cleanupAfterRun(r)}}))})).catch((r=>{throw console.log("ERROR TaskQueue.triggerReadTasks.queue errored:"),console.log(r),r})),this.queue.catch((()=>{})))},t.runWrite=function(r){var n=r.task;return new Promise(((o,a)=>{r.task=async i=>n(i).then((s=>(o(s),s))).catch((s=>{throw a(s),s})),this.writeTasks.push(r),this.writeTaskAdded$.next(),this.triggerWriteTasks()}))},t.triggerWriteTasks=function(){var r=this;this.writeQueueRunsInProgress>2||(this.writeQueueRunsInProgress=this.writeQueueRunsInProgress+1,this.queue=this.queue.then((async()=>{this.writeQueueRunsInProgress=this.writeQueueRunsInProgress-1,this.writeTasks.length!==0&&await this.abstractLock.request(this.lockId,(async()=>{if(this.writeTasks.length!==0)try{for(var n={type:"WRITE",storageInstance:B(this.storageInstance),accessHandlers:new Map,touchedWriteDocuments:new Set,knownChangesContent:[]},o=!1;!o;){var a=this.writeTasks;this.writeTasks=[];var i=async function(){var u=!0,c=s.primaryPath;s.documentWrites.length<20&&(s.documentWrites.find((f=>{var p=f.document[c];return n.touchedWriteDocuments.has(p)}))||(u=!1)),u&&await r.beforeTaskReadOrWrite(n),n.wholeDocumentsFileContent=void 0,await s.task(n)};for(var s of a)await i();this.writeTasks.length===0&&await Promise.race([de(10),it(this.writeTaskAdded$),it(this.readTaskAdded$)]),this.writeTasks.length===0&&(o=!0)}await this.beforeTaskReadOrWrite(n)}finally{n&&await this.cleanupAfterRun(n)}}))})).catch((n=>{throw console.log("ERROR TaskQueue.triggerWriteTasks.queue errored:"),console.error(n.stack||n),n})),this.queue.catch((()=>{})))},t.runCleanup=function(r){return new Promise(((n,o)=>{this.queue=this.queue.then((()=>this.abstractLock.request(this.lockId,(async()=>{try{var a={type:"CLEANUP",storageInstance:B(this.storageInstance),accessHandlers:new Map,touchedWriteDocuments:new Set,knownChangesContent:[]};await this.beforeTaskReadOrWrite(a),await r(a).then((i=>n(i))).catch((i=>o(i)))}finally{a&&await this.cleanupAfterRun(a)}})))),this.queue.catch((()=>{}))}))},t.runInit=function(r){return new Promise(((n,o)=>{this.queue=this.queue.then((()=>this.abstractLock.request(this.lockId,(async()=>{var a={type:"INIT",storageInstance:B(this.storageInstance),accessHandlers:new Map,touchedWriteDocuments:new Set,knownChangesContent:[]};return r(a).then((i=>n(i))).catch((i=>o(i))).then((()=>this.cleanupAfterRun(a)))})))),this.queue.catch((()=>{}))}))},t.cleanupAfterRun=async function(r){await Promise.all(Array.from(r.accessHandlers.values()).map((n=>n.then((o=>o.close())).catch((o=>{})))))},t.awaitIdle=async function(){for(;;){var r=this.queue;if(await this.queue,this.queue===r)return}},e})();function F(e,t){var r=t.accessHandlers.get(e);return r||(r=e.createAccessHandle(),t.accessHandlers.set(e,r)),r}function ma(e){return["rxdb","abstract-filesystem","task-queue-lock",e.databaseName,e.collectionName,e.schema.version].join("||")}globalThis.WCPOS_CHANGELOG_REPLAY_SAFETY_PATCH=3;var ha=256*1024*1024,dn=class extends Error{constructor(t){super("Changelog exceeds "+ha+" bytes: "+t),this.name="WcposChangelogOversized",this.size=t}};async function Ps(e,t){var r=await e.getSize();if(t&&r>ha)throw new dn(r);return e.read(0,r)}var ya=(function(){function e(r,n,o){this.indexStates=r,this.devMode=n,this.fileHandlePromise=o.then((a=>a.getFileHandle("changelog.txt",{create:!0}))),this.fileHandlePromise.catch((()=>{}))}var t=e.prototype;return t.getChangelogOperations=async function(r){var n=await this.fileHandlePromise,o=await F(n,r),a=await Ps(o,this.__wcposSingleInstance),i=r.storageInstance._decode(a);this.__wcposLastRaw=i;var s=new Map;if(this.indexStates.forEach((l=>s.set(l.indexId,[]))),i.length===0)return s;for(var u=JSON.parse("["+i+"]"),c=0;c<u.length;c++){var f=u[c],p=f[0];s.get(p).push(f)}return s},t.addChangelogOperations=async function(r,n,o){if(n.length!==0){o=o||(await F(await this.fileHandlePromise,r)).getWritable();var a,i=JSON.stringify(n),s=i.substring(1,i.length-1);(a=r.knownChangelogFileSize?r.knownChangelogFileSize:await(await F(await this.fileHandlePromise,r)).getSize())>0&&(s=","+s);var u=r.storageInstance._encode(s),c=await o;await c.write(u,{at:a}),r.knownChangelogFileSize=a+u.byteLength,this.devMode&&await this.getChangelogOperations(r)}},t.empty=async function(r){var n=await this.fileHandlePromise,o=await F(n,r);await o.truncate(0),r.knownChangelogFileSize=0},e})();function hr(e,t,r,n,o){for(var a=n===void 0?0:n|0,i=o===void 0?e.length-1:o|0,s=i+1;a<=i;){var u=a+i>>>1;r(e[u],t)>=0?(s=u,i=u-1):a=u+1}return s}function Fe(e,t,r,n,o){for(var a=n===void 0?0:n|0,i=o===void 0?e.length-1:o|0,s=i+1;a<=i;){var u=a+i>>>1;r(e[u],t)>0?(s=u,i=u-1):a=u+1}return s}function ft(e,t,r,n,o){for(var a=n===void 0?0:n|0,i=o===void 0?e.length-1:o|0,s=a-1;a<=i;){var u=a+i>>>1;r(e[u],t)<0?(s=u,a=u+1):i=u-1}return s}function yr(e,t,r,n,o){for(var a=n===void 0?0:n|0,i=o===void 0?e.length-1:o|0,s=a-1;a<=i;){var u=a+i>>>1;r(e[u],t)<=0?(s=u,a=u+1):i=u-1}return s}function At(e,t,r,n,o){for(var a=n===void 0?0:n|0,i=o===void 0?e.length-1:o|0;a<=i;){var s=a+i>>>1,u=r(e[s],t);if(u===0)return s;u<=0?a=s+1:i=s-1}return-1}function ga(e,t,r,n){var o=e.length,a=o-1,i=0;if(o===0)return e.push(t),0;for(var s;n<=a;)i=n+(a-n>>1),s=e[i],r(s,t)<=0?n=i+1:a=i-1;return r(s,t)<=0&&i++,e.splice(i,0,t),i}function le(e){return e.join("||")}var As=["_deleted","_meta.lwt"],Zd=le(As);globalThis.WCPOS_CHANGELOG_IDENTITY_PATCH=1;function Rs(e,t,r){var n=e.rows,o=e.metaIdMap,a=t[3],i=t[1],s=r(a[0],e.primaryKeyLength),u=e.__wcposIndexStates;if(!o&&u&&(t[2]==="A"||t[2]==="R")){var c=u[0],f=c&&c.metaIdMap&&c.metaIdMap.get(s);if(!f||f[1]!==a[1]||f[2]!==a[2])return}function p(w,y){return w&&y&&w[0]===y[0]&&w[1]===y[1]&&w[2]===y[2]}function l(w,y){for(var x=0,b=w.length;x<b;){var S=Math.floor((x+b)/2);w[S][0]<y?x=S+1:b=S}return x}function m(w,y){var x=l(w,y);return w[x]&&w[x][0]===y?x:-1}function h(){var w=o&&o.get(s);if(!o&&!u){for(var y=0;y<n.length;y++)if(r(n[y][0],e.primaryKeyLength)===s){w=n[y];break}}return w&&w[0]!==a[0]}var d;if(t[2]==="A"){if(p(n[i],a))return;var g=i>=0&&i<=n.length&&(i===0||n[i-1][0]<a[0])&&(i===n.length||a[0]<=n[i][0]);if(d=g?i:l(n,a[0]),n[d]&&n[d][0]===a[0])n[d]=a;else{if(!g&&h())return;n.splice(d,0,a)}o&&o.set(s,a)}else if(t[2]==="D"||t[2]==="R")if(d=n[i]&&n[i][0]===a[0]?i:m(n,a[0]),t[2]==="D"){if(t[4]==="wcpos-exact"&&!p(n[d],a))for(d=l(n,a[0]);d<n.length&&n[d][0]===a[0]&&!p(n[d],a);d++);if(d<0||t[4]==="wcpos-exact"&&!p(n[d],a))return;var v=n[d];n.splice(d,1),o&&(o.get(s)===v||p(o.get(s),v))&&o.delete(s)}else{if(d>=0)n[d]=a;else{if(h())return;n.splice(l(n,a[0]),0,a)}o&&o.set(s,a)}else throw new Error("unknown operation key "+t[2])}var wa=(function(){function e(r,n,o,a){this.rows=[],this.indexId=r,this.index=n,this.schema=a,this.name=le(this.index),this.fileHandlePromise=o.then((i=>i.getFileHandle(Ts(r),{create:!0}))),this.fileHandlePromise.catch((()=>{})),this.getIndexableString=fa(this.schema,this.index),this.indexableStringLength=la(this.schema,this.index),this.primaryPath=ue(this.schema.primaryKey),this.primaryKeyLength=B(this.schema.properties[this.primaryPath].maxLength),this.metaIdMap=r===0?new Map:void 0}var t=e.prototype;return t.initRead=async function(r){this.metaIdMap&&this.metaIdMap.clear();var n=await this.fileHandlePromise,o=await F(n,r),a=await o.read(0),i=r.storageInstance._decode(a);if(i.length!==0){var s=JSON.parse(i);if(this.metaIdMap)for(var u=this.primaryKeyLength,c=0;c<s.length;c++){var f=s[c],p=ie(f[0],u);this.metaIdMap.set(p,f)}this.rows=s}else this.rows=[]},t.persistInMemoryRows=async function(r){var n=await this.fileHandlePromise.then((p=>F(p,r))),o=this.rows.length>0?JSON.stringify(this.rows):"",a=await n,i=await a.getSize(),s=r.storageInstance._encode(o),u=!1,c=s.byteLength;i>c&&(u=!0,o=o.padEnd(i," "),s=r.storageInstance._encode(o));var f=await a.getWritable();await f.write(s,{at:0}),u&&await a.truncate(c)},t.runChangelogOperation=function(r){return Rs(this,r,ie)},t.appendWriteOperations=function(r,n,o){for(var a=[],i=r.length,s=0;s<i;s++){var u=r[s],c=n[s],f=u.documentId,p=this.getIndexableString(u.documentData),l=u.previousDocumentData?this.getIndexableString(u.previousDocumentData):null,m=l?At(this.rows,[l],te):-1,h=[p,c[0],c[1]];this.metaIdMap&&this.metaIdMap.set(f,h),p===l?(this.rows[m]=h,o.push([this.indexId,m,"R",[p,c[0],c[1]]])):(u.previousDocumentData&&function(){var y=this.rows[m];this.rows.splice(m,1),o.push([this.indexId,m,"D",y,"wcpos-exact"])}.call(this),a.push(h))}for(var d=0,g=(a=a.sort(va)).length,v=0;v<g;v++){var w=a[v];d=ga(this.rows,w,va,d),o.push([this.indexId,d,"A",w])}return o},t.changeDocumentPosition=function(r,n){var o=this.getIndexableString(r),a=r[this.primaryPath],i=At(this.rows,[o],te),s=[o,n[0],n[1]];return this.rows[i]=s,this.metaIdMap&&this.metaIdMap.set(a,s),[this.indexId,i,"R",s]},e})();function va(e,t){return e[0]<t[0]?-1:1}function Ts(e){return"index-"+ba(e,5)+".txt"}function xa(e){var t=ue(e.primaryKey),r=Lt(e.indexes?e.indexes:[]);(r=(r=ks(r)).map((a=>a.slice(0)))).push(["_meta.lwt",t]),r.push(lt(t));var n=new Set,o=r.slice();return r=o.filter((a=>{var i=le(a);return!n.has(i)&&(n.add(i),!0)}))}function ks(e){return e.map((t=>({index:t,str:t.join(",")}))).sort(((t,r)=>t.str>r.str?1:t.str<r.str?-1:0)).map((t=>t.index))}async function _a(e,t,r,n){for(var o,a,i=[],s=[],u=0,c=o=e.knownDocumentFileSize?e.knownDocumentFileSize:await r.getSize(),f=t.length,p=0;p<f;p++){var l=t[p].documentData,m=JSON.stringify(l),h=c,d=e.storageInstance._encode(m);s.push(d);var g=d.byteLength;u+=g;var v=c+=g;i.push([h,v])}if(s.length===1)a=s[0];else{a=new Uint8Array(u);for(var w=0,y=0;y<s.length;y++){var x=s[y];a.set(x,w),w+=x.byteLength}}return e.knownDocumentFileSize=o+u,{documentPositions:i,writePromise:Mn(n).then((b=>b.write(a,{at:o})))}}async function pe(e,t,r,n){var o=[],a=_n(n,1e3);return await Promise.all(a.map((async i=>{var s=await Ge(e,t,r,i),u=JSON.parse(s);o=o.length===0?u:o.concat(u)}))),o}async function Cs(e,t,r,n){if(!t.wholeDocumentsFileContent){var o=.15;if(Rt(e)*o<n&&Rt(e)>1){var a=await r.read(0);t.wholeDocumentsFileContent=a}}}async function Ge(e,t,r,n){var o=n.length;o>2&&await Cs(e,r,t,o);var a=r.wholeDocumentsFileContent;if(a){for(var i="",s=0;s<o;s++){s>0&&(i+=",");var u=n[s][1],c=n[s][2],f=a.subarray(u,c);i+=r.storageInstance._decode(f)}return"["+i+"]"}var p=new Map,l=r.storageInstance._encode(","),m=o-1;if(o===1){var h=await Sa(t,n,p);m+=h;var d=vt(p,n[0]);return"["+r.storageInstance._decode(d)+"]"}var g=$s(n,25);await Promise.all(g.map((async S=>{var T=await Sa(t,S,p);m+=T})));for(var v=new Uint8Array(m),w=0,y=0;y<o;y++){var x=n[y],b=vt(p,x);v.set(b,w),w+=b.byteLength,y!==o-1&&(v.set(l,w),w+=l.byteLength)}return"["+r.storageInstance._decode(v)+"]"}async function Sa(e,t,r){var n=t[0][1],o=Le(t)[2],a=await e.read(n,o),i=0;if(t.length===1)i+=a.byteLength,r.set(t[0],a);else for(var s=0;s<t.length;s++){var u=t[s],c=a.slice(u[1]-n,u[2]-n);i+=c.byteLength,r.set(u,c)}return i}function Ns(e,t){return e[1]<t[1]?-1:e[1]>t[1]?1:0}function Ms(e,t){var r=[];if(e.length>=t)r=e.slice();else for(;r.length<t;){var n=Fs(e);r.push(n)}var o=0;return r.forEach((a=>o+=a[2]-a[1])),o/r.length}function $s(e,t){for(var r=e.slice(0).sort(Ns),n=Ms(e,5),o=[],a=[],i=0;i<r.length;i++){var s=r[i];if(a.length!==0){var u=Le(a);s[1]-u[2]<t*n?a.push(s):(o.push(a),a=[s])}else a.push(s)}return a.length>0&&o.push(a),o}function Fs(e){return e[Math.floor(Math.random()*e.length)]}globalThis.WCPOS_CHANGELOG_INDEX_STATES_PATCH=1;function Ds(e){for(var t=0;t<e.length;t++)e[t].__wcposIndexStates=e;return e}globalThis.WCPOS_CHANGELOG_REPLAY_SAFETY_PATCH=3;function Ls(e){for(var t=3735928559,r=1103547991,n=0;n<e.length;n++){var o=e.charCodeAt(n);t=Math.imul(t^o,2654435761),r=Math.imul(r^o,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)+":"+e.length}async function Hs(e){for(var t of e.accessHandlers.values()){var r=await t;r&&typeof r.flush=="function"&&await r.flush()}}function Bs(e,t){for(var r=null,n=0;n<e.length;n++){var o=e[n].rows;if(!Array.isArray(o))return"not-array:index-"+n;if(r===null)r=o.length;else if(o.length!==r)return"length-mismatch";for(var a=0;a<o.length;a++){var i=o[a];if(!Array.isArray(i))return"hole:index-"+n;if(typeof i[0]!="string"||!Number.isInteger(i[1])||!Number.isInteger(i[2])||i[1]>i[2])return"invalid-row:index-"+n;if(a>0&&o[a-1][0]>i[0])return"unsorted:index-"+n}}for(var s=e[0].rows,u=new Set,c=0;c<s.length;c++){var f=s[c][0].slice(-t);if(u.has(f))return"duplicate-primary";u.add(f)}return null}function Ws(e,t){for(var r of t.entries())for(var n=e[r[0]],o=n.rows,a=r[1],i=0;i<a.length;i++){var s=a[i],u=s[1],c=s[2],f=s[3];if(!Array.isArray(f)||typeof f[0]!="string")return"stale-changelog-op:malformed:index-"+r[0];if(c==="A"){if(!(u>=0&&u<=o.length)||u>0&&o[u-1][0]>f[0]||u<o.length&&o[u][0]<f[0])return"stale-changelog-op:A:index-"+r[0]}else if(!(u>=0&&u<o.length)||!Array.isArray(o[u])||o[u][0]!==f[0])return"stale-changelog-op:"+c+":index-"+r[0];n.runChangelogOperation(s)}return null}var js=8*1024*1024,qs=512*1024*1024;function Us(){var e=globalThis.__wcposRebuildWindowBytes;return{bytes:e&&e.bytes||js,max:e&&e.max||qs}}async function Ks(e,t,r,n){for(var o=0,a=!1,i=!1,s=t;s<r;){for(var u=await e.read(s,Math.min(s+n,r)),c=0;c<u.length;c++){var f=u[c];if(a)i?i=!1:f===92?i=!0:f===34&&(a=!1);else if(f===34)a=!0;else if(f===123)o++;else if(f===125&&(o--,o===0))return s+c+1}s+=u.length}return-1}async function zs(e){var t=e.reason,r=e.runState,n=e.docsAccessHandle,o=e.indexStates,a=e.changelog,i=e.stampHandle,s=e.decode,u=e.primaryPath,c=e.databaseName,f=e.collectionName,p;try{for(var l=await n.getSize(),m=new Map,h=Us(),d=h.bytes,g=0,v=0;v<l;){for(var w=Math.min(v+d,l),y=await n.read(v,w),x=0;x<y.length;){if(y[x]!==123){x++;continue}for(var b=x,S=0,T=!1,A=!1,C=-1,k=b;k<y.length;k++){var H=y[k];if(T)A?A=!1:H===92?A=!0:H===34&&(T=!1);else if(H===34)T=!0;else if(H===123)S++;else if(H===125&&(S--,S===0)){C=k+1;break}}if(C<0){if(w<l){if(b>0){x=b;break}if(d<h.max){d=Math.min(d*2,h.max),x=0;break}var V=await Ks(n,v,l,h.bytes);if(V>0){g++,x=V-v,d=h.bytes;break}}x=b+1;continue}try{var re=JSON.parse(s(y.subarray(b,C)));if(!re||typeof re!="object"||!Object.prototype.hasOwnProperty.call(re,u)){x=b+1;continue}var _=parseInt(re._rev,10);Number.isNaN(_)&&(_=-1);var E=m.get(re[u]),O=v+b,R=v+C;(!E||_>E.revision||_===E.revision&&O>E.start)&&m.set(re[u],{doc:re,start:O,end:R,revision:_}),x=C,d=h.bytes}catch{x=b+1}}v+=x}p=Array.from(m.values());for(var I of o)I.rows=p.map(function(D){return[I.getIndexableString(D.doc),D.start,D.end]}).sort(function(D,M){return D[0]<M[0]?-1:1});for(var P of o)await P.persistInMemoryRows(r);await Hs(r);for(var W of o)await W.initRead(r);await a.empty(r);var J=await F(i,r);await J.truncate(0)}catch(D){try{D.message="index rebuild failed ("+t+"): "+D.message}catch{}throw D}var L={db:c,col:f,reason:t,documents:p.length,skipped:g};console.warn("[wcpos] rebuilt storage indexes from documents.json",L),e.changelogBytes!==void 0&&typeof globalThis.__wcposOnStorageRecovery=="function"&&globalThis.__wcposOnStorageRecovery({kind:"changelog-oversized-rebuilt",target:c+"/"+f,bytes:e.changelogBytes,documents:p.length}),typeof globalThis.__wcposOnIndexRebuild=="function"&&globalThis.__wcposOnIndexRebuild({target:c+"/"+f,reason:t,documents:p.length,skipped:g})}async function Oa(e,t,r){var n=e.getDirectory(),o=Qs({databaseName:t.databaseName,collectionName:t.collectionName,schemaVersion:t.schema.version}),a=n.then((s=>s.getDirectoryHandle(o,{create:!0})));a.catch((()=>{}));var i=a.then((s=>s.getFileHandle("documents.json",{create:!0})));return i.catch((()=>{})),r.runInit((async s=>{var u=i.then((k=>F(k,s)));u.catch((()=>{}));var c=a.then((k=>k.getFileHandle("changes.json",{create:!0})));c.catch((()=>{}));var f=ue(t.schema.primaryKey),p=B(t.schema.properties[f].maxLength),l=Ds(xa(t.schema).map(((k,H)=>new wa(H,k,a,t.schema)))),m=En(l.map((k=>k.indexableStringLength))),h=new ya(l,t.devMode,a),d=await u;if(h.__wcposSingleInstance=!t.multiInstance,await d.getSize()>0){var g=await(await a).getFileHandle("wcpos-changelog-baked.txt",{create:!0}),v=await F(g,s),w=null,y;try{var x=await Promise.allSettled(l.map((k=>k.initRead(s)))),b=x.find((k=>k.status==="rejected"));if(b)throw b.reason;var S=await h.getChangelogOperations(s),T=s.storageInstance._decode(await v.read(0));T!==""&&T===Ls(h.__wcposLastRaw)?w="stale-changelog-after-compaction":w=Ws(l,S),w||(w=Bs(l,p))}catch(k){if(k&&k.name==="WcposChangelogOversized"){if(t.multiInstance)throw k;y=k.size}w="boot-failed:"+(k&&k.message)}w!==null&&await zs({reason:w,runState:s,docsAccessHandle:d,indexStates:l,changelog:h,stampHandle:g,decode:s.storageInstance._decode.bind(s.storageInstance),primaryPath:f,databaseName:t.databaseName,collectionName:t.collectionName,changelogBytes:y})}var A=t.multiInstance&&typeof BroadcastChannel<"u"?new BroadcastChannel(r.lockId):void 0;A&&A.unref&&A.unref();var C=new ee;return A&&(A.onmessage=k=>{var H=k.data;C.next(H)}),{params:t,taskQueue:r,indexStates:l,firstIdx:l[0],primaryPath:f,primaryKeyLength:p,root:await n,dirHandle:await a,changesFileHandle:await c,documentFileHandle:await i,changelog:h,maxIndexableStringLength:m,broadcastChannel:A,broadcastChannelMessages$:C}}))}function ba(e,t){return(e+"").padStart(t,typeof e=="number"?"0":" ")}function Ea(e){return e.replace(/\//g,"__")}function Qs(e){return["rxdb",Ea(e.databaseName),Ea(e.collectionName),e.schemaVersion].join("-")}function Rt(e){return e.firstIdx.rows.length}function te(e,t){return e[0]<t[0]?-1:e[0]===t[0]?0:1}async function Tt(e,t,r,n){if(t.broadcastChannel){var o={type:"event",eventBulks:n,changelogOperations:r,info:{db:e.databaseName,col:e.collectionName}};t.broadcastChannel.postMessage(o),await de(0)}}function lt(e){return["_deleted","_meta.lwt",e]}async function Ia(e,t){await de(120),t.wholeDocumentsFileContent=void 0;var r=await e.internals.statePromise,n=await F(r.documentFileHandle,t);for(var o of r.indexStates)for(var a of o.rows){var i=await Ge(r,n,t,[a]);try{JSON.parse(i)}catch(s){throw console.log("CANNOT PARSE JSON!! for index "+o.name+":"),console.log(JSON.stringify({indexName:o.name,indexId:o.indexId,indx:o.index,indexRow:a,json:i,indexes:r.indexStates.map((u=>u.metaIdMap?{name:u.name,rows:Array.from(u.metaIdMap?.entries())}:["no meta map fpr "+u.name+" id "+u.indexId])),relindex:o.rows},null,4)),s}}}function Pa(e,t){var r=Math.min(e.length,t);return Array.from(e.subarray(0,r)).map((n=>n.toString(16).padStart(2,"0"))).join(" ")}function Aa(e,t){if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){var r=new Uint8Array(e);return t?new Uint8Array(r):r}var n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return t?new Uint8Array(n):n}var Ra="[]";async function Ta(e,t,r,n){var o=await e.internals.statePromise;if(o.firstIdx.rows.length===0)return Ra;for(var a=F(o.documentFileHandle,n),i=o.firstIdx.metaIdMap,s=[],u=t.length,c=0;c<u;c++){var f=t[c],p=i.get(f);p&&(r||p[0][0]==="0")&&s.push(p)}if(s.length===0)return Ra;var l=await a;return await Ge(o,l,n,s)}async function ka(e,t,r){var n=e.primaryPath,o=new Map,a=await e.internals.statePromise;if(a.firstIdx.rows.length===0)return o;for(var i=F(a.documentFileHandle,r),s=a.firstIdx.metaIdMap,u=[],c=t.length,f=0;f<c;f++){var p=t[f],l=s.get(p);l&&u.push(l)}if(u.length===0)return o;for(var m=await i,h=await pe(a,m,r,u),d=u.length,g=0;g<d;g++){var v=h[g],w=v[n];o.set(w,v)}return o}async function Ca(e,t,r,n){if(t.schema.attachments){var o=r.attachmentsAdd.concat(r.attachmentsUpdate);o.length!==0&&await Promise.all(o.map((async a=>{var i=await Fa(e,t,a.documentId,a.attachmentId,fn(a.attachmentData).digest,!0),s=await F(i,e);await s.truncate(0);var u=new Uint8Array(await a.attachmentData.data.arrayBuffer()),c=await s.getWritable();await c.write(u,{at:0}),c.flush&&await c.flush()})))}}async function Na(e,t,r,n){if(t.schema.attachments){var o=[];n.forEach((a=>{a.events.forEach((i=>{i.previousDocumentData&&Object.keys(i.previousDocumentData._attachments).forEach((s=>{i.documentData._attachments[s]&&!i.documentData._deleted||o.push({documentId:i.documentId,attachmentId:s,digest:B(i.previousDocumentData)._attachments[s].digest})}))}))})),o.length!==0&&await Promise.all(o.map((async a=>{var i=await $a(a.documentId,a.attachmentId,a.digest);await r.dirHandle.removeEntry(i)})))}}async function Ma(e,t,r,n,o){var a=await Fa(e,t,r,n,o),i=await F(a,e),s=await i.read(0);return new Blob([s],{type:""})}async function $a(e,t,r){return"z-attachment-"+(await Nn(e+"||"+t)).slice(0,20)+"-"+r.slice(0,20)+".txt"}var Vs=new WeakMap;async function Fa(e,t,r,n,o,a=!1){var i=await t.internals.statePromise,s=await $a(r,n,o),u=zt(Vs,e,(()=>new Map));return zt(u,s,(()=>i.dirHandle.getFileHandle(s,{create:a})))}globalThis.WCPOS_CHANGES_FILE_SALVAGE_PATCH=1;function Js(e,t){for(var r=0,n=!1,o=!1,a=t;a<e.length;a++){var i=e[a];if(n){o?o=!1:i==="\\"?o=!0:i==='"'&&(n=!1);continue}if(i==='"')n=!0;else if(i==="{"||i==="[")r++;else if((i==="}"||i==="]")&&(r--,r===0))return a+1}return-1}function Da(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e)||e[r]!==t||typeof e._deleted!="boolean"||!e._meta||typeof e._meta.lwt!="number")return!1;if(!n)return!0;var o=e._attachments;if(!o||typeof o!="object"||Array.isArray(o))return!1;for(var a in o){var i=o[a];if(!i||typeof i!="object"||typeof i.digest!="string")return!1}return!0}function Ha(e,t,r){if(!e||typeof e!="object"||Array.isArray(e)||!Array.isArray(e.events))return!1;for(var n=0;n<e.events.length;n++){var o=e.events[n];if(!o||typeof o.documentId!="string"||!Da(o.documentData,o.documentId,t,r)||o.previousDocumentData!==void 0&&o.previousDocumentData!==null&&!Da(o.previousDocumentData,o.documentId,t,r))return!1}return!0}function Gs(e,t,r){for(var n=[],o=0;;){for(;o<e.length&&(e[o]===" "||e[o]===` | |
| 54 | 54 | `||e[o]==="\r"||e[o]===" ");)o++;if(n.length>0){if(e[o]!==",")break;for(o++;o<e.length&&(e[o]===" "||e[o]===` |
| 55 | -`||e[o]==="\r"||e[o]===" ");)o++}if(e[o]!=="{")break;var a=Ks(e,o);if(a<0)break;var i;try{i=JSON.parse(e.slice(o,a))}catch{break}if(!Da(i,t,r))break;n.push(i),o=a}return n}function Fa(e){var t=globalThis.__wcposOnStorageRecovery;if(typeof t=="function")try{t(e);return}catch{}console.error("["+e.kind+"] "+e.target,e)}async function Qs(e,t,r,n,o){var a=e.primaryPath,i=!!(e.schema&&e.schema.attachments),s=r.params.databaseName+"/"+r.params.collectionName;if(o.byteLength>33554432)return await n.truncate(0),Fa({kind:"changes-file-discarded",target:s,reason:"oversized",bytes:o.byteLength,keptBulks:0,quarantined:!1}),null;var u=e._decode(o),c;try{for(var f=JSON.parse("["+u+"]"),p=0;p<f.length;p++)if(!Da(f[p],a,i))throw new Error("event bulk "+p+" failed validation");return f}catch(v){c=v}var l=zs(u,a,i),m=!1;try{var h=await(await r.dirHandle).getFileHandle("wcpos-changes-quarantine.json",{create:!0}),d=await D(h,t),y=await d.getWritable();await y.write(o,{at:0}),await d.truncate(o.byteLength),m=!0}catch{}return l.length===0&&await n.truncate(0),Fa(l.length>0?{kind:"changes-file-salvage",target:s,bytes:o.byteLength,keptBulks:l.length,quarantined:m,error:c}:{kind:"changes-file-discarded",target:s,reason:"no-complete-bulk",bytes:o.byteLength,keptBulks:0,quarantined:m,error:c}),l.length>0?l:null}var Vs=16;async function La(e,t,r,n){var o=t.primaryPath,a=!!t.schema.attachments,i=await t.internals.statePromise,s=[],u=r.length<=Vs&&!a&&r.every((x=>!x.previous)),c=u?void 0:D(i.changesFileHandle,e).then((x=>x.getWritable()));c&&c.catch((()=>{}));var f=r.map((x=>x.document[o])),p=It(i)>0?await Ra(t,f,e):new Map,l=oa(t,o,p,r,n),m=l.eventBulk.events;if(s=l.errors,m.length>0){var h=l.newestRow.document;l.eventBulk.checkpoint={id:h[o],lwt:h._meta.lwt},a&&await Ta(e,t,l,i),e.knownChangesContent.push(l.eventBulk);for(var d=0;d<m.length;d++)e.touchedWriteDocuments.add(m[d].documentId);if(u)t.changes$.next(l.eventBulk);else{var y=JSON.stringify(l.eventBulk),v=y;e.knownChangesFileSize&&(y=","+y);var w=t._encode(y),g=(await c).write(w,{at:e.knownChangesFileSize?e.knownChangesFileSize:0});t.changes$.next(v),await g,e.knownChangesFileSize=(e.knownChangesFileSize||0)+w.byteLength}}return{error:s}}async function Ha(e,t){var r=e.knownChangesContent;e.knownChangesContent=[];var n,o=await t.internals.statePromise,[a,i,s]=await Promise.all([D(o.changesFileHandle,e),D(o.documentFileHandle,e),D(await o.changelog.fileHandlePromise,e)]),u=[];if(r.length>0)n=r;else{var c=await a.read(0);if(c.length===0||(n=await Qs(t,e,o,a,c),!n))return}var f=i.getWritable();typeof f.catch=="function"&&f.catch((()=>{}));var p=s.getWritable();typeof p.catch=="function"&&p.catch((()=>{})),n.length===1?u=n[0].events:n.forEach((S=>u=u.concat(S.events))),u.length>1&&(u=u.sort(Js));var l=await ba(e,u,i,f);l.writePromise.catch((()=>{})),t.schema.attachments&&await ka(e,t,o,n),globalThis.WCPOS_RESURRECTION_LEAK_PATCH=1;var m=u;try{var h=o.firstIdx&&o.firstIdx.metaIdMap;if(h)for(var d=0;d<u.length;d++)try{var y=u[d];if(y.previousDocumentData||!h.has(y.documentId))continue;var v=h.get(y.documentId),w=await fe(o,i,e,[v]);if(!w||!w[0])continue;m===u&&(m=u.slice(0)),m[d]=Object.assign({},y,{previousDocumentData:w[0]})}catch{}}catch{}for(var g=[],x=0;x<o.indexStates.length;x++)o.indexStates[x].appendWriteOperations(m,l.documentPositions,g);await l.writePromise,await Promise.all([o.changelog.addChangelogOperations(e,g,p),a.truncate(0)]),e.knownChangesFileSize=0,await Pt(t,o,g,n)}function Js(e,t){var r=e.documentData._meta.lwt,n=t.documentData._meta.lwt;return r<n?-1:r>n?1:e.documentId<t.documentId?-1:e.documentId>t.documentId?1:0}async function Ba(e,t,r){var n=await e.internals.statePromise,o=t.queryPlan.index.slice(0),a=ce(o),i=H(n.indexStates.find((L=>L.name===a)));if(i.rows.length===0)return{documents:[]};var s=t.queryPlan,u=t.query,c=u.skip?u.skip:0,f=c+(u.limit!==null&&u.limit!==void 0?u.limit:1/0),p=!1;s.selectorSatisfiedByIndex||(p=ea(e.schema,t.query));var l=!s.sortSatisfiedByIndex,m=s.startKeys,h=Ne(e.schema,o,m),d=s.endKeys,y=it(e.schema,o,d),v=(s.inclusiveStart?fr:Me)(i.rows,[h],ee),w=(s.inclusiveEnd?lr:st)(i.rows,[y],ee),g=await D(n.documentFileHandle,r),x=[];if(p){var S=w>=v?i.rows.slice(v,w+1):[];if(S.length>0)for(var b=await fe(n,g,r,S),R=0;R<b.length;R++)p(b[R])&&x.push(b[R])}else{var A=w>=v?i.rows.slice(v,w+1):[];if(!l){var T=(A=A.slice(c,f)).length>0?await Ve(n,g,r,A):"[]";return Promise.resolve('{"documents": '+T+"}")}x=await fe(n,g,r,A)}if(l){var C=Zo(e.schema,t.query);x=x.sort(C)}return x=x.slice(c,f),Promise.resolve({documents:x})}async function Wa(e,t,r,n){n||(n={id:"",lwt:0});var o=await e.internals.statePromise,a=["_meta.lwt",e.primaryPath],i=ce(a),s=H(o.indexStates.find((v=>v.name===i)));if(s.rows.length===0)return{documents:[],checkpoint:n};var u=[n.lwt,n.id],c=Ne(e.schema,a,u),f=Me(s.rows,[c],ee),p=await D(o.documentFileHandle,t),l=s.rows.slice(f,f+r),m=[];for(var h of l){var d=(await fe(o,p,t,[h]))[0];m.push(d)}var y=Fe(m);return{documents:m,checkpoint:y?{id:y[e.primaryPath],lwt:y._meta.lwt}:n}}globalThis.WCPOS_EXACT_CLEANUP_DELETE_PATCH=1;globalThis.WCPOS_CLEANUP_COMPACTION_BATCH_PATCH=1;var Gs=1e3,Xs=250;function Ys(){var e=globalThis.__wcposCompactionBatch;return{documents:e&&e.documents||Gs,ms:e&&e.ms||Xs}}async function Zs(e,t,r){var n=e,o=t,a=r.ensureNotFalsy,i=r.getAccessHandle,s=r.getDocumentsJson,u=await n.internals.statePromise,c=[];try{for(var f=a(u.indexStates.find((W=>W.index[0]==="_meta.lwt"&&W.index[1]===n.primaryPath&&W.index.length===2))),p=await i(u.documentFileHandle,o),l=await p.getSize(),m=Ys(),h=Date.now(),d=0,y=0,v=0;;){if(y>=m.documents||y>0&&Date.now()-h>=m.ms)return y;var w=f.rows[v];if(v+=1,!w)return d<l&&await p.truncate(d),y;var g=w[1],x=w[2];if(g===d)d=x;else{y+=1;var S=(await s(u,p,o,[w]))[0],b=d,R=g-b,A,T,C=n._encode(JSON.stringify(S));if(R>=C.byteLength)A=await p.getWritable(),await A.write(C,{at:b}),T=C.byteLength;else{var L=n._encode(" ".repeat(R));A=await p.getWritable(),await A.write(L,{at:b});var J=[];for(var _ of u.indexStates){var O=_.changeDocumentPosition(S,[b,x]);J.push(O)}await u.changelog.addChangelogOperations(o,J),c.push(...J),T=x-g;var I=JSON.stringify(S)+" ".repeat(R),E=n._encode(I);A=await p.getWritable(),await A.write(E,{at:b})}var k=b+T,P=[];for(var B of u.indexStates){var U=B.changeDocumentPosition(S,[b,k]);P.push(U)}await u.changelog.addChangelogOperations(o,P),c.push(...P),d+=T}}}finally{c.length>0&&await r.broadcast(n,u,c)}}globalThis.WCPOS_CHANGELOG_REPLAY_SAFETY_PATCH=3;function eu(e){for(var t=3735928559,r=1103547991,n=0;n<e.length;n++){var o=e.charCodeAt(n);t=Math.imul(t^o,2654435761),r=Math.imul(r^o,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)+":"+e.length}async function ja(e){for(var t of e.accessHandlers.values()){var r=await t;r&&typeof r.flush=="function"&&await r.flush()}}async function Ua(e,t,r){if((await tu(e,t,r)).length>0||(await qa(e,t)).length>0)return!1;var n=await Zs(e,t,{ensureNotFalsy:H,getAccessHandle:D,getDocumentsJson:fe,broadcast:Pt});return n>0?(e.devMode&&await Oa(e,t),await qa(e,t),!1):!0}async function tu(e,t,r){var n=await e.internals.statePromise,o=H(n.indexStates.find((S=>S.name===ce(ut(e.primaryPath))))),a=De()-r,i=Ne(e.schema,ut(e.primaryPath),[!0,1,""]),s=it(e.schema,ut(e.primaryPath),[!0,a,X]),u=Me(o.rows,[i],ee),c=st(o.rows,[s],ee);if(u===-1)return[];var f=o.rows.slice(u,c+1),p=[],l=await D(n.documentFileHandle,t);for(var m of f){var h=ae(m[0],o.primaryKeyLength);p.push(h);var d=(await fe(n,l,t,[m]))[0],y=[];for(var v of n.indexStates){var w=v.getIndexableString(d),g=Et(v.rows,[w],ee),x=[v.indexId,g,"D",v.rows[g],"wcpos-exact"];y.push(x),v.runChangelogOperation(x)}await n.changelog.addChangelogOperations(t,y),await Pt(e,n,y)}return p}async function qa(e,t){var r=await e.internals.statePromise,n,o;try{n=await r.changelog.getChangelogOperations(t)}catch(p){if(!p||p.name!=="WcposChangelogOversized"||r.params.multiInstance)throw p;o=p.size}var a=o!==void 0?r.indexStates:r.indexStates.filter((p=>{var l=n.get(p.indexId);return!(!l||l.length===0)}));if(a.length>0){var i=await(await r.dirHandle).getFileHandle("wcpos-changelog-baked.txt",{create:!0}),s=await D(i,t),u=await s.getWritable(),c=t.storageInstance._encode(o!==void 0?"oversized:"+o:eu(r.changelog.__wcposLastRaw));await u.write(c,{at:0}),await s.truncate(c.byteLength),await ja(t);for(var f of a)await f.persistInMemoryRows(t);await ja(t),await r.changelog.empty(t),await s.truncate(0)}return o!==void 0&&typeof globalThis.__wcposOnStorageRecovery=="function"&&globalThis.__wcposOnStorageRecovery({kind:"changelog-oversized-compacted",target:e.databaseName+"/"+e.collectionName,bytes:o}),a}async function Ka(e,t,r){var n=await e.internals.statePromise,o=t.queryPlan.index.slice(0),a=ce(o),i=H(n.indexStates.find((d=>d.name===a)));if(i.rows.length===0)return{count:0,mode:"fast"};var s=t.queryPlan,u=s.index,c=s.startKeys,f=Ne(e.schema,u,c),p=s.endKeys,l=it(e.schema,u,p),m=(s.inclusiveStart?fr:Me)(i.rows,[f],ee),h=(s.inclusiveEnd?lr:st)(i.rows,[l],ee);return{count:h>=m?h-m+1:0,mode:"fast"}}var ru=De(),nu=(function(){function e(r,n,o,a,i,s,u,c,f){this.changes$=new Z,this.instanceId=ru++,this.readQueueEntries=[],this.storage=r,this.databaseName=n,this.collectionName=o,this.schema=a,this.internals=i,this.options=s,this.devMode=u,this.settings=c,this.databaseInstanceToken=f,this.primaryPath=ie(this.schema.primaryKey),this.taskQueue=i.taskQueue,this.encoder=this.options?.encoder||this.settings?.encoder||new TextEncoder,this.decoder=this.options?.decoder||this.settings?.decoder||new TextDecoder(void 0,{fatal:u})}var t=e.prototype;return t._encode=function(r){return this.encoder.encode(r)},t._decode=function(r){if(!this.devMode)return this.decoder.decode(r);try{return this.decoder.decode(r)}catch(a){var n=Ia(r,!0),o=8192;throw console.error("RxStorageInstanceAbstractFilesystem._decode() failed",{byteLength:n.byteLength,hex:Ea(n,o)}),a}},t.bulkWrite=async function(r,n){return await this.taskQueue.runWrite({task:async o=>La(o,this,r,n),primaryPath:this.primaryPath,documentWrites:r})},t.findDocumentsById=async function(r,n){return await this.taskQueue.runRead((o=>Aa(this,r,n,o)))},t.query=function(r){return this.taskQueue.runRead((async n=>Ba(this,r,n)))},t.count=async function(r){return r.queryPlan.selectorSatisfiedByIndex?this.taskQueue.runRead((async n=>await Ka(this,r,n))):{count:(await this.query(r)).documents.length,mode:"slow"}},t.getAttachmentData=function(r,n,o){return this.taskQueue.runRead((async a=>Ca(a,this,r,n,o)))},t.getChangedDocumentsSince=function(r,n){return this.taskQueue.runRead((async o=>Wa(this,o,r,n)))},t.changeStream=function(){return this.changes$.pipe(Fr(Hn))},t.cleanup=async function(r){return await le(0),await le(0),await this.taskQueue.runCleanup((async n=>await Ua(this,n,r)))},t.close=async function(){return this.closed||(await this.internals.statePromise,this.closed=(async()=>{var r=await this.internals.statePromise;await this.taskQueue.awaitIdle(),r.broadcastChannelMessages$.complete(),this.changes$.complete()})()),this.closed},t.remove=async function(){if(this.closed)throw new Error("instance is closed "+this.databaseName+"-"+this.collectionName);await this.taskQueue.awaitIdle(),await this.close(),await this.taskQueue.runCleanup((async r=>{var n=await this.internals.statePromise,o=[n.documentFileHandle,n.changelog.fileHandlePromise];for(var a of n.indexStates)o.push(await a.fileHandlePromise);await Promise.all(o.map((async i=>{var s=await i,u=await D(s,r);await u.truncate(0)}))),n.broadcastChannel&&(n.broadcastChannel.postMessage({type:"remove"}),await le(0))}))},e})();async function za(e,t,r){var n=pa(t),o=new la(n,e.abstractLock,(s=>Ha(s,i))),a={taskQueue:o,statePromise:_a(e.abstractFilesystem,t,o)},i=new nu(e,t.databaseName,t.collectionName,t.schema,a,t.options,t.devMode,r,t.databaseInstanceToken);return o.setStorageInstance(i),a.statePromise.then((s=>{s.broadcastChannelMessages$.subscribe((async u=>{if(u.type==="event")u.changelogOperations.forEach((c=>{var f=c[0];s.indexStates[f].runChangelogOperation(c)})),u.eventBulks&&u.eventBulks.forEach((c=>i.changes$.next(c)));else{if(u.type!=="remove")throw new Error("BroadcastChannelMessageChanges$: unknown type "+u);s.indexStates.forEach((c=>{c.rows=[],c.metaIdMap&&c.metaIdMap.clear()}))}}))})).catch((()=>{})),i}var ou=(function(){function e(t,r,n,o,a={}){this.rxdbVersion=Ot,this.name=t,this.abstractFilesystem=r,this.abstractLock=n,this.inWorker=o,this.settings=a}return e.prototype.createStorageInstance=async function(t){aa(t),fa();var r=await za(this,t,this.settings);if(!this.inWorker){["findDocumentsById","query","bulkWrite"].forEach((o=>{var a=r[o].bind(r);r[o]=async(i,s,u,c,f)=>{var p=await a(i,s,u,c,f);return typeof p=="string"&&(p=JSON.parse(p)),p}}));var n=r.changeStream.bind(r);r.changeStream=()=>n().pipe(Mr((o=>(typeof o=="string"&&(o=JSON.parse(o)),o))))}return r},e})();function Qa(e){return new ou(e.name,e.abstractFilesystem,e.abstractLock,!!e.inWorker&&e.inWorker,e.settings?e.settings:{})}var Va=20,au=200,Ja=(function(){function e(){this.opfsRootPromise=navigator.storage.getDirectory()}return e.prototype.getDirectory=async function(){var t=await this.opfsRootPromise;return new iu(t)},e})(),iu=(function(){function e(r){this.baseDir=r}var t=e.prototype;return t.getDirectoryHandle=async function(r,n){return new e(await this.baseDir.getDirectoryHandle(r,n))},t.getFileHandle=async function(r,n){var o=await this.baseDir.getFileHandle(r,n);return new su(r,o)},t.removeEntry=async function(r){for(var n=0;n<Va;n++)try{return void await this.baseDir.removeEntry(r)}catch(o){if(o?.name==="NotFoundError")return;if(o?.name==="NoModificationAllowedError"&&n<Va-1){await new Promise((a=>setTimeout(a,au)));continue}throw o}},e})(),su=(function(){function e(t,r){this.name=t,this.fileHandle=r}return e.prototype.createAccessHandle=function(){return Promise.resolve(new uu(this))},e})(),uu=(function(){function e(r){this.fileHandle=r,this.syncAccessHandlePromise=fu(this.fileHandle)}var t=e.prototype;return t.getHandle=function(){var r=this.syncAccessHandle;return r||this.syncAccessHandlePromise.then((n=>(this.syncAccessHandle=n,n)))},t.getWritable=function(){return new cu(this)},t.read=async function(r,n){var o=await this.getHandle();n||(n=await o.getSize());var a=n-r,i=new Uint8Array(a);return a===0||await o.read(i,{at:r}),i},t.truncate=async function(r){var n=await this.getHandle();await n.truncate(r)},t.getSize=async function(){return(await this.getHandle()).getSize()},t.close=async function(){var r=await this.getHandle();await r.close()},e})(),cu=(function(){function e(r){this.accessHandle=r}var t=e.prototype;return t.write=async function(r,n){var o=await this.accessHandle.getHandle();await o.write(r,n)},t.flush=async function(){var r=await this.accessHandle.getHandle();await r.flush()},t.close=async function(){var r=await this.accessHandle.getHandle();await r.close()},e})();async function fu(e){if(typeof e.fileHandle.createSyncAccessHandle!="function")throw new Error('Could not access fileHandle.createSyncAccessHandle(). Likely this is because this storage only works "inside dedicated Web Workers"');return await e.fileHandle.createSyncAccessHandle()}var lu="opfs";function Ga(e={}){return Qa({name:lu,abstractFilesystem:new Ja,abstractLock:navigator.locks,inWorker:!e.usesRxDatabaseInWorker})}function Je(e,t){return{connectionId:e.connectionId,answerTo:e.requestId,method:e.method,error:Ln(t)}}function ct(e,t){return{connectionId:e.connectionId,answerTo:e.requestId,method:e.method,return:t}}function Xa(e){var t=new Map;e.messages$.pipe(vt(o=>o.method==="custom")).subscribe(async o=>{if(!e.customRequestHandler)e.send(Je(o,new Error("Remote storage: cannot resolve custom request because settings.customRequestHandler is not set")));else try{var a=await e.customRequestHandler(o.params);e.send(ct(o,a))}catch(i){e.send(Je(o,i))}});function r(o){if(e.storage)return e.storage.createStorageInstance(o);if(e.database){var a=Array.from(e.database.storageInstances),i=o.collectionName,s=a.find(c=>c.collectionName===i);if(!s)throw console.dir(a),new Error("storageInstance does not exist "+JSON.stringify({collectionName:i}));var u=o.schema;if(!mt(u,s.schema))throw new Error("Wrong schema "+JSON.stringify({schema:u,existingSchema:s.schema}));return Promise.resolve(s)}else throw new Error("no base given")}var n=e.fakeVersion?e.fakeVersion:Ge;return e.messages$.pipe(vt(o=>o.method==="create")).subscribe(async o=>{if(o.version!==n){e.send(Je(o,Q("RM1",{args:{mainVersion:o.version,remoteVersion:n}})));return}var a=o.connectionId;if(Array.isArray(o.params))return;var i=o.params,s=i.collectionName,u=[i.databaseName,i.collectionName,i.schema.version].join("|"),c=t.get(u);if(c){if(!mt(i.schema,c.params.schema)){e.send(Je(o,new Error("Remote storage: schema not equal to existing storage")));return}}else try{c={storageInstancePromise:r(i),connectionIds:new Set,params:i},t.set(u,c),await c.storageInstancePromise}catch(y){e.send(Je(o,y));return}c.connectionIds.add(o.connectionId);var f=[],p=await c.storageInstancePromise;f.push(p.changeStream().subscribe(y=>{var v={connectionId:a,answerTo:"changestream",method:"changeStream",return:y};try{e.send(v)}catch{}}));var l=!1;function m(){l||(l=!0,f.forEach(y=>y.unsubscribe()),H(c).connectionIds.delete(a),t.delete(u))}if(e.database){var h=e.database,d=h.collections[s];d?d.onClose.push(()=>m()):h.onClose.push(()=>m())}f.push(e.messages$.pipe(vt(y=>y.connectionId===a)).subscribe(async y=>{var v=y;if(!(v.method==="create"||v.method==="custom")&&Array.isArray(v.params)){var w;try{if(v.method==="close"&&e.database){e.send(ct(v,null));return}if(v.method==="close"&&H(c).connectionIds.size>1){e.send(ct(v,null)),H(c).connectionIds.delete(a),f.forEach(g=>g.unsubscribe());return}v.method==="getChangedDocumentsSince"&&!p.getChangedDocumentsSince?w=await ia(p,v.params[0],v.params[1]):w=await p[v.method](v.params[0],v.params[1],v.params[2],v.params[3]),(v.method==="close"||v.method==="remove")&&m(),e.send(ct(v,w))}catch(g){try{e.send(Je(v,g))}catch{}}}})),e.send(ct(o,"ok"))}),{instanceByFullName:t}}function Ya(e){var t,r=new Z;if(typeof self<"u"&&typeof self.onconnect=="object"){var n=new Map;self.onconnect=o=>{var a=o.ports[0];a.onmessage=i=>{var s=i.data;n.set(s.connectionId,a),r.next(s)}},t={storage:e.storage,messages$:r,send(o){ht(n,o.connectionId).postMessage(o)}}}else addEventListener("message",(o=>{var a=o.data;r.next(a)})),t={storage:e.storage,messages$:r,send(o){postMessage(o)}};Xa(t)}function Za({channelName:e}){let t=new Set,r=0,n=new Map,o=e&&typeof BroadcastChannel<"u"?new BroadcastChannel(e):void 0;return o&&(o.unref?.(),o.onmessage=async({data:a})=>{if(a?.type==="ownership"&&Array.isArray(a.owned)&&a.owned.every(i=>typeof i=="string")){let i=[...t].filter(u=>!a.owned.includes(u));t=new Set(a.owned),r=Date.now();let s=i.flatMap(u=>[...n.get(u)??[]]);if(s.length){let u,c=!1;if(await Promise.race([(async()=>{for(let f=0;f<2&&!c;){let p=s.map(l=>l.taskQueue.queue);await Promise.allSettled(s.map(l=>l.taskQueue.awaitIdle())),await new Promise(l=>setTimeout(l,0)),f=s.every((l,m)=>l.taskQueue.queue===p[m])?f+1:0}})(),new Promise(f=>{u=setTimeout(()=>{c=!0,f()},2e3)})]),clearTimeout(u),c){o.postMessage({type:"ownership-drain-timeout",seq:a.seq});return}}o.postMessage({type:"ownership-ack",seq:a.seq})}},o.postMessage({type:"hello"})),{ownsRepairs:a=>!a.multiInstance||t.has(a.databaseName)&&Date.now()-r<3e3,onInstance(a,i){let s=n.get(i.databaseName)??new Set;s.add(a),n.set(i.databaseName,s);let u=a.close.bind(a);a.close=async(...c)=>{try{return await u(...c)}finally{s.delete(a),s.size||n.delete(i.databaseName)}}},close:()=>o?.close()}}function ft(e){return e?.name==="SyntaxError"}function cn(e){return e.every(t=>t===0||t===32||t===9||t===10||t===13)}function pr(e){return typeof e=="string"&&JSON.parse(e),e}function lt(e){return typeof e=="string"?JSON.parse(e):e}function te(e,t){let r=globalThis.__wcposOnStorageRecovery;if(typeof r=="function")try{r({kind:e,...t});return}catch{}let{target:n,error:o,...a}=t;console.error(`[${e}] ${n??""}`.trimEnd(),o??a)}function dr(e,t){let r=t.accessHandlers.get(e.documentFileHandle);return r||(r=e.documentFileHandle.createAccessHandle(),t.accessHandlers.set(e.documentFileHandle,r)),r}async function fn(e,t,r,n){let o=[r.indexId,n,"D",r.rows[n],"wcpos-exact"];r.runChangelogOperation(o),await e.changelog.addChangelogOperations(t,[o]),e.broadcastChannel?.postMessage({type:"event",eventBulks:[],changelogOperations:[o],info:{db:e.params.databaseName,col:e.params.collectionName}}),await new Promise(a=>setTimeout(a,0))}function pu(e,t,r){for(let n=e.indexOf("{");n>=0;n=e.indexOf("{",n+1)){let o=0,a=!1,i=!1;for(let s=n;s<e.length;s+=1){let u=e[s];if(a){i?i=!1:u==="\\"?i=!0:u==='"'&&(a=!1);continue}if(u==='"')a=!0;else if(u==="{")o+=1;else if(u==="}"&&--o===0){try{let c=JSON.parse(e.slice(n,s+1));if(c?.[t]===r)return c}catch{}break}}}}async function du(e,t,{discardInvalid:r=!1,ownsRepairs:n=()=>!0}={}){let o=await e.internals.statePromise;return e.taskQueue.runCleanup(async a=>{if(!n())return"multi-instance";let i=o.firstIdx.metaIdMap.get(t);if(!i)return"missing-primary-row";let s=i[1],u=i[2],c=await dr(o,a),f=await c.read(s,u);if(cn(f))return await ei(o,a,s,u),"hollow-row-dropped";let p=o.indexStates.map(y=>{let v=y.rows.findIndex(w=>w[1]===s&&w[2]===u);return{indexState:y,position:v}});if(p.some(({position:y})=>y<0))return"missing-index-row";let l=pu(e._decode(f),e.primaryPath,t);if(!l)return r?(await ln(o,a,t,{includePrimary:!0}),"discarded-no-valid-document"):"no-valid-document";try{if(p.some(({indexState:y,position:v})=>y.getIndexableString(l)!==y.rows[v][0]))return"index-mismatch"}catch{return"index-mismatch"}let m=e._encode(JSON.stringify(l)),h=new Uint8Array(u-s);if(m.byteLength>h.byteLength)return"recovered-document-too-large";h.fill(32),h.set(m);let d=await c.getWritable();return await d.write(h,{at:s}),await d.flush?.(),!0})}async function mu(e,t,r=()=>!0){let n=await e.internals.statePromise;return e.taskQueue.runCleanup(async o=>{let a=r()?void 0:"multi-instance",i=await dr(n,o);for(let s of n.indexStates){let u=s.rows.length;for(;u--;){let c=s.rows[u],f=await i.read(c[1],c[2]);cn(f)&&(a||await fn(n,o,s,u),s===n.firstIdx&&te(a?"hollow-row-refused":"hollow-row-dropped",{target:t,...a?{reason:a}:{},id:ae(c[0],s.primaryKeyLength)}))}}return a})}async function hu(e,t,{discardForeign:r=!1,ownsRepairs:n=()=>!0}={}){let o=await e.internals.statePromise;return e.taskQueue.runCleanup(async a=>{if(!n())return new Map(t.map(u=>[u,"multi-instance"]));let i=new Map,s=await dr(o,a);for(let u of t){let c=o.firstIdx.metaIdMap.get(u);if(!c){i.set(u,!1);continue}let[,f,p]=c,l=!cn(await s.read(f,p));if(l&&!r){i.set(u,"range-holds-foreign-bytes");continue}l?await ln(o,a,u,{includePrimary:!0}):await ei(o,a,f,p),i.set(u,l?"discarded-foreign-bytes":!0)}return i})}async function ei(e,t,r,n){for(let o of e.indexStates){let a=o.rows.length;for(;a--;){let i=o.rows[a];i[1]!==r||i[2]!==n||await fn(e,t,o,a)}}}async function ln(e,t,r,{includePrimary:n}){let o=e.firstIdx.primaryKeyLength;for(let a of e.indexStates){if(!n&&a===e.firstIdx)continue;let i=a.rows.length;for(;i--;)ae(a.rows[i][0],o)===r&&await fn(e,t,a,i)}}async function yu(e,t,r=()=>!0){let n=await e.internals.statePromise;return e.taskQueue.runCleanup(async o=>{if(!r())return"multi-instance";let a=n.firstIdx,i={...a,metaIdMap:new Map};await a.initRead.call(i,o);let s=await n.changelog.getChangelogOperations(o);for(let f of s.get(0)??[])a.runChangelogOperation.call(i,f);let u=[],c=[];for(let f of t){if(a.metaIdMap.has(f)||i.rows.some(p=>ae(p[0],a.primaryKeyLength)===f)){c.push(f);continue}await ln(n,o,f,{includePrimary:!1}),u.push(f)}return{dropped:u,reappeared:c}})}async function gu(e){let t=await e.internals.statePromise;return e.taskQueue.runCleanup(async r=>{let n=await dr(t,r),o=t.indexStates.filter(d=>d!==t.firstIdx),a=t.firstIdx.primaryKeyLength,i=new Set,s="";for(let[d]of t.firstIdx.rows){if(d<s)return"unsorted-primary";s=d;let y=ae(d,a);if(i.has(y))return`duplicate-primary-id:${y.trim()}`;i.add(y)}let u=[];for(let d of o){let y=new Map,v=!1;for(let g of d.rows){let x=ae(g[0],a);if(!i.has(x))return`id-set-mismatch:${x.trim()}`;let S=y.get(x)??[];S.length>0&&(v=!0),S.push(g),y.set(x,S)}let w=!v&&y.size===i.size;u.push({indexState:d,rowsById:y,healthy:w})}if(!u.some(({healthy:d})=>d))return"no-healthy-secondary";let c=[],f=new Set;for(let[d,y,v]of t.firstIdx.rows){let w=ae(d,a),g;try{g=JSON.parse(e._decode(await n.read(y,v)))}catch{return`primary-row-mismatch:${w.trim()}`}if(g?.[e.primaryPath]!==w||t.firstIdx.getIndexableString(g)!==d)return`primary-row-mismatch:${w.trim()}`;if(f.has(y))return`duplicate-primary-range:${w.trim()}`;let x=1,S=new Map;for(let{indexState:b,rowsById:R,healthy:A}of u)for(let T of R.get(w)??[])if(T[1]===y&&T[2]===v){if(!A)continue;try{b.getIndexableString(g)===T[0]&&(x+=1)}catch{}}else{let C=`${T[1]}-${T[2]}`,L=S.get(C)??{range:[T[1],T[2]],voters:[],voterIndexes:new Set};L.voterIndexes.has(b)||(L.voterIndexes.add(b),L.voters.push([b,T[0]])),S.set(C,L)}for(let{range:b,voters:R}of S.values()){if(R.length<x)continue;let A;try{A=JSON.parse(e._decode(await n.read(b[0],b[1])))}catch{continue}if(A?.[e.primaryPath]!==w)continue;let T=0;for(let[C,L]of R)try{C.getIndexableString(A)===L&&(T+=1)}catch{}if(T>=x)return`uncorroborated-primary-range:${w.trim()}`}f.add(y),c.push({document:g,start:y,end:v})}let p=new Map,l=[...c].sort((d,y)=>d.start-y.start);for(let d=1;d<l.length;d+=1)if(l[d].start<l[d-1].end)return"overlapping-ranges";let m=[];for(let d of t.indexStates){if(d===t.firstIdx)continue;let y=c.map(({document:v,start:w,end:g})=>[d.getIndexableString(v),w,g]).sort((v,w)=>v[0]<w[0]?-1:1);JSON.stringify(y)!==JSON.stringify(d.rows)&&m.push([d,y])}if(m.length===0)return"no-divergence";for(let[d,y]of m)p.set(d,d.rows),d.rows=y;let h=[];try{for(let d of t.indexStates)await d.persistInMemoryRows(r),p.has(d)&&h.push(d);await t.changelog.empty(r)}catch(d){for(let[v,w]of p)v.rows=w;let y=[];for(let v=h.length-1;v>=0;v-=1)try{await h[v].persistInMemoryRows(r)}catch(w){y.push(w)}throw y.length>0?new AggregateError([d,...y],`index persistence failed: ${d?.message??d}; rollback incomplete: ${y.map(v=>v?.message??v).join("; ")}`):d}return!0})}function ti(e,t={}){let r=typeof t.ownsRepairs=="function"?t.ownsRepairs:o=>!o.multiInstance,n=e.createStorageInstance.bind(e);return{...e,async createStorageInstance(o){let a=()=>!!r(o),i=await n(o);t.onInstance?.(i,o);let s=i.findDocumentsById.bind(i),u=i.bulkWrite.bind(i),c=i.query.bind(i),f=i.count?.bind(i),p=i.getChangedDocumentsSince.bind(i),l=i.cleanup?.bind(i),m=new Set,h=`${o.databaseName}/${o.collectionName}`,d=async(_,O,I)=>{let E=(await i.internals?.statePromise)?.firstIdx?.metaIdMap;if(!E)return[];let k=new Set;for(let P of O)P&&k.add(P[i.primaryPath]);return _.filter(P=>{if(k.has(P))return!1;let B=E.get(P);return!!B&&(I||B[0][0]==="0")})},y=async _=>{let O=[];if(_.length===0)return O;if(!a()){for(let E of _)O.push({id:E,reason:"multi-instance"}),te("hollow-row-refused",{target:h,id:E,reason:"multi-instance"});return O}let I=await hu(i,_,{discardForeign:o.collectionName==="logs",ownsRepairs:a});for(let[E,k]of I)k==="discarded-foreign-bytes"?te("log-row-discarded",{target:h,id:E,reason:"range-holds-foreign-bytes"}):typeof k=="string"?(O.push({id:E,reason:k}),te("hollow-row-refused",{target:h,id:E,reason:k})):k&&te("hollow-row-dropped",{target:h,id:E});return O},v=(_,O)=>te("document-repair-refused",{target:h,reason:O,..._.length===1?{id:_[0]}:{batchSize:_.length}}),w=async(_,O)=>{let I=async E=>{let k;try{k=lt(await s(E,!0))}catch(U){if(!ft(U))throw U;if(!a())throw v(E,"multi-instance"),U.message+="; targeted recovery refused: multi-instance",U;if(O?.(),E.length===1){let F=await du(i,E[0],{discardInvalid:o.collectionName==="logs",ownsRepairs:a});if(F==="hollow-row-dropped")return te("hollow-row-dropped",{target:h,id:E[0]}),!0;if(F==="discarded-no-valid-document")return te("log-row-discarded",{target:h,id:E[0],reason:"no-valid-document"}),!0;if(F==="multi-instance")throw v(E,F),U.message+="; targeted recovery refused: multi-instance",U;if(typeof F=="string")throw v(E,F),U.message+=`; targeted recovery failed for ${E[0]}: ${F}`,U;return!0}let W=Math.ceil(E.length/2),K=await I(E.slice(0,W)),N=await I(E.slice(W));return K||N}let P=await d(E,k,!0);if(P.length===0)return!1;let B=await y(P);return O?.(),B.length!==P.length};return I([...new Set(_)])},g=async(_,O)=>lt(await s([_],O)).find(E=>E?.[i.primaryPath]===_),x=async(_,O,I,E)=>{let k=lt(O),P=new Set(_),B=new Set,U=!1,W=k.filter(N=>{let F=N?.[i.primaryPath];return P.has(F)?B.has(F)?(U=!0,!1):(B.add(F),!0):!1});if(!E&&!U)return W.length===k.length?O:typeof O=="string"?JSON.stringify(W):W;let K=[];for(let N of W){let F=await g(N[i.primaryPath],I);F&&K.push(F)}return typeof O=="string"?JSON.stringify(K):K};i.findDocumentsById=async(_,O)=>{try{let I=await s(_,O),E=lt(I),k=await d(_,E,O),P=await y(k),B=P.some(({reason:K})=>K==="range-holds-foreign-bytes"),U=await x(_,I,O,B),W=new Set;for(let K of lt(U))W.add(K[i.primaryPath]);if(O){let K=new Set(P.map(({id:F})=>F)),N=(await i.internals?.statePromise)?.firstIdx?.metaIdMap;for(let F of _)K.has(F)||(W.has(F)||!N?.has(F))&&m.add(F)}else for(let K of W)m.add(K);return U}catch(I){if(!ft(I))throw I;if(m.clear(),await w(_))return x(_,await s(_,O),O,!0);if(_.length>1){let E=await Promise.all(_.map(B=>s([B],O))),k=new Set,P=[];return _.forEach((B,U)=>{if(k.has(B))return;k.add(B);let W=lt(E[U]).find(K=>K?.[i.primaryPath]===B);W&&P.push(W)}),typeof E[0]=="string"?JSON.stringify(P):P}throw I}};let S=async _=>{if(!_.some(N=>N.previous))return _;let O=await i.internals?.statePromise,I=O?.firstIdx?.metaIdMap;if(!I)return _;let E=N=>!!N.previous&&!I.has(N.document[i.primaryPath]),k=_.filter(E).map(N=>N.document[i.primaryPath]);k.length>0&&await s([...new Set(k)],!0);let P=[],B=_.map(N=>E(N)?(P.push(N.document[i.primaryPath]),{document:N.document}):N);if(P.length===0)return B;let U=O.firstIdx.primaryKeyLength,W=P.filter(N=>O.indexStates.some(F=>F!==O.firstIdx&&F.rows.some(At=>ae(At[0],U)===N)));if(W.length===0)return B;let K=a()?await yu(i,W,a):"multi-instance";if(K==="multi-instance"){for(let N of W)te("stale-secondary-refused",{target:h,id:N,reason:"multi-instance"});throw new Error(`stale secondary index rows for ${W.join(", ")} in ${h}; targeted recovery refused: multi-instance`)}for(let N of K.dropped)te("stale-secondary-dropped",{target:h,id:N});for(let N of K.reappeared)te("stale-secondary-refused",{target:h,id:N,reason:"reappeared"});return B.map((N,F)=>K.reappeared.includes(N.document[i.primaryPath])?_[F]:N)},b=async(_,O,I,E)=>{let k=[];for(let P=0;P<O.length;P+=1)k.push(E?await R([_[P]],[O[P]],I):await u([O[P]],I));return await i.taskQueue?.awaitIdle?.(),{error:k.flatMap(P=>P.error)}},R=async(_,O,I)=>{try{return await u(O,I)}catch(E){if(m.clear(),!ft(E))throw E;await w(_.map(P=>P.document[i.primaryPath]));let k=await S(_);try{return await b(_,k,I,!1)}catch(P){throw m.clear(),te("write-retry-failed",{target:h,error:P}),P}}};i.bulkWrite=async(_,O)=>{let I=_.map(P=>P.document[i.primaryPath]),E=!1;if(I.some(P=>!m.has(P))&&(await w(I,()=>{E=!0,m.clear()}),!E))for(let P of I)m.add(P);let k=await S(_);return E&&k.length>1?b(_,k,O,!0):R(_,k,O)};let A=0,T,C=()=>(T||(T=gu(i).then(_=>(_===!0&&(A+=1),_)).finally(()=>{T=void 0})),T),L=async(_,O)=>{m.clear();let I=await i.internals.statePromise,E=await w(I.firstIdx.metaIdMap.keys()),k="multi-instance";if(!o.multiInstance)try{let P=await C();if(P===!0)return!0;k=P}catch(P){k=`error ${P?.message??P}`}return E||A!==O?!0:(_.message+=`; index reconciliation refused: ${k}`,te("index-reconcile-refused",{target:h,reason:k}),!1)};if(i.query=async _=>{let O=A;try{return pr(await c(_))}catch(I){if(!ft(I)||!await L(I,O))throw I;return pr(await c(_))}},f&&(i.count=async _=>{let O=await f(_);if(O&&typeof O=="object"&&typeof O.count=="number")return O;te("count-recovery",{target:h,detail:`typeof=${typeof O} result=${JSON.stringify(O)?.slice(0,200)}`});let I=await i.query(_);return{count:(typeof I=="string"?JSON.parse(I):I).documents.length,mode:"fast"}}),i.getChangedDocumentsSince=async(_,O)=>{let I=A;try{return pr(await p(_,O))}catch(E){if(!ft(E)||!await L(E,I))throw E;return pr(await p(_,O))}},!l)return i;let J=async _=>{if(!ft(_))return!1;m.clear();let O=await i.internals.statePromise;return w(O.firstIdx.metaIdMap.keys())};return i.cleanup=async _=>{try{return await l(_)}catch(O){let I;try{return await mu(i,h,a),await l(_)}catch(E){I=E}try{if(await J(I))return await l(_)}catch(E){I=E}throw te("cleanup-recovery",{target:h,error:I,initialError:String(O)}),I}},i}}}var ri=Za({channelName:typeof self<"u"?self.name:""});Ya({storage:ti(Ga(),{ownsRepairs:ri.ownsRepairs,onInstance:ri.onInstance})});})(); | |
| 55 | +`||e[o]==="\r"||e[o]===" ");)o++}if(e[o]!=="{")break;var a=Js(e,o);if(a<0)break;var i;try{i=JSON.parse(e.slice(o,a))}catch{break}if(!Ha(i,t,r))break;n.push(i),o=a}return n}function La(e){var t=globalThis.__wcposOnStorageRecovery;if(typeof t=="function")try{t(e);return}catch{}console.error("["+e.kind+"] "+e.target,e)}async function Xs(e,t,r,n,o){var a=e.primaryPath,i=!!(e.schema&&e.schema.attachments),s=r.params.databaseName+"/"+r.params.collectionName;if(o.byteLength>33554432)return await n.truncate(0),La({kind:"changes-file-discarded",target:s,reason:"oversized",bytes:o.byteLength,keptBulks:0,quarantined:!1}),null;var u=e._decode(o),c;try{for(var f=JSON.parse("["+u+"]"),p=0;p<f.length;p++)if(!Ha(f[p],a,i))throw new Error("event bulk "+p+" failed validation");return f}catch(v){c=v}var l=Gs(u,a,i),m=!1;try{var h=await(await r.dirHandle).getFileHandle("wcpos-changes-quarantine.json",{create:!0}),d=await F(h,t),g=await d.getWritable();await g.write(o,{at:0}),await d.truncate(o.byteLength),m=!0}catch{}return l.length===0&&await n.truncate(0),La(l.length>0?{kind:"changes-file-salvage",target:s,bytes:o.byteLength,keptBulks:l.length,quarantined:m,error:c}:{kind:"changes-file-discarded",target:s,reason:"no-complete-bulk",bytes:o.byteLength,keptBulks:0,quarantined:m,error:c}),l.length>0?l:null}var Ys=16;async function Ba(e,t,r,n){var o=t.primaryPath,a=!!t.schema.attachments,i=await t.internals.statePromise,s=[],u=r.length<=Ys&&!a&&r.every((x=>!x.previous)),c=u?void 0:F(i.changesFileHandle,e).then((x=>x.getWritable()));c&&c.catch((()=>{}));var f=r.map((x=>x.document[o])),p=Rt(i)>0?await ka(t,f,e):new Map,l=ia(t,o,p,r,n),m=l.eventBulk.events;if(s=l.errors,m.length>0){var h=l.newestRow.document;l.eventBulk.checkpoint={id:h[o],lwt:h._meta.lwt},a&&await Ca(e,t,l,i),e.knownChangesContent.push(l.eventBulk);for(var d=0;d<m.length;d++)e.touchedWriteDocuments.add(m[d].documentId);if(u)t.changes$.next(l.eventBulk);else{var g=JSON.stringify(l.eventBulk),v=g;e.knownChangesFileSize&&(g=","+g);var w=t._encode(g),y=(await c).write(w,{at:e.knownChangesFileSize?e.knownChangesFileSize:0});t.changes$.next(v),await y,e.knownChangesFileSize=(e.knownChangesFileSize||0)+w.byteLength}}return{error:s}}async function Wa(e,t){var r=e.knownChangesContent;e.knownChangesContent=[];var n,o=await t.internals.statePromise,[a,i,s]=await Promise.all([F(o.changesFileHandle,e),F(o.documentFileHandle,e),F(await o.changelog.fileHandlePromise,e)]),u=[];if(r.length>0)n=r;else{var c=await a.read(0);if(c.length===0||(n=await Xs(t,e,o,a,c),!n))return}var f=i.getWritable();typeof f.catch=="function"&&f.catch((()=>{}));var p=s.getWritable();typeof p.catch=="function"&&p.catch((()=>{})),n.length===1?u=n[0].events:n.forEach((b=>u=u.concat(b.events))),u.length>1&&(u=u.sort(Zs));var l=await _a(e,u,i,f);l.writePromise.catch((()=>{})),t.schema.attachments&&await Na(e,t,o,n),globalThis.WCPOS_RESURRECTION_LEAK_PATCH=1;var m=u;try{var h=o.firstIdx&&o.firstIdx.metaIdMap;if(h)for(var d=0;d<u.length;d++)try{var g=u[d];if(g.previousDocumentData||!h.has(g.documentId))continue;var v=h.get(g.documentId),w=await pe(o,i,e,[v]);if(!w||!w[0])continue;m===u&&(m=u.slice(0)),m[d]=Object.assign({},g,{previousDocumentData:w[0]})}catch{}}catch{}for(var y=[],x=0;x<o.indexStates.length;x++)o.indexStates[x].appendWriteOperations(m,l.documentPositions,y);await l.writePromise,await Promise.all([o.changelog.addChangelogOperations(e,y,p),a.truncate(0)]),e.knownChangesFileSize=0,await Tt(t,o,y,n)}function Zs(e,t){var r=e.documentData._meta.lwt,n=t.documentData._meta.lwt;return r<n?-1:r>n?1:e.documentId<t.documentId?-1:e.documentId>t.documentId?1:0}async function ja(e,t,r){var n=await e.internals.statePromise,o=t.queryPlan.index.slice(0),a=le(o),i=B(n.indexStates.find((H=>H.name===a)));if(i.rows.length===0)return{documents:[]};var s=t.queryPlan,u=t.query,c=u.skip?u.skip:0,f=c+(u.limit!==null&&u.limit!==void 0?u.limit:1/0),p=!1;s.selectorSatisfiedByIndex||(p=ra(e.schema,t.query));var l=!s.sortSatisfiedByIndex,m=s.startKeys,h=$e(e.schema,o,m),d=s.endKeys,g=ct(e.schema,o,d),v=(s.inclusiveStart?hr:Fe)(i.rows,[h],te),w=(s.inclusiveEnd?yr:ft)(i.rows,[g],te),y=await F(n.documentFileHandle,r),x=[];if(p){var b=w>=v?i.rows.slice(v,w+1):[];if(b.length>0)for(var S=await pe(n,y,r,b),T=0;T<S.length;T++)p(S[T])&&x.push(S[T])}else{var A=w>=v?i.rows.slice(v,w+1):[];if(!l){var C=(A=A.slice(c,f)).length>0?await Ge(n,y,r,A):"[]";return Promise.resolve('{"documents": '+C+"}")}x=await pe(n,y,r,A)}if(l){var k=ta(e.schema,t.query);x=x.sort(k)}return x=x.slice(c,f),Promise.resolve({documents:x})}async function qa(e,t,r,n){n||(n={id:"",lwt:0});var o=await e.internals.statePromise,a=["_meta.lwt",e.primaryPath],i=le(a),s=B(o.indexStates.find((v=>v.name===i)));if(s.rows.length===0)return{documents:[],checkpoint:n};var u=[n.lwt,n.id],c=$e(e.schema,a,u),f=Fe(s.rows,[c],te),p=await F(o.documentFileHandle,t),l=s.rows.slice(f,f+r),m=[];for(var h of l){var d=(await pe(o,p,t,[h]))[0];m.push(d)}var g=Le(m);return{documents:m,checkpoint:g?{id:g[e.primaryPath],lwt:g._meta.lwt}:n}}globalThis.WCPOS_EXACT_CLEANUP_DELETE_PATCH=1;globalThis.WCPOS_CLEANUP_COMPACTION_BATCH_PATCH=1;var eu=1e3,tu=250;function ru(){var e=globalThis.__wcposCompactionBatch;return{documents:e&&e.documents||eu,ms:e&&e.ms||tu}}async function nu(e,t,r){var n=e,o=t,a=r.ensureNotFalsy,i=r.getAccessHandle,s=r.getDocumentsJson,u=await n.internals.statePromise,c=[];try{for(var f=a(u.indexStates.find((J=>J.index[0]==="_meta.lwt"&&J.index[1]===n.primaryPath&&J.index.length===2))),p=await i(u.documentFileHandle,o),l=await p.getSize(),m=ru(),h=Date.now(),d=0,g=0,v=0;;){if(g>=m.documents||g>0&&Date.now()-h>=m.ms)return g;var w=f.rows[v];if(v+=1,!w)return d<l&&await p.truncate(d),g;var y=w[1],x=w[2];if(y===d)d=x;else{g+=1;var b=(await s(u,p,o,[w]))[0],S=d,T=y-S,A,C,k=n._encode(JSON.stringify(b));if(T>=k.byteLength)A=await p.getWritable(),await A.write(k,{at:S}),C=k.byteLength;else{var H=n._encode(" ".repeat(T));A=await p.getWritable(),await A.write(H,{at:S});var V=[];for(var re of u.indexStates){var _=re.changeDocumentPosition(b,[S,x]);V.push(_)}await u.changelog.addChangelogOperations(o,V),c.push(...V),C=x-y;var E=JSON.stringify(b)+" ".repeat(T),O=n._encode(E);A=await p.getWritable(),await A.write(O,{at:S})}var R=S+C,I=[];for(var P of u.indexStates){var W=P.changeDocumentPosition(b,[S,R]);I.push(W)}await u.changelog.addChangelogOperations(o,I),c.push(...I),d+=C}}}finally{c.length>0&&await r.broadcast(n,u,c)}}globalThis.WCPOS_CHANGELOG_REPLAY_SAFETY_PATCH=3;function ou(e){for(var t=3735928559,r=1103547991,n=0;n<e.length;n++){var o=e.charCodeAt(n);t=Math.imul(t^o,2654435761),r=Math.imul(r^o,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)+":"+e.length}async function Ua(e){for(var t of e.accessHandlers.values()){var r=await t;r&&typeof r.flush=="function"&&await r.flush()}}async function za(e,t,r){if((await au(e,t,r)).length>0||(await Ka(e,t)).length>0)return!1;var n=await nu(e,t,{ensureNotFalsy:B,getAccessHandle:F,getDocumentsJson:pe,broadcast:Tt});return n>0?(e.devMode&&await Ia(e,t),await Ka(e,t),!1):!0}async function au(e,t,r){var n=await e.internals.statePromise,o=B(n.indexStates.find((b=>b.name===le(lt(e.primaryPath))))),a=He()-r,i=$e(e.schema,lt(e.primaryPath),[!0,1,""]),s=ct(e.schema,lt(e.primaryPath),[!0,a,Y]),u=Fe(o.rows,[i],te),c=ft(o.rows,[s],te);if(u===-1)return[];var f=o.rows.slice(u,c+1),p=[],l=await F(n.documentFileHandle,t);for(var m of f){var h=ie(m[0],o.primaryKeyLength);p.push(h);var d=(await pe(n,l,t,[m]))[0],g=[];for(var v of n.indexStates){var w=v.getIndexableString(d),y=At(v.rows,[w],te),x=[v.indexId,y,"D",v.rows[y],"wcpos-exact"];g.push(x),v.runChangelogOperation(x)}await n.changelog.addChangelogOperations(t,g),await Tt(e,n,g)}return p}async function Ka(e,t){var r=await e.internals.statePromise,n,o;try{n=await r.changelog.getChangelogOperations(t)}catch(p){if(!p||p.name!=="WcposChangelogOversized"||r.params.multiInstance)throw p;o=p.size}var a=o!==void 0?r.indexStates:r.indexStates.filter((p=>{var l=n.get(p.indexId);return!(!l||l.length===0)}));if(a.length>0){var i=await(await r.dirHandle).getFileHandle("wcpos-changelog-baked.txt",{create:!0}),s=await F(i,t),u=await s.getWritable(),c=t.storageInstance._encode(o!==void 0?"oversized:"+o:ou(r.changelog.__wcposLastRaw));await u.write(c,{at:0}),await s.truncate(c.byteLength),await Ua(t);for(var f of a)await f.persistInMemoryRows(t);await Ua(t),await r.changelog.empty(t),await s.truncate(0)}return o!==void 0&&typeof globalThis.__wcposOnStorageRecovery=="function"&&globalThis.__wcposOnStorageRecovery({kind:"changelog-oversized-compacted",target:e.databaseName+"/"+e.collectionName,bytes:o}),a}async function Qa(e,t,r){var n=await e.internals.statePromise,o=t.queryPlan.index.slice(0),a=le(o),i=B(n.indexStates.find((d=>d.name===a)));if(i.rows.length===0)return{count:0,mode:"fast"};var s=t.queryPlan,u=s.index,c=s.startKeys,f=$e(e.schema,u,c),p=s.endKeys,l=ct(e.schema,u,p),m=(s.inclusiveStart?hr:Fe)(i.rows,[f],te),h=(s.inclusiveEnd?yr:ft)(i.rows,[l],te);return{count:h>=m?h-m+1:0,mode:"fast"}}var iu=He(),su=(function(){function e(r,n,o,a,i,s,u,c,f){this.changes$=new ee,this.instanceId=iu++,this.readQueueEntries=[],this.storage=r,this.databaseName=n,this.collectionName=o,this.schema=a,this.internals=i,this.options=s,this.devMode=u,this.settings=c,this.databaseInstanceToken=f,this.primaryPath=ue(this.schema.primaryKey),this.taskQueue=i.taskQueue,this.encoder=this.options?.encoder||this.settings?.encoder||new TextEncoder,this.decoder=this.options?.decoder||this.settings?.decoder||new TextDecoder(void 0,{fatal:u})}var t=e.prototype;return t._encode=function(r){return this.encoder.encode(r)},t._decode=function(r){if(!this.devMode)return this.decoder.decode(r);try{return this.decoder.decode(r)}catch(a){var n=Aa(r,!0),o=8192;throw console.error("RxStorageInstanceAbstractFilesystem._decode() failed",{byteLength:n.byteLength,hex:Pa(n,o)}),a}},t.bulkWrite=async function(r,n){return await this.taskQueue.runWrite({task:async o=>Ba(o,this,r,n),primaryPath:this.primaryPath,documentWrites:r})},t.findDocumentsById=async function(r,n){return await this.taskQueue.runRead((o=>Ta(this,r,n,o)))},t.query=function(r){return this.taskQueue.runRead((async n=>ja(this,r,n)))},t.count=async function(r){return r.queryPlan.selectorSatisfiedByIndex?this.taskQueue.runRead((async n=>await Qa(this,r,n))):{count:(await this.query(r)).documents.length,mode:"slow"}},t.getAttachmentData=function(r,n,o){return this.taskQueue.runRead((async a=>Ma(a,this,r,n,o)))},t.getChangedDocumentsSince=function(r,n){return this.taskQueue.runRead((async o=>qa(this,o,r,n)))},t.changeStream=function(){return this.changes$.pipe(Wr(Wn))},t.cleanup=async function(r){return await de(0),await de(0),await this.taskQueue.runCleanup((async n=>await za(this,n,r)))},t.close=async function(){return this.closed||(await this.internals.statePromise,this.closed=(async()=>{var r=await this.internals.statePromise;await this.taskQueue.awaitIdle(),r.broadcastChannelMessages$.complete(),this.changes$.complete()})()),this.closed},t.remove=async function(){if(this.closed)throw new Error("instance is closed "+this.databaseName+"-"+this.collectionName);await this.taskQueue.awaitIdle(),await this.close(),await this.taskQueue.runCleanup((async r=>{var n=await this.internals.statePromise,o=[n.documentFileHandle,n.changelog.fileHandlePromise];for(var a of n.indexStates)o.push(await a.fileHandlePromise);await Promise.all(o.map((async i=>{var s=await i,u=await F(s,r);await u.truncate(0)}))),n.broadcastChannel&&(n.broadcastChannel.postMessage({type:"remove"}),await de(0))}))},e})();async function Va(e,t,r){var n=ma(t),o=new da(n,e.abstractLock,(s=>Wa(s,i))),a={taskQueue:o,statePromise:Oa(e.abstractFilesystem,t,o)},i=new su(e,t.databaseName,t.collectionName,t.schema,a,t.options,t.devMode,r,t.databaseInstanceToken);return o.setStorageInstance(i),a.statePromise.then((s=>{s.broadcastChannelMessages$.subscribe((async u=>{if(u.type==="event")u.changelogOperations.forEach((c=>{var f=c[0];s.indexStates[f].runChangelogOperation(c)})),u.eventBulks&&u.eventBulks.forEach((c=>i.changes$.next(c)));else{if(u.type!=="remove")throw new Error("BroadcastChannelMessageChanges$: unknown type "+u);s.indexStates.forEach((c=>{c.rows=[],c.metaIdMap&&c.metaIdMap.clear()}))}}))})).catch((()=>{})),i}var uu=(function(){function e(t,r,n,o,a={}){this.rxdbVersion=Pt,this.name=t,this.abstractFilesystem=r,this.abstractLock=n,this.inWorker=o,this.settings=a}return e.prototype.createStorageInstance=async function(t){sa(t),pa();var r=await Va(this,t,this.settings);if(!this.inWorker){["findDocumentsById","query","bulkWrite"].forEach((o=>{var a=r[o].bind(r);r[o]=async(i,s,u,c,f)=>{var p=await a(i,s,u,c,f);return typeof p=="string"&&(p=JSON.parse(p)),p}}));var n=r.changeStream.bind(r);r.changeStream=()=>n().pipe(Hr((o=>(typeof o=="string"&&(o=JSON.parse(o)),o))))}return r},e})();function Ja(e){return new uu(e.name,e.abstractFilesystem,e.abstractLock,!!e.inWorker&&e.inWorker,e.settings?e.settings:{})}var Ga=20,cu=200,Xa=(function(){function e(){this.opfsRootPromise=navigator.storage.getDirectory()}return e.prototype.getDirectory=async function(){var t=await this.opfsRootPromise;return new fu(t)},e})(),fu=(function(){function e(r){this.baseDir=r}var t=e.prototype;return t.getDirectoryHandle=async function(r,n){return new e(await this.baseDir.getDirectoryHandle(r,n))},t.getFileHandle=async function(r,n){var o=await this.baseDir.getFileHandle(r,n);return new lu(r,o)},t.removeEntry=async function(r){for(var n=0;n<Ga;n++)try{return void await this.baseDir.removeEntry(r)}catch(o){if(o?.name==="NotFoundError")return;if(o?.name==="NoModificationAllowedError"&&n<Ga-1){await new Promise((a=>setTimeout(a,cu)));continue}throw o}},e})(),lu=(function(){function e(t,r){this.name=t,this.fileHandle=r}return e.prototype.createAccessHandle=function(){return Promise.resolve(new pu(this))},e})(),pu=(function(){function e(r){this.fileHandle=r,this.syncAccessHandlePromise=mu(this.fileHandle)}var t=e.prototype;return t.getHandle=function(){var r=this.syncAccessHandle;return r||this.syncAccessHandlePromise.then((n=>(this.syncAccessHandle=n,n)))},t.getWritable=function(){return new du(this)},t.read=async function(r,n){var o=await this.getHandle();n||(n=await o.getSize());var a=n-r,i=new Uint8Array(a);return a===0||await o.read(i,{at:r}),i},t.truncate=async function(r){var n=await this.getHandle();await n.truncate(r)},t.getSize=async function(){return(await this.getHandle()).getSize()},t.close=async function(){var r=await this.getHandle();await r.close()},e})(),du=(function(){function e(r){this.accessHandle=r}var t=e.prototype;return t.write=async function(r,n){var o=await this.accessHandle.getHandle();await o.write(r,n)},t.flush=async function(){var r=await this.accessHandle.getHandle();await r.flush()},t.close=async function(){var r=await this.accessHandle.getHandle();await r.close()},e})();async function mu(e){if(typeof e.fileHandle.createSyncAccessHandle!="function")throw new Error('Could not access fileHandle.createSyncAccessHandle(). Likely this is because this storage only works "inside dedicated Web Workers"');return await e.fileHandle.createSyncAccessHandle()}var hu="opfs";function Ya(e={}){return Ja({name:hu,abstractFilesystem:new Xa,abstractLock:navigator.locks,inWorker:!e.usesRxDatabaseInWorker})}function Xe(e,t){return{connectionId:e.connectionId,answerTo:e.requestId,method:e.method,error:Bn(t)}}function pt(e,t){return{connectionId:e.connectionId,answerTo:e.requestId,method:e.method,return:t}}function Za(e){var t=new Map;e.messages$.pipe(bt(o=>o.method==="custom")).subscribe(async o=>{if(!e.customRequestHandler)e.send(Xe(o,new Error("Remote storage: cannot resolve custom request because settings.customRequestHandler is not set")));else try{var a=await e.customRequestHandler(o.params);e.send(pt(o,a))}catch(i){e.send(Xe(o,i))}});function r(o){if(e.storage)return e.storage.createStorageInstance(o);if(e.database){var a=Array.from(e.database.storageInstances),i=o.collectionName,s=a.find(c=>c.collectionName===i);if(!s)throw console.dir(a),new Error("storageInstance does not exist "+JSON.stringify({collectionName:i}));var u=o.schema;if(!gt(u,s.schema))throw new Error("Wrong schema "+JSON.stringify({schema:u,existingSchema:s.schema}));return Promise.resolve(s)}else throw new Error("no base given")}var n=e.fakeVersion?e.fakeVersion:Ze;return e.messages$.pipe(bt(o=>o.method==="create")).subscribe(async o=>{if(o.version!==n){e.send(Xe(o,z("RM1",{args:{mainVersion:o.version,remoteVersion:n}})));return}var a=o.connectionId;if(Array.isArray(o.params))return;var i=o.params,s=i.collectionName,u=[i.databaseName,i.collectionName,i.schema.version].join("|"),c=t.get(u);if(c){if(!gt(i.schema,c.params.schema)){e.send(Xe(o,new Error("Remote storage: schema not equal to existing storage")));return}}else try{c={storageInstancePromise:r(i),connectionIds:new Set,params:i},t.set(u,c),await c.storageInstancePromise}catch(g){e.send(Xe(o,g));return}c.connectionIds.add(o.connectionId);var f=[],p=await c.storageInstancePromise;f.push(p.changeStream().subscribe(g=>{var v={connectionId:a,answerTo:"changestream",method:"changeStream",return:g};try{e.send(v)}catch{}}));var l=!1;function m(){l||(l=!0,f.forEach(g=>g.unsubscribe()),B(c).connectionIds.delete(a),t.delete(u))}if(e.database){var h=e.database,d=h.collections[s];d?d.onClose.push(()=>m()):h.onClose.push(()=>m())}f.push(e.messages$.pipe(bt(g=>g.connectionId===a)).subscribe(async g=>{var v=g;if(!(v.method==="create"||v.method==="custom")&&Array.isArray(v.params)){var w;try{if(v.method==="close"&&e.database){e.send(pt(v,null));return}if(v.method==="close"&&B(c).connectionIds.size>1){e.send(pt(v,null)),B(c).connectionIds.delete(a),f.forEach(y=>y.unsubscribe());return}v.method==="getChangedDocumentsSince"&&!p.getChangedDocumentsSince?w=await ua(p,v.params[0],v.params[1]):w=await p[v.method](v.params[0],v.params[1],v.params[2],v.params[3]),(v.method==="close"||v.method==="remove")&&m(),e.send(pt(v,w))}catch(y){try{e.send(Xe(v,y))}catch{}}}})),e.send(pt(o,"ok"))}),{instanceByFullName:t}}function ei(e){var t,r=new ee;if(typeof self<"u"&&typeof self.onconnect=="object"){var n=new Map;self.onconnect=o=>{var a=o.ports[0];a.onmessage=i=>{var s=i.data;n.set(s.connectionId,a),r.next(s)}},t={storage:e.storage,messages$:r,send(o){vt(n,o.connectionId).postMessage(o)}}}else addEventListener("message",(o=>{var a=o.data;r.next(a)})),t={storage:e.storage,messages$:r,send(o){postMessage(o)}};Za(t)}function ti({channelName:e}){let t=new Set,r=0,n=new Map,o=e&&typeof BroadcastChannel<"u"?new BroadcastChannel(e):void 0;return o&&(o.unref?.(),o.onmessage=async({data:a})=>{if(a?.type==="ownership"&&Array.isArray(a.owned)&&a.owned.every(i=>typeof i=="string")){let i=[...t].filter(u=>!a.owned.includes(u));t=new Set(a.owned),r=Date.now();let s=i.flatMap(u=>[...n.get(u)??[]]);if(s.length){let u,c=!1;if(await Promise.race([(async()=>{for(let f=0;f<2&&!c;){let p=s.map(l=>l.taskQueue.queue);await Promise.allSettled(s.map(l=>l.taskQueue.awaitIdle())),await new Promise(l=>setTimeout(l,0)),f=s.every((l,m)=>l.taskQueue.queue===p[m])?f+1:0}})(),new Promise(f=>{u=setTimeout(()=>{c=!0,f()},2e3)})]),clearTimeout(u),c){o.postMessage({type:"ownership-drain-timeout",seq:a.seq});return}}o.postMessage({type:"ownership-ack",seq:a.seq})}},o.postMessage({type:"hello"})),{ownsRepairs:a=>!a.multiInstance||t.has(a.databaseName)&&Date.now()-r<3e3,onInstance(a,i){let s=n.get(i.databaseName)??new Set;s.add(a),n.set(i.databaseName,s);let u=a.close.bind(a);a.close=async(...c)=>{try{return await u(...c)}finally{s.delete(a),s.size||n.delete(i.databaseName)}}},close:()=>o?.close()}}function dt(e){return e?.name==="SyntaxError"}function Ye(e){return e.every(t=>t===0||t===32||t===9||t===10||t===13)}function gr(e){return typeof e=="string"&&JSON.parse(e),e}function mt(e){return typeof e=="string"?JSON.parse(e):e}function X(e,t){let r=globalThis.__wcposOnStorageRecovery;if(typeof r=="function")try{r({kind:e,...t});return}catch{}let{target:n,error:o,...a}=t;console.error(`[${e}] ${n??""}`.trimEnd(),o??a)}function Nt(e,t){let r=t.accessHandlers.get(e.documentFileHandle);return r||(r=e.documentFileHandle.createAccessHandle(),t.accessHandlers.set(e.documentFileHandle,r)),r}async function mn(e,t,r,n){let o=[r.indexId,n,"D",r.rows[n],"wcpos-exact"];r.runChangelogOperation(o),await e.changelog.addChangelogOperations(t,[o]),e.broadcastChannel?.postMessage({type:"event",eventBulks:[],changelogOperations:[o],info:{db:e.params.databaseName,col:e.params.collectionName}}),await new Promise(a=>setTimeout(a,0))}function yu(e,t,r){for(let n=e.indexOf("{");n>=0;n=e.indexOf("{",n+1)){let o=0,a=!1,i=!1;for(let s=n;s<e.length;s+=1){let u=e[s];if(a){i?i=!1:u==="\\"?i=!0:u==='"'&&(a=!1);continue}if(u==='"')a=!0;else if(u==="{")o+=1;else if(u==="}"&&--o===0){try{let c=JSON.parse(e.slice(n,s+1));if(c?.[t]===r)return c}catch{}break}}}}async function gu(e,t,{discardInvalid:r=!1,ownsRepairs:n=()=>!0,dropPastEof:o=!1}={}){let a=await e.internals.statePromise;return e.taskQueue.runCleanup(async i=>{if(!n())return"multi-instance";let s=a.firstIdx.metaIdMap.get(t);if(!s)return"missing-primary-row";let u=s[1],c=s[2],f=await Nt(a,i),p=await Ct(a,f),{bytes:l,pastEof:m}=await kt(f,u,c);if((m||p)&&!o)return"range-past-eof";if(m||p&&Ye(l))return await vr(a,i,t,{includePrimary:!0}),"hollow-row-dropped";if(Ye(l))return await oi(a,i,u,c),"hollow-row-dropped";let h=a.indexStates.map(y=>{let x=y.rows.findIndex(b=>b[1]===u&&b[2]===c);return{indexState:y,position:x}});if(h.some(({position:y})=>y<0))return"missing-index-row";let d=yu(e._decode(l),e.primaryPath,t);if(!d)return r?(await vr(a,i,t,{includePrimary:!0}),"discarded-no-valid-document"):"no-valid-document";try{if(h.some(({indexState:y,position:x})=>y.getIndexableString(d)!==y.rows[x][0]))return"index-mismatch"}catch{return"index-mismatch"}let g=e._encode(JSON.stringify(d)),v=new Uint8Array(c-u);if(g.byteLength>v.byteLength)return"recovered-document-too-large";v.fill(32),v.set(g);let w=await f.getWritable();return await w.write(v,{at:u}),await w.flush?.(),!0})}async function kt(e,t,r){if(r>await e.getSize())return{pastEof:!0};let n=await e.read(t,r),o=Ye(n)&&r>await e.getSize();return{bytes:n,pastEof:o}}function ri(e){let t=0;for(let r of e.indexStates)for(let n of r.rows)n[2]>t&&(t=n[2]);return t}async function Ct(e,t,r={}){let n=await t.getSize();return r.furthest===void 0&&(r.furthest=ri(e)),r.furthest<=n?!1:(r.furthest=ri(e),r.furthest>n)}async function ni(e){let t=await e.internals?.statePromise;return!t?.indexStates||!e.taskQueue?!1:e.taskQueue.runCleanup(async r=>Ct(t,await Nt(t,r)))}async function vu(e,t,r=()=>!0){let n=await e.internals.statePromise;return e.taskQueue.runCleanup(async o=>{let a=r()?void 0:"multi-instance",i=await Nt(n,o),s=(l,m)=>ie(m[0],l.primaryKeyLength),u=(l,m)=>(l===n.firstIdx&&X("hollow-row-refused",{target:t,reason:"range-past-eof",id:s(l,m)}),"range-past-eof"),c=[],f;for(let l of n.indexStates){let m=l.rows.length;for(;m--;){let h=l.rows[m],{bytes:d,pastEof:g}=await kt(i,h[1],h[2]);if(g){f=u(l,h);continue}Ye(d)&&c.push({indexState:l,position:m,row:h})}}if(f)return f;let p={};for(let{indexState:l,position:m,row:h}of c){let{bytes:d,pastEof:g}=await kt(i,h[1],h[2]);if(g||await Ct(n,i,p))return u(l,h);Ye(d)&&(a||await mn(n,o,l,m),l===n.firstIdx&&X(a?"hollow-row-refused":"hollow-row-dropped",{target:t,...a?{reason:a}:{},id:s(l,h)}))}return a})}async function wu(e,t,{discardForeign:r=!1,ownsRepairs:n=()=>!0,dropPastEof:o=!1}={}){let a=await e.internals.statePromise;return e.taskQueue.runCleanup(async i=>{if(!n())return new Map(t.map(l=>[l,"multi-instance"]));let s=new Map,u=await Nt(a,i),c={},f=await Ct(a,u,c);if(f&&!o){for(let l of t)s.set(l,a.firstIdx.metaIdMap.has(l)?"range-past-eof":!1);return s}let p=[];for(let l of t){let m=a.firstIdx.metaIdMap.get(l);if(!m){s.set(l,!1);continue}let[,h,d]=m,{bytes:g,pastEof:v}=await kt(u,h,d),w=!v&&!Ye(g);if(w&&!r){s.set(l,"range-holds-foreign-bytes");continue}p.push({documentId:l,start:h,end:d,foreign:w})}for(let{documentId:l,start:m,end:h,foreign:d}of p){let{bytes:g,pastEof:v}=await kt(u,m,h),w=f||v||await Ct(a,u,c);if(w&&!o){s.set(l,"range-past-eof");continue}if(!v&&!d&&!Ye(g)){s.set(l,"range-changed");continue}d||w?await vr(a,i,l,{includePrimary:!0}):await oi(a,i,m,h),s.set(l,d?"discarded-foreign-bytes":!0)}return s})}async function oi(e,t,r,n){for(let o of e.indexStates){let a=o.rows.length;for(;a--;){let i=o.rows[a];i[1]!==r||i[2]!==n||await mn(e,t,o,a)}}}async function vr(e,t,r,{includePrimary:n}){let o=e.firstIdx.primaryKeyLength;for(let a of e.indexStates){if(!n&&a===e.firstIdx)continue;let i=a.rows.length;for(;i--;)ie(a.rows[i][0],o)===r&&await mn(e,t,a,i)}}async function xu(e,t,r=()=>!0){let n=await e.internals.statePromise;return e.taskQueue.runCleanup(async o=>{if(!r())return"multi-instance";let a=n.firstIdx,i={...a,metaIdMap:new Map};await a.initRead.call(i,o);let s=await n.changelog.getChangelogOperations(o);for(let f of s.get(0)??[])a.runChangelogOperation.call(i,f);let u=[],c=[];for(let f of t){if(a.metaIdMap.has(f)||i.rows.some(p=>ie(p[0],a.primaryKeyLength)===f)){c.push(f);continue}await vr(n,o,f,{includePrimary:!1}),u.push(f)}return{dropped:u,reappeared:c}})}async function bu(e){let t=await e.internals.statePromise;return e.taskQueue.runCleanup(async r=>{let n=await Nt(t,r),o=t.indexStates.filter(d=>d!==t.firstIdx),a=t.firstIdx.primaryKeyLength,i=new Set,s="";for(let[d]of t.firstIdx.rows){if(d<s)return"unsorted-primary";s=d;let g=ie(d,a);if(i.has(g))return`duplicate-primary-id:${g.trim()}`;i.add(g)}let u=[];for(let d of o){let g=new Map,v=!1;for(let y of d.rows){let x=ie(y[0],a);if(!i.has(x))return`id-set-mismatch:${x.trim()}`;let b=g.get(x)??[];b.length>0&&(v=!0),b.push(y),g.set(x,b)}let w=!v&&g.size===i.size;u.push({indexState:d,rowsById:g,healthy:w})}if(!u.some(({healthy:d})=>d))return"no-healthy-secondary";let c=[],f=new Set;for(let[d,g,v]of t.firstIdx.rows){let w=ie(d,a),y;try{y=JSON.parse(e._decode(await n.read(g,v)))}catch{return`primary-row-mismatch:${w.trim()}`}if(y?.[e.primaryPath]!==w||t.firstIdx.getIndexableString(y)!==d)return`primary-row-mismatch:${w.trim()}`;if(f.has(g))return`duplicate-primary-range:${w.trim()}`;let x=1,b=new Map;for(let{indexState:S,rowsById:T,healthy:A}of u)for(let C of T.get(w)??[])if(C[1]===g&&C[2]===v){if(!A)continue;try{S.getIndexableString(y)===C[0]&&(x+=1)}catch{}}else{let k=`${C[1]}-${C[2]}`,H=b.get(k)??{range:[C[1],C[2]],voters:[],voterIndexes:new Set};H.voterIndexes.has(S)||(H.voterIndexes.add(S),H.voters.push([S,C[0]])),b.set(k,H)}for(let{range:S,voters:T}of b.values()){if(T.length<x)continue;let A;try{A=JSON.parse(e._decode(await n.read(S[0],S[1])))}catch{continue}if(A?.[e.primaryPath]!==w)continue;let C=0;for(let[k,H]of T)try{k.getIndexableString(A)===H&&(C+=1)}catch{}if(C>=x)return`uncorroborated-primary-range:${w.trim()}`}f.add(g),c.push({document:y,start:g,end:v})}let p=new Map,l=[...c].sort((d,g)=>d.start-g.start);for(let d=1;d<l.length;d+=1)if(l[d].start<l[d-1].end)return"overlapping-ranges";let m=[];for(let d of t.indexStates){if(d===t.firstIdx)continue;let g=c.map(({document:v,start:w,end:y})=>[d.getIndexableString(v),w,y]).sort((v,w)=>v[0]<w[0]?-1:1);JSON.stringify(g)!==JSON.stringify(d.rows)&&m.push([d,g])}if(m.length===0)return"no-divergence";for(let[d,g]of m)p.set(d,d.rows),d.rows=g;let h=[];try{for(let d of t.indexStates)await d.persistInMemoryRows(r),p.has(d)&&h.push(d);await t.changelog.empty(r)}catch(d){for(let[v,w]of p)v.rows=w;let g=[];for(let v=h.length-1;v>=0;v-=1)try{await h[v].persistInMemoryRows(r)}catch(w){g.push(w)}throw g.length>0?new AggregateError([d,...g],`index persistence failed: ${d?.message??d}; rollback incomplete: ${g.map(v=>v?.message??v).join("; ")}`):d}return!0})}function ai(e,t={}){let r=typeof t.ownsRepairs=="function"?t.ownsRepairs:o=>!o.multiInstance,n=e.createStorageInstance.bind(e);return{...e,async createStorageInstance(o){let a=()=>!!r(o),i=await n(o);t.onInstance?.(i,o);let s=i.findDocumentsById.bind(i),u=i.bulkWrite.bind(i),c=i.query.bind(i),f=i.count?.bind(i),p=i.getChangedDocumentsSince.bind(i),l=i.cleanup?.bind(i),m=new Set,h=`${o.databaseName}/${o.collectionName}`,d=async(_,E,O)=>{let R=(await i.internals?.statePromise)?.firstIdx?.metaIdMap;if(!R)return[];let I=new Set;for(let P of E)P&&I.add(P[i.primaryPath]);return _.filter(P=>{if(I.has(P))return!1;let W=R.get(P);return!!W&&(O||W[0][0]==="0")})},g=async(_,{dropPastEof:E=!1}={})=>{let O=[];if(_.length===0)return O;if(!a()){for(let I of _)O.push({id:I,reason:"multi-instance"}),X("hollow-row-refused",{target:h,id:I,reason:"multi-instance"});return O}let R=await wu(i,_,{discardForeign:o.collectionName==="logs",ownsRepairs:a,dropPastEof:E});for(let[I,P]of R)P==="discarded-foreign-bytes"?X("log-row-discarded",{target:h,id:I,reason:"range-holds-foreign-bytes"}):typeof P=="string"?(O.push({id:I,reason:P}),X("hollow-row-refused",{target:h,id:I,reason:P})):P&&X("hollow-row-dropped",{target:h,id:I});return O},v=_=>{let E=_.filter(({reason:O})=>O==="range-past-eof");if(E.length!==0)throw new Error(`targeted recovery refused: range-past-eof for ${E.map(({id:O})=>O).join(", ")} (${h})`)},w=(_,E)=>X("document-repair-refused",{target:h,reason:E,..._.length===1?{id:_[0]}:{batchSize:_.length}}),y=async(_,E,{dropPastEof:O=!1}={})=>{let R=async I=>{let P;try{P=mt(await s(I,!0))}catch(L){if(!dt(L))throw L;if(!a())throw w(I,"multi-instance"),L.message+="; targeted recovery refused: multi-instance",L;if(E?.(),!O&&await ni(i))throw w(I,"range-past-eof"),L.message+="; targeted recovery refused: range-past-eof",L;if(I.length===1){let se=await gu(i,I[0],{discardInvalid:o.collectionName==="logs",ownsRepairs:a,dropPastEof:O});if(se==="hollow-row-dropped")return X("hollow-row-dropped",{target:h,id:I[0]}),!0;if(se==="discarded-no-valid-document")return X("log-row-discarded",{target:h,id:I[0],reason:"no-valid-document"}),!0;if(se==="multi-instance")throw w(I,se),L.message+="; targeted recovery refused: multi-instance",L;if(typeof se=="string")throw w(I,se),L.message+=`; targeted recovery failed for ${I[0]}: ${se}`,L;return!0}let D=Math.ceil(I.length/2),M=await R(I.slice(0,D)),K=await R(I.slice(D));return M||K}let W=await d(I,P,!0);if(W.length===0)return!1;let J=await g(W,{dropPastEof:O});return v(J),E?.(),J.length!==W.length};return R([...new Set(_)])},x=async(_,E)=>mt(await s([_],E)).find(R=>R?.[i.primaryPath]===_),b=async(_,E,O,R)=>{let I=mt(E),P=new Set(_),W=new Set,J=!1,L=I.filter(M=>{let K=M?.[i.primaryPath];return P.has(K)?W.has(K)?(J=!0,!1):(W.add(K),!0):!1});if(!R&&!J)return L.length===I.length?E:typeof E=="string"?JSON.stringify(L):L;let D=[];for(let M of L){let K=await x(M[i.primaryPath],O);K&&D.push(K)}return typeof E=="string"?JSON.stringify(D):D};i.findDocumentsById=async(_,E)=>{try{let O=await s(_,E),R=mt(O),I=await d(_,R,E),P=await g(I);v(P);let W=P.some(({reason:D})=>D==="range-holds-foreign-bytes"),J=await b(_,O,E,W),L=new Set;for(let D of mt(J))L.add(D[i.primaryPath]);if(E){let D=new Set(P.map(({id:K})=>K)),M=(await i.internals?.statePromise)?.firstIdx?.metaIdMap;for(let K of _)D.has(K)||(L.has(K)||!M?.has(K))&&m.add(K)}else for(let D of L)m.add(D);return J}catch(O){if(!dt(O))throw O;if(m.clear(),await y(_))return b(_,await s(_,E),E,!0);if(_.length>1){let R=await Promise.all(_.map(W=>s([W],E))),I=new Set,P=[];return _.forEach((W,J)=>{if(I.has(W))return;I.add(W);let L=mt(R[J]).find(D=>D?.[i.primaryPath]===W);L&&P.push(L)}),typeof R[0]=="string"?JSON.stringify(P):P}throw O}};let S=async _=>{if(!_.some(M=>M.previous))return _;let E=await i.internals?.statePromise,O=E?.firstIdx?.metaIdMap;if(!O)return _;let R=M=>!!M.previous&&!O.has(M.document[i.primaryPath]),I=_.filter(R).map(M=>M.document[i.primaryPath]);I.length>0&&await s([...new Set(I)],!0);let P=[],W=_.map(M=>R(M)?(P.push(M.document[i.primaryPath]),{document:M.document}):M);if(P.length===0)return W;let J=E.firstIdx.primaryKeyLength,L=P.filter(M=>E.indexStates.some(K=>K!==E.firstIdx&&K.rows.some(se=>ie(se[0],J)===M)));if(L.length===0)return W;let D=a()?await xu(i,L,a):"multi-instance";if(D==="multi-instance"){for(let M of L)X("stale-secondary-refused",{target:h,id:M,reason:"multi-instance"});throw new Error(`stale secondary index rows for ${L.join(", ")} in ${h}; targeted recovery refused: multi-instance`)}for(let M of D.dropped)X("stale-secondary-dropped",{target:h,id:M});for(let M of D.reappeared)X("stale-secondary-refused",{target:h,id:M,reason:"reappeared"});return W.map((M,K)=>D.reappeared.includes(M.document[i.primaryPath])?_[K]:M)},T=async(_,E,O,R)=>{let I=[];for(let P=0;P<E.length;P+=1)I.push(R?await A([_[P]],[E[P]],O):await u([E[P]],O));return await i.taskQueue?.awaitIdle?.(),{error:I.flatMap(P=>P.error)}},A=async(_,E,O)=>{try{return await u(E,O)}catch(R){if(m.clear(),!dt(R))throw R;await y(_.map(P=>P.document[i.primaryPath]),void 0,{dropPastEof:!0});let I=await S(_);try{return await T(_,I,O,!1)}catch(P){throw m.clear(),X("write-retry-failed",{target:h,error:P}),P}}};i.bulkWrite=async(_,E)=>{let O=_.map(P=>P.document[i.primaryPath]),R=!1;if(O.some(P=>!m.has(P))&&(await y(O,()=>{R=!0,m.clear()},{dropPastEof:!0}),!R))for(let P of O)m.add(P);let I=await S(_);return R&&I.length>1?T(_,I,E,!0):A(_,I,E)};let C=0,k,H=()=>(k||(k=bu(i).then(_=>(_===!0&&(C+=1),_)).finally(()=>{k=void 0})),k),V=async(_,E)=>{m.clear();let O=await i.internals.statePromise,R=await y(O.firstIdx.metaIdMap.keys());if(await ni(i))return _.message+="; index reconciliation refused: range-past-eof",X("index-reconcile-refused",{target:h,reason:"range-past-eof"}),!1;let I="multi-instance";if(!o.multiInstance)try{let P=await H();if(P===!0)return!0;I=P}catch(P){I=`error ${P?.message??P}`}return R||C!==E?!0:(_.message+=`; index reconciliation refused: ${I}`,X("index-reconcile-refused",{target:h,reason:I}),!1)};if(i.query=async _=>{let E=C;try{return gr(await c(_))}catch(O){if(!dt(O)||!await V(O,E))throw O;return gr(await c(_))}},f&&(i.count=async _=>{let E=await f(_);if(E&&typeof E=="object"&&typeof E.count=="number")return E;X("count-recovery",{target:h,detail:`typeof=${typeof E} result=${JSON.stringify(E)?.slice(0,200)}`});let O=await i.query(_);return{count:(typeof O=="string"?JSON.parse(O):O).documents.length,mode:"fast"}}),i.getChangedDocumentsSince=async(_,E)=>{let O=C;try{return gr(await p(_,E))}catch(R){if(!dt(R)||!await V(R,O))throw R;return gr(await p(_,E))}},!l)return i;let re=async _=>{if(!dt(_))return!1;m.clear();let E=await i.internals.statePromise;return y(E.firstIdx.metaIdMap.keys())};return i.cleanup=async _=>{try{return await l(_)}catch(E){let O;try{if(await vu(i,h,a)==="range-past-eof")throw new Error(`targeted recovery refused: range-past-eof (${h}); index rows are stale relative to documents.json`);return await l(_)}catch(R){O=R}try{if(await re(O))return await l(_)}catch(R){O=R}throw X("cleanup-recovery",{target:h,error:O,initialError:String(E)}),O}},i}}}var ii=ti({channelName:typeof self<"u"?self.name:""});ei({storage:ai(Ya(),{ownsRepairs:ii.ownsRepairs,onInstance:ii.onInstance})});})(); | |