UNPKG

mingo

Version:

MongoDB query language for in-memory objects

1 lines 96 kB
var mingo=(()=>{var Or=Object.defineProperty;var Uo=Object.getOwnPropertyDescriptor;var Fo=Object.getOwnPropertyNames;var Bo=Object.prototype.hasOwnProperty;var ht=(e,t)=>{for(var r in t)Or(e,r,{get:t[r],enumerable:!0})},Lo=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Fo(t))!Bo.call(e,o)&&o!==r&&Or(e,o,{get:()=>t[o],enumerable:!(n=Uo(t,o))||n.enumerable});return e};var zo=e=>Lo(Or({},"__esModule",{value:!0}),e);var mp={};ht(mp,{Aggregator:()=>ve,Context:()=>Ot,ProcessingMode:()=>wt,Query:()=>Te,aggregate:()=>ko,default:()=>up,find:()=>Co,update:()=>_o,updateMany:()=>Mo,updateOne:()=>Do});function G(e,t){return e*16777619^t>>>0}function On(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=G(n,o|0)}return n>>>0}function Ft(e){let t=0;for(let r=0;r<e.length;r++)t=G(t,e.charCodeAt(r));return t>>>0}function Wo(e){let t=0,r=e<0n,n=r?-e:e;if(n===0n)t=G(t,0);else for(;n>0n;){let o=Number(n&0xffn);t=G(t,o),n>>=8n}return G(t,+r)>>>0}function qo(e){let t=Ft((e.name||"")+e.toString());return t=G(t,e.length),t>>>0}function Yo(e){let t=0;for(let r=0;r<e.length;r++)t=G(t,e[r]);return t>>>0}function Vo(e){let t=Ft(e.constructor.name),r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return t=G(t,Yo(r)),t>>>0}function Ko(e,t){if(t.has(e))return 13;t.add(e);let r=1;for(let n=0;n<e.length;n++)r=G(r,Ar(e[n],t));return t.delete(e),r>>>0}function Qo(e,t){if(t.has(e))return 13;t.add(e);let r=Object.keys(e).sort(),n=Ft(e?.constructor?.name);for(let o of r)n=G(n,Ft(o)),n=G(n,Ar(e[o],t));return t.delete(e),n>>>0}var Ho=[3735928559,305441741].map(e=>G(3,e)),Go=G(1,0),Xo=G(2,0);function Ar(e,t){if(e===null)return Go;switch(typeof e){case"undefined":return Xo;case"boolean":return Ho[+e];case"number":return G(4,On(e));case"string":return G(5,Ft(e));case"bigint":return G(6,Wo(e));case"function":return G(7,qo(e));default:{if(ArrayBuffer.isView(e)&&!(e instanceof DataView))return G(12,Vo(e));if(e instanceof Date)return G(10,On(e.getTime()));if(e instanceof RegExp){let n=Ft(e.source);return G(11,G(n,Ft(e.flags)))}return Array.isArray(e)?G(8,Ko(e,t)):G(9,Qo(e,t))}}}function ft(e){return Ar(e,new WeakSet)>>>0}var kt=class extends Error{},ee=Symbol("missing"),Jo="mingo: cycle detected while processing object/array",It=e=>typeof e!="object"&&typeof e!="function"||e===null,bn=e=>It(e)||R(e)||ot(e),An={undefined:1,null:2,number:3,string:4,symbol:5,object:6,array:7,arraybuffer:8,boolean:9,date:10,regexp:11,function:12},At=(e,t)=>e<t?-1:e>t?1:0,Zo=(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 i=0;i<o;i++){let s=At(r[i],n[i]);if(s!==0)return s}return At(r.length,n.length)};function jt(e,t,r=!1){if(e===ee&&(e=void 0),t===ee&&(t=void 0),e===t||Object.is(e,t))return 0;let n=at(e),o=at(t),i=0;if(n===o)switch(n){case"number":case"string":case"boolean":return At(e,t);case"date":return At(+e,+t);case"regexp":return(i=At(e.source,t.source))?i:At(e.flags,t.flags);case"arraybuffer":return Zo(e,t);case"array":{let c=e.slice().sort(jt),p=t.slice().sort(jt),m=Math.min(c.length,p.length);for(let O=0;O<m;O++)if(i=jt(c[O],p[O]))return i;return At(c.length,p.length)}default:{if(n!=="object"&&e?.constructor===t?.constructor&&dn(e))return At(e.toString(),t.toString());let c=Object.keys(e).sort(),p=Object.keys(t).sort();if(i=jt(c,p))return i;for(let m of c)if(i=jt(e[m],t[m]))return i;return 0}}if(n=="undefined")return-1;if(o=="undefined")return 1;if(r){if(n=="array"){let c=e;if(!c.length)return-1;let p=c.slice().sort(jt);i=1;for(let m of p)if((i=Math.min(i,jt(m,t)))<0)return i;return i}if(o=="array"){let c=t;if(!c.length)return 1;let p=c.slice().sort(jt);i=-1;for(let m of p)if((i=Math.max(i,jt(e,m)))>0)return i;return i}}let s=An[n]??Number.MAX_VALUE,a=An[o]??Number.MAX_VALUE;return s!==a?At(s,a):At(n,o)}var M=(e,t)=>jt(e,t,!0),dn=e=>e!=null&&e.toString!==Object.prototype.toString;function Q(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(R(e))return R(t)&&+e==+t;if(ot(e))return ot(t)&&e.source===t.source&&e.flags===t.flags;if(l(e)&&l(t))return e.length===t.length&&e.every((s,a)=>Q(s,t[a]));if(e?.constructor!==Object&&dn(e))return e?.toString()===t?.toString();let r=e,n=t,o=Object.keys(r),i=Object.keys(n);return o.length!==i.length?!1:o.every(s=>T(n,s)&&Q(r[s],n[s]))}var et=class e extends Map{#t=new Map;#e=t=>{let r=ft(t);return[(this.#t.get(r)??[]).find(o=>Q(o,t)),r]};constructor(){super()}static init(){return new e}clear(){super.clear(),this.#t.clear()}delete(t){if(It(t))return super.delete(t);let[r,n]=this.#e(t);return super.delete(r)?(this.#t.set(n,this.#t.get(n).filter(o=>!Q(o,r))),!0):!1}get(t){if(It(t))return super.get(t);let[r,n]=this.#e(t);return super.get(r)}has(t){if(It(t))return super.has(t);let[r,n]=this.#e(t);return super.has(r)}set(t,r){if(It(t))return super.set(t,r);let[n,o]=this.#e(t);if(super.has(n))super.set(n,r);else{super.set(t,r);let i=this.#t.get(o)||[];i.push(t),this.#t.set(o,i)}return this}get size(){return super.size}};function u(e,t){if(!e)throw new kt(t)}var fe=e=>{if(e==="__proto__"||e.startsWith("__proto__.")||e.endsWith(".__proto__")||e.includes(".__proto__."))throw new kt(`Accessing __proto__ is not allowed in selector: '${e}'.`)};function at(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":l(e)?"array":R(e)?"date":ot(e)?"regexp":gn(e)?"arraybuffer":e?.constructor===Object?"object":e?.constructor?.name?.toLowerCase()??"object"}var Bt=e=>typeof e=="boolean",$=e=>typeof e=="string";var x=e=>!Number.isNaN(e)&&typeof e=="number",w=Number.isInteger,l=Array.isArray,h=e=>at(e)==="object";var R=e=>e instanceof Date,ot=e=>e instanceof RegExp,br=e=>typeof e=="function",y=e=>e==null,nt=(e,t=!0)=>!!e||t&&e==="",le=e=>y(e)||$(e)&&!e||l(e)&&e.length===0||h(e)&&Object.keys(e).length===0,ct=e=>l(e)?e:[e],T=(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))),gn=e=>typeof ArrayBuffer<"u"&&ArrayBuffer.isView(e),we=e=>{for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<48||e.charCodeAt(t)>57)return!1;return!0},it=(e,t)=>{if(It(e))return e;if(R(e))return new Date(e);if(ot(e))return new RegExp(e);if(gn(e)){let r=e.constructor;return new r(e)}if(t instanceof WeakSet||(t=new WeakSet),t.has(e))throw new Error(Jo);t.add(e);try{if(l(e)){let r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=it(e[n],t);return r}if(h(e)){let r={};for(let n of Object.keys(e))r[n]=it(e[n],t);return r}}finally{t.delete(e)}return e};function Lt(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=[et.init(),et.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 i=e[n][o];t[r].has(i)&&t[r^1].set(i,!0)}if(t[r^1].size===0)return[];t[r].clear(),r=r^1}return Array.from(t[r].keys())}function pt(e,t=1){let r=new Array;function n(o,i){for(let s=0,a=o.length;s<a;s++)l(o[s])&&(i>0||i<0)?n(o[s],Math.max(-1,i-1)):r.push(o[s])}return n(e,t),r}function $t(e){let t=et.init();for(let r of e)t.set(r,!0);return Array.from(t.keys())}function zt(e,t){if(e.length<1)return new Map;let r=et.init();for(let n=0;n<e.length;n++){let o=e[n],i=t(o,n)??null,s=r.get(i);s?s.push(o):(s=[o],r.set(i,s))}return r}var ti=new Set(Object.getOwnPropertyNames(Object.prototype).find(e=>e!=="__proto__"));function Ne(e,t){if(!(It(e)||Number.isNaN(t)))return l(e)?e[Number(t)]:!ti.has(t)||T(e,t)?e[t]:void 0}function ei(e,t){if(t<1)return e;for(;t--&&e.length===1&&l(e[0]);)e=e[0];return e}function D(e,t,r){if(fe(t),bn(e))return e;if(!t.includes(".")&&!l(e))return Ne(e,t);let n=0;function o(s,a){let c=s,p=0,m=0;for(;m!==-1;){m=a.indexOf(".",p);let O=m===-1?a.substring(p):a.substring(p,m);if(!we(O)&&l(c)){if(p===0&&n>0)break;n+=1;let b=a.substring(p);c=c.reduce((d,g)=>{let E=o(g,b);return E!==void 0&&d.push(E),d},[]);break}else c=Ne(c,O);if(c===void 0)break;p+=O.length+1}return c}let i=o(e,t);return l(i)&&r?.unwrapArray?ei(i,n):i}function Tt(e,t,r){r?.ignoreProto!==!0&&(fe(t),r={...r,ignoreProto:!0});let n=t.indexOf("."),o=n==-1?t:t.substring(0,n),i=t.substring(n+1),s=n!=-1,{preserveIndex:a}=r;if(l(e)){let m=we(o),O=m&&a==="default"?e.slice():[];if(m){let A=Number(o),b=Ne(e,o);s&&(b=Tt(b,i,r)),a==="default"?O[A]=b:O.push(b)}else for(let A=0;A<e.length;A++){let b=Tt(e[A],t,r);a==="missing"?O.push(b??ee):(b!==void 0||a==="default")&&O.push(b)}return O}let c=r?.preserveKeys?{...e}:{},p=Ne(e,o);if(s&&(p=Tt(p,i,r)),p!==void 0)return c[o]=p,c}function Se(e){if(l(e))for(let t=e.length-1;t>=0;t--)e[t]===ee?e.splice(t,1):Se(e[t]);else if(h(e)){let t=Object.keys(e);for(let r=0;r<t.length;r++)Se(e[t[r]])}}function re(e,t,r,n){n?.ignoreProto!==!0&&(fe(t),n={...n,ignoreProto:!0});let o=t.indexOf("."),i=o===-1?t:t.substring(0,o),s=t.substring(i.length+1);if(s.length===0)(h(e)||l(e)&&we(i))&&r(e,i);else{n?.buildGraph&&y(e[i])&&(e[i]={});let a=e[i];if(!a)return;let c=s.indexOf("."),p=c===-1?s:s.substring(0,c),m=we(p);if(l(a)&&n?.descendArray&&!m)for(let O=0;O<a.length;O++)re(a[O],s,r,n);else re(a,s,r,n)}}function yt(e,t,r){re(e,t,(n,o)=>n[o]=r,{buildGraph:!0})}function Wt(e,t,r){re(e,t,((n,o)=>{l(n)?n.splice(Number(o),1):delete n[o]}),r)}var ut=e=>!!e&&e[0]==="$"&&/^\$[a-zA-Z0-9_]+$/.test(e);function qt(e){if(bn(e))return ot(e)?{$regex:e}:{$eq:e};if(!Object.keys(e).some(ut))return{$eq:e};if(h(e)&&T(e,"$regex")){let t={...e};return t.$regex=new RegExp(e.$regex,e.$options),delete t.$options,t}return e}function Yt(e,t,r=M){let n=0,o=e.length-1;for(;n<=o;){let i=Math.round(n+(o-n)/2);if(r(t,e[i])<0)o=i-1;else if(r(t,e[i])>0)n=i+1;else return i}return n}var vt=class{root;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 wt=(o=>(o[o.CLONE_OFF=0]="CLONE_OFF",o[o.CLONE_INPUT=1]="CLONE_INPUT",o[o.CLONE_OUTPUT=2]="CLONE_OUTPUT",o[o.CLONE_ALL=3]="CLONE_ALL",o))(wt||{}),C=class e{constructor(t,r){this.options=t;this.#t=r?{...r}:{}}options;#t;static init(t){return t instanceof e?new e(t.options,t.#t):new e({idKey:"_id",scriptEnabled:!0,useStrictMode:!0,failOnError:!0,processingMode:0,...t,context:t?.context?Ot.from(t?.context):Ot.init()})}update(t){return Object.assign(this.#t,t,{timestamp:this.#t.timestamp,variables:{...this.#t?.variables,...t?.variables}}),this}get local(){return this.#t}get now(){let t=this.#t.timestamp??0;return t||(t=Date.now(),Object.assign(this.#t,{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}},Vt=(s=>(s.ACCUMULATOR="accumulator",s.EXPRESSION="expression",s.PIPELINE="pipeline",s.PROJECTION="projection",s.QUERY="query",s.WINDOW="window",s))(Vt||{}),Ot=class e{#t;constructor(){this.#t={accumulator:{},expression:{},pipeline:{},projection:{},query:{},window:{}}}static init(t={}){let r=new e;for(let n of Object.keys(t))r.#t[n]={...t[n]};return r}static from(...t){if(t.length===1)return e.init(t[0].#t);let r=new e;for(let n of t)for(let o of Object.values(Vt))r.addOps(o,n.#t[o]);return r}addOps(t,r){return this.#t[t]=Object.assign({},r,this.#t[t]),this}getOperator(t,r){return this.#t[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 f(e,t,r){let n=!(r instanceof C)||y(r.local.root)?C.init(r).update({root:e}):r;return Ce(e,t,n)}var ri=new Set(["$$ROOT","$$CURRENT","$$REMOVE","$$NOW"]);function Ce(e,t,r){if($(t)&&t.length>0&&t[0]==="$"){if(t==="$$KEEP"||t==="$$PRUNE"||t==="$$DESCEND")return t;let n=r.local.root,o=t.indexOf("."),i=o===-1?t:t.substring(0,o);if(ri.has(i)){switch(i){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(i.length>=2&&i[1]==="$"){n=Object.assign({},r.variables,{this:e},r?.local?.variables);let s=i.substring(2);u(T(n,s),`Use of undefined variable: ${s}`),t=t.substring(2)}else t=t.substring(1);return t===""?n:D(n,t)}if(l(t)){let n=new Array(t.length);for(let o=0;o<t.length;o++)n[o]=Ce(e,t[o],r);return n}if(h(t)){let n=Object.keys(t);if(ut(n[0]))return u(n.length===1,"Expression must contain a single operator."),ni(e,t[n[0]],n[0],r);let o={};for(let i=0;i<n.length;i++)o[n[i]]=Ce(e,t[n[i]],r);return o}return t}function ni(e,t,r,n){let o=n.context,i=o.getOperator("expression",r);if(i)return i(e,t,n);let s=o.getOperator("accumulator",r);return u(!!s,`accumulator '${r}' is not registered.`),l(e)||(e=Ce(e,t,n),t=null),u(l(e),`arguments must resolve to array for ${r}.`),s(e,t,n)}function S(e){return new ye(e)}function Nt(...e){let t=0;return S(()=>{for(;t<e.length;){let r=e[t].next();if(!r.done)return r;t++}return{done:!0,value:void 0}})}function oi(e){return!!e&&typeof e=="object"&&typeof e?.next=="function"}function ii(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e[Symbol.iterator]=="function"}var ye=class{#t=[];#e=[];#r;#o=!1;constructor(t){let r;ii(t)?r=t[Symbol.iterator]():oi(t)?r=t:typeof t=="function"?r={next:t}:u(0,"mingo: iterator requires an iterable, generator or function");let n=-1;this.#r=()=>{for(;;){let{value:o,done:i}=r.next();if(i)return{done:i};let s=!0;n++;for(let a=0;a<this.#t.length;a++){let{op:c,fn:p}=this.#t[a],m=p(o,n);if(c==="map")o=m;else if(!m){s=!1;break}}if(s)return{value:o,done:i}}}}push(t,r){return this.#t.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 u(t>=0,"value must be a non-negative integer"),this.filter(r=>t-- >0)}drop(t){return u(t>=0,"value must be a non-negative integer"),this.filter(r=>t--<=0)}transform(t){let r=this,n;return S(()=>(n||(n=t(r.collect())),n.next()))}collect(){for(;!this.#o;){let{done:t,value:r}=this.#r();t||this.#e.push(r),this.#o=t}return this.#e}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}};var bt=class{#t;#e;constructor(t,r){this.#t=t,this.#e=C.init(r)}stream(t,r){let n=S(t),o=r??this.#e,i=o.processingMode;return i&1&&n.map(s=>it(s)),n=this.#t.map((s,a)=>{let c=Object.keys(s);u(c.length===1,`aggregation stage must have single operator, got ${c.toString()}.`);let p=c[0];u(p!=="$documents"||a==0,"$documents must be first stage in pipeline.");let m=o.context.getOperator("pipeline",p);return u(!!m,`unregistered pipeline operator ${p}.`),[m,s[p]]}).reduce((s,[a,c])=>a(s,c,o),n),i&2&&n.map(s=>it(s)),n}run(t,r){return this.stream(t,r).collect()}};var Er={};ht(Er,{$accumulator:()=>si,$addToSet:()=>ai,$avg:()=>ci,$bottom:()=>mi,$bottomN:()=>dr,$count:()=>fi,$covariancePop:()=>li,$covarianceSamp:()=>yi,$first:()=>gr,$firstN:()=>De,$last:()=>xr,$lastN:()=>Re,$max:()=>Oi,$maxN:()=>Pe,$median:()=>hr,$mergeObjects:()=>jr,$min:()=>Ai,$minN:()=>Ue,$percentile:()=>Oe,$push:()=>N,$stdDevPop:()=>bi,$stdDevSamp:()=>di,$sum:()=>gi,$top:()=>xi,$topN:()=>$r});var N=(e,t,r)=>{if(y(t))return e;let n=C.init(r),o=new Array(e.length);for(let i=0;i<e.length;i++){let s=e[i];o[i]=f(s,t,n.update({root:s}))??null}return o};var si=(e,t,r)=>{u(r.scriptEnabled,"$accumulator requires 'scriptEnabled' option to be true");let n=C.init(r),o=t,i=f(n?.local?.groupId,o.initArgs||[],n.update({root:n?.local?.groupId})),s=N(e,o.accumulateArgs,n);for(let m=0;m<s.length;m++)for(let O=0;O<s[m].length;O++)s[m][O]=s[m][O]??null;let a=o.init.apply(null,i),c=o.accumulate,p=a;for(let m=0;m<s.length;m++)p=c.apply(null,[p,...s[m]]);return o.finalize&&(p=o.finalize.call(null,p)),p};var ai=(e,t,r)=>$t(N(e,t,r));var ci=(e,t,r)=>{let n=N(e,t,r).filter(x);if(n.length===0)return null;let o=0;for(let i=0;i<n.length;i++)o+=n[i];return o/n.length};function st(e,t,r){u(h(t)&&Object.keys(t).length>0,"$sort specification is invalid");let n=M,o=r.collation;return h(o)&&$(o.locale)&&(n=ui(o)),e.transform(i=>{let s=Object.keys(t);for(let a of s.reverse()){let c=zt(i,A=>D(A,a)),p=Array.from(c.keys()),m=!1;if(n===M){let A=!0,b=!0;for(let d of p)if(A&&=$(d),b&&=x(d),!A&&!b)break;if(m=A||b,A)p.sort();else if(b){let d=new Float64Array(p).sort();for(let g=0;g<d.length;g++)p[g]=d[g]}}m||p.sort(n),t[a]===-1&&p.reverse();let O=0;for(let A of p)for(let b of c.get(A))i[O++]=b;u(O==i.length,"bug: counter must match collection size.")}return S(i)})}var pi={1:"base",2:"accent",3:"variant"};function ui(e){let t={sensitivity:pi[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)=>$(n)&&$(o)?r.compare(n,o):M(n,o)}var dr=(e,t,r)=>{let n=r,o=t,i=f(n?.local?.groupId,o.n,n),s=st(S(e),o.sortBy,r).collect(),a=s.length;return N(a<=i?s:s.slice(a-i),o.output,n)};var mi=(e,t,r)=>dr(e,{...t,n:1},r);var fi=(e,t,r)=>e.length;function ke(e,t=!0){let r=0;for(let i=0;i<e.length;i++)r+=e[i];let n=r/e.length,o=0;for(let i=0;i<e.length;i++){let s=e[i]-n;o+=s*s}return Math.sqrt(o/(e.length-Number(t)))}function _e(e,t=!0){if(e.length<2)return t?null:0;let r=0,n=0;for(let i=0;i<e.length;i++){let[s,a]=e[i];r+=s,n+=a}r/=e.length,n/=e.length;let o=0;for(let i=0;i<e.length;i++){let[s,a]=e[i];o+=(s-r)*(a-n)}return o/(e.length-Number(t))}var li=(e,t,r)=>_e(N(e,t,r),!1);var yi=(e,t,r)=>_e(N(e,t,r),!0);var gr=(e,t,r)=>{let n=e[0],o=C.init(r).update({root:n});return f(n,t,o)??null};var xn={int:{type:"integers"},obj:{type:"objects"}};function L(e,t){return u(!e,t),null}function Me(e,t){let r=`${t} expression must resolve to object`;return u(!e,r),null}function J(e,t){let r=`${t} expression must resolve to string`;return u(!e,r),null}function H(e,t,r){let n=r?.integer?"integer":"number",o=r?.min??-1/0,i=r?.max??1/0,s;return o===0&&i===0?s=`${t} expression must resolve to non-zero ${n}`:o===0&&i===1/0?s=`${t} expression must resolve to non-negative ${n}`:o!==-1/0&&i!==1/0?s=`${t} expression must resolve to ${n} in range [${o}, ${i}]`:o>0?s=`${t} expression must resolve to positive ${n}`:s=`${t} expression must resolve to ${n}`,u(!e,s),null}var U=(e,t,r)=>H(e,t,{...r,integer:!0});function j(e,t,r){let n="array";!y(r?.size)&&r?.size>=0&&(n=r.size===0?"non-zero array":`array(${r.size})`),r?.type&&(n=`array of ${r.type}`);let o=`${t} expression must resolve to ${n}`;return u(!e,o),null}var De=(e,t,r)=>{let n=r.failOnError,o=r,i=e.length,s=f(o?.local?.groupId,t.n,o);return!w(s)||s<1?U(n,"$firstN 'n'",{min:1}):N(i<=s?e:e.slice(0,s),t.input,r)};var xr=(e,t,r)=>{let n=e[e.length-1],o=C.init(r).update({root:n});return f(n,t,o)??null};var Re=(e,t,r)=>{let n=r,o=e.length,i=f(n?.local?.groupId,t.n,n),s=r.failOnError;return!w(i)||i<1?U(s,"$lastN 'n'",{min:1}):N(o<=i?e:e.slice(o-i),t.input,r)};var Oi=(e,t,r)=>{let n=N(e,t,r).slice().sort(M),o=n.length;return y(n[o-1])?null:n[o-1]};var Pe=(e,t,r)=>{let n=r,o=f(n?.local?.groupId,t.n,n);return!w(o)||o<1?U(r.failOnError,"$maxN 'n'",{min:1}):N(e,t.input,r).filter(i=>!y(i)).sort(M).slice(-o).reverse()};var Oe=(e,t,r)=>{u(h(t)&&T(t,"input","p")&&l(t.p),"$percentile expects object { input, p }");let n=N(e,t.input,r).filter(x).sort(),o=N(t.p,"$$CURRENT",r),i=t.method||"approximate",s=new Array(o.length);for(let a=0;a<o.length;a++){let c=o[a];if(!x(c)||c<0||c>1)return L(r.failOnError,"$percentile 'p' must resolve to array of numbers between [0.0, 1.0]");let p=c*(n.length-1)+1,m=Math.floor(p),O=p===m?n[p-1]:n[m-1]+p%1*(n[m]-n[m-1]);switch(i){case"exact":s[a]=O;break;case"approximate":{let A=Yt(n,O);s[a]=A/n.length>=c?n[Math.max(A-1,0)]:n[A];break}}}return s};var hr=(e,t,r)=>Oe(e,{...t,p:[.5]},r)?.pop();var jr=(e,t,r)=>{let n={};for(let o of e)if(!y(o))for(let i of Object.keys(o))o[i]!==void 0&&(n[i]=o[i]);return n};var Ai=(e,t,r)=>{let n=N(e,t,r).filter(o=>!y(o)).sort(M);return y(n[0])?null:n[0]};var Ue=(e,t,r)=>{let n=r,o=f(n?.local?.groupId,t.n,n);return!w(o)||o<1?U(r.failOnError,"$minN 'n'",{min:1}):N(e,t.input,r).filter(i=>!y(i)).sort(M).slice(0,o)};var bi=(e,t,r)=>ke(N(e,t,r).filter(x),!1);var di=(e,t,r)=>ke(N(e,t,r).filter(x),!0);var gi=(e,t,r)=>{if(x(t))return e.length*t;let n=N(e,t,r),o=0;for(let i=0;i<n.length;i++)x(n[i])&&(o+=n[i]);return o};var $r=(e,t,r)=>{let n=r,{n:o,sortBy:i}=f(n?.local?.groupId,t,n),s=st(S(e),i,r).take(o).collect();return N(s,t.output,n)};var xi=(e,t,r)=>$r(e,{...t,n:1},r);var Vr={};ht(Vr,{$abs:()=>hi,$acos:()=>Pa,$acosh:()=>Ua,$add:()=>ji,$allElementsTrue:()=>sa,$and:()=>$n,$anyElementTrue:()=>aa,$arrayElemAt:()=>Ui,$arrayToObject:()=>Fi,$asin:()=>Fa,$asinh:()=>Ba,$atan:()=>La,$atan2:()=>za,$atanh:()=>Wa,$bitAnd:()=>os,$bitNot:()=>is,$bitOr:()=>ss,$bitXor:()=>as,$ceil:()=>$i,$cmp:()=>Tn,$concat:()=>la,$concatArrays:()=>Bi,$cond:()=>Os,$convert:()=>Na,$cos:()=>qa,$cosh:()=>Ya,$dateAdd:()=>xe,$dateDiff:()=>$s,$dateFromParts:()=>Ts,$dateFromString:()=>Cs,$dateSubtract:()=>ks,$dateToParts:()=>_s,$dateToString:()=>Ds,$dateTrunc:()=>Us,$dayOfMonth:()=>Fs,$dayOfWeek:()=>Bs,$dayOfYear:()=>Ls,$degreesToRadians:()=>Ka,$divide:()=>Ei,$eq:()=>Fn,$exp:()=>Ii,$filter:()=>Li,$first:()=>zi,$firstN:()=>Wi,$floor:()=>Ti,$function:()=>Mr,$getField:()=>ta,$gt:()=>Bn,$gte:()=>Ln,$hour:()=>zs,$ifNull:()=>_r,$in:()=>qi,$indexOfArray:()=>Yi,$indexOfBytes:()=>ya,$isArray:()=>Vi,$isNumber:()=>Sa,$isoDayOfWeek:()=>Ws,$isoWeek:()=>qs,$isoWeekYear:()=>Ys,$last:()=>Ki,$lastN:()=>Qi,$let:()=>tc,$literal:()=>Js,$ln:()=>vi,$log:()=>wi,$log10:()=>Ni,$lt:()=>zn,$lte:()=>Wn,$ltrim:()=>Aa,$map:()=>Hi,$maxN:()=>Gi,$median:()=>Zs,$mergeObjects:()=>Ur,$millisecond:()=>Vs,$minN:()=>Xi,$minute:()=>Ks,$mod:()=>Si,$month:()=>Qs,$multiply:()=>Ci,$ne:()=>qn,$not:()=>En,$objectToArray:()=>na,$or:()=>In,$percentile:()=>ia,$pow:()=>ki,$radiansToDegrees:()=>Ha,$rand:()=>ea,$range:()=>Ji,$reduce:()=>Zi,$regexFind:()=>ba,$regexFindAll:()=>da,$regexMatch:()=>ga,$replaceAll:()=>xa,$replaceOne:()=>ha,$reverseArray:()=>ts,$round:()=>_i,$rtrim:()=>ja,$sampleRate:()=>ra,$second:()=>Hs,$setDifference:()=>ca,$setEquals:()=>pa,$setField:()=>Fr,$setIntersection:()=>ua,$setIsSubset:()=>ma,$setUnion:()=>fa,$sigmoid:()=>Mi,$sin:()=>Ga,$sinh:()=>Xa,$size:()=>es,$slice:()=>Tr,$sortArray:()=>rs,$split:()=>$a,$sqrt:()=>Di,$strLenBytes:()=>Ia,$strLenCP:()=>Ta,$strcasecmp:()=>Ea,$substr:()=>va,$substrBytes:()=>Lr,$substrCP:()=>wa,$subtract:()=>Ri,$switch:()=>As,$tan:()=>Ja,$tanh:()=>Za,$toBool:()=>zr,$toDate:()=>Wr,$toDecimal:()=>Ca,$toDouble:()=>je,$toHashedIndexKey:()=>Ra,$toInt:()=>qr,$toLong:()=>Yr,$toLower:()=>_a,$toString:()=>Gt,$toUpper:()=>Ma,$trim:()=>Da,$trunc:()=>Pi,$type:()=>ka,$unsetField:()=>oa,$week:()=>Gs,$year:()=>Xs,$zip:()=>ns});var hi=(e,t,r)=>{let n=f(e,t,r);return y(n)?null:typeof n!="number"?H(r.failOnError,"$abs"):Math.abs(n)};var hn="$add expression must resolve to array of numbers.",ji=(e,t,r)=>{let n=f(e,t,r),o=r.failOnError,i=!1,s=0;if(!l(n))return L(o,hn);for(let a of n){if(y(a))return null;if(typeof a=="number")s+=a;else if(R(a)){if(i)return L(o,"$add must only have one date");i=!0,s+=+a}else return L(o,hn)}return i?new Date(s):s};var $i=(e,t,r)=>{let n=f(e,t,r);return y(n)?null:typeof n!="number"?H(r.failOnError,"$ceil"):Math.ceil(n)};var Ei=(e,t,r)=>{u(l(t),"$divide expects array(2)");let n=f(e,t,r),o=r.failOnError,i=!0;for(let s of n){if(y(s))return null;i&&=x(s)}return i?n[1]===0?L(o,"$divide cannot divide by zero"):n[0]/n[1]:j(o,"$divide",{size:2,type:"number"})};var Ii=(e,t,r)=>{let n=f(e,t,r);return y(n)?null:typeof n!="number"?H(r.failOnError,"$exp"):Math.exp(n)};var Ti=(e,t,r)=>{let n=f(e,t,r);return y(n)?null:typeof n!="number"?H(r.failOnError,"$floor"):Math.floor(n)};var vi=(e,t,r)=>{let n=f(e,t,r);return y(n)?null:typeof n!="number"?H(r.failOnError,"$ln"):Math.log(n)};var wi=(e,t,r)=>{let n=f(e,t,r);if(l(n)&&n.length==2){let o=!0;for(let i of n){if(y(i))return null;o&&=typeof i=="number"}if(o)return Math.log10(n[0])/Math.log10(n[1])}return j(r.failOnError,"$log",{size:2,type:"number"})};var Ni=(e,t,r)=>{let n=f(e,t,r);return y(n)?null:typeof n=="number"?Math.log10(n):H(r.failOnError,"$log10")};var Si=(e,t,r)=>{let n=f(e,t,r),o=!l(n)||n.length!=2;return o||=!n.every(i=>typeof i=="number"),o?j(r.failOnError,"$mod",{size:2,type:"number"}):n[0]%n[1]};var Ci=(e,t,r)=>{u(l(t),"$multiply expects array");let n=f(e,t,r),o=r.failOnError;if(n.some(y))return null;let i=1;for(let s of n){if(!x(s))return j(o,"$multiply",{type:"number"});i*=s}return i};var ki=(e,t,r)=>{u(l(t)&&t.length===2,"$pow expects array(2)");let n=f(e,t,r),o=r.failOnError,i=!0;for(let s of n){if(y(s))return null;i&&=x(s)}return i?(n[0]===0&&n[1]<0&&L(o,"$pow cannot raise 0 to a negative exponent"),Math.pow(n[0],n[1])):j(o,"$pow",{size:2,type:"number"})};function Fe(e,t,r){let{name:n,roundOff:o,failOnError:i}=r;if(y(e))return null;if(Number.isNaN(e)||Math.abs(e)===1/0)return e;if(!x(e))return H(i,`${n} arg1 <number>`);if(!w(t)||t<-20||t>100)return U(i,`${n} arg2 <precision>`,{min:-20,max:100});let s=Math.abs(e)===e?1:-1;e=Math.abs(e);let a=Math.trunc(e),c=parseFloat((e-a).toFixed(Math.abs(t)+1));if(t===0){let p=Math.trunc(10*c);o&&((a&1)===1&&p>=5||p>5)&&a++}else if(t>0){let p=Math.pow(10,t),m=Math.trunc(c*p),O=Math.trunc(c*p*10)%10;o&&O>5&&(m+=1),a=(a*p+m)/p}else{let p=Math.pow(10,-1*t),m=a%p;if(a=Math.max(0,a-m),o&&s===-1){for(;m>10;)m-=m/10;a>0&&m>=5&&(a+=p)}}return a*s}var _i=(e,t,r)=>{u(l(t),"$round expects array(2)");let[n,o]=f(e,t,r);return Fe(n,o??0,{name:"$round",roundOff:!0,failOnError:r.failOnError})};var jn=1e10,Mi=(e,t,r)=>{if(y(t))return null;let n=f(e,t,r),{input:o,onNull:i}=h(n)?n:{input:n};if(y(o))return x(i)?i:null;if(x(o)){let s=1/(1+Math.exp(-o));return Math.round(s*jn)/jn}return H(r.failOnError,"$sigmoid")};var Di=(e,t,r)=>{let n=f(e,t,r),o=!r.failOnError;return y(n)?null:typeof n!="number"||n<0?(u(o,"$sqrt expression must resolve to non-negative number."),null):Math.sqrt(n)};var Ri=(e,t,r)=>{u(l(t),"$subtract expects array(2)");let n=f(e,t,r);if(n.some(y))return null;let o=r.failOnError,[i,s]=n;return R(i)&&x(s)?new Date(+i-Math.round(s)):R(i)&&R(s)?+i-+s:n.every(a=>typeof a=="number")?i-s:x(i)&&R(s)?L(o,"$subtract cannot subtract date from number"):j(o,"$subtract",{size:2,type:"number|date"})};var Pi=(e,t,r)=>{u(l(t),"$trunc expects array(2)");let[n,o]=f(e,t,r);return Fe(n,o??0,{name:"$trunc",roundOff:!1,failOnError:r.failOnError})};var Ir="$arrayElemAt",Ui=(e,t,r)=>{u(l(t)&&t.length===2,`${Ir} expects array(2)`);let n=f(e,t,r);if(n.some(y))return null;let o=r.failOnError,[i,s]=n;if(!l(i))return j(o,`${Ir} arg1 <array>`);if(!w(s))return U(o,`${Ir} arg2 <index>`);if(s<0&&Math.abs(s)<=i.length)return i[(s+i.length)%i.length];if(s>=0&&s<i.length)return i[s]};var Be={generic:{type:"key-value pairs"},array:{type:"[k,v]"},object:{type:"{k,v}"}},Fi=(e,t,r)=>{let n=r.failOnError,o=f(e,t,r);if(y(o))return null;if(!l(o))return j(n,"$arrayToObject",Be.generic);let i=0,s={};for(let a of o)if(l(a)){let c=pt(a);if(i||(i=1),i!==1)return j(n,"$arrayToObject",Be.object);let[p,m]=c;s[p]=m}else if(h(a)&&T(a,"k","v")){if(i||(i=2),i!==2)return j(n,"$arrayToObject",Be.array);let{k:c,v:p}=a;s[c]=p}else return j(n,"$arrayToObject",Be.generic);return s};var Bi=(e,t,r)=>{let n=f(e,t,r),o=r.failOnError;if(y(n))return null;if(!l(n))return j(o,"$concatArrays");let i=0;for(let c of n){if(y(c))return null;if(!l(c))return j(o,"$concatArrays");i+=c.length}let s=new Array(i),a=0;for(let c of n)for(let p of c)s[a++]=p;return s};var Li=(e,t,r)=>{u(h(t)&&T(t,"input","cond"),"$filter expects object { input, as, cond, limit }");let n=f(e,t.input,r),o=r.failOnError;if(y(n))return null;if(!l(n))return j(o,"$filter 'input'");let i=t.limit??Math.max(n.length,1);if(!w(i)||i<1)return U(o,"$filter 'limit'",{min:1});if(n.length===0)return[];let s=C.init(r),a=t?.as||"this",c={variables:{}},p=[];for(let m=0,O=0;m<n.length&&O<i;m++){c.variables[a]=n[m];let A=f(e,t.cond,s.update(c));nt(A,r.useStrictMode)&&(p.push(n[m]),O++)}return p};var zi=(e,t,r)=>{if(l(e))return gr(e,t,r);let n=f(e,t,r);return y(n)?null:l(n)?pt(n)[0]:j(r.failOnError,"$first")};var Wi=(e,t,r)=>{if(u(h(t)&&T(t,"input","n"),"$firstN expects object { input, n }"),l(e))return De(e,t,r);let{input:n,n:o}=f(e,t,r);return y(n)?null:l(n)?De(n,{n:o,input:"$$this"},r):j(r.failOnError,"$firstN 'input'")};var qi=(e,t,r)=>{u(l(t)&&t.length===2,"$in expects array(2)");let n=f(e,t,r),[o,i]=n;if(!l(i))return L(r.failOnError,"$in arg2 <array>");for(let s of i)if(Q(s,o))return!0;return!1};var Le="$indexOfArray",Yi=(e,t,r)=>{u(l(t)&&t.length>1&&t.length<5,`${Le} expects array(4)`);let n=f(e,t,r),o=r.failOnError,i=n[0];if(y(i))return null;if(!l(i))return j(o,`${Le} arg1 <array>`);let s=n[1],a=n[2]??0,c=n[3]??i.length;return!w(a)||a<0?U(o,`${Le} arg3 <start>`,{min:1}):!w(c)||c<0?U(o,`${Le} arg4 <end>`,{min:1}):a>c?-1:(a>0||c<i.length?i.slice(a,c):i).findIndex(m=>Q(m,s))+a};var Vi=(e,t,r)=>{let n=t;return l(t)&&(u(t.length===1,"$isArray expects array(1)"),n=t[0]),l(f(e,n,r))};var Ki=(e,t,r)=>{if(l(e))return xr(e,t,r);let n=f(e,t,r);return y(n)?null:!l(n)||n.length===0?j(r.failOnError,"$last",{size:0}):pt(n)[n.length-1]};var Qi=(e,t,r)=>{if(u(h(t)&&T(t,"input","n"),"$lastN expects object { input, n }"),l(e))return Re(e,t,r);let{input:n,n:o}=f(e,t,r);return y(n)?null:l(n)?Re(n,{n:o,input:"$$this"},r):j(r.failOnError,"$lastN 'input'")};var Hi=(e,t,r)=>{u(h(t)&&T(t,"input","in"),"$map expects object { input, as, in }");let n=f(e,t.input,r),o=r.failOnError;if(y(n))return null;if(!l(n))return j(o,"$map 'input'");if(!y(t.as)&&!$(t.as))return J(o,"$map 'as'");let i=C.init(r),s=t.as||"this",a={variables:{}},c=new Array(n.length);for(let p=0;p<n.length;p++)a.variables[s]=n[p],c[p]=f(e,t.in,i.update(a));return c};var Gi=(e,t,r)=>{if(u(h(t)&&T(t,"input","n"),"$maxN expects object { input, n }"),l(e))return Pe(e,t,r);let{input:n,n:o}=f(e,t,r);return y(n)?null:l(n)?Pe(n,{n:o,input:"$$this"},r):j(r.failOnError,"$maxN 'input'")};var Xi=(e,t,r)=>{if(u(h(t)&&T(t,"input","n"),"$minN expects object { input, n }"),l(e))return Ue(e,t,r);let{input:n,n:o}=f(e,t,r);return y(n)?null:l(n)?Ue(n,{n:o,input:"$$this"},r):j(r.failOnError,"$minN 'input'")};var Ji=(e,t,r)=>{u(l(t)&&t.length>1&&t.length<4,"$range expects array(3)");let[n,o,i]=f(e,t,r),s=r.failOnError,a=i??1;if(!w(n))return U(s,"$range arg1 <start>");if(!w(o))return U(s,"$range arg2 <end>");if(!w(a)||a===0)return U(s,"$range arg3 <step>",{min:0,max:0});let c=new Array,p=n;for(;p<o&&a>0||p>o&&a<0;)c.push(p),p+=a;return c};function Zi(e,t,r){u(h(t)&&T(t,"input","initialValue","in"),"$reduce expects object { input, initialValue, in }");let n=f(e,t.input,r),o=f(e,t.initialValue,r),i=t.in;if(y(n))return null;if(!l(n))return j(r.failOnError,"$reduce 'input'");let s=C.init(r),a={variables:{value:null}},c=o;for(let p=0;p<n.length;p++)a.variables.value=c,c=f(n[p],i,s.update(a));return c}var ts=(e,t,r)=>{let n=f(e,t,r);return y(n)?null:l(n)?n.slice().reverse():j(r.failOnError,"$reverseArray")};var es=(e,t,r)=>{let n=f(e,t,r);return y(n)?null:l(n)?n.length:H(r.failOnError,"$size")};var Tr=(e,t,r)=>{u(l(t)&&t.length>1&&t.length<4,"$slice expects array(3)");let n=r.failOnError,o=f(e,t,r),i=o[0],s=o[1],a=o[2];if(!l(i))return j(n,"$slice arg1 <array>");if(!w(s))return U(n,"$slice arg2 <n>");if(!y(a)&&!w(a))return U(n,"$slice arg3 <n>");if(y(a))s<0?s=Math.max(0,i.length+s):(a=s,s=0);else{if(s<0&&(s=Math.max(0,i.length+s)),a<1)return U(n,"$slice arg3 <n>",{min:1});a+=s}return i.slice(s,a)};var rs=(e,t,r)=>{u(h(t)&&"input"in t&&"sortBy"in t,"$sortArray expects object { input, sortBy }");let{input:n,sortBy:o}=f(e,t,r);if(y(n))return null;if(!l(n))return j(r.failOnError,"$sortArray 'input'");if(h(o))return st(S(n),o,r).collect();let i=n.slice().sort(M);return o===-1&&i.reverse(),i};var ns=(e,t,r)=>{u(h(t)&&T(t,"inputs"),"$zip received invalid arguments");let n=f(e,t.inputs,r),o=f(e,t.defaults,r)??[],i=t.useLongestLength??!1,s=r.failOnError;if(y(n))return null;if(!l(n))return j(s,"$zip 'inputs'");let a=0;for(let m of n){if(y(m))return null;l(m)||a++}if(a)return j(s,"$zip elements of 'inputs'");Bt(i)||L(s,"$zip 'useLongestLength' must be boolean"),l(o)&&o.length>0&&u(i&&o.length===n.length,"$zip 'useLongestLength' must be set to true to use 'defaults'");let c=0;for(let m of n)c=i?Math.max(c,m.length):Math.min(c||m.length,m.length);let p=[];for(let m=0;m<c;m++){let O=new Array(n.length);for(let A=0;A<n.length;A++){let b=n[A][m];O[A]=y(b)?o[A]??null:b}p.push(O)}return p};function ne(e,t,r,n,o){u(l(t),`${n} expects array as argument`);let i=f(e,t,r),s=!0;for(let a of i){if(y(a))return null;s&&=w(a)}return s?o(i):L(r.failOnError,`${n} array elements must resolve to integers`)}var os=(e,t,r)=>ne(e,t,r,"$bitAnd",n=>n.reduce((o,i)=>o&i,-1));var is=(e,t,r)=>{let n=f(e,t,r);return y(n)?null:w(n)?~n:U(r.failOnError,"$bitNot")};var ss=(e,t,r)=>ne(e,t,r,"$bitOr",n=>n.reduce((o,i)=>o|i,0));var as=(e,t,r)=>ne(e,t,r,"$bitXor",n=>n.reduce((o,i)=>o^i,0));var Ae={};ht(Ae,{$and:()=>$n,$not:()=>En,$or:()=>In});var $n=(e,t,r)=>{u(l(t),"$and expects array");let n=r.useStrictMode;return t.every(o=>nt(f(e,o,r),n))};var En=(e,t,r)=>{let n=ct(t);return n.length===0?!1:n.length>1?j(r.failOnError,"$not",{size:1}):!f(e,n[0],r)};var In=(e,t,r)=>{u(l(t),"$or expects array of expressions");let n=r.useStrictMode;for(let o of t)if(nt(f(e,o,r),n))return!0;return!1};var de={};ht(de,{$cmp:()=>Tn,$eq:()=>Fn,$gt:()=>Bn,$gte:()=>Ln,$lt:()=>zn,$lte:()=>Wn,$ne:()=>qn});var Tn=(e,t,r)=>{u(l(t)&&t.length===2,"$cmp expects array(2)");let[n,o]=f(e,t,r);return M(n,o)};function vr(e,t,r){return e.take(t)}function wr(e,t,r){let n=f(null,t,r);return u(l(n),"$documents expression must resolve to an array."),S(n).map(o=>it(o))}var cs=S([]);function ze(e,t){if(!e)return{};let r=e[0]?.$documents;return r?{documents:wr(cs,r,t).collect(),pipeline:e.slice(1)}:{pipeline:e}}function Nr(e,t,r=!0){let n={exclusions:[],inclusions:[],positional:0},o=Object.keys(e);u(o.length,"Invalid empty sub-projection");let i=t?.idKey,s=!1;for(let a of o){if(a.startsWith("$"))return u(!r&&o.length===1,`FieldPath field names may not start with '$', given '${a}'.`),n;a.endsWith(".$")&&n.positional++;let c=e[a];if(c===!1||x(c)&&c===0)a===i?s=!0:n.exclusions.push(a);else if(!h(c))n.inclusions.push(a);else{let p=Nr(c,t,!1);if(!p.inclusions.length&&!p.exclusions.length)n.inclusions.includes(a)||n.inclusions.push(a);else{for(let m of p.exclusions)n.exclusions.push(`${a}.${m}`);for(let m of p.inclusions)n.inclusions.push(`${a}.${m}`)}n.positional+=p.positional}u(!(n.exclusions.length&&n.inclusions.length),"Cannot do exclusion and inclusion in projection."),u(n.positional<=1,"Cannot specify more than one positional projection.")}if(s&&n.exclusions.push(i),r){let a=new vt;for(let c of n.exclusions)u(a.add(c),`Path collision at ${c}.`);for(let c of n.inclusions)u(a.add(c),`Path collision at ${c}.`);n.exclusions.sort(),n.inclusions.sort()}return n}function Et(e,t,r){$(t)&&u(r.collectionResolver,`${e} requires 'collectionResolver' option to resolve named collection`);let n=$(t)?r.collectionResolver(t):t;return u(l(n),`${e} could not resolve input collection`),n}var Sr="$project";function Kt(e,t,r){if(le(t))return e;let n=Nr(t,r),o=ps(t,C.init(r),n);return e.map(o)}function ps(e,t,r){let n=t.idKey,{exclusions:o,inclusions:i}=r,s={},a={preserveIndex:"missing"};for(let A of o)s[A]=(b,d)=>{Wt(b,A,{descendArray:!0})};for(let A of i){let b=D(e,A)??e[A];if(A.endsWith(".$")&&b===1){let d=t?.local?.condition??{};u(d,`${Sr}: positional operator '.$' requires array condition.`);let g=A.slice(0,-2);s[g]=fs(g,d,t);continue}if(l(b))s[A]=(d,g)=>{t.update({root:g});let E=b.map(I=>f(g,I,t)??null);yt(d,A,E)};else if(x(b)||b===!0)s[A]=(d,g)=>{t.update({root:g});let E=Tt(g,A,a);wn(d,E)};else if(!h(b))s[A]=(d,g)=>{t.update({root:g});let E=f(g,b,t);yt(d,A,E)};else{let d=Object.keys(b);u(d.length===1&&ut(d[0]),"Not a valid operator");let g=d[0],E=b[g],I=t.context.getOperator("projection",g);!I||g==="$slice"&&!ct(E).every(x)?s[A]=(F,k)=>{t.update({root:k});let X=f(k,b,t);yt(F,A,X)}:s[A]=(F,k)=>{t.update({root:k});let X=I(k,E,A,t);yt(F,A,X)}}}let c=o.length===1&&o.includes(n),p=!o.includes(n),m=!i.length,O=m&&c||m&&o.length&&!c;return A=>{let b={};O&&Object.assign(b,A);for(let d in s)s[d](b,A);return m||Se(b),p&&!T(b,n)&&T(A,n)&&(b[n]=D(A,n)),b}}var vn=(e,t,r,n)=>{let o=D(e,t);l(o)||(o=D(o,r)),u(l(o),`${Sr}: field '${t}' must resolve to array`);let i=[];for(let s=0;s<o.length;s++)n({[r]:[o[s]]})&&i.push(s);return i},us=e=>(t=>!e(t)),ms={$and:1,$or:1,$nor:1};function fs(e,t,r){let n=Object.entries(t).slice(),o={$and:[],$or:[]};for(let c=0;c<n.length;c++){let[p,m,O]=n[c];if(p===e||p.startsWith(e+".")){let A=qt(m),b=Object.keys(A)[0],d=A[b],g=r.context.getOperator("query",b),E=p.substring(p.lastIndexOf(".")+1),I=g(E,d,r);!O||O==="$and"?o.$and.push([p,I,E]):O==="$nor"?o.$and.push([p,us(I),E]):O==="$or"&&o.$or.push([p,I,E])}else if(ut(p)){u(!!ms[p],`${Sr}: '${p}' is not allowed in this context`);for(let A of m)for(let b of Object.keys(A))n.push([b,A[b],p])}}let i=e.lastIndexOf("."),s=e.substring(0,i)||e,a=e.substring(i+1);return(c,p)=>{let m=[];for(let[b,d,g]of o.$and)m.push(vn(p,b,g,d));if(o.$or.length){let b=[];for(let[d,g,E]of o.$or)b.push(...vn(p,d,E,g));m.push($t(b))}let O=Lt(m).sort()[0],A=D(p,e)[O];s!=a&&!h(A)&&(A={[a]:A}),yt(c,s,[A])}}function wn(e,t){if(e===ee||y(e))return t;if(y(t))return e;let r=e,n=t;for(let o of Object.keys(t))r[o]=wn(r[o],n[o]);return r}function Cr(e,t,r){return u(t>=0,"$skip value must be a non-negative integer"),e.drop(t)}var Nn={$sort:st,$skip:Cr,$limit:vr},We=class{#t;#e;#r;#o;#s={};#n=null;#i=[];constructor(t,r,n,o){this.#t=t,this.#e=r,this.#r=n,this.#o=o}fetch(){if(this.#n)return this.#n;this.#n=S(this.#t).filter(this.#e);let t=this.#o.processingMode;t&1&&this.#n.map(r=>it(r));for(let r of Object.keys(Nn))if(T(this.#s,r)){let n=Nn[r];this.#n=n(this.#n,this.#s[r],this.#o)}return Object.keys(this.#r).length&&(this.#n=Kt(this.#n,this.#r,this.#o)),t&2&&this.#n.map(r=>it(r)),this.#n}fetchAll(){let t=S(Array.from(this.#i));return this.#i.length=0,Nt(t,this.fetch())}all(){return this.fetchAll().collect()}skip(t){return this.#s.$skip=t,this}limit(t){return this.#s.$limit=t,this}sort(t){return this.#s.$sort=t,this}collation(t){return this.#o={...this.#o,collation:t},this}next(){if(this.#i.length>0)return this.#i.pop();let t=this.fetch().next();if(!t.done)return t.value}hasNext(){if(this.#i.length>0)return!0;let t=this.fetch().next();return t.done?!1:(this.#i.push(t.value),!0)}[Symbol.iterator](){return this.fetchAll()}};var ls=new Set(["$and","$or","$nor","$expr","$jsonSchema"]),Z=class{#t;#e;#r;constructor(t,r){this.#e=it(t),this.#r=C.init(r).update({condition:t}),this.#t=[],this.compile()}compile(){u(h(this.#e),`query criteria must be an object: ${JSON.stringify(this.#e)}`);let t={};for(let r of Object.keys(this.#e)){let n=this.#e[r];if(r==="$where")u(this.#r.scriptEnabled,"$where operator requires 'scriptEnabled' option to be true."),Object.assign(t,{field:r,expr:n});else if(ls.has(r))this.processOperator(r,r,n);else{u(!ut(r),`unknown top level operator: ${r}`);let o=qt(n);for(let i of Object.keys(o))this.processOperator(r,i,o[i])}t.field&&this.processOperator(t.field,t.field,t.expr)}}processOperator(t,r,n){let o=this.#r.context.getOperator("query",r);u(!!o,`unknown query operator ${r}`),this.#t.push(o(t,n,this.#r))}test(t){return this.#t.every(r=>r(t))}find(t,r){return new We(t,n=>this.test(n),r||{},this.#r)}};function kn(e,t){if(Object.keys(e).length===0)return i=>h(i);let r=i=>i,n=!0;for(let i of Object.keys(e))if(n&&=ut(i)&&i!=="$and"&&i!=="$or"&&i!=="$nor",!n)break;n&&(e={field:e},r=i=>({field:i}));let o=new Z(e,t);return i=>o.test(r(i))}function B(e,t,r,n){let[o,i]=[-1,0];for(;(o=e.indexOf(".",o+1))!==-1;)i++;let s=C.init(r).update({depth:i}),a={unwrapArray:!0};return n===He&&(t=kn(t,r)),c=>{let p=D(c,e,a);return n(p,t,s)}}function dt(e,t,r,n){u(l(t)&&t.length===2,`${n.name} expects array(2)`);let[o,i]=f(e,t,r);return n(o,i,r)}function be(e,t,r){if(Q(e,t)||y(e)&&y(t))return!0;if(l(e)){let n=r?.local?.depth??1;return e.some(o=>Q(o,t))||pt(e,n).some(o=>Q(o,t))}return!1}function qe(e,t,r){return!be(e,t,r)}function kr(e,t,r){if(y(e))return t.some(i=>i===null);let n=ct(e);if(Lt([n,t]).length>0)return!0;let o=t.filter(ot);return o.length>0&&n.some(i=>$(i)&&o.some(s=>s.test(i)))}function _n(e,t,r){return!kr(e,t,r)}function Ye(e,t,r){return Ge(e,t,(n,o)=>M(n,o)<0)}function Ve(e,t,r){return Ge(e,t,(n,o)=>M(n,o)<=0)}function Ke(e,t,r){return Ge(e,t,(n,o)=>M(n,o)>0)}function Qe(e,t,r){return Ge(e,t,(n,o)=>M(n,o)>=0)}function Mn(e,t,r){return ct(e).some((n=>t.length===2&&n%t[0]===t[1]))}function Dn(e,t,r){let n=ct(e),o=i=>$(i)&&nt(t.exec(i),r?.useStrictMode);return n.some(o)||pt(n,1).some(o)}function Rn(e,t,r){if(!l(e)||!l(t)||!e.length||!t.length)return!1;let n=!0;for(let o of t){if(!n)break;if(h(o)&&Object.keys(o)[0]==="$elemMatch"){let i=o.$elemMatch,s=kn(i,r);n=He(e,s,r)}else ot(o)?n=e.some(i=>$(i)&&o.test(i)):n=e.some(i=>Q(o,i))}return n}function Pn(e,t,r){return Array.isArray(e)&&e.length===t}function He(e,t,r){if(l(e)&&e.length!==0){for(let n=0,o=e.length;n<o;n++)if(t(e[n]))return!0}return!1}var Sn=e=>e===null,ys={array:l,boolean:Bt,bool:Bt,date:R,number:x,int:w,long:w,double:x,decimal:x,null:Sn,object:h,regexp:ot,regex:ot,string:$,undefined:y,1:x,2:$,3:h,4:l,6:y,8:Bt,9:R,10:Sn,11:ot,16:w,18:w,19:x};function Cn(e,t,r){let n=ys[t];return n?n(e):!1}function Un(e,t,r){return l(t)?t.findIndex(n=>Cn(e,n,r))>=0:Cn(e,t,r)}function Ge(e,t,r){for(let n of ct(e))if(at(n)===at(t)&&r(n,t))return!0;return!1}var Fn=(e,t,r)=>dt(e,t,r,be);var Bn=(e,t,r)=>dt(e,t,r,Ke);var Ln=(e,t,r)=>dt(e,t,r,Qe);var zn=(e,t,r)=>dt(e,t,r,Ye);var Wn=(e,t,r)=>dt(e,t,r,Ve);var qn=(e,t,r)=>dt(e,t,r,qe);var Yn="$cond expects array(3) or object with 'if-then-else' expressions",Os=(e,t,r)=>{let n,o,i;l(t)?(u(t.length===3,Yn),n=t[0],o=t[1],i=t[2]):(u(h(t),Yn),n=t.if,o=t.then,i=t.else);let s=nt(f(e,n,r),r.useStrictMode);return f(e,s?o:i,r)};var _r=(e,t,r)=>{u(l(t),"$ifNull expects an array");let n;for(let o of t)if(n=f(e,o,r),!y(n))return n;return n};var As=(e,t,r)=>{u(h(t),"$switch received invalid arguments");for(let{case:n,then:o}of t.branches)if(nt(f(e,n,r),r.useStrictMode))return f(e,o,r);return f(e,t.default,r)};var Mr=(e,t,r)=>{u(r.scriptEnabled,"$function requires 'scriptEnabled' option to be true");let n=f(e,t,r);return n.body.apply(null,n.args)};var ge=["year","quarter","month","week","day","hour","minute","second","millisecond"],bs={mon:1,tue:2,wed:3,thu:4,fri:5,sat:6,sun:7},ds=-1e9,oe=7,Dr=e=>(e&3)==0&&(e%100!=0||e%400==0);var gs=[365,366],xs=[[0,31,59,90,120,151,181,212,243,273,304,334],[0,31,60,91,121,152,182,213,244,274,305,335]],Qt=e=>xs[+Dr(e.getUTCFullYear())][e.getUTCMonth()]+e.getUTCDate(),Xe=(e,t)=>{let r=e.getUTCDay()||7,n=t.toLowerCase().substring(0,3);return(r-bs[n]+oe)%oe},Vn=e=>(e+Math.floor(e/4)-Math.floor(e/100)+Math.floor(e/400))%7,Kn=e=>52+ +(Vn(e)==4||Vn(e-1)==3);function Ht(e){let t=e.getUTCDay()||7,r=Math.floor((10+Qt(e)-t)/7);return r<1?Kn(e.getUTCFullYear()-1):r>Kn(e.getUTCFullYear())?1:r}function Ze(e){let t=Ht(e);return e.getUTCDay()>0&&e.getUTCDate()==1&&e.getUTCMonth()==0?0:e.getUTCDay()==0?t+1:t}function tr(e){return e.getUTCFullYear()-+(e.getUTCMonth()===0&&e.getUTCDate()==1&&e.getUTCDay()<1)}var _t=60,xt={week:6048e5,day:864e5,hour:36e5,minute:6e4,second:1e3,millisecond:1},er="%Y-%m-%dT%H:%M:%S.%LZ",Rr=[["year",0,9999],["month",1,12],["day",1,31],["hour",0,23],["minute",0,59],["second",0,59],["millisecond",0,999]],Pr={jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12},ie={"%b":{name:"abbr_month",padding:3,re:/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i},"%B":{name:"full_month",padding:0,re:/(January|February|March|April|May|June|July|August|September|October|November|December)/i},"%Y":{name:"year",padding:4,re:/([0-9]{4})/},"%G":{name:"year",padding:4,re:/([0-9]{4})/},"%m":{name:"month",padding:2,re:/(0[1-9]|1[012])/},"%d":{name:"day",padding:2,re:/(0[1-9]|[12][0-9]|3[01])/},"%j":{name:"day_of_year",padding:3,re:/(0[0-9][1-9]|[12][0-9]{2}|3[0-5][0-9]|36[0-6])/},"%H":{name:"hour",padding:2,re:/([01][0-9]|2[0-3])/},"%M":{name:"minute",padding:2,re:/([0-5][0-9])/},"%S":{name:"second",padding:2,re:/([0-5][0-9]|60)/},"%L":{name:"millisecond",padding:3,re:/([0-9]{3})/},"%w":{name:"day_of_week",padding:1,re:/([0-6])/},"%u":{name:"day_of_week_iso",padding:1,re:/([1-7])/},"%U":{name:"week_of_year",padding:2,re:/([1-4][0-9]?|5[0-3]?)/},"%V":{name:"week_of_year_iso",padding:2,re:/([1-4][0-9]?|5[0-3]?)/},"%z":{name:"timezone",padding:2,re:/(([+-][01][0-9]|2[0-3]):?([0-5][0-9])?)/},"%Z":{name:"minute_offset",padding:3,re:/([+-][0-9]{3})/},"%%":{name:"percent_literal",padding:1,re:/%%/}},rr=/(%[bBYGmdjHMSLwuUVzZ%])/g,Gn=/%[bBYGmdjHMSLwuUVzZ%]/,hs=/^[a-zA-Z_]+\/[a-zA-Z_]+$/;function lt(e,t){if(e===void 0)return 0;if(hs.test(e)){let i=new Date(t.toLocaleString("en-US",{timeZone:"UTC"})),s=new Date(t.toLocaleString("en-US",{timeZone:e}));return Math.round((s.getTime()-i.getTime())/6e4)}let r=ie["%z"].re.exec(e);u(!!r,`timezone '${e}' is invalid or not supported.`);let n=parseInt(r[2])||0,o=parseInt(r[3])||0;return(Math.abs(n*_t)+o)*(n<0?-1:1)}function Xn(e){return(e<0?"-":"+")+Je(Math.abs(Math.floor(e/_t)),2)+Je(Math.abs(e)%_t,2)}function gt(e,t){e.setUTCMinutes(e.getUTCMinutes()+t)}function z(e,t,r){let n=f(e,t,r);if(R(n))return new Date(n);u(!!n?.date,`cannot convert ${JSON.stringify(t)} to date`);let o=new Date(n.date);return n.timezone&&gt(o,lt(n.timezone,o)),o}function Je(e,t){return new Array(Math.max(t-String(e).length+1,0)).join("0")+e.toString()}var Qn=e=>{let t=e-ds;return Math.trunc(t/4)-Math.trunc(t/100)+Math.trunc(t/400)};function js(e,t){return Math.trunc(Qn(t-1)-Qn(e-1)+(t-e)*gs[0])}var se=(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),nr=(e,t)=>t.getUTCMonth()-e.getUTCMonth()+se(e,t)*12,or=(e,t)=>{let r=Math.trunc(e.getUTCMonth()/3);return Math.trunc(t.getUTCMonth()/3)-r+se(e,t)*4},ae=(e,t)=>Qt(t)-Qt(e)+js(e.getUTCFullYear(),t.getUTCFullYear()),ir=(e,t,r)=>{let n=(r||"sun").substring(0,3);return Math.trunc((ae(e,t)+Xe(e,n)-Xe(t,n))/oe)},Jn=(e,t)=>t.getUTCHours()-e.getUTCHours()+ae(e,t)*24,Hn=(e,t)=>{let r=e.getUTCMonth()+t,n=Math.floor(r/12);if(r<0){let o=r%12+12;e.setUTCFullYear(e.getUTCFullYear()+n,o,e.getUTCDate())}else e.setUTCFullYear(e.getUTCFullYear()+n,r%12,e.getUTCDate())},ce=(e,t,r,n)=>{let o=new Date(e);switch(t){case"year":o.setUTCFullYear(o.getUTCFullYear()+r);break;case"quarter":Hn(o,3*r);break;case"month":Hn(o,r);break;default:o.setTime(o.getTime()+xt[t]*r)}return o};var xe=(e,t,r)=>{let n=f(e,t,r);return ce(n.startDate,n.unit,n.amount,n.timezone)};var $s=(e,t,r)=>{let{startDate:n,endDate:o,unit:i,timezone:s,startOfWeek:a}=f(e,t,r),c=new Date(n),p=new Date(o);switch(gt(c,lt(s,c)),gt(p,lt(s,p)),i){case"year":return se(c,p);case"quarter":return or(c,p);case"month":return nr(c,p);case"week":return ir(c,p,a);case"day":return ae(c,p);case"hour":return Jn(c,p);case"minute":return c.setUTCSeconds(0),c.setUTCMilliseconds(0),p.setUTCSeconds(0),p.setUTCMilliseconds(0),Math.round((p.getTime()-c.getTime())/xt[i]);default:return Math.round((p.getTime()-c.getTime())/xt[i])}};var Es=[31,28,31,30,31,30,31,31,30,31,30,31],Is=e=>e.month==2&&Dr(e.year)?29:Es[e.month-1],Ts=(e,t,r)=>{let n=f(e,t,r),o=lt(n.timezone,new Date);for(let i=Rr.length-1,s=0;i>=0;i--){let a=Rr[i],c=a[0],p=a[1],m=a[2],O=(n[c]||0)+s;s=0;let A=m+1;if(c=="hour"&&(O+=Math.floor(o/_t)*-1),c=="minute"&&(O+=o%_t*-1),O<p){let b=p-O;s=-1*Math.ceil(b/A),O=A-b%A}else O>m&&(O+=p,s=Math.trunc(O/A),O%=A);n[c]=O}return n.day=Math.min(n.day,Is(n)),new Date(Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second,n.millisecond))};function vs(e){return e==="Z"?0:e>="A"&&e<"N"?e.charCodeAt(0)-64:77-e.charCodeAt(0)}var ws=e=>e.replace(/^\//,"").replace(/\/$/,"").replace(/\/i/,""),Ns=["^",".","-","*","?","$"];function Ss(e){for(let t of Ns)e=e.replace(t,`\\${t}`);return e}function Cs(e,t,r){let n=f(e,t,r),o=n.format||er,i=n.onNull||null,s=n.dateString;if(y(s))return i;let a=o.split(Gn);a.reverse();let c=o.match(rr),p={},m="";for(let d=0,g=c.length;d<g;d++){let E=c[d],I=ie[E];if(h(I)){let P=I.re.exec(s),F=a.pop()||"";P!==null?(p[I.name]=/^\d+$/.exec(P[0])?parseInt(P[0]):P[0],s=s.substring(P.index+P[0].length+1),m+=Ss(F)+ws(I.re.toString())):p[I.name]=null}}if(y(p.month)){let d=(p.full_month?.slice(0,3)??p.abbr_month??"").toLowerCase();Pr[d]&&(p.month=Pr[d])}if(y(p.year)||y(p.month)||y(p.day)||!new RegExp("^"+m+"[A-Z]?$").test(n.dateString))return n.onError;let O=n.dateString.match(/([A-Z])$/);u(!(O&&n.timezone),`$dateFromString: you cannot pass in a date/time string with time zone information ('${O&&O[0]}') together with a timezone argument`);let A=O?vs(O[0])*_t:lt(n.timezone,new Date),b=new Date(Date.UTC(p.year,p.month-1,p.day,0,0,0));return y(p.hour)|