@dcupl/common 2.0.0-beta.21 → 2.0.0-beta.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +542 -459
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/query-builder.d.ts +69 -7
- package/dist/esm/types/query.types.d.ts +11 -11
- package/dist/node/index.cjs +2 -2
- package/dist/node/index.cjs.map +1 -1
- package/package.json +1 -1
|
@@ -43,6 +43,34 @@ export declare class DcuplQueryBuilder {
|
|
|
43
43
|
isQueryGroup(query: Partial<DcuplQuery> | Partial<DcuplQueryGroup>): query is DcuplQueryGroup;
|
|
44
44
|
isRootQueryGroup(groupOrQuery: Partial<DcuplGlobalQueryOptions<any>> | Partial<DcuplQuery> | Partial<DcuplQueryGroup>): groupOrQuery is DcuplGlobalQueryOptions<any>;
|
|
45
45
|
getQueryGroup(groupKey?: string): DcuplQueryGroup | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* Find the group with the given `groupKey` at any nesting depth (#294).
|
|
48
|
+
*
|
|
49
|
+
* Unlike {@link getQueryGroup}, which only looks at the top level, this also finds a
|
|
50
|
+
* keyed group that sits inside a keyless wrapper group — the shape
|
|
51
|
+
* `apply({ groupType: 'and', queries: [{ groupKey: 'plan', ... }] }, { mode: 'set' })`
|
|
52
|
+
* produces. Groups on one level are checked before their children, so a top-level
|
|
53
|
+
* match wins over a nested one; otherwise the first match in query order wins
|
|
54
|
+
* (groupKeys are expected to be unique).
|
|
55
|
+
*
|
|
56
|
+
* @param groupKey - Key of the group to find
|
|
57
|
+
* @param relevantQuery - Query to search (defaults to the current query)
|
|
58
|
+
* @returns The matching group, or undefined
|
|
59
|
+
*/
|
|
60
|
+
findQueryGroup(groupKey: string | undefined, relevantQuery?: DcuplGlobalQueryOptions<any>): DcuplQueryGroup | undefined;
|
|
61
|
+
/**
|
|
62
|
+
* Path from the root `queries` array down to a group: each step names the array that
|
|
63
|
+
* holds a node and the node's index in it; the last step is the group itself.
|
|
64
|
+
*/
|
|
65
|
+
private locateQueryGroup;
|
|
66
|
+
private groupAtPath;
|
|
67
|
+
/**
|
|
68
|
+
* Walk a path upwards from its last group and splice every group that has no
|
|
69
|
+
* queries left, stopping at the first non-empty one. Mirrors the existing
|
|
70
|
+
* "remove the group when its queries are empty" behaviour for nested wrappers, so
|
|
71
|
+
* removing the only group inside a keyless wrapper also removes the wrapper.
|
|
72
|
+
*/
|
|
73
|
+
private pruneEmptyGroups;
|
|
46
74
|
getQuery(): DcuplGlobalQueryOptions<any>;
|
|
47
75
|
hasQueryGroup(groupKey: string): boolean;
|
|
48
76
|
has(options: {
|
|
@@ -69,8 +97,20 @@ export declare class DcuplQueryBuilder {
|
|
|
69
97
|
* - {@link replaceQuery} - Replace complete query
|
|
70
98
|
*
|
|
71
99
|
* @param queryToApply - Query, condition, or array to apply
|
|
72
|
-
* @param options - Mode: 'add' (default) or 'set'
|
|
73
|
-
*
|
|
100
|
+
* @param options - Mode: 'add' (default) or 'set'. `set` works per group, not per query:
|
|
101
|
+
* - Root group (`groupKey: 'root'`): replaces the whole query — all groups plus
|
|
102
|
+
* `count`/`start`/`sort`/`projection` (the only input that does).
|
|
103
|
+
* - Keyed group, or an array of groups: each group replaces the group with the same
|
|
104
|
+
* `groupKey`; every other group is kept. Same as {@link setGroup}.
|
|
105
|
+
* - Condition: replaces the conditions of the group keyed by its attribute.
|
|
106
|
+
*
|
|
107
|
+
* A group without `groupKey` is not the root, even if it carries a `queries` array:
|
|
108
|
+
* `apply({ groupType: 'and', queries: [...] }, { mode: 'set' })` stores it as a keyless
|
|
109
|
+
* wrapper group that replaces the first keyless top-level group, and the keyed groups
|
|
110
|
+
* inside it stay nested there. {@link removeQuery} and `fn.facets` still find them by
|
|
111
|
+
* `groupKey` at any depth (#294). To replace the whole query, pass `groupKey: 'root'`
|
|
112
|
+
* or use {@link replaceQuery}. In 'add' mode a group without `groupKey` is always
|
|
113
|
+
* appended as a new group, never merged into another.
|
|
74
114
|
* @param relevantQuery - Target query (defaults to current)
|
|
75
115
|
* @returns Updated query
|
|
76
116
|
*/
|
|
@@ -87,6 +127,15 @@ export declare class DcuplQueryBuilder {
|
|
|
87
127
|
/**
|
|
88
128
|
* Remove a specific query or query group.
|
|
89
129
|
*
|
|
130
|
+
* - A condition (`attribute` set) is removed from the group keyed by its attribute.
|
|
131
|
+
* - A group with `groupKey` but no `queries` is removed entirely.
|
|
132
|
+
* - A group with `groupKey` and `queries` has those conditions removed from it.
|
|
133
|
+
*
|
|
134
|
+
* The target group is looked up by `groupKey` at any nesting depth (see
|
|
135
|
+
* {@link findQueryGroup}), so a keyed group inside a keyless wrapper group is found
|
|
136
|
+
* too (#294). A group left without queries is removed, and so is every wrapper
|
|
137
|
+
* group that becomes empty as a result.
|
|
138
|
+
*
|
|
90
139
|
* @param queryToRemove - Query or group to remove (partial match)
|
|
91
140
|
* @param relevantQuery - Target query (defaults to current)
|
|
92
141
|
* @returns Updated query
|
|
@@ -238,9 +287,11 @@ export declare class DcuplQueryBuilder {
|
|
|
238
287
|
*/
|
|
239
288
|
addGroup(group: DcuplQueryGroup): DcuplGlobalQueryOptions<any>;
|
|
240
289
|
/**
|
|
241
|
-
* Replace
|
|
290
|
+
* Replace the conditions of an attribute group with new condition(s).
|
|
242
291
|
* Accepts single condition or array of conditions.
|
|
243
|
-
* Each condition replaces all existing conditions
|
|
292
|
+
* Each condition replaces all existing conditions of the group keyed by its attribute
|
|
293
|
+
* (created if missing); groups for other attributes and the query options are kept.
|
|
294
|
+
* This does not replace the whole query — see {@link replaceQuery} for that.
|
|
244
295
|
*
|
|
245
296
|
* Clearer alternative to `applyQuery(condition, { mode: 'set' })`.
|
|
246
297
|
*
|
|
@@ -261,8 +312,16 @@ export declare class DcuplQueryBuilder {
|
|
|
261
312
|
*/
|
|
262
313
|
setCondition(condition: DcuplQuery | DcuplQuery[]): DcuplGlobalQueryOptions<any>;
|
|
263
314
|
/**
|
|
264
|
-
* Replace
|
|
265
|
-
*
|
|
315
|
+
* Replace one query group by key (per-group `set`).
|
|
316
|
+
* The group with the same `groupKey` is replaced by the given definition; if none exists
|
|
317
|
+
* the group is appended. All other groups and the query options (`count`, `start`,
|
|
318
|
+
* `sort`, `projection`) are kept. An unkeyed group replaces the first unkeyed top-level
|
|
319
|
+
* group. Only a group with `groupKey: 'root'` replaces the whole query — equivalent to
|
|
320
|
+
* `applyQuery(rootGroup, { mode: 'set' })` / {@link replaceQuery}.
|
|
321
|
+
*
|
|
322
|
+
* A group without `groupKey` whose `queries` hold keyed groups is stored as a keyless
|
|
323
|
+
* wrapper; the keyed groups inside it stay nested and are still found by `groupKey`
|
|
324
|
+
* via {@link findQueryGroup}, {@link removeQuery} and `fn.facets` (#294).
|
|
266
325
|
*
|
|
267
326
|
* @param group - Query group to set
|
|
268
327
|
* @returns Updated query
|
|
@@ -302,7 +361,10 @@ export declare class DcuplQueryBuilder {
|
|
|
302
361
|
mergeQuery(query: DcuplGlobalQueryOptions<any>): DcuplGlobalQueryOptions<any>;
|
|
303
362
|
/**
|
|
304
363
|
* Replace the entire current query with a new query.
|
|
305
|
-
*
|
|
364
|
+
* Replaces all conditions and groups, and the root `groupType` when given. The query
|
|
365
|
+
* options (`count`, `start`, `sort`, `projection`) are kept — use {@link applyOptions}
|
|
366
|
+
* or `applyQuery({ groupKey: 'root', ... }, { mode: 'set' })` to replace those too.
|
|
367
|
+
* To replace a single group by key, use {@link setGroup}.
|
|
306
368
|
*
|
|
307
369
|
* @param query - Complete query to replace with
|
|
308
370
|
* @returns Updated query
|
|
@@ -380,17 +380,17 @@ export type DcuplQueryGroup<ChildQuery extends DcuplQuery | DcuplQueryGroup = an
|
|
|
380
380
|
*/
|
|
381
381
|
__type?: 'group';
|
|
382
382
|
/**
|
|
383
|
-
* Combination logic for conditions in this group.
|
|
384
|
-
*
|
|
385
|
-
*
|
|
386
|
-
*
|
|
387
|
-
*
|
|
388
|
-
*
|
|
389
|
-
*
|
|
390
|
-
*
|
|
391
|
-
*
|
|
392
|
-
*
|
|
393
|
-
*
|
|
383
|
+
* Combination logic for conditions in this group.
|
|
384
|
+
*
|
|
385
|
+
* Defaults to `'and'` at evaluation time: a group that reaches the query engine without a
|
|
386
|
+
* groupType (the root query, or a nested group passed inside a full query via
|
|
387
|
+
* `apply({ groupKey: 'root', ... })`, `init` or `execute`, or stored by `setGroup`
|
|
388
|
+
* replacing an existing group) is evaluated exactly like `groupType: 'and'`.
|
|
389
|
+
*
|
|
390
|
+
* Note that groups *created* by the query builder (`addGroup` / `setGroup` / `apply(group)`
|
|
391
|
+
* for a group not yet present) are stored as `'or'` when no groupType is given, and
|
|
392
|
+
* `addGroup` extending an existing keyed group keeps that group's current groupType. Set
|
|
393
|
+
* the groupType explicitly to avoid depending on either default.
|
|
394
394
|
*/
|
|
395
395
|
groupType?: DcuplQueryType;
|
|
396
396
|
/**
|
package/dist/node/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("lodash-es");function I(n){const e=Q(n);return oe(e)}function Q(n){if(typeof n!="object"||n===null)return String(n);if(Array.isArray(n))return"["+n.map(Q).join(",")+"]";const e=Object.keys(n).sort();let t="{";for(let r=0;r<e.length;r++){const s=e[r];t+=s+":"+Q(n[s]),r<e.length-1&&(t+=",")}return t+="}",t}function oe(n){let e=0;for(let t=0;t<n.length;t++){const r=n.charCodeAt(t);e=(e<<5)-e+r,e|=0}return e.toString(16)}const b={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:n=>{typeof performance<"u"&&performance.mark&&performance.mark(n)},measure:(n,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(n,e,t)},getEntriesByName(n){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(n)},getEntriesByType(n){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(n)}};class ae{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:b.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,o=Math.round(i*100)/100,a=this.data.get(t);if(a&&e.sum){const u=a.value+o,f={...a,value:u};return this.data.set(t,f),f}const c={name:e.name,type:"measure",value:o,createdAt:Date.now()};return e.detail&&(c.detail=e.detail),this.data.set(t,c),c}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"?[]:b.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 P=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 o of i)if(r(o))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 o=this.edges.get(i);if(o)for(let a of o){const c=s(a);if(c)return c}return r.pop(),t.delete(i),e.add(i),null};for(let i of this.nodes){const o=s(i);if(o)return{hasCycle:!0,path:o}}return{hasCycle:!1}}order(e){const t=new Set,r=new Set,s=[],i=e?.allowCycles??!1,o=a=>{if(t.has(a))return;if(r.has(a)){if(i)return;throw new Error("Graph has a cycle.")}r.add(a);const c=this.edges.get(a);if(c)for(let u of c)o(u);r.delete(a),t.add(a),s.push(a)};for(let a of this.nodes)t.has(a)||o(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 o of this.nodes)t.set(o,0);for(const o of this.edges.values())for(const a of o)t.set(a,(t.get(a)||0)+1);const r=[];let s=Array.from(this.nodes).filter(o=>(t.get(o)||0)===0);const i=new Set;for(;s.length>0;){const o=s.slice();r.push(o),s=[];for(const a of o){if(i.has(a))continue;i.add(a);const c=this.edges.get(a);if(c)for(const u of c)t.set(u,(t.get(u)||0)-1),(t.get(u)||0)===0&&s.push(u)}}if(i.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const o=new Set(e.filterKinds);return{batches:r.map(a=>a.filter(c=>o.has(this.nodeKinds.get(c))))}}return{batches:r}}getImpactedNodes(e,t="downstream",r){const s=new Set(e),i=u=>!r||r.length===0||r.includes(this.nodeKinds.get(u)??void 0),o=()=>{const u=new Set,f=Array.from(s);for(;f.length;){const d=f.shift();for(const[l,h]of this.edges)h.has(d)&&!u.has(l)&&(u.add(l),f.push(l))}return u},a=()=>{const u=new Set,f=Array.from(s);for(;f.length;){const d=f.shift(),l=this.edges.get(d);if(l)for(const h of l)u.has(h)||(u.add(h),f.push(h))}return u};let c;return t==="both"?c=new Set([...o(),...a()]):t==="upstream"?c=a():c=o(),Array.from(c).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(d=>!t.has(d)),i=Array.from(t).filter(d=>!r.has(d)),o=new Set(this.getAllEdges().map(d=>d.join("→"))),a=new Set(e.getAllEdges().map(d=>d.join("→"))),c=Array.from(a).filter(d=>!o.has(d)).map(d=>d.split("→")),u=Array.from(o).filter(d=>!a.has(d)).map(d=>d.split("→")),f=[];for(const d of new Set([...t,...r])){const l=this.nodeKinds.get(d),h=e.nodeKinds.get(d);l!==h&&f.push({name:d,from:l,to:h})}return{addedNodes:s,removedNodes:i,addedEdges:c,removedEdges:u,kindChanges:f}}};class ce{graph;nodeIndex;constructor(){this.graph=new P,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],o=new Set;return i.filter(a=>{const c=this.getNodeId(a.modelKey,a.attributeKey);return o.has(c)?!1:(o.add(c),!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:o,processingStep:a}=s;t.has(i)||t.set(i,new Map);const c=t.get(i);c.has(a)||c.set(a,new Set),c.get(a).add(o)}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 o=0;for(const a of i){const c=t(a,new Set(s));o=Math.max(o,c)}return o+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 o=this.getNodeId(r,i);this.hasNode(o)||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 T={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 T[e]<=T[t]}formatMessage(e){if(this.config.format==="json"){const o={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(o.module=e.prefix),e.context&&(o.context=e.context),e.error&&(o.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(o)}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 o=this.formatMessage(i);if(typeof console<"u")switch(e){case"error":s?console.error(o,s):console.error(o);break;case"warn":console.warn(o);break;case"debug":console.debug?console.debug(o):console.log(o);break;default:console.log(o)}}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 z=new g;class ue{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}enabled;cache;cacheDependencies;hitCount=0;missCount=0;log=z.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[o,a]of e){if(s.models.has(o))if(s.modelAttributes.has(o)){const c=s.modelAttributes.get(o);for(const u of a)if(c.has(u)){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 o of t)if(i.models.has(o)){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 p.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 N=(n,e="")=>{if(!(typeof n!="string"||!n.startsWith("/")||!n.endsWith("/")))return{pattern:n.slice(1,-1),flags:e}},fe=(n,e="")=>`${n}#${e}`,de=n=>`${n.gt}_${n.gte}_${n.lt}_${n.lte}_${n.eq}_${n.ne}`,le=n=>`${n.gt}_${n.gte}_${n.lt}_${n.lte}_${n.eq}_${n.ne}`,he=(n,e)=>{const t=typeof e=="function"?e:r=>r[e];return[...n.reduce((r,s)=>{const i=s==null?s:t(s);return r.has(i)||r.set(i,s),r},new Map).values()]},pe=(n,e)=>n.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(n=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let r=0;r<n;r++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}const ge=n=>n.replace(/\/+$/,""),j=n=>typeof n!="string"?"":n.replace(/[[\]{}()*+?.,\\^$|#]/g,"\\$&"),ye=n=>typeof n!="string"?"":n.replace(/\\([[\]{}()*+?.,\\^$|#])/g,"$1"),me=(n,e)=>{try{return L(n,e)>=0}catch{return!1}},L=(n,e)=>{if(!E(n)||!E(e))throw new Error(`Invalid version format: v1="${n}", v2="${e}". Expected format: "x.y.z"`);const t=n.split(".").map(Number),r=e.split(".").map(Number);for(let s=0;s<3;s++){const i=t[s]||0,o=r[s]||0;if(i>o)return 1;if(i<o)return-1}return 0},E=n=>/^\d+(\.\d+){0,2}$/.test(n);class ve{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=b.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 O=(n,e)=>e?typeof structuredClone<"u"?structuredClone(n):p.cloneDeep(n):n,F=(n,e,t,r,s,i)=>{try{const o=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=O(i,o);if(t.scope==="list"&&(t.listKey=n.cdRef?.key||n.key,t.modelKey=n.model?.key||n.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const c=b.now(),u=c-r,f=Math.round(u*1e3)/1e3;t.duration=f,t.start=r,t.end=c;const d={duration:t.duration};return t.modelKey&&(d.model=t.modelKey),t.connectMessageResult&&(t.result=a),t.args&&(d.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:d}),a}catch{return i}},we=n=>(t,r,s)=>{const i=s.value;return s.value=function(...o){const a=b.now(),c=this.cdRef,u=O(n,!0);u.key||(c.increaseCounter(),u.key=c.getCounter());const f=B();c.analyticsController.mark({name:`${u.type}:start`,context:f});const d=this.model?.key;!u.originCdRefKey&&c.key&&(u.originCdRefKey=c.key),d&&(u.modelKey=d);const l=i.apply(this,o);return u.method=r,u.args=o,l&&typeof l=="object"&&"then"in l?l.then(h=>F(this,c,u,a,f,h)):F(this,c,u,a,f,l)},s};function xe(n,e,t,r){t.max||(t.max=20);const s=[],i=t.transform?r.transformValue(t.value,t.transform):t.value;for(const[o,a]of e.entries()){const c=Array.from(a).some(f=>n.has(f)),u=t.transform?r.transformValue(o,t.transform):o;if(!(t.excludeUndefineds&&typeof o>"u")&&!(t.excludeNulls&&o===null)){if(c&&(i===""||i==="//")){const f={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}else if(c&&N(i)){if(r.queryFind(u,i,"some",t.regexFlags)){const f={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}}else if(c&&typeof i=="string"){const f=String(u??""),d=i;if(f.toLowerCase().startsWith(d.toLowerCase())){const l={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(l)}}else if(c&&r.queryFind(u,i,"some")){const f={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}if(s.length===t.max)break}}return s}function V(n){return n instanceof Date}function U(n){return n instanceof Date&&!isNaN(n.getTime())}const Ae={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 be(n){let e="^";const t=[];let r=n;const s=Object.entries(Ae).sort((i,o)=>o[0].length-i[0].length);for(;r.length>0;){let i=!1;for(const[o,a]of s)if(r.startsWith(o)){e+=a.regex,t.push({type:a.type,pattern:o}),r=r.slice(o.length),i=!0;break}if(!i){const o=r[0];if(!o)break;e+=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=r.slice(1)}}return e+="$",{regex:new RegExp(e),tokenOrder:t}}function De(n,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=n[r+1];if(!s)continue;const i=parseInt(s,10),o=e[r];o&&(o.type==="year"&&o.pattern==="yy"?t.year=2e3+i:t[o.type]=i)}return t}function Se(n){if(n.month<1||n.month>12)return new Date(NaN);if(n.day<1||n.day>31)return new Date(NaN);if(n.hour<0||n.hour>23)return new Date(NaN);if(n.minute<0||n.minute>59)return new Date(NaN);if(n.second<0||n.second>59)return new Date(NaN);if(n.millisecond<0||n.millisecond>999)return new Date(NaN);const e=new Date(n.year,n.month-1,n.day,n.hour,n.minute,n.second,n.millisecond);return U(e)?e.getFullYear()!==n.year||e.getMonth()!==n.month-1||e.getDate()!==n.day?new Date(NaN):e:new Date(NaN)}function Ie(n,e,t){if(n=n.trim(),e==="t"){const a=Number(n);return isNaN(a)?new Date(NaN):new Date(a*1e3)}if(e==="T"){const a=Number(n);return isNaN(a)?new Date(NaN):new Date(a)}const{regex:r,tokenOrder:s}=be(e),i=n.match(r);if(!i)return new Date(NaN);const o=De(i,s);return Se(o)}class Ke{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 ke{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 o=this.graph.get(i);if(o){for(const a of o)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 o=e[i],a=e[i+1];o&&a&&this.addDependency(o,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 Ke(e),this.circularRefDetector=new ke}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("["),o=s||i;if(o){r=e.split(/[.[]/)[0];const c=e.indexOf("."),u=e.indexOf("[");if(i&&(c===-1||u<c)){const d=e.indexOf("]");if(d>-1){const l=e.indexOf(".",d+1);l>-1?t=e.substring(l+1):t=void 0}else s&&(t=e.substring(c+1))}else s&&(t=e.substring(c+1))}const a={attribute:e,isDeepQuery:o};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 o=/\[([^\]]+)\]/g;let a;for(;(a=o.exec(e))!==null;){const f=a[1];f&&f!=="*"&&!/^\d+$/.test(f)&&r.push(`Invalid bracket content: Must be a number or '*', got '${f}' in ${e}`)}const c=(e.match(/\./g)||[]).length+1;c>t&&r.push(`Path too deep: Maximum depth is ${t}, got ${c} in ${e}`);const u=e.match(/[^a-zA-Z0-9._[\]*-]/g);return u&&r.push(`Invalid characters in path: ${u.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 m=new W;function w(n,e){if(e.includes("[*]")){const i=e.indexOf("[*]"),o=e.substring(0,i),a=e.substring(i+3),c=o?p.get(n,o):n;if(!Array.isArray(c))return[];const u=[];for(const f of c)!a||a===""?f!==void 0&&u.push(f):a.startsWith(".")&&u.push(...w(f,a.slice(1)));return u}const t=e.split(".");let r=[n];for(const i of t){const o=[];for(const a of r)if(a!=null)if(Array.isArray(a))for(const c of a){if(c==null)continue;const u=c[i];u!==void 0&&o.push(u)}else{const c=a[i];c!==void 0&&o.push(c)}if(r=o,r.length===0)return[]}const s=[];for(const i of r)if(Array.isArray(i))for(const o of i)o!==void 0&&s.push(o);else i!==void 0&&s.push(i);return s}function M(n){let e=0;for(let t of n){const r=t.toString().split(".")[1];r&&(e=Math.max(e,r.length))}return Math.pow(10,e)}function q(n,e,t){return(n*t+e*t)/t}function Me(n,e,t){return n*t/(e*t)}const K=(n,e,t,r)=>{if(!r)throw new Error("Attribute not found");const s={attribute:r,types:n.types};let i;(s.types.includes("sum")||s.types.includes("avg"))&&(i=Ne(r,e));let o;return(s.types.includes("min")||s.types.includes("max"))&&(o=Ee(r,e)),n.types.forEach(a=>{a==="sum"?s.sum=i?.sum:a==="avg"?s.avg=i?.average:a==="count"?s.count=Qe(r,e):a==="min"?s.min=o&&o[0]:a==="max"?s.max=o&&o[1]:a==="distinct"?s.distinct=H(n,e,t):a==="group"&&(s.group=Ce(n,e))}),s},Qe=(n,e)=>{const r=m.parse(n).isDeepQuery;let s=0;for(const i of e.values())if(i)if(r)s+=w(i,n).filter(o=>o!=null).length;else{const o=i[n];if(o==null)continue;Array.isArray(o)?s+=o.filter(a=>a!=null).length:s++}return s},Ee=(n,e)=>{let t,r;const i=m.parse(n).isDeepQuery;for(const o of e.values()){if(!o)continue;let a;if(i)a=w(o,n);else{const c=o[n];c===void 0?a=[]:Array.isArray(c)?a=c.filter(u=>u!==void 0):a=[c]}for(const c of a)c==null||typeof c=="object"||((t===void 0||c<t)&&(t=c),(r===void 0||c>r)&&(r=c))}if(!(t===void 0||r===void 0))return[t,r]},Ce=(n,e)=>{const t=[];n.groupOptions?.groups?.forEach(o=>{t.push({option:o,count:0,keys:[]})});const r={option:{value:["$dcupl_not_found"]},count:0,keys:[]},i=m.parse(n.attribute).isDeepQuery;for(const o of e.values()){let a;i?a=w(o,n.attribute):a=[o[n.attribute]];let c=!1;for(const u of a)for(const f of t)(typeof f.option.value<"u"&&f.option.value.includes(u)||typeof f.option.from<"u"&&f.option.from<u&&typeof f.option.to<"u"&&f.option.to>u)&&(f.keys.includes(o.key)||(f.count++,f.keys.push(o.key)),c=!0);!c&&n?.groupOptions?.calculateNotFound&&(r.count++,r.keys.push(o.key))}return n?.groupOptions?.calculateNotFound&&t.push(r),t},Ne=(n,e)=>{let t=0,r=0;const i=m.parse(n).isDeepQuery;for(const a of e.values()){if(!a)continue;let c;if(i)c=w(a,n);else{const u=a[n];u===void 0?c=[]:Array.isArray(u)?c=u:c=[u]}for(const u of c)if(Array.isArray(u))for(const f of u)typeof f=="number"&&(t=q(t,f,M([t,f])),r++);else typeof u=="number"&&(t=q(t,u,M([t,u])),r++)}return r===0?void 0:{average:Me(t,r,M([t,r])),count:r,sum:t}},H=(n,e,t)=>{const r=[];for(const[s,i]of t)if(!(n.excludeUndefineds&&typeof s>"u")&&Array.from(i).find(o=>e.has(o))){const o={value:s,count:i.size};if(n.distinctOptions?.skipKeys||(o.keys=Array.from(i)),r.push(o),n.distinctOptions?.limit&&r.length>=n.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 ${_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=p.cloneDeep(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||m}init(e){this._initOptions=p.cloneDeep(e),this.currentQuery=p.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=p.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"queries"in e||"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 p.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:p.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 i=e.groupKey===void 0&&t?.mode!=="set"?-1:r.queries.findIndex(o=>this.isQueryGroup(o)&&o.groupKey===e.groupKey);if(i>-1){const o=r.queries[i];e.groupType&&(o.groupType=e.groupType),t?.mode==="set"?r.queries[i]=e:o.queries=[...o.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=p.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 o=p.findIndex(s.queries,i);o>-1&&s.queries.splice(o,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)),e.operator==="in"&&typeof e.value<"u"&&!Array.isArray(e.value)&&t.push(new x("in operator needs an array value",e)),t.length>0?{valid:!1,errors:t}:{valid:!0};if(this.isQueryGroup(e)){const i=e.queries.map(o=>this.validateQuery(o)).filter(o=>!o.valid).map(o=>o.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 o of i)this.isQuery(o)?o.attribute&&!r.has(o.attribute)&&(t.push(o.attribute),r.add(o.attribute)):this.isQueryGroup(o)&&s(o.queries)};return s(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],r=new Set,s=i=>{for(const o of i)if(this.isQuery(o)){if(o.attribute&&!r.has(o.attribute)){const a=this.getQueryAttributeForString(o.attribute);t.push(a),r.add(o.attribute)}}else this.isQueryGroup(o)&&s(o.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(o=>{o!=="$"&&r.reference&&(t[r.reference][o]=i[o])})}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 o in e)if(s[o]!==e[o]){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 C=new $;function Oe(n,e,t,r,s,i,o){const a=t.excludeGroup??s,c=C.removeQuery({groupKey:a},p.cloneDeep(r)),u=o.queryData(n,c,!1,i),f=e?[...e.keys()]:[],d=new Set(f),l=i.get(s)??new Map;if(!t.excludeUnresolved)for(const y of l.keys())d.add(y);if(t.excludeUndefineds?d.delete(void 0):d.add(void 0),t.sort){const y=[];for(const k of d.values())y.push(_(k,l,u,e,s,a,r,!0));const v=t.excludeZeros?y.filter(k=>k.size>0):y;return v.sort($e(t.sort)),t.count?v.slice(0,t.count):v}const h=[];for(const y of d.values()){const v=_(y,l,u,e,s,a,r,!!t?.calculateFacets);if(!(t?.excludeZeros&&v.size===0)){if(t?.count&&h.length===t?.count)return h;h.push(v)}}return h}function _(n,e,t,r,s,i,o,a){const c=new Map,u=e.get(n)||new Set;for(const f of u){const d=t.get(f);if(d&&(c.set(f,d),!a))break}return{key:String(n),value:n,selected:Re(i,s,n,o),enabled:c.size>0,size:c.size,entry:r?.get(n),resultKeys:Array.from(c.keys())}}function D(n,e){if(n===void 0&&e===void 0)return 0;if(n===void 0)return 1;if(e===void 0)return-1;const t=typeof n,r=typeof e;if(t!==r)return t<r?-1:1;if(t==="number")return n-e;if(t==="string")return n.localeCompare(e);const s=String(n),i=String(e);return s<i?-1:s>i?1:0}function $e(n){switch(n){case"size-desc":return(e,t)=>t.size-e.size||D(e.value,t.value);case"size-asc":return(e,t)=>e.size-t.size||D(e.value,t.value);case"value-asc":return(e,t)=>D(e.value,t.value);case"value-desc":return(e,t)=>e.value===void 0&&t.value===void 0?0:e.value===void 0?1:t.value===void 0?-1:-D(e.value,t.value)}}const Re=(n,e,t,r)=>{const s=r.queries.findIndex(i=>C.isQueryGroup(i)&&i.groupKey===n);return s>-1?!!r.queries[s].queries.find(o=>C.isQuery(o)?o.attribute!==e?!1:(o.operator==="in"&&Array.isArray(o.value)?o.value:[o.value]).some(c=>(c?.key||c)===t):!1):!1};class J{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())}resetIndicesWhere(e){for(const t of Array.from(this.indexMap.keys()))e(t)&&this.reset(t)}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 o=r.get(i);o||(o={key:i},this.dataMap.get(e)?.set(i,o))}}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 o;if(typeof i=="object"&&i&&i.key)o=i.key;else if(Array.isArray(i)){for(const c of i)this.fillInverseIndex(e,t,[c]);return}else i instanceof Date?o=i.toISOString():o=i;let a=s.get(o);a||(a=new Set,s.set(o,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 o=this.indexMetadata.get(s);if(o)o.lastAccessedAt=Date.now();else if(!i){const c=m.parse(e).isDeepQuery??!1;this.indexMetadata.set(s,{createdAt:Date.now(),lastAccessedAt:Date.now(),context:r,type:c?"deep":"shallow"})}if(!i){this.reset(s),this.indexMap.set(s,new Map);const c=m.parse(e).isDeepQuery;for(const u of t.values()){let f;c?(f=w(u,e),f.length===0&&(f=[void 0])):f=[u[e]],this.fillInverseIndex(s,u.key,f),this.fillDataMap(s,f)}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 o;if(typeof i=="object"&&i&&i.key)o=i.key;else if(Array.isArray(i)){for(const c of i)this.removeFromInverseIndex(e,t,[c]);return}else i instanceof Date?o=i.toISOString():o=i;const a=s.get(o);a&&(a.delete(t),a.size===0&&s.delete(o))}}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 o of s)this.removeFromDataMap(e,[o]);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 m.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 o of this.indexMetadata.values()){const a=t-o.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 A="__";function R(n,e,t={key:"root"},r="root",s=new J,i){const o=i||n;for(const a of e.columns)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,o));for(const a of e.rows)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,o));for(const a of e.values)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,o));if(e.rows&&e.rows.length>0){t.rows=t.rows||[];const a=Te(n,e.rows[0],e,s,r,i);t.rows.push(a)}if(e.columns&&e.columns.length>0){t.columns=t.columns||[];const a=X(n,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 c=K(a,n,s.getIndex(a.attribute),a.attribute);t.values.push(c)}return t}function Te(n,e,t,r,s="",i){const o={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return o;for(const[c,u]of a.entries()){const f={key:c,value:c},d=new Map;for(const l of u)n.has(l)&&d.set(l,n.get(l));if(d.size){for(const l of t.values){if(f.values=f.values||[],s==="root"&&e?.calculateTotals===!1)continue;const h=K(l,d,r.getIndex(l.attribute),l.attribute);f.values.push(h)}if(o.rows=o.rows||[],o.rows.push(f),t.rows.length>1){const l={...t,rows:t.rows.slice(1)};R(d,l,f,s+A+e.attribute+A+c,r,i)}else if(t.columns)for(const l of t.columns){f.columns=f.columns||[];const h=X(d,l,t,r,s+A+e.attribute+A+c,i);f.columns.push(h)}}}return o}function X(n,e,t,r,s="",i){const o={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return o;for(const[c,u]of a.entries()){const f={key:c,value:c},d=new Map;for(const l of u)n.has(l)&&d.set(l,n.get(l));if(d.size){for(const l of t.values){if(f.values=f.values||[],s==="root"&&e?.calculateTotals===!1)continue;const h=K(l,d,r.getIndex(l.attribute),l.attribute);f.values.push(h)}if(o.columns=o.columns||[],o.columns.push(f),t.columns.length>1){const l={...t,columns:t.columns.slice(1)};R(d,l,f,s+A+e.attribute+A+c,r,i)}}}return o}const Fe=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/,qe=/^-?\d+$/,_e=/^-?\d+\.\d+$/,Pe=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,Z=n=>n==="true"||n==="false"?"boolean":qe.test(n)?"int":_e.test(n)?"float":Fe.test(n)&&!Number.isNaN(Date.parse(n))?"date":"string",Y=n=>Pe.test(n),Ge=n=>n==null||n==="",ze=n=>{const e=[...n];return e.length<=1?{type:e[0]??"any",conflict:!1}:e.every(t=>t==="int"||t==="float")?{type:"float",conflict:!1}:{type:"any",conflict:!0}},ee=(n,e={})=>{const r=e.deep??(e.sampleSize!==void 0&&e.sampleSize>1)?e.sampleSize??1/0:1,s=e.coerceStrings??!0,i=new Map,o=[],a=Math.min(n.length,r);for(let f=0;f<a;f++){const d=n[f];if(d)for(const[l,h]of Object.entries(d)){let y=i.get(l);if(y||(y={observed:new Set,empty:0,scanned:0},i.set(l,y),o.push(l)),y.scanned++,Ge(h)){y.empty++;continue}let v;typeof h=="string"&&s?(v=Z(h),v==="string"&&!y.hint&&Y(h)&&(y.hint="column looks date-like (non-ISO) — review manually")):v=se(h),y.observed.add(v)}}const c=[],u=[];for(const f of o){const d=i.get(f),{type:l,conflict:h}=ze(d.observed.size?d.observed:new Set(["string"]));c.push({key:f,type:l}),u.push({column:f,inferredType:l,observedTypes:[...d.observed].sort(),emptyRate:d.scanned===0?0:d.empty/d.scanned,conflict:h,hint:d.hint})}return{properties:c,diagnostics:u}},Be=(n,e=!1)=>ee(n,typeof e=="boolean"?{deep:e}:e).properties,te=n=>Number(n)===n&&n%1===0,re=n=>Number(n)===n&&n%1!==0,se=n=>{switch(typeof n){case"string":return"string";case"number":return te(n)?"int":re(n)?"float":"any";case"boolean":return"boolean";case"object":return V(n)?"date":"json";default:return"any"}},je=(n,e)=>{const t=j(n.text||""),r=e?.attributeKey||n.filterKey;let s;const i=e?.comparisonType||"containsIgnoreCase";return i==="containsIgnoreCase"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["lowercase"]}}]}:i==="containsIgnoreCaseAndWhitespace"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["removeWhitespace","lowercase"]}}]}:i==="contains"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:`/${t}/`,operator:"find"}]}:i==="equal"?s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:n.text,operator:"eq"}]}:i==="equalIgnoreCase"&&(s={groupKey:n.filterKey,queries:[{queryKey:n.text,attribute:r,value:n.text,operator:"eq",options:{transform:["lowercase"]}}]}),s},Le=(n,e)=>{const t=e?.attributeKey||n.filterKey;return{groupKey:n.filterKey,queries:[{queryKey:n.value,attribute:t,value:n.value,operator:"eq"}]}},Ve=(n,e)=>{const t=e?.attributeKey||n.filterKey,r={groupKey:n.filterKey,queries:[]};return typeof n.eq<"u"&&(r.groupType="or",Array.isArray(n.eq)?n.eq.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq"})}):r.queries.push({attribute:t,value:n.eq,operator:"eq"})),typeof n.ne<"u"&&(r.groupType="and",Array.isArray(n.ne)?n.ne.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq",options:{invert:!0}})}):r.queries.push({attribute:t,value:n.ne,operator:"eq",options:{invert:!0}})),typeof n.gt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.gt,operator:"gt"})),typeof n.lt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.lt,operator:"lt"})),typeof n.gte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.gte,operator:"gte"})),typeof n.lte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:n.lte,operator:"lte"})),r},Ue=(n,e)=>{const t=e?.attributeKey||n.filterKey,r={groupKey:n.filterKey,queries:[]};return n.itemKeys.forEach(s=>{r.queries.push({queryKey:s,attribute:t,value:{key:s},operator:"eq"})}),r},We=n=>!(typeof n.modelKey!="string"||!Array.isArray(n.queries));class He{constructor(e,t,r){this.scriptController=e,this.globalItemService=t,this.modelParser=r}scriptController;globalItemService;modelParser;registeredCustomOperator=new Map;queryBuilder=new $;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=e.value;const s=e.options?.arrayValueHandling||"some";Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(r=this.transformValue(r,e.options.transform));let i=this.getAttributeValue(t,e.attribute);if(Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(i=this.transformValue(i,e.options.transform)),(typeof i>"u"||i===null)&&!["typeof","isTruthy","eq","in"].includes(e.operator))return!1;let o;switch(e.operator){case"eq":o=this.queryEq(i,r,s);break;case"in":o=this.queryIn(i,r,s);break;case"find":o=this.queryFind(i,r,s,e.options?.regexFlags);break;case"lt":case"gt":case"lte":case"gte":{const a=e.operator;o=this.matchValues(i,s,c=>this.compareValue(a,c,r));break}case"typeof":o=this.matchValues(i,s,a=>typeof a===r);break;case"isTruthy":{const a=r===!0;o=this.matchValues(i,s,c=>!!c===a);break}case"size":typeof i=="string"?o=i.length===r:o=p.size(i)===r;break;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 a=this.registeredCustomOperator.get(e.operator);if(typeof a=="function")return a(e,t)}return!1}return e.options?.invert?!o:o}compareValue(e,t,r){if(t==null)return!1;switch(e){case"lt":return t<r;case"gt":return t>r;case"lte":return t<=r;case"gte":return t>=r}}getAttributeValue(e,t){if(t in e||!(t.includes(".")||t.includes("[")))return e[t];if(t.includes("["))return p.get(e,t);const r=t.split(".");let s=e;for(let i=0;i<r.length;i++){const o=r[i];if(s==null)return;if(Array.isArray(s)&&o!=="length"&&!/^\d+$/.test(o))return w(s,r.slice(i).join("."));s=s[o]}return s}matchValues(e,t,r){return Array.isArray(e)?t==="every"?e.length>0&&e.every(r):e.some(r):r(e)}queryEq(e,t,r){return Array.isArray(e)&&!Array.isArray(t)?this.matchValues(e,r,s=>this.equalsQueryValue(s,t)):this.equalsQueryValue(e,t)}queryIn(e,t,r){return!Array.isArray(t)||t.length===0?!1:this.matchValues(e,r,s=>t.some(i=>this.equalsQueryValue(s,i)))}getIndexKey(e){if(typeof e=="string")return e;if(e?.key&&Object.keys(e).length===1)return e.key}equalsQueryValue(e,t){const r=this.getIndexKey(t);return typeof r>"u"?p.isEqual(e,t):e instanceof Date?!isNaN(e.getTime())&&e.toISOString()===r:typeof e=="object"&&e?.key?e.key===r:e===r}canUseIndex(e){return e.options?.arrayValueHandling!=="every"&&!e.options?.transform?.length}evaluateEqOperator(e,t,r,s){const i=new Map,o=this.canUseIndex(t)?s.get(t.attribute):void 0;if(o){const a=this.getIndexKey(t.value);if(typeof a<"u"){const c=o.get(a);if(c)if(c.forEach(u=>{r.has(u)&&i.set(u,r.get(u))}),t.options?.invert){const u=p.differenceBy(Array.from(r.values()),Array.from(i.values()),"key"),f=new Map;return u.forEach(d=>{f.set(d.key,d)}),f}else return i}}return this.scanDataset(e,t,r)}evaluateInOperator(e,t,r,s){const i=this.canUseIndex(t)?s.get(t.attribute):void 0;if(!i)return this.scanDataset(e,t,r);const o=new Map,a=[];for(const u of t.value){const f=this.getIndexKey(u),d=typeof f<"u"?i.get(f):void 0;if(!d){a.push(u);continue}d.forEach(l=>{const h=r.get(l);h&&o.set(l,h)})}if(a.length>0){const u=new Map;r.forEach((d,l)=>{o.has(l)||u.set(l,d)});const f={...t,value:a,options:{...t.options,invert:!1}};this.scanDataset(e,f,u).forEach((d,l)=>o.set(l,d))}if(!t.options?.invert)return o;const c=new Map;return r.forEach((u,f)=>{o.has(f)||c.set(f,u)}),c}scanDataset(e,t,r){const s=new Map,i=this.queryBuilder.extractQueryAttributes({queries:[t]}).filter(a=>a.isDeepQuery),o=i.length>0?this.queryBuilder.getProjectionForAttributeEntries(i):void 0;for(let[a,c]of r)o&&(c=this.globalItemService.getProjectedData(o,this.modelParser.models.get(e.modelKey),c)),this.evaluateQuery(t,c)&&s.set(a,c);return s}equalRegexFn(e,t,r){const s=N(t,r);if(s)try{return new RegExp(s.pattern,s.flags).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(i=>p.isEqualWith(i,t,(o,a)=>this.equalRegexFn(o,a,r))):typeof t=="object"?p.isMatch(e,t):e===t}queryFind(e,t,r,s){const i=(o,a)=>this.equalRegexFn(o,a,s);return Array.isArray(e)?typeof t=="string"||typeof t=="number"||typeof t=="boolean"?this.matchValues(e,r,o=>p.isEqualWith(o,t,i)):t!==null&&typeof t=="object"?this.matchValues(e,r,o=>p.isMatch(o,t)):!!p.find(e,t):p.isEqualWith(e,t,i)}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");if(e.operator==="in"&&!Array.isArray(e.value))throw new Error("invalid query - in operator needs an array value");return!0}else{if(this.queryBuilder.isQueryGroup(e))return p.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 o=t.options?.invert===!0,a=new Set;for(let c of r.values()){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(h=>h.isDeepQuery)){const h=this.queryBuilder.getProjectionForAttributeEntries(u.filter(y=>y.isDeepQuery));c=this.globalItemService.getProjectedData(h,this.modelParser.models.get(e.modelKey),c)}const d=this.handleArrayStarQuery(t,c).queries.map(h=>({...h,options:{...h.options,invert:!1}}));this.matchValues(d,t.options?.arrayValueHandling||"some",h=>this.evaluateQuery(h,c))&&(a.add(c.key),o||i.set(c.key,c))}if(o)for(const[c,u]of r)a.has(c)||i.set(c,u)}else return t.operator==="eq"?this.evaluateEqOperator(e,t,r,s):t.operator==="in"?this.evaluateInOperator(e,t,r,s):this.scanDataset(e,t,r);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),o=i.includes(".")?p.get(t,i):t[i];if(Array.isArray(o))for(let a=0;a<o.length;a++){const c=e.attribute.replace("[*]",`[${a}]`);s.queries.push({attribute:c,operator:e.operator,value:e.value,options:e.options})}}return s}evaluateQueryGroup(e,t,r,s,i){let o=new Map,a=r;if(!t.queries||t.queries?.length===0)return a;for(const c of t.queries){let u=new Map;if(this.queryBuilder.isQuery(c)?u=this.getEvaluatedQueryDataset(e,c,a,i):u=this.evaluateQueryGroup(e,c,a,s,i),o.size===0&&(o=u),t.groupType==="or")u.forEach(f=>{o.set(f.key,f)});else{const f=p.differenceBy(Array.from(o.values()),Array.from(u.values()),"key");for(const d of f)o.delete(d.key)}t.groupType==="and"?a=o:a=r}return o}queryData(e,t,r,s){if(t.queries.length===0)return e;const i=new Map(e);return t.groupKey||(t.groupKey="root"),t.groupType||(t.groupType="and"),t.queries||(t.queries=[]),this.validateQuery(t),this.evaluateQueryGroup(t,t,i,r,s)}}const Je=new Set(["apikey","api-key","managerkey","token","proxy-key","proxykey","manager-key","sdk-key"]);function Xe(n){const e=n.indexOf("?");if(e<0)return n;const t=n.slice(e+1).split("&").map(r=>{const s=r.indexOf("=");if(s<0)return r;const i=r.slice(0,s);return Je.has(i.toLowerCase())?`${i}=<redacted>`:r}).join("&");return`${n.slice(0,e)}?${t}`}const ne="k:",ie="h:";function S(n,e=0){if(n.key)return`${ne}${n.key}`;const t=I({type:n.type,url:n.rawUrl??n.url,model:n.model??"",occurrence:e});return`${ie}${t}`}function Ze(n){const e=new Map,t=new Set;return n.map(r=>{const s=`${r.key??""}|${r.type}|${r.rawUrl??r.url}|${r.model??""}`;let i=e.get(s)??0,o=S(r,i);for(;t.has(o);)i+=1,o=r.key?`${S(r)}#${i}`:S(r,i);return e.set(s,i+1),t.add(o),o})}function Ye(){const n=globalThis;return typeof n.scheduler?.yield=="function"?n.scheduler.yield():typeof n.setImmediate=="function"?new Promise(e=>n.setImmediate(()=>e())):typeof n.MessageChannel=="function"?new Promise(e=>{const t=new n.MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)}):new Promise(e=>setTimeout(e,0))}class et{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 p=require("lodash-es");function I(i){const e=M(i);return oe(e)}function M(i){if(typeof i!="object"||i===null)return String(i);if(Array.isArray(i))return"["+i.map(M).join(",")+"]";const e=Object.keys(i).sort();let t="{";for(let r=0;r<e.length;r++){const s=e[r];t+=s+":"+M(i[s]),r<e.length-1&&(t+=",")}return t+="}",t}function oe(i){let e=0;for(let t=0;t<i.length;t++){const r=i.charCodeAt(t);e=(e<<5)-e+r,e|=0}return e.toString(16)}const b={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:i=>{typeof performance<"u"&&performance.mark&&performance.mark(i)},measure:(i,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(i,e,t)},getEntriesByName(i){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(i)},getEntriesByType(i){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(i)}};class ae{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:b.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 n=s.value-r.value,o=Math.round(n*100)/100,a=this.data.get(t);if(a&&e.sum){const u=a.value+o,f={...a,value:u};return this.data.set(t,f),f}const c={name:e.name,type:"measure",value:o,createdAt:Date.now()};return e.detail&&(c.detail=e.detail),this.data.set(t,c),c}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"?[]:b.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 P=class _{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 n=this.edges.get(s);if(n){for(let o of n)if(r(o))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=n=>{if(e.has(n))return null;if(t.has(n)){const a=r.indexOf(n);return r.slice(a).concat([n])}t.add(n),r.push(n);const o=this.edges.get(n);if(o)for(let a of o){const c=s(a);if(c)return c}return r.pop(),t.delete(n),e.add(n),null};for(let n of this.nodes){const o=s(n);if(o)return{hasCycle:!0,path:o}}return{hasCycle:!1}}order(e){const t=new Set,r=new Set,s=[],n=e?.allowCycles??!1,o=a=>{if(t.has(a))return;if(r.has(a)){if(n)return;throw new Error("Graph has a cycle.")}r.add(a);const c=this.edges.get(a);if(c)for(let u of c)o(u);r.delete(a),t.add(a),s.push(a)};for(let a of this.nodes)t.has(a)||o(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 o of this.nodes)t.set(o,0);for(const o of this.edges.values())for(const a of o)t.set(a,(t.get(a)||0)+1);const r=[];let s=Array.from(this.nodes).filter(o=>(t.get(o)||0)===0);const n=new Set;for(;s.length>0;){const o=s.slice();r.push(o),s=[];for(const a of o){if(n.has(a))continue;n.add(a);const c=this.edges.get(a);if(c)for(const u of c)t.set(u,(t.get(u)||0)-1),(t.get(u)||0)===0&&s.push(u)}}if(n.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const o=new Set(e.filterKinds);return{batches:r.map(a=>a.filter(c=>o.has(this.nodeKinds.get(c))))}}return{batches:r}}getImpactedNodes(e,t="downstream",r){const s=new Set(e),n=u=>!r||r.length===0||r.includes(this.nodeKinds.get(u)??void 0),o=()=>{const u=new Set,f=Array.from(s);for(;f.length;){const l=f.shift();for(const[d,h]of this.edges)h.has(l)&&!u.has(d)&&(u.add(d),f.push(d))}return u},a=()=>{const u=new Set,f=Array.from(s);for(;f.length;){const l=f.shift(),d=this.edges.get(l);if(d)for(const h of d)u.has(h)||(u.add(h),f.push(h))}return u};let c;return t==="both"?c=new Set([...o(),...a()]):t==="upstream"?c=a():c=o(),Array.from(c).filter(n)}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 _;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)),n=Array.from(t).filter(l=>!r.has(l)),o=new Set(this.getAllEdges().map(l=>l.join("→"))),a=new Set(e.getAllEdges().map(l=>l.join("→"))),c=Array.from(a).filter(l=>!o.has(l)).map(l=>l.split("→")),u=Array.from(o).filter(l=>!a.has(l)).map(l=>l.split("→")),f=[];for(const l of new Set([...t,...r])){const d=this.nodeKinds.get(l),h=e.nodeKinds.get(l);d!==h&&f.push({name:l,from:d,to:h})}return{addedNodes:s,removedNodes:n,addedEdges:c,removedEdges:u,kindChanges:f}}};class ce{graph;nodeIndex;constructor(){this.graph=new P,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),n=[...e,...s],o=new Set;return n.filter(a=>{const c=this.getNodeId(a.modelKey,a.attributeKey);return o.has(c)?!1:(o.add(c),!0)})}getProcessingOrder(e){const t=new Map,r=[...e].sort((s,n)=>s.processingStep-n.processingStep);for(const s of r){const{modelKey:n,attributeKey:o,processingStep:a}=s;t.has(n)||t.set(n,new Map);const c=t.get(n);c.has(a)||c.set(a,new Set),c.get(a).add(o)}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 n=this.graph.getDependencies(r);if(n.length===0)return 1;let o=0;for(const a of n){const c=t(a,new Set(s));o=Math.max(o,c)}return o+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 n of s){const o=this.getNodeId(r,n);this.hasNode(o)||t.push({modelKey:r,attributeKey:n})}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 T={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 T[e]<=T[t]}formatMessage(e){if(this.config.format==="json"){const o={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(o.module=e.prefix),e.context&&(o.context=e.context),e.error&&(o.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(o)}const t=new Date(e.timestamp).toISOString().substring(11,23),r=e.prefix?`[${e.prefix}]`:"",s=this.getLevelIcon(e.level),n=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${s} ${r} ${e.message}${n}`.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 n={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:r,error:s};if(this.config.onLog){this.config.onLog(n);return}const o=this.formatMessage(n);if(typeof console<"u")switch(e){case"error":s?console.error(o,s):console.error(o);break;case"warn":console.warn(o);break;case"debug":console.debug?console.debug(o):console.log(o);break;default:console.log(o)}}error(e,t,r){const s=t instanceof Error?t:void 0,n=t instanceof Error?r:t;this.log("error",e,n,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 z=new g;class ue{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}enabled;cache;cacheDependencies;hitCount=0;missCount=0;log=z.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 n=this.getCacheName(e,t);this.cache.set(n,r),s?this.cacheDependencies.set(n,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 n=!1;for(const[o,a]of e){if(s.models.has(o))if(s.modelAttributes.has(o)){const c=s.modelAttributes.get(o);for(const u of a)if(c.has(u)){n=!0;break}}else n=!0;if(n)break}n&&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,n]of this.cacheDependencies)for(const o of t)if(n.models.has(o)){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 p.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 N=(i,e="")=>{if(!(typeof i!="string"||!i.startsWith("/")||!i.endsWith("/")))return{pattern:i.slice(1,-1),flags:e}},fe=(i,e="")=>`${i}#${e}`,le=i=>`${i.gt}_${i.gte}_${i.lt}_${i.lte}_${i.eq}_${i.ne}`,de=i=>`${i.gt}_${i.gte}_${i.lt}_${i.lte}_${i.eq}_${i.ne}`,he=(i,e)=>{const t=typeof e=="function"?e:r=>r[e];return[...i.reduce((r,s)=>{const n=s==null?s:t(s);return r.has(n)||r.set(n,s),r},new Map).values()]},pe=(i,e)=>i.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(i=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let r=0;r<i;r++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}const ge=i=>i.replace(/\/+$/,""),j=i=>typeof i!="string"?"":i.replace(/[[\]{}()*+?.,\\^$|#]/g,"\\$&"),ye=i=>typeof i!="string"?"":i.replace(/\\([[\]{}()*+?.,\\^$|#])/g,"$1"),me=(i,e)=>{try{return L(i,e)>=0}catch{return!1}},L=(i,e)=>{if(!E(i)||!E(e))throw new Error(`Invalid version format: v1="${i}", v2="${e}". Expected format: "x.y.z"`);const t=i.split(".").map(Number),r=e.split(".").map(Number);for(let s=0;s<3;s++){const n=t[s]||0,o=r[s]||0;if(n>o)return 1;if(n<o)return-1}return 0},E=i=>/^\d+(\.\d+){0,2}$/.test(i);class ve{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=b.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 O=(i,e)=>e?typeof structuredClone<"u"?structuredClone(i):p.cloneDeep(i):i,F=(i,e,t,r,s,n)=>{try{const o=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=O(n,o);if(t.scope==="list"&&(t.listKey=i.cdRef?.key||i.key,t.modelKey=i.model?.key||i.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const c=b.now(),u=c-r,f=Math.round(u*1e3)/1e3;t.duration=f,t.start=r,t.end=c;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 n}},we=i=>(t,r,s)=>{const n=s.value;return s.value=function(...o){const a=b.now(),c=this.cdRef,u=O(i,!0);u.key||(c.increaseCounter(),u.key=c.getCounter());const f=B();c.analyticsController.mark({name:`${u.type}:start`,context:f});const l=this.model?.key;!u.originCdRefKey&&c.key&&(u.originCdRefKey=c.key),l&&(u.modelKey=l);const d=n.apply(this,o);return u.method=r,u.args=o,d&&typeof d=="object"&&"then"in d?d.then(h=>F(this,c,u,a,f,h)):F(this,c,u,a,f,d)},s};function xe(i,e,t,r){t.max||(t.max=20);const s=[],n=t.transform?r.transformValue(t.value,t.transform):t.value;for(const[o,a]of e.entries()){const c=Array.from(a).some(f=>i.has(f)),u=t.transform?r.transformValue(o,t.transform):o;if(!(t.excludeUndefineds&&typeof o>"u")&&!(t.excludeNulls&&o===null)){if(c&&(n===""||n==="//")){const f={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}else if(c&&N(n)){if(r.queryFind(u,n,"some",t.regexFlags)){const f={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}}else if(c&&typeof n=="string"){const f=String(u??""),l=n;if(f.toLowerCase().startsWith(l.toLowerCase())){const d={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(d)}}else if(c&&r.queryFind(u,n,"some")){const f={value:o,keys:t.calculateResultKeys?Array.from(a):[]};s.push(f)}if(s.length===t.max)break}}return s}function V(i){return i instanceof Date}function U(i){return i instanceof Date&&!isNaN(i.getTime())}const Ae={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 be(i){let e="^";const t=[];let r=i;const s=Object.entries(Ae).sort((n,o)=>o[0].length-n[0].length);for(;r.length>0;){let n=!1;for(const[o,a]of s)if(r.startsWith(o)){e+=a.regex,t.push({type:a.type,pattern:o}),r=r.slice(o.length),n=!0;break}if(!n){const o=r[0];if(!o)break;e+=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=r.slice(1)}}return e+="$",{regex:new RegExp(e),tokenOrder:t}}function De(i,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=i[r+1];if(!s)continue;const n=parseInt(s,10),o=e[r];o&&(o.type==="year"&&o.pattern==="yy"?t.year=2e3+n:t[o.type]=n)}return t}function Se(i){if(i.month<1||i.month>12)return new Date(NaN);if(i.day<1||i.day>31)return new Date(NaN);if(i.hour<0||i.hour>23)return new Date(NaN);if(i.minute<0||i.minute>59)return new Date(NaN);if(i.second<0||i.second>59)return new Date(NaN);if(i.millisecond<0||i.millisecond>999)return new Date(NaN);const e=new Date(i.year,i.month-1,i.day,i.hour,i.minute,i.second,i.millisecond);return U(e)?e.getFullYear()!==i.year||e.getMonth()!==i.month-1||e.getDate()!==i.day?new Date(NaN):e:new Date(NaN)}function Ie(i,e,t){if(i=i.trim(),e==="t"){const a=Number(i);return isNaN(a)?new Date(NaN):new Date(a*1e3)}if(e==="T"){const a=Number(i);return isNaN(a)?new Date(NaN):new Date(a)}const{regex:r,tokenOrder:s}=be(e),n=i.match(r);if(!n)return new Date(NaN);const o=De(n,s);return Se(o)}class Qe{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 Ke{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=n=>{t.add(n),r.add(n);const o=this.graph.get(n);if(o){for(const a of o)if(t.has(a)){if(r.has(a))return!0}else if(s(a))return!0}return r.delete(n),!1};for(let n=0;n<e.length-1;n++){const o=e[n],a=e[n+1];o&&a&&this.addDependency(o,a)}for(const n of e)if(!t.has(n)&&s(n))return!0;return!1}clear(){this.graph.clear()}}class W{parseCache;circularRefDetector;cacheHits=0;cacheMisses=0;constructor(e=1e3){this.parseCache=new Qe(e),this.circularRefDetector=new Ke}parse(e){if(this.parseCache.has(e))return this.cacheHits++,this.parseCache.get(e);this.cacheMisses++;let t,r;const s=e.includes("."),n=e.includes("["),o=s||n;if(o){r=e.split(/[.[]/)[0];const c=e.indexOf("."),u=e.indexOf("[");if(n&&(c===-1||u<c)){const l=e.indexOf("]");if(l>-1){const d=e.indexOf(".",l+1);d>-1?t=e.substring(d+1):t=void 0}else s&&(t=e.substring(c+1))}else s&&(t=e.substring(c+1))}const a={attribute:e,isDeepQuery:o};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,n=(e.match(/]/g)||[]).length;s!==n&&r.push(`Invalid bracket notation: Mismatched brackets in ${e}`),e.includes("[]")&&r.push(`Invalid bracket notation: Empty brackets not allowed: ${e}`);const o=/\[([^\]]+)\]/g;let a;for(;(a=o.exec(e))!==null;){const f=a[1];f&&f!=="*"&&!/^\d+$/.test(f)&&r.push(`Invalid bracket content: Must be a number or '*', got '${f}' in ${e}`)}const c=(e.match(/\./g)||[]).length+1;c>t&&r.push(`Path too deep: Maximum depth is ${t}, got ${c} in ${e}`);const u=e.match(/[^a-zA-Z0-9._[\]*-]/g);return u&&r.push(`Invalid characters in path: ${u.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 m=new W;function w(i,e){if(e.includes("[*]")){const n=e.indexOf("[*]"),o=e.substring(0,n),a=e.substring(n+3),c=o?p.get(i,o):i;if(!Array.isArray(c))return[];const u=[];for(const f of c)!a||a===""?f!==void 0&&u.push(f):a.startsWith(".")&&u.push(...w(f,a.slice(1)));return u}const t=e.split(".");let r=[i];for(const n of t){const o=[];for(const a of r)if(a!=null)if(Array.isArray(a))for(const c of a){if(c==null)continue;const u=c[n];u!==void 0&&o.push(u)}else{const c=a[n];c!==void 0&&o.push(c)}if(r=o,r.length===0)return[]}const s=[];for(const n of r)if(Array.isArray(n))for(const o of n)o!==void 0&&s.push(o);else n!==void 0&&s.push(n);return s}function k(i){let e=0;for(let t of i){const r=t.toString().split(".")[1];r&&(e=Math.max(e,r.length))}return Math.pow(10,e)}function G(i,e,t){return(i*t+e*t)/t}function ke(i,e,t){return i*t/(e*t)}const Q=(i,e,t,r)=>{if(!r)throw new Error("Attribute not found");const s={attribute:r,types:i.types};let n;(s.types.includes("sum")||s.types.includes("avg"))&&(n=Ne(r,e));let o;return(s.types.includes("min")||s.types.includes("max"))&&(o=Ee(r,e)),i.types.forEach(a=>{a==="sum"?s.sum=n?.sum:a==="avg"?s.avg=n?.average:a==="count"?s.count=Me(r,e):a==="min"?s.min=o&&o[0]:a==="max"?s.max=o&&o[1]:a==="distinct"?s.distinct=H(i,e,t):a==="group"&&(s.group=Ce(i,e))}),s},Me=(i,e)=>{const r=m.parse(i).isDeepQuery;let s=0;for(const n of e.values())if(n)if(r)s+=w(n,i).filter(o=>o!=null).length;else{const o=n[i];if(o==null)continue;Array.isArray(o)?s+=o.filter(a=>a!=null).length:s++}return s},Ee=(i,e)=>{let t,r;const n=m.parse(i).isDeepQuery;for(const o of e.values()){if(!o)continue;let a;if(n)a=w(o,i);else{const c=o[i];c===void 0?a=[]:Array.isArray(c)?a=c.filter(u=>u!==void 0):a=[c]}for(const c of a)c==null||typeof c=="object"||((t===void 0||c<t)&&(t=c),(r===void 0||c>r)&&(r=c))}if(!(t===void 0||r===void 0))return[t,r]},Ce=(i,e)=>{const t=[];i.groupOptions?.groups?.forEach(o=>{t.push({option:o,count:0,keys:[]})});const r={option:{value:["$dcupl_not_found"]},count:0,keys:[]},n=m.parse(i.attribute).isDeepQuery;for(const o of e.values()){let a;n?a=w(o,i.attribute):a=[o[i.attribute]];let c=!1;for(const u of a)for(const f of t)(typeof f.option.value<"u"&&f.option.value.includes(u)||typeof f.option.from<"u"&&f.option.from<u&&typeof f.option.to<"u"&&f.option.to>u)&&(f.keys.includes(o.key)||(f.count++,f.keys.push(o.key)),c=!0);!c&&i?.groupOptions?.calculateNotFound&&(r.count++,r.keys.push(o.key))}return i?.groupOptions?.calculateNotFound&&t.push(r),t},Ne=(i,e)=>{let t=0,r=0;const n=m.parse(i).isDeepQuery;for(const a of e.values()){if(!a)continue;let c;if(n)c=w(a,i);else{const u=a[i];u===void 0?c=[]:Array.isArray(u)?c=u:c=[u]}for(const u of c)if(Array.isArray(u))for(const f of u)typeof f=="number"&&(t=G(t,f,k([t,f])),r++);else typeof u=="number"&&(t=G(t,u,k([t,u])),r++)}return r===0?void 0:{average:ke(t,r,k([t,r])),count:r,sum:t}},H=(i,e,t)=>{const r=[];for(const[s,n]of t)if(!(i.excludeUndefineds&&typeof s>"u")&&Array.from(n).find(o=>e.has(o))){const o={value:s,count:n.size};if(i.distinctOptions?.skipKeys||(o.keys=Array.from(n)),r.push(o),i.distinctOptions?.limit&&r.length>=i.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 ${_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=p.cloneDeep(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||m}init(e){this._initOptions=p.cloneDeep(e),this.currentQuery=p.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=p.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"queries"in e||"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)}findQueryGroup(e,t){const r=this.locateQueryGroup(e,(t??this.currentQuery).queries);return r?this.groupAtPath(r):void 0}locateQueryGroup(e,t){const r=t.findIndex(s=>this.isQueryGroup(s)&&s.groupKey===e);if(r>-1)return[{queries:t,idx:r}];for(const[s,n]of t.entries())if(this.isQueryGroup(n)){const o=this.locateQueryGroup(e,n.queries);if(o)return[{queries:t,idx:s},...o]}}groupAtPath(e){const t=e[e.length-1];return t.queries[t.idx]}pruneEmptyGroups(e){for(let t=e.length-1;t>=0;t--){const{queries:r,idx:s}=e[t];if(r[s].queries.length>0)break;r.splice(s,1)}}getQuery(){return p.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:p.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(n=>this.isQueryGroup(n)&&n.groupKey===e.attribute);if(s>-1){const n=r.queries[s];t?.mode==="set"?n.queries=[e]:n.queries.push(e)}else r.queries.push({groupKey:e.attribute,groupType:"or",queries:[e]})}else if(this.isQueryGroup(e)){const n=e.groupKey===void 0&&t?.mode!=="set"?-1:r.queries.findIndex(o=>this.isQueryGroup(o)&&o.groupKey===e.groupKey);if(n>-1){const o=r.queries[n];e.groupType&&(o.groupType=e.groupType),t?.mode==="set"?r.queries[n]=e:o.queries=[...o.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=this.locateQueryGroup(e.attribute,t.queries);if(r){const s=this.groupAtPath(r),n=p.findIndex(s.queries,e);n>-1&&s.queries.splice(n,1),this.pruneEmptyGroups(r)}}else if(this.isQueryGroup(e)){const r=this.locateQueryGroup(e.groupKey,t.queries);if(r)if(e.queries){const s=this.groupAtPath(r);for(const n of e.queries){const o=p.findIndex(s.queries,n);o>-1&&s.queries.splice(o,1)}this.pruneEmptyGroups(r)}else{const s=r[r.length-1];s.queries.splice(s.idx,1),this.pruneEmptyGroups(r.slice(0,-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)),e.operator==="in"&&typeof e.value<"u"&&!Array.isArray(e.value)&&t.push(new x("in operator needs an array value",e)),t.length>0?{valid:!1,errors:t}:{valid:!0};if(this.isQueryGroup(e)){const n=e.queries.map(o=>this.validateQuery(o)).filter(o=>!o.valid).map(o=>o.errors).flat();return n.length>0?{valid:!1,errors:n}:{valid:!0}}return t.push(new x("Invalid query definition",e)),{valid:!1,errors:t}}getQueryAttributes(e){const t=[],r=new Set,s=n=>{for(const o of n)this.isQuery(o)?o.attribute&&!r.has(o.attribute)&&(t.push(o.attribute),r.add(o.attribute)):this.isQueryGroup(o)&&s(o.queries)};return s(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],r=new Set,s=n=>{for(const o of n)if(this.isQuery(o)){if(o.attribute&&!r.has(o.attribute)){const a=this.getQueryAttributeForString(o.attribute);t.push(a),r.add(o.attribute)}}else this.isQueryGroup(o)&&s(o.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 n=this.getProjectionForAttributeEntries([s]);Object.keys(n).forEach(o=>{o!=="$"&&r.reference&&(t[r.reference][o]=n[o])})}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 n=!0;for(const o in e)if(s[o]!==e[o]){n=!1;break}if(n)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 C=new $;function Oe(i,e,t,r,s,n,o){const a=t.excludeGroup??s,c=C.removeQuery({groupKey:a},p.cloneDeep(r)),u=o.queryData(i,c,!1,n),f=e?[...e.keys()]:[],l=new Set(f),d=n.get(s)??new Map;if(!t.excludeUnresolved)for(const y of d.keys())l.add(y);if(t.excludeUndefineds?l.delete(void 0):l.add(void 0),t.sort){const y=[];for(const K of l.values())y.push(q(K,d,u,e,s,a,r,!0));const v=t.excludeZeros?y.filter(K=>K.size>0):y;return v.sort($e(t.sort)),t.count?v.slice(0,t.count):v}const h=[];for(const y of l.values()){const v=q(y,d,u,e,s,a,r,!!t?.calculateFacets);if(!(t?.excludeZeros&&v.size===0)){if(t?.count&&h.length===t?.count)return h;h.push(v)}}return h}function q(i,e,t,r,s,n,o,a){const c=new Map,u=e.get(i)||new Set;for(const f of u){const l=t.get(f);if(l&&(c.set(f,l),!a))break}return{key:String(i),value:i,selected:Re(n,s,i,o),enabled:c.size>0,size:c.size,entry:r?.get(i),resultKeys:Array.from(c.keys())}}function D(i,e){if(i===void 0&&e===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;const t=typeof i,r=typeof e;if(t!==r)return t<r?-1:1;if(t==="number")return i-e;if(t==="string")return i.localeCompare(e);const s=String(i),n=String(e);return s<n?-1:s>n?1:0}function $e(i){switch(i){case"size-desc":return(e,t)=>t.size-e.size||D(e.value,t.value);case"size-asc":return(e,t)=>e.size-t.size||D(e.value,t.value);case"value-asc":return(e,t)=>D(e.value,t.value);case"value-desc":return(e,t)=>e.value===void 0&&t.value===void 0?0:e.value===void 0?1:t.value===void 0?-1:-D(e.value,t.value)}}const Re=(i,e,t,r)=>{const s=C.findQueryGroup(i,r);return s?!!s.queries.find(n=>C.isQuery(n)?n.attribute!==e?!1:(n.operator==="in"&&Array.isArray(n.value)?n.value:[n.value]).some(a=>(a?.key||a)===t):!1):!1};class J{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())}resetIndicesWhere(e){for(const t of Array.from(this.indexMap.keys()))e(t)&&this.reset(t)}fillDataMap(e,t){let r=this.dataMap.get(e);r||(r=new Map,this.dataMap.set(e,r));for(const s of t){let n;if(typeof s=="object"&&s&&s.key)n=s.key;else if(Array.isArray(s)){for(const a of s)this.fillDataMap(e,[a]);return}else s instanceof Date?n=s.toISOString():n=s;let o=r.get(n);o||(o={key:n},this.dataMap.get(e)?.set(n,o))}}fillInverseIndex(e,t,r){if(!e||!t||!r||!Array.isArray(r))return;const s=this.indexMap.get(e)||new Map;for(const n of r){let o;if(typeof n=="object"&&n&&n.key)o=n.key;else if(Array.isArray(n)){for(const c of n)this.fillInverseIndex(e,t,[c]);return}else n instanceof Date?o=n.toISOString():o=n;let a=s.get(o);a||(a=new Set,s.set(o,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 n=this.getIndex(s);const o=this.indexMetadata.get(s);if(o)o.lastAccessedAt=Date.now();else if(!n){const c=m.parse(e).isDeepQuery??!1;this.indexMetadata.set(s,{createdAt:Date.now(),lastAccessedAt:Date.now(),context:r,type:c?"deep":"shallow"})}if(!n){this.reset(s),this.indexMap.set(s,new Map);const c=m.parse(e).isDeepQuery;for(const u of t.values()){let f;c?(f=w(u,e),f.length===0&&(f=[void 0])):f=[u[e]],this.fillInverseIndex(s,u.key,f),this.fillDataMap(s,f)}n=this.getIndex(s)||new Map}return n}getIndexName(e,t){return t?e+"_"+I(t):e}removeFromInverseIndex(e,t,r){const s=this.indexMap.get(e);if(s)for(const n of r){let o;if(typeof n=="object"&&n&&n.key)o=n.key;else if(Array.isArray(n)){for(const c of n)this.removeFromInverseIndex(e,t,[c]);return}else n instanceof Date?o=n.toISOString():o=n;const a=s.get(o);a&&(a.delete(t),a.size===0&&s.delete(o))}}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 n;if(typeof s=="object"&&s&&s.key)n=s.key;else if(Array.isArray(s)){for(const o of s)this.removeFromDataMap(e,[o]);return}else s instanceof Date?n=s.toISOString():n=s;r.delete(n)}}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 m.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,n]of this.indexMetadata)t-n.lastAccessedAt>e&&(this.reset(s),r++);return r}getStats(){const e=this.getIndexCount(),t=Date.now();let r=0,s=0;for(const o of this.indexMetadata.values()){const a=t-o.createdAt;r+=a,a>s&&(s=a)}const n=this.indexMetadata.size>0?r/this.indexMetadata.size:0;return{shallow:e.shallow,deep:e.deep,total:e.total,oldestAge:s,avgAge:n}}}const A="__";function R(i,e,t={key:"root"},r="root",s=new J,n){const o=n||i;for(const a of e.columns)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,o));for(const a of e.rows)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,o));for(const a of e.values)a.attribute&&(m.parse(a.attribute),s.getOrCreateIndex(a.attribute,o));if(e.rows&&e.rows.length>0){t.rows=t.rows||[];const a=Te(i,e.rows[0],e,s,r,n);t.rows.push(a)}if(e.columns&&e.columns.length>0){t.columns=t.columns||[];const a=X(i,e.columns[0],e,s,r,n);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 c=Q(a,i,s.getIndex(a.attribute),a.attribute);t.values.push(c)}return t}function Te(i,e,t,r,s="",n){const o={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return o;for(const[c,u]of a.entries()){const f={key:c,value:c},l=new Map;for(const d of u)i.has(d)&&l.set(d,i.get(d));if(l.size){for(const d of t.values){if(f.values=f.values||[],s==="root"&&e?.calculateTotals===!1)continue;const h=Q(d,l,r.getIndex(d.attribute),d.attribute);f.values.push(h)}if(o.rows=o.rows||[],o.rows.push(f),t.rows.length>1){const d={...t,rows:t.rows.slice(1)};R(l,d,f,s+A+e.attribute+A+c,r,n)}else if(t.columns)for(const d of t.columns){f.columns=f.columns||[];const h=X(l,d,t,r,s+A+e.attribute+A+c,n);f.columns.push(h)}}}return o}function X(i,e,t,r,s="",n){const o={key:e.attribute},a=r.getIndex(e.attribute);if(!a)return o;for(const[c,u]of a.entries()){const f={key:c,value:c},l=new Map;for(const d of u)i.has(d)&&l.set(d,i.get(d));if(l.size){for(const d of t.values){if(f.values=f.values||[],s==="root"&&e?.calculateTotals===!1)continue;const h=Q(d,l,r.getIndex(d.attribute),d.attribute);f.values.push(h)}if(o.columns=o.columns||[],o.columns.push(f),t.columns.length>1){const d={...t,columns:t.columns.slice(1)};R(l,d,f,s+A+e.attribute+A+c,r,n)}}}return o}const Fe=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/,Ge=/^-?\d+$/,qe=/^-?\d+\.\d+$/,Pe=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,Z=i=>i==="true"||i==="false"?"boolean":Ge.test(i)?"int":qe.test(i)?"float":Fe.test(i)&&!Number.isNaN(Date.parse(i))?"date":"string",Y=i=>Pe.test(i),_e=i=>i==null||i==="",ze=i=>{const e=[...i];return e.length<=1?{type:e[0]??"any",conflict:!1}:e.every(t=>t==="int"||t==="float")?{type:"float",conflict:!1}:{type:"any",conflict:!0}},ee=(i,e={})=>{const r=e.deep??(e.sampleSize!==void 0&&e.sampleSize>1)?e.sampleSize??1/0:1,s=e.coerceStrings??!0,n=new Map,o=[],a=Math.min(i.length,r);for(let f=0;f<a;f++){const l=i[f];if(l)for(const[d,h]of Object.entries(l)){let y=n.get(d);if(y||(y={observed:new Set,empty:0,scanned:0},n.set(d,y),o.push(d)),y.scanned++,_e(h)){y.empty++;continue}let v;typeof h=="string"&&s?(v=Z(h),v==="string"&&!y.hint&&Y(h)&&(y.hint="column looks date-like (non-ISO) — review manually")):v=se(h),y.observed.add(v)}}const c=[],u=[];for(const f of o){const l=n.get(f),{type:d,conflict:h}=ze(l.observed.size?l.observed:new Set(["string"]));c.push({key:f,type:d}),u.push({column:f,inferredType:d,observedTypes:[...l.observed].sort(),emptyRate:l.scanned===0?0:l.empty/l.scanned,conflict:h,hint:l.hint})}return{properties:c,diagnostics:u}},Be=(i,e=!1)=>ee(i,typeof e=="boolean"?{deep:e}:e).properties,te=i=>Number(i)===i&&i%1===0,re=i=>Number(i)===i&&i%1!==0,se=i=>{switch(typeof i){case"string":return"string";case"number":return te(i)?"int":re(i)?"float":"any";case"boolean":return"boolean";case"object":return V(i)?"date":"json";default:return"any"}},je=(i,e)=>{const t=j(i.text||""),r=e?.attributeKey||i.filterKey;let s;const n=e?.comparisonType||"containsIgnoreCase";return n==="containsIgnoreCase"?s={groupKey:i.filterKey,queries:[{queryKey:i.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["lowercase"]}}]}:n==="containsIgnoreCaseAndWhitespace"?s={groupKey:i.filterKey,queries:[{queryKey:i.text,attribute:r,value:`/${t}/`,operator:"find",options:{transform:["removeWhitespace","lowercase"]}}]}:n==="contains"?s={groupKey:i.filterKey,queries:[{queryKey:i.text,attribute:r,value:`/${t}/`,operator:"find"}]}:n==="equal"?s={groupKey:i.filterKey,queries:[{queryKey:i.text,attribute:r,value:i.text,operator:"eq"}]}:n==="equalIgnoreCase"&&(s={groupKey:i.filterKey,queries:[{queryKey:i.text,attribute:r,value:i.text,operator:"eq",options:{transform:["lowercase"]}}]}),s},Le=(i,e)=>{const t=e?.attributeKey||i.filterKey;return{groupKey:i.filterKey,queries:[{queryKey:i.value,attribute:t,value:i.value,operator:"eq"}]}},Ve=(i,e)=>{const t=e?.attributeKey||i.filterKey,r={groupKey:i.filterKey,queries:[]};return typeof i.eq<"u"&&(r.groupType="or",Array.isArray(i.eq)?i.eq.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq"})}):r.queries.push({attribute:t,value:i.eq,operator:"eq"})),typeof i.ne<"u"&&(r.groupType="and",Array.isArray(i.ne)?i.ne.forEach(s=>{r.queries.push({attribute:t,value:s,operator:"eq",options:{invert:!0}})}):r.queries.push({attribute:t,value:i.ne,operator:"eq",options:{invert:!0}})),typeof i.gt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:i.gt,operator:"gt"})),typeof i.lt<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:i.lt,operator:"lt"})),typeof i.gte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:i.gte,operator:"gte"})),typeof i.lte<"u"&&(r.groupType="and",r.queries.push({attribute:t,value:i.lte,operator:"lte"})),r},Ue=(i,e)=>{const t=e?.attributeKey||i.filterKey,r={groupKey:i.filterKey,queries:[]};return i.itemKeys.forEach(s=>{r.queries.push({queryKey:s,attribute:t,value:{key:s},operator:"eq"})}),r},We=i=>!(typeof i.modelKey!="string"||!Array.isArray(i.queries));class He{constructor(e,t,r){this.scriptController=e,this.globalItemService=t,this.modelParser=r}scriptController;globalItemService;modelParser;registeredCustomOperator=new Map;queryBuilder=new $;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=e.value;const s=e.options?.arrayValueHandling||"some";Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(r=this.transformValue(r,e.options.transform));let n=this.getAttributeValue(t,e.attribute);if(Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(n=this.transformValue(n,e.options.transform)),(typeof n>"u"||n===null)&&!["typeof","isTruthy","eq","in"].includes(e.operator))return!1;let o;switch(e.operator){case"eq":o=this.queryEq(n,r,s);break;case"in":o=this.queryIn(n,r,s);break;case"find":o=this.queryFind(n,r,s,e.options?.regexFlags);break;case"lt":case"gt":case"lte":case"gte":{const a=e.operator;o=this.matchValues(n,s,c=>this.compareValue(a,c,r));break}case"typeof":o=this.matchValues(n,s,a=>typeof a===r);break;case"isTruthy":{const a=r===!0;o=this.matchValues(n,s,c=>!!c===a);break}case"size":typeof n=="string"?o=n.length===r:o=p.size(n)===r;break;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 a=this.registeredCustomOperator.get(e.operator);if(typeof a=="function")return a(e,t)}return!1}return e.options?.invert?!o:o}compareValue(e,t,r){if(t==null)return!1;switch(e){case"lt":return t<r;case"gt":return t>r;case"lte":return t<=r;case"gte":return t>=r}}getAttributeValue(e,t){if(t in e||!(t.includes(".")||t.includes("[")))return e[t];if(t.includes("["))return p.get(e,t);const r=t.split(".");let s=e;for(let n=0;n<r.length;n++){const o=r[n];if(s==null)return;if(Array.isArray(s)&&o!=="length"&&!/^\d+$/.test(o))return w(s,r.slice(n).join("."));s=s[o]}return s}matchValues(e,t,r){return Array.isArray(e)?t==="every"?e.length>0&&e.every(r):e.some(r):r(e)}queryEq(e,t,r){return Array.isArray(e)&&!Array.isArray(t)?this.matchValues(e,r,s=>this.equalsQueryValue(s,t)):this.equalsQueryValue(e,t)}queryIn(e,t,r){return!Array.isArray(t)||t.length===0?!1:this.matchValues(e,r,s=>t.some(n=>this.equalsQueryValue(s,n)))}getIndexKey(e){if(typeof e=="string")return e;if(e?.key&&Object.keys(e).length===1)return e.key}equalsQueryValue(e,t){const r=this.getIndexKey(t);return typeof r>"u"?p.isEqual(e,t):e instanceof Date?!isNaN(e.getTime())&&e.toISOString()===r:typeof e=="object"&&e?.key?e.key===r:e===r}canUseIndex(e){return e.options?.arrayValueHandling!=="every"&&!e.options?.transform?.length}evaluateEqOperator(e,t,r,s){const n=new Map,o=this.canUseIndex(t)?s.get(t.attribute):void 0;if(o){const a=this.getIndexKey(t.value);if(typeof a<"u"){const c=o.get(a);if(c)if(c.forEach(u=>{r.has(u)&&n.set(u,r.get(u))}),t.options?.invert){const u=p.differenceBy(Array.from(r.values()),Array.from(n.values()),"key"),f=new Map;return u.forEach(l=>{f.set(l.key,l)}),f}else return n}}return this.scanDataset(e,t,r)}evaluateInOperator(e,t,r,s){const n=this.canUseIndex(t)?s.get(t.attribute):void 0;if(!n)return this.scanDataset(e,t,r);const o=new Map,a=[];for(const u of t.value){const f=this.getIndexKey(u),l=typeof f<"u"?n.get(f):void 0;if(!l){a.push(u);continue}l.forEach(d=>{const h=r.get(d);h&&o.set(d,h)})}if(a.length>0){const u=new Map;r.forEach((l,d)=>{o.has(d)||u.set(d,l)});const f={...t,value:a,options:{...t.options,invert:!1}};this.scanDataset(e,f,u).forEach((l,d)=>o.set(d,l))}if(!t.options?.invert)return o;const c=new Map;return r.forEach((u,f)=>{o.has(f)||c.set(f,u)}),c}scanDataset(e,t,r){const s=new Map,n=this.queryBuilder.extractQueryAttributes({queries:[t]}).filter(a=>a.isDeepQuery),o=n.length>0?this.queryBuilder.getProjectionForAttributeEntries(n):void 0;for(let[a,c]of r)o&&(c=this.globalItemService.getProjectedData(o,this.modelParser.models.get(e.modelKey),c)),this.evaluateQuery(t,c)&&s.set(a,c);return s}equalRegexFn(e,t,r){const s=N(t,r);if(s)try{return new RegExp(s.pattern,s.flags).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(n=>p.isEqualWith(n,t,(o,a)=>this.equalRegexFn(o,a,r))):typeof t=="object"?p.isMatch(e,t):e===t}queryFind(e,t,r,s){const n=(o,a)=>this.equalRegexFn(o,a,s);return Array.isArray(e)?typeof t=="string"||typeof t=="number"||typeof t=="boolean"?this.matchValues(e,r,o=>p.isEqualWith(o,t,n)):t!==null&&typeof t=="object"?this.matchValues(e,r,o=>p.isMatch(o,t)):!!p.find(e,t):p.isEqualWith(e,t,n)}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");if(e.operator==="in"&&!Array.isArray(e.value))throw new Error("invalid query - in operator needs an array value");return!0}else{if(this.queryBuilder.isQueryGroup(e))return p.every(e.queries,t=>this.validateQuery(t));throw new Error("invalid query - missing query or attribute")}}getEvaluatedQueryDataset(e,t,r,s){const n=new Map;if(t.attribute.includes("[*]")){const o=t.options?.invert===!0,a=new Set;for(let c of r.values()){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(h=>h.isDeepQuery)){const h=this.queryBuilder.getProjectionForAttributeEntries(u.filter(y=>y.isDeepQuery));c=this.globalItemService.getProjectedData(h,this.modelParser.models.get(e.modelKey),c)}const l=this.handleArrayStarQuery(t,c).queries.map(h=>({...h,options:{...h.options,invert:!1}}));this.matchValues(l,t.options?.arrayValueHandling||"some",h=>this.evaluateQuery(h,c))&&(a.add(c.key),o||n.set(c.key,c))}if(o)for(const[c,u]of r)a.has(c)||n.set(c,u)}else return t.operator==="eq"?this.evaluateEqOperator(e,t,r,s):t.operator==="in"?this.evaluateInOperator(e,t,r,s):this.scanDataset(e,t,r);return n}handleArrayStarQuery(e,t){const r=e.attribute.indexOf("[*]"),s={groupKey:e.queryKey||e.attribute+"[*]",groupType:"or",queries:[]};if(r!==-1){const n=e.attribute.substring(0,r),o=n.includes(".")?p.get(t,n):t[n];if(Array.isArray(o))for(let a=0;a<o.length;a++){const c=e.attribute.replace("[*]",`[${a}]`);s.queries.push({attribute:c,operator:e.operator,value:e.value,options:e.options})}}return s}evaluateQueryGroup(e,t,r,s,n){let o=new Map,a=r;if(!t.queries||t.queries?.length===0)return a;const c=t.groupType==="or";for(const u of t.queries){let f=new Map;if(this.queryBuilder.isQuery(u)?f=this.getEvaluatedQueryDataset(e,u,a,n):f=this.evaluateQueryGroup(e,u,a,s,n),o.size===0&&(o=f),c)f.forEach(l=>{o.set(l.key,l)}),a=r;else{const l=p.differenceBy(Array.from(o.values()),Array.from(f.values()),"key");for(const d of l)o.delete(d.key);a=o}}return o}queryData(e,t,r,s){if(t.queries.length===0)return e;const n=new Map(e);return t.groupKey||(t.groupKey="root"),t.groupType||(t.groupType="and"),t.queries||(t.queries=[]),this.validateQuery(t),this.evaluateQueryGroup(t,t,n,r,s)}}const Je=new Set(["apikey","api-key","managerkey","token","proxy-key","proxykey","manager-key","sdk-key"]);function Xe(i){const e=i.indexOf("?");if(e<0)return i;const t=i.slice(e+1).split("&").map(r=>{const s=r.indexOf("=");if(s<0)return r;const n=r.slice(0,s);return Je.has(n.toLowerCase())?`${n}=<redacted>`:r}).join("&");return`${i.slice(0,e)}?${t}`}const ne="k:",ie="h:";function S(i,e=0){if(i.key)return`${ne}${i.key}`;const t=I({type:i.type,url:i.rawUrl??i.url,model:i.model??"",occurrence:e});return`${ie}${t}`}function Ze(i){const e=new Map,t=new Set;return i.map(r=>{const s=`${r.key??""}|${r.type}|${r.rawUrl??r.url}|${r.model??""}`;let n=e.get(s)??0,o=S(r,n);for(;t.has(o);)n+=1,o=r.key?`${S(r)}#${n}`:S(r,n);return e.set(s,n+1),t.add(o),o})}function Ye(){const i=globalThis;return typeof i.scheduler?.yield=="function"?i.scheduler.yield():typeof i.setImmediate=="function"?new Promise(e=>i.setImmediate(()=>e())):typeof i.MessageChannel=="function"?new Promise(e=>{const t=new i.MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)}):new Promise(e=>setTimeout(e,0))}class et{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),n=new Function("script_type",...t,s);return this.scriptFunctions.set(e,n),n}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
|
|
4
|
+
`}executeScript(e,t,r){if(!this.getScript(e))throw new Error(`Script ${e} not found`);r.context||(r.context=r.options||{});const n=Object.keys(r),o=Object.values(r);return this.getScriptAsFn(e,n)(t,...o)}}const tt=(i,e)=>i?(e||(e={}),i.replace(/\$\{(.*?)\}/g,(t,r)=>p.get(e,r.trim(),""))):"",rt=i=>{const e=new Set;return i.replace(/\$\{(.*?)\}/g,(r,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(r=>({name:r}))}},st=["any","Array<date>","Array<float>","Array<int>","Array<string>","boolean","date","float","int","json","string"],nt=["int","float","Array<int>","Array<float>"],it=["date","Array<date>"],ot=["eq","in","find","gt","gte","lt","lte","typeof","isTruthy","size"];exports.AUTHORED_RESOURCE_ID_PREFIX=ne;exports.AnalyticsController=ae;exports.AttributeDependencyGraph=ce;exports.CacheController=ue;exports.ChangeDetector=ve;exports.DERIVED_RESOURCE_ID_PREFIX=ie;exports.DatePropertyTypes=it;exports.DcuplQueryBuilder=$;exports.DcuplQueryOperatorsAsArray=ot;exports.DeepQueryService=W;exports.DependencyGraph=P;exports.IndicesController=J;exports.Logger=g;exports.NumberPropertyTypes=nt;exports.PropertyTypesAsArray=st;exports.QueryManager=He;exports.ScriptController=et;exports.clone=O;exports.coerceStringType=Z;exports.compareVersions=L;exports.computeSuggestions=xe;exports.deepQueryService=m;exports.escapeRegExp=j;exports.evaluateTemplate=tt;exports.generateBooleanQuery=Le;exports.generateKey=B;exports.generateNumberAndDateQuery=Ve;exports.generateReferenceQuery=Ue;exports.generateTextQuery=je;exports.getAggregation=Q;exports.getDateConstraintUid=de;exports.getDcuplPropertyTypeForNativeType=se;exports.getDeepPathValues=w;exports.getDistinct=H;exports.getFacets=Oe;exports.getFilterEntryId=fe;exports.getNumberConstraintUid=le;exports.getPropertiesForData=Be;exports.groupBy=pe;exports.hasMinimumVersion=me;exports.inferModel=ee;exports.isDateInstance=V;exports.isFloat=re;exports.isInt=te;exports.isValidDate=U;exports.isValidQueryStatement=We;exports.isValidVersion=E;exports.logger=z;exports.looksDateLike=Y;exports.parseDate=Ie;exports.parseRegexLiteral=N;exports.parseTemplate=rt;exports.perf=b;exports.pivot=R;exports.redactUrl=Xe;exports.removeTrailingSlash=ge;exports.resolveResourceId=S;exports.resolveResourceIds=Ze;exports.trigger=we;exports.unescapeRegExp=ye;exports.uniqBy=he;exports.yieldToEventLoop=Ye;
|
|
5
5
|
//# sourceMappingURL=index.cjs.map
|