@dcupl/common 2.0.0-beta.0 → 2.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("lodash-es");function Q(o){const e=D(o);return Y(e)}function D(o){if(typeof o!="object"||o===null)return String(o);if(Array.isArray(o))return"["+o.map(D).join(",")+"]";const e=Object.keys(o).sort();let t="{";for(let r=0;r<e.length;r++){const s=e[r];t+=s+":"+D(o[s]),r<e.length-1&&(t+=",")}return t+="}",t}function Y(o){let e=0;for(let t=0;t<o.length;t++){const r=o.charCodeAt(t);e=(e<<5)-e+r,e|=0}return e.toString(16)}const v={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:o=>{typeof performance<"u"&&performance.mark&&performance.mark(o)},measure:(o,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(o,e,t)},getEntriesByName(o){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(o)},getEntriesByType(o){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(o)}};class X{data;enabled=!1;constructor(){}init(e){this.data=new Map,this.enabled=e}set(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context);return this.data.set(t,e.value),this.data.get(t)}mark(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),r={name:e.name,type:"mark",value:v.now(),createdAt:Date.now()};return this.data.set(t,r),r}measure(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),r=this.data.get(this.getKey(e.start,e.context)),s=this.data.get(this.getKey(e.end,e.context));if(!r||!s)return;const i=s.value-r.value,n=Math.round(i*100)/100,a=this.data.get(t);if(a&&e.sum){const c=a.value+n,d={...a,value:c};return this.data.set(t,d),d}const u={name:e.name,type:"measure",value:n,createdAt:Date.now()};return e.detail&&(u.detail=e.detail),this.data.set(t,u),u}update(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context),r=this.data.get(t);if(r){const s={...r,...e.value};this.data.set(t,s)}else this.data.set(t,e.value);return this.data.get(t)}getResourceInfosFromPerformanceAPI(){return typeof performance>"u"?[]:v.getEntriesByType("resource")}get(e){const t=this.getKey(e.name,e.context);return this.data.get(t)}getByType(e){return Array.from(this.data.values()).filter(t=>t.type===e)}getByName(e){return Array.from(this.data.values()).filter(t=>t.name===e)}clear(){this.data.clear()}getKey(e,t){if(!t)return e;const r=Q(t);return e+"_"+r}}let F=class T{nodes;edges;nodeKinds=new Map;nodeMeta=new Map;edgePolicy;constructor(){this.nodes=new Set,this.edges=new Map}addNode(e,t){this.nodes.has(e)||(this.nodes.add(e),this.edges.set(e,new Set)),t?.kind!==void 0&&this.nodeKinds.set(e,t.kind),t?.meta!==void 0&&this.nodeMeta.set(e,t.meta)}addDependency(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))throw new Error("Both nodes must exist before adding a dependency.");if(this.edgePolicy&&!this.edgePolicy({name:e,kind:this.nodeKinds.get(e)},{name:t,kind:this.nodeKinds.get(t)}))throw new Error(`Edge policy rejected dependency from "${e}" to "${t}".`);this.edges.get(e).add(t)}setEdgePolicy(e){this.edgePolicy=e}setNodeKind(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");t===void 0?this.nodeKinds.delete(e):this.nodeKinds.set(e,t)}getNodeKind(e){return this.nodeKinds.get(e)}setNodeMeta(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodeMeta.set(e,t)}getNodeMeta(e){return this.nodeMeta.get(e)}removeNode(e){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodes.delete(e),this.edges.delete(e);for(let t of this.edges.values())t.delete(e)}removeDependency(e,t){if(!this.edges.has(e))throw new Error("From node does not exist.");this.edges.get(e).delete(t)}hasNode(e){return this.nodes.has(e)}hasDependency(e,t){return this.edges.has(e)?this.edges.get(e).has(t):!1}getDependencies(e){if(!this.edges.has(e))throw new Error("Node does not exist.");return Array.from(this.edges.get(e))}getDependents(e){const t=[];for(let[r,s]of this.edges)s.has(e)&&t.push(r);return t}isCyclic(){const e=new Set,t=new Set,r=s=>{if(e.has(s))return!1;if(t.has(s))return!0;t.add(s);const i=this.edges.get(s);if(i){for(let n of i)if(r(n))return!0}return t.delete(s),e.add(s),!1};for(let s of this.nodes)if(r(s))return!0;return!1}validateNoCycles(){const e=new Set,t=new Set,r=[],s=i=>{if(e.has(i))return null;if(t.has(i)){const a=r.indexOf(i);return r.slice(a).concat([i])}t.add(i),r.push(i);const n=this.edges.get(i);if(n)for(let a of n){const u=s(a);if(u)return u}return r.pop(),t.delete(i),e.add(i),null};for(let i of this.nodes){const n=s(i);if(n)return{hasCycle:!0,path:n}}return{hasCycle:!1}}order(e){const t=new Set,r=new Set,s=[],i=e?.allowCycles??!1,n=a=>{if(t.has(a))return;if(r.has(a)){if(i)return;throw new Error("Graph has a cycle.")}r.add(a);const u=this.edges.get(a);if(u)for(let c of u)n(c);r.delete(a),t.add(a),s.push(a)};for(let a of this.nodes)t.has(a)||n(a);return s}clear(){this.nodes.clear(),this.edges.clear()}getNodes(){return Array.from(this.nodes)}getAllEdges(){const e=[];for(let[t,r]of this.edges)for(let s of r)e.push([t,s]);return e}getNodesWithNoDependants(){if(this.nodes.size===0)return[];const e=new Set;for(const r of this.edges.values())for(const s of r)e.add(s);const t=[];for(const r of this.nodes)e.has(r)||t.push(r);return t}getNodesByKind(e){const t=[];for(const r of this.nodes)this.nodeKinds.get(r)===e&&t.push(r);return t}getRootsByKind(e){const t=new Set(this.getNodesWithNoDependants()),r=Array.from(t);return e?r.filter(s=>this.nodeKinds.get(s)===e):r}getLeavesByKind(e){const t=[];for(const r of this.nodes){const s=this.edges.get(r);(!s||s.size===0)&&(!e||this.nodeKinds.get(r)===e)&&t.push(r)}return t}getDependenciesOfKind(e,t){return this.getDependencies(e).filter(s=>this.nodeKinds.get(s)===t)}getDependentsOfKind(e,t){return this.getDependents(e).filter(s=>this.nodeKinds.get(s)===t)}plan(e){const t=new Map;for(const n of this.nodes)t.set(n,0);for(const n of this.edges.values())for(const a of n)t.set(a,(t.get(a)||0)+1);const r=[];let s=Array.from(this.nodes).filter(n=>(t.get(n)||0)===0);const i=new Set;for(;s.length>0;){const n=s.slice();r.push(n),s=[];for(const a of n){if(i.has(a))continue;i.add(a);const u=this.edges.get(a);if(u)for(const c of u)t.set(c,(t.get(c)||0)-1),(t.get(c)||0)===0&&s.push(c)}}if(i.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const n=new Set(e.filterKinds);return{batches:r.map(a=>a.filter(u=>n.has(this.nodeKinds.get(u))))}}return{batches:r}}getImpactedNodes(e,t="downstream",r){const s=new Set(e),i=c=>!r||r.length===0||r.includes(this.nodeKinds.get(c)??void 0),n=()=>{const c=new Set,d=Array.from(s);for(;d.length;){const f=d.shift();for(const[l,p]of this.edges)p.has(f)&&!c.has(l)&&(c.add(l),d.push(l))}return c},a=()=>{const c=new Set,d=Array.from(s);for(;d.length;){const f=d.shift(),l=this.edges.get(f);if(l)for(const p of l)c.has(p)||(c.add(p),d.push(p))}return c};let u;return t==="both"?u=new Set([...n(),...a()]):t==="upstream"?u=a():u=n(),Array.from(u).filter(i)}toJSON(){const e=Array.from(this.nodes).map(r=>({name:r,kind:this.nodeKinds.get(r),meta:this.nodeMeta.get(r)})),t=this.getAllEdges().map(([r,s])=>({from:r,to:s}));return{nodes:e,edges:t}}static fromJSON(e){const t=new T;for(const r of e.nodes)t.addNode(r.name,{kind:r.kind,meta:r.meta});for(const r of e.edges)t.addDependency(r.from,r.to);return t}diff(e){const t=new Set(this.getNodes()),r=new Set(e.getNodes()),s=Array.from(r).filter(f=>!t.has(f)),i=Array.from(t).filter(f=>!r.has(f)),n=new Set(this.getAllEdges().map(f=>f.join("→"))),a=new Set(e.getAllEdges().map(f=>f.join("→"))),u=Array.from(a).filter(f=>!n.has(f)).map(f=>f.split("→")),c=Array.from(n).filter(f=>!a.has(f)).map(f=>f.split("→")),d=[];for(const f of new Set([...t,...r])){const l=this.nodeKinds.get(f),p=e.nodeKinds.get(f);l!==p&&d.push({name:f,from:l,to:p})}return{addedNodes:s,removedNodes:i,addedEdges:u,removedEdges:c,kindChanges:d}}};class ee{graph;nodeIndex;constructor(){this.graph=new F,this.nodeIndex=new Map}getNodeId(e,t){return`${e}.${t}`}parseNodeId(e){const t=e.split(".");return{modelKey:t[0],attributeKey:t.slice(1).join(".")}}addAttribute(e){const t=this.getNodeId(e.modelKey,e.attributeKey);this.nodeIndex.has(t)||(this.graph.addNode(t,{meta:e}),this.nodeIndex.set(t,e))}addAttributeDependency(e,t){this.addAttribute(e),this.addAttribute(t);const r=this.getNodeId(e.modelKey,e.attributeKey),s=this.getNodeId(t.modelKey,t.attributeKey);this.graph.hasDependency(r,s)||this.graph.addDependency(r,s)}getImpactedAttributes(e){const t=e.map(a=>this.getNodeId(a.modelKey,a.attributeKey)),s=this.graph.getImpactedNodes(t,"downstream").map(a=>this.nodeIndex.get(a)).filter(a=>a!==void 0),i=[...e,...s],n=new Set;return i.filter(a=>{const u=this.getNodeId(a.modelKey,a.attributeKey);return n.has(u)?!1:(n.add(u),!0)})}getProcessingOrder(e){const t=new Map,r=[...e].sort((s,i)=>s.processingStep-i.processingStep);for(const s of r){const{modelKey:i,attributeKey:n,processingStep:a}=s;t.has(i)||t.set(i,new Map);const u=t.get(i);u.has(a)||u.set(a,new Set),u.get(a).add(n)}return t}getAttributesForModel(e){const t=[];for(const r of this.nodeIndex.values())r.modelKey===e&&t.push(r);return t}getDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}getDependents(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependents(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}hasDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).length>0:!1}hasNode(e){return this.nodeIndex.has(e)}getAllAttributes(){return Array.from(this.nodeIndex.values())}getMaxDepth(){let e=0;const t=(r,s=new Set)=>{if(s.has(r))return 0;s.add(r);const i=this.graph.getDependencies(r);if(i.length===0)return 1;let n=0;for(const a of i){const u=t(a,new Set(s));n=Math.max(n,u)}return n+1};for(const r of this.graph.getNodes()){const s=t(r);e=Math.max(e,s)}return e}validateCompleteness(e){const t=[];for(const[r,s]of e)for(const i of s){const n=this.getNodeId(r,i);this.hasNode(n)||t.push({modelKey:r,attributeKey:i})}return{isComplete:t.length===0,missing:t}}clear(){this.graph.clear(),this.nodeIndex.clear()}getStats(){const e=new Map,t=new Map;for(const r of this.nodeIndex.values())e.set(r.modelKey,(e.get(r.modelKey)||0)+1),t.set(r.processingStep,(t.get(r.processingStep)||0)+1);return{totalAttributes:this.nodeIndex.size,totalDependencies:this.graph.getAllEdges().length,maxDepth:this.getMaxDepth(),attributesByModel:e,attributesByStep:t}}toJSON(){return{nodes:Array.from(this.nodeIndex.values()),edges:this.graph.getAllEdges().map(([e,t])=>{const r=this.parseNodeId(e),s=this.parseNodeId(t);return{from:r,to:s}})}}}const q={silent:0,error:1,warn:2,info:3,debug:4};class g{config;static globalConfig={};constructor(e={}){this.config={level:e.level??g.globalConfig.level??this.getDefaultLevel(),format:e.format??g.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??g.globalConfig.onLog,onTrackError:e.onTrackError??g.globalConfig.onTrackError}}static setGlobalConfig(e){g.globalConfig={...g.globalConfig,...e}}static getGlobalConfig(){return{...g.globalConfig}}static setModuleLevel(e,t){g.globalConfig.onLog||(g.globalConfig.onLog=void 0),g._moduleOverrides||(g._moduleOverrides=new Map),g._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!g._moduleOverrides))return g._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=g.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return q[e]<=q[t]}formatMessage(e){if(this.config.format==="json"){const n={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(n.module=e.prefix),e.context&&(n.context=e.context),e.error&&(n.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(n)}const t=new Date(e.timestamp).toISOString().substring(11,23),r=e.prefix?`[${e.prefix}]`:"",s=this.getLevelIcon(e.level),i=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${s} ${r} ${e.message}${i}`.trim()}getLevelIcon(e){switch(e){case"error":return"✖";case"warn":return"⚠";case"info":return"ℹ";case"debug":return"⚙";default:return" "}}log(e,t,r,s){if(!this.shouldLog(e))return;const i={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:r,error:s};if(this.config.onLog){this.config.onLog(i);return}const n=this.formatMessage(i);if(typeof console<"u")switch(e){case"error":s?console.error(n,s):console.error(n);break;case"warn":console.warn(n);break;case"debug":console.debug?console.debug(n):console.log(n);break;default:console.log(n)}}error(e,t,r){const s=t instanceof Error?t:void 0,i=t instanceof Error?r:t;this.log("error",e,i,s)}trackError(e,t,r){if(this.error(e,t,r?.context),this.config.onTrackError){const s={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:r?.context,error:t,errorType:r?.errorType,errorGroup:r?.errorGroup};this.config.onTrackError(s)}}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}child(e){const t={...this.config,...e,prefix:e.prefix?this.config.prefix?`${this.config.prefix}:${e.prefix}`:e.prefix:this.config.prefix};return new g(t)}configure(e){Object.assign(this.config,e)}}const G=new g;class te{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}cache;cacheDependencies;hitCount=0;missCount=0;log=G.child({prefix:"CacheController"});get(e,t){if(!this.enabled)return;const r=this.getCacheName(e,t);return this.cache.has(r)?this.hitCount++:this.missCount++,this.cache.get(r)}set(e,t,r,s){if(!this.enabled)return;const i=this.getCacheName(e,t);this.cache.set(i,r),s?this.cacheDependencies.set(i,s):this.log.debug(`Cache entry '${e}' stored without dependencies. This prevents granular invalidation and may cause stale data.`)}has(e,t){return this.cache.has(this.getCacheName(e,t))}clear(){this.cache.clear(),this.cacheDependencies.clear(),this.hitCount=0,this.missCount=0}invalidateByDependencies(e){if(!this.enabled)return;const t=[];for(const[r,s]of this.cacheDependencies){let i=!1;for(const[n,a]of e){if(s.models.has(n))if(s.modelAttributes.has(n)){const u=s.modelAttributes.get(n);for(const c of a)if(u.has(c)){i=!0;break}}else i=!0;if(i)break}i&&t.push(r)}for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}invalidateByModels(e){if(!this.enabled)return;const t=new Set(e),r=[];for(const[s,i]of this.cacheDependencies)for(const n of t)if(i.models.has(n)){r.push(s);break}for(const s of r)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateByKeyPrefix(e){if(!this.enabled)return;const t=[];for(const r of this.cache.keys())r.startsWith(e+"_")&&t.push(r);for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}invalidateForModel(e){this.invalidateByModels([e])}invalidateForAttribute(e,t){if(!this.enabled)return;const r=new Map;r.set(e,new Set([t])),this.invalidateByDependencies(r)}invalidateMatching(e){if(!this.enabled)return;const t=[];for(const r of this.cache.keys())e(r)&&t.push(r);for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}generateContext(e){try{return h.cloneDeep(e)}catch(t){return this.log.error("Error in cache generateContext",t),e}}getCacheName(e,t){const r=Q(t);return e+"_"+r}getStats(){const e=this.hitCount+this.missCount,t=e>0?this.hitCount/e:0;return{size:this.cache.size,hitRate:t,totalEntries:this.cache.size,entriesWithDependencies:this.cacheDependencies.size,hits:this.hitCount,misses:this.missCount}}}const re=(o,e="")=>`${o}#${e}`,se=o=>`${o.gt}_${o.gte}_${o.lt}_${o.lte}_${o.eq}_${o.ne}`,ne=o=>`${o.gt}_${o.gte}_${o.lt}_${o.lte}_${o.eq}_${o.ne}`,ie=(o,e)=>{const t=typeof e=="function"?e:r=>r[e];return[...o.reduce((r,s)=>{const i=s==null?s:t(s);return r.has(i)||r.set(i,s),r},new Map).values()]},oe=(o,e)=>o.reduce(function(t,r){const s=typeof e=="function"?e(r):r[e];return Object.prototype.hasOwnProperty.call(t,s)||(t[s]=[]),t[s].push(r),t},{});function B(o=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let r=0;r<o;r++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}const ae=o=>o.replace(/\/+$/,""),P=o=>typeof o!="string"?"":o.replace(/[[\]{}()*+?.,\\^$|#]/g,"\\$&"),ue=o=>typeof o!="string"?"":o.replace(/\\([[\]{}()*+?.,\\^$|#])/g,"$1"),ce=(o,e)=>{try{return j(o,e)>=0}catch{return!1}},j=(o,e)=>{if(!S(o)||!S(e))throw new Error(`Invalid version format: v1="${o}", v2="${e}". Expected format: "x.y.z"`);const t=o.split(".").map(Number),r=e.split(".").map(Number);for(let s=0;s<3;s++){const i=t[s]||0,n=r[s]||0;if(i>n)return 1;if(i<n)return-1}return 0},S=o=>/^\d+(\.\d+){0,2}$/.test(o);class de{key;parentCd;dcuplInitOptions;analyticsController;off;updateListener=new Set;counter=0;constructor(){}_init(e){this.key=e.cdRefKey,this.analyticsController=e.analyticsController,this.parentCd=e.parentCd,this.dcuplInitOptions=e.dcuplInitOptions,this.parentCd&&(this.off=this.parentCd.on(t=>{t.action==="update"&&t.originCdRefKey===this.parentCd?.key&&(t.connectMessage=!1,this.trigger(t))}))}getCounter(){return this.parentCd?this.parentCd.getCounter():this.counter}increaseCounter(){this.parentCd?this.parentCd.increaseCounter():this.counter++}destroy(){this.off&&this.off()}trigger(e){e.originCdRefKey||(e.originCdRefKey=this.key),e.key||(this.increaseCounter(),e.key=this.getCounter()),e.end||(e.end=v.now(),e.duration=e.start-e.end),this.updateListener.forEach(t=>{t(e)})}on(e){return this.updateListener.add(e),()=>{this.updateListener.delete(e)}}}const I=(o,e)=>e?typeof structuredClone<"u"?structuredClone(o):h.cloneDeep(o):o,O=(o,e,t,r,s,i)=>{try{const n=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=I(i,n);if(t.scope==="list"&&(t.listKey=o.cdRef?.key||o.key,t.modelKey=o.model?.key||o.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const u=v.now(),c=u-r,d=Math.round(c*1e3)/1e3;t.duration=d,t.start=r,t.end=u;const f={duration:t.duration};return t.modelKey&&(f.model=t.modelKey),t.connectMessageResult&&(t.result=a),t.args&&(f.args=t.args),e?.trigger(t),e.analyticsController.mark({name:`${t.type}:end`,context:s}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:s,detail:f}),a}catch{return i}},fe=o=>(t,r,s)=>{const i=s.value;return s.value=function(...n){const a=v.now(),u=this.cdRef,c=I(o,!0);c.key||(u.increaseCounter(),c.key=u.getCounter());const d=B();u.analyticsController.mark({name:`${c.type}:start`,context:d});const f=this.model?.key;!c.originCdRefKey&&u.key&&(c.originCdRefKey=u.key),f&&(c.modelKey=f);const l=i.apply(this,n);return c.method=r,c.args=n,l&&typeof l=="object"&&"then"in l?l.then(p=>O(this,u,c,a,d,p)):O(this,u,c,a,d,l)},s};function le(o,e,t,r){t.max||(t.max=20);const s=[],i=t.transform?r.transformValue(t.value,t.transform):t.value;for(const[n,a]of e.entries()){const u=Array.from(a).some(d=>o.has(d)),c=t.transform?r.transformValue(n,t.transform):n;if(!(t.excludeUndefineds&&typeof n>"u")&&!(t.excludeNulls&&n===null)){if(u&&(i===""||i==="//")){const d={value:n,keys:t.calculateResultKeys?Array.from(a):[]};s.push(d)}else if(u&&typeof i=="string"&&i.startsWith("/")&&i.endsWith("/")){if(r.queryFind(c,i,"some")){const d={value:n,keys:t.calculateResultKeys?Array.from(a):[]};s.push(d)}}else if(u&&typeof i=="string"){const d=String(c??""),f=i;if(d.toLowerCase().startsWith(f.toLowerCase())){const l={value:n,keys:t.calculateResultKeys?Array.from(a):[]};s.push(l)}}else if(u&&r.queryFind(c,i,"some")){const d={value:n,keys:t.calculateResultKeys?Array.from(a):[]};s.push(d)}if(s.length===t.max)break}}return s}function R(o){return o instanceof Date}function z(o){return o instanceof Date&&!isNaN(o.getTime())}const he={yyyy:{type:"year",pattern:"yyyy",regex:"(\\d{4})"},yy:{type:"year",pattern:"yy",regex:"(\\d{2})"},MM:{type:"month",pattern:"MM",regex:"(\\d{2})"},M:{type:"month",pattern:"M",regex:"(\\d{1,2})"},dd:{type:"day",pattern:"dd",regex:"(\\d{2})"},d:{type:"day",pattern:"d",regex:"(\\d{1,2})"},HH:{type:"hour",pattern:"HH",regex:"(\\d{2})"},H:{type:"hour",pattern:"H",regex:"(\\d{1,2})"},mm:{type:"minute",pattern:"mm",regex:"(\\d{2})"},m:{type:"minute",pattern:"m",regex:"(\\d{1,2})"},ss:{type:"second",pattern:"ss",regex:"(\\d{2})"},s:{type:"second",pattern:"s",regex:"(\\d{1,2})"},SSS:{type:"millisecond",pattern:"SSS",regex:"(\\d{3})"}};function pe(o){let e="^";const t=[];let r=o;const s=Object.entries(he).sort((i,n)=>n[0].length-i[0].length);for(;r.length>0;){let i=!1;for(const[n,a]of s)if(r.startsWith(n)){e+=a.regex,t.push({type:a.type,pattern:n}),r=r.slice(n.length),i=!0;break}if(!i){const n=r[0];if(!n)break;e+=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=r.slice(1)}}return e+="$",{regex:new RegExp(e),tokenOrder:t}}function ge(o,e){const t={year:1970,month:1,day:1,hour:0,minute:0,second:0,millisecond:0};for(let r=0;r<e.length;r++){const s=o[r+1];if(!s)continue;const i=parseInt(s,10),n=e[r];n&&(n.type==="year"&&n.pattern==="yy"?t.year=2e3+i:t[n.type]=i)}return t}function ye(o){if(o.month<1||o.month>12)return new Date(NaN);if(o.day<1||o.day>31)return new Date(NaN);if(o.hour<0||o.hour>23)return new Date(NaN);if(o.minute<0||o.minute>59)return new Date(NaN);if(o.second<0||o.second>59)return new Date(NaN);if(o.millisecond<0||o.millisecond>999)return new Date(NaN);const e=new Date(o.year,o.month-1,o.day,o.hour,o.minute,o.second,o.millisecond);return z(e)?e.getFullYear()!==o.year||e.getMonth()!==o.month-1||e.getDate()!==o.day?new Date(NaN):e:new Date(NaN)}function me(o,e,t){if(o=o.trim(),e==="t"){const a=Number(o);return isNaN(a)?new Date(NaN):new Date(a*1e3)}if(e==="T"){const a=Number(o);return isNaN(a)?new Date(NaN):new Date(a)}const{regex:r,tokenOrder:s}=pe(e),i=o.match(r);if(!i)return new Date(NaN);const n=ge(i,s);return ye(n)}class ve{cache;maxSize;accessOrder;constructor(e){this.cache=new Map,this.maxSize=e,this.accessOrder=[]}get(e){const t=this.cache.get(e);return t!==void 0&&this.updateAccessOrder(e),t}set(e,t){if(this.cache.has(e))this.cache.set(e,t),this.updateAccessOrder(e);else{if(this.cache.size>=this.maxSize){const r=this.accessOrder.shift();r!==void 0&&this.cache.delete(r)}this.cache.set(e,t),this.accessOrder.push(e)}}has(e){return this.cache.has(e)}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}updateAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e)}getStats(){return{size:this.cache.size,maxSize:this.maxSize}}}class we{graph;constructor(){this.graph=new Map}addDependency(e,t){this.graph.has(e)||this.graph.set(e,new Set),this.graph.get(e).add(t)}hasCycle(e){if(e.length===0)return!1;const t=new Set,r=new Set,s=i=>{t.add(i),r.add(i);const n=this.graph.get(i);if(n){for(const a of n)if(t.has(a)){if(r.has(a))return!0}else if(s(a))return!0}return r.delete(i),!1};for(let i=0;i<e.length-1;i++){const n=e[i],a=e[i+1];n&&a&&this.addDependency(n,a)}for(const i of e)if(!t.has(i)&&s(i))return!0;return!1}clear(){this.graph.clear()}}class _{parseCache;circularRefDetector;cacheHits=0;cacheMisses=0;constructor(e=1e3){this.parseCache=new ve(e),this.circularRefDetector=new we}parse(e){if(this.parseCache.has(e))return this.cacheHits++,this.parseCache.get(e);this.cacheMisses++;let t,r;const s=e.includes("."),i=e.includes("["),n=s||i;if(n)if(r=e.split(/[.[]/)[0],i){const u=e.indexOf("]");if(u>-1){const c=e.indexOf(".",u+1);c>-1?t=e.substring(c+1):t=void 0}else s&&(t=e.substring(e.indexOf(".")+1))}else s&&(t=e.substring(e.indexOf(".")+1));const a={attribute:e,isDeepQuery:n};return r&&(a.reference=r),typeof t<"u"&&t!==""&&(a.referenceAttribute=t),this.parseCache.set(e,a),a}detectCircular(e){return e.length===0?!1:new Set(e).size!==e.length?!0:this.circularRefDetector.hasCycle(e)}validatePath(e,t=10){const r=[];if(!e||e.trim().length===0)return r.push("Attribute path cannot be empty"),{valid:!1,errors:r};(e.startsWith(".")||e.endsWith("."))&&r.push(`Invalid path: Leading or trailing dots are not allowed: ${e}`),e.includes("..")&&r.push(`Invalid path: Consecutive dots are not allowed: ${e}`);const s=(e.match(/\[/g)||[]).length,i=(e.match(/]/g)||[]).length;s!==i&&r.push(`Invalid bracket notation: Mismatched brackets in ${e}`),e.includes("[]")&&r.push(`Invalid bracket notation: Empty brackets not allowed: ${e}`);const n=/\[([^\]]+)\]/g;let a;for(;(a=n.exec(e))!==null;){const d=a[1];d&&d!=="*"&&!/^\d+$/.test(d)&&r.push(`Invalid bracket content: Must be a number or '*', got '${d}' in ${e}`)}const u=(e.match(/\./g)||[]).length+1;u>t&&r.push(`Path too deep: Maximum depth is ${t}, got ${u} in ${e}`);const c=e.match(/[^a-zA-Z0-9._[\]*-]/g);return c&&r.push(`Invalid characters in path: ${c.join(", ")} in ${e}`),{valid:r.length===0,errors:r.length>0?r:void 0}}clearCache(){this.parseCache.clear(),this.cacheHits=0,this.cacheMisses=0}clearCircularDetector(){this.circularRefDetector.clear()}getCacheStats(){const e=this.parseCache.getStats(),t=this.cacheHits+this.cacheMisses,r=t>0?this.cacheHits/t:0;return{...e,hits:this.cacheHits,misses:this.cacheMisses,hitRate:r}}getPathSegments(e){return e.replace(/\[[^\]]+\]/g,"").split(".").filter(r=>r.length>0)}getPathDepth(e){return this.getPathSegments(e).length}}const y=new _;function b(o){let e=0;for(let t of o){const r=t.toString().split(".")[1];r&&(e=Math.max(e,r.length))}return Math.pow(10,e)}function $(o,e,t){return(o*t+e*t)/t}function xe(o,e,t){return o*t/(e*t)}const A=(o,e,t,r)=>{if(!r)throw new Error("Attribute not found");const s={attribute:r,types:o.types};let i;(s.types.includes("sum")||s.types.includes("avg")||s.types.includes("count"))&&(i=De(r,e));let n;return(s.types.includes("min")||s.types.includes("max"))&&(n=Ae(r,e)),o.types.forEach(a=>{a==="sum"?s.sum=i?.sum:a==="avg"?s.avg=i?.average:a==="count"?s.count=i?.count:a==="min"?s.min=n&&n[0]:a==="max"?s.max=n&&n[1]:a==="distinct"?s.distinct=W(o,e,t):a==="group"&&(s.group=be(o,e))}),s},Ae=(o,e)=>{let t,r;const i=y.parse(o).isDeepQuery;for(const n of e.values())if(n){const a=i?h.get(n,o):n[o];(t===void 0||a<t)&&(t=a),(r===void 0||a>r)&&(r=a)}if(!(t===void 0||r===void 0))return[t,r]},be=(o,e)=>{const t=[];o.groupOptions?.groups?.forEach(n=>{t.push({option:n,count:0,keys:[]})});const r={option:{value:["$dcupl_not_found"]},count:0,keys:[]},i=y.parse(o.attribute).isDeepQuery;for(const n of e.values()){const a=i?h.get(n,o.attribute):n[o.attribute];for(const u of t)typeof u.option.value<"u"&&u.option.value.includes(a)||typeof u.option.from<"u"&&u.option.from<a&&typeof u.option.to<"u"&&u.option.to>a?(u.count++,u.keys.push(n.key)):o?.groupOptions?.calculateNotFound&&(r.count++,r.keys.push(n.key))}return o?.groupOptions?.calculateNotFound&&t.push(r),t},De=(o,e)=>{let t=0,r=0;const i=y.parse(o).isDeepQuery;for(const u of e.values()){if(!u)continue;const c=i?h.get(u,o):u[o];if(Array.isArray(c))for(const d of c)typeof d=="number"&&(t=$(t,d,b([t,d])),r++);else typeof c=="number"&&(t=$(t,c,b([t,c])),r++)}return r===0||r===0?void 0:{average:xe(t,r,b([t,r])),count:e.size,sum:t}},W=(o,e,t)=>{const r=[];for(const[s,i]of t)if(!(o.excludeUndefineds&&typeof s>"u")&&Array.from(i).find(n=>e.has(n))){const n={value:s,count:i.size};if(o.distinctOptions?.skipKeys||(n.keys=Array.from(i)),r.push(n),o.distinctOptions?.limit&&r.length>=o.distinctOptions.limit)break}return r};class w extends Error{query;constructor(e,t){const r=`Query Error: ${e} in ${JSON.stringify(t,null,2)}`;super(r),this.query=t,this.name="DcuplQueryError"}}class M{_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=h.cloneDeep(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||y}init(e){this._initOptions=h.cloneDeep(e),this.currentQuery=h.cloneDeep(this._defaultQueryOptions),this.currentQuery.modelKey=e.modelKey,"queries"in e&&Array.isArray(e.queries)&&(e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&(this.currentQuery.queries=h.cloneDeep(e.queries)),e.count!==void 0&&(this.currentQuery.count=e.count),e.start!==void 0&&(this.currentQuery.start=e.start),e.sort&&(this.currentQuery.sort=e.sort),e.projection&&(this.currentQuery.projection=e.projection))}reset(){return this.init(this._initOptions),this.getQuery()}isQuery(e){return"attribute"in e}isQueryGroup(e){return"groupKey"in e}isRootQueryGroup(e){return this.isQueryGroup(e)&&e.groupKey==="root"}getQueryGroup(e){return this.currentQuery.queries.find(t=>this.isQueryGroup(t)&&t.groupKey===e)}getQuery(){return h.cloneDeep(this.currentQuery)}hasQueryGroup(e){return this.currentQuery.queries.some(t=>this.isQueryGroup(t)&&t.groupKey===e)}has(e){if(e.groupKey&&e.queryKey){const t=this.getQueryGroup(e.groupKey);if(t)return t.queries.some(r=>this.isQuery(r)&&r.queryKey===e.queryKey)}else if(e.groupKey)return this.hasQueryGroup(e.groupKey);return!1}validate(e){const t=e.queries.map(s=>this.validateQuery(s));return{valid:h.every(t,s=>s.valid),errors:t.map(s=>s.errors).flat()}}applyOptions(e,t="update"){return t==="set"?(this.currentQuery.count=e.count,this.currentQuery.start=e.start,this.currentQuery.sort=e.sort,this.currentQuery.projection=e.projection):(typeof e?.sort<"u"&&(this.currentQuery.sort=e.sort),typeof e?.count<"u"&&(this.currentQuery.count=e.count),typeof e?.start<"u"&&(this.currentQuery.start=e?.start),typeof e?.projection<"u"&&(this.currentQuery.projection=e?.projection)),this.getQuery()}applyQuery(e,t,r){if(r||(r=this.currentQuery),Array.isArray(e))for(const s of e)this.applyQuery(s,t,r);else if(this.isRootQueryGroup(e))e.groupType&&(r.groupType=e.groupType),t?.mode==="set"?r.queries=e.queries:r.queries=[...r.queries,...e.queries],this.applyOptions(e,"set");else if(this.isQuery(e)){const s=r.queries.findIndex(i=>this.isQueryGroup(i)&&i.groupKey===e.attribute);if(s>-1){const i=r.queries[s];t?.mode==="set"?i.queries=[e]:i.queries.push(e)}else r.queries.push({groupKey:e.attribute,groupType:"or",queries:[e]})}else if(this.isQueryGroup(e)){const s=r.queries.findIndex(i=>this.isQueryGroup(i)&&i.groupKey===e.groupKey);if(s>-1){const i=r.queries[s];e.groupType&&(i.groupType=e.groupType),t?.mode==="set"?r.queries[s]=e:i.queries=[...i.queries,...e.queries]}else r.queries.push({groupKey:e.groupKey,groupType:e.groupType||"or",queries:e.queries})}return r}removeAllQueries(){return this.currentQuery.queries=[],this.getQuery()}removeQuery(e,t){if(t||(t=this.currentQuery),this.isQuery(e)){const r=t.queries.findIndex(s=>this.isQueryGroup(s)&&s.groupKey===e.attribute);if(r>-1){const s=t.queries[r],i=h.findIndex(s.queries,e);i>-1&&s.queries.splice(i,1),s.queries.length===0&&t.queries.splice(r,1)}}else if(this.isQueryGroup(e)){const r=t.queries.findIndex(s=>this.isQueryGroup(s)&&s.groupKey===e.groupKey);if(r>-1)if(!e.queries)t.queries.splice(r,1);else{const s=t.queries[r];for(const i of e.queries){const n=h.findIndex(s.queries,i);n>-1&&s.queries.splice(n,1)}s.queries.length===0&&t.queries.splice(r,1)}}return t}validateQuery(e){const t=[];if(this.isQuery(e))return e.attribute||t.push(new w("Missing attribute",e)),e.operator||t.push(new w("Missing operator",e)),typeof e.value>"u"&&t.push(new w("Missing value",e)),e.operator==="find"&&Array.isArray(e.value)&&t.push(new w("find operator cannot have array value",e)),t.length>0?{valid:!1,errors:t}:{valid:!0};if(this.isQueryGroup(e)){const i=e.queries.map(n=>this.validateQuery(n)).filter(n=>!n.valid).map(n=>n.errors).flat();return i.length>0?{valid:!1,errors:i}:{valid:!0}}return t.push(new w("Invalid query definition",e)),{valid:!1,errors:t}}getQueryAttributes(e){const t=[],r=new Set,s=i=>{for(const n of i)this.isQuery(n)?n.attribute&&!r.has(n.attribute)&&(t.push(n.attribute),r.add(n.attribute)):this.isQueryGroup(n)&&s(n.queries)};return s(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],r=new Set,s=i=>{for(const n of i)if(this.isQuery(n)){if(n.attribute&&!r.has(n.attribute)){const a=this.getQueryAttributeForString(n.attribute);t.push(a),r.add(n.attribute)}}else this.isQueryGroup(n)&&s(n.queries)};return s(e?.queries||this.currentQuery.queries),t}getQueryAttributeForString(e){return this.deepQueryService.parse(e)}getDeepQueryService(){return this.deepQueryService}getProjectionForAttributes(e){const t={};return e.forEach(r=>{t[r]=!0}),t}getProjectionForAttributeEntries(e){const t={$:!0};return e.forEach(r=>{if(r.isDeepQuery){if(r.reference)if(r.referenceAttribute&&r.referenceAttribute.length>0){t[r.reference]||(t[r.reference]={$:!0});const s=this.deepQueryService.parse(r.referenceAttribute);if(s.isDeepQuery&&r.reference){const i=this.getProjectionForAttributeEntries([s]);Object.keys(i).forEach(n=>{n!=="$"&&r.reference&&(t[r.reference][n]=i[n])})}else r.reference&&(t[r.reference][r.referenceAttribute]=!0)}else t[r.reference]=!0}else t[r.attribute]=!0}),t}getAttributeNames(e){return this.getQueryAttributes(e)}getAttributeDetails(e){return this.extractQueryAttributes(e||this.currentQuery)}getCurrentAttributeNames(){return this.getAttributeNames(this.currentQuery)}getCurrentAttributeDetails(){return this.getAttributeDetails(this.currentQuery)}addCondition(e){return this.applyQuery(e,{mode:"add"})}addGroup(e){return this.applyQuery(e,{mode:"add"})}setCondition(e){return this.applyQuery(e,{mode:"set"})}setGroup(e){return this.applyQuery(e,{mode:"set"})}mergeQuery(e){if(e.queries&&Array.isArray(e.queries))for(const t of e.queries)this.applyQuery(t,{mode:"add"});return this.currentQuery}replaceQuery(e){return this.currentQuery.queries=[],e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&Array.isArray(e.queries)&&(this.currentQuery.queries=e.queries),this.currentQuery}clear(){return this.reset()}clearConditions(){return this.removeAllQueries()}getCurrentQuery(){return this.getQuery()}isEmpty(){return this.currentQuery.queries.length===0}hasCondition(e){const t=r=>{for(const s of r)if(this.isQuery(s)){let i=!0;for(const n in e)if(s[n]!==e[n]){i=!1;break}if(i)return!0}else if(this.isQueryGroup(s)&&t(s.queries))return!0;return!1};return t(this.currentQuery.queries)}hasGroup(e){return this.hasQueryGroup(e)}getUsedAttributes(){return this.getAttributeNames()}getDeepQueryAttributes(){return this.getAttributeDetails().filter(t=>t.isDeepQuery)}getGroups(){return this.currentQuery.queries.filter(e=>this.isQueryGroup(e))}getTopLevelConditions(){return this.currentQuery.queries.filter(e=>this.isQuery(e))}getGroup(e){return this.getQueryGroup(e)}getConditionCount(){const e=t=>{let r=0;for(const s of t)this.isQuery(s)?r++:this.isQueryGroup(s)&&(r+=e(s.queries));return r};return e(this.currentQuery.queries)}}const K=new M;function Se(o,e,t,r,s,i,n){const a=[],u=K.removeQuery({groupKey:s},h.cloneDeep(r)),c=n.queryData(o,u,!1,i),d=e?[...e.keys()]:[],f=new Set(d),l=i.get(s);if(!t.excludeUnresolved)for(const p of l.keys())f.add(p);t.excludeUndefineds?f.delete(void 0):f.add(void 0);for(const p of f.values()){const x=new Map,Z=l.get(p)||new Set;for(const k of Z){const E=c.get(k);if(E&&(x.set(k,E),!t?.calculateFacets))break}const C={key:String(p),value:p,selected:Ke(s,p,r),enabled:x.size>0,size:x.size,entry:e.get(p),resultKeys:Array.from(x.keys())};if(!(t?.excludeZeros&&C.size===0)){if(t?.count&&a.length===t?.count)return a;a.push(C)}}return a}const Ke=(o,e,t)=>{const r=t.queries.findIndex(s=>K.isQueryGroup(s)&&s.groupKey===o);return r>-1?!!t.queries[r].queries.find(i=>{if(K.isQuery(i)){const n=i.value?.key||i.value;return i.attribute===o&&n===e}return!1}):!1};class L{indexMap=new Map;dataMap=new Map;indexMetadata=new Map;constructor(){}reset(e){e?(this.indexMap.delete(e),this.dataMap.delete(e),this.indexMetadata.delete(e)):(this.indexMap.clear(),this.dataMap.clear(),this.indexMetadata.clear())}fillDataMap(e,t){let r=this.dataMap.get(e);r||(r=new Map,this.dataMap.set(e,r));for(const s of t){let i;if(typeof s=="object"&&s&&s.key)i=s.key;else if(Array.isArray(s)){for(const a of s)this.fillDataMap(e,[a]);return}else s instanceof Date?i=s.toISOString():i=s;let n=r.get(i);n||(n={key:i},this.dataMap.get(e)?.set(i,n))}}fillInverseIndex(e,t,r){if(!e||!t||!r||!Array.isArray(r))return;const s=this.indexMap.get(e)||new Map;for(const i of r){let n;if(typeof i=="object"&&i&&i.key)n=i.key;else if(Array.isArray(i)){for(const u of i)this.fillInverseIndex(e,t,[u]);return}else i instanceof Date?n=i.toISOString():n=i;let a=s.get(n);a||(a=new Set,s.set(n,a)),a.add(t)}this.indexMap.set(e,s)}getIndex(e,t){const r=this.getIndexName(e,t);return this.indexMap.get(r)}getData(e,t){const r=this.getIndexName(e,t);return this.dataMap.get(r)}getOrCreateIndex(e,t,r){const s=this.getIndexName(e,r);let i=this.getIndex(s);const n=this.indexMetadata.get(s);if(n)n.lastAccessedAt=Date.now();else if(!i){const u=y.parse(e).isDeepQuery??!1;this.indexMetadata.set(s,{createdAt:Date.now(),lastAccessedAt:Date.now(),context:r,type:u?"deep":"shallow"})}if(!i){this.reset(s),this.indexMap.set(s,new Map);const u=y.parse(e).isDeepQuery;for(const c of t.values()){const d=u?h.get(c,e):c[e];this.fillInverseIndex(s,c.key,[d]),this.fillDataMap(s,[d])}i=this.getIndex(s)||new Map}return i}getIndexName(e,t){return t?e+"_"+Q(t):e}removeFromInverseIndex(e,t,r){const s=this.indexMap.get(e);if(s)for(const i of r){let n;if(typeof i=="object"&&i&&i.key)n=i.key;else if(Array.isArray(i)){for(const u of i)this.removeFromInverseIndex(e,t,[u]);return}else i instanceof Date?n=i.toISOString():n=i;const a=s.get(n);a&&(a.delete(t),a.size===0&&s.delete(n))}}updateInverseIndex(e,t,r,s){this.removeFromInverseIndex(e,t,r),this.fillInverseIndex(e,t,s)}removeFromDataMap(e,t){const r=this.dataMap.get(e);if(r)for(const s of t){let i;if(typeof s=="object"&&s&&s.key)i=s.key;else if(Array.isArray(s)){for(const n of s)this.removeFromDataMap(e,[n]);return}else s instanceof Date?i=s.toISOString():i=s;r.delete(i)}}updateDataMap(e,t,r){this.removeFromDataMap(e,t),this.fillDataMap(e,r)}removeItemFromAllIndices(e){for(const t of this.indexMap.values())for(const[r,s]of t)s.delete(e)&&s.size===0&&t.delete(r);for(const t of this.dataMap.values())t.has(e)&&t.delete(e)}resetAttributes(e){for(const t of e)this.reset(t)}isDeepQueryIndex(e){const t=e.includes("_")?e.split("_")[0]:e;try{return y.parse(t).isDeepQuery??!1}catch{return!1}}getDeepIndexKeys(){const e=[];for(const t of this.indexMap.keys())this.isDeepQueryIndex(t)&&e.push(t);return e}resetAllDeepIndices(){const e=this.getDeepIndexKeys();for(const t of e)this.indexMap.delete(t),this.dataMap.delete(t)}getIndexCount(){let e=0,t=0;for(const r of this.indexMap.keys())this.isDeepQueryIndex(r)?t++:e++;return{shallow:e,deep:t,total:e+t}}cleanupStaleIndices(e=300*1e3){const t=Date.now();let r=0;for(const[s,i]of this.indexMetadata)t-i.lastAccessedAt>e&&(this.reset(s),r++);return r}getStats(){const e=this.getIndexCount(),t=Date.now();let r=0,s=0;for(const n of this.indexMetadata.values()){const a=t-n.createdAt;r+=a,a>s&&(s=a)}const i=this.indexMetadata.size>0?r/this.indexMetadata.size:0;return{shallow:e.shallow,deep:e.deep,total:e.total,oldestAge:s,avgAge:i}}}const m="__";function N(o,e,t={key:"root"},r="root",s=new L,i){const n=i||o;for(const a of e.columns)a.attribute&&(y.parse(a.attribute),s.getOrCreateIndex(a.attribute,n));for(const a of e.rows)a.attribute&&(y.parse(a.attribute),s.getOrCreateIndex(a.attribute,n));for(const a of e.values)a.attribute&&(y.parse(a.attribute),s.getOrCreateIndex(a.attribute,n));if(e.rows&&e.rows.length>0){t.rows=t.rows||[];const a=Qe(o,e.rows[0],e,s,r,i);t.rows.push(a)}if(e.columns&&e.columns.length>0){t.columns=t.columns||[];const a=H(o,e.columns[0],e,s,r,i);t.columns.push(a)}if(t.key==="root")for(const a of e.values){if(t.values=t.values||[],r==="root"&&e.options?.calculateTotals===!1)continue;const u=A(a,o,s.getIndex(a.attribute),a.attribute);t.values.push(u)}return t}function Qe(o,e,t,r,s="",i){const n={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return n;for(const[u,c]of a.entries()){const d={key:u,value:u},f=new Map;for(const l of c)o.has(l)&&f.set(l,o.get(l));if(f.size){for(const l of t.values){if(d.values=d.values||[],s==="root"&&e?.calculateTotals===!1)continue;const p=A(l,f,r.getIndex(l.attribute),l.attribute);d.values.push(p)}if(n.rows=n.rows||[],n.rows.push(d),t.rows.length>1){const l={...t,rows:t.rows.slice(1)};N(f,l,d,s+m+e.attribute+m+u,r,i)}else if(t.columns)for(const l of t.columns){d.columns=d.columns||[];const p=H(f,l,t,r,s+m+e.attribute+m+u,i);d.columns.push(p)}}}return n}function H(o,e,t,r,s="",i){const n={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return n;for(const[u,c]of a.entries()){const d={key:u,value:u},f=new Map;for(const l of c)o.has(l)&&f.set(l,o.get(l));if(f.size){for(const l of t.values){if(d.values=d.values||[],s==="root"&&e?.calculateTotals===!1)continue;const p=A(l,f,r.getIndex(l.attribute),l.attribute);d.values.push(p)}if(n.columns=n.columns||[],n.columns.push(d),t.columns.length>1){const l={...t,columns:t.columns.slice(1)};N(f,l,d,s+m+e.attribute+m+u,r,i)}}}return n}const Ie=(o,e)=>{const t=[];for(const r of o){for(const[s,i]of Object.entries(r)){const n=t.find(u=>u.key===s),a=J(i);if(n)n.type!==a&&(n.type="any");else{const u={key:s,type:a};t.push(u)}}if(!e)break}return t},V=o=>Number(o)===o&&o%1===0,U=o=>Number(o)===o&&o%1!==0,J=o=>{switch(typeof o){case"string":return"string";case"number":return V(o)?"int":U(o)?"float":"any";case"boolean":return"boolean";case"object":return R(o)?"date":"json";default:return"any"}},Me=(o,e)=>{const t=P(o.text||""),r=e?.attributeKey||o.filterKey;let s;const i=e?.comparisonType||"containsIgnoreCase";return i==="containsIgnoreCase"?s={groupKey:o.filterKey,queries:[{queryKey:o.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["lowercase"]}}]}:i==="containsIgnoreCaseAndWhitespace"?s={groupKey:o.filterKey,queries:[{queryKey:o.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["removeWhitespace","lowercase"]}}]}:i==="contains"?s={groupKey:o.filterKey,queries:[{queryKey:o.text,attribute:r,value:`/${t}/`,operator:"find"}]}:i==="equal"?s={groupKey:o.filterKey,queries:[{queryKey:o.text,attribute:r,value:o.text,operator:"eq"}]}:i==="equalIgnoreCase"&&(s={groupKey:o.filterKey,queries:[{queryKey:o.text,attribute:r,value:o.text,operator:"eq",options:{transform:["lowercase"]}}]}),s},Ne=(o,e)=>{const t=e?.attributeKey||o.filterKey;return{groupKey:o.filterKey,queries:[{queryKey:o.value,attribute:t,value:o.value,operator:"eq"}]}},Ce=(o,e)=>{const t=e?.attributeKey||o.filterKey,r={groupKey:o.filterKey,queries:[]};return typeof o.eq<"u"&&(r.groupType="or",Array.isArray(o.eq)?o.eq.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq"})}):r.queries.push({attribute:t,value:o.eq,operator:"eq"})),typeof o.ne<"u"&&(r.groupType="and",Array.isArray(o.ne)?o.ne.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq",options:{invert:!0}})}):r.queries.push({attribute:t,value:o.ne,operator:"eq",options:{invert:!0}})),typeof o.gt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:o.gt,operator:"gt"})),typeof o.lt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:o.lt,operator:"lt"})),typeof o.gte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:o.gte,operator:"gte"})),typeof o.lte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:o.lte,operator:"lte"})),r},ke=(o,e)=>{const t=e?.attributeKey||o.filterKey,r={groupKey:o.filterKey,queries:[]};return o.itemKeys.forEach(s=>{r.queries.push({queryKey:s,attribute:t,value:{key:s},operator:"eq"})}),r},Ee=o=>!(typeof o.modelKey!="string"||!Array.isArray(o.queries));class qe{constructor(e,t,r){this.scriptController=e,this.globalItemService=t,this.modelParser=r}registeredCustomOperator=new Map;queryBuilder=new M;registerCustomOperator(e,t){this.registeredCustomOperator.set(e,t)}transformValue(e,t){if(Array.isArray(e))return e.map(r=>this.transformValue(r,t));if(typeof e!="string")return e;for(const r of t)r==="lowercase"?e=e.toLowerCase():r==="trim"?e=e.trim():r==="removeWhitespace"&&(e=e.replace(/\s/g,""));return e}evaluateQuery(e,t){let r,s=e.value;const i=e.options?.arrayValueHandling||"some";if(Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(s=this.transformValue(s,e.options.transform)),e.attribute.includes(".")||e.attribute.includes("[")?r=h.get(t,e.attribute):r=t[e.attribute],Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(r=this.transformValue(r,e.options.transform)),(typeof r>"u"||r===null)&&!["typeof","isTruthy","eq"].includes(e.operator))return!1;switch(e.operator){case"eq":return e.options?.invert?!h.isEqual(r,s):h.isEqual(r,s);case"find":return e.options?.invert?!this.queryFind(r,s,i):this.queryFind(r,s,i);case"lt":return Array.isArray(r)?i==="some"?r.some(n=>n<s):r.every(n=>n<s):r<s;case"gt":return Array.isArray(r)?i==="some"?r.some(n=>n>s):r.every(n=>n>s):r>s;case"lte":return Array.isArray(r)?i==="some"?r.some(n=>n<=s):r.every(n=>n<=s):r<=s;case"gte":return Array.isArray(r)?i==="some"?r.some(n=>n>=s):r.every(n=>n>=s):r>=s;case"typeof":return e.options?.invert?typeof r!==s:Array.isArray(r)?i==="some"?r.some(n=>typeof n===s):r.every(n=>typeof n===s):typeof r===s;case"isTruthy":return s===!0?Array.isArray(r)?i==="some"?r.some(n=>typeof!!n):r.every(n=>typeof!!n):!!r:!r;case"size":return typeof r=="string"?r.length===s:h.size(r)===s;default:if(this.scriptController.hasScript(e.operator))return this.scriptController.executeScript(e.operator,"operator",{query:e,item:t});if(this.registeredCustomOperator.has(e.operator)){const n=this.registeredCustomOperator.get(e.operator);if(typeof n=="function")return n(e,t)}}return!1}evaluateEqOperator(e,t,r,s){const i=new Map,n=s.get(t.attribute);if(n){let a;if(typeof t.value=="string"?a=t.value:t.value?.key&&Object.keys(t.value).length===1&&(a=t.value.key),typeof a<"u"){const u=n.get(a);if(u)if(u.forEach(c=>{r.has(c)&&i.set(c,r.get(c))}),t.options?.invert){const c=h.differenceBy(Array.from(r.values()),Array.from(i.values()),"key"),d=new Map;return c.forEach(f=>{d.set(f.key,f)}),d}else return i}}for(let[a,u]of r){const c=this.queryBuilder.extractQueryAttributes({queries:[t]});if(c.some(d=>d.isDeepQuery)){const d=this.queryBuilder.getProjectionForAttributeEntries(c.filter(f=>f.isDeepQuery));u=this.globalItemService.getProjectedData(d,this.modelParser.models.get(e.modelKey),u)}this.evaluateQuery(t,u)&&i.set(a,u)}return i}equalRegexFn(e,t){if(typeof t=="string"&&h.startsWith(t,"/")&&h.endsWith(t,"/"))try{return new RegExp(t.slice(1,-1)).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(r=>h.isEqualWith(r,t,this.equalRegexFn)):typeof t=="object"?h.isMatch(e,t):e===t}queryFind(e,t,r){return Array.isArray(e)?typeof t=="string"||typeof t=="number"||typeof t=="boolean"?r==="some"?e.some(s=>h.isEqualWith(s,t,this.equalRegexFn)):e.every(s=>h.isEqualWith(s,t,this.equalRegexFn)):!!h.find(e,t):h.isEqualWith(e,t,this.equalRegexFn)}validateQuery(e){if(this.queryBuilder.isQuery(e)){if(!e.attribute||!e.operator)throw new Error("invalid query - missing attribute or operator");if(e.operator==="find"&&Array.isArray(e.value))throw new Error("invalid query - find operator cannot have array value");return!0}else{if(this.queryBuilder.isQueryGroup(e))return h.every(e.queries,t=>this.validateQuery(t));throw new Error("invalid query - missing query or attribute")}}getEvaluatedQueryDataset(e,t,r,s){const i=new Map;if(t.attribute.includes("[*]"))for(let n of r.values()){const a=this.queryBuilder.extractQueryAttributes({queries:[t]});if(a.some(c=>c.isDeepQuery)){const c=this.queryBuilder.getProjectionForAttributeEntries(a.filter(d=>d.isDeepQuery));n=this.globalItemService.getProjectedData(c,this.modelParser.models.get(e.modelKey),n)}const u=this.handleArrayStarQuery(t,n);for(const c of u.queries)this.evaluateQuery(c,n)&&i.set(n.key,n)}else{if(t.operator==="eq")return this.evaluateEqOperator(e,t,r,s);for(let[n,a]of r){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(c=>c.isDeepQuery)){const c=this.queryBuilder.getProjectionForAttributeEntries(u.filter(d=>d.isDeepQuery));a=this.globalItemService.getProjectedData(c,this.modelParser.models.get(e.modelKey),a)}this.evaluateQuery(t,a)&&i.set(n,a)}}return i}handleArrayStarQuery(e,t){const r=e.attribute.indexOf("[*]"),s={groupKey:e.queryKey||e.attribute+"[*]",groupType:"or",queries:[]};if(r!==-1){const i=e.attribute.substring(0,r),n=t[i];if(Array.isArray(n))for(let a=0;a<n.length;a++){const u=e.attribute.replace("[*]",`[${a}]`);s.queries.push({attribute:u,operator:e.operator,value:e.value})}}return s}evaluateQueryGroup(e,t,r,s,i){let n=new Map,a=r;if(!t.queries||t.queries?.length===0)return a;for(const u of t.queries){let c=new Map;if(this.queryBuilder.isQuery(u)?c=this.getEvaluatedQueryDataset(e,u,a,i):c=this.evaluateQueryGroup(e,u,a,s,i),n.size===0&&(n=c),t.groupType==="or")c.forEach(d=>{n.set(d.key,d)});else{const d=h.differenceBy(Array.from(n.values()),Array.from(c.values()),"key");for(const f of d)n.delete(f.key)}t.groupType==="and"?a=n:a=r}return n}queryData(e,t,r,s){const i=new Map(e);return t.queries.length===0?e:(t.groupKey||(t.groupKey="root"),t.groupType||(t.groupType="and"),t.queries||(t.queries=[]),this.validateQuery(t),this.evaluateQueryGroup(t,t,i,r,s))}}class Oe{scripts=new Map;scriptFunctions=new Map;constructor(){}keys(){return Array.from(this.scripts.keys())}setScript(e,t){this.scripts.set(e,t)}removeScript(e){this.scripts.delete(e)}getScript(e){return this.scripts.get(e)}hasScript(e){return this.scripts.has(e)}getScriptAsFn(e,t){if(this.scriptFunctions.has(e))return this.scriptFunctions.get(e);const r=this.getScript(e);if(!r)throw new Error(`Script ${e} not found`);const s=this.getWrapperScript(r),i=new Function("script_type",...t,s);return this.scriptFunctions.set(e,i),i}getWrapperScript(e){return`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("lodash-es");function I(o){const e=S(o);return X(e)}function S(o){if(typeof o!="object"||o===null)return String(o);if(Array.isArray(o))return"["+o.map(S).join(",")+"]";const e=Object.keys(o).sort();let t="{";for(let r=0;r<e.length;r++){const s=e[r];t+=s+":"+S(o[s]),r<e.length-1&&(t+=",")}return t+="}",t}function X(o){let e=0;for(let t=0;t<o.length;t++){const r=o.charCodeAt(t);e=(e<<5)-e+r,e|=0}return e.toString(16)}const v={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:o=>{typeof performance<"u"&&performance.mark&&performance.mark(o)},measure:(o,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(o,e,t)},getEntriesByName(o){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(o)},getEntriesByType(o){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(o)}};class ee{data;enabled=!1;constructor(){}init(e){this.data=new Map,this.enabled=e}set(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context);return this.data.set(t,e.value),this.data.get(t)}mark(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),r={name:e.name,type:"mark",value:v.now(),createdAt:Date.now()};return this.data.set(t,r),r}measure(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),r=this.data.get(this.getKey(e.start,e.context)),s=this.data.get(this.getKey(e.end,e.context));if(!r||!s)return;const i=s.value-r.value,n=Math.round(i*100)/100,a=this.data.get(t);if(a&&e.sum){const f=a.value+n,c={...a,value:f};return this.data.set(t,c),c}const u={name:e.name,type:"measure",value:n,createdAt:Date.now()};return e.detail&&(u.detail=e.detail),this.data.set(t,u),u}update(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context),r=this.data.get(t);if(r){const s={...r,...e.value};this.data.set(t,s)}else this.data.set(t,e.value);return this.data.get(t)}getResourceInfosFromPerformanceAPI(){return typeof performance>"u"?[]:v.getEntriesByType("resource")}get(e){const t=this.getKey(e.name,e.context);return this.data.get(t)}getByType(e){return Array.from(this.data.values()).filter(t=>t.type===e)}getByName(e){return Array.from(this.data.values()).filter(t=>t.name===e)}clear(){this.data.clear()}getKey(e,t){if(!t)return e;const r=I(t);return e+"_"+r}}let T=class G{nodes;edges;nodeKinds=new Map;nodeMeta=new Map;edgePolicy;constructor(){this.nodes=new Set,this.edges=new Map}addNode(e,t){this.nodes.has(e)||(this.nodes.add(e),this.edges.set(e,new Set)),t?.kind!==void 0&&this.nodeKinds.set(e,t.kind),t?.meta!==void 0&&this.nodeMeta.set(e,t.meta)}addDependency(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))throw new Error("Both nodes must exist before adding a dependency.");if(this.edgePolicy&&!this.edgePolicy({name:e,kind:this.nodeKinds.get(e)},{name:t,kind:this.nodeKinds.get(t)}))throw new Error(`Edge policy rejected dependency from "${e}" to "${t}".`);this.edges.get(e).add(t)}setEdgePolicy(e){this.edgePolicy=e}setNodeKind(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");t===void 0?this.nodeKinds.delete(e):this.nodeKinds.set(e,t)}getNodeKind(e){return this.nodeKinds.get(e)}setNodeMeta(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodeMeta.set(e,t)}getNodeMeta(e){return this.nodeMeta.get(e)}removeNode(e){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodes.delete(e),this.edges.delete(e);for(let t of this.edges.values())t.delete(e)}removeDependency(e,t){if(!this.edges.has(e))throw new Error("From node does not exist.");this.edges.get(e).delete(t)}hasNode(e){return this.nodes.has(e)}hasDependency(e,t){return this.edges.has(e)?this.edges.get(e).has(t):!1}getDependencies(e){if(!this.edges.has(e))throw new Error("Node does not exist.");return Array.from(this.edges.get(e))}getDependents(e){const t=[];for(let[r,s]of this.edges)s.has(e)&&t.push(r);return t}isCyclic(){const e=new Set,t=new Set,r=s=>{if(e.has(s))return!1;if(t.has(s))return!0;t.add(s);const i=this.edges.get(s);if(i){for(let n of i)if(r(n))return!0}return t.delete(s),e.add(s),!1};for(let s of this.nodes)if(r(s))return!0;return!1}validateNoCycles(){const e=new Set,t=new Set,r=[],s=i=>{if(e.has(i))return null;if(t.has(i)){const a=r.indexOf(i);return r.slice(a).concat([i])}t.add(i),r.push(i);const n=this.edges.get(i);if(n)for(let a of n){const u=s(a);if(u)return u}return r.pop(),t.delete(i),e.add(i),null};for(let i of this.nodes){const n=s(i);if(n)return{hasCycle:!0,path:n}}return{hasCycle:!1}}order(e){const t=new Set,r=new Set,s=[],i=e?.allowCycles??!1,n=a=>{if(t.has(a))return;if(r.has(a)){if(i)return;throw new Error("Graph has a cycle.")}r.add(a);const u=this.edges.get(a);if(u)for(let f of u)n(f);r.delete(a),t.add(a),s.push(a)};for(let a of this.nodes)t.has(a)||n(a);return s}clear(){this.nodes.clear(),this.edges.clear()}getNodes(){return Array.from(this.nodes)}getAllEdges(){const e=[];for(let[t,r]of this.edges)for(let s of r)e.push([t,s]);return e}getNodesWithNoDependants(){if(this.nodes.size===0)return[];const e=new Set;for(const r of this.edges.values())for(const s of r)e.add(s);const t=[];for(const r of this.nodes)e.has(r)||t.push(r);return t}getNodesByKind(e){const t=[];for(const r of this.nodes)this.nodeKinds.get(r)===e&&t.push(r);return t}getRootsByKind(e){const t=new Set(this.getNodesWithNoDependants()),r=Array.from(t);return e?r.filter(s=>this.nodeKinds.get(s)===e):r}getLeavesByKind(e){const t=[];for(const r of this.nodes){const s=this.edges.get(r);(!s||s.size===0)&&(!e||this.nodeKinds.get(r)===e)&&t.push(r)}return t}getDependenciesOfKind(e,t){return this.getDependencies(e).filter(s=>this.nodeKinds.get(s)===t)}getDependentsOfKind(e,t){return this.getDependents(e).filter(s=>this.nodeKinds.get(s)===t)}plan(e){const t=new Map;for(const n of this.nodes)t.set(n,0);for(const n of this.edges.values())for(const a of n)t.set(a,(t.get(a)||0)+1);const r=[];let s=Array.from(this.nodes).filter(n=>(t.get(n)||0)===0);const i=new Set;for(;s.length>0;){const n=s.slice();r.push(n),s=[];for(const a of n){if(i.has(a))continue;i.add(a);const u=this.edges.get(a);if(u)for(const f of u)t.set(f,(t.get(f)||0)-1),(t.get(f)||0)===0&&s.push(f)}}if(i.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const n=new Set(e.filterKinds);return{batches:r.map(a=>a.filter(u=>n.has(this.nodeKinds.get(u))))}}return{batches:r}}getImpactedNodes(e,t="downstream",r){const s=new Set(e),i=f=>!r||r.length===0||r.includes(this.nodeKinds.get(f)??void 0),n=()=>{const f=new Set,c=Array.from(s);for(;c.length;){const l=c.shift();for(const[d,p]of this.edges)p.has(l)&&!f.has(d)&&(f.add(d),c.push(d))}return f},a=()=>{const f=new Set,c=Array.from(s);for(;c.length;){const l=c.shift(),d=this.edges.get(l);if(d)for(const p of d)f.has(p)||(f.add(p),c.push(p))}return f};let u;return t==="both"?u=new Set([...n(),...a()]):t==="upstream"?u=a():u=n(),Array.from(u).filter(i)}toJSON(){const e=Array.from(this.nodes).map(r=>({name:r,kind:this.nodeKinds.get(r),meta:this.nodeMeta.get(r)})),t=this.getAllEdges().map(([r,s])=>({from:r,to:s}));return{nodes:e,edges:t}}static fromJSON(e){const t=new G;for(const r of e.nodes)t.addNode(r.name,{kind:r.kind,meta:r.meta});for(const r of e.edges)t.addDependency(r.from,r.to);return t}diff(e){const t=new Set(this.getNodes()),r=new Set(e.getNodes()),s=Array.from(r).filter(l=>!t.has(l)),i=Array.from(t).filter(l=>!r.has(l)),n=new Set(this.getAllEdges().map(l=>l.join("→"))),a=new Set(e.getAllEdges().map(l=>l.join("→"))),u=Array.from(a).filter(l=>!n.has(l)).map(l=>l.split("→")),f=Array.from(n).filter(l=>!a.has(l)).map(l=>l.split("→")),c=[];for(const l of new Set([...t,...r])){const d=this.nodeKinds.get(l),p=e.nodeKinds.get(l);d!==p&&c.push({name:l,from:d,to:p})}return{addedNodes:s,removedNodes:i,addedEdges:u,removedEdges:f,kindChanges:c}}};class te{graph;nodeIndex;constructor(){this.graph=new T,this.nodeIndex=new Map}getNodeId(e,t){return`${e}.${t}`}parseNodeId(e){const t=e.split(".");return{modelKey:t[0],attributeKey:t.slice(1).join(".")}}addAttribute(e){const t=this.getNodeId(e.modelKey,e.attributeKey);this.nodeIndex.has(t)||(this.graph.addNode(t,{meta:e}),this.nodeIndex.set(t,e))}addAttributeDependency(e,t){this.addAttribute(e),this.addAttribute(t);const r=this.getNodeId(e.modelKey,e.attributeKey),s=this.getNodeId(t.modelKey,t.attributeKey);this.graph.hasDependency(r,s)||this.graph.addDependency(r,s)}getImpactedAttributes(e){const t=e.map(a=>this.getNodeId(a.modelKey,a.attributeKey)),s=this.graph.getImpactedNodes(t,"downstream").map(a=>this.nodeIndex.get(a)).filter(a=>a!==void 0),i=[...e,...s],n=new Set;return i.filter(a=>{const u=this.getNodeId(a.modelKey,a.attributeKey);return n.has(u)?!1:(n.add(u),!0)})}getProcessingOrder(e){const t=new Map,r=[...e].sort((s,i)=>s.processingStep-i.processingStep);for(const s of r){const{modelKey:i,attributeKey:n,processingStep:a}=s;t.has(i)||t.set(i,new Map);const u=t.get(i);u.has(a)||u.set(a,new Set),u.get(a).add(n)}return t}getAttributesForModel(e){const t=[];for(const r of this.nodeIndex.values())r.modelKey===e&&t.push(r);return t}getDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}getDependents(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependents(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}hasDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).length>0:!1}hasNode(e){return this.nodeIndex.has(e)}getAllAttributes(){return Array.from(this.nodeIndex.values())}getMaxDepth(){let e=0;const t=(r,s=new Set)=>{if(s.has(r))return 0;s.add(r);const i=this.graph.getDependencies(r);if(i.length===0)return 1;let n=0;for(const a of i){const u=t(a,new Set(s));n=Math.max(n,u)}return n+1};for(const r of this.graph.getNodes()){const s=t(r);e=Math.max(e,s)}return e}validateCompleteness(e){const t=[];for(const[r,s]of e)for(const i of s){const n=this.getNodeId(r,i);this.hasNode(n)||t.push({modelKey:r,attributeKey:i})}return{isComplete:t.length===0,missing:t}}clear(){this.graph.clear(),this.nodeIndex.clear()}getStats(){const e=new Map,t=new Map;for(const r of this.nodeIndex.values())e.set(r.modelKey,(e.get(r.modelKey)||0)+1),t.set(r.processingStep,(t.get(r.processingStep)||0)+1);return{totalAttributes:this.nodeIndex.size,totalDependencies:this.graph.getAllEdges().length,maxDepth:this.getMaxDepth(),attributesByModel:e,attributesByStep:t}}toJSON(){return{nodes:Array.from(this.nodeIndex.values()),edges:this.graph.getAllEdges().map(([e,t])=>{const r=this.parseNodeId(e),s=this.parseNodeId(t);return{from:r,to:s}})}}}const O={silent:0,error:1,warn:2,info:3,debug:4};class g{config;static globalConfig={};constructor(e={}){this.config={level:e.level??g.globalConfig.level??this.getDefaultLevel(),format:e.format??g.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??g.globalConfig.onLog,onTrackError:e.onTrackError??g.globalConfig.onTrackError}}static setGlobalConfig(e){g.globalConfig={...g.globalConfig,...e}}static getGlobalConfig(){return{...g.globalConfig}}static setModuleLevel(e,t){g.globalConfig.onLog||(g.globalConfig.onLog=void 0),g._moduleOverrides||(g._moduleOverrides=new Map),g._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!g._moduleOverrides))return g._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=g.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return O[e]<=O[t]}formatMessage(e){if(this.config.format==="json"){const n={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(n.module=e.prefix),e.context&&(n.context=e.context),e.error&&(n.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(n)}const t=new Date(e.timestamp).toISOString().substring(11,23),r=e.prefix?`[${e.prefix}]`:"",s=this.getLevelIcon(e.level),i=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${s} ${r} ${e.message}${i}`.trim()}getLevelIcon(e){switch(e){case"error":return"✖";case"warn":return"⚠";case"info":return"ℹ";case"debug":return"⚙";default:return" "}}log(e,t,r,s){if(!this.shouldLog(e))return;const i={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:r,error:s};if(this.config.onLog){this.config.onLog(i);return}const n=this.formatMessage(i);if(typeof console<"u")switch(e){case"error":s?console.error(n,s):console.error(n);break;case"warn":console.warn(n);break;case"debug":console.debug?console.debug(n):console.log(n);break;default:console.log(n)}}error(e,t,r){const s=t instanceof Error?t:void 0,i=t instanceof Error?r:t;this.log("error",e,i,s)}trackError(e,t,r){if(this.error(e,t,r?.context),this.config.onTrackError){const s={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:r?.context,error:t,errorType:r?.errorType,errorGroup:r?.errorGroup};this.config.onTrackError(s)}}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}child(e){const t={...this.config,...e,prefix:e.prefix?this.config.prefix?`${this.config.prefix}:${e.prefix}`:e.prefix:this.config.prefix};return new g(t)}configure(e){Object.assign(this.config,e)}}const B=new g;class re{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}cache;cacheDependencies;hitCount=0;missCount=0;log=B.child({prefix:"CacheController"});get(e,t){if(!this.enabled)return;const r=this.getCacheName(e,t);return this.cache.has(r)?this.hitCount++:this.missCount++,this.cache.get(r)}set(e,t,r,s){if(!this.enabled)return;const i=this.getCacheName(e,t);this.cache.set(i,r),s?this.cacheDependencies.set(i,s):this.log.debug(`Cache entry '${e}' stored without dependencies. This prevents granular invalidation and may cause stale data.`)}has(e,t){return this.cache.has(this.getCacheName(e,t))}clear(){this.cache.clear(),this.cacheDependencies.clear(),this.hitCount=0,this.missCount=0}invalidateByDependencies(e){if(!this.enabled)return;const t=[];for(const[r,s]of this.cacheDependencies){let i=!1;for(const[n,a]of e){if(s.models.has(n))if(s.modelAttributes.has(n)){const u=s.modelAttributes.get(n);for(const f of a)if(u.has(f)){i=!0;break}}else i=!0;if(i)break}i&&t.push(r)}for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}invalidateByModels(e){if(!this.enabled)return;const t=new Set(e),r=[];for(const[s,i]of this.cacheDependencies)for(const n of t)if(i.models.has(n)){r.push(s);break}for(const s of r)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateByKeyPrefix(e){if(!this.enabled)return;const t=[];for(const r of this.cache.keys())r.startsWith(e+"_")&&t.push(r);for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}invalidateForModel(e){this.invalidateByModels([e])}invalidateForAttribute(e,t){if(!this.enabled)return;const r=new Map;r.set(e,new Set([t])),this.invalidateByDependencies(r)}invalidateMatching(e){if(!this.enabled)return;const t=[];for(const r of this.cache.keys())e(r)&&t.push(r);for(const r of t)this.cache.delete(r),this.cacheDependencies.delete(r)}generateContext(e){try{return h.cloneDeep(e)}catch(t){return this.log.error("Error in cache generateContext",t),e}}getCacheName(e,t){const r=I(t);return e+"_"+r}getStats(){const e=this.hitCount+this.missCount,t=e>0?this.hitCount/e:0;return{size:this.cache.size,hitRate:t,totalEntries:this.cache.size,entriesWithDependencies:this.cacheDependencies.size,hits:this.hitCount,misses:this.missCount}}}const se=(o,e="")=>`${o}#${e}`,ne=o=>`${o.gt}_${o.gte}_${o.lt}_${o.lte}_${o.eq}_${o.ne}`,ie=o=>`${o.gt}_${o.gte}_${o.lt}_${o.lte}_${o.eq}_${o.ne}`,oe=(o,e)=>{const t=typeof e=="function"?e:r=>r[e];return[...o.reduce((r,s)=>{const i=s==null?s:t(s);return r.has(i)||r.set(i,s),r},new Map).values()]},ae=(o,e)=>o.reduce(function(t,r){const s=typeof e=="function"?e(r):r[e];return Object.prototype.hasOwnProperty.call(t,s)||(t[s]=[]),t[s].push(r),t},{});function P(o=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let r=0;r<o;r++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}const ue=o=>o.replace(/\/+$/,""),j=o=>typeof o!="string"?"":o.replace(/[[\]{}()*+?.,\\^$|#]/g,"\\$&"),ce=o=>typeof o!="string"?"":o.replace(/\\([[\]{}()*+?.,\\^$|#])/g,"$1"),fe=(o,e)=>{try{return R(o,e)>=0}catch{return!1}},R=(o,e)=>{if(!K(o)||!K(e))throw new Error(`Invalid version format: v1="${o}", v2="${e}". Expected format: "x.y.z"`);const t=o.split(".").map(Number),r=e.split(".").map(Number);for(let s=0;s<3;s++){const i=t[s]||0,n=r[s]||0;if(i>n)return 1;if(i<n)return-1}return 0},K=o=>/^\d+(\.\d+){0,2}$/.test(o);class le{key;parentCd;dcuplInitOptions;analyticsController;off;updateListener=new Set;counter=0;constructor(){}_init(e){this.key=e.cdRefKey,this.analyticsController=e.analyticsController,this.parentCd=e.parentCd,this.dcuplInitOptions=e.dcuplInitOptions,this.parentCd&&(this.off=this.parentCd.on(t=>{t.action==="update"&&t.originCdRefKey===this.parentCd?.key&&(t.connectMessage=!1,this.trigger(t))}))}getCounter(){return this.parentCd?this.parentCd.getCounter():this.counter}increaseCounter(){this.parentCd?this.parentCd.increaseCounter():this.counter++}destroy(){this.off&&this.off()}trigger(e){e.originCdRefKey||(e.originCdRefKey=this.key),e.key||(this.increaseCounter(),e.key=this.getCounter()),e.end||(e.end=v.now(),e.duration=e.start-e.end),this.updateListener.forEach(t=>{t(e)})}on(e){return this.updateListener.add(e),()=>{this.updateListener.delete(e)}}}const M=(o,e)=>e?typeof structuredClone<"u"?structuredClone(o):h.cloneDeep(o):o,$=(o,e,t,r,s,i)=>{try{const n=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=M(i,n);if(t.scope==="list"&&(t.listKey=o.cdRef?.key||o.key,t.modelKey=o.model?.key||o.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const u=v.now(),f=u-r,c=Math.round(f*1e3)/1e3;t.duration=c,t.start=r,t.end=u;const l={duration:t.duration};return t.modelKey&&(l.model=t.modelKey),t.connectMessageResult&&(t.result=a),t.args&&(l.args=t.args),e?.trigger(t),e.analyticsController.mark({name:`${t.type}:end`,context:s}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:s,detail:l}),a}catch{return i}},de=o=>(t,r,s)=>{const i=s.value;return s.value=function(...n){const a=v.now(),u=this.cdRef,f=M(o,!0);f.key||(u.increaseCounter(),f.key=u.getCounter());const c=P();u.analyticsController.mark({name:`${f.type}:start`,context:c});const l=this.model?.key;!f.originCdRefKey&&u.key&&(f.originCdRefKey=u.key),l&&(f.modelKey=l);const d=i.apply(this,n);return f.method=r,f.args=n,d&&typeof d=="object"&&"then"in d?d.then(p=>$(this,u,f,a,c,p)):$(this,u,f,a,c,d)},s};function he(o,e,t,r){t.max||(t.max=20);const s=[],i=t.transform?r.transformValue(t.value,t.transform):t.value;for(const[n,a]of e.entries()){const u=Array.from(a).some(c=>o.has(c)),f=t.transform?r.transformValue(n,t.transform):n;if(!(t.excludeUndefineds&&typeof n>"u")&&!(t.excludeNulls&&n===null)){if(u&&(i===""||i==="//")){const c={value:n,keys:t.calculateResultKeys?Array.from(a):[]};s.push(c)}else if(u&&typeof i=="string"&&i.startsWith("/")&&i.endsWith("/")){if(r.queryFind(f,i,"some")){const c={value:n,keys:t.calculateResultKeys?Array.from(a):[]};s.push(c)}}else if(u&&typeof i=="string"){const c=String(f??""),l=i;if(c.toLowerCase().startsWith(l.toLowerCase())){const d={value:n,keys:t.calculateResultKeys?Array.from(a):[]};s.push(d)}}else if(u&&r.queryFind(f,i,"some")){const c={value:n,keys:t.calculateResultKeys?Array.from(a):[]};s.push(c)}if(s.length===t.max)break}}return s}function z(o){return o instanceof Date}function _(o){return o instanceof Date&&!isNaN(o.getTime())}const pe={yyyy:{type:"year",pattern:"yyyy",regex:"(\\d{4})"},yy:{type:"year",pattern:"yy",regex:"(\\d{2})"},MM:{type:"month",pattern:"MM",regex:"(\\d{2})"},M:{type:"month",pattern:"M",regex:"(\\d{1,2})"},dd:{type:"day",pattern:"dd",regex:"(\\d{2})"},d:{type:"day",pattern:"d",regex:"(\\d{1,2})"},HH:{type:"hour",pattern:"HH",regex:"(\\d{2})"},H:{type:"hour",pattern:"H",regex:"(\\d{1,2})"},mm:{type:"minute",pattern:"mm",regex:"(\\d{2})"},m:{type:"minute",pattern:"m",regex:"(\\d{1,2})"},ss:{type:"second",pattern:"ss",regex:"(\\d{2})"},s:{type:"second",pattern:"s",regex:"(\\d{1,2})"},SSS:{type:"millisecond",pattern:"SSS",regex:"(\\d{3})"}};function ge(o){let e="^";const t=[];let r=o;const s=Object.entries(pe).sort((i,n)=>n[0].length-i[0].length);for(;r.length>0;){let i=!1;for(const[n,a]of s)if(r.startsWith(n)){e+=a.regex,t.push({type:a.type,pattern:n}),r=r.slice(n.length),i=!0;break}if(!i){const n=r[0];if(!n)break;e+=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=r.slice(1)}}return e+="$",{regex:new RegExp(e),tokenOrder:t}}function ye(o,e){const t={year:1970,month:1,day:1,hour:0,minute:0,second:0,millisecond:0};for(let r=0;r<e.length;r++){const s=o[r+1];if(!s)continue;const i=parseInt(s,10),n=e[r];n&&(n.type==="year"&&n.pattern==="yy"?t.year=2e3+i:t[n.type]=i)}return t}function me(o){if(o.month<1||o.month>12)return new Date(NaN);if(o.day<1||o.day>31)return new Date(NaN);if(o.hour<0||o.hour>23)return new Date(NaN);if(o.minute<0||o.minute>59)return new Date(NaN);if(o.second<0||o.second>59)return new Date(NaN);if(o.millisecond<0||o.millisecond>999)return new Date(NaN);const e=new Date(o.year,o.month-1,o.day,o.hour,o.minute,o.second,o.millisecond);return _(e)?e.getFullYear()!==o.year||e.getMonth()!==o.month-1||e.getDate()!==o.day?new Date(NaN):e:new Date(NaN)}function ve(o,e,t){if(o=o.trim(),e==="t"){const a=Number(o);return isNaN(a)?new Date(NaN):new Date(a*1e3)}if(e==="T"){const a=Number(o);return isNaN(a)?new Date(NaN):new Date(a)}const{regex:r,tokenOrder:s}=ge(e),i=o.match(r);if(!i)return new Date(NaN);const n=ye(i,s);return me(n)}class we{cache;maxSize;accessOrder;constructor(e){this.cache=new Map,this.maxSize=e,this.accessOrder=[]}get(e){const t=this.cache.get(e);return t!==void 0&&this.updateAccessOrder(e),t}set(e,t){if(this.cache.has(e))this.cache.set(e,t),this.updateAccessOrder(e);else{if(this.cache.size>=this.maxSize){const r=this.accessOrder.shift();r!==void 0&&this.cache.delete(r)}this.cache.set(e,t),this.accessOrder.push(e)}}has(e){return this.cache.has(e)}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}updateAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e)}getStats(){return{size:this.cache.size,maxSize:this.maxSize}}}class xe{graph;constructor(){this.graph=new Map}addDependency(e,t){this.graph.has(e)||this.graph.set(e,new Set),this.graph.get(e).add(t)}hasCycle(e){if(e.length===0)return!1;const t=new Set,r=new Set,s=i=>{t.add(i),r.add(i);const n=this.graph.get(i);if(n){for(const a of n)if(t.has(a)){if(r.has(a))return!0}else if(s(a))return!0}return r.delete(i),!1};for(let i=0;i<e.length-1;i++){const n=e[i],a=e[i+1];n&&a&&this.addDependency(n,a)}for(const i of e)if(!t.has(i)&&s(i))return!0;return!1}clear(){this.graph.clear()}}class W{parseCache;circularRefDetector;cacheHits=0;cacheMisses=0;constructor(e=1e3){this.parseCache=new we(e),this.circularRefDetector=new xe}parse(e){if(this.parseCache.has(e))return this.cacheHits++,this.parseCache.get(e);this.cacheMisses++;let t,r;const s=e.includes("."),i=e.includes("["),n=s||i;if(n)if(r=e.split(/[.[]/)[0],i){const u=e.indexOf("]");if(u>-1){const f=e.indexOf(".",u+1);f>-1?t=e.substring(f+1):t=void 0}else s&&(t=e.substring(e.indexOf(".")+1))}else s&&(t=e.substring(e.indexOf(".")+1));const a={attribute:e,isDeepQuery:n};return r&&(a.reference=r),typeof t<"u"&&t!==""&&(a.referenceAttribute=t),this.parseCache.set(e,a),a}detectCircular(e){return e.length===0?!1:new Set(e).size!==e.length?!0:this.circularRefDetector.hasCycle(e)}validatePath(e,t=10){const r=[];if(!e||e.trim().length===0)return r.push("Attribute path cannot be empty"),{valid:!1,errors:r};(e.startsWith(".")||e.endsWith("."))&&r.push(`Invalid path: Leading or trailing dots are not allowed: ${e}`),e.includes("..")&&r.push(`Invalid path: Consecutive dots are not allowed: ${e}`);const s=(e.match(/\[/g)||[]).length,i=(e.match(/]/g)||[]).length;s!==i&&r.push(`Invalid bracket notation: Mismatched brackets in ${e}`),e.includes("[]")&&r.push(`Invalid bracket notation: Empty brackets not allowed: ${e}`);const n=/\[([^\]]+)\]/g;let a;for(;(a=n.exec(e))!==null;){const c=a[1];c&&c!=="*"&&!/^\d+$/.test(c)&&r.push(`Invalid bracket content: Must be a number or '*', got '${c}' in ${e}`)}const u=(e.match(/\./g)||[]).length+1;u>t&&r.push(`Path too deep: Maximum depth is ${t}, got ${u} in ${e}`);const f=e.match(/[^a-zA-Z0-9._[\]*-]/g);return f&&r.push(`Invalid characters in path: ${f.join(", ")} in ${e}`),{valid:r.length===0,errors:r.length>0?r:void 0}}clearCache(){this.parseCache.clear(),this.cacheHits=0,this.cacheMisses=0}clearCircularDetector(){this.circularRefDetector.clear()}getCacheStats(){const e=this.parseCache.getStats(),t=this.cacheHits+this.cacheMisses,r=t>0?this.cacheHits/t:0;return{...e,hits:this.cacheHits,misses:this.cacheMisses,hitRate:r}}getPathSegments(e){return e.replace(/\[[^\]]+\]/g,"").split(".").filter(r=>r.length>0)}getPathDepth(e){return this.getPathSegments(e).length}}const y=new W;function w(o,e){if(!e.includes("[*]")){const a=h.get(o,e);return a!==void 0?[a]:[]}const t=e.indexOf("[*]"),r=e.substring(0,t),s=e.substring(t+3),i=r?h.get(o,r):o;if(!Array.isArray(i))return[];const n=[];for(const a of i)!s||s===""?a!==void 0&&n.push(a):s.startsWith(".")&&n.push(...w(a,s.slice(1)));return n}function D(o){let e=0;for(let t of o){const r=t.toString().split(".")[1];r&&(e=Math.max(e,r.length))}return Math.pow(10,e)}function F(o,e,t){return(o*t+e*t)/t}function Ae(o,e,t){return o*t/(e*t)}const b=(o,e,t,r)=>{if(!r)throw new Error("Attribute not found");const s={attribute:r,types:o.types};let i;(s.types.includes("sum")||s.types.includes("avg")||s.types.includes("count"))&&(i=Se(r,e));let n;return(s.types.includes("min")||s.types.includes("max"))&&(n=be(r,e)),o.types.forEach(a=>{a==="sum"?s.sum=i?.sum:a==="avg"?s.avg=i?.average:a==="count"?s.count=i?.count:a==="min"?s.min=n&&n[0]:a==="max"?s.max=n&&n[1]:a==="distinct"?s.distinct=L(o,e,t):a==="group"&&(s.group=De(o,e))}),s},be=(o,e)=>{let t,r;const i=y.parse(o).isDeepQuery;for(const n of e.values())if(n){let a;if(i&&o.includes("[*]"))a=w(n,o);else if(i){const u=h.get(n,o);a=u!==void 0?[u]:[]}else a=n[o]!==void 0?[n[o]]:[];for(const u of a)(t===void 0||u<t)&&(t=u),(r===void 0||u>r)&&(r=u)}if(!(t===void 0||r===void 0))return[t,r]},De=(o,e)=>{const t=[];o.groupOptions?.groups?.forEach(n=>{t.push({option:n,count:0,keys:[]})});const r={option:{value:["$dcupl_not_found"]},count:0,keys:[]},i=y.parse(o.attribute).isDeepQuery;for(const n of e.values()){let a;if(i&&o.attribute.includes("[*]"))a=w(n,o.attribute);else if(i){const f=h.get(n,o.attribute);a=f!==void 0?[f]:[]}else a=[n[o.attribute]];let u=!1;for(const f of a)for(const c of t)(typeof c.option.value<"u"&&c.option.value.includes(f)||typeof c.option.from<"u"&&c.option.from<f&&typeof c.option.to<"u"&&c.option.to>f)&&(c.keys.includes(n.key)||(c.count++,c.keys.push(n.key)),u=!0);!u&&o?.groupOptions?.calculateNotFound&&(r.count++,r.keys.push(n.key))}return o?.groupOptions?.calculateNotFound&&t.push(r),t},Se=(o,e)=>{let t=0,r=0;const i=y.parse(o).isDeepQuery;for(const u of e.values()){if(!u)continue;let f;if(i&&o.includes("[*]"))f=w(u,o);else if(i){const c=h.get(u,o);f=c!==void 0?[c]:[]}else f=u[o]!==void 0?[u[o]]:[];for(const c of f)if(Array.isArray(c))for(const l of c)typeof l=="number"&&(t=F(t,l,D([t,l])),r++);else typeof c=="number"&&(t=F(t,c,D([t,c])),r++)}return r===0?void 0:{average:Ae(t,r,D([t,r])),count:e.size,sum:t}},L=(o,e,t)=>{const r=[];for(const[s,i]of t)if(!(o.excludeUndefineds&&typeof s>"u")&&Array.from(i).find(n=>e.has(n))){const n={value:s,count:i.size};if(o.distinctOptions?.skipKeys||(n.keys=Array.from(i)),r.push(n),o.distinctOptions?.limit&&r.length>=o.distinctOptions.limit)break}return r};class x extends Error{query;constructor(e,t){const r=`Query Error: ${e} in ${JSON.stringify(t,null,2)}`;super(r),this.query=t,this.name="DcuplQueryError"}}class N{_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=h.cloneDeep(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||y}init(e){this._initOptions=h.cloneDeep(e),this.currentQuery=h.cloneDeep(this._defaultQueryOptions),this.currentQuery.modelKey=e.modelKey,"queries"in e&&Array.isArray(e.queries)&&(e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&(this.currentQuery.queries=h.cloneDeep(e.queries)),e.count!==void 0&&(this.currentQuery.count=e.count),e.start!==void 0&&(this.currentQuery.start=e.start),e.sort&&(this.currentQuery.sort=e.sort),e.projection&&(this.currentQuery.projection=e.projection))}reset(){return this.init(this._initOptions),this.getQuery()}isQuery(e){return"attribute"in e}isQueryGroup(e){return"groupKey"in e}isRootQueryGroup(e){return this.isQueryGroup(e)&&e.groupKey==="root"}getQueryGroup(e){return this.currentQuery.queries.find(t=>this.isQueryGroup(t)&&t.groupKey===e)}getQuery(){return h.cloneDeep(this.currentQuery)}hasQueryGroup(e){return this.currentQuery.queries.some(t=>this.isQueryGroup(t)&&t.groupKey===e)}has(e){if(e.groupKey&&e.queryKey){const t=this.getQueryGroup(e.groupKey);if(t)return t.queries.some(r=>this.isQuery(r)&&r.queryKey===e.queryKey)}else if(e.groupKey)return this.hasQueryGroup(e.groupKey);return!1}validate(e){const t=e.queries.map(s=>this.validateQuery(s));return{valid:h.every(t,s=>s.valid),errors:t.map(s=>s.errors).flat()}}applyOptions(e,t="update"){return t==="set"?(this.currentQuery.count=e.count,this.currentQuery.start=e.start,this.currentQuery.sort=e.sort,this.currentQuery.projection=e.projection):(typeof e?.sort<"u"&&(this.currentQuery.sort=e.sort),typeof e?.count<"u"&&(this.currentQuery.count=e.count),typeof e?.start<"u"&&(this.currentQuery.start=e?.start),typeof e?.projection<"u"&&(this.currentQuery.projection=e?.projection)),this.getQuery()}applyQuery(e,t,r){if(r||(r=this.currentQuery),Array.isArray(e))for(const s of e)this.applyQuery(s,t,r);else if(this.isRootQueryGroup(e))e.groupType&&(r.groupType=e.groupType),t?.mode==="set"?r.queries=e.queries:r.queries=[...r.queries,...e.queries],this.applyOptions(e,"set");else if(this.isQuery(e)){const s=r.queries.findIndex(i=>this.isQueryGroup(i)&&i.groupKey===e.attribute);if(s>-1){const i=r.queries[s];t?.mode==="set"?i.queries=[e]:i.queries.push(e)}else r.queries.push({groupKey:e.attribute,groupType:"or",queries:[e]})}else if(this.isQueryGroup(e)){const s=r.queries.findIndex(i=>this.isQueryGroup(i)&&i.groupKey===e.groupKey);if(s>-1){const i=r.queries[s];e.groupType&&(i.groupType=e.groupType),t?.mode==="set"?r.queries[s]=e:i.queries=[...i.queries,...e.queries]}else r.queries.push({groupKey:e.groupKey,groupType:e.groupType||"or",queries:e.queries})}return r}removeAllQueries(){return this.currentQuery.queries=[],this.getQuery()}removeQuery(e,t){if(t||(t=this.currentQuery),this.isQuery(e)){const r=t.queries.findIndex(s=>this.isQueryGroup(s)&&s.groupKey===e.attribute);if(r>-1){const s=t.queries[r],i=h.findIndex(s.queries,e);i>-1&&s.queries.splice(i,1),s.queries.length===0&&t.queries.splice(r,1)}}else if(this.isQueryGroup(e)){const r=t.queries.findIndex(s=>this.isQueryGroup(s)&&s.groupKey===e.groupKey);if(r>-1)if(!e.queries)t.queries.splice(r,1);else{const s=t.queries[r];for(const i of e.queries){const n=h.findIndex(s.queries,i);n>-1&&s.queries.splice(n,1)}s.queries.length===0&&t.queries.splice(r,1)}}return t}validateQuery(e){const t=[];if(this.isQuery(e))return e.attribute||t.push(new x("Missing attribute",e)),e.operator||t.push(new x("Missing operator",e)),typeof e.value>"u"&&t.push(new x("Missing value",e)),e.operator==="find"&&Array.isArray(e.value)&&t.push(new x("find operator cannot have array value",e)),t.length>0?{valid:!1,errors:t}:{valid:!0};if(this.isQueryGroup(e)){const i=e.queries.map(n=>this.validateQuery(n)).filter(n=>!n.valid).map(n=>n.errors).flat();return i.length>0?{valid:!1,errors:i}:{valid:!0}}return t.push(new x("Invalid query definition",e)),{valid:!1,errors:t}}getQueryAttributes(e){const t=[],r=new Set,s=i=>{for(const n of i)this.isQuery(n)?n.attribute&&!r.has(n.attribute)&&(t.push(n.attribute),r.add(n.attribute)):this.isQueryGroup(n)&&s(n.queries)};return s(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],r=new Set,s=i=>{for(const n of i)if(this.isQuery(n)){if(n.attribute&&!r.has(n.attribute)){const a=this.getQueryAttributeForString(n.attribute);t.push(a),r.add(n.attribute)}}else this.isQueryGroup(n)&&s(n.queries)};return s(e?.queries||this.currentQuery.queries),t}getQueryAttributeForString(e){return this.deepQueryService.parse(e)}getDeepQueryService(){return this.deepQueryService}getProjectionForAttributes(e){const t={};return e.forEach(r=>{t[r]=!0}),t}getProjectionForAttributeEntries(e){const t={$:!0};return e.forEach(r=>{if(r.isDeepQuery){if(r.reference)if(r.referenceAttribute&&r.referenceAttribute.length>0){t[r.reference]||(t[r.reference]={$:!0});const s=this.deepQueryService.parse(r.referenceAttribute);if(s.isDeepQuery&&r.reference){const i=this.getProjectionForAttributeEntries([s]);Object.keys(i).forEach(n=>{n!=="$"&&r.reference&&(t[r.reference][n]=i[n])})}else r.reference&&(t[r.reference][r.referenceAttribute]=!0)}else t[r.reference]=!0}else t[r.attribute]=!0}),t}getAttributeNames(e){return this.getQueryAttributes(e)}getAttributeDetails(e){return this.extractQueryAttributes(e||this.currentQuery)}getCurrentAttributeNames(){return this.getAttributeNames(this.currentQuery)}getCurrentAttributeDetails(){return this.getAttributeDetails(this.currentQuery)}addCondition(e){return this.applyQuery(e,{mode:"add"})}addGroup(e){return this.applyQuery(e,{mode:"add"})}setCondition(e){return this.applyQuery(e,{mode:"set"})}setGroup(e){return this.applyQuery(e,{mode:"set"})}mergeQuery(e){if(e.queries&&Array.isArray(e.queries))for(const t of e.queries)this.applyQuery(t,{mode:"add"});return this.currentQuery}replaceQuery(e){return this.currentQuery.queries=[],e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&Array.isArray(e.queries)&&(this.currentQuery.queries=e.queries),this.currentQuery}clear(){return this.reset()}clearConditions(){return this.removeAllQueries()}getCurrentQuery(){return this.getQuery()}isEmpty(){return this.currentQuery.queries.length===0}hasCondition(e){const t=r=>{for(const s of r)if(this.isQuery(s)){let i=!0;for(const n in e)if(s[n]!==e[n]){i=!1;break}if(i)return!0}else if(this.isQueryGroup(s)&&t(s.queries))return!0;return!1};return t(this.currentQuery.queries)}hasGroup(e){return this.hasQueryGroup(e)}getUsedAttributes(){return this.getAttributeNames()}getDeepQueryAttributes(){return this.getAttributeDetails().filter(t=>t.isDeepQuery)}getGroups(){return this.currentQuery.queries.filter(e=>this.isQueryGroup(e))}getTopLevelConditions(){return this.currentQuery.queries.filter(e=>this.isQuery(e))}getGroup(e){return this.getQueryGroup(e)}getConditionCount(){const e=t=>{let r=0;for(const s of t)this.isQuery(s)?r++:this.isQueryGroup(s)&&(r+=e(s.queries));return r};return e(this.currentQuery.queries)}}const Q=new N;function Ke(o,e,t,r,s,i,n){const a=[],u=Q.removeQuery({groupKey:s},h.cloneDeep(r)),f=n.queryData(o,u,!1,i),c=e?[...e.keys()]:[],l=new Set(c),d=i.get(s);if(!t.excludeUnresolved)for(const p of d.keys())l.add(p);t.excludeUndefineds?l.delete(void 0):l.add(void 0);for(const p of l.values()){const A=new Map,Y=d.get(p)||new Set;for(const E of Y){const q=f.get(E);if(q&&(A.set(E,q),!t?.calculateFacets))break}const k={key:String(p),value:p,selected:Qe(s,p,r),enabled:A.size>0,size:A.size,entry:e.get(p),resultKeys:Array.from(A.keys())};if(!(t?.excludeZeros&&k.size===0)){if(t?.count&&a.length===t?.count)return a;a.push(k)}}return a}const Qe=(o,e,t)=>{const r=t.queries.findIndex(s=>Q.isQueryGroup(s)&&s.groupKey===o);return r>-1?!!t.queries[r].queries.find(i=>{if(Q.isQuery(i)){const n=i.value?.key||i.value;return i.attribute===o&&n===e}return!1}):!1};class V{indexMap=new Map;dataMap=new Map;indexMetadata=new Map;constructor(){}reset(e){e?(this.indexMap.delete(e),this.dataMap.delete(e),this.indexMetadata.delete(e)):(this.indexMap.clear(),this.dataMap.clear(),this.indexMetadata.clear())}fillDataMap(e,t){let r=this.dataMap.get(e);r||(r=new Map,this.dataMap.set(e,r));for(const s of t){let i;if(typeof s=="object"&&s&&s.key)i=s.key;else if(Array.isArray(s)){for(const a of s)this.fillDataMap(e,[a]);return}else s instanceof Date?i=s.toISOString():i=s;let n=r.get(i);n||(n={key:i},this.dataMap.get(e)?.set(i,n))}}fillInverseIndex(e,t,r){if(!e||!t||!r||!Array.isArray(r))return;const s=this.indexMap.get(e)||new Map;for(const i of r){let n;if(typeof i=="object"&&i&&i.key)n=i.key;else if(Array.isArray(i)){for(const u of i)this.fillInverseIndex(e,t,[u]);return}else i instanceof Date?n=i.toISOString():n=i;let a=s.get(n);a||(a=new Set,s.set(n,a)),a.add(t)}this.indexMap.set(e,s)}getIndex(e,t){const r=this.getIndexName(e,t);return this.indexMap.get(r)}getData(e,t){const r=this.getIndexName(e,t);return this.dataMap.get(r)}getOrCreateIndex(e,t,r){const s=this.getIndexName(e,r);let i=this.getIndex(s);const n=this.indexMetadata.get(s);if(n)n.lastAccessedAt=Date.now();else if(!i){const u=y.parse(e).isDeepQuery??!1;this.indexMetadata.set(s,{createdAt:Date.now(),lastAccessedAt:Date.now(),context:r,type:u?"deep":"shallow"})}if(!i){this.reset(s),this.indexMap.set(s,new Map);const u=y.parse(e).isDeepQuery;for(const f of t.values()){let c;u&&e.includes("[*]")?(c=w(f,e),c.length===0&&(c=[void 0])):u?c=[h.get(f,e)]:c=[f[e]],this.fillInverseIndex(s,f.key,c),this.fillDataMap(s,c)}i=this.getIndex(s)||new Map}return i}getIndexName(e,t){return t?e+"_"+I(t):e}removeFromInverseIndex(e,t,r){const s=this.indexMap.get(e);if(s)for(const i of r){let n;if(typeof i=="object"&&i&&i.key)n=i.key;else if(Array.isArray(i)){for(const u of i)this.removeFromInverseIndex(e,t,[u]);return}else i instanceof Date?n=i.toISOString():n=i;const a=s.get(n);a&&(a.delete(t),a.size===0&&s.delete(n))}}updateInverseIndex(e,t,r,s){this.removeFromInverseIndex(e,t,r),this.fillInverseIndex(e,t,s)}removeFromDataMap(e,t){const r=this.dataMap.get(e);if(r)for(const s of t){let i;if(typeof s=="object"&&s&&s.key)i=s.key;else if(Array.isArray(s)){for(const n of s)this.removeFromDataMap(e,[n]);return}else s instanceof Date?i=s.toISOString():i=s;r.delete(i)}}updateDataMap(e,t,r){this.removeFromDataMap(e,t),this.fillDataMap(e,r)}removeItemFromAllIndices(e){for(const t of this.indexMap.values())for(const[r,s]of t)s.delete(e)&&s.size===0&&t.delete(r);for(const t of this.dataMap.values())t.has(e)&&t.delete(e)}resetAttributes(e){for(const t of e)this.reset(t)}isDeepQueryIndex(e){const t=e.includes("_")?e.split("_")[0]:e;try{return y.parse(t).isDeepQuery??!1}catch{return!1}}getDeepIndexKeys(){const e=[];for(const t of this.indexMap.keys())this.isDeepQueryIndex(t)&&e.push(t);return e}resetAllDeepIndices(){const e=this.getDeepIndexKeys();for(const t of e)this.indexMap.delete(t),this.dataMap.delete(t)}getIndexCount(){let e=0,t=0;for(const r of this.indexMap.keys())this.isDeepQueryIndex(r)?t++:e++;return{shallow:e,deep:t,total:e+t}}cleanupStaleIndices(e=300*1e3){const t=Date.now();let r=0;for(const[s,i]of this.indexMetadata)t-i.lastAccessedAt>e&&(this.reset(s),r++);return r}getStats(){const e=this.getIndexCount(),t=Date.now();let r=0,s=0;for(const n of this.indexMetadata.values()){const a=t-n.createdAt;r+=a,a>s&&(s=a)}const i=this.indexMetadata.size>0?r/this.indexMetadata.size:0;return{shallow:e.shallow,deep:e.deep,total:e.total,oldestAge:s,avgAge:i}}}const m="__";function C(o,e,t={key:"root"},r="root",s=new V,i){const n=i||o;for(const a of e.columns)a.attribute&&(y.parse(a.attribute),s.getOrCreateIndex(a.attribute,n));for(const a of e.rows)a.attribute&&(y.parse(a.attribute),s.getOrCreateIndex(a.attribute,n));for(const a of e.values)a.attribute&&(y.parse(a.attribute),s.getOrCreateIndex(a.attribute,n));if(e.rows&&e.rows.length>0){t.rows=t.rows||[];const a=Ie(o,e.rows[0],e,s,r,i);t.rows.push(a)}if(e.columns&&e.columns.length>0){t.columns=t.columns||[];const a=H(o,e.columns[0],e,s,r,i);t.columns.push(a)}if(t.key==="root")for(const a of e.values){if(t.values=t.values||[],r==="root"&&e.options?.calculateTotals===!1)continue;const u=b(a,o,s.getIndex(a.attribute),a.attribute);t.values.push(u)}return t}function Ie(o,e,t,r,s="",i){const n={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return n;for(const[u,f]of a.entries()){const c={key:u,value:u},l=new Map;for(const d of f)o.has(d)&&l.set(d,o.get(d));if(l.size){for(const d of t.values){if(c.values=c.values||[],s==="root"&&e?.calculateTotals===!1)continue;const p=b(d,l,r.getIndex(d.attribute),d.attribute);c.values.push(p)}if(n.rows=n.rows||[],n.rows.push(c),t.rows.length>1){const d={...t,rows:t.rows.slice(1)};C(l,d,c,s+m+e.attribute+m+u,r,i)}else if(t.columns)for(const d of t.columns){c.columns=c.columns||[];const p=H(l,d,t,r,s+m+e.attribute+m+u,i);c.columns.push(p)}}}return n}function H(o,e,t,r,s="",i){const n={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return n;for(const[u,f]of a.entries()){const c={key:u,value:u},l=new Map;for(const d of f)o.has(d)&&l.set(d,o.get(d));if(l.size){for(const d of t.values){if(c.values=c.values||[],s==="root"&&e?.calculateTotals===!1)continue;const p=b(d,l,r.getIndex(d.attribute),d.attribute);c.values.push(p)}if(n.columns=n.columns||[],n.columns.push(c),t.columns.length>1){const d={...t,columns:t.columns.slice(1)};C(l,d,c,s+m+e.attribute+m+u,r,i)}}}return n}const Me=(o,e)=>{const t=[];for(const r of o){for(const[s,i]of Object.entries(r)){const n=t.find(u=>u.key===s),a=Z(i);if(n)n.type!==a&&(n.type="any");else{const u={key:s,type:a};t.push(u)}}if(!e)break}return t},U=o=>Number(o)===o&&o%1===0,J=o=>Number(o)===o&&o%1!==0,Z=o=>{switch(typeof o){case"string":return"string";case"number":return U(o)?"int":J(o)?"float":"any";case"boolean":return"boolean";case"object":return z(o)?"date":"json";default:return"any"}},Ne=(o,e)=>{const t=j(o.text||""),r=e?.attributeKey||o.filterKey;let s;const i=e?.comparisonType||"containsIgnoreCase";return i==="containsIgnoreCase"?s={groupKey:o.filterKey,queries:[{queryKey:o.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["lowercase"]}}]}:i==="containsIgnoreCaseAndWhitespace"?s={groupKey:o.filterKey,queries:[{queryKey:o.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["removeWhitespace","lowercase"]}}]}:i==="contains"?s={groupKey:o.filterKey,queries:[{queryKey:o.text,attribute:r,value:`/${t}/`,operator:"find"}]}:i==="equal"?s={groupKey:o.filterKey,queries:[{queryKey:o.text,attribute:r,value:o.text,operator:"eq"}]}:i==="equalIgnoreCase"&&(s={groupKey:o.filterKey,queries:[{queryKey:o.text,attribute:r,value:o.text,operator:"eq",options:{transform:["lowercase"]}}]}),s},Ce=(o,e)=>{const t=e?.attributeKey||o.filterKey;return{groupKey:o.filterKey,queries:[{queryKey:o.value,attribute:t,value:o.value,operator:"eq"}]}},ke=(o,e)=>{const t=e?.attributeKey||o.filterKey,r={groupKey:o.filterKey,queries:[]};return typeof o.eq<"u"&&(r.groupType="or",Array.isArray(o.eq)?o.eq.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq"})}):r.queries.push({attribute:t,value:o.eq,operator:"eq"})),typeof o.ne<"u"&&(r.groupType="and",Array.isArray(o.ne)?o.ne.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq",options:{invert:!0}})}):r.queries.push({attribute:t,value:o.ne,operator:"eq",options:{invert:!0}})),typeof o.gt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:o.gt,operator:"gt"})),typeof o.lt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:o.lt,operator:"lt"})),typeof o.gte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:o.gte,operator:"gte"})),typeof o.lte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:o.lte,operator:"lte"})),r},Ee=(o,e)=>{const t=e?.attributeKey||o.filterKey,r={groupKey:o.filterKey,queries:[]};return o.itemKeys.forEach(s=>{r.queries.push({queryKey:s,attribute:t,value:{key:s},operator:"eq"})}),r},qe=o=>!(typeof o.modelKey!="string"||!Array.isArray(o.queries));class Oe{constructor(e,t,r){this.scriptController=e,this.globalItemService=t,this.modelParser=r}registeredCustomOperator=new Map;queryBuilder=new N;registerCustomOperator(e,t){this.registeredCustomOperator.set(e,t)}transformValue(e,t){if(Array.isArray(e))return e.map(r=>this.transformValue(r,t));if(typeof e!="string")return e;for(const r of t)r==="lowercase"?e=e.toLowerCase():r==="trim"?e=e.trim():r==="removeWhitespace"&&(e=e.replace(/\s/g,""));return e}evaluateQuery(e,t){let r,s=e.value;const i=e.options?.arrayValueHandling||"some";if(Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(s=this.transformValue(s,e.options.transform)),e.attribute.includes(".")||e.attribute.includes("[")?r=h.get(t,e.attribute):r=t[e.attribute],Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(r=this.transformValue(r,e.options.transform)),(typeof r>"u"||r===null)&&!["typeof","isTruthy","eq"].includes(e.operator))return!1;switch(e.operator){case"eq":return e.options?.invert?!h.isEqual(r,s):h.isEqual(r,s);case"find":return e.options?.invert?!this.queryFind(r,s,i):this.queryFind(r,s,i);case"lt":return Array.isArray(r)?i==="some"?r.some(n=>n<s):r.every(n=>n<s):r<s;case"gt":return Array.isArray(r)?i==="some"?r.some(n=>n>s):r.every(n=>n>s):r>s;case"lte":return Array.isArray(r)?i==="some"?r.some(n=>n<=s):r.every(n=>n<=s):r<=s;case"gte":return Array.isArray(r)?i==="some"?r.some(n=>n>=s):r.every(n=>n>=s):r>=s;case"typeof":return e.options?.invert?typeof r!==s:Array.isArray(r)?i==="some"?r.some(n=>typeof n===s):r.every(n=>typeof n===s):typeof r===s;case"isTruthy":return s===!0?Array.isArray(r)?i==="some"?r.some(n=>typeof!!n):r.every(n=>typeof!!n):!!r:!r;case"size":return typeof r=="string"?r.length===s:h.size(r)===s;default:if(this.scriptController.hasScript(e.operator))return this.scriptController.executeScript(e.operator,"operator",{query:e,item:t});if(this.registeredCustomOperator.has(e.operator)){const n=this.registeredCustomOperator.get(e.operator);if(typeof n=="function")return n(e,t)}}return!1}evaluateEqOperator(e,t,r,s){const i=new Map,n=s.get(t.attribute);if(n){let a;if(typeof t.value=="string"?a=t.value:t.value?.key&&Object.keys(t.value).length===1&&(a=t.value.key),typeof a<"u"){const u=n.get(a);if(u)if(u.forEach(f=>{r.has(f)&&i.set(f,r.get(f))}),t.options?.invert){const f=h.differenceBy(Array.from(r.values()),Array.from(i.values()),"key"),c=new Map;return f.forEach(l=>{c.set(l.key,l)}),c}else return i}}for(let[a,u]of r){const f=this.queryBuilder.extractQueryAttributes({queries:[t]});if(f.some(c=>c.isDeepQuery)){const c=this.queryBuilder.getProjectionForAttributeEntries(f.filter(l=>l.isDeepQuery));u=this.globalItemService.getProjectedData(c,this.modelParser.models.get(e.modelKey),u)}this.evaluateQuery(t,u)&&i.set(a,u)}return i}equalRegexFn(e,t){if(typeof t=="string"&&h.startsWith(t,"/")&&h.endsWith(t,"/"))try{return new RegExp(t.slice(1,-1)).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(r=>h.isEqualWith(r,t,this.equalRegexFn)):typeof t=="object"?h.isMatch(e,t):e===t}queryFind(e,t,r){return Array.isArray(e)?typeof t=="string"||typeof t=="number"||typeof t=="boolean"?r==="some"?e.some(s=>h.isEqualWith(s,t,this.equalRegexFn)):e.every(s=>h.isEqualWith(s,t,this.equalRegexFn)):!!h.find(e,t):h.isEqualWith(e,t,this.equalRegexFn)}validateQuery(e){if(this.queryBuilder.isQuery(e)){if(!e.attribute||!e.operator)throw new Error("invalid query - missing attribute or operator");if(e.operator==="find"&&Array.isArray(e.value))throw new Error("invalid query - find operator cannot have array value");return!0}else{if(this.queryBuilder.isQueryGroup(e))return h.every(e.queries,t=>this.validateQuery(t));throw new Error("invalid query - missing query or attribute")}}getEvaluatedQueryDataset(e,t,r,s){const i=new Map;if(t.attribute.includes("[*]")){const n=t.options?.invert===!0,a=new Set;for(let u of r.values()){const f=this.queryBuilder.extractQueryAttributes({queries:[t]});if(f.some(d=>d.isDeepQuery)){const d=this.queryBuilder.getProjectionForAttributeEntries(f.filter(p=>p.isDeepQuery));u=this.globalItemService.getProjectedData(d,this.modelParser.models.get(e.modelKey),u)}const c=this.handleArrayStarQuery(t,u);let l=!1;for(const d of c.queries){const p={...d,options:{...d.options,invert:!1}};if(this.evaluateQuery(p,u)){l=!0;break}}l&&(a.add(u.key),n||i.set(u.key,u))}if(n)for(const[u,f]of r)a.has(u)||i.set(u,f)}else{if(t.operator==="eq")return this.evaluateEqOperator(e,t,r,s);for(let[n,a]of r){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(f=>f.isDeepQuery)){const f=this.queryBuilder.getProjectionForAttributeEntries(u.filter(c=>c.isDeepQuery));a=this.globalItemService.getProjectedData(f,this.modelParser.models.get(e.modelKey),a)}this.evaluateQuery(t,a)&&i.set(n,a)}}return i}handleArrayStarQuery(e,t){const r=e.attribute.indexOf("[*]"),s={groupKey:e.queryKey||e.attribute+"[*]",groupType:"or",queries:[]};if(r!==-1){const i=e.attribute.substring(0,r),n=i.includes(".")?h.get(t,i):t[i];if(Array.isArray(n))for(let a=0;a<n.length;a++){const u=e.attribute.replace("[*]",`[${a}]`);s.queries.push({attribute:u,operator:e.operator,value:e.value,options:e.options})}}return s}evaluateQueryGroup(e,t,r,s,i){let n=new Map,a=r;if(!t.queries||t.queries?.length===0)return a;for(const u of t.queries){let f=new Map;if(this.queryBuilder.isQuery(u)?f=this.getEvaluatedQueryDataset(e,u,a,i):f=this.evaluateQueryGroup(e,u,a,s,i),n.size===0&&(n=f),t.groupType==="or")f.forEach(c=>{n.set(c.key,c)});else{const c=h.differenceBy(Array.from(n.values()),Array.from(f.values()),"key");for(const l of c)n.delete(l.key)}t.groupType==="and"?a=n:a=r}return n}queryData(e,t,r,s){const i=new Map(e);return t.queries.length===0?e:(t.groupKey||(t.groupKey="root"),t.groupType||(t.groupType="and"),t.queries||(t.queries=[]),this.validateQuery(t),this.evaluateQueryGroup(t,t,i,r,s))}}class $e{scripts=new Map;scriptFunctions=new Map;constructor(){}keys(){return Array.from(this.scripts.keys())}setScript(e,t){this.scripts.set(e,t)}removeScript(e){this.scripts.delete(e)}getScript(e){return this.scripts.get(e)}hasScript(e){return this.scripts.has(e)}getScriptAsFn(e,t){if(this.scriptFunctions.has(e))return this.scriptFunctions.get(e);const r=this.getScript(e);if(!r)throw new Error(`Script ${e} not found`);const s=this.getWrapperScript(r),i=new Function("script_type",...t,s);return this.scriptFunctions.set(e,i),i}getWrapperScript(e){return`
2
2
  "use strict";
3
3
  ${e}
4
- `}executeScript(e,t,r){if(!this.getScript(e))throw new Error(`Script ${e} not found`);r.context||(r.context=r.options||{});const i=Object.keys(r),n=Object.values(r);return this.getScriptAsFn(e,i)(t,...n)}}const $e=(o,e)=>o?(e||(e={}),o.replace(/\$\{(.*?)\}/g,(t,r)=>h.get(e,r.trim(),""))):"",Fe=o=>{const e=new Set;return o.replace(/\$\{(.*?)\}/g,(r,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(r=>({name:r}))}},Te=["any","Array<date>","Array<float>","Array<int>","Array<string>","boolean","date","float","int","json","string"],Ge=["int","float","Array<int>","Array<float>"],Be=["date","Array<date>"],Pe=["eq","find","gt","gte","lt","lte","typeof","isTruthy","size"];exports.AnalyticsController=X;exports.AttributeDependencyGraph=ee;exports.CacheController=te;exports.ChangeDetector=de;exports.DatePropertyTypes=Be;exports.DcuplQueryBuilder=M;exports.DcuplQueryOperatorsAsArray=Pe;exports.DeepQueryService=_;exports.DependencyGraph=F;exports.IndicesController=L;exports.Logger=g;exports.NumberPropertyTypes=Ge;exports.PropertyTypesAsArray=Te;exports.QueryManager=qe;exports.ScriptController=Oe;exports.clone=I;exports.compareVersions=j;exports.computeSuggestions=le;exports.deepQueryService=y;exports.escapeRegExp=P;exports.evaluateTemplate=$e;exports.generateBooleanQuery=Ne;exports.generateKey=B;exports.generateNumberAndDateQuery=Ce;exports.generateReferenceQuery=ke;exports.generateTextQuery=Me;exports.getAggregation=A;exports.getDateConstraintUid=ne;exports.getDcuplPropertyTypeForNativeType=J;exports.getDistinct=W;exports.getFacets=Se;exports.getFilterEntryId=re;exports.getNumberConstraintUid=se;exports.getPropertiesForData=Ie;exports.groupBy=oe;exports.hasMinimumVersion=ce;exports.isDateInstance=R;exports.isFloat=U;exports.isInt=V;exports.isValidDate=z;exports.isValidQueryStatement=Ee;exports.isValidVersion=S;exports.logger=G;exports.parseDate=me;exports.parseTemplate=Fe;exports.perf=v;exports.pivot=N;exports.removeTrailingSlash=ae;exports.trigger=fe;exports.unescapeRegExp=ue;exports.uniqBy=ie;
4
+ `}executeScript(e,t,r){if(!this.getScript(e))throw new Error(`Script ${e} not found`);r.context||(r.context=r.options||{});const i=Object.keys(r),n=Object.values(r);return this.getScriptAsFn(e,i)(t,...n)}}const Fe=(o,e)=>o?(e||(e={}),o.replace(/\$\{(.*?)\}/g,(t,r)=>h.get(e,r.trim(),""))):"",Te=o=>{const e=new Set;return o.replace(/\$\{(.*?)\}/g,(r,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(r=>({name:r}))}},Ge=["any","Array<date>","Array<float>","Array<int>","Array<string>","boolean","date","float","int","json","string"],Be=["int","float","Array<int>","Array<float>"],Pe=["date","Array<date>"],je=["eq","find","gt","gte","lt","lte","typeof","isTruthy","size"];exports.AnalyticsController=ee;exports.AttributeDependencyGraph=te;exports.CacheController=re;exports.ChangeDetector=le;exports.DatePropertyTypes=Pe;exports.DcuplQueryBuilder=N;exports.DcuplQueryOperatorsAsArray=je;exports.DeepQueryService=W;exports.DependencyGraph=T;exports.IndicesController=V;exports.Logger=g;exports.NumberPropertyTypes=Be;exports.PropertyTypesAsArray=Ge;exports.QueryManager=Oe;exports.ScriptController=$e;exports.clone=M;exports.compareVersions=R;exports.computeSuggestions=he;exports.deepQueryService=y;exports.escapeRegExp=j;exports.evaluateTemplate=Fe;exports.generateBooleanQuery=Ce;exports.generateKey=P;exports.generateNumberAndDateQuery=ke;exports.generateReferenceQuery=Ee;exports.generateTextQuery=Ne;exports.getAggregation=b;exports.getDateConstraintUid=ie;exports.getDcuplPropertyTypeForNativeType=Z;exports.getDeepPathValues=w;exports.getDistinct=L;exports.getFacets=Ke;exports.getFilterEntryId=se;exports.getNumberConstraintUid=ne;exports.getPropertiesForData=Me;exports.groupBy=ae;exports.hasMinimumVersion=fe;exports.isDateInstance=z;exports.isFloat=J;exports.isInt=U;exports.isValidDate=_;exports.isValidQueryStatement=qe;exports.isValidVersion=K;exports.logger=B;exports.parseDate=ve;exports.parseTemplate=Te;exports.perf=v;exports.pivot=C;exports.removeTrailingSlash=ue;exports.trigger=de;exports.unescapeRegExp=ce;exports.uniqBy=oe;
5
5
  //# sourceMappingURL=index.cjs.map