@dcupl/bundle 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/dcupl.bundle.js +1434 -1218
- package/dist/dcupl.bundle.js.map +1 -1
- package/dist/dcupl.bundle.min.js +9 -9
- package/dist/dcupl.bundle.min.js.map +1 -1
- package/package.json +4 -4
package/dist/dcupl.bundle.min.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
(function(){"use strict";var R=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},O={searchParams:"URLSearchParams"in R,iterable:"Symbol"in R&&"iterator"in Symbol,blob:"FileReader"in R&&"Blob"in R&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in R,arrayBuffer:"ArrayBuffer"in R};function Fi(r){return r&&DataView.prototype.isPrototypeOf(r)}if(O.arrayBuffer)var qi=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Qi=ArrayBuffer.isView||function(r){return r&&qi.indexOf(Object.prototype.toString.call(r))>-1};function Ee(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(r)||r==="")throw new TypeError('Invalid character in header field name: "'+r+'"');return r.toLowerCase()}function
|
|
2
|
-
`)===0?s.substr(1,s.length):s}).forEach(function(s){var o=s.split(":"),n=o.shift().trim();if(n){var i=o.join(":").trim();try{e.append(n,i)}catch(a){console.warn("Response "+a.message)}}}),e}us.call(ye.prototype);function H(r,e){if(!(this instanceof H))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new x(e.headers),this.url=e.url||"",this._initBody(r)}us.call(H.prototype),H.prototype.clone=function(){return new H(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new x(this.headers),url:this.url})},H.error=function(){var r=new H(null,{status:200,statusText:""});return r.ok=!1,r.status=0,r.type="error",r};var Wi=[301,302,303,307,308];H.redirect=function(r,e){if(Wi.indexOf(e)===-1)throw new RangeError("Invalid status code");return new H(null,{status:e,headers:{location:r}})};var ge=R.DOMException;try{new ge}catch{ge=function(e,t){this.message=e,this.name=t;var s=Error(e);this.stack=s.stack},ge.prototype=Object.create(Error.prototype),ge.prototype.constructor=ge}function cs(r,e){return new Promise(function(t,s){var o=new ye(r,e);if(o.signal&&o.signal.aborted)return s(new ge("Aborted","AbortError"));var n=new XMLHttpRequest;function i(){n.abort()}n.onload=function(){var u={statusText:n.statusText,headers:Li(n.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(n.status<200||n.status>599)?u.status=200:u.status=n.status,u.url="responseURL"in n?n.responseURL:u.headers.get("X-Request-URL");var c="response"in n?n.response:n.responseText;setTimeout(function(){t(new H(c,u))},0)},n.onerror=function(){setTimeout(function(){s(new TypeError("Network request failed"))},0)},n.ontimeout=function(){setTimeout(function(){s(new TypeError("Network request timed out"))},0)},n.onabort=function(){setTimeout(function(){s(new ge("Aborted","AbortError"))},0)};function a(u){try{return u===""&&R.location.href?R.location.href:u}catch{return u}}if(n.open(o.method,a(o.url),!0),o.credentials==="include"?n.withCredentials=!0:o.credentials==="omit"&&(n.withCredentials=!1),"responseType"in n&&(O.blob?n.responseType="blob":O.arrayBuffer&&(n.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof x||R.Headers&&e.headers instanceof R.Headers)){var l=[];Object.getOwnPropertyNames(e.headers).forEach(function(u){l.push(Ee(u)),n.setRequestHeader(u,Lt(e.headers[u]))}),o.headers.forEach(function(u,c){l.indexOf(c)===-1&&n.setRequestHeader(c,u)})}else o.headers.forEach(function(u,c){n.setRequestHeader(c,u)});o.signal&&(o.signal.addEventListener("abort",i),n.onreadystatechange=function(){n.readyState===4&&o.signal.removeEventListener("abort",i)}),n.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}cs.polyfill=!0,R.fetch||(R.fetch=cs,R.Headers=x,R.Request=ye,R.Response=H);var ds=typeof global=="object"&&global&&global.Object===Object&&global,Hi=typeof self=="object"&&self&&self.Object===Object&&self,J=ds||Hi||Function("return this")(),B=J.Symbol,fs=Object.prototype,Ji=fs.hasOwnProperty,Zi=fs.toString,He=B?B.toStringTag:void 0;function Yi(r){var e=Ji.call(r,He),t=r[He];try{r[He]=void 0;var s=!0}catch{}var o=Zi.call(r);return s&&(e?r[He]=t:delete r[He]),o}var Xi=Object.prototype,ea=Xi.toString;function ta(r){return ea.call(r)}var ra="[object Null]",sa="[object Undefined]",ps=B?B.toStringTag:void 0;function ee(r){return r==null?r===void 0?sa:ra:ps&&ps in Object(r)?Yi(r):ta(r)}function K(r){return r!=null&&typeof r=="object"}var oa="[object Symbol]";function je(r){return typeof r=="symbol"||K(r)&&ee(r)==oa}function Se(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var E=Array.isArray,hs=B?B.prototype:void 0,ys=hs?hs.toString:void 0;function Jt(r){if(typeof r=="string")return r;if(E(r))return Se(r,Jt)+"";if(je(r))return ys?ys.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var na=/\s/;function ia(r){for(var e=r.length;e--&&na.test(r.charAt(e)););return e}var aa=/^\s+/;function la(r){return r&&r.slice(0,ia(r)+1).replace(aa,"")}function z(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var gs=NaN,ua=/^[-+]0x[0-9a-f]+$/i,ca=/^0b[01]+$/i,da=/^0o[0-7]+$/i,fa=parseInt;function pa(r){if(typeof r=="number")return r;if(je(r))return gs;if(z(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=z(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=la(r);var t=ca.test(r);return t||da.test(r)?fa(r.slice(2),t?2:8):ua.test(r)?gs:+r}var ms=1/0,ha=17976931348623157e292;function ya(r){if(!r)return r===0?r:0;if(r=pa(r),r===ms||r===-ms){var e=r<0?-1:1;return e*ha}return r===r?r:0}function Zt(r){var e=ya(r),t=e%1;return e===e?t?e-t:e:0}function wt(r){return r}var ga="[object AsyncFunction]",ma="[object Function]",va="[object GeneratorFunction]",ba="[object Proxy]";function Yt(r){if(!z(r))return!1;var e=ee(r);return e==ma||e==va||e==ga||e==ba}var Xt=J["__core-js_shared__"],vs=(function(){var r=/[^.]+$/.exec(Xt&&Xt.keys&&Xt.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function ka(r){return!!vs&&vs in r}var wa=Function.prototype,Aa=wa.toString;function me(r){if(r!=null){try{return Aa.call(r)}catch{}try{return r+""}catch{}}return""}var $a=/[\\^$.*+?()[\]{}|]/g,Ca=/^\[object .+?Constructor\]$/,Da=Function.prototype,_a=Object.prototype,Pa=Da.toString,xa=_a.hasOwnProperty,Ea=RegExp("^"+Pa.call(xa).replace($a,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ja(r){if(!z(r)||ka(r))return!1;var e=Yt(r)?Ea:Ca;return e.test(me(r))}function Sa(r,e){return r?.[e]}function ve(r,e){var t=Sa(r,e);return ja(t)?t:void 0}var er=ve(J,"WeakMap"),bs=Object.create,Ma=(function(){function r(){}return function(e){if(!z(e))return{};if(bs)return bs(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function Ra(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var Ia=800,Ta=16,Oa=Date.now;function Ka(r){var e=0,t=0;return function(){var s=Oa(),o=Ta-(s-t);if(t=s,o>0){if(++e>=Ia)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function Fa(r){return function(){return r}}var At=(function(){try{var r=ve(Object,"defineProperty");return r({},"",{}),r}catch{}})(),qa=At?function(r,e){return At(r,"toString",{configurable:!0,enumerable:!1,value:Fa(e),writable:!0})}:wt,Qa=Ka(qa);function Va(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function ks(r,e,t,s){for(var o=r.length,n=t+-1;++n<o;)if(e(r[n],n,r))return n;return-1}function Ga(r){return r!==r}function Ba(r,e,t){for(var s=t-1,o=r.length;++s<o;)if(r[s]===e)return s;return-1}function ws(r,e,t){return e===e?Ba(r,e,t):ks(r,Ga,t)}function Ua(r,e){var t=r==null?0:r.length;return!!t&&ws(r,e,0)>-1}var Na=9007199254740991,za=/^(?:0|[1-9]\d*)$/;function tr(r,e){var t=typeof r;return e=e??Na,!!e&&(t=="number"||t!="symbol"&&za.test(r))&&r>-1&&r%1==0&&r<e}function $t(r,e,t){e=="__proto__"&&At?At(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function Je(r,e){return r===e||r!==r&&e!==e}var La=Object.prototype,Wa=La.hasOwnProperty;function As(r,e,t){var s=r[e];(!(Wa.call(r,e)&&Je(s,t))||t===void 0&&!(e in r))&&$t(r,e,t)}var $s=Math.max;function Ha(r,e,t){return e=$s(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=$s(s.length-e,0),i=Array(n);++o<n;)i[o]=s[e+o];o=-1;for(var a=Array(e+1);++o<e;)a[o]=s[o];return a[e]=t(i),Ra(r,this,a)}}function rr(r,e){return Qa(Ha(r,e,wt),r+"")}var Ja=9007199254740991;function sr(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ja}function te(r){return r!=null&&sr(r.length)&&!Yt(r)}var Za=Object.prototype;function or(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Za;return r===t}function Ya(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var Xa="[object Arguments]";function Cs(r){return K(r)&&ee(r)==Xa}var Ds=Object.prototype,el=Ds.hasOwnProperty,tl=Ds.propertyIsEnumerable,Ze=Cs((function(){return arguments})())?Cs:function(r){return K(r)&&el.call(r,"callee")&&!tl.call(r,"callee")};function rl(){return!1}var _s=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ps=_s&&typeof module=="object"&&module&&!module.nodeType&&module,sl=Ps&&Ps.exports===_s,xs=sl?J.Buffer:void 0,ol=xs?xs.isBuffer:void 0,Ye=ol||rl,nl="[object Arguments]",il="[object Array]",al="[object Boolean]",ll="[object Date]",ul="[object Error]",cl="[object Function]",dl="[object Map]",fl="[object Number]",pl="[object Object]",hl="[object RegExp]",yl="[object Set]",gl="[object String]",ml="[object WeakMap]",vl="[object ArrayBuffer]",bl="[object DataView]",kl="[object Float32Array]",wl="[object Float64Array]",Al="[object Int8Array]",$l="[object Int16Array]",Cl="[object Int32Array]",Dl="[object Uint8Array]",_l="[object Uint8ClampedArray]",Pl="[object Uint16Array]",xl="[object Uint32Array]",C={};C[kl]=C[wl]=C[Al]=C[$l]=C[Cl]=C[Dl]=C[_l]=C[Pl]=C[xl]=!0,C[nl]=C[il]=C[vl]=C[al]=C[bl]=C[ll]=C[ul]=C[cl]=C[dl]=C[fl]=C[pl]=C[hl]=C[yl]=C[gl]=C[ml]=!1;function El(r){return K(r)&&sr(r.length)&&!!C[ee(r)]}function Xe(r){return function(e){return r(e)}}var Es=typeof exports=="object"&&exports&&!exports.nodeType&&exports,et=Es&&typeof module=="object"&&module&&!module.nodeType&&module,jl=et&&et.exports===Es,nr=jl&&ds.process,Me=(function(){try{var r=et&&et.require&&et.require("util").types;return r||nr&&nr.binding&&nr.binding("util")}catch{}})(),js=Me&&Me.isTypedArray,ir=js?Xe(js):El,Sl=Object.prototype,Ml=Sl.hasOwnProperty;function Ss(r,e){var t=E(r),s=!t&&Ze(r),o=!t&&!s&&Ye(r),n=!t&&!s&&!o&&ir(r),i=t||s||o||n,a=i?Ya(r.length,String):[],l=a.length;for(var u in r)(e||Ml.call(r,u))&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||n&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||tr(u,l)))&&a.push(u);return a}function Ms(r,e){return function(t){return r(e(t))}}var Rl=Ms(Object.keys,Object),Il=Object.prototype,Tl=Il.hasOwnProperty;function Rs(r){if(!or(r))return Rl(r);var e=[];for(var t in Object(r))Tl.call(r,t)&&t!="constructor"&&e.push(t);return e}function tt(r){return te(r)?Ss(r):Rs(r)}var Ol=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Kl=/^\w*$/;function ar(r,e){if(E(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||je(r)?!0:Kl.test(r)||!Ol.test(r)||e!=null&&r in Object(e)}var rt=ve(Object,"create");function Fl(){this.__data__=rt?rt(null):{},this.size=0}function ql(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Ql="__lodash_hash_undefined__",Vl=Object.prototype,Gl=Vl.hasOwnProperty;function Bl(r){var e=this.__data__;if(rt){var t=e[r];return t===Ql?void 0:t}return Gl.call(e,r)?e[r]:void 0}var Ul=Object.prototype,Nl=Ul.hasOwnProperty;function zl(r){var e=this.__data__;return rt?e[r]!==void 0:Nl.call(e,r)}var Ll="__lodash_hash_undefined__";function Wl(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=rt&&e===void 0?Ll:e,this}function be(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}be.prototype.clear=Fl,be.prototype.delete=ql,be.prototype.get=Bl,be.prototype.has=zl,be.prototype.set=Wl;function Hl(){this.__data__=[],this.size=0}function Ct(r,e){for(var t=r.length;t--;)if(Je(r[t][0],e))return t;return-1}var Jl=Array.prototype,Zl=Jl.splice;function Yl(r){var e=this.__data__,t=Ct(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Zl.call(e,t,1),--this.size,!0}function Xl(r){var e=this.__data__,t=Ct(e,r);return t<0?void 0:e[t][1]}function eu(r){return Ct(this.__data__,r)>-1}function tu(r,e){var t=this.__data__,s=Ct(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function re(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}re.prototype.clear=Hl,re.prototype.delete=Yl,re.prototype.get=Xl,re.prototype.has=eu,re.prototype.set=tu;var st=ve(J,"Map");function ru(){this.size=0,this.__data__={hash:new be,map:new(st||re),string:new be}}function su(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Dt(r,e){var t=r.__data__;return su(e)?t[typeof e=="string"?"string":"hash"]:t.map}function ou(r){var e=Dt(this,r).delete(r);return this.size-=e?1:0,e}function nu(r){return Dt(this,r).get(r)}function iu(r){return Dt(this,r).has(r)}function au(r,e){var t=Dt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function se(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}se.prototype.clear=ru,se.prototype.delete=ou,se.prototype.get=nu,se.prototype.has=iu,se.prototype.set=au;var lu="Expected a function";function lr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(lu);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(lr.Cache||se),t}lr.Cache=se;var uu=500;function cu(r){var e=lr(r,function(s){return t.size===uu&&t.clear(),s}),t=e.cache;return e}var du=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,fu=/\\(\\)?/g,pu=cu(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(du,function(t,s,o,n){e.push(o?n.replace(fu,"$1"):s||t)}),e});function Is(r){return r==null?"":Jt(r)}function Ts(r,e){return E(r)?r:ar(r,e)?[r]:pu(Is(r))}function _t(r){if(typeof r=="string"||je(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ur(r,e){e=Ts(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[_t(e[t++])];return t&&t==s?r:void 0}function ot(r,e,t){var s=r==null?void 0:ur(r,e);return s===void 0?t:s}function Os(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var Ks=B?B.isConcatSpreadable:void 0;function hu(r){return E(r)||Ze(r)||!!(Ks&&r&&r[Ks])}function Fs(r,e,t,s,o){var n=-1,i=r.length;for(t||(t=hu),o||(o=[]);++n<i;){var a=r[n];t(a)&&Os(o,a)}return o}var qs=Ms(Object.getPrototypeOf,Object),yu="\\ud800-\\udfff",gu="\\u0300-\\u036f",mu="\\ufe20-\\ufe2f",vu="\\u20d0-\\u20ff",bu=gu+mu+vu,ku="\\ufe0e\\ufe0f",wu="\\u200d",Au=RegExp("["+wu+yu+bu+ku+"]");function $u(r){return Au.test(r)}function Cu(){this.__data__=new re,this.size=0}function Du(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function _u(r){return this.__data__.get(r)}function Pu(r){return this.__data__.has(r)}var xu=200;function Eu(r,e){var t=this.__data__;if(t instanceof re){var s=t.__data__;if(!st||s.length<xu-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new se(s)}return t.set(r,e),this.size=t.size,this}function L(r){var e=this.__data__=new re(r);this.size=e.size}L.prototype.clear=Cu,L.prototype.delete=Du,L.prototype.get=_u,L.prototype.has=Pu,L.prototype.set=Eu;var Qs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Vs=Qs&&typeof module=="object"&&module&&!module.nodeType&&module,ju=Vs&&Vs.exports===Qs,Gs=ju?J.Buffer:void 0,Bs=Gs?Gs.allocUnsafe:void 0;function Us(r,e){if(e)return r.slice();var t=r.length,s=Bs?Bs(t):new r.constructor(t);return r.copy(s),s}function Su(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function Mu(){return[]}var Ru=Object.prototype,Iu=Ru.propertyIsEnumerable,Ns=Object.getOwnPropertySymbols,Tu=Ns?function(r){return r==null?[]:(r=Object(r),Su(Ns(r),function(e){return Iu.call(r,e)}))}:Mu;function Ou(r,e,t){var s=e(r);return E(r)?s:Os(s,t(r))}function cr(r){return Ou(r,tt,Tu)}var dr=ve(J,"DataView"),fr=ve(J,"Promise"),pr=ve(J,"Set"),zs="[object Map]",Ku="[object Object]",Ls="[object Promise]",Ws="[object Set]",Hs="[object WeakMap]",Js="[object DataView]",Fu=me(dr),qu=me(st),Qu=me(fr),Vu=me(pr),Gu=me(er),U=ee;(dr&&U(new dr(new ArrayBuffer(1)))!=Js||st&&U(new st)!=zs||fr&&U(fr.resolve())!=Ls||pr&&U(new pr)!=Ws||er&&U(new er)!=Hs)&&(U=function(r){var e=ee(r),t=e==Ku?r.constructor:void 0,s=t?me(t):"";if(s)switch(s){case Fu:return Js;case qu:return zs;case Qu:return Ls;case Vu:return Ws;case Gu:return Hs}return e});var Bu=Object.prototype,Uu=Bu.hasOwnProperty;function Nu(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Uu.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var Pt=J.Uint8Array;function hr(r){var e=new r.constructor(r.byteLength);return new Pt(e).set(new Pt(r)),e}function zu(r,e){var t=hr(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Lu=/\w*$/;function Wu(r){var e=new r.constructor(r.source,Lu.exec(r));return e.lastIndex=r.lastIndex,e}var Zs=B?B.prototype:void 0,Ys=Zs?Zs.valueOf:void 0;function Hu(r){return Ys?Object(Ys.call(r)):{}}function Xs(r,e){var t=e?hr(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.length)}var Ju="[object Boolean]",Zu="[object Date]",Yu="[object Map]",Xu="[object Number]",ec="[object RegExp]",tc="[object Set]",rc="[object String]",sc="[object Symbol]",oc="[object ArrayBuffer]",nc="[object DataView]",ic="[object Float32Array]",ac="[object Float64Array]",lc="[object Int8Array]",uc="[object Int16Array]",cc="[object Int32Array]",dc="[object Uint8Array]",fc="[object Uint8ClampedArray]",pc="[object Uint16Array]",hc="[object Uint32Array]";function yc(r,e,t){var s=r.constructor;switch(e){case oc:return hr(r);case Ju:case Zu:return new s(+r);case nc:return zu(r);case ic:case ac:case lc:case uc:case cc:case dc:case fc:case pc:case hc:return Xs(r,t);case Yu:return new s;case Xu:case rc:return new s(r);case ec:return Wu(r);case tc:return new s;case sc:return Hu(r)}}function eo(r){return typeof r.constructor=="function"&&!or(r)?Ma(qs(r)):{}}var gc="[object Map]";function mc(r){return K(r)&&U(r)==gc}var to=Me&&Me.isMap,vc=to?Xe(to):mc,bc="[object Set]";function kc(r){return K(r)&&U(r)==bc}var ro=Me&&Me.isSet,wc=ro?Xe(ro):kc,Ac=1,so="[object Arguments]",$c="[object Array]",Cc="[object Boolean]",Dc="[object Date]",_c="[object Error]",oo="[object Function]",Pc="[object GeneratorFunction]",xc="[object Map]",Ec="[object Number]",no="[object Object]",jc="[object RegExp]",Sc="[object Set]",Mc="[object String]",Rc="[object Symbol]",Ic="[object WeakMap]",Tc="[object ArrayBuffer]",Oc="[object DataView]",Kc="[object Float32Array]",Fc="[object Float64Array]",qc="[object Int8Array]",Qc="[object Int16Array]",Vc="[object Int32Array]",Gc="[object Uint8Array]",Bc="[object Uint8ClampedArray]",Uc="[object Uint16Array]",Nc="[object Uint32Array]",w={};w[so]=w[$c]=w[Tc]=w[Oc]=w[Cc]=w[Dc]=w[Kc]=w[Fc]=w[qc]=w[Qc]=w[Vc]=w[xc]=w[Ec]=w[no]=w[jc]=w[Sc]=w[Mc]=w[Rc]=w[Gc]=w[Bc]=w[Uc]=w[Nc]=!0,w[_c]=w[oo]=w[Ic]=!1;function xt(r,e,t,s,o,n){var i,a=e&Ac;if(i!==void 0)return i;if(!z(r))return r;var l=E(r);if(l)i=Nu(r);else{var u=U(r),c=u==oo||u==Pc;if(Ye(r))return Us(r,a);if(u==no||u==so||c&&!o)i=c?{}:eo(r);else{if(!w[u])return o?r:{};i=yc(r,u,a)}}n||(n=new L);var d=n.get(r);if(d)return d;n.set(r,i),wc(r)?r.forEach(function(p){i.add(xt(p,e,t,p,r,n))}):vc(r)&&r.forEach(function(p,y){i.set(y,xt(p,e,t,y,r,n))});var f=cr,h=l?void 0:f(r);return Va(h||r,function(p,y){h&&(y=p,p=r[y]),As(i,y,xt(p,e,t,y,r,n))}),i}var zc=1,Lc=4;function oe(r){return xt(r,zc|Lc)}var Wc="__lodash_hash_undefined__";function Hc(r){return this.__data__.set(r,Wc),this}function Jc(r){return this.__data__.has(r)}function nt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new se;++e<t;)this.add(r[e])}nt.prototype.add=nt.prototype.push=Hc,nt.prototype.has=Jc;function Zc(r,e){for(var t=-1,s=r==null?0:r.length;++t<s;)if(e(r[t],t,r))return!0;return!1}function io(r,e){return r.has(e)}var Yc=1,Xc=2;function ao(r,e,t,s,o,n){var i=t&Yc,a=r.length,l=e.length;if(a!=l&&!(i&&l>a))return!1;var u=n.get(r),c=n.get(e);if(u&&c)return u==e&&c==r;var d=-1,f=!0,h=t&Xc?new nt:void 0;for(n.set(r,e),n.set(e,r);++d<a;){var p=r[d],y=e[d];if(s)var v=i?s(y,p,d,e,r,n):s(p,y,d,r,e,n);if(v!==void 0){if(v)continue;f=!1;break}if(h){if(!Zc(e,function(g,k){if(!io(h,k)&&(p===g||o(p,g,t,s,n)))return h.push(k)})){f=!1;break}}else if(!(p===y||o(p,y,t,s,n))){f=!1;break}}return n.delete(r),n.delete(e),f}function ed(r){var e=-1,t=Array(r.size);return r.forEach(function(s,o){t[++e]=[o,s]}),t}function td(r){var e=-1,t=Array(r.size);return r.forEach(function(s){t[++e]=s}),t}var rd=1,sd=2,od="[object Boolean]",nd="[object Date]",id="[object Error]",ad="[object Map]",ld="[object Number]",ud="[object RegExp]",cd="[object Set]",dd="[object String]",fd="[object Symbol]",pd="[object ArrayBuffer]",hd="[object DataView]",lo=B?B.prototype:void 0,yr=lo?lo.valueOf:void 0;function yd(r,e,t,s,o,n,i){switch(t){case hd:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case pd:return!(r.byteLength!=e.byteLength||!n(new Pt(r),new Pt(e)));case od:case nd:case ld:return Je(+r,+e);case id:return r.name==e.name&&r.message==e.message;case ud:case dd:return r==e+"";case ad:var a=ed;case cd:var l=s&rd;if(a||(a=td),r.size!=e.size&&!l)return!1;var u=i.get(r);if(u)return u==e;s|=sd,i.set(r,e);var c=ao(a(r),a(e),s,o,n,i);return i.delete(r),c;case fd:if(yr)return yr.call(r)==yr.call(e)}return!1}var gd=1,md=Object.prototype,vd=md.hasOwnProperty;function bd(r,e,t,s,o,n){var i=t&gd,a=cr(r),l=a.length,u=cr(e),c=u.length;if(l!=c&&!i)return!1;for(var d=l;d--;){var f=a[d];if(!(i?f in e:vd.call(e,f)))return!1}var h=n.get(r),p=n.get(e);if(h&&p)return h==e&&p==r;var y=!0;n.set(r,e),n.set(e,r);for(var v=i;++d<l;){f=a[d];var g=r[f],k=e[f];if(s)var m=i?s(k,g,f,e,r,n):s(g,k,f,r,e,n);if(!(m===void 0?g===k||o(g,k,t,s,n):m)){y=!1;break}v||(v=f=="constructor")}if(y&&!v){var M=r.constructor,N=e.constructor;M!=N&&"constructor"in r&&"constructor"in e&&!(typeof M=="function"&&M instanceof M&&typeof N=="function"&&N instanceof N)&&(y=!1)}return n.delete(r),n.delete(e),y}var kd=1,uo="[object Arguments]",co="[object Array]",Et="[object Object]",wd=Object.prototype,fo=wd.hasOwnProperty;function Ad(r,e,t,s,o,n){var i=E(r),a=E(e),l=i?co:U(r),u=a?co:U(e);l=l==uo?Et:l,u=u==uo?Et:u;var c=l==Et,d=u==Et,f=l==u;if(f&&Ye(r)){if(!Ye(e))return!1;i=!0,c=!1}if(f&&!c)return n||(n=new L),i||ir(r)?ao(r,e,t,s,o,n):yd(r,e,l,t,s,o,n);if(!(t&kd)){var h=c&&fo.call(r,"__wrapped__"),p=d&&fo.call(e,"__wrapped__");if(h||p){var y=h?r.value():r,v=p?e.value():e;return n||(n=new L),o(y,v,t,s,n)}}return f?(n||(n=new L),bd(r,e,t,s,o,n)):!1}function it(r,e,t,s,o){return r===e?!0:r==null||e==null||!K(r)&&!K(e)?r!==r&&e!==e:Ad(r,e,t,s,it,o)}var $d=1,Cd=2;function po(r,e,t,s){var o=t.length,n=o;if(r==null)return!n;for(r=Object(r);o--;){var i=t[o];if(i[2]?i[1]!==r[i[0]]:!(i[0]in r))return!1}for(;++o<n;){i=t[o];var a=i[0],l=r[a],u=i[1];if(i[2]){if(l===void 0&&!(a in r))return!1}else{var c=new L,d;if(!(d===void 0?it(u,l,$d|Cd,s,c):d))return!1}}return!0}function ho(r){return r===r&&!z(r)}function yo(r){for(var e=tt(r),t=e.length;t--;){var s=e[t],o=r[s];e[t]=[s,o,ho(o)]}return e}function go(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Dd(r){var e=yo(r);return e.length==1&&e[0][2]?go(e[0][0],e[0][1]):function(t){return t===r||po(t,r,e)}}function _d(r,e){return r!=null&&e in Object(r)}function Pd(r,e,t){e=Ts(e,r);for(var s=-1,o=e.length,n=!1;++s<o;){var i=_t(e[s]);if(!(n=r!=null&&t(r,i)))break;r=r[i]}return n||++s!=o?n:(o=r==null?0:r.length,!!o&&sr(o)&&tr(i,o)&&(E(r)||Ze(r)))}function xd(r,e){return r!=null&&Pd(r,e,_d)}var Ed=1,jd=2;function Sd(r,e){return ar(r)&&ho(e)?go(_t(r),e):function(t){var s=ot(t,r);return s===void 0&&s===e?xd(t,r):it(e,s,Ed|jd)}}function mo(r){return function(e){return e?.[r]}}function Md(r){return function(e){return ur(e,r)}}function Rd(r){return ar(r)?mo(_t(r)):Md(r)}function Re(r){return typeof r=="function"?r:r==null?wt:typeof r=="object"?E(r)?Sd(r[0],r[1]):Dd(r):Rd(r)}function Id(r){return function(e,t,s){for(var o=-1,n=Object(e),i=s(e),a=i.length;a--;){var l=i[++o];if(t(n[l],l,n)===!1)break}return e}}var vo=Id();function Td(r,e){return r&&vo(r,e,tt)}function Od(r,e){return function(t,s){if(t==null)return t;if(!te(t))return r(t,s);for(var o=t.length,n=-1,i=Object(t);++n<o&&s(i[n],n,i)!==!1;);return t}}var gr=Od(Td);function Ie(r){return K(r)&&te(r)}var Kd=200;function bo(r,e,t,s){var o=-1,n=Ua,i=!0,a=r.length,l=[],u=e.length;if(!a)return l;t&&(e=Se(e,Xe(t))),e.length>=Kd&&(n=io,i=!1,e=new nt(e));e:for(;++o<a;){var c=r[o],d=t==null?c:t(c);if(c=c!==0?c:0,i&&d===d){for(var f=u;f--;)if(e[f]===d)continue e;l.push(c)}else n(e,d,s)||l.push(c)}return l}function Fd(r){var e=r==null?0:r.length;return e?r[e-1]:void 0}var ko=rr(function(r,e){var t=Fd(e);return Ie(t)&&(t=void 0),Ie(r)?bo(r,Fs(e,1,Ie),Re(t)):[]});function qd(r,e){for(var t=-1,s=r==null?0:r.length;++t<s;)if(!e(r[t],t,r))return!1;return!0}function Qd(r,e){var t=!0;return gr(r,function(s,o,n){return t=!!e(s,o,n),t}),t}function wo(r,e,t){var s=E(r)?qd:Qd;return s(r,Re(e))}function Vd(r){return function(e,t,s){var o=Object(e);if(!te(e)){var n=Re(t);e=tt(e),t=function(a){return n(o[a],a,o)}}var i=r(e,t,s);return i>-1?o[n?e[i]:i]:void 0}}var Gd=Math.max;function mr(r,e,t){var s=r==null?0:r.length;if(!s)return-1;var o=t==null?0:Zt(t);return o<0&&(o=Gd(s+o,0)),ks(r,Re(e),o)}var Bd=Vd(mr);function Ud(r,e){var t=-1,s=te(r)?Array(r.length):[];return gr(r,function(o,n,i){s[++t]=e(o,n,i)}),s}var Nd="[object String]";function jt(r){return typeof r=="string"||!E(r)&&K(r)&&ee(r)==Nd}function zd(r,e){return it(r,e)}function vr(r,e,t){t=typeof t=="function"?t:void 0;var s=t?t(r,e):void 0;return s===void 0?it(r,e,void 0,t):!!s}function Ao(r,e){return r===e||po(r,e,yo(e))}function Ld(r,e){var t=r.length;for(r.sort(e);t--;)r[t]=r[t].value;return r}function Wd(r,e){if(r!==e){var t=r!==void 0,s=r===null,o=r===r,n=je(r),i=e!==void 0,a=e===null,l=e===e,u=je(e);if(!a&&!u&&!n&&r>e||n&&i&&l&&!a&&!u||s&&i&&l||!t&&l||!o)return 1;if(!s&&!n&&!u&&r<e||u&&t&&o&&!s&&!n||a&&t&&o||!i&&o||!l)return-1}return 0}function Hd(r,e,t){for(var s=-1,o=r.criteria,n=e.criteria,i=o.length,a=t.length;++s<i;){var l=Wd(o[s],n[s]);if(l){if(s>=a)return l;var u=t[s];return l*(u=="desc"?-1:1)}}return r.index-e.index}function Jd(r,e,t){e.length?e=Se(e,function(n){return E(n)?function(i){return ur(i,n.length===1?n[0]:n)}:n}):e=[wt];var s=-1;e=Se(e,Xe(Re));var o=Ud(r,function(n,i,a){var l=Se(e,function(u){return u(n)});return{criteria:l,index:++s,value:n}});return Ld(o,function(n,i){return Hd(n,i,t)})}function $o(r,e,t,s){return r==null?[]:(E(e)||(e=e==null?[]:[e]),t=t,E(t)||(t=t==null?[]:[t]),Jd(r,e,t))}var Zd=mo("length"),Co="\\ud800-\\udfff",Yd="\\u0300-\\u036f",Xd="\\ufe20-\\ufe2f",ef="\\u20d0-\\u20ff",tf=Yd+Xd+ef,rf="\\ufe0e\\ufe0f",sf="["+Co+"]",br="["+tf+"]",kr="\\ud83c[\\udffb-\\udfff]",of="(?:"+br+"|"+kr+")",Do="[^"+Co+"]",_o="(?:\\ud83c[\\udde6-\\uddff]){2}",Po="[\\ud800-\\udbff][\\udc00-\\udfff]",nf="\\u200d",xo=of+"?",Eo="["+rf+"]?",af="(?:"+nf+"(?:"+[Do,_o,Po].join("|")+")"+Eo+xo+")*",lf=Eo+xo+af,uf="(?:"+[Do+br+"?",br,_o,Po,sf].join("|")+")",jo=RegExp(kr+"(?="+kr+")|"+uf+lf,"g");function cf(r){for(var e=jo.lastIndex=0;jo.test(r);)++e;return e}function df(r){return $u(r)?cf(r):Zd(r)}var ff="[object Map]",pf="[object Set]";function hf(r){if(r==null)return 0;if(te(r))return jt(r)?df(r):r.length;var e=U(r);return e==ff||e==pf?r.size:Rs(r).length}function wr(r){const e=Ar(r);return yf(e)}function Ar(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(Ar).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+Ar(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function yf(r){let e=0;for(let t=0;t<r.length;t++){const s=r.charCodeAt(t);e=(e<<5)-e+s,e|=0}return e.toString(16)}const ce={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:r=>{typeof performance<"u"&&performance.mark&&performance.mark(r)},measure:(r,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(r,e,t)},getEntriesByName(r){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(r)},getEntriesByType(r){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(r)}};class gf{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),s={name:e.name,type:"mark",value:ce.now(),createdAt:Date.now()};return this.data.set(t,s),s}measure(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),s=this.data.get(this.getKey(e.start,e.context)),o=this.data.get(this.getKey(e.end,e.context));if(!s||!o)return;const n=o.value-s.value,i=Math.round(n*100)/100,a=this.data.get(t);if(a&&e.sum){const u=a.value+i,c={...a,value:u};return this.data.set(t,c),c}const l={name:e.name,type:"measure",value:i,createdAt:Date.now()};return e.detail&&(l.detail=e.detail),this.data.set(t,l),l}update(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context),s=this.data.get(t);if(s){const o={...s,...e.value};this.data.set(t,o)}else this.data.set(t,e.value);return this.data.get(t)}getResourceInfosFromPerformanceAPI(){return typeof performance>"u"?[]:ce.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 s=wr(t);return e+"_"+s}}let So=class Ki{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[s,o]of this.edges)o.has(e)&&t.push(s);return t}isCyclic(){const e=new Set,t=new Set,s=o=>{if(e.has(o))return!1;if(t.has(o))return!0;t.add(o);const n=this.edges.get(o);if(n){for(let i of n)if(s(i))return!0}return t.delete(o),e.add(o),!1};for(let o of this.nodes)if(s(o))return!0;return!1}validateNoCycles(){const e=new Set,t=new Set,s=[],o=n=>{if(e.has(n))return null;if(t.has(n)){const a=s.indexOf(n);return s.slice(a).concat([n])}t.add(n),s.push(n);const i=this.edges.get(n);if(i)for(let a of i){const l=o(a);if(l)return l}return s.pop(),t.delete(n),e.add(n),null};for(let n of this.nodes){const i=o(n);if(i)return{hasCycle:!0,path:i}}return{hasCycle:!1}}order(e){const t=new Set,s=new Set,o=[],n=e?.allowCycles??!1,i=a=>{if(t.has(a))return;if(s.has(a)){if(n)return;throw new Error("Graph has a cycle.")}s.add(a);const l=this.edges.get(a);if(l)for(let u of l)i(u);s.delete(a),t.add(a),o.push(a)};for(let a of this.nodes)t.has(a)||i(a);return o}clear(){this.nodes.clear(),this.edges.clear()}getNodes(){return Array.from(this.nodes)}getAllEdges(){const e=[];for(let[t,s]of this.edges)for(let o of s)e.push([t,o]);return e}getNodesWithNoDependants(){if(this.nodes.size===0)return[];const e=new Set;for(const s of this.edges.values())for(const o of s)e.add(o);const t=[];for(const s of this.nodes)e.has(s)||t.push(s);return t}getNodesByKind(e){const t=[];for(const s of this.nodes)this.nodeKinds.get(s)===e&&t.push(s);return t}getRootsByKind(e){const t=new Set(this.getNodesWithNoDependants()),s=Array.from(t);return e?s.filter(o=>this.nodeKinds.get(o)===e):s}getLeavesByKind(e){const t=[];for(const s of this.nodes){const o=this.edges.get(s);(!o||o.size===0)&&(!e||this.nodeKinds.get(s)===e)&&t.push(s)}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 i of this.nodes)t.set(i,0);for(const i of this.edges.values())for(const a of i)t.set(a,(t.get(a)||0)+1);const s=[];let o=Array.from(this.nodes).filter(i=>(t.get(i)||0)===0);const n=new Set;for(;o.length>0;){const i=o.slice();s.push(i),o=[];for(const a of i){if(n.has(a))continue;n.add(a);const l=this.edges.get(a);if(l)for(const u of l)t.set(u,(t.get(u)||0)-1),(t.get(u)||0)===0&&o.push(u)}}if(n.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const i=new Set(e.filterKinds);return{batches:s.map(a=>a.filter(l=>i.has(this.nodeKinds.get(l))))}}return{batches:s}}getImpactedNodes(e,t="downstream",s){const o=new Set(e),n=u=>!s||s.length===0||s.includes(this.nodeKinds.get(u)??void 0),i=()=>{const u=new Set,c=Array.from(o);for(;c.length;){const d=c.shift();for(const[f,h]of this.edges)h.has(d)&&!u.has(f)&&(u.add(f),c.push(f))}return u},a=()=>{const u=new Set,c=Array.from(o);for(;c.length;){const d=c.shift(),f=this.edges.get(d);if(f)for(const h of f)u.has(h)||(u.add(h),c.push(h))}return u};let l;return t==="both"?l=new Set([...i(),...a()]):t==="upstream"?l=a():l=i(),Array.from(l).filter(n)}toJSON(){const e=Array.from(this.nodes).map(s=>({name:s,kind:this.nodeKinds.get(s),meta:this.nodeMeta.get(s)})),t=this.getAllEdges().map(([s,o])=>({from:s,to:o}));return{nodes:e,edges:t}}static fromJSON(e){const t=new Ki;for(const s of e.nodes)t.addNode(s.name,{kind:s.kind,meta:s.meta});for(const s of e.edges)t.addDependency(s.from,s.to);return t}diff(e){const t=new Set(this.getNodes()),s=new Set(e.getNodes()),o=Array.from(s).filter(d=>!t.has(d)),n=Array.from(t).filter(d=>!s.has(d)),i=new Set(this.getAllEdges().map(d=>d.join("→"))),a=new Set(e.getAllEdges().map(d=>d.join("→"))),l=Array.from(a).filter(d=>!i.has(d)).map(d=>d.split("→")),u=Array.from(i).filter(d=>!a.has(d)).map(d=>d.split("→")),c=[];for(const d of new Set([...t,...s])){const f=this.nodeKinds.get(d),h=e.nodeKinds.get(d);f!==h&&c.push({name:d,from:f,to:h})}return{addedNodes:o,removedNodes:n,addedEdges:l,removedEdges:u,kindChanges:c}}};class mf{graph;nodeIndex;constructor(){this.graph=new So,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 s=this.getNodeId(e.modelKey,e.attributeKey),o=this.getNodeId(t.modelKey,t.attributeKey);this.graph.hasDependency(s,o)||this.graph.addDependency(s,o)}getImpactedAttributes(e){const t=e.map(i=>this.getNodeId(i.modelKey,i.attributeKey)),s=this.graph.getImpactedNodes(t,"downstream").map(i=>this.nodeIndex.get(i)).filter(i=>i!==void 0),o=[...e,...s],n=new Set;return o.filter(i=>{const a=this.getNodeId(i.modelKey,i.attributeKey);return n.has(a)?!1:(n.add(a),!0)})}getProcessingOrder(e){const t=new Map,s=[...e].sort((o,n)=>o.processingStep-n.processingStep);for(const o of s){const{modelKey:n,attributeKey:i,processingStep:a}=o;t.has(n)||t.set(n,new Map);const l=t.get(n);l.has(a)||l.set(a,new Set),l.get(a).add(i)}return t}getAttributesForModel(e){const t=[];for(const s of this.nodeIndex.values())s.modelKey===e&&t.push(s);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=(s,o=new Set)=>{if(o.has(s))return 0;o.add(s);const n=this.graph.getDependencies(s);if(n.length===0)return 1;let i=0;for(const a of n){const l=t(a,new Set(o));i=Math.max(i,l)}return i+1};for(const s of this.graph.getNodes()){const o=t(s);e=Math.max(e,o)}return e}validateCompleteness(e){const t=[];for(const[s,o]of e)for(const n of o){const i=this.getNodeId(s,n);this.hasNode(i)||t.push({modelKey:s,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 s of this.nodeIndex.values())e.set(s.modelKey,(e.get(s.modelKey)||0)+1),t.set(s.processingStep,(t.get(s.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 s=this.parseNodeId(e),o=this.parseNodeId(t);return{from:s,to:o}})}}}const Mo={silent:0,error:1,warn:2,info:3,debug:4};let vf=class T{config;static globalConfig={};constructor(e={}){this.config={level:e.level??T.globalConfig.level??this.getDefaultLevel(),format:e.format??T.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??T.globalConfig.onLog,onTrackError:e.onTrackError??T.globalConfig.onTrackError}}static setGlobalConfig(e){T.globalConfig={...T.globalConfig,...e}}static getGlobalConfig(){return{...T.globalConfig}}static setModuleLevel(e,t){T.globalConfig.onLog||(T.globalConfig.onLog=void 0),T._moduleOverrides||(T._moduleOverrides=new Map),T._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!T._moduleOverrides))return T._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=T.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return Mo[e]<=Mo[t]}formatMessage(e){if(this.config.format==="json"){const i={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(i.module=e.prefix),e.context&&(i.context=e.context),e.error&&(i.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(i)}const t=new Date(e.timestamp).toISOString().substring(11,23),s=e.prefix?`[${e.prefix}]`:"",o=this.getLevelIcon(e.level),n=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${o} ${s} ${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,s,o){if(!this.shouldLog(e))return;const n={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:s,error:o};if(this.config.onLog){this.config.onLog(n);return}const i=this.formatMessage(n);if(typeof console<"u")switch(e){case"error":o?console.error(i,o):console.error(i);break;case"warn":console.warn(i);break;case"debug":console.debug?console.debug(i):console.log(i);break;default:console.log(i)}}error(e,t,s){const o=t instanceof Error?t:void 0,n=t instanceof Error?s:t;this.log("error",e,n,o)}trackError(e,t,s){if(this.error(e,t,s?.context),this.config.onTrackError){const o={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:s?.context,error:t,errorType:s?.errorType,errorGroup:s?.errorGroup};this.config.onTrackError(o)}}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 T(t)}configure(e){Object.assign(this.config,e)}};const Te=new vf;class bf{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}enabled;cache;cacheDependencies;hitCount=0;missCount=0;log=Te.child({prefix:"CacheController"});get(e,t){if(!this.enabled)return;const s=this.getCacheName(e,t);return this.cache.has(s)?this.hitCount++:this.missCount++,this.cache.get(s)}set(e,t,s,o){if(!this.enabled)return;const n=this.getCacheName(e,t);this.cache.set(n,s),o?this.cacheDependencies.set(n,o):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[s,o]of this.cacheDependencies){let n=!1;for(const[i,a]of e){if(o.models.has(i))if(o.modelAttributes.has(i)){const l=o.modelAttributes.get(i);for(const u of a)if(l.has(u)){n=!0;break}}else n=!0;if(n)break}n&&t.push(s)}for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateByModels(e){if(!this.enabled)return;const t=new Set(e),s=[];for(const[o,n]of this.cacheDependencies)for(const i of t)if(n.models.has(i)){s.push(o);break}for(const o of s)this.cache.delete(o),this.cacheDependencies.delete(o)}invalidateByKeyPrefix(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())s.startsWith(e+"_")&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateForModel(e){this.invalidateByModels([e])}invalidateForAttribute(e,t){if(!this.enabled)return;const s=new Map;s.set(e,new Set([t])),this.invalidateByDependencies(s)}invalidateMatching(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())e(s)&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}generateContext(e){try{return oe(e)}catch(t){return this.log.error("Error in cache generateContext",t),e}}getCacheName(e,t){const s=wr(t);return e+"_"+s}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 $r=(r,e="")=>{if(!(typeof r!="string"||!r.startsWith("/")||!r.endsWith("/")))return{pattern:r.slice(1,-1),flags:e}};function W(r=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let s=0;s<r;s++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}class Cr{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=ce.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 Ro=(r,e)=>e?typeof structuredClone<"u"?structuredClone(r):oe(r):r,Io=(r,e,t,s,o,n)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=Ro(n,i);if(t.scope==="list"&&(t.listKey=r.cdRef?.key||r.key,t.modelKey=r.model?.key||r.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const l=ce.now(),u=l-s,c=Math.round(u*1e3)/1e3;t.duration=c,t.start=s,t.end=l;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:o}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:o,detail:d}),a}catch{return n}},b=r=>(e,t,s)=>{const o=s.value;return s.value=function(...n){const i=ce.now(),a=this.cdRef,l=Ro(r,!0);l.key||(a.increaseCounter(),l.key=a.getCounter());const u=W();a.analyticsController.mark({name:`${l.type}:start`,context:u});const c=this.model?.key;!l.originCdRefKey&&a.key&&(l.originCdRefKey=a.key),c&&(l.modelKey=c);const d=o.apply(this,n);return l.method=t,l.args=n,d&&typeof d=="object"&&"then"in d?d.then(f=>Io(this,a,l,i,u,f)):Io(this,a,l,i,u,d)},s};function kf(r,e,t,s){t.max||(t.max=20);const o=[],n=t.transform?s.transformValue(t.value,t.transform):t.value;for(const[i,a]of e.entries()){const l=Array.from(a).some(c=>r.has(c)),u=t.transform?s.transformValue(i,t.transform):i;if(!(t.excludeUndefineds&&typeof i>"u")&&!(t.excludeNulls&&i===null)){if(l&&(n===""||n==="//")){const c={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(c)}else if(l&&$r(n)){if(s.queryFind(u,n,"some",t.regexFlags)){const c={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(c)}}else if(l&&typeof n=="string"){const c=String(u??""),d=n;if(c.toLowerCase().startsWith(d.toLowerCase())){const f={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(f)}}else if(l&&s.queryFind(u,n,"some")){const c={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(c)}if(o.length===t.max)break}}return o}function wf(r){return r instanceof Date}function To(r){return r instanceof Date&&!isNaN(r.getTime())}const Af={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 $f(r){let e="^";const t=[];let s=r;const o=Object.entries(Af).sort((n,i)=>i[0].length-n[0].length);for(;s.length>0;){let n=!1;for(const[i,a]of o)if(s.startsWith(i)){e+=a.regex,t.push({type:a.type,pattern:i}),s=s.slice(i.length),n=!0;break}if(!n){const i=s[0];if(!i)break;e+=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=s.slice(1)}}return e+="$",{regex:new RegExp(e),tokenOrder:t}}function Cf(r,e){const t={year:1970,month:1,day:1,hour:0,minute:0,second:0,millisecond:0};for(let s=0;s<e.length;s++){const o=r[s+1];if(!o)continue;const n=parseInt(o,10),i=e[s];i&&(i.type==="year"&&i.pattern==="yy"?t.year=2e3+n:t[i.type]=n)}return t}function Df(r){if(r.month<1||r.month>12)return new Date(NaN);if(r.day<1||r.day>31)return new Date(NaN);if(r.hour<0||r.hour>23)return new Date(NaN);if(r.minute<0||r.minute>59)return new Date(NaN);if(r.second<0||r.second>59)return new Date(NaN);if(r.millisecond<0||r.millisecond>999)return new Date(NaN);const e=new Date(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return To(e)?e.getFullYear()!==r.year||e.getMonth()!==r.month-1||e.getDate()!==r.day?new Date(NaN):e:new Date(NaN)}function _f(r,e,t){if(r=r.trim(),e==="t"){const a=Number(r);return isNaN(a)?new Date(NaN):new Date(a*1e3)}if(e==="T"){const a=Number(r);return isNaN(a)?new Date(NaN):new Date(a)}const{regex:s,tokenOrder:o}=$f(e),n=r.match(s);if(!n)return new Date(NaN);const i=Cf(n,o);return Df(i)}class Pf{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 s=this.accessOrder.shift();s!==void 0&&this.cache.delete(s)}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 xf{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,s=new Set,o=n=>{t.add(n),s.add(n);const i=this.graph.get(n);if(i){for(const a of i)if(t.has(a)){if(s.has(a))return!0}else if(o(a))return!0}return s.delete(n),!1};for(let n=0;n<e.length-1;n++){const i=e[n],a=e[n+1];i&&a&&this.addDependency(i,a)}for(const n of e)if(!t.has(n)&&o(n))return!0;return!1}clear(){this.graph.clear()}}class Ef{parseCache;circularRefDetector;cacheHits=0;cacheMisses=0;constructor(e=1e3){this.parseCache=new Pf(e),this.circularRefDetector=new xf}parse(e){if(this.parseCache.has(e))return this.cacheHits++,this.parseCache.get(e);this.cacheMisses++;let t,s;const o=e.includes("."),n=e.includes("["),i=o||n;if(i){s=e.split(/[.[]/)[0];const l=e.indexOf("."),u=e.indexOf("[");if(n&&(l===-1||u<l)){const c=e.indexOf("]");if(c>-1){const d=e.indexOf(".",c+1);d>-1?t=e.substring(d+1):t=void 0}else o&&(t=e.substring(l+1))}else o&&(t=e.substring(l+1))}const a={attribute:e,isDeepQuery:i};return s&&(a.reference=s),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 s=[];if(!e||e.trim().length===0)return s.push("Attribute path cannot be empty"),{valid:!1,errors:s};(e.startsWith(".")||e.endsWith("."))&&s.push(`Invalid path: Leading or trailing dots are not allowed: ${e}`),e.includes("..")&&s.push(`Invalid path: Consecutive dots are not allowed: ${e}`);const o=(e.match(/\[/g)||[]).length,n=(e.match(/]/g)||[]).length;o!==n&&s.push(`Invalid bracket notation: Mismatched brackets in ${e}`),e.includes("[]")&&s.push(`Invalid bracket notation: Empty brackets not allowed: ${e}`);const i=/\[([^\]]+)\]/g;let a;for(;(a=i.exec(e))!==null;){const c=a[1];c&&c!=="*"&&!/^\d+$/.test(c)&&s.push(`Invalid bracket content: Must be a number or '*', got '${c}' in ${e}`)}const l=(e.match(/\./g)||[]).length+1;l>t&&s.push(`Path too deep: Maximum depth is ${t}, got ${l} in ${e}`);const u=e.match(/[^a-zA-Z0-9._[\]*-]/g);return u&&s.push(`Invalid characters in path: ${u.join(", ")} in ${e}`),{valid:s.length===0,errors:s.length>0?s: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,s=t>0?this.cacheHits/t:0;return{...e,hits:this.cacheHits,misses:this.cacheMisses,hitRate:s}}getPathSegments(e){return e.replace(/\[[^\]]+\]/g,"").split(".").filter(t=>t.length>0)}getPathDepth(e){return this.getPathSegments(e).length}}const P=new Ef;function de(r,e){if(e.includes("[*]")){const n=e.indexOf("[*]"),i=e.substring(0,n),a=e.substring(n+3),l=i?ot(r,i):r;if(!Array.isArray(l))return[];const u=[];for(const c of l)!a||a===""?c!==void 0&&u.push(c):a.startsWith(".")&&u.push(...de(c,a.slice(1)));return u}const t=e.split(".");let s=[r];for(const n of t){const i=[];for(const a of s)if(a!=null)if(Array.isArray(a))for(const l of a){if(l==null)continue;const u=l[n];u!==void 0&&i.push(u)}else{const l=a[n];l!==void 0&&i.push(l)}if(s=i,s.length===0)return[]}const o=[];for(const n of s)if(Array.isArray(n))for(const i of n)i!==void 0&&o.push(i);else n!==void 0&&o.push(n);return o}function Dr(r){let e=0;for(let t of r){const s=t.toString().split(".")[1];s&&(e=Math.max(e,s.length))}return Math.pow(10,e)}function Oo(r,e,t){return(r*t+e*t)/t}function jf(r,e,t){return r*t/(e*t)}const at=(r,e,t,s)=>{if(!s)throw new Error("Attribute not found");const o={attribute:s,types:r.types};let n;(o.types.includes("sum")||o.types.includes("avg"))&&(n=If(s,e));let i;return(o.types.includes("min")||o.types.includes("max"))&&(i=Mf(s,e)),r.types.forEach(a=>{a==="sum"?o.sum=n?.sum:a==="avg"?o.avg=n?.average:a==="count"?o.count=Sf(s,e):a==="min"?o.min=i&&i[0]:a==="max"?o.max=i&&i[1]:a==="distinct"?o.distinct=Tf(r,e,t):a==="group"&&(o.group=Rf(r,e))}),o},Sf=(r,e)=>{const t=P.parse(r).isDeepQuery;let s=0;for(const o of e.values())if(o)if(t)s+=de(o,r).filter(n=>n!=null).length;else{const n=o[r];if(n==null)continue;Array.isArray(n)?s+=n.filter(i=>i!=null).length:s++}return s},Mf=(r,e)=>{let t,s;const o=P.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=de(n,r);else{const a=n[r];a===void 0?i=[]:Array.isArray(a)?i=a.filter(l=>l!==void 0):i=[a]}for(const a of i)a==null||typeof a=="object"||((t===void 0||a<t)&&(t=a),(s===void 0||a>s)&&(s=a))}if(!(t===void 0||s===void 0))return[t,s]},Rf=(r,e)=>{const t=[];r.groupOptions?.groups?.forEach(n=>{t.push({option:n,count:0,keys:[]})});const s={option:{value:["$dcupl_not_found"]},count:0,keys:[]},o=P.parse(r.attribute).isDeepQuery;for(const n of e.values()){let i;o?i=de(n,r.attribute):i=[n[r.attribute]];let a=!1;for(const l of i)for(const u of t)(typeof u.option.value<"u"&&u.option.value.includes(l)||typeof u.option.from<"u"&&u.option.from<l&&typeof u.option.to<"u"&&u.option.to>l)&&(u.keys.includes(n.key)||(u.count++,u.keys.push(n.key)),a=!0);!a&&r?.groupOptions?.calculateNotFound&&(s.count++,s.keys.push(n.key))}return r?.groupOptions?.calculateNotFound&&t.push(s),t},If=(r,e)=>{let t=0,s=0;const o=P.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=de(n,r);else{const a=n[r];a===void 0?i=[]:Array.isArray(a)?i=a:i=[a]}for(const a of i)if(Array.isArray(a))for(const l of a)typeof l=="number"&&(t=Oo(t,l,Dr([t,l])),s++);else typeof a=="number"&&(t=Oo(t,a,Dr([t,a])),s++)}return s===0?void 0:{average:jf(t,s,Dr([t,s])),count:s,sum:t}},Tf=(r,e,t)=>{const s=[];for(const[o,n]of t)if(!(r.excludeUndefineds&&typeof o>"u")&&Array.from(n).find(i=>e.has(i))){const i={value:o,count:n.size};if(r.distinctOptions?.skipKeys||(i.keys=Array.from(n)),s.push(i),r.distinctOptions?.limit&&s.length>=r.distinctOptions.limit)break}return s};let Oe=class extends Error{query;constructor(e,t){const s=`Query Error: ${e} in ${JSON.stringify(t,null,2)}`;super(s),this.query=t,this.name="DcuplQueryError"}},ke=class{_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=oe(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||P}init(e){this._initOptions=oe(e),this.currentQuery=oe(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=oe(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 oe(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(s=>this.isQuery(s)&&s.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:wo(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,s){if(s||(s=this.currentQuery),Array.isArray(e))for(const o of e)this.applyQuery(o,t,s);else if(this.isRootQueryGroup(e))e.groupType&&(s.groupType=e.groupType),t?.mode==="set"?s.queries=e.queries:s.queries=[...s.queries,...e.queries],this.applyOptions(e,"set");else if(this.isQuery(e)){const o=s.queries.findIndex(n=>this.isQueryGroup(n)&&n.groupKey===e.attribute);if(o>-1){const n=s.queries[o];t?.mode==="set"?n.queries=[e]:n.queries.push(e)}else s.queries.push({groupKey:e.attribute,groupType:"or",queries:[e]})}else if(this.isQueryGroup(e)){const o=e.groupKey===void 0&&t?.mode!=="set"?-1:s.queries.findIndex(n=>this.isQueryGroup(n)&&n.groupKey===e.groupKey);if(o>-1){const n=s.queries[o];e.groupType&&(n.groupType=e.groupType),t?.mode==="set"?s.queries[o]=e:n.queries=[...n.queries,...e.queries]}else s.queries.push({groupKey:e.groupKey,groupType:e.groupType||"or",queries:e.queries})}return s}removeAllQueries(){return this.currentQuery.queries=[],this.getQuery()}removeQuery(e,t){if(t||(t=this.currentQuery),this.isQuery(e)){const s=t.queries.findIndex(o=>this.isQueryGroup(o)&&o.groupKey===e.attribute);if(s>-1){const o=t.queries[s],n=mr(o.queries,e);n>-1&&o.queries.splice(n,1),o.queries.length===0&&t.queries.splice(s,1)}}else if(this.isQueryGroup(e)){const s=t.queries.findIndex(o=>this.isQueryGroup(o)&&o.groupKey===e.groupKey);if(s>-1)if(!e.queries)t.queries.splice(s,1);else{const o=t.queries[s];for(const n of e.queries){const i=mr(o.queries,n);i>-1&&o.queries.splice(i,1)}o.queries.length===0&&t.queries.splice(s,1)}}return t}validateQuery(e){const t=[];if(this.isQuery(e))return e.attribute||t.push(new Oe("Missing attribute",e)),e.operator||t.push(new Oe("Missing operator",e)),typeof e.value>"u"&&t.push(new Oe("Missing value",e)),e.operator==="find"&&Array.isArray(e.value)&&t.push(new Oe("find operator cannot have array value",e)),e.operator==="in"&&typeof e.value<"u"&&!Array.isArray(e.value)&&t.push(new Oe("in operator needs an array value",e)),t.length>0?{valid:!1,errors:t}:{valid:!0};if(this.isQueryGroup(e)){const s=e.queries.map(o=>this.validateQuery(o)).filter(o=>!o.valid).map(o=>o.errors).flat();return s.length>0?{valid:!1,errors:s}:{valid:!0}}return t.push(new Oe("Invalid query definition",e)),{valid:!1,errors:t}}getQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)this.isQuery(i)?i.attribute&&!s.has(i.attribute)&&(t.push(i.attribute),s.add(i.attribute)):this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)if(this.isQuery(i)){if(i.attribute&&!s.has(i.attribute)){const a=this.getQueryAttributeForString(i.attribute);t.push(a),s.add(i.attribute)}}else this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}getQueryAttributeForString(e){return this.deepQueryService.parse(e)}getDeepQueryService(){return this.deepQueryService}getProjectionForAttributes(e){const t={};return e.forEach(s=>{t[s]=!0}),t}getProjectionForAttributeEntries(e){const t={$:!0};return e.forEach(s=>{if(s.isDeepQuery){if(s.reference)if(s.referenceAttribute&&s.referenceAttribute.length>0){t[s.reference]||(t[s.reference]={$:!0});const o=this.deepQueryService.parse(s.referenceAttribute);if(o.isDeepQuery&&s.reference){const n=this.getProjectionForAttributeEntries([o]);Object.keys(n).forEach(i=>{i!=="$"&&s.reference&&(t[s.reference][i]=n[i])})}else s.reference&&(t[s.reference][s.referenceAttribute]=!0)}else t[s.reference]=!0}else t[s.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=s=>{for(const o of s)if(this.isQuery(o)){let n=!0;for(const i in e)if(o[i]!==e[i]){n=!1;break}if(n)return!0}else if(this.isQueryGroup(o)&&t(o.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(e=>e.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 s=0;for(const o of t)this.isQuery(o)?s++:this.isQueryGroup(o)&&(s+=e(o.queries));return s};return e(this.currentQuery.queries)}};const _r=new ke;function Of(r,e,t,s,o,n,i){const a=t.excludeGroup??o,l=_r.removeQuery({groupKey:a},oe(s)),u=i.queryData(r,l,!1,n),c=e?[...e.keys()]:[],d=new Set(c),f=n.get(o)??new Map;if(!t.excludeUnresolved)for(const p of f.keys())d.add(p);if(t.excludeUndefineds?d.delete(void 0):d.add(void 0),t.sort){const p=[];for(const v of d.values())p.push(Ko(v,f,u,e,o,a,s,!0));const y=t.excludeZeros?p.filter(v=>v.size>0):p;return y.sort(Kf(t.sort)),t.count?y.slice(0,t.count):y}const h=[];for(const p of d.values()){const y=Ko(p,f,u,e,o,a,s,!!t?.calculateFacets);if(!(t?.excludeZeros&&y.size===0)){if(t?.count&&h.length===t?.count)return h;h.push(y)}}return h}function Ko(r,e,t,s,o,n,i,a){const l=new Map,u=e.get(r)||new Set;for(const c of u){const d=t.get(c);if(d&&(l.set(c,d),!a))break}return{key:String(r),value:r,selected:Ff(n,o,r,i),enabled:l.size>0,size:l.size,entry:s?.get(r),resultKeys:Array.from(l.keys())}}function St(r,e){if(r===void 0&&e===void 0)return 0;if(r===void 0)return 1;if(e===void 0)return-1;const t=typeof r,s=typeof e;if(t!==s)return t<s?-1:1;if(t==="number")return r-e;if(t==="string")return r.localeCompare(e);const o=String(r),n=String(e);return o<n?-1:o>n?1:0}function Kf(r){switch(r){case"size-desc":return(e,t)=>t.size-e.size||St(e.value,t.value);case"size-asc":return(e,t)=>e.size-t.size||St(e.value,t.value);case"value-asc":return(e,t)=>St(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:-St(e.value,t.value)}}const Ff=(r,e,t,s)=>{const o=s.queries.findIndex(n=>_r.isQueryGroup(n)&&n.groupKey===r);return o>-1?!!s.queries[o].queries.find(n=>_r.isQuery(n)?n.attribute!==e?!1:(n.operator==="in"&&Array.isArray(n.value)?n.value:[n.value]).some(i=>(i?.key||i)===t):!1):!1};class Mt{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 s=this.dataMap.get(e);s||(s=new Map,this.dataMap.set(e,s));for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const a of o)this.fillDataMap(e,[a]);return}else o instanceof Date?n=o.toISOString():n=o;let i=s.get(n);i||(i={key:n},this.dataMap.get(e)?.set(n,i))}}fillInverseIndex(e,t,s){if(!e||!t||!s||!Array.isArray(s))return;const o=this.indexMap.get(e)||new Map;for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const l of n)this.fillInverseIndex(e,t,[l]);return}else n instanceof Date?i=n.toISOString():i=n;let a=o.get(i);a||(a=new Set,o.set(i,a)),a.add(t)}this.indexMap.set(e,o)}getIndex(e,t){const s=this.getIndexName(e,t);return this.indexMap.get(s)}getData(e,t){const s=this.getIndexName(e,t);return this.dataMap.get(s)}getOrCreateIndex(e,t,s){const o=this.getIndexName(e,s);let n=this.getIndex(o);const i=this.indexMetadata.get(o);if(i)i.lastAccessedAt=Date.now();else if(!n){const a=P.parse(e).isDeepQuery??!1;this.indexMetadata.set(o,{createdAt:Date.now(),lastAccessedAt:Date.now(),context:s,type:a?"deep":"shallow"})}if(!n){this.reset(o),this.indexMap.set(o,new Map);const a=P.parse(e).isDeepQuery;for(const l of t.values()){let u;a?(u=de(l,e),u.length===0&&(u=[void 0])):u=[l[e]],this.fillInverseIndex(o,l.key,u),this.fillDataMap(o,u)}n=this.getIndex(o)||new Map}return n}getIndexName(e,t){return t?e+"_"+wr(t):e}removeFromInverseIndex(e,t,s){const o=this.indexMap.get(e);if(o)for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const l of n)this.removeFromInverseIndex(e,t,[l]);return}else n instanceof Date?i=n.toISOString():i=n;const a=o.get(i);a&&(a.delete(t),a.size===0&&o.delete(i))}}updateInverseIndex(e,t,s,o){this.removeFromInverseIndex(e,t,s),this.fillInverseIndex(e,t,o)}removeFromDataMap(e,t){const s=this.dataMap.get(e);if(s)for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const i of o)this.removeFromDataMap(e,[i]);return}else o instanceof Date?n=o.toISOString():n=o;s.delete(n)}}updateDataMap(e,t,s){this.removeFromDataMap(e,t),this.fillDataMap(e,s)}removeItemFromAllIndices(e){for(const t of this.indexMap.values())for(const[s,o]of t)o.delete(e)&&o.size===0&&t.delete(s);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 P.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 s of this.indexMap.keys())this.isDeepQueryIndex(s)?t++:e++;return{shallow:e,deep:t,total:e+t}}cleanupStaleIndices(e=300*1e3){const t=Date.now();let s=0;for(const[o,n]of this.indexMetadata)t-n.lastAccessedAt>e&&(this.reset(o),s++);return s}getStats(){const e=this.getIndexCount(),t=Date.now();let s=0,o=0;for(const i of this.indexMetadata.values()){const a=t-i.createdAt;s+=a,a>o&&(o=a)}const n=this.indexMetadata.size>0?s/this.indexMetadata.size:0;return{shallow:e.shallow,deep:e.deep,total:e.total,oldestAge:o,avgAge:n}}}const Ke="__";function Pr(r,e,t={key:"root"},s="root",o=new Mt,n){const i=n||r;for(const a of e.columns)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.rows)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.values)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));if(e.rows&&e.rows.length>0){t.rows=t.rows||[];const a=qf(r,e.rows[0],e,o,s,n);t.rows.push(a)}if(e.columns&&e.columns.length>0){t.columns=t.columns||[];const a=Fo(r,e.columns[0],e,o,s,n);t.columns.push(a)}if(t.key==="root")for(const a of e.values){if(t.values=t.values||[],s==="root"&&e.options?.calculateTotals===!1)continue;const l=at(a,r,o.getIndex(a.attribute),a.attribute);t.values.push(l)}return t}function qf(r,e,t,s,o="",n){const i={key:e.attribute},a=s.getIndex(e.attribute);if(!a)return i;for(const[l,u]of a.entries()){const c={key:l,value:l},d=new Map;for(const f of u)r.has(f)&&d.set(f,r.get(f));if(d.size){for(const f of t.values){if(c.values=c.values||[],o==="root"&&e?.calculateTotals===!1)continue;const h=at(f,d,s.getIndex(f.attribute),f.attribute);c.values.push(h)}if(i.rows=i.rows||[],i.rows.push(c),t.rows.length>1){const f={...t,rows:t.rows.slice(1)};Pr(d,f,c,o+Ke+e.attribute+Ke+l,s,n)}else if(t.columns)for(const f of t.columns){c.columns=c.columns||[];const h=Fo(d,f,t,s,o+Ke+e.attribute+Ke+l,n);c.columns.push(h)}}}return i}function Fo(r,e,t,s,o="",n){const i={key:e.attribute},a=s.getIndex(e.attribute);if(!a)return i;for(const[l,u]of a.entries()){const c={key:l,value:l},d=new Map;for(const f of u)r.has(f)&&d.set(f,r.get(f));if(d.size){for(const f of t.values){if(c.values=c.values||[],o==="root"&&e?.calculateTotals===!1)continue;const h=at(f,d,s.getIndex(f.attribute),f.attribute);c.values.push(h)}if(i.columns=i.columns||[],i.columns.push(c),t.columns.length>1){const f={...t,columns:t.columns.slice(1)};Pr(d,f,c,o+Ke+e.attribute+Ke+l,s,n)}}}return i}const Qf=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/,Vf=/^-?\d+$/,Gf=/^-?\d+\.\d+$/,Bf=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,Uf=r=>r==="true"||r==="false"?"boolean":Vf.test(r)?"int":Gf.test(r)?"float":Qf.test(r)&&!Number.isNaN(Date.parse(r))?"date":"string",Nf=r=>Bf.test(r),zf=r=>r==null||r==="",Lf=r=>{const e=[...r];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}},Wf=(r,e={})=>{const t=e.deep??(e.sampleSize!==void 0&&e.sampleSize>1)?e.sampleSize??1/0:1,s=e.coerceStrings??!0,o=new Map,n=[],i=Math.min(r.length,t);for(let u=0;u<i;u++){const c=r[u];if(c)for(const[d,f]of Object.entries(c)){let h=o.get(d);if(h||(h={observed:new Set,empty:0,scanned:0},o.set(d,h),n.push(d)),h.scanned++,zf(f)){h.empty++;continue}let p;typeof f=="string"&&s?(p=Uf(f),p==="string"&&!h.hint&&Nf(f)&&(h.hint="column looks date-like (non-ISO) — review manually")):p=Hf(f),h.observed.add(p)}}const a=[],l=[];for(const u of n){const c=o.get(u),{type:d,conflict:f}=Lf(c.observed.size?c.observed:new Set(["string"]));a.push({key:u,type:d}),l.push({column:u,inferredType:d,observedTypes:[...c.observed].sort(),emptyRate:c.scanned===0?0:c.empty/c.scanned,conflict:f,hint:c.hint})}return{properties:a,diagnostics:l}},qo=(r,e=!1)=>Wf(r,typeof e=="boolean"?{deep:e}:e).properties,Qo=r=>Number(r)===r&&r%1===0,Vo=r=>Number(r)===r&&r%1!==0,Hf=r=>{switch(typeof r){case"string":return"string";case"number":return Qo(r)?"int":Vo(r)?"float":"any";case"boolean":return"boolean";case"object":return wf(r)?"date":"json";default:return"any"}};class Jf{constructor(e,t,s){this.scriptController=e,this.globalItemService=t,this.modelParser=s}scriptController;globalItemService;modelParser;registeredCustomOperator=new Map;queryBuilder=new ke;registerCustomOperator(e,t){this.registeredCustomOperator.set(e,t)}transformValue(e,t){if(Array.isArray(e))return e.map(s=>this.transformValue(s,t));if(typeof e!="string")return e;for(const s of t)s==="lowercase"?e=e.toLowerCase():s==="trim"?e=e.trim():s==="removeWhitespace"&&(e=e.replace(/\s/g,""));return e}evaluateQuery(e,t){let s=e.value;const o=e.options?.arrayValueHandling||"some";Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(s=this.transformValue(s,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 i;switch(e.operator){case"eq":i=this.queryEq(n,s,o);break;case"in":i=this.queryIn(n,s,o);break;case"find":i=this.queryFind(n,s,o,e.options?.regexFlags);break;case"lt":case"gt":case"lte":case"gte":{const a=e.operator;i=this.matchValues(n,o,l=>this.compareValue(a,l,s));break}case"typeof":i=this.matchValues(n,o,a=>typeof a===s);break;case"isTruthy":{const a=s===!0;i=this.matchValues(n,o,l=>!!l===a);break}case"size":typeof n=="string"?i=n.length===s:i=hf(n)===s;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?!i:i}compareValue(e,t,s){if(t==null)return!1;switch(e){case"lt":return t<s;case"gt":return t>s;case"lte":return t<=s;case"gte":return t>=s}}getAttributeValue(e,t){if(t in e||!(t.includes(".")||t.includes("[")))return e[t];if(t.includes("["))return ot(e,t);const s=t.split(".");let o=e;for(let n=0;n<s.length;n++){const i=s[n];if(o==null)return;if(Array.isArray(o)&&i!=="length"&&!/^\d+$/.test(i))return de(o,s.slice(n).join("."));o=o[i]}return o}matchValues(e,t,s){return Array.isArray(e)?t==="every"?e.length>0&&e.every(s):e.some(s):s(e)}queryEq(e,t,s){return Array.isArray(e)&&!Array.isArray(t)?this.matchValues(e,s,o=>this.equalsQueryValue(o,t)):this.equalsQueryValue(e,t)}queryIn(e,t,s){return!Array.isArray(t)||t.length===0?!1:this.matchValues(e,s,o=>t.some(n=>this.equalsQueryValue(o,n)))}getIndexKey(e){if(typeof e=="string")return e;if(e?.key&&Object.keys(e).length===1)return e.key}equalsQueryValue(e,t){const s=this.getIndexKey(t);return typeof s>"u"?zd(e,t):e instanceof Date?!isNaN(e.getTime())&&e.toISOString()===s:typeof e=="object"&&e?.key?e.key===s:e===s}canUseIndex(e){return e.options?.arrayValueHandling!=="every"&&!e.options?.transform?.length}evaluateEqOperator(e,t,s,o){const n=new Map,i=this.canUseIndex(t)?o.get(t.attribute):void 0;if(i){const a=this.getIndexKey(t.value);if(typeof a<"u"){const l=i.get(a);if(l)if(l.forEach(u=>{s.has(u)&&n.set(u,s.get(u))}),t.options?.invert){const u=ko(Array.from(s.values()),Array.from(n.values()),"key"),c=new Map;return u.forEach(d=>{c.set(d.key,d)}),c}else return n}}return this.scanDataset(e,t,s)}evaluateInOperator(e,t,s,o){const n=this.canUseIndex(t)?o.get(t.attribute):void 0;if(!n)return this.scanDataset(e,t,s);const i=new Map,a=[];for(const u of t.value){const c=this.getIndexKey(u),d=typeof c<"u"?n.get(c):void 0;if(!d){a.push(u);continue}d.forEach(f=>{const h=s.get(f);h&&i.set(f,h)})}if(a.length>0){const u=new Map;s.forEach((d,f)=>{i.has(f)||u.set(f,d)});const c={...t,value:a,options:{...t.options,invert:!1}};this.scanDataset(e,c,u).forEach((d,f)=>i.set(f,d))}if(!t.options?.invert)return i;const l=new Map;return s.forEach((u,c)=>{i.has(c)||l.set(c,u)}),l}scanDataset(e,t,s){const o=new Map,n=this.queryBuilder.extractQueryAttributes({queries:[t]}).filter(a=>a.isDeepQuery),i=n.length>0?this.queryBuilder.getProjectionForAttributeEntries(n):void 0;for(let[a,l]of s)i&&(l=this.globalItemService.getProjectedData(i,this.modelParser.models.get(e.modelKey),l)),this.evaluateQuery(t,l)&&o.set(a,l);return o}equalRegexFn(e,t,s){const o=$r(t,s);if(o)try{return new RegExp(o.pattern,o.flags).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(n=>vr(n,t,(i,a)=>this.equalRegexFn(i,a,s))):typeof t=="object"?Ao(e,t):e===t}queryFind(e,t,s,o){const n=(i,a)=>this.equalRegexFn(i,a,o);return Array.isArray(e)?typeof t=="string"||typeof t=="number"||typeof t=="boolean"?this.matchValues(e,s,i=>vr(i,t,n)):t!==null&&typeof t=="object"?this.matchValues(e,s,i=>Ao(i,t)):!!Bd(e,t):vr(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 wo(e.queries,t=>this.validateQuery(t));throw new Error("invalid query - missing query or attribute")}}getEvaluatedQueryDataset(e,t,s,o){const n=new Map;if(t.attribute.includes("[*]")){const i=t.options?.invert===!0,a=new Set;for(let l of s.values()){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(d=>d.isDeepQuery)){const d=this.queryBuilder.getProjectionForAttributeEntries(u.filter(f=>f.isDeepQuery));l=this.globalItemService.getProjectedData(d,this.modelParser.models.get(e.modelKey),l)}const c=this.handleArrayStarQuery(t,l).queries.map(d=>({...d,options:{...d.options,invert:!1}}));this.matchValues(c,t.options?.arrayValueHandling||"some",d=>this.evaluateQuery(d,l))&&(a.add(l.key),i||n.set(l.key,l))}if(i)for(const[l,u]of s)a.has(l)||n.set(l,u)}else return t.operator==="eq"?this.evaluateEqOperator(e,t,s,o):t.operator==="in"?this.evaluateInOperator(e,t,s,o):this.scanDataset(e,t,s);return n}handleArrayStarQuery(e,t){const s=e.attribute.indexOf("[*]"),o={groupKey:e.queryKey||e.attribute+"[*]",groupType:"or",queries:[]};if(s!==-1){const n=e.attribute.substring(0,s),i=n.includes(".")?ot(t,n):t[n];if(Array.isArray(i))for(let a=0;a<i.length;a++){const l=e.attribute.replace("[*]",`[${a}]`);o.queries.push({attribute:l,operator:e.operator,value:e.value,options:e.options})}}return o}evaluateQueryGroup(e,t,s,o,n){let i=new Map,a=s;if(!t.queries||t.queries?.length===0)return a;for(const l of t.queries){let u=new Map;if(this.queryBuilder.isQuery(l)?u=this.getEvaluatedQueryDataset(e,l,a,n):u=this.evaluateQueryGroup(e,l,a,o,n),i.size===0&&(i=u),t.groupType==="or")u.forEach(c=>{i.set(c.key,c)});else{const c=ko(Array.from(i.values()),Array.from(u.values()),"key");for(const d of c)i.delete(d.key)}t.groupType==="and"?a=i:a=s}return i}queryData(e,t,s,o){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,s,o)}}function Z(){const r=globalThis;return typeof r.scheduler?.yield=="function"?r.scheduler.yield():typeof r.setImmediate=="function"?new Promise(e=>r.setImmediate(()=>e())):typeof r.MessageChannel=="function"?new Promise(e=>{const t=new r.MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)}):new Promise(e=>setTimeout(e,0))}class Zf{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 s=this.getScript(e);if(!s)throw new Error(`Script ${e} not found`);const o=this.getWrapperScript(s),n=new Function("script_type",...t,o);return this.scriptFunctions.set(e,n),n}getWrapperScript(e){return`
|
|
1
|
+
(function(){"use strict";var R=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},O={searchParams:"URLSearchParams"in R,iterable:"Symbol"in R&&"iterator"in Symbol,blob:"FileReader"in R&&"Blob"in R&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in R,arrayBuffer:"ArrayBuffer"in R};function Fi(r){return r&&DataView.prototype.isPrototypeOf(r)}if(O.arrayBuffer)var qi=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Qi=ArrayBuffer.isView||function(r){return r&&qi.indexOf(Object.prototype.toString.call(r))>-1};function Ee(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(r)||r==="")throw new TypeError('Invalid character in header field name: "'+r+'"');return r.toLowerCase()}function zt(r){return typeof r!="string"&&(r=String(r)),r}function Lt(r){var e={next:function(){var t=r.shift();return{done:t===void 0,value:t}}};return O.iterable&&(e[Symbol.iterator]=function(){return e}),e}function x(r){this.map={},r instanceof x?r.forEach(function(e,t){this.append(t,e)},this):Array.isArray(r)?r.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(e){this.append(e,r[e])},this)}x.prototype.append=function(r,e){r=Ee(r),e=zt(e);var t=this.map[r];this.map[r]=t?t+", "+e:e},x.prototype.delete=function(r){delete this.map[Ee(r)]},x.prototype.get=function(r){return r=Ee(r),this.has(r)?this.map[r]:null},x.prototype.has=function(r){return this.map.hasOwnProperty(Ee(r))},x.prototype.set=function(r,e){this.map[Ee(r)]=zt(e)},x.prototype.forEach=function(r,e){for(var t in this.map)this.map.hasOwnProperty(t)&&r.call(e,this.map[t],t,this)},x.prototype.keys=function(){var r=[];return this.forEach(function(e,t){r.push(t)}),Lt(r)},x.prototype.values=function(){var r=[];return this.forEach(function(e){r.push(e)}),Lt(r)},x.prototype.entries=function(){var r=[];return this.forEach(function(e,t){r.push([t,e])}),Lt(r)},O.iterable&&(x.prototype[Symbol.iterator]=x.prototype.entries);function Wt(r){if(!r._noBody){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}}function as(r){return new Promise(function(e,t){r.onload=function(){e(r.result)},r.onerror=function(){t(r.error)}})}function Vi(r){var e=new FileReader,t=as(e);return e.readAsArrayBuffer(r),t}function Gi(r){var e=new FileReader,t=as(e),s=/charset=([A-Za-z0-9_-]+)/.exec(r.type),o=s?s[1]:"utf-8";return e.readAsText(r,o),t}function Bi(r){for(var e=new Uint8Array(r),t=new Array(e.length),s=0;s<e.length;s++)t[s]=String.fromCharCode(e[s]);return t.join("")}function ls(r){if(r.slice)return r.slice(0);var e=new Uint8Array(r.byteLength);return e.set(new Uint8Array(r)),e.buffer}function us(){return this.bodyUsed=!1,this._initBody=function(r){this.bodyUsed=this.bodyUsed,this._bodyInit=r,r?typeof r=="string"?this._bodyText=r:O.blob&&Blob.prototype.isPrototypeOf(r)?this._bodyBlob=r:O.formData&&FormData.prototype.isPrototypeOf(r)?this._bodyFormData=r:O.searchParams&&URLSearchParams.prototype.isPrototypeOf(r)?this._bodyText=r.toString():O.arrayBuffer&&O.blob&&Fi(r)?(this._bodyArrayBuffer=ls(r.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):O.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(r)||Qi(r))?this._bodyArrayBuffer=ls(r):this._bodyText=r=Object.prototype.toString.call(r):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof r=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):O.searchParams&&URLSearchParams.prototype.isPrototypeOf(r)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},O.blob&&(this.blob=function(){var r=Wt(this);if(r)return r;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var r=Wt(this);return r||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(O.blob)return this.blob().then(Vi);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var r=Wt(this);if(r)return r;if(this._bodyBlob)return Gi(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(Bi(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},O.formData&&(this.formData=function(){return this.text().then(zi)}),this.json=function(){return this.text().then(JSON.parse)},this}var Ui=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function Ni(r){var e=r.toUpperCase();return Ui.indexOf(e)>-1?e:r}function ye(r,e){if(!(this instanceof ye))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{};var t=e.body;if(r instanceof ye){if(r.bodyUsed)throw new TypeError("Already read");this.url=r.url,this.credentials=r.credentials,e.headers||(this.headers=new x(r.headers)),this.method=r.method,this.mode=r.mode,this.signal=r.signal,!t&&r._bodyInit!=null&&(t=r._bodyInit,r.bodyUsed=!0)}else this.url=String(r);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new x(e.headers)),this.method=Ni(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||(function(){if("AbortController"in R){var n=new AbortController;return n.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&t)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(t),(this.method==="GET"||this.method==="HEAD")&&(e.cache==="no-store"||e.cache==="no-cache")){var s=/([?&])_=[^&]*/;if(s.test(this.url))this.url=this.url.replace(s,"$1_="+new Date().getTime());else{var o=/\?/;this.url+=(o.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}ye.prototype.clone=function(){return new ye(this,{body:this._bodyInit})};function zi(r){var e=new FormData;return r.trim().split("&").forEach(function(t){if(t){var s=t.split("="),o=s.shift().replace(/\+/g," "),n=s.join("=").replace(/\+/g," ");e.append(decodeURIComponent(o),decodeURIComponent(n))}}),e}function Li(r){var e=new x,t=r.replace(/\r?\n[\t ]+/g," ");return t.split("\r").map(function(s){return s.indexOf(`
|
|
2
|
+
`)===0?s.substr(1,s.length):s}).forEach(function(s){var o=s.split(":"),n=o.shift().trim();if(n){var i=o.join(":").trim();try{e.append(n,i)}catch(a){console.warn("Response "+a.message)}}}),e}us.call(ye.prototype);function H(r,e){if(!(this instanceof H))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new x(e.headers),this.url=e.url||"",this._initBody(r)}us.call(H.prototype),H.prototype.clone=function(){return new H(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new x(this.headers),url:this.url})},H.error=function(){var r=new H(null,{status:200,statusText:""});return r.ok=!1,r.status=0,r.type="error",r};var Wi=[301,302,303,307,308];H.redirect=function(r,e){if(Wi.indexOf(e)===-1)throw new RangeError("Invalid status code");return new H(null,{status:e,headers:{location:r}})};var ge=R.DOMException;try{new ge}catch{ge=function(e,t){this.message=e,this.name=t;var s=Error(e);this.stack=s.stack},ge.prototype=Object.create(Error.prototype),ge.prototype.constructor=ge}function cs(r,e){return new Promise(function(t,s){var o=new ye(r,e);if(o.signal&&o.signal.aborted)return s(new ge("Aborted","AbortError"));var n=new XMLHttpRequest;function i(){n.abort()}n.onload=function(){var u={statusText:n.statusText,headers:Li(n.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(n.status<200||n.status>599)?u.status=200:u.status=n.status,u.url="responseURL"in n?n.responseURL:u.headers.get("X-Request-URL");var c="response"in n?n.response:n.responseText;setTimeout(function(){t(new H(c,u))},0)},n.onerror=function(){setTimeout(function(){s(new TypeError("Network request failed"))},0)},n.ontimeout=function(){setTimeout(function(){s(new TypeError("Network request timed out"))},0)},n.onabort=function(){setTimeout(function(){s(new ge("Aborted","AbortError"))},0)};function a(u){try{return u===""&&R.location.href?R.location.href:u}catch{return u}}if(n.open(o.method,a(o.url),!0),o.credentials==="include"?n.withCredentials=!0:o.credentials==="omit"&&(n.withCredentials=!1),"responseType"in n&&(O.blob?n.responseType="blob":O.arrayBuffer&&(n.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof x||R.Headers&&e.headers instanceof R.Headers)){var l=[];Object.getOwnPropertyNames(e.headers).forEach(function(u){l.push(Ee(u)),n.setRequestHeader(u,zt(e.headers[u]))}),o.headers.forEach(function(u,c){l.indexOf(c)===-1&&n.setRequestHeader(c,u)})}else o.headers.forEach(function(u,c){n.setRequestHeader(c,u)});o.signal&&(o.signal.addEventListener("abort",i),n.onreadystatechange=function(){n.readyState===4&&o.signal.removeEventListener("abort",i)}),n.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}cs.polyfill=!0,R.fetch||(R.fetch=cs,R.Headers=x,R.Request=ye,R.Response=H);var ds=typeof global=="object"&&global&&global.Object===Object&&global,Hi=typeof self=="object"&&self&&self.Object===Object&&self,J=ds||Hi||Function("return this")(),B=J.Symbol,fs=Object.prototype,Ji=fs.hasOwnProperty,Zi=fs.toString,He=B?B.toStringTag:void 0;function Yi(r){var e=Ji.call(r,He),t=r[He];try{r[He]=void 0;var s=!0}catch{}var o=Zi.call(r);return s&&(e?r[He]=t:delete r[He]),o}var Xi=Object.prototype,ea=Xi.toString;function ta(r){return ea.call(r)}var ra="[object Null]",sa="[object Undefined]",ps=B?B.toStringTag:void 0;function ee(r){return r==null?r===void 0?sa:ra:ps&&ps in Object(r)?Yi(r):ta(r)}function K(r){return r!=null&&typeof r=="object"}var oa="[object Symbol]";function je(r){return typeof r=="symbol"||K(r)&&ee(r)==oa}function Me(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var E=Array.isArray,hs=B?B.prototype:void 0,ys=hs?hs.toString:void 0;function Ht(r){if(typeof r=="string")return r;if(E(r))return Me(r,Ht)+"";if(je(r))return ys?ys.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var na=/\s/;function ia(r){for(var e=r.length;e--&&na.test(r.charAt(e)););return e}var aa=/^\s+/;function la(r){return r&&r.slice(0,ia(r)+1).replace(aa,"")}function z(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var gs=NaN,ua=/^[-+]0x[0-9a-f]+$/i,ca=/^0b[01]+$/i,da=/^0o[0-7]+$/i,fa=parseInt;function pa(r){if(typeof r=="number")return r;if(je(r))return gs;if(z(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=z(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=la(r);var t=ca.test(r);return t||da.test(r)?fa(r.slice(2),t?2:8):ua.test(r)?gs:+r}var ms=1/0,ha=17976931348623157e292;function ya(r){if(!r)return r===0?r:0;if(r=pa(r),r===ms||r===-ms){var e=r<0?-1:1;return e*ha}return r===r?r:0}function Jt(r){var e=ya(r),t=e%1;return e===e?t?e-t:e:0}function kt(r){return r}var ga="[object AsyncFunction]",ma="[object Function]",va="[object GeneratorFunction]",ba="[object Proxy]";function Zt(r){if(!z(r))return!1;var e=ee(r);return e==ma||e==va||e==ga||e==ba}var Yt=J["__core-js_shared__"],vs=(function(){var r=/[^.]+$/.exec(Yt&&Yt.keys&&Yt.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function ka(r){return!!vs&&vs in r}var wa=Function.prototype,Aa=wa.toString;function me(r){if(r!=null){try{return Aa.call(r)}catch{}try{return r+""}catch{}}return""}var $a=/[\\^$.*+?()[\]{}|]/g,Ca=/^\[object .+?Constructor\]$/,Da=Function.prototype,_a=Object.prototype,Pa=Da.toString,xa=_a.hasOwnProperty,Ea=RegExp("^"+Pa.call(xa).replace($a,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ja(r){if(!z(r)||ka(r))return!1;var e=Zt(r)?Ea:Ca;return e.test(me(r))}function Ma(r,e){return r?.[e]}function ve(r,e){var t=Ma(r,e);return ja(t)?t:void 0}var Xt=ve(J,"WeakMap"),bs=Object.create,Sa=(function(){function r(){}return function(e){if(!z(e))return{};if(bs)return bs(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function Ra(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var Ia=800,Ta=16,Oa=Date.now;function Ka(r){var e=0,t=0;return function(){var s=Oa(),o=Ta-(s-t);if(t=s,o>0){if(++e>=Ia)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function Fa(r){return function(){return r}}var wt=(function(){try{var r=ve(Object,"defineProperty");return r({},"",{}),r}catch{}})(),qa=wt?function(r,e){return wt(r,"toString",{configurable:!0,enumerable:!1,value:Fa(e),writable:!0})}:kt,Qa=Ka(qa);function Va(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function ks(r,e,t,s){for(var o=r.length,n=t+-1;++n<o;)if(e(r[n],n,r))return n;return-1}function Ga(r){return r!==r}function Ba(r,e,t){for(var s=t-1,o=r.length;++s<o;)if(r[s]===e)return s;return-1}function ws(r,e,t){return e===e?Ba(r,e,t):ks(r,Ga,t)}function Ua(r,e){var t=r==null?0:r.length;return!!t&&ws(r,e,0)>-1}var Na=9007199254740991,za=/^(?:0|[1-9]\d*)$/;function er(r,e){var t=typeof r;return e=e??Na,!!e&&(t=="number"||t!="symbol"&&za.test(r))&&r>-1&&r%1==0&&r<e}function At(r,e,t){e=="__proto__"&&wt?wt(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function Je(r,e){return r===e||r!==r&&e!==e}var La=Object.prototype,Wa=La.hasOwnProperty;function As(r,e,t){var s=r[e];(!(Wa.call(r,e)&&Je(s,t))||t===void 0&&!(e in r))&&At(r,e,t)}var $s=Math.max;function Ha(r,e,t){return e=$s(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=$s(s.length-e,0),i=Array(n);++o<n;)i[o]=s[e+o];o=-1;for(var a=Array(e+1);++o<e;)a[o]=s[o];return a[e]=t(i),Ra(r,this,a)}}function tr(r,e){return Qa(Ha(r,e,kt),r+"")}var Ja=9007199254740991;function rr(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ja}function te(r){return r!=null&&rr(r.length)&&!Zt(r)}var Za=Object.prototype;function sr(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Za;return r===t}function Ya(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var Xa="[object Arguments]";function Cs(r){return K(r)&&ee(r)==Xa}var Ds=Object.prototype,el=Ds.hasOwnProperty,tl=Ds.propertyIsEnumerable,Ze=Cs((function(){return arguments})())?Cs:function(r){return K(r)&&el.call(r,"callee")&&!tl.call(r,"callee")};function rl(){return!1}var _s=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ps=_s&&typeof module=="object"&&module&&!module.nodeType&&module,sl=Ps&&Ps.exports===_s,xs=sl?J.Buffer:void 0,ol=xs?xs.isBuffer:void 0,Ye=ol||rl,nl="[object Arguments]",il="[object Array]",al="[object Boolean]",ll="[object Date]",ul="[object Error]",cl="[object Function]",dl="[object Map]",fl="[object Number]",pl="[object Object]",hl="[object RegExp]",yl="[object Set]",gl="[object String]",ml="[object WeakMap]",vl="[object ArrayBuffer]",bl="[object DataView]",kl="[object Float32Array]",wl="[object Float64Array]",Al="[object Int8Array]",$l="[object Int16Array]",Cl="[object Int32Array]",Dl="[object Uint8Array]",_l="[object Uint8ClampedArray]",Pl="[object Uint16Array]",xl="[object Uint32Array]",C={};C[kl]=C[wl]=C[Al]=C[$l]=C[Cl]=C[Dl]=C[_l]=C[Pl]=C[xl]=!0,C[nl]=C[il]=C[vl]=C[al]=C[bl]=C[ll]=C[ul]=C[cl]=C[dl]=C[fl]=C[pl]=C[hl]=C[yl]=C[gl]=C[ml]=!1;function El(r){return K(r)&&rr(r.length)&&!!C[ee(r)]}function Xe(r){return function(e){return r(e)}}var Es=typeof exports=="object"&&exports&&!exports.nodeType&&exports,et=Es&&typeof module=="object"&&module&&!module.nodeType&&module,jl=et&&et.exports===Es,or=jl&&ds.process,Se=(function(){try{var r=et&&et.require&&et.require("util").types;return r||or&&or.binding&&or.binding("util")}catch{}})(),js=Se&&Se.isTypedArray,nr=js?Xe(js):El,Ml=Object.prototype,Sl=Ml.hasOwnProperty;function Ms(r,e){var t=E(r),s=!t&&Ze(r),o=!t&&!s&&Ye(r),n=!t&&!s&&!o&&nr(r),i=t||s||o||n,a=i?Ya(r.length,String):[],l=a.length;for(var u in r)(e||Sl.call(r,u))&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||n&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||er(u,l)))&&a.push(u);return a}function Ss(r,e){return function(t){return r(e(t))}}var Rl=Ss(Object.keys,Object),Il=Object.prototype,Tl=Il.hasOwnProperty;function Rs(r){if(!sr(r))return Rl(r);var e=[];for(var t in Object(r))Tl.call(r,t)&&t!="constructor"&&e.push(t);return e}function tt(r){return te(r)?Ms(r):Rs(r)}var Ol=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Kl=/^\w*$/;function ir(r,e){if(E(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||je(r)?!0:Kl.test(r)||!Ol.test(r)||e!=null&&r in Object(e)}var rt=ve(Object,"create");function Fl(){this.__data__=rt?rt(null):{},this.size=0}function ql(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Ql="__lodash_hash_undefined__",Vl=Object.prototype,Gl=Vl.hasOwnProperty;function Bl(r){var e=this.__data__;if(rt){var t=e[r];return t===Ql?void 0:t}return Gl.call(e,r)?e[r]:void 0}var Ul=Object.prototype,Nl=Ul.hasOwnProperty;function zl(r){var e=this.__data__;return rt?e[r]!==void 0:Nl.call(e,r)}var Ll="__lodash_hash_undefined__";function Wl(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=rt&&e===void 0?Ll:e,this}function be(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}be.prototype.clear=Fl,be.prototype.delete=ql,be.prototype.get=Bl,be.prototype.has=zl,be.prototype.set=Wl;function Hl(){this.__data__=[],this.size=0}function $t(r,e){for(var t=r.length;t--;)if(Je(r[t][0],e))return t;return-1}var Jl=Array.prototype,Zl=Jl.splice;function Yl(r){var e=this.__data__,t=$t(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Zl.call(e,t,1),--this.size,!0}function Xl(r){var e=this.__data__,t=$t(e,r);return t<0?void 0:e[t][1]}function eu(r){return $t(this.__data__,r)>-1}function tu(r,e){var t=this.__data__,s=$t(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function re(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}re.prototype.clear=Hl,re.prototype.delete=Yl,re.prototype.get=Xl,re.prototype.has=eu,re.prototype.set=tu;var st=ve(J,"Map");function ru(){this.size=0,this.__data__={hash:new be,map:new(st||re),string:new be}}function su(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Ct(r,e){var t=r.__data__;return su(e)?t[typeof e=="string"?"string":"hash"]:t.map}function ou(r){var e=Ct(this,r).delete(r);return this.size-=e?1:0,e}function nu(r){return Ct(this,r).get(r)}function iu(r){return Ct(this,r).has(r)}function au(r,e){var t=Ct(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function se(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}se.prototype.clear=ru,se.prototype.delete=ou,se.prototype.get=nu,se.prototype.has=iu,se.prototype.set=au;var lu="Expected a function";function ar(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(lu);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(ar.Cache||se),t}ar.Cache=se;var uu=500;function cu(r){var e=ar(r,function(s){return t.size===uu&&t.clear(),s}),t=e.cache;return e}var du=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,fu=/\\(\\)?/g,pu=cu(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(du,function(t,s,o,n){e.push(o?n.replace(fu,"$1"):s||t)}),e});function Is(r){return r==null?"":Ht(r)}function Ts(r,e){return E(r)?r:ir(r,e)?[r]:pu(Is(r))}function Dt(r){if(typeof r=="string"||je(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function lr(r,e){e=Ts(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[Dt(e[t++])];return t&&t==s?r:void 0}function ot(r,e,t){var s=r==null?void 0:lr(r,e);return s===void 0?t:s}function Os(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var Ks=B?B.isConcatSpreadable:void 0;function hu(r){return E(r)||Ze(r)||!!(Ks&&r&&r[Ks])}function Fs(r,e,t,s,o){var n=-1,i=r.length;for(t||(t=hu),o||(o=[]);++n<i;){var a=r[n];t(a)&&Os(o,a)}return o}var qs=Ss(Object.getPrototypeOf,Object),yu="\\ud800-\\udfff",gu="\\u0300-\\u036f",mu="\\ufe20-\\ufe2f",vu="\\u20d0-\\u20ff",bu=gu+mu+vu,ku="\\ufe0e\\ufe0f",wu="\\u200d",Au=RegExp("["+wu+yu+bu+ku+"]");function $u(r){return Au.test(r)}function Cu(){this.__data__=new re,this.size=0}function Du(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function _u(r){return this.__data__.get(r)}function Pu(r){return this.__data__.has(r)}var xu=200;function Eu(r,e){var t=this.__data__;if(t instanceof re){var s=t.__data__;if(!st||s.length<xu-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new se(s)}return t.set(r,e),this.size=t.size,this}function L(r){var e=this.__data__=new re(r);this.size=e.size}L.prototype.clear=Cu,L.prototype.delete=Du,L.prototype.get=_u,L.prototype.has=Pu,L.prototype.set=Eu;var Qs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Vs=Qs&&typeof module=="object"&&module&&!module.nodeType&&module,ju=Vs&&Vs.exports===Qs,Gs=ju?J.Buffer:void 0,Bs=Gs?Gs.allocUnsafe:void 0;function Us(r,e){if(e)return r.slice();var t=r.length,s=Bs?Bs(t):new r.constructor(t);return r.copy(s),s}function Mu(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function Su(){return[]}var Ru=Object.prototype,Iu=Ru.propertyIsEnumerable,Ns=Object.getOwnPropertySymbols,Tu=Ns?function(r){return r==null?[]:(r=Object(r),Mu(Ns(r),function(e){return Iu.call(r,e)}))}:Su;function Ou(r,e,t){var s=e(r);return E(r)?s:Os(s,t(r))}function ur(r){return Ou(r,tt,Tu)}var cr=ve(J,"DataView"),dr=ve(J,"Promise"),fr=ve(J,"Set"),zs="[object Map]",Ku="[object Object]",Ls="[object Promise]",Ws="[object Set]",Hs="[object WeakMap]",Js="[object DataView]",Fu=me(cr),qu=me(st),Qu=me(dr),Vu=me(fr),Gu=me(Xt),U=ee;(cr&&U(new cr(new ArrayBuffer(1)))!=Js||st&&U(new st)!=zs||dr&&U(dr.resolve())!=Ls||fr&&U(new fr)!=Ws||Xt&&U(new Xt)!=Hs)&&(U=function(r){var e=ee(r),t=e==Ku?r.constructor:void 0,s=t?me(t):"";if(s)switch(s){case Fu:return Js;case qu:return zs;case Qu:return Ls;case Vu:return Ws;case Gu:return Hs}return e});var Bu=Object.prototype,Uu=Bu.hasOwnProperty;function Nu(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Uu.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var _t=J.Uint8Array;function pr(r){var e=new r.constructor(r.byteLength);return new _t(e).set(new _t(r)),e}function zu(r,e){var t=pr(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Lu=/\w*$/;function Wu(r){var e=new r.constructor(r.source,Lu.exec(r));return e.lastIndex=r.lastIndex,e}var Zs=B?B.prototype:void 0,Ys=Zs?Zs.valueOf:void 0;function Hu(r){return Ys?Object(Ys.call(r)):{}}function Xs(r,e){var t=e?pr(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.length)}var Ju="[object Boolean]",Zu="[object Date]",Yu="[object Map]",Xu="[object Number]",ec="[object RegExp]",tc="[object Set]",rc="[object String]",sc="[object Symbol]",oc="[object ArrayBuffer]",nc="[object DataView]",ic="[object Float32Array]",ac="[object Float64Array]",lc="[object Int8Array]",uc="[object Int16Array]",cc="[object Int32Array]",dc="[object Uint8Array]",fc="[object Uint8ClampedArray]",pc="[object Uint16Array]",hc="[object Uint32Array]";function yc(r,e,t){var s=r.constructor;switch(e){case oc:return pr(r);case Ju:case Zu:return new s(+r);case nc:return zu(r);case ic:case ac:case lc:case uc:case cc:case dc:case fc:case pc:case hc:return Xs(r,t);case Yu:return new s;case Xu:case rc:return new s(r);case ec:return Wu(r);case tc:return new s;case sc:return Hu(r)}}function eo(r){return typeof r.constructor=="function"&&!sr(r)?Sa(qs(r)):{}}var gc="[object Map]";function mc(r){return K(r)&&U(r)==gc}var to=Se&&Se.isMap,vc=to?Xe(to):mc,bc="[object Set]";function kc(r){return K(r)&&U(r)==bc}var ro=Se&&Se.isSet,wc=ro?Xe(ro):kc,Ac=1,so="[object Arguments]",$c="[object Array]",Cc="[object Boolean]",Dc="[object Date]",_c="[object Error]",oo="[object Function]",Pc="[object GeneratorFunction]",xc="[object Map]",Ec="[object Number]",no="[object Object]",jc="[object RegExp]",Mc="[object Set]",Sc="[object String]",Rc="[object Symbol]",Ic="[object WeakMap]",Tc="[object ArrayBuffer]",Oc="[object DataView]",Kc="[object Float32Array]",Fc="[object Float64Array]",qc="[object Int8Array]",Qc="[object Int16Array]",Vc="[object Int32Array]",Gc="[object Uint8Array]",Bc="[object Uint8ClampedArray]",Uc="[object Uint16Array]",Nc="[object Uint32Array]",w={};w[so]=w[$c]=w[Tc]=w[Oc]=w[Cc]=w[Dc]=w[Kc]=w[Fc]=w[qc]=w[Qc]=w[Vc]=w[xc]=w[Ec]=w[no]=w[jc]=w[Mc]=w[Sc]=w[Rc]=w[Gc]=w[Bc]=w[Uc]=w[Nc]=!0,w[_c]=w[oo]=w[Ic]=!1;function Pt(r,e,t,s,o,n){var i,a=e&Ac;if(i!==void 0)return i;if(!z(r))return r;var l=E(r);if(l)i=Nu(r);else{var u=U(r),c=u==oo||u==Pc;if(Ye(r))return Us(r,a);if(u==no||u==so||c&&!o)i=c?{}:eo(r);else{if(!w[u])return o?r:{};i=yc(r,u,a)}}n||(n=new L);var d=n.get(r);if(d)return d;n.set(r,i),wc(r)?r.forEach(function(p){i.add(Pt(p,e,t,p,r,n))}):vc(r)&&r.forEach(function(p,y){i.set(y,Pt(p,e,t,y,r,n))});var f=ur,h=l?void 0:f(r);return Va(h||r,function(p,y){h&&(y=p,p=r[y]),As(i,y,Pt(p,e,t,y,r,n))}),i}var zc=1,Lc=4;function oe(r){return Pt(r,zc|Lc)}var Wc="__lodash_hash_undefined__";function Hc(r){return this.__data__.set(r,Wc),this}function Jc(r){return this.__data__.has(r)}function nt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new se;++e<t;)this.add(r[e])}nt.prototype.add=nt.prototype.push=Hc,nt.prototype.has=Jc;function Zc(r,e){for(var t=-1,s=r==null?0:r.length;++t<s;)if(e(r[t],t,r))return!0;return!1}function io(r,e){return r.has(e)}var Yc=1,Xc=2;function ao(r,e,t,s,o,n){var i=t&Yc,a=r.length,l=e.length;if(a!=l&&!(i&&l>a))return!1;var u=n.get(r),c=n.get(e);if(u&&c)return u==e&&c==r;var d=-1,f=!0,h=t&Xc?new nt:void 0;for(n.set(r,e),n.set(e,r);++d<a;){var p=r[d],y=e[d];if(s)var v=i?s(y,p,d,e,r,n):s(p,y,d,r,e,n);if(v!==void 0){if(v)continue;f=!1;break}if(h){if(!Zc(e,function(g,k){if(!io(h,k)&&(p===g||o(p,g,t,s,n)))return h.push(k)})){f=!1;break}}else if(!(p===y||o(p,y,t,s,n))){f=!1;break}}return n.delete(r),n.delete(e),f}function ed(r){var e=-1,t=Array(r.size);return r.forEach(function(s,o){t[++e]=[o,s]}),t}function td(r){var e=-1,t=Array(r.size);return r.forEach(function(s){t[++e]=s}),t}var rd=1,sd=2,od="[object Boolean]",nd="[object Date]",id="[object Error]",ad="[object Map]",ld="[object Number]",ud="[object RegExp]",cd="[object Set]",dd="[object String]",fd="[object Symbol]",pd="[object ArrayBuffer]",hd="[object DataView]",lo=B?B.prototype:void 0,hr=lo?lo.valueOf:void 0;function yd(r,e,t,s,o,n,i){switch(t){case hd:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case pd:return!(r.byteLength!=e.byteLength||!n(new _t(r),new _t(e)));case od:case nd:case ld:return Je(+r,+e);case id:return r.name==e.name&&r.message==e.message;case ud:case dd:return r==e+"";case ad:var a=ed;case cd:var l=s&rd;if(a||(a=td),r.size!=e.size&&!l)return!1;var u=i.get(r);if(u)return u==e;s|=sd,i.set(r,e);var c=ao(a(r),a(e),s,o,n,i);return i.delete(r),c;case fd:if(hr)return hr.call(r)==hr.call(e)}return!1}var gd=1,md=Object.prototype,vd=md.hasOwnProperty;function bd(r,e,t,s,o,n){var i=t&gd,a=ur(r),l=a.length,u=ur(e),c=u.length;if(l!=c&&!i)return!1;for(var d=l;d--;){var f=a[d];if(!(i?f in e:vd.call(e,f)))return!1}var h=n.get(r),p=n.get(e);if(h&&p)return h==e&&p==r;var y=!0;n.set(r,e),n.set(e,r);for(var v=i;++d<l;){f=a[d];var g=r[f],k=e[f];if(s)var m=i?s(k,g,f,e,r,n):s(g,k,f,r,e,n);if(!(m===void 0?g===k||o(g,k,t,s,n):m)){y=!1;break}v||(v=f=="constructor")}if(y&&!v){var S=r.constructor,N=e.constructor;S!=N&&"constructor"in r&&"constructor"in e&&!(typeof S=="function"&&S instanceof S&&typeof N=="function"&&N instanceof N)&&(y=!1)}return n.delete(r),n.delete(e),y}var kd=1,uo="[object Arguments]",co="[object Array]",xt="[object Object]",wd=Object.prototype,fo=wd.hasOwnProperty;function Ad(r,e,t,s,o,n){var i=E(r),a=E(e),l=i?co:U(r),u=a?co:U(e);l=l==uo?xt:l,u=u==uo?xt:u;var c=l==xt,d=u==xt,f=l==u;if(f&&Ye(r)){if(!Ye(e))return!1;i=!0,c=!1}if(f&&!c)return n||(n=new L),i||nr(r)?ao(r,e,t,s,o,n):yd(r,e,l,t,s,o,n);if(!(t&kd)){var h=c&&fo.call(r,"__wrapped__"),p=d&&fo.call(e,"__wrapped__");if(h||p){var y=h?r.value():r,v=p?e.value():e;return n||(n=new L),o(y,v,t,s,n)}}return f?(n||(n=new L),bd(r,e,t,s,o,n)):!1}function it(r,e,t,s,o){return r===e?!0:r==null||e==null||!K(r)&&!K(e)?r!==r&&e!==e:Ad(r,e,t,s,it,o)}var $d=1,Cd=2;function po(r,e,t,s){var o=t.length,n=o;if(r==null)return!n;for(r=Object(r);o--;){var i=t[o];if(i[2]?i[1]!==r[i[0]]:!(i[0]in r))return!1}for(;++o<n;){i=t[o];var a=i[0],l=r[a],u=i[1];if(i[2]){if(l===void 0&&!(a in r))return!1}else{var c=new L,d;if(!(d===void 0?it(u,l,$d|Cd,s,c):d))return!1}}return!0}function ho(r){return r===r&&!z(r)}function yo(r){for(var e=tt(r),t=e.length;t--;){var s=e[t],o=r[s];e[t]=[s,o,ho(o)]}return e}function go(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Dd(r){var e=yo(r);return e.length==1&&e[0][2]?go(e[0][0],e[0][1]):function(t){return t===r||po(t,r,e)}}function _d(r,e){return r!=null&&e in Object(r)}function Pd(r,e,t){e=Ts(e,r);for(var s=-1,o=e.length,n=!1;++s<o;){var i=Dt(e[s]);if(!(n=r!=null&&t(r,i)))break;r=r[i]}return n||++s!=o?n:(o=r==null?0:r.length,!!o&&rr(o)&&er(i,o)&&(E(r)||Ze(r)))}function xd(r,e){return r!=null&&Pd(r,e,_d)}var Ed=1,jd=2;function Md(r,e){return ir(r)&&ho(e)?go(Dt(r),e):function(t){var s=ot(t,r);return s===void 0&&s===e?xd(t,r):it(e,s,Ed|jd)}}function mo(r){return function(e){return e?.[r]}}function Sd(r){return function(e){return lr(e,r)}}function Rd(r){return ir(r)?mo(Dt(r)):Sd(r)}function Re(r){return typeof r=="function"?r:r==null?kt:typeof r=="object"?E(r)?Md(r[0],r[1]):Dd(r):Rd(r)}function Id(r){return function(e,t,s){for(var o=-1,n=Object(e),i=s(e),a=i.length;a--;){var l=i[++o];if(t(n[l],l,n)===!1)break}return e}}var vo=Id();function Td(r,e){return r&&vo(r,e,tt)}function Od(r,e){return function(t,s){if(t==null)return t;if(!te(t))return r(t,s);for(var o=t.length,n=-1,i=Object(t);++n<o&&s(i[n],n,i)!==!1;);return t}}var yr=Od(Td);function Ie(r){return K(r)&&te(r)}var Kd=200;function bo(r,e,t,s){var o=-1,n=Ua,i=!0,a=r.length,l=[],u=e.length;if(!a)return l;t&&(e=Me(e,Xe(t))),e.length>=Kd&&(n=io,i=!1,e=new nt(e));e:for(;++o<a;){var c=r[o],d=t==null?c:t(c);if(c=c!==0?c:0,i&&d===d){for(var f=u;f--;)if(e[f]===d)continue e;l.push(c)}else n(e,d,s)||l.push(c)}return l}function Fd(r){var e=r==null?0:r.length;return e?r[e-1]:void 0}var ko=tr(function(r,e){var t=Fd(e);return Ie(t)&&(t=void 0),Ie(r)?bo(r,Fs(e,1,Ie),Re(t)):[]});function qd(r,e){for(var t=-1,s=r==null?0:r.length;++t<s;)if(!e(r[t],t,r))return!1;return!0}function Qd(r,e){var t=!0;return yr(r,function(s,o,n){return t=!!e(s,o,n),t}),t}function wo(r,e,t){var s=E(r)?qd:Qd;return s(r,Re(e))}function Vd(r){return function(e,t,s){var o=Object(e);if(!te(e)){var n=Re(t);e=tt(e),t=function(a){return n(o[a],a,o)}}var i=r(e,t,s);return i>-1?o[n?e[i]:i]:void 0}}var Gd=Math.max;function gr(r,e,t){var s=r==null?0:r.length;if(!s)return-1;var o=t==null?0:Jt(t);return o<0&&(o=Gd(s+o,0)),ks(r,Re(e),o)}var Bd=Vd(gr);function Ud(r,e){var t=-1,s=te(r)?Array(r.length):[];return yr(r,function(o,n,i){s[++t]=e(o,n,i)}),s}var Nd="[object String]";function Et(r){return typeof r=="string"||!E(r)&&K(r)&&ee(r)==Nd}function zd(r,e){return it(r,e)}function mr(r,e,t){t=typeof t=="function"?t:void 0;var s=t?t(r,e):void 0;return s===void 0?it(r,e,void 0,t):!!s}function Ao(r,e){return r===e||po(r,e,yo(e))}function Ld(r,e){var t=r.length;for(r.sort(e);t--;)r[t]=r[t].value;return r}function Wd(r,e){if(r!==e){var t=r!==void 0,s=r===null,o=r===r,n=je(r),i=e!==void 0,a=e===null,l=e===e,u=je(e);if(!a&&!u&&!n&&r>e||n&&i&&l&&!a&&!u||s&&i&&l||!t&&l||!o)return 1;if(!s&&!n&&!u&&r<e||u&&t&&o&&!s&&!n||a&&t&&o||!i&&o||!l)return-1}return 0}function Hd(r,e,t){for(var s=-1,o=r.criteria,n=e.criteria,i=o.length,a=t.length;++s<i;){var l=Wd(o[s],n[s]);if(l){if(s>=a)return l;var u=t[s];return l*(u=="desc"?-1:1)}}return r.index-e.index}function Jd(r,e,t){e.length?e=Me(e,function(n){return E(n)?function(i){return lr(i,n.length===1?n[0]:n)}:n}):e=[kt];var s=-1;e=Me(e,Xe(Re));var o=Ud(r,function(n,i,a){var l=Me(e,function(u){return u(n)});return{criteria:l,index:++s,value:n}});return Ld(o,function(n,i){return Hd(n,i,t)})}function $o(r,e,t,s){return r==null?[]:(E(e)||(e=e==null?[]:[e]),t=t,E(t)||(t=t==null?[]:[t]),Jd(r,e,t))}var Zd=mo("length"),Co="\\ud800-\\udfff",Yd="\\u0300-\\u036f",Xd="\\ufe20-\\ufe2f",ef="\\u20d0-\\u20ff",tf=Yd+Xd+ef,rf="\\ufe0e\\ufe0f",sf="["+Co+"]",vr="["+tf+"]",br="\\ud83c[\\udffb-\\udfff]",of="(?:"+vr+"|"+br+")",Do="[^"+Co+"]",_o="(?:\\ud83c[\\udde6-\\uddff]){2}",Po="[\\ud800-\\udbff][\\udc00-\\udfff]",nf="\\u200d",xo=of+"?",Eo="["+rf+"]?",af="(?:"+nf+"(?:"+[Do,_o,Po].join("|")+")"+Eo+xo+")*",lf=Eo+xo+af,uf="(?:"+[Do+vr+"?",vr,_o,Po,sf].join("|")+")",jo=RegExp(br+"(?="+br+")|"+uf+lf,"g");function cf(r){for(var e=jo.lastIndex=0;jo.test(r);)++e;return e}function df(r){return $u(r)?cf(r):Zd(r)}var ff="[object Map]",pf="[object Set]";function hf(r){if(r==null)return 0;if(te(r))return Et(r)?df(r):r.length;var e=U(r);return e==ff||e==pf?r.size:Rs(r).length}function kr(r){const e=wr(r);return yf(e)}function wr(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(wr).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+wr(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function yf(r){let e=0;for(let t=0;t<r.length;t++){const s=r.charCodeAt(t);e=(e<<5)-e+s,e|=0}return e.toString(16)}const ce={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:r=>{typeof performance<"u"&&performance.mark&&performance.mark(r)},measure:(r,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(r,e,t)},getEntriesByName(r){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(r)},getEntriesByType(r){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(r)}};class gf{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),s={name:e.name,type:"mark",value:ce.now(),createdAt:Date.now()};return this.data.set(t,s),s}measure(e){if(!this.enabled)return;const t=this.getKey(e.name,e.context),s=this.data.get(this.getKey(e.start,e.context)),o=this.data.get(this.getKey(e.end,e.context));if(!s||!o)return;const n=o.value-s.value,i=Math.round(n*100)/100,a=this.data.get(t);if(a&&e.sum){const u=a.value+i,c={...a,value:u};return this.data.set(t,c),c}const l={name:e.name,type:"measure",value:i,createdAt:Date.now()};return e.detail&&(l.detail=e.detail),this.data.set(t,l),l}update(e){if(!this.enabled)return e.value;const t=this.getKey(e.value.name,e.context),s=this.data.get(t);if(s){const o={...s,...e.value};this.data.set(t,o)}else this.data.set(t,e.value);return this.data.get(t)}getResourceInfosFromPerformanceAPI(){return typeof performance>"u"?[]:ce.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 s=kr(t);return e+"_"+s}}let Mo=class Ki{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[s,o]of this.edges)o.has(e)&&t.push(s);return t}isCyclic(){const e=new Set,t=new Set,s=o=>{if(e.has(o))return!1;if(t.has(o))return!0;t.add(o);const n=this.edges.get(o);if(n){for(let i of n)if(s(i))return!0}return t.delete(o),e.add(o),!1};for(let o of this.nodes)if(s(o))return!0;return!1}validateNoCycles(){const e=new Set,t=new Set,s=[],o=n=>{if(e.has(n))return null;if(t.has(n)){const a=s.indexOf(n);return s.slice(a).concat([n])}t.add(n),s.push(n);const i=this.edges.get(n);if(i)for(let a of i){const l=o(a);if(l)return l}return s.pop(),t.delete(n),e.add(n),null};for(let n of this.nodes){const i=o(n);if(i)return{hasCycle:!0,path:i}}return{hasCycle:!1}}order(e){const t=new Set,s=new Set,o=[],n=e?.allowCycles??!1,i=a=>{if(t.has(a))return;if(s.has(a)){if(n)return;throw new Error("Graph has a cycle.")}s.add(a);const l=this.edges.get(a);if(l)for(let u of l)i(u);s.delete(a),t.add(a),o.push(a)};for(let a of this.nodes)t.has(a)||i(a);return o}clear(){this.nodes.clear(),this.edges.clear()}getNodes(){return Array.from(this.nodes)}getAllEdges(){const e=[];for(let[t,s]of this.edges)for(let o of s)e.push([t,o]);return e}getNodesWithNoDependants(){if(this.nodes.size===0)return[];const e=new Set;for(const s of this.edges.values())for(const o of s)e.add(o);const t=[];for(const s of this.nodes)e.has(s)||t.push(s);return t}getNodesByKind(e){const t=[];for(const s of this.nodes)this.nodeKinds.get(s)===e&&t.push(s);return t}getRootsByKind(e){const t=new Set(this.getNodesWithNoDependants()),s=Array.from(t);return e?s.filter(o=>this.nodeKinds.get(o)===e):s}getLeavesByKind(e){const t=[];for(const s of this.nodes){const o=this.edges.get(s);(!o||o.size===0)&&(!e||this.nodeKinds.get(s)===e)&&t.push(s)}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 i of this.nodes)t.set(i,0);for(const i of this.edges.values())for(const a of i)t.set(a,(t.get(a)||0)+1);const s=[];let o=Array.from(this.nodes).filter(i=>(t.get(i)||0)===0);const n=new Set;for(;o.length>0;){const i=o.slice();s.push(i),o=[];for(const a of i){if(n.has(a))continue;n.add(a);const l=this.edges.get(a);if(l)for(const u of l)t.set(u,(t.get(u)||0)-1),(t.get(u)||0)===0&&o.push(u)}}if(n.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const i=new Set(e.filterKinds);return{batches:s.map(a=>a.filter(l=>i.has(this.nodeKinds.get(l))))}}return{batches:s}}getImpactedNodes(e,t="downstream",s){const o=new Set(e),n=u=>!s||s.length===0||s.includes(this.nodeKinds.get(u)??void 0),i=()=>{const u=new Set,c=Array.from(o);for(;c.length;){const d=c.shift();for(const[f,h]of this.edges)h.has(d)&&!u.has(f)&&(u.add(f),c.push(f))}return u},a=()=>{const u=new Set,c=Array.from(o);for(;c.length;){const d=c.shift(),f=this.edges.get(d);if(f)for(const h of f)u.has(h)||(u.add(h),c.push(h))}return u};let l;return t==="both"?l=new Set([...i(),...a()]):t==="upstream"?l=a():l=i(),Array.from(l).filter(n)}toJSON(){const e=Array.from(this.nodes).map(s=>({name:s,kind:this.nodeKinds.get(s),meta:this.nodeMeta.get(s)})),t=this.getAllEdges().map(([s,o])=>({from:s,to:o}));return{nodes:e,edges:t}}static fromJSON(e){const t=new Ki;for(const s of e.nodes)t.addNode(s.name,{kind:s.kind,meta:s.meta});for(const s of e.edges)t.addDependency(s.from,s.to);return t}diff(e){const t=new Set(this.getNodes()),s=new Set(e.getNodes()),o=Array.from(s).filter(d=>!t.has(d)),n=Array.from(t).filter(d=>!s.has(d)),i=new Set(this.getAllEdges().map(d=>d.join("→"))),a=new Set(e.getAllEdges().map(d=>d.join("→"))),l=Array.from(a).filter(d=>!i.has(d)).map(d=>d.split("→")),u=Array.from(i).filter(d=>!a.has(d)).map(d=>d.split("→")),c=[];for(const d of new Set([...t,...s])){const f=this.nodeKinds.get(d),h=e.nodeKinds.get(d);f!==h&&c.push({name:d,from:f,to:h})}return{addedNodes:o,removedNodes:n,addedEdges:l,removedEdges:u,kindChanges:c}}};class mf{graph;nodeIndex;constructor(){this.graph=new Mo,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 s=this.getNodeId(e.modelKey,e.attributeKey),o=this.getNodeId(t.modelKey,t.attributeKey);this.graph.hasDependency(s,o)||this.graph.addDependency(s,o)}getImpactedAttributes(e){const t=e.map(i=>this.getNodeId(i.modelKey,i.attributeKey)),s=this.graph.getImpactedNodes(t,"downstream").map(i=>this.nodeIndex.get(i)).filter(i=>i!==void 0),o=[...e,...s],n=new Set;return o.filter(i=>{const a=this.getNodeId(i.modelKey,i.attributeKey);return n.has(a)?!1:(n.add(a),!0)})}getProcessingOrder(e){const t=new Map,s=[...e].sort((o,n)=>o.processingStep-n.processingStep);for(const o of s){const{modelKey:n,attributeKey:i,processingStep:a}=o;t.has(n)||t.set(n,new Map);const l=t.get(n);l.has(a)||l.set(a,new Set),l.get(a).add(i)}return t}getAttributesForModel(e){const t=[];for(const s of this.nodeIndex.values())s.modelKey===e&&t.push(s);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=(s,o=new Set)=>{if(o.has(s))return 0;o.add(s);const n=this.graph.getDependencies(s);if(n.length===0)return 1;let i=0;for(const a of n){const l=t(a,new Set(o));i=Math.max(i,l)}return i+1};for(const s of this.graph.getNodes()){const o=t(s);e=Math.max(e,o)}return e}validateCompleteness(e){const t=[];for(const[s,o]of e)for(const n of o){const i=this.getNodeId(s,n);this.hasNode(i)||t.push({modelKey:s,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 s of this.nodeIndex.values())e.set(s.modelKey,(e.get(s.modelKey)||0)+1),t.set(s.processingStep,(t.get(s.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 s=this.parseNodeId(e),o=this.parseNodeId(t);return{from:s,to:o}})}}}const So={silent:0,error:1,warn:2,info:3,debug:4};let vf=class T{config;static globalConfig={};constructor(e={}){this.config={level:e.level??T.globalConfig.level??this.getDefaultLevel(),format:e.format??T.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??T.globalConfig.onLog,onTrackError:e.onTrackError??T.globalConfig.onTrackError}}static setGlobalConfig(e){T.globalConfig={...T.globalConfig,...e}}static getGlobalConfig(){return{...T.globalConfig}}static setModuleLevel(e,t){T.globalConfig.onLog||(T.globalConfig.onLog=void 0),T._moduleOverrides||(T._moduleOverrides=new Map),T._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!T._moduleOverrides))return T._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=T.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return So[e]<=So[t]}formatMessage(e){if(this.config.format==="json"){const i={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(i.module=e.prefix),e.context&&(i.context=e.context),e.error&&(i.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(i)}const t=new Date(e.timestamp).toISOString().substring(11,23),s=e.prefix?`[${e.prefix}]`:"",o=this.getLevelIcon(e.level),n=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${o} ${s} ${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,s,o){if(!this.shouldLog(e))return;const n={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:s,error:o};if(this.config.onLog){this.config.onLog(n);return}const i=this.formatMessage(n);if(typeof console<"u")switch(e){case"error":o?console.error(i,o):console.error(i);break;case"warn":console.warn(i);break;case"debug":console.debug?console.debug(i):console.log(i);break;default:console.log(i)}}error(e,t,s){const o=t instanceof Error?t:void 0,n=t instanceof Error?s:t;this.log("error",e,n,o)}trackError(e,t,s){if(this.error(e,t,s?.context),this.config.onTrackError){const o={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:s?.context,error:t,errorType:s?.errorType,errorGroup:s?.errorGroup};this.config.onTrackError(o)}}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 T(t)}configure(e){Object.assign(this.config,e)}};const Te=new vf;class bf{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}enabled;cache;cacheDependencies;hitCount=0;missCount=0;log=Te.child({prefix:"CacheController"});get(e,t){if(!this.enabled)return;const s=this.getCacheName(e,t);return this.cache.has(s)?this.hitCount++:this.missCount++,this.cache.get(s)}set(e,t,s,o){if(!this.enabled)return;const n=this.getCacheName(e,t);this.cache.set(n,s),o?this.cacheDependencies.set(n,o):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[s,o]of this.cacheDependencies){let n=!1;for(const[i,a]of e){if(o.models.has(i))if(o.modelAttributes.has(i)){const l=o.modelAttributes.get(i);for(const u of a)if(l.has(u)){n=!0;break}}else n=!0;if(n)break}n&&t.push(s)}for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateByModels(e){if(!this.enabled)return;const t=new Set(e),s=[];for(const[o,n]of this.cacheDependencies)for(const i of t)if(n.models.has(i)){s.push(o);break}for(const o of s)this.cache.delete(o),this.cacheDependencies.delete(o)}invalidateByKeyPrefix(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())s.startsWith(e+"_")&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateForModel(e){this.invalidateByModels([e])}invalidateForAttribute(e,t){if(!this.enabled)return;const s=new Map;s.set(e,new Set([t])),this.invalidateByDependencies(s)}invalidateMatching(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())e(s)&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}generateContext(e){try{return oe(e)}catch(t){return this.log.error("Error in cache generateContext",t),e}}getCacheName(e,t){const s=kr(t);return e+"_"+s}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 Ar=(r,e="")=>{if(!(typeof r!="string"||!r.startsWith("/")||!r.endsWith("/")))return{pattern:r.slice(1,-1),flags:e}};function W(r=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let s=0;s<r;s++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}class $r{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=ce.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 Ro=(r,e)=>e?typeof structuredClone<"u"?structuredClone(r):oe(r):r,Io=(r,e,t,s,o,n)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=Ro(n,i);if(t.scope==="list"&&(t.listKey=r.cdRef?.key||r.key,t.modelKey=r.model?.key||r.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const l=ce.now(),u=l-s,c=Math.round(u*1e3)/1e3;t.duration=c,t.start=s,t.end=l;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:o}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:o,detail:d}),a}catch{return n}},b=r=>(e,t,s)=>{const o=s.value;return s.value=function(...n){const i=ce.now(),a=this.cdRef,l=Ro(r,!0);l.key||(a.increaseCounter(),l.key=a.getCounter());const u=W();a.analyticsController.mark({name:`${l.type}:start`,context:u});const c=this.model?.key;!l.originCdRefKey&&a.key&&(l.originCdRefKey=a.key),c&&(l.modelKey=c);const d=o.apply(this,n);return l.method=t,l.args=n,d&&typeof d=="object"&&"then"in d?d.then(f=>Io(this,a,l,i,u,f)):Io(this,a,l,i,u,d)},s};function kf(r,e,t,s){t.max||(t.max=20);const o=[],n=t.transform?s.transformValue(t.value,t.transform):t.value;for(const[i,a]of e.entries()){const l=Array.from(a).some(c=>r.has(c)),u=t.transform?s.transformValue(i,t.transform):i;if(!(t.excludeUndefineds&&typeof i>"u")&&!(t.excludeNulls&&i===null)){if(l&&(n===""||n==="//")){const c={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(c)}else if(l&&Ar(n)){if(s.queryFind(u,n,"some",t.regexFlags)){const c={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(c)}}else if(l&&typeof n=="string"){const c=String(u??""),d=n;if(c.toLowerCase().startsWith(d.toLowerCase())){const f={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(f)}}else if(l&&s.queryFind(u,n,"some")){const c={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(c)}if(o.length===t.max)break}}return o}function wf(r){return r instanceof Date}function To(r){return r instanceof Date&&!isNaN(r.getTime())}const Af={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 $f(r){let e="^";const t=[];let s=r;const o=Object.entries(Af).sort((n,i)=>i[0].length-n[0].length);for(;s.length>0;){let n=!1;for(const[i,a]of o)if(s.startsWith(i)){e+=a.regex,t.push({type:a.type,pattern:i}),s=s.slice(i.length),n=!0;break}if(!n){const i=s[0];if(!i)break;e+=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=s.slice(1)}}return e+="$",{regex:new RegExp(e),tokenOrder:t}}function Cf(r,e){const t={year:1970,month:1,day:1,hour:0,minute:0,second:0,millisecond:0};for(let s=0;s<e.length;s++){const o=r[s+1];if(!o)continue;const n=parseInt(o,10),i=e[s];i&&(i.type==="year"&&i.pattern==="yy"?t.year=2e3+n:t[i.type]=n)}return t}function Df(r){if(r.month<1||r.month>12)return new Date(NaN);if(r.day<1||r.day>31)return new Date(NaN);if(r.hour<0||r.hour>23)return new Date(NaN);if(r.minute<0||r.minute>59)return new Date(NaN);if(r.second<0||r.second>59)return new Date(NaN);if(r.millisecond<0||r.millisecond>999)return new Date(NaN);const e=new Date(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return To(e)?e.getFullYear()!==r.year||e.getMonth()!==r.month-1||e.getDate()!==r.day?new Date(NaN):e:new Date(NaN)}function _f(r,e,t){if(r=r.trim(),e==="t"){const a=Number(r);return isNaN(a)?new Date(NaN):new Date(a*1e3)}if(e==="T"){const a=Number(r);return isNaN(a)?new Date(NaN):new Date(a)}const{regex:s,tokenOrder:o}=$f(e),n=r.match(s);if(!n)return new Date(NaN);const i=Cf(n,o);return Df(i)}class Pf{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 s=this.accessOrder.shift();s!==void 0&&this.cache.delete(s)}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 xf{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,s=new Set,o=n=>{t.add(n),s.add(n);const i=this.graph.get(n);if(i){for(const a of i)if(t.has(a)){if(s.has(a))return!0}else if(o(a))return!0}return s.delete(n),!1};for(let n=0;n<e.length-1;n++){const i=e[n],a=e[n+1];i&&a&&this.addDependency(i,a)}for(const n of e)if(!t.has(n)&&o(n))return!0;return!1}clear(){this.graph.clear()}}class Ef{parseCache;circularRefDetector;cacheHits=0;cacheMisses=0;constructor(e=1e3){this.parseCache=new Pf(e),this.circularRefDetector=new xf}parse(e){if(this.parseCache.has(e))return this.cacheHits++,this.parseCache.get(e);this.cacheMisses++;let t,s;const o=e.includes("."),n=e.includes("["),i=o||n;if(i){s=e.split(/[.[]/)[0];const l=e.indexOf("."),u=e.indexOf("[");if(n&&(l===-1||u<l)){const c=e.indexOf("]");if(c>-1){const d=e.indexOf(".",c+1);d>-1?t=e.substring(d+1):t=void 0}else o&&(t=e.substring(l+1))}else o&&(t=e.substring(l+1))}const a={attribute:e,isDeepQuery:i};return s&&(a.reference=s),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 s=[];if(!e||e.trim().length===0)return s.push("Attribute path cannot be empty"),{valid:!1,errors:s};(e.startsWith(".")||e.endsWith("."))&&s.push(`Invalid path: Leading or trailing dots are not allowed: ${e}`),e.includes("..")&&s.push(`Invalid path: Consecutive dots are not allowed: ${e}`);const o=(e.match(/\[/g)||[]).length,n=(e.match(/]/g)||[]).length;o!==n&&s.push(`Invalid bracket notation: Mismatched brackets in ${e}`),e.includes("[]")&&s.push(`Invalid bracket notation: Empty brackets not allowed: ${e}`);const i=/\[([^\]]+)\]/g;let a;for(;(a=i.exec(e))!==null;){const c=a[1];c&&c!=="*"&&!/^\d+$/.test(c)&&s.push(`Invalid bracket content: Must be a number or '*', got '${c}' in ${e}`)}const l=(e.match(/\./g)||[]).length+1;l>t&&s.push(`Path too deep: Maximum depth is ${t}, got ${l} in ${e}`);const u=e.match(/[^a-zA-Z0-9._[\]*-]/g);return u&&s.push(`Invalid characters in path: ${u.join(", ")} in ${e}`),{valid:s.length===0,errors:s.length>0?s: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,s=t>0?this.cacheHits/t:0;return{...e,hits:this.cacheHits,misses:this.cacheMisses,hitRate:s}}getPathSegments(e){return e.replace(/\[[^\]]+\]/g,"").split(".").filter(t=>t.length>0)}getPathDepth(e){return this.getPathSegments(e).length}}const P=new Ef;function de(r,e){if(e.includes("[*]")){const n=e.indexOf("[*]"),i=e.substring(0,n),a=e.substring(n+3),l=i?ot(r,i):r;if(!Array.isArray(l))return[];const u=[];for(const c of l)!a||a===""?c!==void 0&&u.push(c):a.startsWith(".")&&u.push(...de(c,a.slice(1)));return u}const t=e.split(".");let s=[r];for(const n of t){const i=[];for(const a of s)if(a!=null)if(Array.isArray(a))for(const l of a){if(l==null)continue;const u=l[n];u!==void 0&&i.push(u)}else{const l=a[n];l!==void 0&&i.push(l)}if(s=i,s.length===0)return[]}const o=[];for(const n of s)if(Array.isArray(n))for(const i of n)i!==void 0&&o.push(i);else n!==void 0&&o.push(n);return o}function Cr(r){let e=0;for(let t of r){const s=t.toString().split(".")[1];s&&(e=Math.max(e,s.length))}return Math.pow(10,e)}function Oo(r,e,t){return(r*t+e*t)/t}function jf(r,e,t){return r*t/(e*t)}const at=(r,e,t,s)=>{if(!s)throw new Error("Attribute not found");const o={attribute:s,types:r.types};let n;(o.types.includes("sum")||o.types.includes("avg"))&&(n=If(s,e));let i;return(o.types.includes("min")||o.types.includes("max"))&&(i=Sf(s,e)),r.types.forEach(a=>{a==="sum"?o.sum=n?.sum:a==="avg"?o.avg=n?.average:a==="count"?o.count=Mf(s,e):a==="min"?o.min=i&&i[0]:a==="max"?o.max=i&&i[1]:a==="distinct"?o.distinct=Tf(r,e,t):a==="group"&&(o.group=Rf(r,e))}),o},Mf=(r,e)=>{const t=P.parse(r).isDeepQuery;let s=0;for(const o of e.values())if(o)if(t)s+=de(o,r).filter(n=>n!=null).length;else{const n=o[r];if(n==null)continue;Array.isArray(n)?s+=n.filter(i=>i!=null).length:s++}return s},Sf=(r,e)=>{let t,s;const o=P.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=de(n,r);else{const a=n[r];a===void 0?i=[]:Array.isArray(a)?i=a.filter(l=>l!==void 0):i=[a]}for(const a of i)a==null||typeof a=="object"||((t===void 0||a<t)&&(t=a),(s===void 0||a>s)&&(s=a))}if(!(t===void 0||s===void 0))return[t,s]},Rf=(r,e)=>{const t=[];r.groupOptions?.groups?.forEach(n=>{t.push({option:n,count:0,keys:[]})});const s={option:{value:["$dcupl_not_found"]},count:0,keys:[]},o=P.parse(r.attribute).isDeepQuery;for(const n of e.values()){let i;o?i=de(n,r.attribute):i=[n[r.attribute]];let a=!1;for(const l of i)for(const u of t)(typeof u.option.value<"u"&&u.option.value.includes(l)||typeof u.option.from<"u"&&u.option.from<l&&typeof u.option.to<"u"&&u.option.to>l)&&(u.keys.includes(n.key)||(u.count++,u.keys.push(n.key)),a=!0);!a&&r?.groupOptions?.calculateNotFound&&(s.count++,s.keys.push(n.key))}return r?.groupOptions?.calculateNotFound&&t.push(s),t},If=(r,e)=>{let t=0,s=0;const o=P.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=de(n,r);else{const a=n[r];a===void 0?i=[]:Array.isArray(a)?i=a:i=[a]}for(const a of i)if(Array.isArray(a))for(const l of a)typeof l=="number"&&(t=Oo(t,l,Cr([t,l])),s++);else typeof a=="number"&&(t=Oo(t,a,Cr([t,a])),s++)}return s===0?void 0:{average:jf(t,s,Cr([t,s])),count:s,sum:t}},Tf=(r,e,t)=>{const s=[];for(const[o,n]of t)if(!(r.excludeUndefineds&&typeof o>"u")&&Array.from(n).find(i=>e.has(i))){const i={value:o,count:n.size};if(r.distinctOptions?.skipKeys||(i.keys=Array.from(n)),s.push(i),r.distinctOptions?.limit&&s.length>=r.distinctOptions.limit)break}return s};class Oe extends Error{query;constructor(e,t){const s=`Query Error: ${e} in ${JSON.stringify(t,null,2)}`;super(s),this.query=t,this.name="DcuplQueryError"}}let ke=class{_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=oe(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||P}init(e){this._initOptions=oe(e),this.currentQuery=oe(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=oe(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 s=this.locateQueryGroup(e,(t??this.currentQuery).queries);return s?this.groupAtPath(s):void 0}locateQueryGroup(e,t){const s=t.findIndex(o=>this.isQueryGroup(o)&&o.groupKey===e);if(s>-1)return[{queries:t,idx:s}];for(const[o,n]of t.entries())if(this.isQueryGroup(n)){const i=this.locateQueryGroup(e,n.queries);if(i)return[{queries:t,idx:o},...i]}}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:s,idx:o}=e[t];if(s[o].queries.length>0)break;s.splice(o,1)}}getQuery(){return oe(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(s=>this.isQuery(s)&&s.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:wo(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,s){if(s||(s=this.currentQuery),Array.isArray(e))for(const o of e)this.applyQuery(o,t,s);else if(this.isRootQueryGroup(e))e.groupType&&(s.groupType=e.groupType),t?.mode==="set"?s.queries=e.queries:s.queries=[...s.queries,...e.queries],this.applyOptions(e,"set");else if(this.isQuery(e)){const o=s.queries.findIndex(n=>this.isQueryGroup(n)&&n.groupKey===e.attribute);if(o>-1){const n=s.queries[o];t?.mode==="set"?n.queries=[e]:n.queries.push(e)}else s.queries.push({groupKey:e.attribute,groupType:"or",queries:[e]})}else if(this.isQueryGroup(e)){const o=e.groupKey===void 0&&t?.mode!=="set"?-1:s.queries.findIndex(n=>this.isQueryGroup(n)&&n.groupKey===e.groupKey);if(o>-1){const n=s.queries[o];e.groupType&&(n.groupType=e.groupType),t?.mode==="set"?s.queries[o]=e:n.queries=[...n.queries,...e.queries]}else s.queries.push({groupKey:e.groupKey,groupType:e.groupType||"or",queries:e.queries})}return s}removeAllQueries(){return this.currentQuery.queries=[],this.getQuery()}removeQuery(e,t){if(t||(t=this.currentQuery),this.isQuery(e)){const s=this.locateQueryGroup(e.attribute,t.queries);if(s){const o=this.groupAtPath(s),n=gr(o.queries,e);n>-1&&o.queries.splice(n,1),this.pruneEmptyGroups(s)}}else if(this.isQueryGroup(e)){const s=this.locateQueryGroup(e.groupKey,t.queries);if(s)if(e.queries){const o=this.groupAtPath(s);for(const n of e.queries){const i=gr(o.queries,n);i>-1&&o.queries.splice(i,1)}this.pruneEmptyGroups(s)}else{const o=s[s.length-1];o.queries.splice(o.idx,1),this.pruneEmptyGroups(s.slice(0,-1))}}return t}validateQuery(e){const t=[];if(this.isQuery(e))return e.attribute||t.push(new Oe("Missing attribute",e)),e.operator||t.push(new Oe("Missing operator",e)),typeof e.value>"u"&&t.push(new Oe("Missing value",e)),e.operator==="find"&&Array.isArray(e.value)&&t.push(new Oe("find operator cannot have array value",e)),e.operator==="in"&&typeof e.value<"u"&&!Array.isArray(e.value)&&t.push(new Oe("in operator needs an array value",e)),t.length>0?{valid:!1,errors:t}:{valid:!0};if(this.isQueryGroup(e)){const s=e.queries.map(o=>this.validateQuery(o)).filter(o=>!o.valid).map(o=>o.errors).flat();return s.length>0?{valid:!1,errors:s}:{valid:!0}}return t.push(new Oe("Invalid query definition",e)),{valid:!1,errors:t}}getQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)this.isQuery(i)?i.attribute&&!s.has(i.attribute)&&(t.push(i.attribute),s.add(i.attribute)):this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)if(this.isQuery(i)){if(i.attribute&&!s.has(i.attribute)){const a=this.getQueryAttributeForString(i.attribute);t.push(a),s.add(i.attribute)}}else this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}getQueryAttributeForString(e){return this.deepQueryService.parse(e)}getDeepQueryService(){return this.deepQueryService}getProjectionForAttributes(e){const t={};return e.forEach(s=>{t[s]=!0}),t}getProjectionForAttributeEntries(e){const t={$:!0};return e.forEach(s=>{if(s.isDeepQuery){if(s.reference)if(s.referenceAttribute&&s.referenceAttribute.length>0){t[s.reference]||(t[s.reference]={$:!0});const o=this.deepQueryService.parse(s.referenceAttribute);if(o.isDeepQuery&&s.reference){const n=this.getProjectionForAttributeEntries([o]);Object.keys(n).forEach(i=>{i!=="$"&&s.reference&&(t[s.reference][i]=n[i])})}else s.reference&&(t[s.reference][s.referenceAttribute]=!0)}else t[s.reference]=!0}else t[s.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=s=>{for(const o of s)if(this.isQuery(o)){let n=!0;for(const i in e)if(o[i]!==e[i]){n=!1;break}if(n)return!0}else if(this.isQueryGroup(o)&&t(o.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(e=>e.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 s=0;for(const o of t)this.isQuery(o)?s++:this.isQueryGroup(o)&&(s+=e(o.queries));return s};return e(this.currentQuery.queries)}};const Dr=new ke;function Of(r,e,t,s,o,n,i){const a=t.excludeGroup??o,l=Dr.removeQuery({groupKey:a},oe(s)),u=i.queryData(r,l,!1,n),c=e?[...e.keys()]:[],d=new Set(c),f=n.get(o)??new Map;if(!t.excludeUnresolved)for(const p of f.keys())d.add(p);if(t.excludeUndefineds?d.delete(void 0):d.add(void 0),t.sort){const p=[];for(const v of d.values())p.push(Ko(v,f,u,e,o,a,s,!0));const y=t.excludeZeros?p.filter(v=>v.size>0):p;return y.sort(Kf(t.sort)),t.count?y.slice(0,t.count):y}const h=[];for(const p of d.values()){const y=Ko(p,f,u,e,o,a,s,!!t?.calculateFacets);if(!(t?.excludeZeros&&y.size===0)){if(t?.count&&h.length===t?.count)return h;h.push(y)}}return h}function Ko(r,e,t,s,o,n,i,a){const l=new Map,u=e.get(r)||new Set;for(const c of u){const d=t.get(c);if(d&&(l.set(c,d),!a))break}return{key:String(r),value:r,selected:Ff(n,o,r,i),enabled:l.size>0,size:l.size,entry:s?.get(r),resultKeys:Array.from(l.keys())}}function jt(r,e){if(r===void 0&&e===void 0)return 0;if(r===void 0)return 1;if(e===void 0)return-1;const t=typeof r,s=typeof e;if(t!==s)return t<s?-1:1;if(t==="number")return r-e;if(t==="string")return r.localeCompare(e);const o=String(r),n=String(e);return o<n?-1:o>n?1:0}function Kf(r){switch(r){case"size-desc":return(e,t)=>t.size-e.size||jt(e.value,t.value);case"size-asc":return(e,t)=>e.size-t.size||jt(e.value,t.value);case"value-asc":return(e,t)=>jt(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:-jt(e.value,t.value)}}const Ff=(r,e,t,s)=>{const o=Dr.findQueryGroup(r,s);return o?!!o.queries.find(n=>Dr.isQuery(n)?n.attribute!==e?!1:(n.operator==="in"&&Array.isArray(n.value)?n.value:[n.value]).some(i=>(i?.key||i)===t):!1):!1};class Mt{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 s=this.dataMap.get(e);s||(s=new Map,this.dataMap.set(e,s));for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const a of o)this.fillDataMap(e,[a]);return}else o instanceof Date?n=o.toISOString():n=o;let i=s.get(n);i||(i={key:n},this.dataMap.get(e)?.set(n,i))}}fillInverseIndex(e,t,s){if(!e||!t||!s||!Array.isArray(s))return;const o=this.indexMap.get(e)||new Map;for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const l of n)this.fillInverseIndex(e,t,[l]);return}else n instanceof Date?i=n.toISOString():i=n;let a=o.get(i);a||(a=new Set,o.set(i,a)),a.add(t)}this.indexMap.set(e,o)}getIndex(e,t){const s=this.getIndexName(e,t);return this.indexMap.get(s)}getData(e,t){const s=this.getIndexName(e,t);return this.dataMap.get(s)}getOrCreateIndex(e,t,s){const o=this.getIndexName(e,s);let n=this.getIndex(o);const i=this.indexMetadata.get(o);if(i)i.lastAccessedAt=Date.now();else if(!n){const a=P.parse(e).isDeepQuery??!1;this.indexMetadata.set(o,{createdAt:Date.now(),lastAccessedAt:Date.now(),context:s,type:a?"deep":"shallow"})}if(!n){this.reset(o),this.indexMap.set(o,new Map);const a=P.parse(e).isDeepQuery;for(const l of t.values()){let u;a?(u=de(l,e),u.length===0&&(u=[void 0])):u=[l[e]],this.fillInverseIndex(o,l.key,u),this.fillDataMap(o,u)}n=this.getIndex(o)||new Map}return n}getIndexName(e,t){return t?e+"_"+kr(t):e}removeFromInverseIndex(e,t,s){const o=this.indexMap.get(e);if(o)for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const l of n)this.removeFromInverseIndex(e,t,[l]);return}else n instanceof Date?i=n.toISOString():i=n;const a=o.get(i);a&&(a.delete(t),a.size===0&&o.delete(i))}}updateInverseIndex(e,t,s,o){this.removeFromInverseIndex(e,t,s),this.fillInverseIndex(e,t,o)}removeFromDataMap(e,t){const s=this.dataMap.get(e);if(s)for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const i of o)this.removeFromDataMap(e,[i]);return}else o instanceof Date?n=o.toISOString():n=o;s.delete(n)}}updateDataMap(e,t,s){this.removeFromDataMap(e,t),this.fillDataMap(e,s)}removeItemFromAllIndices(e){for(const t of this.indexMap.values())for(const[s,o]of t)o.delete(e)&&o.size===0&&t.delete(s);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 P.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 s of this.indexMap.keys())this.isDeepQueryIndex(s)?t++:e++;return{shallow:e,deep:t,total:e+t}}cleanupStaleIndices(e=300*1e3){const t=Date.now();let s=0;for(const[o,n]of this.indexMetadata)t-n.lastAccessedAt>e&&(this.reset(o),s++);return s}getStats(){const e=this.getIndexCount(),t=Date.now();let s=0,o=0;for(const i of this.indexMetadata.values()){const a=t-i.createdAt;s+=a,a>o&&(o=a)}const n=this.indexMetadata.size>0?s/this.indexMetadata.size:0;return{shallow:e.shallow,deep:e.deep,total:e.total,oldestAge:o,avgAge:n}}}const Ke="__";function _r(r,e,t={key:"root"},s="root",o=new Mt,n){const i=n||r;for(const a of e.columns)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.rows)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.values)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));if(e.rows&&e.rows.length>0){t.rows=t.rows||[];const a=qf(r,e.rows[0],e,o,s,n);t.rows.push(a)}if(e.columns&&e.columns.length>0){t.columns=t.columns||[];const a=Fo(r,e.columns[0],e,o,s,n);t.columns.push(a)}if(t.key==="root")for(const a of e.values){if(t.values=t.values||[],s==="root"&&e.options?.calculateTotals===!1)continue;const l=at(a,r,o.getIndex(a.attribute),a.attribute);t.values.push(l)}return t}function qf(r,e,t,s,o="",n){const i={key:e.attribute},a=s.getIndex(e.attribute);if(!a)return i;for(const[l,u]of a.entries()){const c={key:l,value:l},d=new Map;for(const f of u)r.has(f)&&d.set(f,r.get(f));if(d.size){for(const f of t.values){if(c.values=c.values||[],o==="root"&&e?.calculateTotals===!1)continue;const h=at(f,d,s.getIndex(f.attribute),f.attribute);c.values.push(h)}if(i.rows=i.rows||[],i.rows.push(c),t.rows.length>1){const f={...t,rows:t.rows.slice(1)};_r(d,f,c,o+Ke+e.attribute+Ke+l,s,n)}else if(t.columns)for(const f of t.columns){c.columns=c.columns||[];const h=Fo(d,f,t,s,o+Ke+e.attribute+Ke+l,n);c.columns.push(h)}}}return i}function Fo(r,e,t,s,o="",n){const i={key:e.attribute},a=s.getIndex(e.attribute);if(!a)return i;for(const[l,u]of a.entries()){const c={key:l,value:l},d=new Map;for(const f of u)r.has(f)&&d.set(f,r.get(f));if(d.size){for(const f of t.values){if(c.values=c.values||[],o==="root"&&e?.calculateTotals===!1)continue;const h=at(f,d,s.getIndex(f.attribute),f.attribute);c.values.push(h)}if(i.columns=i.columns||[],i.columns.push(c),t.columns.length>1){const f={...t,columns:t.columns.slice(1)};_r(d,f,c,o+Ke+e.attribute+Ke+l,s,n)}}}return i}const Qf=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/,Vf=/^-?\d+$/,Gf=/^-?\d+\.\d+$/,Bf=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,Uf=r=>r==="true"||r==="false"?"boolean":Vf.test(r)?"int":Gf.test(r)?"float":Qf.test(r)&&!Number.isNaN(Date.parse(r))?"date":"string",Nf=r=>Bf.test(r),zf=r=>r==null||r==="",Lf=r=>{const e=[...r];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}},Wf=(r,e={})=>{const t=e.deep??(e.sampleSize!==void 0&&e.sampleSize>1)?e.sampleSize??1/0:1,s=e.coerceStrings??!0,o=new Map,n=[],i=Math.min(r.length,t);for(let u=0;u<i;u++){const c=r[u];if(c)for(const[d,f]of Object.entries(c)){let h=o.get(d);if(h||(h={observed:new Set,empty:0,scanned:0},o.set(d,h),n.push(d)),h.scanned++,zf(f)){h.empty++;continue}let p;typeof f=="string"&&s?(p=Uf(f),p==="string"&&!h.hint&&Nf(f)&&(h.hint="column looks date-like (non-ISO) — review manually")):p=Hf(f),h.observed.add(p)}}const a=[],l=[];for(const u of n){const c=o.get(u),{type:d,conflict:f}=Lf(c.observed.size?c.observed:new Set(["string"]));a.push({key:u,type:d}),l.push({column:u,inferredType:d,observedTypes:[...c.observed].sort(),emptyRate:c.scanned===0?0:c.empty/c.scanned,conflict:f,hint:c.hint})}return{properties:a,diagnostics:l}},qo=(r,e=!1)=>Wf(r,typeof e=="boolean"?{deep:e}:e).properties,Qo=r=>Number(r)===r&&r%1===0,Vo=r=>Number(r)===r&&r%1!==0,Hf=r=>{switch(typeof r){case"string":return"string";case"number":return Qo(r)?"int":Vo(r)?"float":"any";case"boolean":return"boolean";case"object":return wf(r)?"date":"json";default:return"any"}};class Jf{constructor(e,t,s){this.scriptController=e,this.globalItemService=t,this.modelParser=s}scriptController;globalItemService;modelParser;registeredCustomOperator=new Map;queryBuilder=new ke;registerCustomOperator(e,t){this.registeredCustomOperator.set(e,t)}transformValue(e,t){if(Array.isArray(e))return e.map(s=>this.transformValue(s,t));if(typeof e!="string")return e;for(const s of t)s==="lowercase"?e=e.toLowerCase():s==="trim"?e=e.trim():s==="removeWhitespace"&&(e=e.replace(/\s/g,""));return e}evaluateQuery(e,t){let s=e.value;const o=e.options?.arrayValueHandling||"some";Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(s=this.transformValue(s,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 i;switch(e.operator){case"eq":i=this.queryEq(n,s,o);break;case"in":i=this.queryIn(n,s,o);break;case"find":i=this.queryFind(n,s,o,e.options?.regexFlags);break;case"lt":case"gt":case"lte":case"gte":{const a=e.operator;i=this.matchValues(n,o,l=>this.compareValue(a,l,s));break}case"typeof":i=this.matchValues(n,o,a=>typeof a===s);break;case"isTruthy":{const a=s===!0;i=this.matchValues(n,o,l=>!!l===a);break}case"size":typeof n=="string"?i=n.length===s:i=hf(n)===s;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?!i:i}compareValue(e,t,s){if(t==null)return!1;switch(e){case"lt":return t<s;case"gt":return t>s;case"lte":return t<=s;case"gte":return t>=s}}getAttributeValue(e,t){if(t in e||!(t.includes(".")||t.includes("[")))return e[t];if(t.includes("["))return ot(e,t);const s=t.split(".");let o=e;for(let n=0;n<s.length;n++){const i=s[n];if(o==null)return;if(Array.isArray(o)&&i!=="length"&&!/^\d+$/.test(i))return de(o,s.slice(n).join("."));o=o[i]}return o}matchValues(e,t,s){return Array.isArray(e)?t==="every"?e.length>0&&e.every(s):e.some(s):s(e)}queryEq(e,t,s){return Array.isArray(e)&&!Array.isArray(t)?this.matchValues(e,s,o=>this.equalsQueryValue(o,t)):this.equalsQueryValue(e,t)}queryIn(e,t,s){return!Array.isArray(t)||t.length===0?!1:this.matchValues(e,s,o=>t.some(n=>this.equalsQueryValue(o,n)))}getIndexKey(e){if(typeof e=="string")return e;if(e?.key&&Object.keys(e).length===1)return e.key}equalsQueryValue(e,t){const s=this.getIndexKey(t);return typeof s>"u"?zd(e,t):e instanceof Date?!isNaN(e.getTime())&&e.toISOString()===s:typeof e=="object"&&e?.key?e.key===s:e===s}canUseIndex(e){return e.options?.arrayValueHandling!=="every"&&!e.options?.transform?.length}evaluateEqOperator(e,t,s,o){const n=new Map,i=this.canUseIndex(t)?o.get(t.attribute):void 0;if(i){const a=this.getIndexKey(t.value);if(typeof a<"u"){const l=i.get(a);if(l)if(l.forEach(u=>{s.has(u)&&n.set(u,s.get(u))}),t.options?.invert){const u=ko(Array.from(s.values()),Array.from(n.values()),"key"),c=new Map;return u.forEach(d=>{c.set(d.key,d)}),c}else return n}}return this.scanDataset(e,t,s)}evaluateInOperator(e,t,s,o){const n=this.canUseIndex(t)?o.get(t.attribute):void 0;if(!n)return this.scanDataset(e,t,s);const i=new Map,a=[];for(const u of t.value){const c=this.getIndexKey(u),d=typeof c<"u"?n.get(c):void 0;if(!d){a.push(u);continue}d.forEach(f=>{const h=s.get(f);h&&i.set(f,h)})}if(a.length>0){const u=new Map;s.forEach((d,f)=>{i.has(f)||u.set(f,d)});const c={...t,value:a,options:{...t.options,invert:!1}};this.scanDataset(e,c,u).forEach((d,f)=>i.set(f,d))}if(!t.options?.invert)return i;const l=new Map;return s.forEach((u,c)=>{i.has(c)||l.set(c,u)}),l}scanDataset(e,t,s){const o=new Map,n=this.queryBuilder.extractQueryAttributes({queries:[t]}).filter(a=>a.isDeepQuery),i=n.length>0?this.queryBuilder.getProjectionForAttributeEntries(n):void 0;for(let[a,l]of s)i&&(l=this.globalItemService.getProjectedData(i,this.modelParser.models.get(e.modelKey),l)),this.evaluateQuery(t,l)&&o.set(a,l);return o}equalRegexFn(e,t,s){const o=Ar(t,s);if(o)try{return new RegExp(o.pattern,o.flags).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(n=>mr(n,t,(i,a)=>this.equalRegexFn(i,a,s))):typeof t=="object"?Ao(e,t):e===t}queryFind(e,t,s,o){const n=(i,a)=>this.equalRegexFn(i,a,o);return Array.isArray(e)?typeof t=="string"||typeof t=="number"||typeof t=="boolean"?this.matchValues(e,s,i=>mr(i,t,n)):t!==null&&typeof t=="object"?this.matchValues(e,s,i=>Ao(i,t)):!!Bd(e,t):mr(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 wo(e.queries,t=>this.validateQuery(t));throw new Error("invalid query - missing query or attribute")}}getEvaluatedQueryDataset(e,t,s,o){const n=new Map;if(t.attribute.includes("[*]")){const i=t.options?.invert===!0,a=new Set;for(let l of s.values()){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(d=>d.isDeepQuery)){const d=this.queryBuilder.getProjectionForAttributeEntries(u.filter(f=>f.isDeepQuery));l=this.globalItemService.getProjectedData(d,this.modelParser.models.get(e.modelKey),l)}const c=this.handleArrayStarQuery(t,l).queries.map(d=>({...d,options:{...d.options,invert:!1}}));this.matchValues(c,t.options?.arrayValueHandling||"some",d=>this.evaluateQuery(d,l))&&(a.add(l.key),i||n.set(l.key,l))}if(i)for(const[l,u]of s)a.has(l)||n.set(l,u)}else return t.operator==="eq"?this.evaluateEqOperator(e,t,s,o):t.operator==="in"?this.evaluateInOperator(e,t,s,o):this.scanDataset(e,t,s);return n}handleArrayStarQuery(e,t){const s=e.attribute.indexOf("[*]"),o={groupKey:e.queryKey||e.attribute+"[*]",groupType:"or",queries:[]};if(s!==-1){const n=e.attribute.substring(0,s),i=n.includes(".")?ot(t,n):t[n];if(Array.isArray(i))for(let a=0;a<i.length;a++){const l=e.attribute.replace("[*]",`[${a}]`);o.queries.push({attribute:l,operator:e.operator,value:e.value,options:e.options})}}return o}evaluateQueryGroup(e,t,s,o,n){let i=new Map,a=s;if(!t.queries||t.queries?.length===0)return a;const l=t.groupType==="or";for(const u of t.queries){let c=new Map;if(this.queryBuilder.isQuery(u)?c=this.getEvaluatedQueryDataset(e,u,a,n):c=this.evaluateQueryGroup(e,u,a,o,n),i.size===0&&(i=c),l)c.forEach(d=>{i.set(d.key,d)}),a=s;else{const d=ko(Array.from(i.values()),Array.from(c.values()),"key");for(const f of d)i.delete(f.key);a=i}}return i}queryData(e,t,s,o){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,s,o)}}function Z(){const r=globalThis;return typeof r.scheduler?.yield=="function"?r.scheduler.yield():typeof r.setImmediate=="function"?new Promise(e=>r.setImmediate(()=>e())):typeof r.MessageChannel=="function"?new Promise(e=>{const t=new r.MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)}):new Promise(e=>setTimeout(e,0))}class Zf{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 s=this.getScript(e);if(!s)throw new Error(`Script ${e} not found`);const o=this.getWrapperScript(s),n=new Function("script_type",...t,o);return this.scriptFunctions.set(e,n),n}getWrapperScript(e){return`
|
|
3
3
|
"use strict";
|
|
4
4
|
${e}
|
|
5
|
-
`}executeScript(e,t,s){if(!this.getScript(e))throw new Error(`Script ${e} not found`);s.context||(s.context=s.options||{});const o=Object.keys(s),n=Object.values(s);return this.getScriptAsFn(e,o)(t,...n)}}const Rt=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>ot(e,s.trim(),""))):"",xr=r=>{const e=new Set;return r.replace(/\$\{(.*?)\}/g,(t,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(t=>({name:t}))}};var Yf=rr(function(r,e){return Ie(r)?bo(r,Fs(e,1,Ie)):[]});let Xf=class{constructor(e,t,s,o,n){this.modelParser=e,this.cdRef=t,this.item=s,this.indicesController=o,this.queryManager=n,this.cacheCtrl=new bf(!!this.cdRef.dcuplInitOptions.performance?.cache?.enabled)}modelParser;cdRef;item;indicesController;queryManager;initialData;_filteredData;filteredDataStale=!1;model;get filteredData(){return this.filteredDataStale&&(this.filteredDataStale=!1,this._filteredData=this.getFilteredData(this.initialData,!1)),this._filteredData}set filteredData(e){this._filteredData=e,this.filteredDataStale=!1}filterItems=new Map;queryBuilder;cacheCtrl;projectionCache=new Map;init(e,t){this.model=e,this.initialData=t,this.filteredData=this.initialData,this.queryBuilder=new ke,this.queryBuilder.init({modelKey:e.key}),this.initFilterItems({skipProcessing:!0})}indexDependsOnAttributes(e,t){const s=e.includes("_")?e.split("_")[0]:e;try{const o=P.parse(s);if(!o.isDeepQuery)return!1;const n=o.attribute.split(".");for(let i=0;i<n.length-1;i++)if(t.has(n[i]))return!0;return!1}catch{return!0}}invalidateAllCaches(e){this.cacheCtrl.clear(),this.projectionCache.clear();let t=0;if(e&&e.size>0){const o=this.indicesController.getDeepIndexKeys(),n=[];for(const i of o)this.indexDependsOnAttributes(i,e)&&n.push(i);for(const i of n)this.indicesController.reset(i);t=n.length}else{const o=this.indicesController.getIndexCount().deep;this.indicesController.resetAllDeepIndices(),t=o}const s=this.cdRef.dcuplInitOptions.logging;if(s&&s.level==="debug"){const o=this.indicesController.getIndexCount();console.debug("[Filter] Caches invalidated",{granular:e!==void 0,changedAttributes:e?Array.from(e):"all",deepIndicesReset:t,shallowIndicesPreserved:o.shallow,totalIndices:o.total})}}update(e,t,s){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}updateWithChanges(e,t,s,o){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(o),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}resetCache(){this.invalidateAllCaches(),this.filteredDataStale=!0}getDeepQueryAttributes(e){const t=new Set;if(!e||!e.queries)return[];for(const s of e.queries)if(s.queries)for(const o of s.queries)o.attribute&&P.parse(o.attribute).isDeepQuery&&t.add(o.attribute);return Array.from(t)}getProjectionForQuery(e){const t=this.getDeepQueryAttributes(e);if(t.length===0)return null;const s=t.map(o=>P.parse(o));return this.queryBuilder.getProjectionForAttributeEntries(s)}getProjectionCacheKey(e){const t=this.getDeepQueryAttributes(e);return t.length===0?"":t.sort().join("|")}getProjectedData(e,t,s){if(s&&this.projectionCache.has(s))return this.projectionCache.get(s);const o=new Map;for(const[n,i]of e){const a=this.item.getProjectedData(t,this.model,i);o.set(n,a)}return s&&this.projectionCache.set(s,o),o}getProjectedInitialData(e){const t=new Set(this.getDeepQueryAttributes(this.queryBuilder.getQuery()));t.add(e);const s=Array.from(t).sort(),o=this.queryBuilder.getProjectionForAttributeEntries(s.map(n=>P.parse(n)));return this.getProjectedData(this.initialData,o,s.join("|"))}initFilterItems(e){[...this.model.properties.values(),...this.model.references.values()].forEach(t=>{t.filter&&(Array.isArray(e?.filterKeys)?e?.filterKeys.includes(t.key)&&this.updateFilterItem(t.key,e):this.updateFilterItem(t.key,e))})}getAggregate(e,t,s){if(P.parse(e.attribute).isDeepQuery)return at(e,t,s,e.attribute);{const o=this.model.getAttribute(e.attribute);if(!o)throw new Error("Attribute not found");return at(e,t,s,o.key)}}getSections(e){const t={_meta:{currentSize:0,initialSize:0},items:[]},s=P.parse(e.attribute),o=s.isDeepQuery;let n;if(!o&&(n=this.model.getAttribute(e.attribute),!n))throw new Error("Attribute not found");let i=new Map,a;!o&&n&&(n.type==="singleValued"||n.type==="multiValued")&&(a=this.modelParser.models.get(n.model));const l={},u=this.getSortingProjectionForModel(e,this.model);l.sort=u;let c=this.item.getItemsAsMap(this.filteredData,this.model,l);if(o){const p=this.queryBuilder.getProjectionForAttributeEntries([s]),y=new Map;for(const[v,g]of c){const k=this.item.getProjectedData(p,this.model,g);y.set(v,k)}c=y}const d=this.indicesController.getOrCreateIndex(`${e.attribute}`,c,{childLevelSorting:u,query:this.queryBuilder.getQuery()}),f=this.getAggregate({attribute:e.attribute,types:["distinct"],excludeUndefineds:!0},c,d);if(f.distinct)for(const p of f.distinct){let y={key:p.value,value:p.value};const v=p.keys.filter(k=>c.has(k));if(a){const k=a.data.get(p.value);k&&(y=k)}const g={...y,key:p.value,_items:[],_aggregates:[],_meta:{size:v.length}};i.set(p.value,g)}const h={count:e.count,start:e.start,projection:e.projection};if(a){const p=this.getSortingProjectionForModel(e,a);h.sort=p}if(t._meta.currentSize=i.size,t._meta.initialSize=f.distinct.length,i=this.item.getItemsAsMap(i,a,h),Array.isArray(e?.aggregates)&&i.forEach(p=>{const y=f.distinct.find(g=>g.value===p.key),v=this.getDataByKeys(c,y.keys);p._aggregates=e.aggregates.map(g=>{const k=this.indicesController.getOrCreateIndex(`${g.attribute}`,v,{section:p.key,childLevelSorting:u,query:this.queryBuilder.getQuery()});return this.getAggregate(g,v,k)})}),e?.items){const p=e.items?.find(y=>y.key==="*");p?i.forEach(y=>{const v=f.distinct.find(m=>m.value===y.key),g=this.getDataByKeys(c,v.keys),k=this.item.getItems(g,this.model,p);y._items=k}):i.forEach(y=>{const v=e.items?.find(g=>g.key===y.key);if(v){const g=f.distinct.find(M=>M.value===y.key),k=this.getDataByKeys(c,g.keys),m=this.item.getItems(k,this.model,v);y._items=m}})}return t.items=Array.from(i.values()),t}getSortingProjectionForModel(e,t){const s={attributes:[],order:[]};return e?.sort?.attributes.forEach((o,n)=>{if(t.properties.has(o)){s.attributes.push(o);const i=e.sort?.order;s.order.push(i[n])}}),s}getReferenceKeyForFilterKey(e){const t=this.filterItems.get(e);return t?.attributeKey||t?.key||e}updateFilterItem(e,t={}){const s={calculateFacets:!1,excludeZeros:!0,excludeUndefineds:!0,excludeUnresolved:!0,skipProcessing:!1},o=this.getReferenceKeyForFilterKey(e);if(!o)return;const n=this.model.references.get(o);let i={};if(typeof n?.filter=="object"?i=Object.assign(s,n.filter,t):i=Object.assign(s,t),n){this.updateFilterItemReference(n.key,n.key,i);return}const a=this.model.properties.get(o);if(a)if(Array.isArray(a.filter)){a.filter.forEach(l=>{const u=l?.comparisonType||"containsIgnoreCase";this.updateFilterItemProperty(l.key,a.key,a.type,u,i)});return}else{const l=a.filter?.comparisonType||"containsIgnoreCase";this.updateFilterItemProperty(a.key,a.key,a.type,l,i);return}if(e==="key"){this.updateFilterItemProperty("key","key","string","containsIgnoreCase",i);return}}updateFilterItemReference(e,t,s){let o=[];const n=this.model.references.get(t);if(n&&!s.skipProcessing){const a=this.modelParser.models.get(n.model);o=this.getFacets(n.key,a,s)}const i={key:e,attributeKey:t,enabled:!!o.find(a=>a.enabled),selected:!!o.find(a=>a.selected),type:"reference",entries:o};this.filterItems.set(i.key,i)}updateFilterItemProperty(e,t,s,o,n){const i=this.getFilterTypeForPropertyType(s),a=this.queryBuilder.hasQueryGroup(e),l={key:e,attributeKey:t,enabled:!0,selected:!!a,type:i};if(l.type==="text"&&(l.comparisonType=o),l.type==="boolean"){const u=this.getFacets(l.attributeKey,void 0,n);l.entries=u}n.skipProcessing||(l.type==="number"&&(l.range=this.getNumberRangesForFilterItem(l)),l.type==="date"&&(l.range=this.getDateRangesForFilterItem(l))),this.filterItems.set(l.key,l)}getNumberRange(e,t=e){let s=1/0,o=-1/0;for(const a of this.filteredData.values()){const l=a[e];if(!(typeof l>"u"||l===null))if(Array.isArray(l))for(const u of l)typeof u=="number"&&(u<s&&(s=u),u>o&&(o=u));else typeof l=="number"&&(l<s&&(s=l),l>o&&(o=l))}let n=1/0,i=-1/0;for(const a of this.initialData.values()){const l=a[e];if(!(typeof l>"u"||l===null))if(Array.isArray(l))for(const u of l)typeof u=="number"&&(u<n&&(n=u),u>i&&(i=u));else typeof l=="number"&&(l<n&&(n=l),l>i&&(i=l))}return s===1/0&&(s=0),o===-1/0&&(o=0),n===1/0&&(n=0),i===-1/0&&(i=0),{available:{min:s,max:o},initial:{min:n,max:i},relatedQuery:this.queryBuilder.getQueryGroup(t)}}getNumberRangesForFilterItem(e){return this.getNumberRange(e.attributeKey,e.key)}getDateRangesForFilterItem(e){return this.getDateRange(e.attributeKey,e.key)}getDateRange(e,t=e){let s=null,o=null;for(const l of this.filteredData.values()){const u=l[e];if(typeof u>"u"||u===null)continue;const c=Array.isArray(u)?u:[u];for(const d of c)d instanceof Date&&((!s||d<s)&&(s=d),(!o||d>o)&&(o=d))}let n=null,i=null;for(const l of this.initialData.values()){const u=l[e];if(typeof u>"u"||u===null)continue;const c=Array.isArray(u)?u:[u];for(const d of c)d instanceof Date&&((!n||d<n)&&(n=d),(!i||d>i)&&(i=d))}const a=new Date;return s||(s=a),o||(o=a),n||(n=a),i||(i=a),{available:{min:s,max:o},initial:{min:n,max:i},relatedQuery:this.queryBuilder.getQueryGroup(t)}}getFacets(e,t,s,o){let n;const i=this.cacheCtrl.generateContext({attributeKey:e,query:this.queryBuilder.getQuery(),options:s}),a=this.cacheCtrl.get("facets",i);if(a)return a;let l=new Map;n=this.indicesController.getIndex(e),t?l=t.getData():l=this.indicesController.getData(e);let u=o||this.initialData;if(!o){const d=this.queryBuilder.getQueryAttributeForString(e);if(d.isDeepQuery){const f=this.queryBuilder.getProjectionForAttributeEntries([d]);u=this.item.getItemsAsMap(u,this.model,{projection:f})}}if(!n||!l){this.indicesController.reset(e);const d=P.parse(e),f=d.isDeepQuery;let h=u;if(f){const p=this.queryBuilder.getProjectionForAttributeEntries([d]);h=new Map;for(const[y,v]of u){const g=this.item.getProjectedData(p,this.model,v);h.set(y,g)}}h.forEach(p=>{let y;f?(y=de(p,e),y.length===0&&(y=[void 0])):y=[p[e]],this.indicesController.fillInverseIndex(e,p.key,y),this.indicesController.fillDataMap(e,y)}),n=this.indicesController.getIndex(e),t||(l=this.indicesController.getData(e))}const c=Of(u,l,s,this.queryBuilder.getQuery(),e,this.indicesController.indexMap,this.queryManager);return this.cacheCtrl.set("facets",i,c,{models:new Set([this.model.key]),modelAttributes:new Map([[this.model.key,new Set([e])]])}),c}getDataByKeys(e,t){if(t){const s=new Map;return t.forEach(o=>{const n=e.get(o);n&&s.set(n.key,n)}),s}return e}getFilterTypeForPropertyType(e){switch(e){case"string":return"text";case"int":return"number";case"float":return"number";case"date":return"date";case"boolean":return"boolean";case"json":return"text";case"any":return"text";case"Array<string>":return"text";case"Array<int>":return"number";case"Array<float>":return"number";case"Array<date>":return"date"}}updateFilteredData(e){const t=ce.now();e?.skipProcessing||(this.filteredData=this.getFilteredData(this.initialData,!1),this.emitResultUpdated(t))}emitResultUpdated(e=ce.now()){this.cdRef.trigger({scope:"list",type:"result_updated",action:"update",connectMessage:!0,listKey:this.cdRef.key,modelKey:this.model.key,start:e})}getFilteredData(e,t){const s=this.cacheCtrl.generateContext({query:this.queryBuilder.getQuery(),earlyReturn:t}),o=this.cacheCtrl.get("data",s);if(o)return o;const n=this.queryBuilder.getQuery(),i=this.getProjectionForQuery(n);let a;if(i){const l=this.getProjectionCacheKey(n),u=this.getProjectedData(e,i,l),c=this.queryManager.queryData(u,n,t,this.indicesController.indexMap);a=new Map;for(const d of c.keys())e.has(d)&&a.set(d,e.get(d))}else a=this.queryManager.queryData(e,n,t,this.indicesController.indexMap);return this.cacheCtrl.set("data",s,a,{models:new Set([this.model.key]),modelAttributes:new Map}),a}getFilterItems(e){if(Array.isArray(e?.filterKeys)){const t=[];return e?.filterKeys.forEach(s=>{const o=this.getFilterItem(s,e);o&&t.push(o)}),t}else return e?.skipProcessing||this.initFilterItems(e),Array.from(this.filterItems.values())}getFilterItem(e,t){return this.filterItems.has(e)&&(t?.skipProcessing||this.updateFilterItem(e,t)),this.filterItems.get(e)}},Go=class{constructor(e,t){this.modelParser=e,this.scriptController=t}modelParser;scriptController;getItem(e,t,s,o){const n=o?.projection||{$:!0},i=t.get(e);return i?this.getProjectedData(n,s,i):null}getManyItems(e,t,s,o){const n=[];for(const i of e){const a=o?.projection||{$:!0},l=t.get(i);if(!l)continue;const u=this.getProjectedData(a,s,l);n.push(u)}return n}getItems(e,t,s){const o=this.getItemsAsMap(e,t,s);return Array.from(o.values())}getItemsAsMap(e,t,s){const o=s?.start||0,n=s?.count??e.size,i=s?.projection||{$:!0};return this.isValidSortProjection(s?.sort)&&(e=this.getSortedItems(e,s,t)),this.isValidScriptSorting(s?.sort)&&(e=this.getSortedItemsBasedOnScript(e,s)),this.getPagedData(e,o,n,i,t)}getSortedItemsBasedOnScript(e,t){const s=Array.from(e.values()),o=t?.sort?.script?.key||"",n=t?.sort?.script?.options||void 0;if(!this.scriptController.hasScript(o))return e;const i=this.scriptController.executeScript(o,"sort",{options:n,items:s});return new Map(i.map(a=>[a.key,a]))}getSortedItems(e,t,s){const o=[...t.sort.attributes],n=Array.from(e.values()),i=(c,d,f)=>{const h=c[d];return typeof h>"u"||h===null?f:typeof h=="string"?h.toLowerCase():typeof h=="object"&&typeof h?.key=="string"?h.key.toLowerCase():h},a=o.map((c,d)=>f=>{const h=t.sort.order.at(d),p=this.getUndefinedValueForSorting(c,h,s);return i(f,c,p)}),l=[...t.sort.order].map(c=>c.toLowerCase()),u=$o(n,[...a],l);return new Map(u.map(c=>[c.key,c]))}getUndefinedValueForSorting(e,t,s){const o=s?.properties.get(e);if(o){if(o.type==="string"){if(t=="ASC")return;if(t=="DESC")return""}if(o.type==="int"||o.type==="float"||o.type==="date"||o.type==="boolean"){if(t=="ASC")return 1/0;if(t=="DESC")return-1/0}}}isValidProjection(e){return!(!e||e.$===!0&&Object.keys(e).length===1)}getPagedData(e,t,s,o,n){const i=e.entries(),a=new Map;if(t===0&&s===e.size&&o?.$===!0&&Object.keys(o).length===1)return e;for(let l=0;l<t+s;l++){if(l<t){i.next();continue}if(l>t+s)break;const u=i.next().value;if(u)if(n&&o&&this.isValidProjection(o)){const c=this.getProjectedData(o,n,u[1]);a.set(u[0],c)}else a.set(u[0],u[1])}return a}isValidScriptSorting(e){return!(!e||!e.script)}isValidSortProjection(e){const t=["ASC","DESC"];return!(!e||!Array.isArray(e.attributes)||e.attributes.length===0||!Array.isArray(e.order)||e.attributes.length!==e.order.length||Yf(e.order,t).length>0)}getProjectedData(e,t,s){let o={key:s.key};return e.$===!0&&(o=Object.assign({},s)),e.$$===!0&&(o=Object.assign({},s),t.references.forEach(n=>{e[n.key]||(e[n.key]={$:!0})})),Object.keys(e).filter(n=>n!=="$"&&n!=="$$").forEach(n=>{const i=e[n];if(i===!1){delete o[n];return}if(i===!0){o[n]=s[n];return}if(typeof i=="object"){const a=t.references.get(n);if(a){const l=this.modelParser.models.get(a.model);if(l){if(a.type==="multiValued"){const u=s[n]||[];o[n]=u.map(c=>{const d=typeof c=="string"?c:c.key,f=l.getEntry(d);return f?this.getProjectedData(i,l,f):this.modelParser.initOptions.referenceMetadata?.enabled?{key:d,_dcupl_ref_:"miss"}:null}).filter(Boolean)}else if(a.type==="singleValued"){const u=s[n];if(u){const c=typeof u=="string"?u:u.key,d=l?.getEntry(c);d?o[n]=this.getProjectedData(i,l,d):this.modelParser.initOptions.referenceMetadata?.enabled?o[n]={key:c,_dcupl_ref_:"miss"}:delete o[n]}}}}}}),o}};var ep=Object.defineProperty,tp=Object.getOwnPropertyDescriptor,I=(r,e,t,s)=>{for(var o=tp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&ep(e,t,o),o};let j=class{constructor(e,t,s){this.dcuplApi=e,this.cdRef=t,this.indicesController=s,this.itemService=new Go(this.dcuplApi.modelParser,this.dcuplApi.scriptController),this.filter=new Xf(this.dcuplApi.modelParser,this.cdRef,this.itemService,this.indicesController,this.dcuplApi.queryManager)}dcuplApi;cdRef;indicesController;metadata;model;filter;itemService;log=Te.child({prefix:"Catalog"});initListeners(){this.initListMetadata()}initListMetadata(){this.metadata={key:this.model.key,currentSize:this.filter.filteredData.size,initialSize:this.filter.initialData.size,attributes:this.getModelAttributes(),views:this.getViews(),appliedQuery:this.filter.queryBuilder.getQuery()}}getModelAttributes(){return[...this.model.references.values(),...this.model.properties.values()]}query={apply:(e,t)=>this.applyQuery(e,t),applyOptions:(e,t)=>this.applyOptions(e,t),remove:e=>this.removeQuery(e),reset:(e={skipProcessing:!1})=>this.resetQuery(e),execute:e=>this.executeQuery(e),one:e=>this._getItem(e),many:e=>this._getManyItems(e),get:()=>this.getQuery(),has:e=>this.hasGroupOrQueryKey(e),addCondition:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setCondition:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),addGroup:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setGroup:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),removeCondition:(e,t)=>{if(Array.isArray(e)){for(const s of e)this.removeQuery(s,t);return this.getQuery()}return this.removeQuery(e,t)},removeGroup:(e,t)=>this.removeQuery({groupKey:e},t),clear:e=>this.resetQuery(e),current:()=>this.getQuery(),isEmpty:()=>this.getQuery().queries.length===0,items:e=>this.executeQuery(e),first:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t)[0]},any:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t).length>0},count:e=>this.executeQuery(e).length};filters={get:e=>this.getFilter(e),getAll:e=>this.getFilters(e)};fn={pivot:e=>this._getPivot(e),aggregate:e=>this.getAggregate(e),suggest:e=>this._getSuggestions(e),groupBy:e=>this._getSections(e),facets:e=>this._getFacets(e),metadata:()=>this._getMetadata()};getViews(){const e=[];return this.filter.modelParser.views.forEach(t=>{t.model===this.model.key&&e.push(t)}),e}_getMetadata(){return this.initListMetadata(),this.metadata}getFilters(e){return this._getFilters(e)}_getFilters(e){const t=this.filter.getFilterItems(e);return e?.filterKeys?e.filterKeys.map(s=>{const o=t.find(n=>n.key===s);return o||this.log.error("Filter not found",void 0,{filterKey:s,model:this.model.key}),o}).filter(Boolean):t}getFilter(e){return this._getFilter(e)}_getFilter(e){return this.filter.getFilterItem(e.filterKey,e)}getQuery(){return this.filter.queryBuilder.getQuery()}hasGroupOrQueryKey(e){return this.filter.queryBuilder.has(e)}applyQuery(e,t){const s=this.filter.queryBuilder.applyQuery(e,t);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}applyOptions(e,t){const s=this.filter.queryBuilder.applyOptions(e,t?.mode);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}removeQuery(e,t){let s;return e?s=this.filter.queryBuilder.removeQuery(e):s=this.filter.queryBuilder.removeAllQueries(),this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}resetQuery(e){const t=this.filter.queryBuilder.reset();return this.filter.updateFilteredData({skipProcessing:e?.skipProcessing}),t}executeQuery(e){if(!e)e=this.filter.queryBuilder.getQuery();else if(!e.queries){const i=this.filter.queryBuilder.getQuery();e=Object.assign({},i,e)}const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("query",t))return this.filter.cacheCtrl.get("query",t);const s=Object.assign({},e,{modelKey:this.model.key}),o=this.dcuplApi.queryManager.queryData(this.filter.filteredData,s,!1,this.filter.indicesController.indexMap),n=this.itemService.getItems(o,this.model,e);return this.filter.cacheCtrl.set("query",t,n),n}_getSections(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("sections",t))return this.filter.cacheCtrl.get("sections",t);const s=this.filter.getSections(e);return this.filter.cacheCtrl.set("sections",t,s),s}_getItem(e){return this.itemService.getItem(e.itemKey,this.filter.filteredData,this.model,e)}_getManyItems(e){return this.itemService.getManyItems(e.itemKeys,this.filter.filteredData,this.model,e)}_getSuggestions(e){typeof e.excludeUndefineds>"u"&&(e.excludeUndefineds=!0),typeof e.excludeNulls>"u"&&(e.excludeNulls=!0),typeof e.calculateResultKeys>"u"&&(e.calculateResultKeys=!0);const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("suggestions",t))return this.filter.cacheCtrl.get("suggestions",t);const s=P.parse(e.attribute).isDeepQuery;if(!s&&!this.model.getAttribute(e.attribute))throw new Error(`Attribute ${e.attribute} does not exist`);const o=$r(e.value,e.regexFlags);if(o)try{new RegExp(o.pattern,o.flags)}catch{return[]}let n,i;if(e.relevantData==="all")n=this.filter.initialData,i={modelKey:this.model.key,queries:[]};else if(e.relevantData==="filtered")n=this.filter.filteredData,i=this.filter.queryBuilder.getQuery();else if(e.relevantData==="excludeQuery"&&e.excludeQuery){const c=new ke;c.init(this.filter.queryBuilder.getQuery()),c.removeQuery(e.excludeQuery),i=c.getQuery(),n=this.dcuplApi.queryManager.queryData(this.filter.initialData,i,!1,this.filter.indicesController.indexMap)}else n=this.filter.filteredData,i=this.filter.queryBuilder.getQuery();let a=n;if(s){const c=P.parse(e.attribute),d=this.filter.queryBuilder.getProjectionForAttributeEntries([c]),f=new Map;for(const[h,p]of n){const y=this.filter.item.getProjectedData(d,this.model,p);f.set(h,y)}a=f}const l=this.filter.indicesController.getOrCreateIndex(e.attribute,a,{query:i}),u=kf(a,l,e,this.dcuplApi.queryManager);return this.filter.cacheCtrl.set("suggestions",t,u),u}_getFacets(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("facets",t))return this.filter.cacheCtrl.get("facets",t);const s=P.parse(e.attribute).isDeepQuery;let o;if(!s){const i=this.model.references.get(e.attribute);i&&(o=this.filter.modelParser.models.get(i.model))}const n=s?this.filter.getProjectedInitialData(e.attribute):void 0;return this.computeFacetsInternal(e,o,t,n)}computeFacetsInternal(e,t,s,o){typeof e.excludeZeros>"u"&&(e.excludeZeros=!0),typeof e.excludeUndefineds>"u"&&(e.excludeUndefineds=!0),typeof e.excludeUnresolved>"u"&&(e.excludeUnresolved=!0),typeof e.calculateResults>"u"&&(e.calculateResults=!0);const n=this.filter.getFacets(e.attribute,t,{calculateFacets:e.calculateResults,count:e.count,excludeZeros:e.excludeZeros,excludeUndefineds:e.excludeUndefineds,excludeUnresolved:e.excludeUnresolved,sort:e.sort,excludeGroup:e.excludeGroup,skipProcessing:!1},o);return this.filter.cacheCtrl.set("facets",s,n),n}getAggregate(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("aggregation",t))return this.filter.cacheCtrl.get("aggregation",t);const s=P.parse(e.attribute);let o=this.filter.filteredData;if(s.isDeepQuery){const i=this.filter.queryBuilder.getProjectionForAttributeEntries([s]),a=new Map;for(const[l,u]of this.filter.filteredData){const c=this.filter.item.getProjectedData(i,this.model,u);a.set(l,c)}o=a}const n=this.filter.getAggregate(e,o,this.filter.indicesController.getOrCreateIndex(e.attribute,o,this.filter.queryBuilder.getQuery()));return this.filter.cacheCtrl.set("aggregation",t,n),n}_getPivot(e){if(!e||!Array.isArray(e.columns)||!Array.isArray(e.rows)||!e.values||!e.values.length)return this.log.error("Invalid pivot options",void 0,{model:this.model.key}),{key:"invalid_options"};const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("pivot",t))return this.filter.cacheCtrl.get("pivot",t);let s=new Mt;this.filter.filteredData.size===this.filter.initialData.size&&(s=this.filter.indicesController);const o=[...e.rows.map(a=>a.attribute),...e.columns.map(a=>a.attribute),...e.values.map(a=>a.attribute)].map(a=>P.parse(a)).filter(a=>a.isDeepQuery);let n;if(o.length>0){const a=this.filter.queryBuilder.getProjectionForAttributeEntries(o);n=new Map;for(const[l,u]of this.filter.filteredData){const c=this.filter.item.getProjectedData(a,this.model,u);n.set(l,c)}}const i=Pr(this.filter.filteredData,e,{key:"root"},"root",s,n);return this.filter.cacheCtrl.set("pivot",t,i),i}};I([b({scope:"list",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getMetadata"),I([b({scope:"list",type:"filter_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFilters"),I([b({scope:"list",type:"filter_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFilter"),I([b({scope:"list",type:"query_get",cloneResult:!0})],j.prototype,"getQuery"),I([b({scope:"list",type:"query_has"})],j.prototype,"hasGroupOrQueryKey"),I([b({scope:"list",type:"query_apply",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"applyQuery"),I([b({scope:"list",type:"query_apply_options",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"applyOptions"),I([b({scope:"list",type:"query_remove",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"removeQuery"),I([b({scope:"list",type:"query_reset",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"resetQuery"),I([b({scope:"list",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"executeQuery"),I([b({scope:"list",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getSections"),I([b({scope:"list",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getItem"),I([b({scope:"list",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getManyItems"),I([b({scope:"list",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getSuggestions"),I([b({scope:"list",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFacets"),I([b({scope:"list",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"getAggregate"),I([b({scope:"list",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getPivot");let rp=class extends j{constructor(e,t,s){super(e,t,s),this.dcuplApi=e,this.cdRef=t,this.indicesController=s}dcuplApi;cdRef;indicesController;listKey;init(e,t,s){this.listKey=e,this.model=t,this.filter.init(t,s),super.initListeners()}update(e,t,s){this.model=e,this.filter.update(e,t,s)}};function sp(r,e){var t=-1,s=r.length;for(e||(e=Array(s));++t<s;)e[t]=r[t];return e}function op(r,e,t,s){var o=!t;t||(t={});for(var n=-1,i=e.length;++n<i;){var a=e[n],l=void 0;l===void 0&&(l=r[a]),o?$t(t,a,l):As(t,a,l)}return t}function np(r,e,t){if(!z(t))return!1;var s=typeof e;return(s=="number"?te(t)&&tr(e,t.length):s=="string"&&e in t)?Je(t[e],r):!1}function ip(r){return rr(function(e,t){var s=-1,o=t.length,n=o>1?t[o-1]:void 0,i=o>2?t[2]:void 0;for(n=r.length>3&&typeof n=="function"?(o--,n):void 0,i&&np(t[0],t[1],i)&&(n=o<3?void 0:n,o=1),e=Object(e);++s<o;){var a=t[s];a&&r(e,a,s,n)}return e})}function ap(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var lp=Object.prototype,up=lp.hasOwnProperty;function cp(r){if(!z(r))return ap(r);var e=or(r),t=[];for(var s in r)s=="constructor"&&(e||!up.call(r,s))||t.push(s);return t}function Bo(r){return te(r)?Ss(r,!0):cp(r)}var dp="[object Object]",fp=Function.prototype,pp=Object.prototype,Uo=fp.toString,hp=pp.hasOwnProperty,yp=Uo.call(Object);function gp(r){if(!K(r)||ee(r)!=dp)return!1;var e=qs(r);if(e===null)return!0;var t=hp.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Uo.call(t)==yp}function mp(r,e,t,s){for(var o=-1,n=r==null?0:r.length;++o<n;){var i=r[o];e(s,i,t(i),r)}return s}function vp(r,e,t,s){return gr(r,function(o,n,i){e(s,o,t(o),i)}),s}function bp(r,e){return function(t,s){var o=E(t)?mp:vp,n={};return o(t,r,Re(s),n)}}function Er(r,e,t){(t!==void 0&&!Je(r[e],t)||t===void 0&&!(e in r))&&$t(r,e,t)}function jr(r,e){if(!(e==="constructor"&&typeof r[e]=="function")&&e!="__proto__")return r[e]}function kp(r){return op(r,Bo(r))}function wp(r,e,t,s,o,n,i){var a=jr(r,t),l=jr(e,t),u=i.get(l);if(u){Er(r,t,u);return}var c=n?n(a,l,t+"",r,e,i):void 0,d=c===void 0;if(d){var f=E(l),h=!f&&Ye(l),p=!f&&!h&&ir(l);c=l,f||h||p?E(a)?c=a:Ie(a)?c=sp(a):h?(d=!1,c=Us(l,!0)):p?(d=!1,c=Xs(l,!0)):c=[]:gp(l)||Ze(l)?(c=a,Ze(a)?c=kp(a):(!z(a)||Yt(a))&&(c=eo(l))):d=!1}d&&(i.set(l,c),o(c,l,s,n,i),i.delete(l)),Er(r,t,c)}function No(r,e,t,s,o){r!==e&&vo(e,function(n,i){if(o||(o=new L),z(n))wp(r,e,i,t,No,s,o);else{var a=s?s(jr(r,i),n,i+"",r,e,o):void 0;a===void 0&&(a=n),Er(r,i,a)}},Bo)}var Ap=Object.prototype,$p=Ap.hasOwnProperty,Sr=bp(function(r,e,t){$p.call(r,t)?r[t].push(e):$t(r,t,[e])}),Cp="[object Boolean]";function Dp(r){return r===!0||r===!1||K(r)&&ee(r)==Cp}var lt=ip(function(r,e,t){No(r,e,t)});const V=(r,e,t)=>({title:r,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",attribute:e,description:t}),_p=r=>{const e=["any","Array<date>","Array<float>","Array<int>","Array<string>","boolean","date","float","int","json","string"];if(!r.key)return V("Invalid Property",r.key,"Property key is missing");if(!r.type||e.indexOf(r.type)===-1)return V("Invalid Property",r.key,"Property type is invalid");if("derive"in r){if(!r.derive?.localReference)return V("Invalid Property",r.key,"Derived Property localReference is missing");if(!r.derive.remoteProperty)return V("Invalid Property",r.key,"Derived Property remoteProperty is missing")}if("expression"in r&&typeof r.expression!="string")return V("Invalid Property",r.key,"Expression is invalid")},Pp=r=>{const e=["multiValued","singleValued"];if(!r.key)return V("Invalid Reference",r.key,"Reference key is missing");if(!r.type||e.indexOf(r.type)===-1)return V("Invalid Reference",r.key,"Reference type is invalid");if(!r.model)return V("Invalid Reference",r.key,"Reference model is missing");if("derive"in r){if(!r.derive.localReference)return V("Invalid Reference",r.key,"Derived Reference localReference is missing");if(!r.derive.remoteReference)return V("Invalid Reference",r.key,"Derived Reference remoteReference is missing")}if("resolve"in r){if(!r.resolve.reference)return V("Invalid Reference",r.key,"Resolved Reference reference is missing");if(!r.resolve.model)return V("Invalid Reference",r.key,"Resolved Reference model is missing")}if("groupBy"in r&&!r.groupBy.reference)return V("Invalid Reference",r.key,"Grouped Reference reference is missing")},xp=r=>{if(typeof r.key!="string"||r.key.length===0)throw new Error("Invalid Model: key must be a non-empty string");if(typeof r.keyProperty<"u"){const e=r.keyProperty,t=typeof e=="string"&&e.length>0,s=Array.isArray(e)&&e.length>0&&e.every(o=>typeof o=="string"&&o.length>0);if(!t&&!s)throw new Error("Invalid Model: keyProperty must be a non-empty string or a non-empty array of non-empty strings")}if(typeof r.keyPropertySeparator<"u"&&(typeof r.keyPropertySeparator!="string"||r.keyPropertySeparator.length===0))throw new Error("Invalid Model: keyPropertySeparator must be a non-empty string");if(typeof r.autoGenerateKey<"u"&&typeof r.autoGenerateKey!="boolean")throw new Error("Invalid Model: autoGenerateKey must be a boolean");if(typeof r.autoGenerateProperties<"u"){const e=r.autoGenerateProperties;if(typeof e!="boolean"){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("Invalid Model: autoGenerateProperties must be a boolean or an options object");if(typeof e.deep<"u"&&typeof e.deep!="boolean")throw new Error("Invalid Model: autoGenerateProperties.deep must be a boolean");if(typeof e.sampleSize<"u"&&(typeof e.sampleSize!="number"||!Number.isFinite(e.sampleSize)||e.sampleSize<1))throw new Error("Invalid Model: autoGenerateProperties.sampleSize must be a positive number")}}if(r.properties&&!Array.isArray(r.properties))throw new Error("Invalid Model: properties must be an array");if(r.references&&!Array.isArray(r.references))throw new Error("Invalid Model: references must be an array");return!0},Ep=(r,e)=>{const t=[];return r.references.forEach(s=>{e.has(s.model)||t.push({title:"Missing Model",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingModel",attribute:s.key,model:r.key,description:`Referenced model ${s.model} does not exist`}),"derive"in s&&t.push(...jp(s,r,e)),"resolve"in s&&t.push(...Sp(s,r,e)),"groupBy"in s&&t.push(...Mp(s,r))}),r.properties.forEach(s=>{"derive"in s&&t.push(...Rp(s,r,e)),"expression"in s&&t.push(...Ip(s,r))}),t},jp=(r,e,t)=>{const s=[],o=e.references.get(r.derive.localReference);if(!o)return s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Local Referenced ${r.derive.localReference} does not exist in model ${e.key}`}),s;const n=t.get(o.model);return n&&(n.references.get(r.derive.remoteReference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Remote Reference ${r.derive.remoteReference} does not exist in model ${n.key}`})),s},Sp=(r,e,t)=>{const s=[],o=t.get(r.resolve.model);return o?(o.references.get(r.resolve.reference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Resolved Reference ${r.resolve.reference} does not exist in model ${o.key}`}),s):(s.push({title:"Missing Model",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingModel",attribute:r.key,model:e.key,description:`Referenced model ${r.model} does not exist`}),s)},Mp=(r,e)=>{const t=[];return e.references.get(r.groupBy.reference)||t.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Resolved Reference ${r.groupBy.reference} does not exist in model ${e.key}`}),t},Rp=(r,e,t)=>{const s=[],o=e.references.get(r.derive.localReference);if(!o)return s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Local Referenced ${r.derive.localReference} does not exist in model ${e.key}`}),s;const n=t.get(o.model);if(n){if(r.derive.remoteProperty==="key")return s;n.properties.get(r.derive.remoteProperty)||s.push({title:"Missing Property",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingProperty",attribute:r.key,model:e.key,description:`Remote Property ${r.derive.remoteProperty} does not exist in model ${n.key}`})}return s},Ip=(r,e)=>{const t=[];return xr(r.expression).variables.forEach(s=>{s.name==="key"||s.name.endsWith(".key")||!e.properties.get(s.name)&&!e.references.get(s.name)&&t.push({title:"Unknown Expression Variable",type:"model",errorGroup:"ModelDefinitionError",errorType:"UnknownExpressionVariable",attribute:r.key,model:e.key,description:`Expression Variable ${s.name} not found in expression ${r.key} in ${e.key}`})}),t},we="::";function Tp(r){return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function zo(r,e,t=we){return typeof e=="string"?String(r[e]):e.length===1?String(r[e[0]]):e.map(s=>String(r[s])).join(t)}function Mr(r,e=we){if(r!==void 0)return typeof r=="string"?r:r.join(e)}const Op={REF_VALUE:"_dcupl_ref_"},Lo={required:!0,forceStrictDataType:!1,nullable:!1,validatorHandling:"loose"},Wo={enabled:!0,attributes:Lo};let Kp=class{constructor(e){this.modelParser=e,this.cdRef=e.cdRef}modelParser;properties=new Map;references=new Map;attributeQualityConfigs=new Map;key;log=Te.child({prefix:"Model"});initialDefinition;data=new Map;supportsAutoCreation=!1;autoGenerateKey=!1;autoGenerateProperties=!1;autoGeneratePropertiesOption=!1;keyProperty="key";keyPropertySeparator;valueMappings=[];meta;qualityConfig=Wo;indicesController=new Mt;cdRef;groupedRefReverseIndex=new Map;init(e){this.key=e.key,this.initialDefinition=e,e.quality&&(this.qualityConfig=lt({},Wo,e.quality))}applyPropertiesAndReferences(e){const t=new Set;e.properties?.map(s=>{const o=_p(s);if(o)o.model=this.key,this.setError(o);else{if(t.has(s.key)){this.setError({title:"Duplicate Property Key",type:"model",errorGroup:"ModelDefinitionError",errorType:"DuplicatePropertyKey",description:`Model "${this.key}" declares property "${s.key}" more than once; the first definition is kept and the duplicate is ignored.`,attribute:s.key,model:this.key});return}t.add(s.key),this.setAttributeQualityConfig(s),this.properties.set(s.key,s)}}),e.references?.map(s=>{const o=Pp(s);o?(o.model=this.key,this.setError(o)):(s.validity=s.validity||"loose",this.setAttributeQualityConfig(s),this.references.set(s.key,s))}),this.supportsAutoCreation=!!e.supportsAutoCreation,this.keyProperty=e.keyProperty||"key",this.keyPropertySeparator=e.keyPropertySeparator,this.autoGenerateKey=!!e.autoGenerateKey,this.autoGenerateProperties=!!e.autoGenerateProperties,this.autoGeneratePropertiesOption=e.autoGenerateProperties??!1,this.valueMappings=e.valueMappings||[],this.meta=e.meta}setAttributeQualityConfig(e){const t=this.qualityConfig.attributes,s=lt({},Lo,t,e.quality);this.attributeQualityConfigs.set(e.key,s)}getModelDefinition(){return this.autoGenerateProperties?{key:this.key,keyProperty:this.keyProperty,keyPropertySeparator:this.keyPropertySeparator,references:Array.from(this.references.values()),properties:Array.from(this.properties.values()),autoGenerateKey:this.autoGenerateKey,supportsAutoCreation:this.supportsAutoCreation,valueMappings:this.valueMappings,meta:this.meta,autoGenerateProperties:this.autoGeneratePropertiesOption,quality:this.qualityConfig}:this.initialDefinition}generatePropertiesFromContainer(e){const t=this.autoGeneratePropertiesOption;(typeof t=="object"&&t!==null?qo(e.data,t):qo(e.data,!1)).map(s=>{if(!this.properties.has(s.key)){if(s.key==="key")return;const o=e.keyProperty??this.keyProperty;Tp(o).some(n=>n&&n!=="key"&&n===s.key)&&(s.type="string"),s.filter=!0,this.properties.set(s.key,s)}})}getReferenceKeys(e){return e.map(t=>{if(typeof t=="string")return String(t.trim());if(typeof t=="number")return String(t);if(t===null)return"null";if(typeof t=="object"&&t&&t.key)return t.key})}setError(e){this.modelParser.qualityController.enabled&&this.qualityConfig.enabled===!0&&(e.model=this.key,this.modelParser.qualityController.setError(e))}emitUnknownColumnErrors(e,t,s,o,n){const i=new Set;for(const l of s)i.add(l.key);for(const l of o)i.add(l.key);const a=e.keyProperty??this.keyProperty;if(typeof a=="string")i.add(a);else if(Array.isArray(a))for(const l of a)i.add(l);i.add("key");for(const l of t)i.has(l)||this.setError({title:"Unknown Column",type:"model",errorGroup:"DataContainerError",errorType:"UnknownColumn",description:`Column "${l}" in the source for model "${e.model}" is not declared on the model; its values are dropped during ingest`,attribute:l,model:e.model,meta:{column:l,origin:n}})}processBasicProperty(e,t,s,o="inline"){const n=t[e.key],i=this.attributeQualityConfigs.get(e.key);let a;if(typeof n>"u"){if(i?.required){const l=e.type;this.setError({title:"Undefined Value",type:"model",errorGroup:"PropertyDataError",errorType:"UndefinedValue",description:`The required ${l??""} property "${e.key}" in the "${this.key}" model is undefined (no value)`.replace(/\s+/g," "),itemKey:t.key,attribute:e.key,model:this.key,meta:{rawValue:n,declaredType:l,origin:o}})}return}else{if(n===null)i?.nullable||this.setError({title:"Null Value",description:`The value of the property "${e.key}" in the "${this.key}" model should not be null`,type:"model",errorGroup:"PropertyDataError",errorType:"NullValue",itemKey:t.key,attribute:e.key,model:this.key}),a=n;else if(e.type==="string"){if(a=this.processStringProperty(e,n,t),typeof a>"u")return}else if(e.type==="int"){if(a=this.processIntProperty(e,n,t),typeof a>"u")return}else if(e.type==="float"){if(a=this.processFloatProperty(e,n,t),typeof a>"u")return}else if(e.type==="date"){if(a=this.processDateProperty(e,n,t),typeof a>"u")return}else if(e.type==="json"){if(a=this.processJSONProperty(e,n,t),typeof a>"u")return}else if(e.type==="boolean"){if(a=this.processBooleanProperty(e,n,t),typeof a>"u")return}else if(e.type==="any")a=n;else if(e.type==="Array<string>"){const l=this.getValueAsArray(n,e?.separator);Array.isArray(l)&&(a=[],l.forEach(u=>{const c=this.processStringProperty(e,u,t);typeof c<"u"&&a.push(c)}))}else if(e.type==="Array<int>"){const l=this.getValueAsArray(n,e?.separator);Array.isArray(l)&&(a=[],l.forEach(u=>{const c=this.processIntProperty(e,u,t);typeof c<"u"&&a.push(c)}))}else if(e.type==="Array<float>"){const l=this.getValueAsArray(n,e?.separator);Array.isArray(l)&&(a=[],l.forEach(u=>{const c=this.processFloatProperty(e,u,t);typeof c<"u"&&a.push(c)}))}else if(e.type==="Array<date>"){const l=this.getValueAsArray(n,e?.separator);Array.isArray(l)&&(a=[],l.forEach(u=>{const c=this.processDateProperty(e,u,t);typeof c<"u"&&a.push(c)}))}s[e.key]=a}e.index&&(this.indicesController.fillInverseIndex(e.key,s.key,[a]),this.indicesController.fillDataMap(e.key,[a]))}handleValidators(e,t,s){if(!this.modelParser.qualityController.enabled||this.qualityConfig.enabled!==!0)return!0;let o=!0;try{if(t.quality?.validators){const n=this.modelParser.qualityController.validateAttribute(e,t.quality.validators,t.key);for(const i of n)o=!1,i.attribute=t.key,i.itemKey=s.key,i.model=this.key,this.setError(i)}}catch(n){this.log.error("Validator definition error",n)}return o}getWrongDataTypeError(e,t,s){return{title:"Wrong Data Type",type:"model",errorGroup:"PropertyDataError",errorType:"WrongDataType",itemKey:s.key,attribute:e.key,model:this.key,description:`Expect ${e.type} but got ${typeof t} with value ${t}`,meta:{expected:e.type,rawValue:t,typeof:typeof t}}}isLossyNumericCoercion(e,t,s){const o=Number(typeof e=="string"?e.trim():e);return isNaN(o)?!0:s?o!==t:!1}getLossyCoercionError(e,t,s,o){return{title:"Lossy Data Coercion",type:"model",errorGroup:"PropertyDataError",errorType:"WrongDataType",itemKey:o.key,attribute:e.key,model:this.key,description:`Lossy coercion to ${e.type}: raw value "${t}" was coerced to ${s}`,meta:{expected:e.type,rawValue:t,coercedValue:s,typeof:typeof t,lossy:!0}}}getValueAsArray(e,t=","){if(e)return Array.isArray(e)?e:e&&typeof e=="string"?e.split(t).map(s=>s.trim()):[]}processStringProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);let n=t;if(o?.forceStrictDataType){if(!jt(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}}else if(n=String(t),!jt(n)&&n!=t){this.setError(this.getWrongDataTypeError(e,t,s));return}if(!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processIntProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);if(o?.forceStrictDataType){if(!Qo(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}const n=parseInt(t,10);if(isNaN(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}if(this.isLossyNumericCoercion(t,n,!0)&&this.setError(this.getLossyCoercionError(e,t,n,s)),!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processFloatProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);if(o?.forceStrictDataType){if(!Vo(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}let n;const i=e.fractionDigits;if(typeof i>"u"?n=parseFloat(t):n=parseFloat(parseFloat(t).toFixed(i)),isNaN(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}if(this.isLossyNumericCoercion(t,n,!1)&&this.setError(this.getLossyCoercionError(e,t,n,s)),!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processJSONProperty(e,t,s){if(this.attributeQualityConfigs.get(e.key)?.forceStrictDataType){if(!K(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}if(K(t))return t;if(!K(t)&&typeof t=="string")try{return JSON.parse(t)}catch{this.setError(this.getWrongDataTypeError(e,t,s));return}}processBooleanProperty(e,t,s){if(this.attributeQualityConfigs.get(e.key)?.forceStrictDataType){if(!Dp(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}return!!t}processDateProperty(e,t,s){if(t===""){this.setError(this.getWrongDataTypeError(e,t,s));return}const o=e.inputFormat;let n;try{if(o&&typeof o=="string"){let i=t;typeof i!="string"&&(i=String(i)),n=_f(i,o,new Date)}else n=new Date(t)}catch(i){this.log.error("Property extraction error",i,{property:e.key,model:this.key}),this.setError(this.getWrongDataTypeError(e,t,s));return}if(!To(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}return e.UTC&&(n=new Date(Date.UTC(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),n.getMilliseconds()))),n}processSingleValuedReference(e,t,s){const o=this.modelParser.models.get(e.model);if(!o)return;let n="";typeof t=="string"?n=t:typeof t=="object"&&t&&t.key&&(n=t.key);const i=o.getEntry(String(n));if(!i){if(o.supportsAutoCreation){const l=this.handleAutoCreationAndReturnKey(o,t);this.indicesController.fillInverseIndex(e.key,s.key,[t]),s[e.key]=l,this.setRefValue(l,"auto_hit");return}else if(this.indicesController.fillInverseIndex(e.key,s.key,[n]),this.setError({title:"Remote Reference Key Not Found",type:"model",errorGroup:"ReferenceDataError",errorType:"RemoteReferenceKeyNotFound",itemKey:s.key,attribute:e.key,description:`The reference "${e.key}" in the "${this.key}" model can not find the value "${t}" in the remote model "${e.model}"`,meta:{remoteModel:e.model,remoteKey:t}}),e.validity==="strict")return}this.indicesController.fillInverseIndex(e.key,s.key,[n]);const a={key:String(n)};s[e.key]=a,!i&&!o.supportsAutoCreation&&e.validity!=="strict"?this.setRefValue(a,"miss"):this.setRefValue(a,"hit")}processMultiValuedReference(e,t,s){const o=this.modelParser.models.get(e.model);if(!o)return;const n=this.getReferenceKeys(t),i=[];n.forEach((a,l)=>{const u=o.getEntry(String(a));if(!u){if(o.supportsAutoCreation){const d=this.handleAutoCreationAndReturnKey(o,t[l]);this.setRefValue(d,"auto_hit"),i.push(d);return}else if(this.setError({title:"Remote Reference Key Not Found",type:"model",errorGroup:"ReferenceDataError",errorType:"RemoteReferenceKeyNotFound",itemKey:s.key,attribute:e.key,description:`The reference "${e.key}" in the "${this.key}" model can not find the value "${a}" in the remote model "${e.model}"`,meta:{remoteModel:e.model,remoteKey:a}}),e.validity==="strict")return}const c={key:a};!u&&!o.supportsAutoCreation&&e.validity!=="strict"?this.setRefValue(c,"miss"):this.setRefValue(c,"hit"),i.push(c)}),this.indicesController.fillInverseIndex(e.key,s.key,i.map(a=>a.key)),s[e.key]=i}getViewKeys(){return this.modelParser._getViewKeys({modelKey:this.key})}addBasicPropertiesAndReferences(e){const t=this.getBasicProperties(),s=this.getBasicReferences(),o=this.modelParser.qualityController.dcupl?.getContainerSourceMetadata(e),n=o?.origin??"inline";o&&o.sourceColumns.length>0&&this.emitUnknownColumnErrors(e,o.sourceColumns,t,s,n);for(let i of e.data){if(i.key===void 0||i.key===null){const u=e.keyProperty??this.keyProperty,c=e.keyPropertySeparator??this.keyPropertySeparator??we,d=Mr(u,c);this.setError({title:"Missing Key",type:"model",errorGroup:"DataContainerError",errorType:"MissingKey",description:`A row in model "${e.model}" has no value for the key attribute "${d}"; the row is dropped.`,attribute:d,model:e.model});continue}let a=this.data.get(String(i.key));if(!a)a={key:String(i.key)};else if(e.type==="set"){const u=e.keyProperty??this.keyProperty,c=e.keyPropertySeparator??this.keyPropertySeparator??we,d=Mr(u,c),f=String(i.key);this.setError({title:"Non Unique Key",type:"model",errorGroup:"DataContainerError",errorType:"NonUniqueKey",description:`Row with key "${f}" in model "${e.model}" collides with an existing entry (key attribute "${d}"); the duplicate row is dropped`,itemKey:i.key,attribute:d,model:e.model,meta:{duplicateCount:1,droppedRows:[f]}})}for(const u of t){u.origin&&(i[u.key]=i[u.origin]);const c=this.valueMappings.find(d=>d.attributes.includes(u.key));this.isValidValueMapping(c)&&(i=this.mapRawValueUsingValueMapping(i,u.key,c)),this.processBasicProperty(u,i,a,n)}for(const u of s){const c=this.attributeQualityConfigs.get(u.key);u.origin&&(i[u.key]=i[u.origin]);const d=this.valueMappings.find(h=>h.attributes.includes(u.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,u.key,d));let f=i[u.key];if(typeof f=="number"&&(f=String(f)),!f){this.indicesController.fillInverseIndex(u.key,a.key,[void 0]),c?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${u.type} reference "${u.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:u.key,model:e.model,meta:{rawValue:f,declaredType:u.type,origin:n}});continue}if(u.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?this.processSingleValuedReference(u,f,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}});else if(u.type==="multiValued"){const h=this.getValueAsArray(f,u?.separator);Array.isArray(h)?this.processMultiValuedReference(u,h,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}})}}const l=String(a.key);a.key=l,this.data.set(l,a)}}addQueryReferences(e){const t=this.getQueryReferences();for(let s of t){const o=JSON.stringify(s.query);for(let n of e.data){let i=this.data.get(String(n.key));const a=Rt(o,{...n}),l=JSON.parse(a),u=new ke;u.init({modelKey:s.model}),u.applyQuery(l,{mode:"set"}),l.projection||u.applyOptions({projection:{$:!1}});const c=u.getQuery();if(c.queries.length>0){const f=this.modelParser.dcuplInstance.query.execute(c);s.type==="singleValued"?f[0]&&(i[s.key]={key:f[0].key,_dcupl_ref_:"hit"}):s.type==="multiValued"&&(f.forEach(h=>{h._dcupl_ref_="hit"}),i[s.key]=f)}else s.type==="singleValued"?i[s.key]=null:s.type==="multiValued"&&(i[s.key]=[]);const d=String(i.key);i.key=d,this.data.set(d,i)}}}isValidValueMapping(e){if(!e||!Array.isArray(e.attributes)||!Array.isArray(e.values))return!1;const t=e.values.find(o=>!Array.isArray(o.from)),s=e.values.find(o=>o.to===void 0);return!(t||s)}mapRawValueUsingValueMapping(e,t,s){for(const o of s.values){if(o.from.includes("$dcupl_falsy")){if(typeof e[t]>"u"||e[t]===null||e[t]===""){e[t]=o.to;continue}continue}if(o.from.includes(e[t])){e[t]=o.to;continue}}return e}handleAutoCreationAndReturnKey(e,t){if(Array.isArray(t))return[];if(t===null)return{key:"null"};if(typeof t=="object"){const s=e.keyProperty,o=e.keyPropertySeparator??we;let n;e.autoGenerateKey?n=W():typeof s=="string"||Array.isArray(s)&&s.length>0?n=zo(t,s,o):n=String(t.key),e.data.set(n,{key:n}),t.key=n;const i={model:e.key,data:[t]};return Z().then(()=>e.addContainer(i)),{key:n}}if(typeof t=="string"){e.data.set(t,{key:t});const s={model:e.key,data:[{key:t}]};Z().then(()=>e.addContainer(s))}return{key:String(t)}}addContainer(e){if(this.cdRef.analyticsController.mark({name:"model:autogenerate_data:start",context:e.model}),this.modelParser.handleAlternativeKey([e]),!Array.isArray(e.data)){this.setError({title:"Invalid Data",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",description:`Expect the data to be an Array but got ${typeof e.data}`,model:e.model});return}this.autoGenerateProperties&&this.generatePropertiesFromContainer(e),this.addBasicPropertiesAndReferences(e),this.addQueryReferences(e),this.addResolvedReferences(e),this.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(e),(this.hasDerivedPropertiesBasedOnResolvedReferences()||this?.hasDerivedReferencesBasedOnResolvedReferences())&&this.reRunDerivedPropertiesBasedOnResolves(e),this.cdRef.analyticsController.mark({name:"model:autogenerate_data:end",context:e.model}),this.cdRef.analyticsController.measure({name:"model:autogenerate_data",start:"model:autogenerate_data:start",end:"model:autogenerate_data:end",sum:!0,context:e.model,detail:{model:e.model,origin:this.key}})}addResolvedReferences(e){const t=this.getResolvedReferences().map(s=>{const o=this.modelParser.models.get(s.resolve.model);if(!o)return;const n=o.getDataAsArray(),i=o.indicesController.getIndex(s.resolve.reference);return{reference:s,model:o,remoteData:n,inverseKeys:i}}).filter(s=>!!s);for(const s of e.data){const o=String(s.key),n=this.data.get(o);for(const a of t){const l=a.reference.key;let u;if(a.inverseKeys){if(a.reference.type==="multiValued"){const c=a.inverseKeys.get(n.key)||new Set;u=Array.from(c).map(d=>({key:d}))}else{const c=a.inverseKeys.get(n.key),d=c&&Array.from(c)[0]||null;d?u={key:d}:u=null}n[l]=u,this.indicesController.fillInverseIndex(l,o,n[l])}}const i=String(n.key);n.key=i,this.data.set(i,n)}}rebuildResolvedReferencesForAllItems(e){let t=this.getResolvedReferences();if(t.length===0||e&&(t=t.filter(o=>e.has(o.key)),t.length===0))return;const s=t.map(o=>{const n=this.modelParser.models.get(o.resolve.model);if(!n)return;const i=n.indicesController.getIndex(o.resolve.reference);return{reference:o,model:n,remoteData:[],inverseKeys:i}}).filter(o=>!!o);for(const o of this.data.values())for(const n of s){const i=n.reference.key;let a;if(n.inverseKeys){if(n.reference.type==="multiValued"){const l=n.inverseKeys.get(o.key)||new Set;a=Array.from(l).map(u=>({key:u}))}else{const l=n.inverseKeys.get(o.key),u=l?Array.from(l)[0]:null;u?a={key:u}:a=null}o[i]=a,this.indicesController.fillInverseIndex(i,o.key,o[i])}}}addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(e){const t=this.getDerivedPropertiesForBasicAndDerivedReferences(),s=this.getExpressionProperties(),o=this.getDerivedReferences(),n=this.getGroupedReferences();for(const i of e.data){const a=this.data.get(String(i.key));o.length>0&&o.forEach(u=>{this.handleDerivedReferences(u,a)}),n.length>0&&n.forEach(u=>{this.handleGroupedReferences(u,a)}),t.length>0&&t.forEach(u=>{this.handleDerivedProperties(u,a)}),s.length>0&&s.forEach(u=>{const c=this.createExpressionContext(a),d=Rt(u.expression,c);a[u.key]=d});const l=String(a.key);a.key=l,this.data.set(l,a)}}handleDerivedProperties(e,t){const s=this.references.get(e.derive.localReference);if(s){const o=this.modelParser.models.get(s.model);o&&(s.type==="singleValued"?this.handleSingleValuedDerivedProperties(o,t,s,e):s.type==="multiValued"&&this.handleMultiValuedDerivedProperties(o,t,s,e))}}reRunDerivedPropertiesBasedOnResolves(e){const t=this.getDerivedProperties(),s=this.getDerivedReferences();for(const o of e.data){const n=this.data.get(String(o.key));s.forEach(a=>{this.handleDerivedReferences(a,n)}),t.forEach(a=>{const l=this.references.get(a.derive.localReference);if(l){const u=this.modelParser.models.get(l.model);u&&(l.type==="singleValued"?this.handleSingleValuedDerivedProperties(u,n,l,a):l.type==="multiValued"&&this.handleMultiValuedDerivedProperties(u,n,l,a))}});const i=String(n.key);n.key=i,this.data.set(i,n)}}handleSingleValuedDerivedProperties(e,t,s,o){const n=t[s.key];if(!n){delete t[o.key];return}const i=e?.getData().get(n.key);if(i){const a=i[o.derive.remoteProperty];typeof a<"u"&&(t[o.key]=a),o.index&&this.indicesController.fillInverseIndex(o.key,t.key,[a])}else delete t[o.key]}handleMultiValuedDerivedProperties(e,t,s,o){const n=t[s.key];let i;n?Array.isArray(n)?i=[...n]:n&&typeof n.key=="string"?i=[{key:n.key}]:i=[]:i=[];const a=o.derive?.separator||", ",l=i.map(c=>{const d=e?.getData().get(c.key);if(d)return d[o.derive.remoteProperty]}).filter(Boolean);let u;o.type.includes("Array<")?u=l:o.type==="string"||o.type==="int"||o.type==="float"||o.type==="date"?u=l.join(a):(o.type,u=l),t[o.key]=u}handleDerivedReferences(e,t){const s=this.references.get(e.derive.localReference);if(!s)return;const o=this.modelParser.models.get(s.model);if(!o)return;const n=t[s.key];if(!n)return;let i=[];if(Array.isArray(n)){const l=new Set;n.forEach(u=>{const c=o?.data.get(u.key);if(c){const d=c[e.derive.remoteReference];d&&(Array.isArray(d)?d.forEach(f=>{l.add(f.key)}):l.add(d.key))}}),i=Array.from(l.values())}else{const l=o?.data.get(n.key);if(l){const u=l[e.derive.remoteReference];u?Array.isArray(u)?i=u.map(c=>c.key):"key"in u&&(i=[u.key]):i=[]}}let a;e.type==="singleValued"?a={key:i[0]}:a=i.map(l=>({key:l})),this.indicesController.fillInverseIndex(e.key,t.key,i),this.groupedRefReverseIndex.delete(e.key),t[e.key]=a}asStringArray(e){return e?Array.isArray(e)?e.map(t=>t.key):[e.key]:[]}buildReverseIndexForReference(e){const t=new Map;this.data.forEach(s=>{const o=this.asStringArray(s[e]);for(const n of o)t.has(n)||t.set(n,new Set),t.get(n).add(s.key)}),this.groupedRefReverseIndex.set(e,t)}ensureReverseIndex(e){return this.groupedRefReverseIndex.has(e)||this.buildReverseIndexForReference(e),this.groupedRefReverseIndex.get(e)}handleGroupedReferences(e,t){const s=[],o=this.references.get(e.groupBy.reference);if(o){const n=this.asStringArray(t[o.key]);if(!n.length)return;const i=this.ensureReverseIndex(o.key),a=new Set;for(const l of n){const u=i.get(l);u&&u.forEach(c=>a.add(c))}for(const l of a)e.groupBy.includeSelfInGroup?s.push({key:l}):t.key!==l&&s.push({key:l})}t[e.key]=s}resetData(){this.data.clear(),this.groupedRefReverseIndex.clear()}resetIndexMap(){this.indicesController.reset()}resetIndicesForChangedAttributes(e){this.indicesController.resetIndicesWhere(t=>{if(this.references.has(t))return!1;for(const s of e)if(t===s||t.startsWith(`${s}_`)||t.startsWith(`${s}.`))return!0;return!1})}deleteDataEntries(e){for(const t of e.data){const s=String(t.key);this.data.delete(s),this.indicesController.removeItemFromAllIndices(s),this.groupedRefReverseIndex.forEach(o=>{o.forEach(n=>{n.delete(s)})})}}getItemCount(){return this.data.size}getAttributes(){return[...this.references.values(),...this.properties.values()]}getAttribute(e){return e==="key"?{key:"key",type:"string"}:this.references.get(e)||this.properties.get(e)}getReferencesRelevantForDependencyGraph(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e))}getBasicReferences(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e)&&!("query"in e)&&!("groupBy"in e))}getQueryReferences(){return Array.from(this.references.values()).filter(e=>"query"in e)}getResolvedReferences(){return Array.from(this.references.values()).filter(e=>"resolve"in e)}getGroupedReferences(){return Array.from(this.references.values()).filter(e=>"groupBy"in e)}getDerivedReferences(){return Array.from(this.references.values()).filter(e=>"derive"in e)}getAggregatedReferences(){return Array.from(this.references.values()).filter(e=>"aggregate"in e)}getBasicProperties(){return Array.from(this.properties.values()).filter(e=>!("derive"in e)&&!("expression"in e))}getDerivedProperties(){return Array.from(this.properties.values()).filter(e=>"derive"in e)}getDerivedPropertiesForBasicAndDerivedReferences(){const e=this.getBasicReferences(),t=this.getDerivedReferences(),s=this.getQueryReferences(),o=this.getDerivedProperties(),n=[...e,...t,...s];return o.filter(i=>n.find(a=>a.key===i.derive?.localReference))}getDerivedPropertiesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedProperties().filter(t=>e.find(s=>s.key===t.derive?.localReference))}getDerivedReferencesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedReferences().filter(t=>e.find(s=>s.key===t.derive.localReference))}getExpressionProperties(){return Array.from(this.properties.values()).filter(e=>"expression"in e)}getAggregatedProperties(){return Array.from(this.properties.values()).filter(e=>"aggregate"in e)}hasBasicReferences(){return this.getBasicReferences().length>0}hasQueryReferences(){return this.getQueryReferences().length>0}hasResolvedReferences(){return this.getResolvedReferences().length>0}hasGroupedReferences(){return this.getGroupedReferences().length>0}hasDerivedReferences(){return this.getDerivedReferences().length>0}hasBasicProperties(){return this.getBasicProperties().length>0}hasDerivedProperties(){return this.getDerivedProperties().length>0}hasDerivedPropertiesForBasicReferences(){return this.getDerivedPropertiesForBasicAndDerivedReferences().length>0}hasDerivedPropertiesBasedOnResolvedReferences(){return this.getDerivedPropertiesForResolvedReferences().length>0}hasDerivedReferencesBasedOnResolvedReferences(){return this.getDerivedReferencesForResolvedReferences().length>0}hasExpressionProperties(){return this.getExpressionProperties().length>0}hasAggregatedProperties(){return this.getAggregatedProperties().length>0}getData(e){if(e?.itemKeys){const t=new Map;return e.itemKeys.forEach(s=>{const o=this.data.get(s);o&&t.set(o.key,o)}),t}return this.data}getDataAsArray(){return Array.from(this.data.values())}getEntry(e){return this.data.get(e)}setRefValue(e,t){this.modelParser.initOptions.referenceMetadata?.enabled&&Object.defineProperty(e,Op.REF_VALUE,{value:t,enumerable:!0,writable:!1,configurable:!1})}addBasicPropertiesAndReferencesPartial(e,t){const s=this.getBasicProperties().filter(i=>t.has(i.key)),o=this.getBasicReferences().filter(i=>t.has(i.key)),n=this.modelParser.qualityController.dcupl?.getContainerSourceMetadata(e)?.origin??"inline";for(let i of e.data){if(i.key===void 0||i.key===null){const u=e.keyProperty??this.keyProperty,c=e.keyPropertySeparator??this.keyPropertySeparator??we,d=Mr(u,c);this.setError({title:"Missing Key",type:"model",errorGroup:"DataContainerError",errorType:"MissingKey",description:`A row in model "${e.model}" has no value for the key attribute "${d}"; the row is dropped.`,attribute:d,model:e.model});continue}let a=this.data.get(String(i.key));a||(a={key:String(i.key)});for(const u of s){u.origin&&(i[u.key]=i[u.origin]);const c=this.valueMappings.find(d=>d.attributes.includes(u.key));this.isValidValueMapping(c)&&(i=this.mapRawValueUsingValueMapping(i,u.key,c)),this.processBasicProperty(u,i,a,n)}for(const u of o){const c=this.attributeQualityConfigs.get(u.key);u.origin&&(i[u.key]=i[u.origin]);const d=this.valueMappings.find(p=>p.attributes.includes(u.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,u.key,d));let f=i[u.key];typeof f=="number"&&(f=String(f));const h=a[u.key];if(this.groupedRefReverseIndex.delete(u.key),!f){h&&this.indicesController.removeFromInverseIndex(u.key,a.key,[h]),this.indicesController.fillInverseIndex(u.key,a.key,[void 0]),delete a[u.key],c?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${u.type} reference "${u.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:u.key,model:e.model,meta:{rawValue:f,declaredType:u.type,origin:n}});continue}if(u.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?(h&&h.key!==f&&this.indicesController.removeFromInverseIndex(u.key,a.key,[h]),this.processSingleValuedReference(u,f,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}});else if(u.type==="multiValued"){const p=this.getValueAsArray(f,u?.separator);Array.isArray(p)?(h&&Array.isArray(h)&&this.indicesController.removeFromInverseIndex(u.key,a.key,h),this.processMultiValuedReference(u,p,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}})}}const l=String(a.key);a.key=l,this.data.set(l,a)}}addQueryAndResolvedReferencesPartial(e,t){if(this.hasQueryReferences()){const s=this.getQueryReferences().filter(o=>t.has(o.key));for(let o of s){const n=JSON.stringify(o.query);for(let i of e.data){let a=this.data.get(String(i.key));if(!a)continue;const l=Rt(n,{...i}),u=JSON.parse(l),c=new ke;c.init({modelKey:o.model}),c.applyQuery(u,{mode:"set"}),u.projection||c.applyOptions({projection:{$:!1}});const d=c.getQuery();if(d.queries.length>0){const h=this.modelParser.dcuplInstance.query.execute(d);o.type==="singleValued"?h[0]&&(a[o.key]={key:h[0].key,_dcupl_ref_:"hit"}):o.type==="multiValued"&&(h.forEach(p=>{p._dcupl_ref_="hit"}),a[o.key]=h)}else o.type==="singleValued"?a[o.key]=null:o.type==="multiValued"&&(a[o.key]=[]);const f=String(a.key);a.key=f,this.data.set(f,a)}}}this.hasResolvedReferences()&&this.getResolvedReferences().filter(s=>t.has(s.key)).length>0&&this.rebuildResolvedReferencesForAllItems()}createExpressionContext(e){const t={...e};return this.references.forEach((s,o)=>{const n=e[o];if(!n)return;const i=this.modelParser.models.get(s.model);if(i)if(s.type==="singleValued"&&typeof n=="object"&&"key"in n){const a=i.getData().get(n.key);a&&(t[o]=this.createNestedContext(a,i))}else s.type==="multiValued"&&Array.isArray(n)&&(t[o]=n.map(a=>{const l=i.getData().get(a.key);return l?this.createNestedContext(l,i):null}).filter(Boolean))}),t}createNestedContext(e,t){const s={...e};return t.references.forEach((o,n)=>{const i=e[n];if(!i)return;const a=this.modelParser.models.get(o.model);if(a&&o.type==="singleValued"&&typeof i=="object"&&"key"in i){const l=a.getData().get(i.key);l&&(s[n]={...l})}}),s}addDerivedAndExpressionAttributesPartial(e,t){const s=this.getDerivedPropertiesForBasicAndDerivedReferences().filter(a=>t.has(a.key)),o=this.getDerivedReferences().filter(a=>t.has(a.key)),n=this.getGroupedReferences().filter(a=>t.has(a.key)),i=this.getExpressionProperties().filter(a=>t.has(a.key));for(const a of e.data){const l=this.data.get(String(a.key));if(!l)continue;o.forEach(c=>{this.handleDerivedReferences(c,l)}),n.forEach(c=>{this.handleGroupedReferences(c,l)}),s.forEach(c=>{this.handleDerivedProperties(c,l)}),i.forEach(c=>{const d=this.createExpressionContext(l),f=Rt(c.expression,d);l[c.key]=f});const u=String(l.key);l.key=u,this.data.set(u,l)}}reRunDerivedPropertiesBasedOnResolvesPartial(e,t){const s=this.getDerivedProperties().filter(n=>t.has(n.key)),o=this.getDerivedReferences().filter(n=>t.has(n.key));for(const n of e.data){const i=this.data.get(String(n.key));if(!i)continue;o.forEach(l=>{this.handleDerivedReferences(l,i)}),s.forEach(l=>{this.handleDerivedProperties(l,i)});const a=String(i.key);i.key=a,this.data.set(a,i)}}},Fp=class{changedAttributes;changedItems;deletedItems;modelFullReset;state="clean";constructor(){this.changedAttributes=new Map,this.changedItems=new Map,this.deletedItems=new Map,this.modelFullReset=new Set}recordDataChange(e){const t=e.model;if(!(e.type!=="set"&&(!e.data||e.data.length===0)))if(e.type==="set")this.state==="clean"?this.state="full-reset":this.state==="tracking"&&(this.state="full-reset",this.changedAttributes.delete(t),this.changedItems.delete(t),this.deletedItems.delete(t)),this.modelFullReset.add(t);else{if(this.modelFullReset.has(t))return;this.state==="clean"?this.state="tracking":this.state==="full-reset"&&(this.state="tracking"),e.type==="remove"?this.recordDeletedItems(t,e.data):this.recordChangedData(t,e.data)}}recordAttributeChange(e,t){this.changedAttributes.has(e)||this.changedAttributes.set(e,new Set),this.changedAttributes.get(e).add(t)}recordChangedData(e,t){this.changedAttributes.has(e)||this.changedAttributes.set(e,new Set),this.changedItems.has(e)||this.changedItems.set(e,new Set);const s=this.changedAttributes.get(e),o=this.changedItems.get(e);for(const n of t){n.key&&o.add(String(n.key));for(const i in n)i!=="key"&&s.add(i)}}recordDeletedItems(e,t){this.deletedItems.has(e)||this.deletedItems.set(e,new Set);const s=this.deletedItems.get(e);for(const o of t)o.key&&s.add(String(o.key))}getChangedAttributes(){return this.changedAttributes}getChangedAttributesForModel(e){return this.changedAttributes.get(e)}getChangedItems(e){return this.changedItems.get(e)||new Set}getDeletedItems(e){return this.deletedItems.get(e)||new Set}getModelsWithChanges(){const e=new Set;for(const t of this.changedAttributes.keys())e.add(t);for(const t of this.changedItems.keys())e.add(t);for(const t of this.deletedItems.keys())e.add(t);return Array.from(e)}getEffectivelyChangedModels(){return new Set([...this.getModelsWithChanges(),...this.modelFullReset])}getModelsWithFullReset(){return this.modelFullReset}hasFullReset(e){return this.modelFullReset.has(e)}hasChanges(){return this.changedAttributes.size>0||this.changedItems.size>0||this.deletedItems.size>0||this.modelFullReset.size>0}getTotalChangedItemCount(){let e=0;for(const t of this.changedItems.values())e+=t.size;for(const t of this.deletedItems.values())e+=t.size;return e}getAffectedModelRatio(e){return e===0?0:(this.getModelsWithChanges().length+this.modelFullReset.size)/e}getAffectedItemRatio(e,t){return t===0?0:this.getChangedItems(e).size/t}clear(){this.changedAttributes.clear(),this.changedItems.clear(),this.deletedItems.clear(),this.modelFullReset.clear(),this.state="clean"}requiresFullReset(){return this.state==="full-reset"}getState(){return this.state}getStats(){let e=0,t=0,s=0;for(const o of this.changedItems.values())e+=o.size;for(const o of this.deletedItems.values())t+=o.size;for(const o of this.changedAttributes.values())s+=o.size;return{modelsWithChanges:this.getModelsWithChanges().length,modelsWithFullReset:this.modelFullReset.size,totalChangedItems:e,totalDeletedItems:t,totalChangedAttributes:s}}},qp=class{metrics=[];enabled=!1;constructor(){}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}recordUpdate(e){this.enabled&&(this.metrics.push({...e,timestamp:Date.now()}),this.metrics.length>100&&this.metrics.shift())}getMetrics(){return[...this.metrics]}getSummary(){if(this.metrics.length===0)return{totalUpdates:0,partialUpdates:0,fullUpdates:0,avgPartialUpdateTime:0,avgFullUpdateTime:0,avgAttributesProcessed:0,avgModelsAffected:0,totalTimeSaved:0};const e=this.metrics.filter(l=>l.type==="partial"),t=this.metrics.filter(l=>l.type==="full"),s=e.length>0?e.reduce((l,u)=>l+u.durationMs,0)/e.length:0,o=t.length>0?t.reduce((l,u)=>l+u.durationMs,0)/t.length:0,n=e.length>0?e.reduce((l,u)=>l+(u.attributesProcessed||0),0)/e.length:0,i=e.length>0?e.reduce((l,u)=>l+(u.modelsAffected||0),0)/e.length:0,a=o>0?e.reduce((l,u)=>l+(o-u.durationMs),0):0;return{totalUpdates:this.metrics.length,partialUpdates:e.length,fullUpdates:t.length,avgPartialUpdateTime:s,avgFullUpdateTime:o,avgAttributesProcessed:n,avgModelsAffected:i,totalTimeSaved:a}}getLastUpdates(e=10){return this.metrics.slice(-e)}clear(){this.metrics=[]}getMetricsInRange(e,t){return this.metrics.filter(s=>s.timestamp>=e&&s.timestamp<=t)}};function Qp(r){return"query"in r}function Rr(r){return"resolve"in r}function Vp(r){return"derive"in r}function Gp(r){return"groupBy"in r}var Bp=Object.defineProperty,Up=Object.getOwnPropertyDescriptor,It=(r,e,t,s)=>{for(var o=Up(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Bp(e,t,o),o};let ut=class{constructor(e,t,s){this.cdRef=e,this.qualityController=t,this.dcuplInstance=s,this.qualityController.modelParser=this}cdRef;qualityController;dcuplInstance;unprocessedModelDescriptions=new Map;unprocessedData=[];keyedContainers=new WeakSet;dependencyGraph;attributeDependencyGraph;changeTracker=new Fp;partialUpdateMetrics=new qp;views=new Map;models=new Map;initOptions;calculationTimings=[];log=Te.child({prefix:"ModelParser"});async init(){this.changeTracker.clear(),this.qualityController.enabled&&(this.qualityController.resetDataErrors(),this.models.get("$DcuplErrorTrackingErrors")||this.qualityController.initErrorTrackingModels()),this.prepareModels(),this.qualityController.enabled&&this.validateModels(),this.initDependencyGraph(),this.buildAttributeDependencyGraph(),this.validateAttributeDependencyGraph();const e=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(e),this.consolidateUnprocessedData(e),this.qualityController.enabled&&await this.qualityController.initData(),this.changeTracker.clear()}prepareModels(){this.unprocessedModelDescriptions.forEach(e=>{if(this.models.has(e.key))this.models.get(e.key).resetData(),this.models.get(e.key).resetIndexMap(),this.models.get(e.key).applyPropertiesAndReferences(e);else{const t=new Kp(this);t.init(e),t.applyPropertiesAndReferences(e),this.models.set(t.key,t)}})}validateModels(){this.models.forEach(e=>{e.qualityConfig.enabled===!0&&Ep(e,this.models).forEach(t=>{this.setError(t,e)})})}initDependencyGraph(){this.dependencyGraph=new So,this.models.forEach(t=>{this.dependencyGraph.addNode(t.key)}),this.models.forEach(t=>{t.getReferencesRelevantForDependencyGraph().forEach(s=>{t.key!==s.model&&(this.dependencyGraph.addNode(s.model),this.dependencyGraph.addDependency(t.key,s.model))})});const e=this.dependencyGraph.validateNoCycles();if(e.hasCycle){const t=e.path.join(" → ");throw this.log.error(`Circular dependency detected in model references: ${t}
|
|
5
|
+
`}executeScript(e,t,s){if(!this.getScript(e))throw new Error(`Script ${e} not found`);s.context||(s.context=s.options||{});const o=Object.keys(s),n=Object.values(s);return this.getScriptAsFn(e,o)(t,...n)}}const St=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>ot(e,s.trim(),""))):"",Pr=r=>{const e=new Set;return r.replace(/\$\{(.*?)\}/g,(t,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(t=>({name:t}))}};var Yf=tr(function(r,e){return Ie(r)?bo(r,Fs(e,1,Ie)):[]});let Xf=class{constructor(e,t,s,o,n){this.modelParser=e,this.cdRef=t,this.item=s,this.indicesController=o,this.queryManager=n,this.cacheCtrl=new bf(!!this.cdRef.dcuplInitOptions.performance?.cache?.enabled)}modelParser;cdRef;item;indicesController;queryManager;initialData;_filteredData;filteredDataStale=!1;model;get filteredData(){return this.filteredDataStale&&(this.filteredDataStale=!1,this._filteredData=this.getFilteredData(this.initialData,!1)),this._filteredData}set filteredData(e){this._filteredData=e,this.filteredDataStale=!1}filterItems=new Map;queryBuilder;cacheCtrl;projectionCache=new Map;dependencyModels=new Set;init(e,t){this.model=e,this.initialData=t,this.filteredData=this.initialData,this.queryBuilder=new ke,this.queryBuilder.init({modelKey:e.key}),this.initFilterItems({skipProcessing:!0})}indexDependsOnAttributes(e,t){const s=e.includes("_")?e.split("_")[0]:e;try{const o=P.parse(s);if(!o.isDeepQuery)return!1;const n=o.attribute.split(".");for(let i=0;i<n.length-1;i++)if(t.has(n[i]))return!0;return!1}catch{return!0}}invalidateAllCaches(e){this.cacheCtrl.clear(),this.projectionCache.clear(),this.dependencyModels.clear();let t=0;if(e&&e.size>0){const o=this.indicesController.getDeepIndexKeys(),n=[];for(const i of o)this.indexDependsOnAttributes(i,e)&&n.push(i);for(const i of n)this.indicesController.reset(i);t=n.length}else{const o=this.indicesController.getIndexCount().deep;this.indicesController.resetAllDeepIndices(),t=o}const s=this.cdRef.dcuplInitOptions.logging;if(s&&s.level==="debug"){const o=this.indicesController.getIndexCount();console.debug("[Filter] Caches invalidated",{granular:e!==void 0,changedAttributes:e?Array.from(e):"all",deepIndicesReset:t,shallowIndicesPreserved:o.shallow,totalIndices:o.total})}}update(e,t,s){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}updateWithChanges(e,t,s,o){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(o),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}resetCache(){this.invalidateAllCaches(),this.filteredDataStale=!0}getDeepQueryAttributes(e){const t=new Set;if(!e||!e.queries)return[];for(const s of e.queries)if(s.queries)for(const o of s.queries)o.attribute&&P.parse(o.attribute).isDeepQuery&&t.add(o.attribute);return Array.from(t)}getProjectionForQuery(e){const t=this.getDeepQueryAttributes(e);if(t.length===0)return null;const s=t.map(o=>P.parse(o));return this.projectionFor(s)}projectionFor(e){const t=this.queryBuilder.getProjectionForAttributeEntries(e);return this.item.getProjectionModels(t,this.model,this.dependencyModels),t}pathModels(e){const t=P.parse(e);return t.isDeepQuery?this.item.getProjectionModels(this.projectionFor([t]),this.model):new Set}getDependencyModels(){return this.dependencyModels}getProjectionCacheKey(e){const t=this.getDeepQueryAttributes(e);return t.length===0?"":t.sort().join("|")}getProjectedData(e,t,s){if(s&&this.projectionCache.has(s))return this.projectionCache.get(s);const o=new Map;for(const[n,i]of e){const a=this.item.getProjectedData(t,this.model,i);o.set(n,a)}return s&&this.projectionCache.set(s,o),o}getProjectedInitialData(e){const t=new Set(this.getDeepQueryAttributes(this.queryBuilder.getQuery()));t.add(e);const s=Array.from(t).sort(),o=this.projectionFor(s.map(n=>P.parse(n)));return this.getProjectedData(this.initialData,o,s.join("|"))}initFilterItems(e){[...this.model.properties.values(),...this.model.references.values()].forEach(t=>{t.filter&&(Array.isArray(e?.filterKeys)?e?.filterKeys.includes(t.key)&&this.updateFilterItem(t.key,e):this.updateFilterItem(t.key,e))})}getAggregate(e,t,s){if(P.parse(e.attribute).isDeepQuery)return at(e,t,s,e.attribute);{const o=this.model.getAttribute(e.attribute);if(!o)throw new Error("Attribute not found");return at(e,t,s,o.key)}}getSections(e){const t={_meta:{currentSize:0,initialSize:0},items:[]},s=P.parse(e.attribute),o=s.isDeepQuery;let n;if(!o&&(n=this.model.getAttribute(e.attribute),!n))throw new Error("Attribute not found");let i=new Map,a;!o&&n&&(n.type==="singleValued"||n.type==="multiValued")&&(a=this.modelParser.models.get(n.model));const l={},u=this.getSortingProjectionForModel(e,this.model);l.sort=u;let c=this.item.getItemsAsMap(this.filteredData,this.model,l);if(o){const p=this.projectionFor([s]),y=new Map;for(const[v,g]of c){const k=this.item.getProjectedData(p,this.model,g);y.set(v,k)}c=y}const d=this.indicesController.getOrCreateIndex(`${e.attribute}`,c,{childLevelSorting:u,query:this.queryBuilder.getQuery()}),f=this.getAggregate({attribute:e.attribute,types:["distinct"],excludeUndefineds:!0},c,d);if(f.distinct)for(const p of f.distinct){let y={key:p.value,value:p.value};const v=p.keys.filter(k=>c.has(k));if(a){const k=a.data.get(p.value);k&&(y=k)}const g={...y,key:p.value,_items:[],_aggregates:[],_meta:{size:v.length}};i.set(p.value,g)}const h={count:e.count,start:e.start,projection:e.projection};if(a){const p=this.getSortingProjectionForModel(e,a);h.sort=p}if(t._meta.currentSize=i.size,t._meta.initialSize=f.distinct.length,i=this.item.getItemsAsMap(i,a,h),Array.isArray(e?.aggregates)&&i.forEach(p=>{const y=f.distinct.find(g=>g.value===p.key),v=this.getDataByKeys(c,y.keys);p._aggregates=e.aggregates.map(g=>{const k=this.indicesController.getOrCreateIndex(`${g.attribute}`,v,{section:p.key,childLevelSorting:u,query:this.queryBuilder.getQuery()});return this.getAggregate(g,v,k)})}),e?.items){const p=e.items?.find(y=>y.key==="*");p?i.forEach(y=>{const v=f.distinct.find(m=>m.value===y.key),g=this.getDataByKeys(c,v.keys),k=this.item.getItems(g,this.model,p);y._items=k}):i.forEach(y=>{const v=e.items?.find(g=>g.key===y.key);if(v){const g=f.distinct.find(S=>S.value===y.key),k=this.getDataByKeys(c,g.keys),m=this.item.getItems(k,this.model,v);y._items=m}})}return t.items=Array.from(i.values()),t}getSortingProjectionForModel(e,t){const s={attributes:[],order:[]};return e?.sort?.attributes.forEach((o,n)=>{if(t.properties.has(o)){s.attributes.push(o);const i=e.sort?.order;s.order.push(i[n])}}),s}getReferenceKeyForFilterKey(e){const t=this.filterItems.get(e);return t?.attributeKey||t?.key||e}updateFilterItem(e,t={}){const s={calculateFacets:!1,excludeZeros:!0,excludeUndefineds:!0,excludeUnresolved:!0,skipProcessing:!1},o=this.getReferenceKeyForFilterKey(e);if(!o)return;const n=this.model.references.get(o);let i={};if(typeof n?.filter=="object"?i=Object.assign(s,n.filter,t):i=Object.assign(s,t),n){this.updateFilterItemReference(n.key,n.key,i);return}const a=this.model.properties.get(o);if(a)if(Array.isArray(a.filter)){a.filter.forEach(l=>{const u=l?.comparisonType||"containsIgnoreCase";this.updateFilterItemProperty(l.key,a.key,a.type,u,i)});return}else{const l=a.filter?.comparisonType||"containsIgnoreCase";this.updateFilterItemProperty(a.key,a.key,a.type,l,i);return}if(e==="key"){this.updateFilterItemProperty("key","key","string","containsIgnoreCase",i);return}}updateFilterItemReference(e,t,s){let o=[];const n=this.model.references.get(t);if(n&&!s.skipProcessing){const a=this.modelParser.models.get(n.model);o=this.getFacets(n.key,a,s)}const i={key:e,attributeKey:t,enabled:!!o.find(a=>a.enabled),selected:!!o.find(a=>a.selected),type:"reference",entries:o};this.filterItems.set(i.key,i)}updateFilterItemProperty(e,t,s,o,n){const i=this.getFilterTypeForPropertyType(s),a=this.queryBuilder.hasQueryGroup(e),l={key:e,attributeKey:t,enabled:!0,selected:!!a,type:i};if(l.type==="text"&&(l.comparisonType=o),l.type==="boolean"){const u=this.getFacets(l.attributeKey,void 0,n);l.entries=u}n.skipProcessing||(l.type==="number"&&(l.range=this.getNumberRangesForFilterItem(l)),l.type==="date"&&(l.range=this.getDateRangesForFilterItem(l))),this.filterItems.set(l.key,l)}getNumberRange(e,t=e){let s=1/0,o=-1/0;for(const a of this.filteredData.values()){const l=a[e];if(!(typeof l>"u"||l===null))if(Array.isArray(l))for(const u of l)typeof u=="number"&&(u<s&&(s=u),u>o&&(o=u));else typeof l=="number"&&(l<s&&(s=l),l>o&&(o=l))}let n=1/0,i=-1/0;for(const a of this.initialData.values()){const l=a[e];if(!(typeof l>"u"||l===null))if(Array.isArray(l))for(const u of l)typeof u=="number"&&(u<n&&(n=u),u>i&&(i=u));else typeof l=="number"&&(l<n&&(n=l),l>i&&(i=l))}return s===1/0&&(s=0),o===-1/0&&(o=0),n===1/0&&(n=0),i===-1/0&&(i=0),{available:{min:s,max:o},initial:{min:n,max:i},relatedQuery:this.queryBuilder.getQueryGroup(t)}}getNumberRangesForFilterItem(e){return this.getNumberRange(e.attributeKey,e.key)}getDateRangesForFilterItem(e){return this.getDateRange(e.attributeKey,e.key)}getDateRange(e,t=e){let s=null,o=null;for(const l of this.filteredData.values()){const u=l[e];if(typeof u>"u"||u===null)continue;const c=Array.isArray(u)?u:[u];for(const d of c)d instanceof Date&&((!s||d<s)&&(s=d),(!o||d>o)&&(o=d))}let n=null,i=null;for(const l of this.initialData.values()){const u=l[e];if(typeof u>"u"||u===null)continue;const c=Array.isArray(u)?u:[u];for(const d of c)d instanceof Date&&((!n||d<n)&&(n=d),(!i||d>i)&&(i=d))}const a=new Date;return s||(s=a),o||(o=a),n||(n=a),i||(i=a),{available:{min:s,max:o},initial:{min:n,max:i},relatedQuery:this.queryBuilder.getQueryGroup(t)}}getFacets(e,t,s,o){let n;const i=this.cacheCtrl.generateContext({attributeKey:e,query:this.queryBuilder.getQuery(),options:s}),a=this.cacheCtrl.get("facets",i);if(a)return a;let l=new Map;n=this.indicesController.getIndex(e),t?l=t.getData():l=this.indicesController.getData(e);let u=o||this.initialData;if(!o){const d=this.queryBuilder.getQueryAttributeForString(e);if(d.isDeepQuery){const f=this.projectionFor([d]);u=this.item.getItemsAsMap(u,this.model,{projection:f})}}if(!n||!l){this.indicesController.reset(e);const d=P.parse(e),f=d.isDeepQuery;let h=u;if(f){const p=this.projectionFor([d]);h=new Map;for(const[y,v]of u){const g=this.item.getProjectedData(p,this.model,v);h.set(y,g)}}h.forEach(p=>{let y;f?(y=de(p,e),y.length===0&&(y=[void 0])):y=[p[e]],this.indicesController.fillInverseIndex(e,p.key,y),this.indicesController.fillDataMap(e,y)}),n=this.indicesController.getIndex(e),t||(l=this.indicesController.getData(e))}const c=Of(u,l,s,this.queryBuilder.getQuery(),e,this.indicesController.indexMap,this.queryManager);return this.cacheCtrl.set("facets",i,c,{models:new Set([this.model.key,...this.pathModels(e)]),modelAttributes:new Map([[this.model.key,new Set([e])]])}),c}getDataByKeys(e,t){if(t){const s=new Map;return t.forEach(o=>{const n=e.get(o);n&&s.set(n.key,n)}),s}return e}getFilterTypeForPropertyType(e){switch(e){case"string":return"text";case"int":return"number";case"float":return"number";case"date":return"date";case"boolean":return"boolean";case"json":return"text";case"any":return"text";case"Array<string>":return"text";case"Array<int>":return"number";case"Array<float>":return"number";case"Array<date>":return"date"}}updateFilteredData(e){const t=ce.now();e?.skipProcessing||(this.filteredData=this.getFilteredData(this.initialData,!1),this.emitResultUpdated(t))}emitResultUpdated(e=ce.now()){this.cdRef.trigger({scope:"list",type:"result_updated",action:"update",connectMessage:!0,listKey:this.cdRef.key,modelKey:this.model.key,start:e})}getFilteredData(e,t){const s=this.cacheCtrl.generateContext({query:this.queryBuilder.getQuery(),earlyReturn:t}),o=this.cacheCtrl.get("data",s);if(o)return o;const n=this.queryBuilder.getQuery(),i=this.getProjectionForQuery(n);let a;if(i){const u=this.getProjectionCacheKey(n),c=this.getProjectedData(e,i,u),d=this.queryManager.queryData(c,n,t,this.indicesController.indexMap);a=new Map;for(const f of d.keys())e.has(f)&&a.set(f,e.get(f))}else a=this.queryManager.queryData(e,n,t,this.indicesController.indexMap);const l=i?this.item.getProjectionModels(i,this.model):new Set;return this.cacheCtrl.set("data",s,a,{models:new Set([this.model.key,...l]),modelAttributes:new Map}),a}getFilterItems(e){if(Array.isArray(e?.filterKeys)){const t=[];return e?.filterKeys.forEach(s=>{const o=this.getFilterItem(s,e);o&&t.push(o)}),t}else return e?.skipProcessing||this.initFilterItems(e),Array.from(this.filterItems.values())}getFilterItem(e,t){return this.filterItems.has(e)&&(t?.skipProcessing||this.updateFilterItem(e,t)),this.filterItems.get(e)}},Go=class{constructor(e,t){this.modelParser=e,this.scriptController=t}modelParser;scriptController;getItem(e,t,s,o){const n=o?.projection||{$:!0},i=t.get(e);return i?this.getProjectedData(n,s,i):null}getManyItems(e,t,s,o){const n=[];for(const i of e){const a=o?.projection||{$:!0},l=t.get(i);if(!l)continue;const u=this.getProjectedData(a,s,l);n.push(u)}return n}getItems(e,t,s){const o=this.getItemsAsMap(e,t,s);return Array.from(o.values())}getItemsAsMap(e,t,s){const o=s?.start||0,n=s?.count??e.size,i=s?.projection||{$:!0};return this.isValidSortProjection(s?.sort)&&(e=this.getSortedItems(e,s,t)),this.isValidScriptSorting(s?.sort)&&(e=this.getSortedItemsBasedOnScript(e,s)),this.getPagedData(e,o,n,i,t)}getSortedItemsBasedOnScript(e,t){const s=Array.from(e.values()),o=t?.sort?.script?.key||"",n=t?.sort?.script?.options||void 0;if(!this.scriptController.hasScript(o))return e;const i=this.scriptController.executeScript(o,"sort",{options:n,items:s});return new Map(i.map(a=>[a.key,a]))}getSortedItems(e,t,s){const o=[...t.sort.attributes],n=Array.from(e.values()),i=(c,d,f)=>{const h=c[d];return typeof h>"u"||h===null?f:typeof h=="string"?h.toLowerCase():typeof h=="object"&&typeof h?.key=="string"?h.key.toLowerCase():h},a=o.map((c,d)=>f=>{const h=t.sort.order.at(d),p=this.getUndefinedValueForSorting(c,h,s);return i(f,c,p)}),l=[...t.sort.order].map(c=>c.toLowerCase()),u=$o(n,[...a],l);return new Map(u.map(c=>[c.key,c]))}getUndefinedValueForSorting(e,t,s){const o=s?.properties.get(e);if(o){if(o.type==="string"){if(t=="ASC")return;if(t=="DESC")return""}if(o.type==="int"||o.type==="float"||o.type==="date"||o.type==="boolean"){if(t=="ASC")return 1/0;if(t=="DESC")return-1/0}}}isValidProjection(e){return!(!e||e.$===!0&&Object.keys(e).length===1)}getPagedData(e,t,s,o,n){const i=e.entries(),a=new Map;if(t===0&&s===e.size&&o?.$===!0&&Object.keys(o).length===1)return e;for(let l=0;l<t+s;l++){if(l<t){i.next();continue}if(l>t+s)break;const u=i.next().value;if(u)if(n&&o&&this.isValidProjection(o)){const c=this.getProjectedData(o,n,u[1]);a.set(u[0],c)}else a.set(u[0],u[1])}return a}isValidScriptSorting(e){return!(!e||!e.script)}isValidSortProjection(e){const t=["ASC","DESC"];return!(!e||!Array.isArray(e.attributes)||e.attributes.length===0||!Array.isArray(e.order)||e.attributes.length!==e.order.length||Yf(e.order,t).length>0)}getProjectedData(e,t,s){let o={key:s.key};return e.$===!0&&(o=Object.assign({},s)),e.$$===!0&&(o=Object.assign({},s),t.references.forEach(n=>{e[n.key]||(e[n.key]={$:!0})})),Object.keys(e).filter(n=>n!=="$"&&n!=="$$").forEach(n=>{const i=e[n];if(i===!1){delete o[n];return}if(i===!0){o[n]=s[n];return}if(typeof i=="object"){const a=t.references.get(n);if(a){const l=this.modelParser.models.get(a.model);if(l){if(a.type==="multiValued"){const u=s[n]||[];o[n]=u.map(c=>{const d=typeof c=="string"?c:c.key,f=l.getEntry(d);return f?this.getProjectedData(i,l,f):this.modelParser.initOptions.referenceMetadata?.enabled?{key:d,_dcupl_ref_:"miss"}:null}).filter(Boolean)}else if(a.type==="singleValued"){const u=s[n];if(u){const c=typeof u=="string"?u:u.key,d=l?.getEntry(c);d?o[n]=this.getProjectedData(i,l,d):this.modelParser.initOptions.referenceMetadata?.enabled?o[n]={key:c,_dcupl_ref_:"miss"}:delete o[n]}}}}}}),o}getProjectionModels(e,t,s=new Set){if(!e||typeof e!="object")return s;for(const[o,n]of Object.entries(e)){if(o==="$"||o==="$$"||typeof n!="object"||n===null)continue;const i=t.references.get(o);if(!i)continue;s.add(i.model);const a=this.modelParser.models.get(i.model);a&&this.getProjectionModels(n,a,s)}return s}};var ep=Object.defineProperty,tp=Object.getOwnPropertyDescriptor,I=(r,e,t,s)=>{for(var o=tp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&ep(e,t,o),o};let j=class{constructor(e,t,s){this.dcuplApi=e,this.cdRef=t,this.indicesController=s,this.itemService=new Go(this.dcuplApi.modelParser,this.dcuplApi.scriptController),this.filter=new Xf(this.dcuplApi.modelParser,this.cdRef,this.itemService,this.indicesController,this.dcuplApi.queryManager)}dcuplApi;cdRef;indicesController;metadata;model;filter;itemService;log=Te.child({prefix:"Catalog"});initListeners(){this.initListMetadata()}initListMetadata(){this.metadata={key:this.model.key,currentSize:this.filter.filteredData.size,initialSize:this.filter.initialData.size,attributes:this.getModelAttributes(),views:this.getViews(),appliedQuery:this.filter.queryBuilder.getQuery()}}getModelAttributes(){return[...this.model.references.values(),...this.model.properties.values()]}query={apply:(e,t)=>this.applyQuery(e,t),applyOptions:(e,t)=>this.applyOptions(e,t),remove:e=>this.removeQuery(e),reset:(e={skipProcessing:!1})=>this.resetQuery(e),execute:e=>this.executeQuery(e),one:e=>this._getItem(e),many:e=>this._getManyItems(e),get:()=>this.getQuery(),has:e=>this.hasGroupOrQueryKey(e),addCondition:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setCondition:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),addGroup:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setGroup:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),removeCondition:(e,t)=>{if(Array.isArray(e)){for(const s of e)this.removeQuery(s,t);return this.getQuery()}return this.removeQuery(e,t)},removeGroup:(e,t)=>this.removeQuery({groupKey:e},t),clear:e=>this.resetQuery(e),current:()=>this.getQuery(),isEmpty:()=>this.getQuery().queries.length===0,items:e=>this.executeQuery(e),first:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t)[0]},any:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t).length>0},count:e=>this.executeQuery(e).length};filters={get:e=>this.getFilter(e),getAll:e=>this.getFilters(e)};fn={pivot:e=>this._getPivot(e),aggregate:e=>this.getAggregate(e),suggest:e=>this._getSuggestions(e),groupBy:e=>this._getSections(e),facets:e=>this._getFacets(e),metadata:()=>this._getMetadata()};getViews(){const e=[];return this.filter.modelParser.views.forEach(t=>{t.model===this.model.key&&e.push(t)}),e}_getMetadata(){return this.initListMetadata(),this.metadata}getFilters(e){return this._getFilters(e)}_getFilters(e){const t=this.filter.getFilterItems(e);return e?.filterKeys?e.filterKeys.map(s=>{const o=t.find(n=>n.key===s);return o||this.log.error("Filter not found",void 0,{filterKey:s,model:this.model.key}),o}).filter(Boolean):t}getFilter(e){return this._getFilter(e)}_getFilter(e){return this.filter.getFilterItem(e.filterKey,e)}getQuery(){return this.filter.queryBuilder.getQuery()}hasGroupOrQueryKey(e){return this.filter.queryBuilder.has(e)}applyQuery(e,t){const s=this.filter.queryBuilder.applyQuery(e,t);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}applyOptions(e,t){const s=this.filter.queryBuilder.applyOptions(e,t?.mode);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}removeQuery(e,t){let s;return e?s=this.filter.queryBuilder.removeQuery(e):s=this.filter.queryBuilder.removeAllQueries(),this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}resetQuery(e){const t=this.filter.queryBuilder.reset();return this.filter.updateFilteredData({skipProcessing:e?.skipProcessing}),t}executeQuery(e){if(!e)e=this.filter.queryBuilder.getQuery();else if(!e.queries){const i=this.filter.queryBuilder.getQuery();e=Object.assign({},i,e)}const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("query",t))return this.filter.cacheCtrl.get("query",t);const s=Object.assign({},e,{queries:e.queries??[],modelKey:this.model.key}),o=this.dcuplApi.queryManager.queryData(this.filter.filteredData,s,!1,this.filter.indicesController.indexMap),n=this.itemService.getItems(o,this.model,e);return this.filter.cacheCtrl.set("query",t,n),n}_getSections(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("sections",t))return this.filter.cacheCtrl.get("sections",t);const s=this.filter.getSections(e);return this.filter.cacheCtrl.set("sections",t,s),s}_getItem(e){return this.itemService.getItem(e.itemKey,this.filter.filteredData,this.model,e)}_getManyItems(e){return this.itemService.getManyItems(e.itemKeys,this.filter.filteredData,this.model,e)}_getSuggestions(e){typeof e.excludeUndefineds>"u"&&(e.excludeUndefineds=!0),typeof e.excludeNulls>"u"&&(e.excludeNulls=!0),typeof e.calculateResultKeys>"u"&&(e.calculateResultKeys=!0);const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("suggestions",t))return this.filter.cacheCtrl.get("suggestions",t);const s=P.parse(e.attribute).isDeepQuery;if(!s&&!this.model.getAttribute(e.attribute))throw new Error(`Attribute ${e.attribute} does not exist`);const o=Ar(e.value,e.regexFlags);if(o)try{new RegExp(o.pattern,o.flags)}catch{return[]}let n,i;if(e.relevantData==="all")n=this.filter.initialData,i={modelKey:this.model.key,queries:[]};else if(e.relevantData==="filtered")n=this.filter.filteredData,i=this.filter.queryBuilder.getQuery();else if(e.relevantData==="excludeQuery"&&e.excludeQuery){const c=new ke;c.init(this.filter.queryBuilder.getQuery()),c.removeQuery(e.excludeQuery),i=c.getQuery(),n=this.dcuplApi.queryManager.queryData(this.filter.initialData,i,!1,this.filter.indicesController.indexMap)}else n=this.filter.filteredData,i=this.filter.queryBuilder.getQuery();let a=n;if(s){const c=P.parse(e.attribute),d=this.filter.projectionFor([c]),f=new Map;for(const[h,p]of n){const y=this.filter.item.getProjectedData(d,this.model,p);f.set(h,y)}a=f}const l=this.filter.indicesController.getOrCreateIndex(e.attribute,a,{query:i}),u=kf(a,l,e,this.dcuplApi.queryManager);return this.filter.cacheCtrl.set("suggestions",t,u),u}_getFacets(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("facets",t))return this.filter.cacheCtrl.get("facets",t);const s=P.parse(e.attribute).isDeepQuery;let o;if(!s){const i=this.model.references.get(e.attribute);i&&(o=this.filter.modelParser.models.get(i.model))}const n=s?this.filter.getProjectedInitialData(e.attribute):void 0;return this.computeFacetsInternal(e,o,t,n)}computeFacetsInternal(e,t,s,o){typeof e.excludeZeros>"u"&&(e.excludeZeros=!0),typeof e.excludeUndefineds>"u"&&(e.excludeUndefineds=!0),typeof e.excludeUnresolved>"u"&&(e.excludeUnresolved=!0),typeof e.calculateResults>"u"&&(e.calculateResults=!0);const n=this.filter.getFacets(e.attribute,t,{calculateFacets:e.calculateResults,count:e.count,excludeZeros:e.excludeZeros,excludeUndefineds:e.excludeUndefineds,excludeUnresolved:e.excludeUnresolved,sort:e.sort,excludeGroup:e.excludeGroup,skipProcessing:!1},o);return this.filter.cacheCtrl.set("facets",s,n),n}getAggregate(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("aggregation",t))return this.filter.cacheCtrl.get("aggregation",t);const s=P.parse(e.attribute);let o=this.filter.filteredData;if(s.isDeepQuery){const i=this.filter.projectionFor([s]),a=new Map;for(const[l,u]of this.filter.filteredData){const c=this.filter.item.getProjectedData(i,this.model,u);a.set(l,c)}o=a}const n=this.filter.getAggregate(e,o,this.filter.indicesController.getOrCreateIndex(e.attribute,o,this.filter.queryBuilder.getQuery()));return this.filter.cacheCtrl.set("aggregation",t,n),n}_getPivot(e){if(!e||!Array.isArray(e.columns)||!Array.isArray(e.rows)||!e.values||!e.values.length)return this.log.error("Invalid pivot options",void 0,{model:this.model.key}),{key:"invalid_options"};const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("pivot",t))return this.filter.cacheCtrl.get("pivot",t);let s=new Mt;this.filter.filteredData.size===this.filter.initialData.size&&(s=this.filter.indicesController);const o=[...e.rows.map(a=>a.attribute),...e.columns.map(a=>a.attribute),...e.values.map(a=>a.attribute)].map(a=>P.parse(a)).filter(a=>a.isDeepQuery);let n;if(o.length>0){const a=this.filter.projectionFor(o);n=new Map;for(const[l,u]of this.filter.filteredData){const c=this.filter.item.getProjectedData(a,this.model,u);n.set(l,c)}}const i=_r(this.filter.filteredData,e,{key:"root"},"root",s,n);return this.filter.cacheCtrl.set("pivot",t,i),i}};I([b({scope:"list",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getMetadata"),I([b({scope:"list",type:"filter_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFilters"),I([b({scope:"list",type:"filter_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFilter"),I([b({scope:"list",type:"query_get",cloneResult:!0})],j.prototype,"getQuery"),I([b({scope:"list",type:"query_has"})],j.prototype,"hasGroupOrQueryKey"),I([b({scope:"list",type:"query_apply",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"applyQuery"),I([b({scope:"list",type:"query_apply_options",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"applyOptions"),I([b({scope:"list",type:"query_remove",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"removeQuery"),I([b({scope:"list",type:"query_reset",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"resetQuery"),I([b({scope:"list",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"executeQuery"),I([b({scope:"list",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getSections"),I([b({scope:"list",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getItem"),I([b({scope:"list",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getManyItems"),I([b({scope:"list",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getSuggestions"),I([b({scope:"list",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFacets"),I([b({scope:"list",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"getAggregate"),I([b({scope:"list",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getPivot");let rp=class extends j{constructor(e,t,s){super(e,t,s),this.dcuplApi=e,this.cdRef=t,this.indicesController=s}dcuplApi;cdRef;indicesController;listKey;init(e,t,s){this.listKey=e,this.model=t,this.filter.init(t,s),super.initListeners()}update(e,t,s){this.model=e,this.filter.update(e,t,s)}};function sp(r,e){var t=-1,s=r.length;for(e||(e=Array(s));++t<s;)e[t]=r[t];return e}function op(r,e,t,s){var o=!t;t||(t={});for(var n=-1,i=e.length;++n<i;){var a=e[n],l=void 0;l===void 0&&(l=r[a]),o?At(t,a,l):As(t,a,l)}return t}function np(r,e,t){if(!z(t))return!1;var s=typeof e;return(s=="number"?te(t)&&er(e,t.length):s=="string"&&e in t)?Je(t[e],r):!1}function ip(r){return tr(function(e,t){var s=-1,o=t.length,n=o>1?t[o-1]:void 0,i=o>2?t[2]:void 0;for(n=r.length>3&&typeof n=="function"?(o--,n):void 0,i&&np(t[0],t[1],i)&&(n=o<3?void 0:n,o=1),e=Object(e);++s<o;){var a=t[s];a&&r(e,a,s,n)}return e})}function ap(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var lp=Object.prototype,up=lp.hasOwnProperty;function cp(r){if(!z(r))return ap(r);var e=sr(r),t=[];for(var s in r)s=="constructor"&&(e||!up.call(r,s))||t.push(s);return t}function Bo(r){return te(r)?Ms(r,!0):cp(r)}var dp="[object Object]",fp=Function.prototype,pp=Object.prototype,Uo=fp.toString,hp=pp.hasOwnProperty,yp=Uo.call(Object);function gp(r){if(!K(r)||ee(r)!=dp)return!1;var e=qs(r);if(e===null)return!0;var t=hp.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Uo.call(t)==yp}function mp(r,e,t,s){for(var o=-1,n=r==null?0:r.length;++o<n;){var i=r[o];e(s,i,t(i),r)}return s}function vp(r,e,t,s){return yr(r,function(o,n,i){e(s,o,t(o),i)}),s}function bp(r,e){return function(t,s){var o=E(t)?mp:vp,n={};return o(t,r,Re(s),n)}}function xr(r,e,t){(t!==void 0&&!Je(r[e],t)||t===void 0&&!(e in r))&&At(r,e,t)}function Er(r,e){if(!(e==="constructor"&&typeof r[e]=="function")&&e!="__proto__")return r[e]}function kp(r){return op(r,Bo(r))}function wp(r,e,t,s,o,n,i){var a=Er(r,t),l=Er(e,t),u=i.get(l);if(u){xr(r,t,u);return}var c=n?n(a,l,t+"",r,e,i):void 0,d=c===void 0;if(d){var f=E(l),h=!f&&Ye(l),p=!f&&!h&&nr(l);c=l,f||h||p?E(a)?c=a:Ie(a)?c=sp(a):h?(d=!1,c=Us(l,!0)):p?(d=!1,c=Xs(l,!0)):c=[]:gp(l)||Ze(l)?(c=a,Ze(a)?c=kp(a):(!z(a)||Zt(a))&&(c=eo(l))):d=!1}d&&(i.set(l,c),o(c,l,s,n,i),i.delete(l)),xr(r,t,c)}function No(r,e,t,s,o){r!==e&&vo(e,function(n,i){if(o||(o=new L),z(n))wp(r,e,i,t,No,s,o);else{var a=s?s(Er(r,i),n,i+"",r,e,o):void 0;a===void 0&&(a=n),xr(r,i,a)}},Bo)}var Ap=Object.prototype,$p=Ap.hasOwnProperty,jr=bp(function(r,e,t){$p.call(r,t)?r[t].push(e):At(r,t,[e])}),Cp="[object Boolean]";function Dp(r){return r===!0||r===!1||K(r)&&ee(r)==Cp}var Mr=ip(function(r,e,t){No(r,e,t)});const V=(r,e,t)=>({title:r,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",attribute:e,description:t}),_p=r=>{const e=["any","Array<date>","Array<float>","Array<int>","Array<string>","boolean","date","float","int","json","string"];if(!r.key)return V("Invalid Property",r.key,"Property key is missing");if(!r.type||e.indexOf(r.type)===-1)return V("Invalid Property",r.key,"Property type is invalid");if("derive"in r){if(!r.derive?.localReference)return V("Invalid Property",r.key,"Derived Property localReference is missing");if(!r.derive.remoteProperty)return V("Invalid Property",r.key,"Derived Property remoteProperty is missing")}if("expression"in r&&typeof r.expression!="string")return V("Invalid Property",r.key,"Expression is invalid")},Pp=r=>{const e=["multiValued","singleValued"];if(!r.key)return V("Invalid Reference",r.key,"Reference key is missing");if(!r.type||e.indexOf(r.type)===-1)return V("Invalid Reference",r.key,"Reference type is invalid");if(!r.model)return V("Invalid Reference",r.key,"Reference model is missing");if("derive"in r){if(!r.derive.localReference)return V("Invalid Reference",r.key,"Derived Reference localReference is missing");if(!r.derive.remoteReference)return V("Invalid Reference",r.key,"Derived Reference remoteReference is missing")}if("resolve"in r){if(!r.resolve.reference)return V("Invalid Reference",r.key,"Resolved Reference reference is missing");if(!r.resolve.model)return V("Invalid Reference",r.key,"Resolved Reference model is missing")}if("groupBy"in r&&!r.groupBy.reference)return V("Invalid Reference",r.key,"Grouped Reference reference is missing")},xp=r=>{if(typeof r.key!="string"||r.key.length===0)throw new Error("Invalid Model: key must be a non-empty string");if(typeof r.keyProperty<"u"){const e=r.keyProperty,t=typeof e=="string"&&e.length>0,s=Array.isArray(e)&&e.length>0&&e.every(o=>typeof o=="string"&&o.length>0);if(!t&&!s)throw new Error("Invalid Model: keyProperty must be a non-empty string or a non-empty array of non-empty strings")}if(typeof r.keyPropertySeparator<"u"&&(typeof r.keyPropertySeparator!="string"||r.keyPropertySeparator.length===0))throw new Error("Invalid Model: keyPropertySeparator must be a non-empty string");if(typeof r.autoGenerateKey<"u"&&typeof r.autoGenerateKey!="boolean")throw new Error("Invalid Model: autoGenerateKey must be a boolean");if(typeof r.autoGenerateProperties<"u"){const e=r.autoGenerateProperties;if(typeof e!="boolean"){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("Invalid Model: autoGenerateProperties must be a boolean or an options object");if(typeof e.deep<"u"&&typeof e.deep!="boolean")throw new Error("Invalid Model: autoGenerateProperties.deep must be a boolean");if(typeof e.sampleSize<"u"&&(typeof e.sampleSize!="number"||!Number.isFinite(e.sampleSize)||e.sampleSize<1))throw new Error("Invalid Model: autoGenerateProperties.sampleSize must be a positive number")}}if(r.properties&&!Array.isArray(r.properties))throw new Error("Invalid Model: properties must be an array");if(r.references&&!Array.isArray(r.references))throw new Error("Invalid Model: references must be an array");return!0},Ep=(r,e)=>{const t=[];return r.references.forEach(s=>{e.has(s.model)||t.push({title:"Missing Model",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingModel",attribute:s.key,model:r.key,description:`Referenced model ${s.model} does not exist`}),"derive"in s&&t.push(...jp(s,r,e)),"resolve"in s&&t.push(...Mp(s,r,e)),"groupBy"in s&&t.push(...Sp(s,r))}),r.properties.forEach(s=>{"derive"in s&&t.push(...Rp(s,r,e)),"expression"in s&&t.push(...Ip(s,r))}),t},jp=(r,e,t)=>{const s=[],o=e.references.get(r.derive.localReference);if(!o)return s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Local Referenced ${r.derive.localReference} does not exist in model ${e.key}`}),s;const n=t.get(o.model);return n&&(n.references.get(r.derive.remoteReference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Remote Reference ${r.derive.remoteReference} does not exist in model ${n.key}`})),s},Mp=(r,e,t)=>{const s=[],o=t.get(r.resolve.model);return o?(o.references.get(r.resolve.reference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Resolved Reference ${r.resolve.reference} does not exist in model ${o.key}`}),s):(s.push({title:"Missing Model",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingModel",attribute:r.key,model:e.key,description:`Referenced model ${r.model} does not exist`}),s)},Sp=(r,e)=>{const t=[];return e.references.get(r.groupBy.reference)||t.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Resolved Reference ${r.groupBy.reference} does not exist in model ${e.key}`}),t},Rp=(r,e,t)=>{const s=[],o=e.references.get(r.derive.localReference);if(!o)return s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Local Referenced ${r.derive.localReference} does not exist in model ${e.key}`}),s;const n=t.get(o.model);if(n){if(r.derive.remoteProperty==="key")return s;n.properties.get(r.derive.remoteProperty)||s.push({title:"Missing Property",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingProperty",attribute:r.key,model:e.key,description:`Remote Property ${r.derive.remoteProperty} does not exist in model ${n.key}`})}return s},Ip=(r,e)=>{const t=[];return Pr(r.expression).variables.forEach(s=>{s.name==="key"||s.name.endsWith(".key")||!e.properties.get(s.name)&&!e.references.get(s.name)&&t.push({title:"Unknown Expression Variable",type:"model",errorGroup:"ModelDefinitionError",errorType:"UnknownExpressionVariable",attribute:r.key,model:e.key,description:`Expression Variable ${s.name} not found in expression ${r.key} in ${e.key}`})}),t},we="::";function Tp(r){return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function zo(r,e,t=we){return typeof e=="string"?String(r[e]):e.length===1?String(r[e[0]]):e.map(s=>String(r[s])).join(t)}function Sr(r,e=we){if(r!==void 0)return typeof r=="string"?r:r.join(e)}const Op={REF_VALUE:"_dcupl_ref_"},Lo={required:!0,forceStrictDataType:!1,nullable:!1,validatorHandling:"loose"},Wo={enabled:!0,attributes:Lo};let Kp=class{constructor(e){this.modelParser=e,this.cdRef=e.cdRef}modelParser;properties=new Map;references=new Map;attributeQualityConfigs=new Map;key;log=Te.child({prefix:"Model"});initialDefinition;data=new Map;supportsAutoCreation=!1;autoGenerateKey=!1;autoGenerateProperties=!1;autoGeneratePropertiesOption=!1;keyProperty="key";keyPropertySeparator;valueMappings=[];meta;qualityConfig=Wo;indicesController=new Mt;cdRef;groupedRefReverseIndex=new Map;init(e){this.key=e.key,this.initialDefinition=e,e.quality&&(this.qualityConfig=Mr({},Wo,e.quality))}applyPropertiesAndReferences(e){const t=new Set;e.properties?.map(s=>{const o=_p(s);if(o)o.model=this.key,this.setError(o);else{if(t.has(s.key)){this.setError({title:"Duplicate Property Key",type:"model",errorGroup:"ModelDefinitionError",errorType:"DuplicatePropertyKey",description:`Model "${this.key}" declares property "${s.key}" more than once; the first definition is kept and the duplicate is ignored.`,attribute:s.key,model:this.key});return}t.add(s.key),this.setAttributeQualityConfig(s),this.properties.set(s.key,s)}}),e.references?.map(s=>{const o=Pp(s);o?(o.model=this.key,this.setError(o)):(s.validity=s.validity||"loose",this.setAttributeQualityConfig(s),this.references.set(s.key,s))}),this.supportsAutoCreation=!!e.supportsAutoCreation,this.keyProperty=e.keyProperty||"key",this.keyPropertySeparator=e.keyPropertySeparator,this.autoGenerateKey=!!e.autoGenerateKey,this.autoGenerateProperties=!!e.autoGenerateProperties,this.autoGeneratePropertiesOption=e.autoGenerateProperties??!1,this.valueMappings=e.valueMappings||[],this.meta=e.meta}setAttributeQualityConfig(e){const t=this.qualityConfig.attributes,s=Mr({},Lo,t,e.quality);this.attributeQualityConfigs.set(e.key,s)}getModelDefinition(){return this.autoGenerateProperties?{key:this.key,keyProperty:this.keyProperty,keyPropertySeparator:this.keyPropertySeparator,references:Array.from(this.references.values()),properties:Array.from(this.properties.values()),autoGenerateKey:this.autoGenerateKey,supportsAutoCreation:this.supportsAutoCreation,valueMappings:this.valueMappings,meta:this.meta,autoGenerateProperties:this.autoGeneratePropertiesOption,quality:this.qualityConfig}:this.initialDefinition}generatePropertiesFromContainer(e){const t=this.autoGeneratePropertiesOption;(typeof t=="object"&&t!==null?qo(e.data,t):qo(e.data,!1)).map(s=>{if(!this.properties.has(s.key)){if(s.key==="key")return;const o=e.keyProperty??this.keyProperty;Tp(o).some(n=>n&&n!=="key"&&n===s.key)&&(s.type="string"),s.filter=!0,this.properties.set(s.key,s)}})}getReferenceKeys(e){return e.map(t=>{if(typeof t=="string")return String(t.trim());if(typeof t=="number")return String(t);if(t===null)return"null";if(typeof t=="object"&&t&&t.key)return t.key})}setError(e){this.modelParser.qualityController.enabled&&this.qualityConfig.enabled===!0&&(e.model=this.key,this.modelParser.qualityController.setError(e))}emitUnknownColumnErrors(e,t,s,o,n){const i=new Set;for(const l of s)i.add(l.key);for(const l of o)i.add(l.key);const a=e.keyProperty??this.keyProperty;if(typeof a=="string")i.add(a);else if(Array.isArray(a))for(const l of a)i.add(l);i.add("key");for(const l of t)i.has(l)||this.setError({title:"Unknown Column",type:"model",errorGroup:"DataContainerError",errorType:"UnknownColumn",description:`Column "${l}" in the source for model "${e.model}" is not declared on the model; its values are dropped during ingest`,attribute:l,model:e.model,meta:{column:l,origin:n}})}processBasicProperty(e,t,s,o="inline"){const n=t[e.key],i=this.attributeQualityConfigs.get(e.key);let a;if(typeof n>"u"){if(i?.required){const l=e.type;this.setError({title:"Undefined Value",type:"model",errorGroup:"PropertyDataError",errorType:"UndefinedValue",description:`The required ${l??""} property "${e.key}" in the "${this.key}" model is undefined (no value)`.replace(/\s+/g," "),itemKey:t.key,attribute:e.key,model:this.key,meta:{rawValue:n,declaredType:l,origin:o}})}return}else{if(n===null)i?.nullable||this.setError({title:"Null Value",description:`The value of the property "${e.key}" in the "${this.key}" model should not be null`,type:"model",errorGroup:"PropertyDataError",errorType:"NullValue",itemKey:t.key,attribute:e.key,model:this.key}),a=n;else if(e.type==="string"){if(a=this.processStringProperty(e,n,t),typeof a>"u")return}else if(e.type==="int"){if(a=this.processIntProperty(e,n,t),typeof a>"u")return}else if(e.type==="float"){if(a=this.processFloatProperty(e,n,t),typeof a>"u")return}else if(e.type==="date"){if(a=this.processDateProperty(e,n,t),typeof a>"u")return}else if(e.type==="json"){if(a=this.processJSONProperty(e,n,t),typeof a>"u")return}else if(e.type==="boolean"){if(a=this.processBooleanProperty(e,n,t),typeof a>"u")return}else if(e.type==="any")a=n;else if(e.type==="Array<string>"){const l=this.getValueAsArray(n,e?.separator);Array.isArray(l)&&(a=[],l.forEach(u=>{const c=this.processStringProperty(e,u,t);typeof c<"u"&&a.push(c)}))}else if(e.type==="Array<int>"){const l=this.getValueAsArray(n,e?.separator);Array.isArray(l)&&(a=[],l.forEach(u=>{const c=this.processIntProperty(e,u,t);typeof c<"u"&&a.push(c)}))}else if(e.type==="Array<float>"){const l=this.getValueAsArray(n,e?.separator);Array.isArray(l)&&(a=[],l.forEach(u=>{const c=this.processFloatProperty(e,u,t);typeof c<"u"&&a.push(c)}))}else if(e.type==="Array<date>"){const l=this.getValueAsArray(n,e?.separator);Array.isArray(l)&&(a=[],l.forEach(u=>{const c=this.processDateProperty(e,u,t);typeof c<"u"&&a.push(c)}))}s[e.key]=a}e.index&&(this.indicesController.fillInverseIndex(e.key,s.key,[a]),this.indicesController.fillDataMap(e.key,[a]))}handleValidators(e,t,s){if(!this.modelParser.qualityController.enabled||this.qualityConfig.enabled!==!0)return!0;let o=!0;try{if(t.quality?.validators){const n=this.modelParser.qualityController.validateAttribute(e,t.quality.validators,t.key);for(const i of n)o=!1,i.attribute=t.key,i.itemKey=s.key,i.model=this.key,this.setError(i)}}catch(n){this.log.error("Validator definition error",n)}return o}getWrongDataTypeError(e,t,s){return{title:"Wrong Data Type",type:"model",errorGroup:"PropertyDataError",errorType:"WrongDataType",itemKey:s.key,attribute:e.key,model:this.key,description:`Expect ${e.type} but got ${typeof t} with value ${t}`,meta:{expected:e.type,rawValue:t,typeof:typeof t}}}isLossyNumericCoercion(e,t,s){const o=Number(typeof e=="string"?e.trim():e);return isNaN(o)?!0:s?o!==t:!1}getLossyCoercionError(e,t,s,o){return{title:"Lossy Data Coercion",type:"model",errorGroup:"PropertyDataError",errorType:"WrongDataType",itemKey:o.key,attribute:e.key,model:this.key,description:`Lossy coercion to ${e.type}: raw value "${t}" was coerced to ${s}`,meta:{expected:e.type,rawValue:t,coercedValue:s,typeof:typeof t,lossy:!0}}}getValueAsArray(e,t=","){if(e)return Array.isArray(e)?e:e&&typeof e=="string"?e.split(t).map(s=>s.trim()):[]}processStringProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);let n=t;if(o?.forceStrictDataType){if(!Et(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}}else if(n=String(t),!Et(n)&&n!=t){this.setError(this.getWrongDataTypeError(e,t,s));return}if(!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processIntProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);if(o?.forceStrictDataType){if(!Qo(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}const n=parseInt(t,10);if(isNaN(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}if(this.isLossyNumericCoercion(t,n,!0)&&this.setError(this.getLossyCoercionError(e,t,n,s)),!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processFloatProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);if(o?.forceStrictDataType){if(!Vo(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}let n;const i=e.fractionDigits;if(typeof i>"u"?n=parseFloat(t):n=parseFloat(parseFloat(t).toFixed(i)),isNaN(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}if(this.isLossyNumericCoercion(t,n,!1)&&this.setError(this.getLossyCoercionError(e,t,n,s)),!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processJSONProperty(e,t,s){if(this.attributeQualityConfigs.get(e.key)?.forceStrictDataType){if(!K(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}if(K(t))return t;if(!K(t)&&typeof t=="string")try{return JSON.parse(t)}catch{this.setError(this.getWrongDataTypeError(e,t,s));return}}processBooleanProperty(e,t,s){if(this.attributeQualityConfigs.get(e.key)?.forceStrictDataType){if(!Dp(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}return!!t}processDateProperty(e,t,s){if(t===""){this.setError(this.getWrongDataTypeError(e,t,s));return}const o=e.inputFormat;let n;try{if(o&&typeof o=="string"){let i=t;typeof i!="string"&&(i=String(i)),n=_f(i,o,new Date)}else n=new Date(t)}catch(i){this.log.error("Property extraction error",i,{property:e.key,model:this.key}),this.setError(this.getWrongDataTypeError(e,t,s));return}if(!To(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}return e.UTC&&(n=new Date(Date.UTC(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),n.getMilliseconds()))),n}processSingleValuedReference(e,t,s){const o=this.modelParser.models.get(e.model);if(!o)return;let n="";typeof t=="string"?n=t:typeof t=="object"&&t&&t.key&&(n=t.key);const i=o.getEntry(String(n));if(!i){if(o.supportsAutoCreation){const l=this.handleAutoCreationAndReturnKey(o,t);this.indicesController.fillInverseIndex(e.key,s.key,[t]),s[e.key]=l,this.setRefValue(l,"auto_hit");return}else if(this.indicesController.fillInverseIndex(e.key,s.key,[n]),this.setError({title:"Remote Reference Key Not Found",type:"model",errorGroup:"ReferenceDataError",errorType:"RemoteReferenceKeyNotFound",itemKey:s.key,attribute:e.key,description:`The reference "${e.key}" in the "${this.key}" model can not find the value "${t}" in the remote model "${e.model}"`,meta:{remoteModel:e.model,remoteKey:t}}),e.validity==="strict")return}this.indicesController.fillInverseIndex(e.key,s.key,[n]);const a={key:String(n)};s[e.key]=a,!i&&!o.supportsAutoCreation&&e.validity!=="strict"?this.setRefValue(a,"miss"):this.setRefValue(a,"hit")}processMultiValuedReference(e,t,s){const o=this.modelParser.models.get(e.model);if(!o)return;const n=this.getReferenceKeys(t),i=[];n.forEach((a,l)=>{const u=o.getEntry(String(a));if(!u){if(o.supportsAutoCreation){const d=this.handleAutoCreationAndReturnKey(o,t[l]);this.setRefValue(d,"auto_hit"),i.push(d);return}else if(this.setError({title:"Remote Reference Key Not Found",type:"model",errorGroup:"ReferenceDataError",errorType:"RemoteReferenceKeyNotFound",itemKey:s.key,attribute:e.key,description:`The reference "${e.key}" in the "${this.key}" model can not find the value "${a}" in the remote model "${e.model}"`,meta:{remoteModel:e.model,remoteKey:a}}),e.validity==="strict")return}const c={key:a};!u&&!o.supportsAutoCreation&&e.validity!=="strict"?this.setRefValue(c,"miss"):this.setRefValue(c,"hit"),i.push(c)}),this.indicesController.fillInverseIndex(e.key,s.key,i.map(a=>a.key)),s[e.key]=i}getViewKeys(){return this.modelParser._getViewKeys({modelKey:this.key})}addBasicPropertiesAndReferences(e){const t=this.getBasicProperties(),s=this.getBasicReferences(),o=this.modelParser.qualityController.dcupl?.getContainerSourceMetadata(e),n=o?.origin??"inline";o&&o.sourceColumns.length>0&&this.emitUnknownColumnErrors(e,o.sourceColumns,t,s,n);for(let i of e.data){if(i.key===void 0||i.key===null){const u=e.keyProperty??this.keyProperty,c=e.keyPropertySeparator??this.keyPropertySeparator??we,d=Sr(u,c);this.setError({title:"Missing Key",type:"model",errorGroup:"DataContainerError",errorType:"MissingKey",description:`A row in model "${e.model}" has no value for the key attribute "${d}"; the row is dropped.`,attribute:d,model:e.model});continue}let a=this.data.get(String(i.key));if(!a)a={key:String(i.key)};else if(e.type==="set"){const u=e.keyProperty??this.keyProperty,c=e.keyPropertySeparator??this.keyPropertySeparator??we,d=Sr(u,c),f=String(i.key);this.setError({title:"Non Unique Key",type:"model",errorGroup:"DataContainerError",errorType:"NonUniqueKey",description:`Row with key "${f}" in model "${e.model}" collides with an existing entry (key attribute "${d}"); the duplicate row is dropped`,itemKey:i.key,attribute:d,model:e.model,meta:{duplicateCount:1,droppedRows:[f]}})}for(const u of t){u.origin&&(i[u.key]=i[u.origin]);const c=this.valueMappings.find(d=>d.attributes.includes(u.key));this.isValidValueMapping(c)&&(i=this.mapRawValueUsingValueMapping(i,u.key,c)),this.processBasicProperty(u,i,a,n)}for(const u of s){const c=this.attributeQualityConfigs.get(u.key);u.origin&&(i[u.key]=i[u.origin]);const d=this.valueMappings.find(h=>h.attributes.includes(u.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,u.key,d));let f=i[u.key];if(typeof f=="number"&&(f=String(f)),!f){this.indicesController.fillInverseIndex(u.key,a.key,[void 0]),c?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${u.type} reference "${u.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:u.key,model:e.model,meta:{rawValue:f,declaredType:u.type,origin:n}});continue}if(u.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?this.processSingleValuedReference(u,f,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}});else if(u.type==="multiValued"){const h=this.getValueAsArray(f,u?.separator);Array.isArray(h)?this.processMultiValuedReference(u,h,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}})}}const l=String(a.key);a.key=l,this.data.set(l,a)}}addQueryReferences(e){const t=this.getQueryReferences();for(let s of t){const o=JSON.stringify(s.query);for(let n of e.data){let i=this.data.get(String(n.key));const a=St(o,{...n}),l=JSON.parse(a),u=new ke;u.init({modelKey:s.model}),u.applyQuery(l,{mode:"set"}),l.projection||u.applyOptions({projection:{$:!1}});const c=u.getQuery();if(c.queries.length>0){const f=this.modelParser.dcuplInstance.query.execute(c);s.type==="singleValued"?f[0]&&(i[s.key]={key:f[0].key,_dcupl_ref_:"hit"}):s.type==="multiValued"&&(f.forEach(h=>{h._dcupl_ref_="hit"}),i[s.key]=f)}else s.type==="singleValued"?i[s.key]=null:s.type==="multiValued"&&(i[s.key]=[]);const d=String(i.key);i.key=d,this.data.set(d,i)}}}isValidValueMapping(e){if(!e||!Array.isArray(e.attributes)||!Array.isArray(e.values))return!1;const t=e.values.find(o=>!Array.isArray(o.from)),s=e.values.find(o=>o.to===void 0);return!(t||s)}mapRawValueUsingValueMapping(e,t,s){for(const o of s.values){if(o.from.includes("$dcupl_falsy")){if(typeof e[t]>"u"||e[t]===null||e[t]===""){e[t]=o.to;continue}continue}if(o.from.includes(e[t])){e[t]=o.to;continue}}return e}handleAutoCreationAndReturnKey(e,t){if(Array.isArray(t))return[];if(t===null)return{key:"null"};if(typeof t=="object"){const s=e.keyProperty,o=e.keyPropertySeparator??we;let n;e.autoGenerateKey?n=W():typeof s=="string"||Array.isArray(s)&&s.length>0?n=zo(t,s,o):n=String(t.key),e.data.set(n,{key:n}),t.key=n;const i={model:e.key,data:[t]};return Z().then(()=>e.addContainer(i)),{key:n}}if(typeof t=="string"){e.data.set(t,{key:t});const s={model:e.key,data:[{key:t}]};Z().then(()=>e.addContainer(s))}return{key:String(t)}}addContainer(e){if(this.cdRef.analyticsController.mark({name:"model:autogenerate_data:start",context:e.model}),this.modelParser.handleAlternativeKey([e]),!Array.isArray(e.data)){this.setError({title:"Invalid Data",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",description:`Expect the data to be an Array but got ${typeof e.data}`,model:e.model});return}this.autoGenerateProperties&&this.generatePropertiesFromContainer(e),this.addBasicPropertiesAndReferences(e),this.addQueryReferences(e),this.addResolvedReferences(e),this.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(e),(this.hasDerivedPropertiesBasedOnResolvedReferences()||this?.hasDerivedReferencesBasedOnResolvedReferences())&&this.reRunDerivedPropertiesBasedOnResolves(e),this.cdRef.analyticsController.mark({name:"model:autogenerate_data:end",context:e.model}),this.cdRef.analyticsController.measure({name:"model:autogenerate_data",start:"model:autogenerate_data:start",end:"model:autogenerate_data:end",sum:!0,context:e.model,detail:{model:e.model,origin:this.key}})}addResolvedReferences(e){const t=this.getResolvedReferences().map(s=>{const o=this.modelParser.models.get(s.resolve.model);if(!o)return;const n=o.getDataAsArray(),i=o.indicesController.getIndex(s.resolve.reference);return{reference:s,model:o,remoteData:n,inverseKeys:i}}).filter(s=>!!s);for(const s of e.data){const o=String(s.key),n=this.data.get(o);for(const a of t){const l=a.reference.key;let u;if(a.inverseKeys){if(a.reference.type==="multiValued"){const c=a.inverseKeys.get(n.key)||new Set;u=Array.from(c).map(d=>({key:d}))}else{const c=a.inverseKeys.get(n.key),d=c&&Array.from(c)[0]||null;d?u={key:d}:u=null}n[l]=u,this.indicesController.fillInverseIndex(l,o,n[l])}}const i=String(n.key);n.key=i,this.data.set(i,n)}}rebuildResolvedReferencesForAllItems(e){let t=this.getResolvedReferences();if(t.length===0||e&&(t=t.filter(o=>e.has(o.key)),t.length===0))return;const s=t.map(o=>{const n=this.modelParser.models.get(o.resolve.model);if(!n)return;const i=n.indicesController.getIndex(o.resolve.reference);return{reference:o,model:n,remoteData:[],inverseKeys:i}}).filter(o=>!!o);for(const o of this.data.values())for(const n of s){const i=n.reference.key;let a;if(n.inverseKeys){if(n.reference.type==="multiValued"){const l=n.inverseKeys.get(o.key)||new Set;a=Array.from(l).map(u=>({key:u}))}else{const l=n.inverseKeys.get(o.key),u=l?Array.from(l)[0]:null;u?a={key:u}:a=null}o[i]=a,this.indicesController.fillInverseIndex(i,o.key,o[i])}}}addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(e){const t=this.getDerivedPropertiesForBasicAndDerivedReferences(),s=this.getExpressionProperties(),o=this.getDerivedReferences(),n=this.getGroupedReferences();for(const i of e.data){const a=this.data.get(String(i.key));o.length>0&&o.forEach(u=>{this.handleDerivedReferences(u,a)}),n.length>0&&n.forEach(u=>{this.handleGroupedReferences(u,a)}),t.length>0&&t.forEach(u=>{this.handleDerivedProperties(u,a)}),s.length>0&&s.forEach(u=>{const c=this.createExpressionContext(a),d=St(u.expression,c);a[u.key]=d});const l=String(a.key);a.key=l,this.data.set(l,a)}}handleDerivedProperties(e,t){const s=this.references.get(e.derive.localReference);if(s){const o=this.modelParser.models.get(s.model);o&&(s.type==="singleValued"?this.handleSingleValuedDerivedProperties(o,t,s,e):s.type==="multiValued"&&this.handleMultiValuedDerivedProperties(o,t,s,e))}}reRunDerivedPropertiesBasedOnResolves(e){const t=this.getDerivedProperties(),s=this.getDerivedReferences();for(const o of e.data){const n=this.data.get(String(o.key));s.forEach(a=>{this.handleDerivedReferences(a,n)}),t.forEach(a=>{const l=this.references.get(a.derive.localReference);if(l){const u=this.modelParser.models.get(l.model);u&&(l.type==="singleValued"?this.handleSingleValuedDerivedProperties(u,n,l,a):l.type==="multiValued"&&this.handleMultiValuedDerivedProperties(u,n,l,a))}});const i=String(n.key);n.key=i,this.data.set(i,n)}}handleSingleValuedDerivedProperties(e,t,s,o){const n=t[s.key];if(!n){delete t[o.key];return}const i=e?.getData().get(n.key);if(i){const a=i[o.derive.remoteProperty];typeof a<"u"&&(t[o.key]=a),o.index&&this.indicesController.fillInverseIndex(o.key,t.key,[a])}else delete t[o.key]}handleMultiValuedDerivedProperties(e,t,s,o){const n=t[s.key];let i;n?Array.isArray(n)?i=[...n]:n&&typeof n.key=="string"?i=[{key:n.key}]:i=[]:i=[];const a=o.derive?.separator||", ",l=i.map(c=>{const d=e?.getData().get(c.key);if(d)return d[o.derive.remoteProperty]}).filter(Boolean);let u;o.type.includes("Array<")?u=l:o.type==="string"||o.type==="int"||o.type==="float"||o.type==="date"?u=l.join(a):(o.type,u=l),t[o.key]=u}handleDerivedReferences(e,t){const s=this.references.get(e.derive.localReference);if(!s)return;const o=this.modelParser.models.get(s.model);if(!o)return;const n=t[s.key];if(!n)return;let i=[];if(Array.isArray(n)){const l=new Set;n.forEach(u=>{const c=o?.data.get(u.key);if(c){const d=c[e.derive.remoteReference];d&&(Array.isArray(d)?d.forEach(f=>{l.add(f.key)}):l.add(d.key))}}),i=Array.from(l.values())}else{const l=o?.data.get(n.key);if(l){const u=l[e.derive.remoteReference];u?Array.isArray(u)?i=u.map(c=>c.key):"key"in u&&(i=[u.key]):i=[]}}let a;e.type==="singleValued"?a={key:i[0]}:a=i.map(l=>({key:l})),this.indicesController.fillInverseIndex(e.key,t.key,i),this.groupedRefReverseIndex.delete(e.key),t[e.key]=a}asStringArray(e){return e?Array.isArray(e)?e.map(t=>t.key):[e.key]:[]}buildReverseIndexForReference(e){const t=new Map;this.data.forEach(s=>{const o=this.asStringArray(s[e]);for(const n of o)t.has(n)||t.set(n,new Set),t.get(n).add(s.key)}),this.groupedRefReverseIndex.set(e,t)}ensureReverseIndex(e){return this.groupedRefReverseIndex.has(e)||this.buildReverseIndexForReference(e),this.groupedRefReverseIndex.get(e)}handleGroupedReferences(e,t){const s=[],o=this.references.get(e.groupBy.reference);if(o){const n=this.asStringArray(t[o.key]);if(!n.length)return;const i=this.ensureReverseIndex(o.key),a=new Set;for(const l of n){const u=i.get(l);u&&u.forEach(c=>a.add(c))}for(const l of a)e.groupBy.includeSelfInGroup?s.push({key:l}):t.key!==l&&s.push({key:l})}t[e.key]=s}resetData(){this.data.clear(),this.groupedRefReverseIndex.clear()}resetIndexMap(){this.indicesController.reset()}resetIndicesForChangedAttributes(e){this.indicesController.resetIndicesWhere(t=>{if(this.references.has(t))return!1;for(const s of e)if(t===s||t.startsWith(`${s}_`)||t.startsWith(`${s}.`))return!0;return!1})}deleteDataEntries(e){for(const t of e.data){const s=String(t.key);this.data.delete(s),this.indicesController.removeItemFromAllIndices(s),this.groupedRefReverseIndex.forEach(o=>{o.forEach(n=>{n.delete(s)})})}}getItemCount(){return this.data.size}getAttributes(){return[...this.references.values(),...this.properties.values()]}getAttribute(e){return e==="key"?{key:"key",type:"string"}:this.references.get(e)||this.properties.get(e)}getReferencesRelevantForDependencyGraph(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e))}getBasicReferences(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e)&&!("query"in e)&&!("groupBy"in e))}getQueryReferences(){return Array.from(this.references.values()).filter(e=>"query"in e)}getResolvedReferences(){return Array.from(this.references.values()).filter(e=>"resolve"in e)}getGroupedReferences(){return Array.from(this.references.values()).filter(e=>"groupBy"in e)}getDerivedReferences(){return Array.from(this.references.values()).filter(e=>"derive"in e)}getAggregatedReferences(){return Array.from(this.references.values()).filter(e=>"aggregate"in e)}getBasicProperties(){return Array.from(this.properties.values()).filter(e=>!("derive"in e)&&!("expression"in e))}getDerivedProperties(){return Array.from(this.properties.values()).filter(e=>"derive"in e)}getDerivedPropertiesForBasicAndDerivedReferences(){const e=this.getBasicReferences(),t=this.getDerivedReferences(),s=this.getQueryReferences(),o=this.getDerivedProperties(),n=[...e,...t,...s];return o.filter(i=>n.find(a=>a.key===i.derive?.localReference))}getDerivedPropertiesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedProperties().filter(t=>e.find(s=>s.key===t.derive?.localReference))}getDerivedReferencesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedReferences().filter(t=>e.find(s=>s.key===t.derive.localReference))}getExpressionProperties(){return Array.from(this.properties.values()).filter(e=>"expression"in e)}getAggregatedProperties(){return Array.from(this.properties.values()).filter(e=>"aggregate"in e)}hasBasicReferences(){return this.getBasicReferences().length>0}hasQueryReferences(){return this.getQueryReferences().length>0}hasResolvedReferences(){return this.getResolvedReferences().length>0}hasGroupedReferences(){return this.getGroupedReferences().length>0}hasDerivedReferences(){return this.getDerivedReferences().length>0}hasBasicProperties(){return this.getBasicProperties().length>0}hasDerivedProperties(){return this.getDerivedProperties().length>0}hasDerivedPropertiesForBasicReferences(){return this.getDerivedPropertiesForBasicAndDerivedReferences().length>0}hasDerivedPropertiesBasedOnResolvedReferences(){return this.getDerivedPropertiesForResolvedReferences().length>0}hasDerivedReferencesBasedOnResolvedReferences(){return this.getDerivedReferencesForResolvedReferences().length>0}hasExpressionProperties(){return this.getExpressionProperties().length>0}hasAggregatedProperties(){return this.getAggregatedProperties().length>0}getData(e){if(e?.itemKeys){const t=new Map;return e.itemKeys.forEach(s=>{const o=this.data.get(s);o&&t.set(o.key,o)}),t}return this.data}getDataAsArray(){return Array.from(this.data.values())}getEntry(e){return this.data.get(e)}setRefValue(e,t){this.modelParser.initOptions.referenceMetadata?.enabled&&Object.defineProperty(e,Op.REF_VALUE,{value:t,enumerable:!0,writable:!1,configurable:!1})}addBasicPropertiesAndReferencesPartial(e,t){const s=this.getBasicProperties().filter(i=>t.has(i.key)),o=this.getBasicReferences().filter(i=>t.has(i.key)),n=this.modelParser.qualityController.dcupl?.getContainerSourceMetadata(e)?.origin??"inline";for(let i of e.data){if(i.key===void 0||i.key===null){const u=e.keyProperty??this.keyProperty,c=e.keyPropertySeparator??this.keyPropertySeparator??we,d=Sr(u,c);this.setError({title:"Missing Key",type:"model",errorGroup:"DataContainerError",errorType:"MissingKey",description:`A row in model "${e.model}" has no value for the key attribute "${d}"; the row is dropped.`,attribute:d,model:e.model});continue}let a=this.data.get(String(i.key));a||(a={key:String(i.key)});for(const u of s){u.origin&&(i[u.key]=i[u.origin]);const c=this.valueMappings.find(d=>d.attributes.includes(u.key));this.isValidValueMapping(c)&&(i=this.mapRawValueUsingValueMapping(i,u.key,c)),this.processBasicProperty(u,i,a,n)}for(const u of o){const c=this.attributeQualityConfigs.get(u.key);u.origin&&(i[u.key]=i[u.origin]);const d=this.valueMappings.find(p=>p.attributes.includes(u.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,u.key,d));let f=i[u.key];typeof f=="number"&&(f=String(f));const h=a[u.key];if(this.groupedRefReverseIndex.delete(u.key),!f){h&&this.indicesController.removeFromInverseIndex(u.key,a.key,[h]),this.indicesController.fillInverseIndex(u.key,a.key,[void 0]),delete a[u.key],c?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${u.type} reference "${u.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:u.key,model:e.model,meta:{rawValue:f,declaredType:u.type,origin:n}});continue}if(u.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?(h&&h.key!==f&&this.indicesController.removeFromInverseIndex(u.key,a.key,[h]),this.processSingleValuedReference(u,f,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}});else if(u.type==="multiValued"){const p=this.getValueAsArray(f,u?.separator);Array.isArray(p)?(h&&Array.isArray(h)&&this.indicesController.removeFromInverseIndex(u.key,a.key,h),this.processMultiValuedReference(u,p,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}})}}const l=String(a.key);a.key=l,this.data.set(l,a)}}addQueryAndResolvedReferencesPartial(e,t){if(this.hasQueryReferences()){const s=this.getQueryReferences().filter(o=>t.has(o.key));for(let o of s){const n=JSON.stringify(o.query);for(let i of e.data){let a=this.data.get(String(i.key));if(!a)continue;const l=St(n,{...i}),u=JSON.parse(l),c=new ke;c.init({modelKey:o.model}),c.applyQuery(u,{mode:"set"}),u.projection||c.applyOptions({projection:{$:!1}});const d=c.getQuery();if(d.queries.length>0){const h=this.modelParser.dcuplInstance.query.execute(d);o.type==="singleValued"?h[0]&&(a[o.key]={key:h[0].key,_dcupl_ref_:"hit"}):o.type==="multiValued"&&(h.forEach(p=>{p._dcupl_ref_="hit"}),a[o.key]=h)}else o.type==="singleValued"?a[o.key]=null:o.type==="multiValued"&&(a[o.key]=[]);const f=String(a.key);a.key=f,this.data.set(f,a)}}}this.hasResolvedReferences()&&this.getResolvedReferences().filter(s=>t.has(s.key)).length>0&&this.rebuildResolvedReferencesForAllItems()}createExpressionContext(e){const t={...e};return this.references.forEach((s,o)=>{const n=e[o];if(!n)return;const i=this.modelParser.models.get(s.model);if(i)if(s.type==="singleValued"&&typeof n=="object"&&"key"in n){const a=i.getData().get(n.key);a&&(t[o]=this.createNestedContext(a,i))}else s.type==="multiValued"&&Array.isArray(n)&&(t[o]=n.map(a=>{const l=i.getData().get(a.key);return l?this.createNestedContext(l,i):null}).filter(Boolean))}),t}createNestedContext(e,t){const s={...e};return t.references.forEach((o,n)=>{const i=e[n];if(!i)return;const a=this.modelParser.models.get(o.model);if(a&&o.type==="singleValued"&&typeof i=="object"&&"key"in i){const l=a.getData().get(i.key);l&&(s[n]={...l})}}),s}addDerivedAndExpressionAttributesPartial(e,t){const s=this.getDerivedPropertiesForBasicAndDerivedReferences().filter(a=>t.has(a.key)),o=this.getDerivedReferences().filter(a=>t.has(a.key)),n=this.getGroupedReferences().filter(a=>t.has(a.key)),i=this.getExpressionProperties().filter(a=>t.has(a.key));for(const a of e.data){const l=this.data.get(String(a.key));if(!l)continue;o.forEach(c=>{this.handleDerivedReferences(c,l)}),n.forEach(c=>{this.handleGroupedReferences(c,l)}),s.forEach(c=>{this.handleDerivedProperties(c,l)}),i.forEach(c=>{const d=this.createExpressionContext(l),f=St(c.expression,d);l[c.key]=f});const u=String(l.key);l.key=u,this.data.set(u,l)}}reRunDerivedPropertiesBasedOnResolvesPartial(e,t){const s=this.getDerivedProperties().filter(n=>t.has(n.key)),o=this.getDerivedReferences().filter(n=>t.has(n.key));for(const n of e.data){const i=this.data.get(String(n.key));if(!i)continue;o.forEach(l=>{this.handleDerivedReferences(l,i)}),s.forEach(l=>{this.handleDerivedProperties(l,i)});const a=String(i.key);i.key=a,this.data.set(a,i)}}},Fp=class{changedAttributes;changedItems;deletedItems;modelFullReset;state="clean";constructor(){this.changedAttributes=new Map,this.changedItems=new Map,this.deletedItems=new Map,this.modelFullReset=new Set}recordDataChange(e){const t=e.model;if(!(e.type!=="set"&&(!e.data||e.data.length===0)))if(e.type==="set")this.state==="clean"?this.state="full-reset":this.state==="tracking"&&(this.state="full-reset",this.changedAttributes.delete(t),this.changedItems.delete(t),this.deletedItems.delete(t)),this.modelFullReset.add(t);else{if(this.modelFullReset.has(t))return;this.state==="clean"?this.state="tracking":this.state==="full-reset"&&(this.state="tracking"),e.type==="remove"?this.recordDeletedItems(t,e.data):this.recordChangedData(t,e.data)}}recordAttributeChange(e,t){this.changedAttributes.has(e)||this.changedAttributes.set(e,new Set),this.changedAttributes.get(e).add(t)}recordChangedData(e,t){this.changedAttributes.has(e)||this.changedAttributes.set(e,new Set),this.changedItems.has(e)||this.changedItems.set(e,new Set);const s=this.changedAttributes.get(e),o=this.changedItems.get(e);for(const n of t){n.key&&o.add(String(n.key));for(const i in n)i!=="key"&&s.add(i)}}recordDeletedItems(e,t){this.deletedItems.has(e)||this.deletedItems.set(e,new Set);const s=this.deletedItems.get(e);for(const o of t)o.key&&s.add(String(o.key))}getChangedAttributes(){return this.changedAttributes}getChangedAttributesForModel(e){return this.changedAttributes.get(e)}getChangedItems(e){return this.changedItems.get(e)||new Set}getDeletedItems(e){return this.deletedItems.get(e)||new Set}getModelsWithChanges(){const e=new Set;for(const t of this.changedAttributes.keys())e.add(t);for(const t of this.changedItems.keys())e.add(t);for(const t of this.deletedItems.keys())e.add(t);return Array.from(e)}getEffectivelyChangedModels(){return new Set([...this.getModelsWithChanges(),...this.modelFullReset])}getModelsWithFullReset(){return this.modelFullReset}hasFullReset(e){return this.modelFullReset.has(e)}hasChanges(){return this.changedAttributes.size>0||this.changedItems.size>0||this.deletedItems.size>0||this.modelFullReset.size>0}getTotalChangedItemCount(){let e=0;for(const t of this.changedItems.values())e+=t.size;for(const t of this.deletedItems.values())e+=t.size;return e}getAffectedModelRatio(e){return e===0?0:(this.getModelsWithChanges().length+this.modelFullReset.size)/e}getAffectedItemRatio(e,t){return t===0?0:this.getChangedItems(e).size/t}clear(){this.changedAttributes.clear(),this.changedItems.clear(),this.deletedItems.clear(),this.modelFullReset.clear(),this.state="clean"}requiresFullReset(){return this.state==="full-reset"}getState(){return this.state}getStats(){let e=0,t=0,s=0;for(const o of this.changedItems.values())e+=o.size;for(const o of this.deletedItems.values())t+=o.size;for(const o of this.changedAttributes.values())s+=o.size;return{modelsWithChanges:this.getModelsWithChanges().length,modelsWithFullReset:this.modelFullReset.size,totalChangedItems:e,totalDeletedItems:t,totalChangedAttributes:s}}},qp=class{metrics=[];enabled=!1;constructor(){}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}recordUpdate(e){this.enabled&&(this.metrics.push({...e,timestamp:Date.now()}),this.metrics.length>100&&this.metrics.shift())}getMetrics(){return[...this.metrics]}getSummary(){if(this.metrics.length===0)return{totalUpdates:0,partialUpdates:0,fullUpdates:0,avgPartialUpdateTime:0,avgFullUpdateTime:0,avgAttributesProcessed:0,avgModelsAffected:0,totalTimeSaved:0};const e=this.metrics.filter(l=>l.type==="partial"),t=this.metrics.filter(l=>l.type==="full"),s=e.length>0?e.reduce((l,u)=>l+u.durationMs,0)/e.length:0,o=t.length>0?t.reduce((l,u)=>l+u.durationMs,0)/t.length:0,n=e.length>0?e.reduce((l,u)=>l+(u.attributesProcessed||0),0)/e.length:0,i=e.length>0?e.reduce((l,u)=>l+(u.modelsAffected||0),0)/e.length:0,a=o>0?e.reduce((l,u)=>l+(o-u.durationMs),0):0;return{totalUpdates:this.metrics.length,partialUpdates:e.length,fullUpdates:t.length,avgPartialUpdateTime:s,avgFullUpdateTime:o,avgAttributesProcessed:n,avgModelsAffected:i,totalTimeSaved:a}}getLastUpdates(e=10){return this.metrics.slice(-e)}clear(){this.metrics=[]}getMetricsInRange(e,t){return this.metrics.filter(s=>s.timestamp>=e&&s.timestamp<=t)}};function Qp(r){return"query"in r}function Rr(r){return"resolve"in r}function Vp(r){return"derive"in r}function Gp(r){return"groupBy"in r}var Bp=Object.defineProperty,Up=Object.getOwnPropertyDescriptor,Rt=(r,e,t,s)=>{for(var o=Up(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Bp(e,t,o),o};let lt=class{constructor(e,t,s){this.cdRef=e,this.qualityController=t,this.dcuplInstance=s,this.qualityController.modelParser=this}cdRef;qualityController;dcuplInstance;unprocessedModelDescriptions=new Map;unprocessedData=[];keyedContainers=new WeakSet;dependencyGraph;attributeDependencyGraph;changeTracker=new Fp;partialUpdateMetrics=new qp;views=new Map;models=new Map;initOptions;calculationTimings=[];log=Te.child({prefix:"ModelParser"});async init(){this.changeTracker.clear(),this.qualityController.enabled&&(this.qualityController.resetDataErrors(),this.models.get("$DcuplErrorTrackingErrors")||this.qualityController.initErrorTrackingModels()),this.prepareModels(),this.qualityController.enabled&&this.validateModels(),this.initDependencyGraph(),this.buildAttributeDependencyGraph(),this.validateAttributeDependencyGraph();const e=this.unprocessedData.filter(s=>!s.placeholderUid),t=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(t),this.consolidateUnprocessedData(t,e),this.qualityController.enabled&&await this.qualityController.initData(),this.changeTracker.clear(),this.retrackUnprocessedData(t)}prepareModels(){this.unprocessedModelDescriptions.forEach(e=>{if(this.models.has(e.key))this.models.get(e.key).resetData(),this.models.get(e.key).resetIndexMap(),this.models.get(e.key).applyPropertiesAndReferences(e);else{const t=new Kp(this);t.init(e),t.applyPropertiesAndReferences(e),this.models.set(t.key,t)}})}validateModels(){this.models.forEach(e=>{e.qualityConfig.enabled===!0&&Ep(e,this.models).forEach(t=>{this.setError(t,e)})})}initDependencyGraph(){this.dependencyGraph=new Mo,this.models.forEach(t=>{this.dependencyGraph.addNode(t.key)}),this.models.forEach(t=>{t.getReferencesRelevantForDependencyGraph().forEach(s=>{t.key!==s.model&&(this.dependencyGraph.addNode(s.model),this.dependencyGraph.addDependency(t.key,s.model))})});const e=this.dependencyGraph.validateNoCycles();if(e.hasCycle){const t=e.path.join(" → ");throw this.log.error(`Circular dependency detected in model references: ${t}
|
|
6
6
|
This will cause unpredictable update ordering. Please restructure your models to remove the circular dependency.`),new Error(`Circular dependency detected: ${t}
|
|
7
7
|
Models cannot have circular references as this leads to unpredictable behavior during updates.`)}}buildAttributeDependencyGraph(){this.attributeDependencyGraph=new mf,this.models.forEach(e=>{const t=e.key;e.properties.forEach((s,o)=>{if(s.expression)this.processExpressionProperty(t,o,s.expression);else if(s.derive)this.processDerivedProperty(t,o,s.derive);else{const n={modelKey:t,attributeKey:o,type:"property",processingStep:1};this.attributeDependencyGraph.addAttribute(n)}}),e.references.forEach((s,o)=>{if(Qp(s))this.processQueryReference(t,o,s.query);else if(Rr(s))this.processResolvedReference(t,o,s.resolve);else if(Vp(s))this.processDerivedReference(t,o,s.derive);else if(Gp(s))this.processGroupedReference(t,o,s.groupBy);else{const n={modelKey:t,attributeKey:o,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttribute(n)}})})}validateAttributeDependencyGraph(){const e=new Map;this.models.forEach(s=>{const o=[];s.properties.forEach((n,i)=>{o.push(i)}),s.references.forEach((n,i)=>{o.push(i)}),o.length>0&&e.set(s.key,o)});const t=this.attributeDependencyGraph.validateCompleteness(e);if(!t.isComplete){const s=t.missing.length,o=t.missing.map(({modelKey:i,attributeKey:a})=>`${i}.${a}`).slice(0,10).join(", "),n=`Attribute dependency graph incomplete. ${s} attribute(s) missing: ${o}${s>10?` ... and ${s-10} more`:""}`;this.log.warn(`${n}
|
|
8
|
-
These attributes will default to Step 1 processing which may be incorrect. This usually indicates a problem during expression or reference parsing.`)}}processExpressionProperty(e,t,s){const o={modelKey:e,attributeKey:t,type:"property",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const{variables:n}=xr(s);n.forEach(i=>{const a=i.name.split("."),l=this.models.get(e);if(!l)return;const u=a[0];if(l.properties.has(u)){const c={modelKey:e,attributeKey:u,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,c)}else if(l.references.has(u)){const c={modelKey:e,attributeKey:u,type:"reference",processingStep:1};if(this.attributeDependencyGraph.addAttributeDependency(o,c),a.length>1){let d=l,f=e;for(let h=0;h<a.length-1;h++){const p=a[h],y=d.references.get(p);if(y){const v=this.models.get(y.model);if(v&&(d=v,f=y.model,h===a.length-2)){const g=a[a.length-1],k={modelKey:f,attributeKey:g,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,k)}}}}}})}processDerivedProperty(e,t,s){const o={modelKey:e,attributeKey:t,type:"property",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.localReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n);const i=this.models.get(e);if(i){const a=i.references.get(s.localReference);if(a){const l={modelKey:a.model,attributeKey:s.remoteProperty,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,l)}}}processQueryReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:2};this.attributeDependencyGraph.addAttribute(o);try{const n=JSON.stringify(s),{variables:i}=xr(n);i.forEach(a=>{const l=a.name,u=this.models.get(e);if(u){if(u.properties.has(l)){const c={modelKey:e,attributeKey:l,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,c)}else if(u.references.has(l)){const c={modelKey:e,attributeKey:l,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,c)}}})}catch{}}processResolvedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:2};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:s.model,attributeKey:s.reference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n)}processDerivedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.localReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n);const i=this.models.get(e);if(i){const a=i.references.get(s.localReference);if(a){const l={modelKey:a.model,attributeKey:s.remoteReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,l)}}}processGroupedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.reference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n)}async update(){const e=performance.now(),t=this.shouldUsePartialUpdate();if(t.decision){const s=this.changeTracker.getModelsWithChanges().length,o=Array.from(this.changeTracker.getChangedAttributes().values()).reduce((a,l)=>a+l.size,0),n=this.changeTracker.getTotalChangedItemCount();await this.partialUpdate();const i=performance.now()-e;this.partialUpdateMetrics.recordUpdate({type:"partial",durationMs:i,modelsAffected:s,attributesProcessed:o,itemsChanged:n,decisionReason:t.reason,timestamp:Date.now()})}else{await this.init();const s=performance.now()-e;this.partialUpdateMetrics.recordUpdate({type:"full",durationMs:s,decisionReason:t.reason,timestamp:Date.now()})}}shouldUsePartialUpdate(){const e=this.dcuplInstance.initOptions.performance?.partialUpdates,t=e?.modelRatioThreshold??.5,s=e?.itemRatioThreshold??.5,o=e?.enableDetailedLogging??!1;if(!this.changeTracker.hasChanges())return o&&this.log.debug("Partial update decision: SKIP",{reason:"no_changes_detected"}),{decision:!1,reason:"no_changes_detected"};if(this.changeTracker.getModelsWithFullReset().size>0)return o&&this.log.debug("Partial update decision: FULL",{reason:"full_reset_detected"}),{decision:!1,reason:"full_reset_detected"};const n=Array.from(this.models.keys()).filter(c=>!c.startsWith("$")).length,i=this.changeTracker.getAffectedModelRatio(n);let a=0,l=0;for(const c of this.changeTracker.getModelsWithChanges()){const d=this.models.get(c);if(d){const f=d.getData().size;a+=f,l+=this.changeTracker.getChangedItems(c).size,l+=this.changeTracker.getDeletedItems(c).size}}const u=a>0?l/a:0;return i>t&&u>s?(o&&this.log.debug("Partial update decision: FULL",{reason:"both_ratios_high",modelRatio:i.toFixed(2),itemRatio:u.toFixed(2)}),{decision:!1,reason:`both_ratios_high:models=${i.toFixed(2)},items=${u.toFixed(2)}`}):(o&&this.log.debug("Partial update decision: PARTIAL",{modelRatio:i.toFixed(2),itemRatio:u.toFixed(2),modelThreshold:t,itemThreshold:s}),{decision:!0,reason:`optimal:models=${i.toFixed(2)},items=${u.toFixed(2)}`})}async partialUpdate(){const e=this.handleAlternativeKey(this.unprocessedData).filter(s=>!s.placeholderUid);for(const s of e)if(s.type==="remove"){const o=this.models.get(s.model);if(o){o.deleteDataEntries(s);for(const n of o.properties.values())this.changeTracker.recordAttributeChange(s.model,n.key);for(const n of o.references.values())this.changeTracker.recordAttributeChange(s.model,n.key)}}const t=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModelsPartial(t),this.consolidateUnprocessedData(t)}async reprocessData(){this.qualityController.enabled&&this.qualityController.resetModelErrors();const e=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(e)}getSortedCalculationTimings(){return $o(this.calculationTimings,"value")}addModel(e){if(e?.quality?.enabled!==!1)try{xp(e)}catch(t){this.qualityController.enabled&&this.qualityController.setError({title:"Invalid Model Definition",type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:e.key,description:t.message});return}if(this.unprocessedModelDescriptions.has(e.key)){const t=this.unprocessedModelDescriptions.get(e.key),s=this.mergeModels(t,e);this.unprocessedModelDescriptions.set(e.key,s)}else this.unprocessedModelDescriptions.set(e.key,e);e.data&&this.addData({model:e.key,data:e.data,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty})}mergeModels(e,t){const s=Object.assign({},e,t);return(Array.isArray(e.properties)||Array.isArray(t.properties))&&(s.properties=[...Array.isArray(e.properties)?e.properties:[],...Array.isArray(t.properties)?t.properties:[]]),(Array.isArray(e.references)||Array.isArray(t.references))&&(s.references=[...Array.isArray(e.references)?e.references:[],...Array.isArray(t.references)?t.references:[]]),s}addData(e){if(!e||!e.model||!e.data)throw new Error("Invalid Data Container");if(!Array.isArray(e.data))throw new Error("Invalid Data - Data must be an Array");e.type||(e.type="set"),e.autoGenerateProperties&&this.addModel({key:e.model,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty||"key"}),this.changeTracker.recordDataChange(e),this.unprocessedData.push(e)}addView(e){this.views.set(e.key,e)}setError(e,t){this.qualityController.enabled&&t.qualityConfig.enabled===!0&&this.qualityController.setError(e)}getMergedContainers(e){const t=this.handleAlternativeKey(e).filter(n=>!n.placeholderUid),s=[],o=Sr(t,"model");for(const n in o){const i=o[n];if(i.length>1){const a=this.mergeContainers(i),l=this.mergeContainerSourceMetadata(i);l&&this.dcuplInstance.setContainerSourceMetadata(a,l),s.push(a)}else s.push(i[0])}return s}consolidateUnprocessedData(e){const t=this.unprocessedData.filter(s=>s.placeholderUid);for(const s of e)this.keyedContainers.add(s);this.unprocessedData=[...e,...t]}mergeContainers(e){let t;return e?.forEach(s=>{if(!t){if(s.type==="remove")return;t=new Map(s.data.map(o=>[o.key,o]));return}switch(s.type){case"upsert":s.data.forEach(o=>{if(t.has(o.key)){let n=t.get(o.key);n=lt(n,o),t.set(o.key,n)}else t.set(o.key,o)});break;case"update":s.data.forEach(o=>{if(t.has(o.key)){let n=t.get(o.key);n=lt(n,o),t.set(o.key,n)}});break;case"remove":s.data.forEach(o=>{t.delete(o.key)});break;case"set":t=new Map(s.data.map(o=>[o.key,o]));break;default:t=new Map(s.data.map(o=>[o.key,o]));break}}),{model:e[0].model,data:Array.from(t.values()),type:"set"}}mergeContainerSourceMetadata(e){let t;for(const s of e){const o=this.dcuplInstance.getContainerSourceMetadata(s),n=s.type??"set";if(n==="set")t=o?{columns:new Set(o.sourceColumns),samples:this.cloneCoercionSamples(o.coercionFailureSamples),origin:o.origin}:void 0;else if((n==="upsert"||n==="update")&&o){t||(t={columns:new Set,samples:{},origin:o.origin}),o.sourceColumns.forEach(i=>t.columns.add(i));for(const i of Object.keys(o.coercionFailureSamples)){const a=o.coercionFailureSamples[i],l=t.samples[i];l?l.count+=a.count:t.samples[i]={...a}}}}if(t)return{sourceColumns:Array.from(t.columns),coercionFailureSamples:t.samples,origin:t.origin}}cloneCoercionSamples(e){const t={};for(const s of Object.keys(e))t[s]={...e[s]};return t}async connectDataWithModels(e){try{this.dependencyGraph.order()}catch(s){this.log.warn("Your models have circular dependencies which might lead to errors. Please consider changing your models"),this.log.error("Dependency graph error",s)}const t=this.dependencyGraph.order({allowCycles:!0});e.sort((s,o)=>t.indexOf(s.model)-t.indexOf(o.model)),await this.handleDataContainer(e)}async connectDataWithModelsPartial(e){const t=this.dependencyGraph.order({allowCycles:!0});e.sort((i,a)=>t.indexOf(i.model)-t.indexOf(a.model));const s=[];for(const[i,a]of this.changeTracker.getChangedAttributes())for(const l of a){const u=this.attributeDependencyGraph.getAttributesForModel(i).find(c=>c.attributeKey===l);if(u)s.push(u);else{const c=this.models.get(i);if(c){const d=c.properties.get(l),f=c.references.get(l);(d||f)&&s.push({modelKey:i,attributeKey:l,type:d?"property":"reference",processingStep:1})}}}const o=this.attributeDependencyGraph.getImpactedAttributes(s),n=this.attributeDependencyGraph.getProcessingOrder(o);for(const i of e){const a=this.models.get(i.model);a?.autoGenerateProperties&&a.generatePropertiesFromContainer(i)}for(const i of[1,2,3,4])await this.processAttributesForStep(i,n,e);for(const[i,a]of n.entries()){const l=this.models.get(i);if(!l)continue;const u=new Set;for(const c of a.values())for(const d of c)u.add(d);l.resetIndicesForChangedAttributes(u)}for(const i of e){const a=this.models.get(i.model);if(a&&this.qualityController.enabled){const l=this.changeTracker.getChangedItems(a.key),u=this.changeTracker.getChangedAttributes().get(a.key);l.size>0&&u&&(this.qualityController.cleanUpErrorsForItems(a,l,u),this.qualityController.validateItemsPartial(a,l,u).forEach(c=>{this.setError(c,a)}))}}this.changeTracker.clear()}getResolvedReferenceProcessingOrder(e){const t=new Map,s=new Set;for(const[l,u]of e.entries()){const c=u.get(2);c&&c.size>0&&(s.add(l),t.set(l,new Set))}if(s.size===0)return this.dependencyGraph.order();for(const l of s){const u=this.models.get(l);if(!u)continue;const c=e.get(l)?.get(2);if(c)for(const d of c){const f=u.references.get(d);if(f&&Rr(f)){const h=f.resolve.model,p=f.resolve.reference,y=this.models.get(h);if(y){const v=y.references.get(p);v&&Rr(v)&&t.get(l).add(h)}}}}const o=[],n=new Set,i=new Set,a=l=>{if(i.has(l)||n.has(l))return;n.add(l);const u=t.get(l);if(u)for(const c of u)a(c);n.delete(l),i.add(l),o.push(l)};for(const l of s)a(l);return o}async processAttributesForStep(e,t,s){let o=this.dependencyGraph.order({allowCycles:!0});e===2&&(o=this.getResolvedReferenceProcessingOrder(t));for(const n of o){const i=t.get(n);if(!i)continue;const a=i.get(e);if(!a||a.size===0)continue;const l=this.models.get(n);if(!l)continue;const u=W(),c=`dcupl:partial_process_data:step_${e}`;if(this.cdRef.analyticsController.mark({name:`${c}:start`,context:u}),e===2)l.rebuildResolvedReferencesForAllItems(a);else{const d=s.find(f=>f.model===n);if(!d)continue;switch(e){case 1:l.addBasicPropertiesAndReferencesPartial(d,a);break;case 3:l.addDerivedAndExpressionAttributesPartial(d,a);break;case 4:l.reRunDerivedPropertiesBasedOnResolvesPartial(d,a);break}}this.cdRef.analyticsController.mark({name:`${c}:end`,context:u}),this.cdRef.analyticsController.measure({name:c,start:`${c}:start`,end:`${c}:end`,context:u,detail:{model:n,attributeCount:a.size}})}}handleAlternativeKey(e){return e.forEach(t=>{if(this.keyedContainers.has(t))return;const s=this.models.get(t.model),o=t.keyProperty??s?.keyProperty,n=t.keyPropertySeparator??s?.keyPropertySeparator??we,i=t.autoGenerateKey||s?.autoGenerateKey;(typeof o=="string"?o!==""&&o!=="key":Array.isArray(o)&&o.length>0)?t.data.forEach(a=>{a.key=zo(a,o,n)}):i&&t.data.forEach(a=>{a.key||(a.key=W())}),this.keyedContainers.add(t)}),e}async handleDataContainer(e){for(const o of e){const n=this.models.get(o.model);n?.autoGenerateProperties&&n.generatePropertiesFromContainer(o)}const t=this.initOptions.performance?.containerBatchSize,s=t!==void 0;for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:start",context:a}),i&&(i.addBasicPropertiesAndReferences(n),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.cleanUpErrors(i,n)),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_1",start:"dcupl:process_data:step_1:start",end:"dcupl:process_data:step_1:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:start",context:a}),i&&i.hasQueryReferences()&&i.addQueryReferences(n),i&&i.hasResolvedReferences()&&i.addResolvedReferences(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_2",start:"dcupl:process_data:step_2:start",end:"dcupl:process_data:step_2:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:start",context:a}),i&&(i.hasDerivedPropertiesForBasicReferences()||i?.hasDerivedReferences()||i?.hasGroupedReferences()||i?.hasExpressionProperties())&&i.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_3",start:"dcupl:process_data:step_3:start",end:"dcupl:process_data:step_3:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model);if(!i){this.log.error("Model not found during data processing",void 0,{model:n.model,step:4});continue}const a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:start",context:a}),(i.hasDerivedPropertiesBasedOnResolvedReferences()||i.hasDerivedReferencesBasedOnResolvedReferences())&&i.reRunDerivedPropertiesBasedOnResolves(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_4",start:"dcupl:process_data:step_4:start",end:"dcupl:process_data:step_4:end",context:a,detail:{model:n.model}}),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.validateAttributesAfterInitialization(i).forEach(l=>{this.setError(l,i)}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}}_getModelKeys(){return Array.from(this.models.values()).map(e=>e.key).filter(e=>e&&!e.startsWith("$Dcupl"))}_getViewKeys(e){const t=e?.modelKey;return Array.from(this.views.values()).filter(s=>t?s.model===t:!0).map(s=>s.key)}getTotalItemCount(){let e=0;for(const t of this.models.values())e+=t.getItemCount();return e}};It([b({scope:"global",type:"model_add",connectMessage:!0})],ut.prototype,"addModel"),It([b({scope:"global",type:"data_change",connectMessage:!0})],ut.prototype,"addData"),It([b({scope:"global",type:"view_add",connectMessage:!0})],ut.prototype,"addView"),It([b({scope:"global",type:"dcupl_handle_datacontainer"})],ut.prototype,"handleDataContainer");function Np(r,e,t){return r===r&&(t!==void 0&&(r=r<=t?r:t),r=r>=e?r:e),r}function zp(r,e,t){r=Is(r),e=Jt(e);var s=r.length;t=t===void 0?s:Np(Zt(t),0,s);var o=t;return t-=e.length,t>=0&&r.slice(t,o)==e}function Lp(r,e){return Se(e,function(t){return r[t]})}function Wp(r){return r==null?[]:Lp(r,tt(r))}var Hp=Math.max;function Jp(r,e,t,s){r=te(r)?r:Wp(r),t=t?Zt(t):0;var o=r.length;return t<0&&(t=Hp(o+t,0)),jt(r)?t<=o&&r.indexOf(e,t)>-1:!!o&&ws(r,e,t)>-1}var Zp=Object.defineProperty,Yp=Object.getOwnPropertyDescriptor,Ho=(r,e,t,s)=>{for(var o=Yp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Zp(e,t,o),o};let Ir=class{constructor(e,t){this.dcuplApi=e,this.cdRef=t}dcuplApi;cdRef;options;key;modelKey;catalog;ownsIndicesController=!1;setup(e){const t=this.dcuplApi.modelParser.models.get(e.modelKey);if(!t)throw new Error(`Model with key ${e.modelKey} not found`);const s=this.getListItemKeys(e),o=this.getRelevantData(t,s),n=this.initIndicesController(s,t,o);this.catalog?this.catalog.filter.update(t,o,n):(this.catalog=new rp(this.dcuplApi,this.cdRef,n),this.catalog.init(this.modelKey,t,o))}initIndicesController(e,t,s){let o;if(e){o=new Mt;for(const n of t.indicesController.indexMap.keys())o.getOrCreateIndex(n,s);this.ownsIndicesController=!0}else o=t.indicesController,this.ownsIndicesController=!1;return o}getListItemKeys(e){let t;return e.listItemKeys?t=e.listItemKeys:e.query&&(t=this.dcuplApi.query.execute(e.query).map(s=>s.key)),t}getRelevantData(e,t){const s=e.getData();return t?this.initFromItemKeys(s,t):s}init(e){this.options=oe(e),this.key=this.options.listKey,this.modelKey=this.options.modelKey,this.setup(this.options)}initFromItemKeys(e,t){const s=new Map;return t.forEach(o=>{if(e.has(o)){const n=e.get(o);n&&s.set(o,n)}}),s}destroy(){try{this.dcuplApi.lists.destroy({listKey:this.key})}catch{}}_destroy(){this.catalog.filter.cdRef?.destroy()}update(e){(e&&e.reprocessData||!e)&&this.setup(this.options)}invalidate(){this.catalog&&(this.ownsIndicesController&&this.catalog.filter.indicesController.reset(),this.catalog.filter.resetCache())}emitResultUpdated(){this.catalog&&this.catalog.filter.emitResultUpdated()}on(e){return this.cdRef.on(e)}onResultChange(e){return this.cdRef.on(t=>{t.type==="result_updated"&&e(t)})}};Ho([b({scope:"list",type:"list_destroyed",connectMessage:!0})],Ir.prototype,"_destroy"),Ho([b({scope:"list",type:"list_updated",action:"update",connectMessage:!0})],Ir.prototype,"update");var Xp=Object.defineProperty,eh=Object.getOwnPropertyDescriptor,th=(r,e,t,s)=>{for(var o=eh(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Xp(e,t,o),o};class Jo{constructor(e,t){this.dcuplInstance=e,this.cdRef=t}dcuplInstance;cdRef;lists=[];get(e){if(e)return this.lists.find(t=>t.key===e)}getAll(e){return e?this.lists.filter(t=>t.modelKey===e?.modelKey):this.lists}destroy(e){if(!e)this.lists.forEach(t=>t._destroy()),this.lists=[];else if(e.listKey){const t=this.lists.findIndex(s=>s.key===e.listKey);t>-1&&(this.lists[t]._destroy(),this.lists.splice(t,1))}else e.modelKey&&(this.lists=this.lists.filter(t=>t.modelKey===e.modelKey?(t._destroy(),!1):!0))}create(e){e.listKey=e.listKey||W();const t=new Cr;t._init({cdRefKey:e.listKey,parentCd:this.dcuplInstance.cdRef,dcuplInitOptions:this.dcuplInstance.initOptions,analyticsController:this.dcuplInstance.analyticsController});const s=new Ir(this.dcuplInstance,t);return s.init(e),this.lists.push(s),s}}th([b({scope:"global",type:"list_created",connectMessage:!0})],Jo.prototype,"create");let rh=class{constructor(e){this.scriptsController=e}scriptsController;enabled=!1;maxErrorsPerGroup=1e3;errors=new Map;errorCounts=new Map;log=Te.child({prefix:"QualityController"});values={loading:0,processing:0,startup:0,counts:{resources:0,modelFiles:0,dataFiles:0,models:0,rows:0,attributes:0,dataEntries:0},unusedAttributes:[],errors:{size:0,UndefinedValue:0,UndefinedAttribute:0,WrongDataType:0,MissingModel:0,InvalidModelDescription:0,RemoteReferenceKeyNotFound:0},sizes:{totalEncoded:0,totalDecoded:0,unusedDecoded:0,models:[]}};modelParser;dcupl;getErrorGroupKey(e){const t="attribute"in e?e.attribute:void 0;return`${e.model??""}::${t??""}::${e.errorType}`}getGroupCount(e,t,s){const o=`${e??""}::${t??""}::${s}`;return this.errorCounts.get(o)?.count??0}setError(e){const t=this.getErrorGroupKey(e);let s=this.errorCounts.get(t);s||(s={model:e.model,attribute:"attribute"in e?e.attribute:void 0,errorGroup:e.errorGroup,errorType:e.errorType,type:e.type,count:0},this.errorCounts.set(t,s)),s.count+=1,!(s.count>this.maxErrorsPerGroup)&&(e.key||(e.key=W()),this.errors.set(e.key,e))}getErrorCounts(){return Array.from(this.errorCounts.values()).map(({model:e,attribute:t,errorType:s,count:o})=>({model:e,attribute:t,errorType:s,count:o}))}getErrorSummary(){const e=new Map;for(const s of this.errors.values()){const o=this.getErrorGroupKey(s);e.set(o,(e.get(o)??0)+1)}const t=[];for(const[s,o]of this.errorCounts){const n=e.get(s)??0;t.push({key:s,model:o.model,attribute:o.attribute,errorGroup:o.errorGroup,errorType:o.errorType,type:o.type,totalCount:o.count,storedCount:n,truncated:o.count>n})}return t}stampGroupTotals(e){const t=new Map(e.map(s=>[s.key,s]));for(const s of this.errors.values()){const o=t.get(this.getErrorGroupKey(s));s.groupTotal=o?.totalCount??1,s.truncated=o?.truncated??!1}}removeError(e){const t=this.errors.get(e);if(t){const s=this.getErrorGroupKey(t),o=this.errorCounts.get(s);o&&(o.count-=1,o.count<=0&&this.errorCounts.delete(s))}this.errors.delete(e)}getError(e){return this.errors.get(e)}getErrors(){return Array.from(this.errors.values())}resetErrors(){this.errors.clear(),this.errorCounts.clear()}resetModelErrors(){this.getErrors().forEach(e=>{e.type==="model"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&this.errorCounts.delete(e)}resetValidationErrors(){this.getErrors().forEach(e=>{e.type==="model"&&e.errorType==="InvalidValidator"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&t.errorType==="InvalidValidator"&&this.errorCounts.delete(e)}resetDataErrors(){const e=["ReferenceDataError","PropertyDataError","DataContainerError"];this.getErrors().forEach(t=>{t.type==="model"&&e.includes(t.errorGroup)&&this.removeError(t.key)});for(const[t,s]of this.errorCounts)s.type==="model"&&e.includes(s.errorGroup)&&this.errorCounts.delete(t)}cleanUpErrors(e,t){const s=this.dcupl?.getContainerSourceMetadata(t),o=t.model;if(s){const n=s.coercionFailureSamples??{};for(const i of Object.keys(n)){const a=n[i];if(!a||a.count<=0)continue;for(const u of this.getModelErrors(o))u.attribute===i&&u.itemKey!=null&&(u.errorType==="UndefinedValue"||u.errorType==="WrongDataType")&&this.removeError(u.key);const l=e.properties.get(i)?.type??a.expected;this.setError(this.buildColumnCoercionError(o,i,a.rawValue,l,a.count))}for(const[i]of e.properties){if(n[i]||s.sourceColumns.includes(i))continue;const a=this.getGroupCount(o,i,"UndefinedValue");if(a>0&&a===t.data.length){for(const l of this.getModelErrors(o))l.attribute===i&&l.itemKey!=null&&l.errorType==="UndefinedValue"&&this.removeError(l.key);this.setError(this.buildAbsentColumnError(o,i))}}}else{const n=new Set(this.getModelErrors(o).filter(l=>l.errorType==="UndefinedValue"&&l.attribute!=null).map(l=>l.attribute));for(const l of n){const u=this.getGroupCount(o,l,"UndefinedValue");if(u>0&&u===t.data.length){for(const c of this.getModelErrors(o))c.attribute===l&&c.itemKey!=null&&c.errorType==="UndefinedValue"&&this.removeError(c.key);this.setError(this.buildAbsentColumnError(o,l))}}const i=this.getModelErrors(o).filter(l=>l.errorType==="WrongDataType"&&l.errorGroup==="PropertyDataError"&&l.title==="Wrong Data Type"&&l.itemKey!=null),a=Sr(i,"attribute");for(const l in a){const u=a[l];if(!u?.length)continue;const c=u[0].meta,d=e.properties.get(l)?.type??c?.expected??"unknown";for(const f of u)this.removeError(f.key);this.setError(this.buildColumnCoercionError(o,l,String(c?.rawValue??""),d,u.length))}}}buildColumnCoercionError(e,t,s,o,n){return{title:"Wrong Data Type",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",model:e,attribute:t,description:`${n} value(s) in column "${t}" of model "${e}" failed to coerce to the declared type "${o}" (e.g. "${s}")`,meta:{rawValue:s,declaredType:o,rowCount:n}}}buildAbsentColumnError(e,t){return{title:"Missing Data",type:"model",errorGroup:"DataContainerError",errorType:"UndefinedAttribute",model:e,attribute:t,description:`The Attribute "${t}" is not present in the dataset for model "${e}"`}}getModelErrors(e){return this.getErrors().filter(t=>t.type==="model"&&t.model===e)}cleanUpErrorsForItems(e,t,s,o){let n,i;typeof s=="string"?i=s:s instanceof Set&&(n=s,i=o);const a=this.getModelErrors(e.key),l=i?a.filter(u=>u.errorType===i):a;for(const u of l)if(u.itemKey&&t.has(u.itemKey)){if(n&&u.attribute&&!n.has(u.attribute))continue;this.removeError(u.key)}}getErrorsForItems(e,t){return this.getModelErrors(e).filter(s=>s.itemKey&&t.has(s.itemKey))}validateItemsPartial(e,t,s){if(!e)return[];const o=[],n=e.getData(),i=e.getAttributes();for(const a of i){if(!s.has(a.key))continue;const l=a.quality?.validators;if(l)for(const u of t){const c=n.get(u);if(!c)continue;const d=c[a.key],f=this.validateAttribute(d,l,a.key);for(const h of f)h.model=e.key,h.itemKey=c.key,o.push(h)}}return o}async initData(){if(!this.modelParser)return;const e=["$DcuplErrorTrackingErrors","$DcuplErrorTrackingSummary"];this.modelParser.unprocessedData=this.modelParser.unprocessedData.filter(o=>!e.includes(o.model));for(const o of e){const n=this.modelParser.models.get(o);n?.resetData(),n?.resetIndexMap()}const t=this.getErrorSummary();this.stampGroupTotals(t),this.modelParser.addData({data:this.getErrors(),model:"$DcuplErrorTrackingErrors",type:"set"}),this.modelParser.addData({data:t,model:"$DcuplErrorTrackingSummary",type:"set"});const s=this.modelParser.unprocessedData.filter(o=>e.includes(o.model));s.length>0&&await this.modelParser.handleDataContainer(s)}initErrorTrackingModels(){this.modelParser?.addModel({key:"$DcuplErrorTrackingErrors",autoGenerateKey:!0,supportsAutoCreation:!0,references:[{key:"model",type:"singleValued",model:"$DcuplErrorTrackingModel",filter:{calculateFacets:!0}},{key:"errorGroup",type:"singleValued",model:"$DcuplErrorTrackingGroup",filter:{calculateFacets:!0}},{key:"errorType",type:"singleValued",model:"$DcuplErrorTrackingType",filter:{calculateFacets:!0}}],properties:[{key:"title",type:"string",filter:!0},{key:"itemKey",type:"string",filter:!0},{key:"attribute",type:"string",filter:!0},{key:"description",type:"string"},{key:"meta",type:"json"},{key:"groupTotal",type:"int"},{key:"truncated",type:"boolean",filter:!0}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingSummary",supportsAutoCreation:!0,references:[{key:"model",type:"singleValued",model:"$DcuplErrorTrackingModel",filter:{calculateFacets:!0}},{key:"errorGroup",type:"singleValued",model:"$DcuplErrorTrackingGroup",filter:{calculateFacets:!0}},{key:"errorType",type:"singleValued",model:"$DcuplErrorTrackingType",filter:{calculateFacets:!0}}],properties:[{key:"attribute",type:"string",filter:!0},{key:"type",type:"string",filter:!0},{key:"totalCount",type:"int",filter:!0},{key:"storedCount",type:"int"},{key:"truncated",type:"boolean",filter:!0}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingType",data:[{key:"UndefinedAttribute"},{key:"InvalidValidator"},{key:"UndefinedValue"},{key:"NullValue"},{key:"WrongDataType"},{key:"MissingModel"},{key:"NonUniqueKey"},{key:"RemoteReferenceKeyNotFound"},{key:"InvalidModelDescription"},{key:"InvalidResource"},{key:"InvalidModelDefinition"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingGroup",data:[{key:"ReferenceDataError"},{key:"PropertyDataError"},{key:"DataContainerError"},{key:"ModelDescriptionError"},{key:"LoaderError"},{key:"ResourceError"},{key:"ModelDefinitionError"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingModel",supportsAutoCreation:!0,quality:{enabled:!1}})}initAnalyticsValues(){this.calculateTiming(),this.calculateSizes(),this.calculateErrorTrackingFacet(),this.calculateCounts(),this.calculateUnusedAttributes()}calculateUnusedAttributes(){this.values.unusedAttributes=[];const e=this.dcupl.models.keys();for(const t of e){const s=this.getUnusedAttributesFromModel(this.dcupl,t);for(const o of s)this.values.unusedAttributes?.push({model:t,attribute:o})}}calculateCounts(){this.values.counts={},this.values.counts.modelFiles=this.dcupl.modelParser.unprocessedModelDescriptions.size,this.values.counts.dataFiles=this.dcupl.modelParser.unprocessedData.length,this.values.counts.models=this.dcupl.models.keys().length;let e=0,t=0,s=0;this.dcupl.models.keys().forEach(o=>{const n=this.dcupl.modelParser.models.get(o);if(!n)return;const i=n?.getBasicProperties()||[],a=n?.getBasicReferences()||[],l=i.length+a.length;t+=l;const u=n.data?.size||0;e+=u,s+=l*u}),this.values.counts.rows=e,this.values.counts.attributes=t,this.values.counts.dataEntries=s}calculateTiming(){const e=this.dcupl.analyticsController.getByName("loader_processed");e&&e[0]&&(this.values.loading=e[0].value);const t=this.dcupl.analyticsController.getByName("dcupl_initialized");t&&t[0]&&(this.values.processing=t[0].value),this.values.startup=this.values.loading+this.values.processing}calculateSizes(){const e=this.calculateSizesForModels();this.values.sizes={},this.values.sizes.totalEncoded=e.reduce((t,s)=>t+s.encodedBodySize,0),this.values.sizes.totalDecoded=e.reduce((t,s)=>t+s.decodedBodySize,0),this.values.sizes.unusedDecoded=this.calculateUnusedData(),this.values.sizes.models=e.map(t=>({model:t.model,decodedBodySize:t.decodedBodySize,encodedBodySize:t.encodedBodySize})),this.values.sizes.models?.sort((t,s)=>(s.encodedBodySize||0)-(t.encodedBodySize||0))}calculateErrorTrackingFacet(){try{if(!this.enabled)return;const e=new Map;let t=0;for(const s of this.errorCounts.values())e.set(s.errorType,(e.get(s.errorType)??0)+s.count),t+=s.count;this.values.errors={size:t,UndefinedValue:e.get("UndefinedValue")??0,UndefinedAttribute:e.get("UndefinedAttribute")??0,WrongDataType:e.get("WrongDataType")??0,MissingModel:e.get("MissingModel")??0,InvalidModelDescription:e.get("InvalidModelDescription")??0,RemoteReferenceKeyNotFound:e.get("RemoteReferenceKeyNotFound")??0}}catch(e){this.log.error("Error calculating error tracking facet",e)}}calculateSizesForModels(){const e=this.dcupl.analyticsController.getByType("resource").filter(s=>s.value?.type==="data"),t=Sr(e,s=>s.value?.model);return Object.keys(t).map(s=>{const o=t[s]?.reduce((i,a)=>{const l=a.value.encodedBodySize;return i+l},0),n=t[s]?.reduce((i,a)=>{const l=a.value.decodedBodySize;return i+l},0);return{model:s,decodedBodySize:n,encodedBodySize:o}})}calculateUnusedData(){const e=this.dcupl.models.keys();let t=0;return e.forEach(s=>{const o=this.dcupl.modelParser.unprocessedData.find(a=>a.model===s)?.data||[],n=this.getUnusedAttributesFromModel(this.dcupl,s);if(!n.length)return;const i=this.getDataWithAttributes(o,n);t+=JSON.stringify(i).length}),t}getDataWithAttributes(e,t){return e.map(s=>{const o={};return t.forEach(n=>{o[n]=s[n]}),o})}getUnusedAttributesFromModel(e,t){const s=e.modelParser.models.get(t),o=s?.getBasicProperties()||[],n=s?.getBasicReferences()||[],i=s?.keyProperty,a=[...o,...n].map(u=>u.key);typeof i=="string"?a.push(i):Array.isArray(i)?a.push(...i):a.push("key"),a.push("key");const l=e.modelParser.unprocessedData.find(u=>u.model===t)?.data||[];return this.getUnusedAttributes(l,a)}getUnusedAttributes(e,t){const s=new Set;return e.forEach(o=>{Object.keys(o).forEach(n=>{t.includes(n)||s.add(n)})}),Array.from(s.values())}validateAttribute(e,t,s){const o=[];if(t.email){const n=this.validateEmail(e,s);n&&o.push(n)}if(t.endsWith){const n=this.validateEndsWith(e,t.endsWith,s);n&&o.push(n)}if(t.enum){const n=this.validateEnum(e,t.enum,s);n&&o.push(n)}if(t.includes){const n=this.validateIncludes(e,t.includes,s);n&&o.push(n)}if(t.max){const n=this.validateMax(e,t.max,s);n&&o.push(n)}if(t.maxLength){const n=this.validateMaxLength(e,t.maxLength,s);n&&o.push(n)}if(t.min){const n=this.validateMin(e,t.min,s);n&&o.push(n)}if(t.minLength){const n=this.validateMinLength(e,t.minLength,s);n&&o.push(n)}if(t.pattern){const n=this.validatePattern(e,t.pattern,s);n&&o.push(n)}if(t.startsWith){const n=this.validateStartsWith(e,t.startsWith,s);n&&o.push(n)}return o}validateAttributesAfterInitialization(e){if(!e)return[];const t=e.getAttributes(),s=e.getDataAsArray(),o=[];for(const n of t){const i=n.quality?.validators;if(i&&i.unique){const a=this.validateUnique(s,n.key,e);o.push(...a)}}return o}validateUnique(e,t,s){const o=[],n=new Set,i=s.attributeQualityConfigs?.get(t)?.validatorHandling!=="loose";for(const a of e){const l=a[t];if(n.has(l)){const u={title:"Validator Error - Unique",type:"model",errorGroup:"PropertyDataError",model:s.key,errorType:"InvalidValidator",attribute:t,itemKey:a.key,description:`The value "${l}" is not unique`};o.push(u),i&&delete a[t]}else n.add(l)}return o}validateEmail(e,t){if(e!=null&&!/^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,6}$/.test(e))return{title:"Validator Error - Invalid Email",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:t,description:`The value "${e}" is not a valid email address`}}validateMin(e,t,s){if(e<t.value)return{title:"Validator Error - Min Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is smaller than the minimum value of "${t.value}"`}}validateMax(e,t,s){if(e>t.value)return{title:"Validator Error - Max Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is larger than the maximum value of "${t.value}"`}}validateStartsWith(e,t,s){if(e!=null&&!e.startsWith(t.value))return{title:"Validator Error - StartsWith",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not start with "${t.value}"`}}validateEndsWith(e,t,s){if(e!=null&&!zp(e,t.value))return{title:"Validator Error - EndsWith",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not end with "${t.value}"`}}validateIncludes(e,t,s){if(e!=null&&!Jp(e,t.value))return{title:"Validator Error - Includes",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not include "${t.value}"`}}validateMinLength(e,t,s){if(e!=null&&e.length<t.value)return{title:"Validator Error - Min Length",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is shorter than the minimum length of "${t.value}"`}}validateMaxLength(e,t,s){if(e!=null&&e.length>t.value)return{title:"Validator Error - Max Length",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is longer than the maximum length of "${t.value}"`}}validateEnum(e,t,s){if(!t.value.includes(e))return{title:"Validator Error - Enum",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is not in the enum values`}}validatePattern(e,t,s){if(e!=null)try{if(!new RegExp(t.value).test(e))return{title:"Validator Error - Pattern",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not match the pattern "${t.value}"`}}catch(o){this.log.error("Invalid pattern validation",o)}}};var sh=Object.defineProperty,oh=Object.getOwnPropertyDescriptor,G=(r,e,t,s)=>{for(var o=oh(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&sh(e,t,o),o};class Q{cdRef=new Cr;analyticsController=new gf;containerSourceMetadata=new WeakMap;scriptController=new Zf;qualityController=new rh(this.scriptController);log=Te.child({prefix:"Dcupl"});modelParser=new ut(this.cdRef,this.qualityController,this);globalItemService=new Go(this.modelParser,this.scriptController);queryManager=new Jf(this.scriptController,this.globalItemService,this.modelParser);_loaders=new Map;rootQueryBuilder=new ke;_defaultInitOptions={config:{projectId:void 0,apiKey:void 0,version:"draft"},errorTracking:{enabled:!1},quality:{enabled:!0},analytics:{enabled:!1},performance:{cache:{enabled:!0},clone:{enabled:!0},partialUpdates:{modelRatioThreshold:.5,itemRatioThreshold:.5,enableDetailedLogging:!1},autoUpdateLists:{enabled:!1}},referenceMetadata:{enabled:!1}};initOptions;lists=new Jo(this,this.cdRef);busy=!1;updateQueue=[];constructor(e){this.analyticsController.init(!!e?.analytics?.enabled),this.qualityController.dcupl=this,this.analyticsController.mark({name:"dcupl:constructor"}),this.initOptions=lt({},this._defaultInitOptions,e),this.qualityController.enabled=this.initOptions.errorTracking?.enabled||this.initOptions.quality?.enabled||!1,this.qualityController.maxErrorsPerGroup=this.initOptions.quality?.maxErrorsPerGroup??1e3,this.modelParser.initOptions=Object.assign({},this.initOptions),this.cdRef._init({cdRefKey:"root",dcuplInitOptions:this.initOptions,analyticsController:this.analyticsController})}models={get:e=>this.modelParser.models.get(e)?.getModelDefinition(),set:e=>(this.modelParser.models.delete(e.key),this.modelParser.addModel(e)),update:e=>this.modelParser.addModel(e),remove:e=>{this.modelParser.models.delete(e)},keys:()=>this.modelParser._getModelKeys()};quality={errors:{summary:()=>this.qualityController.getErrorSummary()}};views={get:e=>this.modelParser.views.get(e),keys:e=>this.modelParser._getViewKeys(e),set:e=>this.modelParser.addView(e)};data={update:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"update",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},upsert:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"upsert",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},set:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"set",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},remove:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"remove",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},reset:e=>{e.model&&this.modelParser.addData({data:[],model:e.model,type:"set"})},apply:e=>this.modelParser.addData(e)};loaders={add:(e,t)=>{this.addLoader(e,t)},remove:e=>{this.removeLoader(e)},get:e=>this._loaders.get(e)};scripts={set:(e,t)=>{this.scriptController.setScript(e,t)},remove:e=>{this.scriptController.removeScript(e)},get:e=>{this.scriptController.getScript(e)},keys:()=>this.scriptController.keys(),execute:(e,t)=>{const s={dcupl:this,options:t};return this.scriptController.executeScript(e,"script",s)},executeAsync:(e,t)=>new Promise((s,o)=>{const n={dcupl:this,options:t,resolve:s,reject:o};return this.scriptController.executeScript(e,"async_script",n)})};fn={pivot:e=>this._pivot(e),aggregate:e=>this._aggregate(e),suggest:e=>this._suggest(e),groupBy:e=>this._groupBy(e),facets:e=>this._facets(e),metadata:e=>this._metadata(e)};_pivot(e){return this.getFnList(e).catalog.fn.pivot(e.options)}_aggregate(e){return this.getFnList(e).catalog.fn.aggregate(e.options)}_suggest(e){return this.getFnList(e).catalog.fn.suggest(e.options)}_groupBy(e){return this.getFnList(e).catalog.fn.groupBy(e.options)}_facets(e){return this.getFnList(e).catalog.fn.facets(e.options)}_metadata(e){return this.getFnList(e).catalog.fn.metadata()}registerContainer(e){this.modelParser.addData(e)}updateRegisteredContainer(e,t){const s=this.modelParser.unprocessedData.findIndex(o=>o.placeholderUid===e.placeholderUid);s>-1&&(delete e.placeholderUid,this.modelParser.unprocessedData[s]=e,t&&this.containerSourceMetadata.set(e,t))}removeRegisteredContainer(e){const t=this.modelParser.unprocessedData.findIndex(s=>s.placeholderUid===e.placeholderUid);t>-1&&this.modelParser.unprocessedData.splice(t,1)}getContainerSourceMetadata(e){return this.containerSourceMetadata.get(e)}setContainerSourceMetadata(e,t){this.containerSourceMetadata.set(e,t)}getFnList(e){let t=this.lists.get(`__global_list__${e.modelKey}`);return t||(t=this.lists.create({modelKey:e.modelKey,listKey:`__global_list__${e.modelKey}`})),e.query?t.catalog.query.apply(e.query,{mode:"set"}):t.catalog.query.reset(),t}snapshotChangedAttributes(){const e=this.modelParser.changeTracker;if(!e.hasChanges())return null;const t=e.getChangedAttributes(),s=new Map;for(const o of e.getEffectivelyChangedModels()){const n=new Set(t.get(o)??[]);if(n.size===0){const i=this.modelParser.models.get(o);for(const a of i?.properties.keys()??[])n.add(a);for(const a of i?.references.keys()??[])n.add(a)}s.set(o,n)}return s}getAffectedModels(e){const t=new Set(e.keys()),s=this.modelParser.dependencyGraph;if(s)for(const n of s.getImpactedNodes(Array.from(e.keys()),"downstream"))t.add(n);const o=this.modelParser.attributeDependencyGraph;if(o){const n=[];for(const[i,a]of e)for(const l of a)n.push({modelKey:i,attributeKey:l,type:"property",processingStep:1});for(const i of o.getImpactedAttributes(n))t.add(i.modelKey)}return Array.from(t)}updateFnLists(e,t){const s=this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1,o=[];for(const n of this.lists.getAll()){if(e&&!this.isListAffectedByChanges(n,e.affectedModels)){s&&this.log.debug("List skipped (not affected)",{listKey:n.key,modelKey:n.modelKey});continue}try{this.shouldAutoUpdateList(n,t)?(s&&this.log.debug("List auto-updating",{listKey:n.key,modelKey:n.modelKey,affectedModels:e?.affectedModels??"all"}),n.update()):(s&&this.log.debug("List caches invalidated (auto-update disabled)",{listKey:n.key,modelKey:n.modelKey}),n.invalidate()),o.push(n)}catch(i){this.log.error(`List refresh failed for '${n.key}'`,i)}}for(const n of o)if(!n.key.startsWith("__global_list__"))try{n.emitResultUpdated()}catch(i){this.log.error(`result_updated handler failed for list '${n.key}'`,i)}}isListAffectedByChanges(e,t){const s=e.modelKey;return t.includes(s)}shouldAutoUpdateList(e,t){return e.key.startsWith("__global_list__")?!0:t!==void 0?t:e.options.autoUpdate!==void 0?e.options.autoUpdate:this.initOptions.performance?.autoUpdateLists?.enabled??!1}query={one:e=>this.getItem(e),many:e=>this._getManyItems(e),execute:e=>this.executeQuery(e),generate:(e,t)=>(this.rootQueryBuilder.init({modelKey:e}),this.rootQueryBuilder.applyQuery(t)),registerCustomOperator:(e,t)=>{this.queryManager.registerCustomOperator(e,t)}};on(e){return this.cdRef.on(e)}async init(){try{return await this.performUpdate(()=>this.modelParser.init()),this.updateFnLists(null),!0}catch(e){return this.log.error("Initialization failed",e),!1}}async update(e){try{const t=this.snapshotChangedAttributes();if(await this.performUpdate(()=>this.modelParser.update()),t){const s={isPartialUpdate:!0,changedModels:Array.from(t.keys()),changedAttributes:t,affectedModels:this.getAffectedModels(t)};this.updateFnLists(s,e?.autoUpdateLists),this.cdRef.trigger({scope:"global",type:"dcupl_partial_update",args:[s]})}else this.updateFnLists(null,e?.autoUpdateLists);return!0}catch(t){return this.log.error("Update failed",t),!1}}destroy(){try{this.lists.destroy(),this._loaders.forEach(e=>{e.destroy()})}catch{}}getItem(e){const t=this.modelParser.models.get(e.modelKey);if(!t)throw new Error;return this.globalItemService.getItem(e.itemKey,t.data,t,e)}_getManyItems(e){const t=this.modelParser.models.get(e.modelKey);if(!t)throw new Error;return this.globalItemService.getManyItems(e.itemKeys,t.data,t,e)}executeQuery(e){if(!e?.modelKey)throw new Error("No modelKey provided");return this.getFnList({modelKey:e?.modelKey}).catalog.query.execute(e)}addLoader(e,t){const s=ce.now(),o=t||W();this._loaders.set(o,e),e.core=this,e.key=o;const n=new Cr;n._init({cdRefKey:o,parentCd:this.cdRef,dcuplInitOptions:this.initOptions,analyticsController:this.analyticsController}),e.cdRef=n,this.initOptions.config?.projectId&&e.defaultVariables.set("projectId",{key:"projectId",value:this.initOptions.config?.projectId}),this.initOptions.config?.apiKey&&e.defaultVariables.set("apiKey",{key:"apiKey",value:this.initOptions.config?.apiKey}),this.initOptions.config?.version&&e.defaultVariables.set("version",{key:"version",value:this.initOptions.config?.version}),this.cdRef.trigger({scope:"global",type:"loader_added",connectMessage:!0,args:[o],start:s})}removeLoader(e){const t=this._loaders.get(e);t&&t.destroy(),this._loaders.delete(e)}async performUpdate(e){if(this.busy)return new Promise(t=>{this.updateQueue.push(()=>e().then(t))});try{this.busy=!0,await e()}finally{this.busy=!1,this.processQueue()}}async processQueue(){if(this.updateQueue.length>0){const e=this.updateQueue.shift();e&&(await e(),this.processQueue())}}}G([b({scope:"global",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_pivot"),G([b({scope:"global",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_aggregate"),G([b({scope:"global",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_suggest"),G([b({scope:"global",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_groupBy"),G([b({scope:"global",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_facets"),G([b({scope:"global",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_metadata"),G([b({scope:"global",type:"dcupl_initialized",connectMessage:!0})],Q.prototype,"init"),G([b({scope:"global",type:"dcupl_updated_manually",action:"update",connectMessage:!0})],Q.prototype,"update"),G([b({scope:"global",type:"dcupl_destroyed",connectMessage:!0})],Q.prototype,"destroy"),G([b({scope:"global",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"getItem"),G([b({scope:"global",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_getManyItems"),G([b({scope:"global",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"executeQuery"),G([b({scope:"global",type:"loader_removed",connectMessage:!0})],Q.prototype,"removeLoader");let nh=class extends Q{version="2.0.0-beta.6";constructor(e){super(e)}};var Zo=typeof global=="object"&&global&&global.Object===Object&&global,ih=typeof self=="object"&&self&&self.Object===Object&&self,Y=Zo||ih||Function("return this")(),fe=Y.Symbol,Yo=Object.prototype,ah=Yo.hasOwnProperty,lh=Yo.toString,ct=fe?fe.toStringTag:void 0;function uh(r){var e=ah.call(r,ct),t=r[ct];try{r[ct]=void 0;var s=!0}catch{}var o=lh.call(r);return s&&(e?r[ct]=t:delete r[ct]),o}var ch=Object.prototype,dh=ch.toString;function fh(r){return dh.call(r)}var ph="[object Null]",hh="[object Undefined]",Xo=fe?fe.toStringTag:void 0;function Fe(r){return r==null?r===void 0?hh:ph:Xo&&Xo in Object(r)?uh(r):fh(r)}function qe(r){return r!=null&&typeof r=="object"}var yh="[object Symbol]";function Tr(r){return typeof r=="symbol"||qe(r)&&Fe(r)==yh}function gh(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var Qe=Array.isArray,en=fe?fe.prototype:void 0,tn=en?en.toString:void 0;function rn(r){if(typeof r=="string")return r;if(Qe(r))return gh(r,rn)+"";if(Tr(r))return tn?tn.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Tt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var mh="[object AsyncFunction]",vh="[object Function]",bh="[object GeneratorFunction]",kh="[object Proxy]";function sn(r){if(!Tt(r))return!1;var e=Fe(r);return e==vh||e==bh||e==mh||e==kh}var Or=Y["__core-js_shared__"],on=(function(){var r=/[^.]+$/.exec(Or&&Or.keys&&Or.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function wh(r){return!!on&&on in r}var Ah=Function.prototype,$h=Ah.toString;function Ae(r){if(r!=null){try{return $h.call(r)}catch{}try{return r+""}catch{}}return""}var Ch=/[\\^$.*+?()[\]{}|]/g,Dh=/^\[object .+?Constructor\]$/,_h=Function.prototype,Ph=Object.prototype,xh=_h.toString,Eh=Ph.hasOwnProperty,jh=RegExp("^"+xh.call(Eh).replace(Ch,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Sh(r){if(!Tt(r)||wh(r))return!1;var e=sn(r)?jh:Dh;return e.test(Ae(r))}function Mh(r,e){return r?.[e]}function $e(r,e){var t=Mh(r,e);return Sh(t)?t:void 0}var Kr=$e(Y,"WeakMap"),nn=Object.create,Rh=(function(){function r(){}return function(e){if(!Tt(e))return{};if(nn)return nn(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})(),an=(function(){try{var r=$e(Object,"defineProperty");return r({},"",{}),r}catch{}})();function Ih(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}var Th=9007199254740991,Oh=/^(?:0|[1-9]\d*)$/;function Kh(r,e){var t=typeof r;return e=e??Th,!!e&&(t=="number"||t!="symbol"&&Oh.test(r))&&r>-1&&r%1==0&&r<e}function Fh(r,e,t){e=="__proto__"&&an?an(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function ln(r,e){return r===e||r!==r&&e!==e}var qh=Object.prototype,Qh=qh.hasOwnProperty;function Vh(r,e,t){var s=r[e];(!(Qh.call(r,e)&&ln(s,t))||t===void 0&&!(e in r))&&Fh(r,e,t)}var Gh=9007199254740991;function un(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Gh}function Bh(r){return r!=null&&un(r.length)&&!sn(r)}var Uh=Object.prototype;function cn(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Uh;return r===t}function Nh(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var zh="[object Arguments]";function dn(r){return qe(r)&&Fe(r)==zh}var fn=Object.prototype,Lh=fn.hasOwnProperty,Wh=fn.propertyIsEnumerable,Hh=dn((function(){return arguments})())?dn:function(r){return qe(r)&&Lh.call(r,"callee")&&!Wh.call(r,"callee")};function Jh(){return!1}var pn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hn=pn&&typeof module=="object"&&module&&!module.nodeType&&module,Zh=hn&&hn.exports===pn,yn=Zh?Y.Buffer:void 0,Yh=yn?yn.isBuffer:void 0,gn=Yh||Jh,Xh="[object Arguments]",ey="[object Array]",ty="[object Boolean]",ry="[object Date]",sy="[object Error]",oy="[object Function]",ny="[object Map]",iy="[object Number]",ay="[object Object]",ly="[object RegExp]",uy="[object Set]",cy="[object String]",dy="[object WeakMap]",fy="[object ArrayBuffer]",py="[object DataView]",hy="[object Float32Array]",yy="[object Float64Array]",gy="[object Int8Array]",my="[object Int16Array]",vy="[object Int32Array]",by="[object Uint8Array]",ky="[object Uint8ClampedArray]",wy="[object Uint16Array]",Ay="[object Uint32Array]",D={};D[hy]=D[yy]=D[gy]=D[my]=D[vy]=D[by]=D[ky]=D[wy]=D[Ay]=!0,D[Xh]=D[ey]=D[fy]=D[ty]=D[py]=D[ry]=D[sy]=D[oy]=D[ny]=D[iy]=D[ay]=D[ly]=D[uy]=D[cy]=D[dy]=!1;function $y(r){return qe(r)&&un(r.length)&&!!D[Fe(r)]}function Fr(r){return function(e){return r(e)}}var mn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,dt=mn&&typeof module=="object"&&module&&!module.nodeType&&module,Cy=dt&&dt.exports===mn,qr=Cy&&Zo.process,Ve=(function(){try{var r=dt&&dt.require&&dt.require("util").types;return r||qr&&qr.binding&&qr.binding("util")}catch{}})(),vn=Ve&&Ve.isTypedArray,Dy=vn?Fr(vn):$y,_y=Object.prototype,Py=_y.hasOwnProperty;function xy(r,e){var t=Qe(r),s=!t&&Hh(r),o=!t&&!s&&gn(r),n=!t&&!s&&!o&&Dy(r),i=t||s||o||n,a=i?Nh(r.length,String):[],l=a.length;for(var u in r)Py.call(r,u)&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||n&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Kh(u,l)))&&a.push(u);return a}function bn(r,e){return function(t){return r(e(t))}}var Ey=bn(Object.keys,Object),jy=Object.prototype,Sy=jy.hasOwnProperty;function My(r){if(!cn(r))return Ey(r);var e=[];for(var t in Object(r))Sy.call(r,t)&&t!="constructor"&&e.push(t);return e}function Ry(r){return Bh(r)?xy(r):My(r)}var Iy=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ty=/^\w*$/;function Oy(r,e){if(Qe(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Tr(r)?!0:Ty.test(r)||!Iy.test(r)||e!=null&&r in Object(e)}var ft=$e(Object,"create");function Ky(){this.__data__=ft?ft(null):{},this.size=0}function Fy(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var qy="__lodash_hash_undefined__",Qy=Object.prototype,Vy=Qy.hasOwnProperty;function Gy(r){var e=this.__data__;if(ft){var t=e[r];return t===qy?void 0:t}return Vy.call(e,r)?e[r]:void 0}var By=Object.prototype,Uy=By.hasOwnProperty;function Ny(r){var e=this.__data__;return ft?e[r]!==void 0:Uy.call(e,r)}var zy="__lodash_hash_undefined__";function Ly(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=ft&&e===void 0?zy:e,this}function Ce(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}Ce.prototype.clear=Ky,Ce.prototype.delete=Fy,Ce.prototype.get=Gy,Ce.prototype.has=Ny,Ce.prototype.set=Ly;function Wy(){this.__data__=[],this.size=0}function Ot(r,e){for(var t=r.length;t--;)if(ln(r[t][0],e))return t;return-1}var Hy=Array.prototype,Jy=Hy.splice;function Zy(r){var e=this.__data__,t=Ot(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Jy.call(e,t,1),--this.size,!0}function Yy(r){var e=this.__data__,t=Ot(e,r);return t<0?void 0:e[t][1]}function Xy(r){return Ot(this.__data__,r)>-1}function eg(r,e){var t=this.__data__,s=Ot(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function ne(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ne.prototype.clear=Wy,ne.prototype.delete=Zy,ne.prototype.get=Yy,ne.prototype.has=Xy,ne.prototype.set=eg;var pt=$e(Y,"Map");function tg(){this.size=0,this.__data__={hash:new Ce,map:new(pt||ne),string:new Ce}}function rg(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Kt(r,e){var t=r.__data__;return rg(e)?t[typeof e=="string"?"string":"hash"]:t.map}function sg(r){var e=Kt(this,r).delete(r);return this.size-=e?1:0,e}function og(r){return Kt(this,r).get(r)}function ng(r){return Kt(this,r).has(r)}function ig(r,e){var t=Kt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function pe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}pe.prototype.clear=tg,pe.prototype.delete=sg,pe.prototype.get=og,pe.prototype.has=ng,pe.prototype.set=ig;var ag="Expected a function";function Qr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(ag);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(Qr.Cache||pe),t}Qr.Cache=pe;var lg=500;function ug(r){var e=Qr(r,function(s){return t.size===lg&&t.clear(),s}),t=e.cache;return e}var cg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,dg=/\\(\\)?/g,fg=ug(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(cg,function(t,s,o,n){e.push(o?n.replace(dg,"$1"):s||t)}),e});function pg(r){return r==null?"":rn(r)}function hg(r,e){return Qe(r)?r:Oy(r,e)?[r]:fg(pg(r))}function yg(r){if(typeof r=="string"||Tr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function gg(r,e){e=hg(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[yg(e[t++])];return t&&t==s?r:void 0}function mg(r,e,t){var s=r==null?void 0:gg(r,e);return s===void 0?t:s}function vg(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var bg=bn(Object.getPrototypeOf,Object);function kg(){this.__data__=new ne,this.size=0}function wg(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Ag(r){return this.__data__.get(r)}function $g(r){return this.__data__.has(r)}var Cg=200;function Dg(r,e){var t=this.__data__;if(t instanceof ne){var s=t.__data__;if(!pt||s.length<Cg-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new pe(s)}return t.set(r,e),this.size=t.size,this}function Ge(r){var e=this.__data__=new ne(r);this.size=e.size}Ge.prototype.clear=kg,Ge.prototype.delete=wg,Ge.prototype.get=Ag,Ge.prototype.has=$g,Ge.prototype.set=Dg;var kn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,wn=kn&&typeof module=="object"&&module&&!module.nodeType&&module,_g=wn&&wn.exports===kn,An=_g?Y.Buffer:void 0;An&&An.allocUnsafe;function Pg(r,e){return r.slice()}function xg(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function Eg(){return[]}var jg=Object.prototype,Sg=jg.propertyIsEnumerable,$n=Object.getOwnPropertySymbols,Mg=$n?function(r){return r==null?[]:(r=Object(r),xg($n(r),function(e){return Sg.call(r,e)}))}:Eg;function Rg(r,e,t){var s=e(r);return Qe(r)?s:vg(s,t(r))}function Ig(r){return Rg(r,Ry,Mg)}var Vr=$e(Y,"DataView"),Gr=$e(Y,"Promise"),Br=$e(Y,"Set"),Cn="[object Map]",Tg="[object Object]",Dn="[object Promise]",_n="[object Set]",Pn="[object WeakMap]",xn="[object DataView]",Og=Ae(Vr),Kg=Ae(pt),Fg=Ae(Gr),qg=Ae(Br),Qg=Ae(Kr),ie=Fe;(Vr&&ie(new Vr(new ArrayBuffer(1)))!=xn||pt&&ie(new pt)!=Cn||Gr&&ie(Gr.resolve())!=Dn||Br&&ie(new Br)!=_n||Kr&&ie(new Kr)!=Pn)&&(ie=function(r){var e=Fe(r),t=e==Tg?r.constructor:void 0,s=t?Ae(t):"";if(s)switch(s){case Og:return xn;case Kg:return Cn;case Fg:return Dn;case qg:return _n;case Qg:return Pn}return e});var Vg=Object.prototype,Gg=Vg.hasOwnProperty;function Bg(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Gg.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var En=Y.Uint8Array;function Ur(r){var e=new r.constructor(r.byteLength);return new En(e).set(new En(r)),e}function Ug(r,e){var t=Ur(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Ng=/\w*$/;function zg(r){var e=new r.constructor(r.source,Ng.exec(r));return e.lastIndex=r.lastIndex,e}var jn=fe?fe.prototype:void 0,Sn=jn?jn.valueOf:void 0;function Lg(r){return Sn?Object(Sn.call(r)):{}}function Wg(r,e){var t=Ur(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var Hg="[object Boolean]",Jg="[object Date]",Zg="[object Map]",Yg="[object Number]",Xg="[object RegExp]",em="[object Set]",tm="[object String]",rm="[object Symbol]",sm="[object ArrayBuffer]",om="[object DataView]",nm="[object Float32Array]",im="[object Float64Array]",am="[object Int8Array]",lm="[object Int16Array]",um="[object Int32Array]",cm="[object Uint8Array]",dm="[object Uint8ClampedArray]",fm="[object Uint16Array]",pm="[object Uint32Array]";function hm(r,e,t){var s=r.constructor;switch(e){case sm:return Ur(r);case Hg:case Jg:return new s(+r);case om:return Ug(r);case nm:case im:case am:case lm:case um:case cm:case dm:case fm:case pm:return Wg(r);case Zg:return new s;case Yg:case tm:return new s(r);case Xg:return zg(r);case em:return new s;case rm:return Lg(r)}}function ym(r){return typeof r.constructor=="function"&&!cn(r)?Rh(bg(r)):{}}var gm="[object Map]";function mm(r){return qe(r)&&ie(r)==gm}var Mn=Ve&&Ve.isMap,vm=Mn?Fr(Mn):mm,bm="[object Set]";function km(r){return qe(r)&&ie(r)==bm}var Rn=Ve&&Ve.isSet,wm=Rn?Fr(Rn):km,In="[object Arguments]",Am="[object Array]",$m="[object Boolean]",Cm="[object Date]",Dm="[object Error]",Tn="[object Function]",_m="[object GeneratorFunction]",Pm="[object Map]",xm="[object Number]",On="[object Object]",Em="[object RegExp]",jm="[object Set]",Sm="[object String]",Mm="[object Symbol]",Rm="[object WeakMap]",Im="[object ArrayBuffer]",Tm="[object DataView]",Om="[object Float32Array]",Km="[object Float64Array]",Fm="[object Int8Array]",qm="[object Int16Array]",Qm="[object Int32Array]",Vm="[object Uint8Array]",Gm="[object Uint8ClampedArray]",Bm="[object Uint16Array]",Um="[object Uint32Array]",A={};A[In]=A[Am]=A[Im]=A[Tm]=A[$m]=A[Cm]=A[Om]=A[Km]=A[Fm]=A[qm]=A[Qm]=A[Pm]=A[xm]=A[On]=A[Em]=A[jm]=A[Sm]=A[Mm]=A[Vm]=A[Gm]=A[Bm]=A[Um]=!0,A[Dm]=A[Tn]=A[Rm]=!1;function Ft(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Tt(r))return r;var a=Qe(r);if(a)i=Bg(r);else{var l=ie(r),u=l==Tn||l==_m;if(gn(r))return Pg(r);if(l==On||l==In||u&&!o)i=u?{}:ym(r);else{if(!A[l])return o?r:{};i=hm(r,l)}}n||(n=new Ge);var c=n.get(r);if(c)return c;n.set(r,i),wm(r)?r.forEach(function(h){i.add(Ft(h,e,t,h,r,n))}):vm(r)&&r.forEach(function(h,p){i.set(p,Ft(h,e,t,p,r,n))});var d=Ig,f=a?void 0:d(r);return Ih(f||r,function(h,p){f&&(p=h,h=r[p]),Vh(i,p,Ft(h,e,t,p,r,n))}),i}var Nm=1,zm=4;function Lm(r){return Ft(r,Nm|zm)}function Wm(r){const e=Nr(r);return Hm(e)}function Nr(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(Nr).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+Nr(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function Hm(r){let e=0;for(let t=0;t<r.length;t++){const s=r.charCodeAt(t);e=(e<<5)-e+s,e|=0}return e.toString(16)}const F={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:r=>{typeof performance<"u"&&performance.mark&&performance.mark(r)},measure:(r,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(r,e,t)},getEntriesByName(r){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(r)},getEntriesByType(r){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(r)}},Kn={silent:0,error:1,warn:2,info:3,debug:4};class S{config;static globalConfig={};constructor(e={}){this.config={level:e.level??S.globalConfig.level??this.getDefaultLevel(),format:e.format??S.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??S.globalConfig.onLog,onTrackError:e.onTrackError??S.globalConfig.onTrackError}}static setGlobalConfig(e){S.globalConfig={...S.globalConfig,...e}}static getGlobalConfig(){return{...S.globalConfig}}static setModuleLevel(e,t){S.globalConfig.onLog||(S.globalConfig.onLog=void 0),S._moduleOverrides||(S._moduleOverrides=new Map),S._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!S._moduleOverrides))return S._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=S.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return Kn[e]<=Kn[t]}formatMessage(e){if(this.config.format==="json"){const i={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(i.module=e.prefix),e.context&&(i.context=e.context),e.error&&(i.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(i)}const t=new Date(e.timestamp).toISOString().substring(11,23),s=e.prefix?`[${e.prefix}]`:"",o=this.getLevelIcon(e.level),n=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${o} ${s} ${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,s,o){if(!this.shouldLog(e))return;const n={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:s,error:o};if(this.config.onLog){this.config.onLog(n);return}const i=this.formatMessage(n);if(typeof console<"u")switch(e){case"error":o?console.error(i,o):console.error(i);break;case"warn":console.warn(i);break;case"debug":console.debug?console.debug(i):console.log(i);break;default:console.log(i)}}error(e,t,s){const o=t instanceof Error?t:void 0,n=t instanceof Error?s:t;this.log("error",e,n,o)}trackError(e,t,s){if(this.error(e,t,s?.context),this.config.onTrackError){const o={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:s?.context,error:t,errorType:s?.errorType,errorGroup:s?.errorGroup};this.config.onTrackError(o)}}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 S(t)}configure(e){Object.assign(this.config,e)}}const zr=new S;function Lr(r=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let s=0;s<r;s++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}let Jm=class{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=F.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 Fn=(r,e)=>e?typeof structuredClone<"u"?structuredClone(r):Lm(r):r,qn=(r,e,t,s,o,n)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=Fn(n,i);if(t.scope==="list"&&(t.listKey=r.cdRef?.key||r.key,t.modelKey=r.model?.key||r.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const l=F.now(),u=l-s,c=Math.round(u*1e3)/1e3;t.duration=c,t.start=s,t.end=l;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:o}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:o,detail:d}),a}catch{return n}},Qn=r=>(e,t,s)=>{const o=s.value;return s.value=function(...n){const i=F.now(),a=this.cdRef,l=Fn(r,!0);l.key||(a.increaseCounter(),l.key=a.getCounter());const u=Lr();a.analyticsController.mark({name:`${l.type}:start`,context:u});const c=this.model?.key;!l.originCdRefKey&&a.key&&(l.originCdRefKey=a.key),c&&(l.modelKey=c);const d=o.apply(this,n);return l.method=t,l.args=n,d&&typeof d=="object"&&"then"in d?d.then(f=>qn(this,a,l,i,u,f)):qn(this,a,l,i,u,d)},s},Zm=new Set(["apikey","api-key","managerkey","token","proxy-key","proxykey","manager-key","sdk-key"]);function Be(r){const e=r.indexOf("?");if(e<0)return r;const t=r.slice(e+1).split("&").map(s=>{const o=s.indexOf("=");if(o<0)return s;const n=s.slice(0,o);return Zm.has(n.toLowerCase())?`${n}=<redacted>`:s}).join("&");return`${r.slice(0,e)}?${t}`}const Ym="k:",Xm="h:";function Wr(r,e=0){if(r.key)return`${Ym}${r.key}`;const t=Wm({type:r.type,url:r.rawUrl??r.url,model:r.model??"",occurrence:e});return`${Xm}${t}`}function ev(r){const e=new Map,t=new Set;return r.map(s=>{const o=`${s.key??""}|${s.type}|${s.rawUrl??s.url}|${s.model??""}`;let n=e.get(o)??0,i=Wr(s,n);for(;t.has(i);)n+=1,i=s.key?`${Wr(s)}#${n}`:Wr(s,n);return e.set(o,n+1),t.add(i),i})}const qt=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>mg(e,s.trim(),""))):"",tv=r=>{const e=new Set;return r.replace(/\$\{(.*?)\}/g,(t,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(t=>({name:t}))}};let rv=class{log=zr.child({prefix:"DcuplCsvParser"});parse(r,e={}){const{quoteChar:t=e.quoteChar||'"',escapeChar:s=e.escapeChar||'"',comments:o=e.comments||void 0,dynamicTyping:n=!1,header:i=!0,skipEmptyLines:a=!0,transformHeader:l,transform:u}=e,c=[],d=i?[]:null;let f=r.length,h=[],p="",y=!1,v=!0,g=0;if(a){for(;g<f&&(r[g]===`
|
|
9
|
-
`||r[g]==="\r"||r[g]===""||r[g]==="'"||r[g]==='"');)g++;r=r.slice(g),f=r.length,g=0}const k=e.delimiter||this.detectDelimiter(r);for(;g<f;g++){const m=r[g],
|
|
8
|
+
These attributes will default to Step 1 processing which may be incorrect. This usually indicates a problem during expression or reference parsing.`)}}processExpressionProperty(e,t,s){const o={modelKey:e,attributeKey:t,type:"property",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const{variables:n}=Pr(s);n.forEach(i=>{const a=i.name.split("."),l=this.models.get(e);if(!l)return;const u=a[0];if(l.properties.has(u)){const c={modelKey:e,attributeKey:u,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,c)}else if(l.references.has(u)){const c={modelKey:e,attributeKey:u,type:"reference",processingStep:1};if(this.attributeDependencyGraph.addAttributeDependency(o,c),a.length>1){let d=l,f=e;for(let h=0;h<a.length-1;h++){const p=a[h],y=d.references.get(p);if(y){const v=this.models.get(y.model);if(v&&(d=v,f=y.model,h===a.length-2)){const g=a[a.length-1],k={modelKey:f,attributeKey:g,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,k)}}}}}})}processDerivedProperty(e,t,s){const o={modelKey:e,attributeKey:t,type:"property",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.localReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n);const i=this.models.get(e);if(i){const a=i.references.get(s.localReference);if(a){const l={modelKey:a.model,attributeKey:s.remoteProperty,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,l)}}}processQueryReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:2};this.attributeDependencyGraph.addAttribute(o);try{const n=JSON.stringify(s),{variables:i}=Pr(n);i.forEach(a=>{const l=a.name,u=this.models.get(e);if(u){if(u.properties.has(l)){const c={modelKey:e,attributeKey:l,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,c)}else if(u.references.has(l)){const c={modelKey:e,attributeKey:l,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,c)}}})}catch{}}processResolvedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:2};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:s.model,attributeKey:s.reference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n)}processDerivedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.localReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n);const i=this.models.get(e);if(i){const a=i.references.get(s.localReference);if(a){const l={modelKey:a.model,attributeKey:s.remoteReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,l)}}}processGroupedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.reference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n)}async update(){const e=performance.now(),t=this.shouldUsePartialUpdate();if(t.decision){const s=this.changeTracker.getModelsWithChanges().length,o=Array.from(this.changeTracker.getChangedAttributes().values()).reduce((a,l)=>a+l.size,0),n=this.changeTracker.getTotalChangedItemCount();await this.partialUpdate();const i=performance.now()-e;this.partialUpdateMetrics.recordUpdate({type:"partial",durationMs:i,modelsAffected:s,attributesProcessed:o,itemsChanged:n,decisionReason:t.reason,timestamp:Date.now()})}else{await this.init();const s=performance.now()-e;this.partialUpdateMetrics.recordUpdate({type:"full",durationMs:s,decisionReason:t.reason,timestamp:Date.now()})}}shouldUsePartialUpdate(){const e=this.dcuplInstance.initOptions.performance?.partialUpdates,t=e?.modelRatioThreshold??.5,s=e?.itemRatioThreshold??.5,o=e?.enableDetailedLogging??!1;if(!this.changeTracker.hasChanges())return o&&this.log.debug("Partial update decision: SKIP",{reason:"no_changes_detected"}),{decision:!1,reason:"no_changes_detected"};if(this.changeTracker.getModelsWithFullReset().size>0)return o&&this.log.debug("Partial update decision: FULL",{reason:"full_reset_detected"}),{decision:!1,reason:"full_reset_detected"};const n=Array.from(this.models.keys()).filter(c=>!c.startsWith("$")).length,i=this.changeTracker.getAffectedModelRatio(n);let a=0,l=0;for(const c of this.changeTracker.getModelsWithChanges()){const d=this.models.get(c);if(d){const f=d.getData().size;a+=f,l+=this.changeTracker.getChangedItems(c).size,l+=this.changeTracker.getDeletedItems(c).size}}const u=a>0?l/a:0;return i>t&&u>s?(o&&this.log.debug("Partial update decision: FULL",{reason:"both_ratios_high",modelRatio:i.toFixed(2),itemRatio:u.toFixed(2)}),{decision:!1,reason:`both_ratios_high:models=${i.toFixed(2)},items=${u.toFixed(2)}`}):(o&&this.log.debug("Partial update decision: PARTIAL",{modelRatio:i.toFixed(2),itemRatio:u.toFixed(2),modelThreshold:t,itemThreshold:s}),{decision:!0,reason:`optimal:models=${i.toFixed(2)},items=${u.toFixed(2)}`})}async partialUpdate(){const e=this.handleAlternativeKey(this.unprocessedData).filter(o=>!o.placeholderUid);for(const o of e)if(o.type==="remove"){const n=this.models.get(o.model);if(n){n.deleteDataEntries(o);for(const i of n.properties.values())this.changeTracker.recordAttributeChange(o.model,i.key);for(const i of n.references.values())this.changeTracker.recordAttributeChange(o.model,i.key)}}const t=this.unprocessedData.filter(o=>!o.placeholderUid),s=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModelsPartial(s),this.consolidateUnprocessedData(s,t),this.retrackUnprocessedData(s)}async reprocessData(){this.qualityController.enabled&&this.qualityController.resetModelErrors();const e=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(e)}getSortedCalculationTimings(){return $o(this.calculationTimings,"value")}addModel(e){if(e?.quality?.enabled!==!1)try{xp(e)}catch(t){this.qualityController.enabled&&this.qualityController.setError({title:"Invalid Model Definition",type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:e.key,description:t.message});return}if(this.unprocessedModelDescriptions.has(e.key)){const t=this.unprocessedModelDescriptions.get(e.key),s=this.mergeModels(t,e);this.unprocessedModelDescriptions.set(e.key,s)}else this.unprocessedModelDescriptions.set(e.key,e);e.data&&this.addData({model:e.key,data:e.data,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty})}mergeModels(e,t){const s=Object.assign({},e,t);return(Array.isArray(e.properties)||Array.isArray(t.properties))&&(s.properties=[...Array.isArray(e.properties)?e.properties:[],...Array.isArray(t.properties)?t.properties:[]]),(Array.isArray(e.references)||Array.isArray(t.references))&&(s.references=[...Array.isArray(e.references)?e.references:[],...Array.isArray(t.references)?t.references:[]]),s}addData(e){if(!e||!e.model||!e.data)throw new Error("Invalid Data Container");if(!Array.isArray(e.data))throw new Error("Invalid Data - Data must be an Array");e.type||(e.type="set"),e.autoGenerateProperties&&this.addModel({key:e.model,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty||"key"}),this.changeTracker.recordDataChange(e),this.unprocessedData.push(e)}addView(e){this.views.set(e.key,e)}setError(e,t){this.qualityController.enabled&&t.qualityConfig.enabled===!0&&this.qualityController.setError(e)}getMergedContainers(e){const t=this.handleAlternativeKey(e).filter(n=>!n.placeholderUid),s=[],o=jr(t,"model");for(const n in o){const i=o[n];if(i.length>1){const a=this.mergeContainers(i),l=this.mergeContainerSourceMetadata(i);l&&this.dcuplInstance.setContainerSourceMetadata(a,l),s.push(a)}else s.push(i[0])}return s}consolidateUnprocessedData(e,t){const s=new Set(t),o=this.unprocessedData.filter(n=>!s.has(n));for(const n of e)this.keyedContainers.add(n);this.unprocessedData=[...e,...o]}retrackUnprocessedData(e){const t=new Set(e);for(const s of this.unprocessedData)t.has(s)||s.placeholderUid||s.model.startsWith("$")||this.changeTracker.recordDataChange(s)}mergeContainers(e){let t;return e?.forEach(s=>{if(!t){if(s.type==="remove")return;t=new Map(s.data.map(o=>[o.key,o]));return}switch(s.type){case"upsert":s.data.forEach(o=>{if(t.has(o.key)){let n=t.get(o.key);n=this.mergeRow(n,o),t.set(o.key,n)}else t.set(o.key,o)});break;case"update":s.data.forEach(o=>{if(t.has(o.key)){let n=t.get(o.key);n=this.mergeRow(n,o),t.set(o.key,n)}});break;case"remove":s.data.forEach(o=>{t.delete(o.key)});break;case"set":t=new Map(s.data.map(o=>[o.key,o]));break;default:t=new Map(s.data.map(o=>[o.key,o]));break}}),{model:e[0].model,data:Array.from(t.values()),type:"set"}}mergeRow(e,t){const s={...e};for(const o of Object.keys(t)){const n=t[o];n!==void 0&&o!=="__proto__"&&(s[o]=n)}return s}mergeContainerSourceMetadata(e){let t;for(const s of e){const o=this.dcuplInstance.getContainerSourceMetadata(s),n=s.type??"set";if(n==="set")t=o?{columns:new Set(o.sourceColumns),samples:this.cloneCoercionSamples(o.coercionFailureSamples),origin:o.origin}:void 0;else if((n==="upsert"||n==="update")&&o){t||(t={columns:new Set,samples:{},origin:o.origin}),o.sourceColumns.forEach(i=>t.columns.add(i));for(const i of Object.keys(o.coercionFailureSamples)){const a=o.coercionFailureSamples[i],l=t.samples[i];l?l.count+=a.count:t.samples[i]={...a}}}}if(t)return{sourceColumns:Array.from(t.columns),coercionFailureSamples:t.samples,origin:t.origin}}cloneCoercionSamples(e){const t={};for(const s of Object.keys(e))t[s]={...e[s]};return t}async connectDataWithModels(e){try{this.dependencyGraph.order()}catch(s){this.log.warn("Your models have circular dependencies which might lead to errors. Please consider changing your models"),this.log.error("Dependency graph error",s)}const t=this.dependencyGraph.order({allowCycles:!0});e.sort((s,o)=>t.indexOf(s.model)-t.indexOf(o.model)),await this.handleDataContainer(e)}async connectDataWithModelsPartial(e){const t=this.dependencyGraph.order({allowCycles:!0});e.sort((i,a)=>t.indexOf(i.model)-t.indexOf(a.model));const s=[];for(const[i,a]of this.changeTracker.getChangedAttributes())for(const l of a){const u=this.attributeDependencyGraph.getAttributesForModel(i).find(c=>c.attributeKey===l);if(u)s.push(u);else{const c=this.models.get(i);if(c){const d=c.properties.get(l),f=c.references.get(l);(d||f)&&s.push({modelKey:i,attributeKey:l,type:d?"property":"reference",processingStep:1})}}}const o=this.attributeDependencyGraph.getImpactedAttributes(s),n=this.attributeDependencyGraph.getProcessingOrder(o);for(const i of e){const a=this.models.get(i.model);a?.autoGenerateProperties&&a.generatePropertiesFromContainer(i)}for(const i of[1,2,3,4])await this.processAttributesForStep(i,n,e);for(const[i,a]of n.entries()){const l=this.models.get(i);if(!l)continue;const u=new Set;for(const c of a.values())for(const d of c)u.add(d);l.resetIndicesForChangedAttributes(u)}for(const i of e){const a=this.models.get(i.model);if(a&&this.qualityController.enabled){const l=this.changeTracker.getChangedItems(a.key),u=this.changeTracker.getChangedAttributes().get(a.key);l.size>0&&u&&(this.qualityController.cleanUpErrorsForItems(a,l,u),this.qualityController.validateItemsPartial(a,l,u).forEach(c=>{this.setError(c,a)}))}}this.changeTracker.clear()}getResolvedReferenceProcessingOrder(e){const t=new Map,s=new Set;for(const[l,u]of e.entries()){const c=u.get(2);c&&c.size>0&&(s.add(l),t.set(l,new Set))}if(s.size===0)return this.dependencyGraph.order();for(const l of s){const u=this.models.get(l);if(!u)continue;const c=e.get(l)?.get(2);if(c)for(const d of c){const f=u.references.get(d);if(f&&Rr(f)){const h=f.resolve.model,p=f.resolve.reference,y=this.models.get(h);if(y){const v=y.references.get(p);v&&Rr(v)&&t.get(l).add(h)}}}}const o=[],n=new Set,i=new Set,a=l=>{if(i.has(l)||n.has(l))return;n.add(l);const u=t.get(l);if(u)for(const c of u)a(c);n.delete(l),i.add(l),o.push(l)};for(const l of s)a(l);return o}async processAttributesForStep(e,t,s){let o=this.dependencyGraph.order({allowCycles:!0});e===2&&(o=this.getResolvedReferenceProcessingOrder(t));for(const n of o){const i=t.get(n);if(!i)continue;const a=i.get(e);if(!a||a.size===0)continue;const l=this.models.get(n);if(!l)continue;const u=W(),c=`dcupl:partial_process_data:step_${e}`;if(this.cdRef.analyticsController.mark({name:`${c}:start`,context:u}),e===2)l.rebuildResolvedReferencesForAllItems(a);else{const d=s.find(f=>f.model===n);if(!d)continue;switch(e){case 1:l.addBasicPropertiesAndReferencesPartial(d,a);break;case 3:l.addDerivedAndExpressionAttributesPartial(d,a);break;case 4:l.reRunDerivedPropertiesBasedOnResolvesPartial(d,a);break}}this.cdRef.analyticsController.mark({name:`${c}:end`,context:u}),this.cdRef.analyticsController.measure({name:c,start:`${c}:start`,end:`${c}:end`,context:u,detail:{model:n,attributeCount:a.size}})}}handleAlternativeKey(e){return e.forEach(t=>{if(this.keyedContainers.has(t))return;const s=this.models.get(t.model),o=t.keyProperty??s?.keyProperty,n=t.keyPropertySeparator??s?.keyPropertySeparator??we,i=t.autoGenerateKey||s?.autoGenerateKey;(typeof o=="string"?o!==""&&o!=="key":Array.isArray(o)&&o.length>0)?t.data.forEach(a=>{a.key=zo(a,o,n)}):i&&t.data.forEach(a=>{a.key||(a.key=W())}),this.keyedContainers.add(t)}),e}async handleDataContainer(e){for(const o of e){const n=this.models.get(o.model);n?.autoGenerateProperties&&n.generatePropertiesFromContainer(o)}const t=this.initOptions.performance?.containerBatchSize,s=t!==void 0;for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:start",context:a}),i&&(i.addBasicPropertiesAndReferences(n),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.cleanUpErrors(i,n)),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_1",start:"dcupl:process_data:step_1:start",end:"dcupl:process_data:step_1:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:start",context:a}),i&&i.hasQueryReferences()&&i.addQueryReferences(n),i&&i.hasResolvedReferences()&&i.addResolvedReferences(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_2",start:"dcupl:process_data:step_2:start",end:"dcupl:process_data:step_2:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:start",context:a}),i&&(i.hasDerivedPropertiesForBasicReferences()||i?.hasDerivedReferences()||i?.hasGroupedReferences()||i?.hasExpressionProperties())&&i.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_3",start:"dcupl:process_data:step_3:start",end:"dcupl:process_data:step_3:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model);if(!i){this.log.error("Model not found during data processing",void 0,{model:n.model,step:4});continue}const a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:start",context:a}),(i.hasDerivedPropertiesBasedOnResolvedReferences()||i.hasDerivedReferencesBasedOnResolvedReferences())&&i.reRunDerivedPropertiesBasedOnResolves(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_4",start:"dcupl:process_data:step_4:start",end:"dcupl:process_data:step_4:end",context:a,detail:{model:n.model}}),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.validateAttributesAfterInitialization(i).forEach(l=>{this.setError(l,i)}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}}_getModelKeys(){return Array.from(this.models.values()).map(e=>e.key).filter(e=>e&&!e.startsWith("$Dcupl"))}_getViewKeys(e){const t=e?.modelKey;return Array.from(this.views.values()).filter(s=>t?s.model===t:!0).map(s=>s.key)}getTotalItemCount(){let e=0;for(const t of this.models.values())e+=t.getItemCount();return e}};Rt([b({scope:"global",type:"model_add",connectMessage:!0})],lt.prototype,"addModel"),Rt([b({scope:"global",type:"data_change",connectMessage:!0})],lt.prototype,"addData"),Rt([b({scope:"global",type:"view_add",connectMessage:!0})],lt.prototype,"addView"),Rt([b({scope:"global",type:"dcupl_handle_datacontainer"})],lt.prototype,"handleDataContainer");function Np(r,e,t){return r===r&&(t!==void 0&&(r=r<=t?r:t),r=r>=e?r:e),r}function zp(r,e,t){r=Is(r),e=Ht(e);var s=r.length;t=t===void 0?s:Np(Jt(t),0,s);var o=t;return t-=e.length,t>=0&&r.slice(t,o)==e}function Lp(r,e){return Me(e,function(t){return r[t]})}function Wp(r){return r==null?[]:Lp(r,tt(r))}var Hp=Math.max;function Jp(r,e,t,s){r=te(r)?r:Wp(r),t=t?Jt(t):0;var o=r.length;return t<0&&(t=Hp(o+t,0)),Et(r)?t<=o&&r.indexOf(e,t)>-1:!!o&&ws(r,e,t)>-1}var Zp=Object.defineProperty,Yp=Object.getOwnPropertyDescriptor,Ho=(r,e,t,s)=>{for(var o=Yp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Zp(e,t,o),o};let Ir=class{constructor(e,t){this.dcuplApi=e,this.cdRef=t}dcuplApi;cdRef;options;key;modelKey;catalog;ownsIndicesController=!1;setup(e){const t=this.dcuplApi.modelParser.models.get(e.modelKey);if(!t)throw new Error(`Model with key ${e.modelKey} not found`);const s=this.getListItemKeys(e),o=this.getRelevantData(t,s),n=this.initIndicesController(s,t,o);this.catalog?this.catalog.filter.update(t,o,n):(this.catalog=new rp(this.dcuplApi,this.cdRef,n),this.catalog.init(this.modelKey,t,o))}initIndicesController(e,t,s){let o;if(e){o=new Mt;for(const n of t.indicesController.indexMap.keys())o.getOrCreateIndex(n,s);this.ownsIndicesController=!0}else o=t.indicesController,this.ownsIndicesController=!1;return o}getListItemKeys(e){let t;return e.listItemKeys?t=e.listItemKeys:e.query&&(t=this.dcuplApi.query.execute(e.query).map(s=>s.key)),t}getRelevantData(e,t){const s=e.getData();return t?this.initFromItemKeys(s,t):s}init(e){this.options=oe(e),this.key=this.options.listKey,this.modelKey=this.options.modelKey,this.setup(this.options)}initFromItemKeys(e,t){const s=new Map;return t.forEach(o=>{if(e.has(o)){const n=e.get(o);n&&s.set(o,n)}}),s}destroy(){try{this.dcuplApi.lists.destroy({listKey:this.key})}catch{}}_destroy(){this.catalog.filter.cdRef?.destroy()}update(e){(e&&e.reprocessData||!e)&&this.setup(this.options)}invalidate(){this.catalog&&(this.ownsIndicesController&&this.catalog.filter.indicesController.reset(),this.catalog.filter.resetCache())}getDependencyModels(){return this.catalog?this.catalog.filter.getDependencyModels():new Set}emitResultUpdated(){this.catalog&&this.catalog.filter.emitResultUpdated()}on(e){return this.cdRef.on(e)}onResultChange(e){return this.cdRef.on(t=>{t.type==="result_updated"&&e(t)})}};Ho([b({scope:"list",type:"list_destroyed",connectMessage:!0})],Ir.prototype,"_destroy"),Ho([b({scope:"list",type:"list_updated",action:"update",connectMessage:!0})],Ir.prototype,"update");var Xp=Object.defineProperty,eh=Object.getOwnPropertyDescriptor,th=(r,e,t,s)=>{for(var o=eh(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Xp(e,t,o),o};let Jo=class{constructor(e,t){this.dcuplInstance=e,this.cdRef=t}dcuplInstance;cdRef;lists=[];get(e){if(e)return this.lists.find(t=>t.key===e)}getAll(e){return e?this.lists.filter(t=>t.modelKey===e?.modelKey):this.lists}destroy(e){if(!e)this.lists.forEach(t=>t._destroy()),this.lists=[];else if(e.listKey){const t=this.lists.findIndex(s=>s.key===e.listKey);t>-1&&(this.lists[t]._destroy(),this.lists.splice(t,1))}else e.modelKey&&(this.lists=this.lists.filter(t=>t.modelKey===e.modelKey?(t._destroy(),!1):!0))}create(e){e.listKey=e.listKey||W();const t=new $r;t._init({cdRefKey:e.listKey,parentCd:this.dcuplInstance.cdRef,dcuplInitOptions:this.dcuplInstance.initOptions,analyticsController:this.dcuplInstance.analyticsController});const s=new Ir(this.dcuplInstance,t);return s.init(e),this.lists.push(s),s}};th([b({scope:"global",type:"list_created",connectMessage:!0})],Jo.prototype,"create");let rh=class{constructor(e){this.scriptsController=e}scriptsController;enabled=!1;maxErrorsPerGroup=1e3;errors=new Map;errorCounts=new Map;log=Te.child({prefix:"QualityController"});values={loading:0,processing:0,startup:0,counts:{resources:0,modelFiles:0,dataFiles:0,models:0,rows:0,attributes:0,dataEntries:0},unusedAttributes:[],errors:{size:0,UndefinedValue:0,UndefinedAttribute:0,WrongDataType:0,MissingModel:0,InvalidModelDescription:0,RemoteReferenceKeyNotFound:0},sizes:{totalEncoded:0,totalDecoded:0,unusedDecoded:0,models:[]}};modelParser;dcupl;getErrorGroupKey(e){const t="attribute"in e?e.attribute:void 0;return`${e.model??""}::${t??""}::${e.errorType}`}getGroupCount(e,t,s){const o=`${e??""}::${t??""}::${s}`;return this.errorCounts.get(o)?.count??0}setError(e){const t=this.getErrorGroupKey(e);let s=this.errorCounts.get(t);s||(s={model:e.model,attribute:"attribute"in e?e.attribute:void 0,errorGroup:e.errorGroup,errorType:e.errorType,type:e.type,count:0},this.errorCounts.set(t,s)),s.count+=1,!(s.count>this.maxErrorsPerGroup)&&(e.key||(e.key=W()),this.errors.set(e.key,e))}getErrorCounts(){return Array.from(this.errorCounts.values()).map(({model:e,attribute:t,errorType:s,count:o})=>({model:e,attribute:t,errorType:s,count:o}))}getErrorSummary(){const e=new Map;for(const s of this.errors.values()){const o=this.getErrorGroupKey(s);e.set(o,(e.get(o)??0)+1)}const t=[];for(const[s,o]of this.errorCounts){const n=e.get(s)??0;t.push({key:s,model:o.model,attribute:o.attribute,errorGroup:o.errorGroup,errorType:o.errorType,type:o.type,totalCount:o.count,storedCount:n,truncated:o.count>n})}return t}stampGroupTotals(e){const t=new Map(e.map(s=>[s.key,s]));for(const s of this.errors.values()){const o=t.get(this.getErrorGroupKey(s));s.groupTotal=o?.totalCount??1,s.truncated=o?.truncated??!1}}removeError(e){const t=this.errors.get(e);if(t){const s=this.getErrorGroupKey(t),o=this.errorCounts.get(s);o&&(o.count-=1,o.count<=0&&this.errorCounts.delete(s))}this.errors.delete(e)}getError(e){return this.errors.get(e)}getErrors(){return Array.from(this.errors.values())}resetErrors(){this.errors.clear(),this.errorCounts.clear()}resetModelErrors(){this.getErrors().forEach(e=>{e.type==="model"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&this.errorCounts.delete(e)}resetValidationErrors(){this.getErrors().forEach(e=>{e.type==="model"&&e.errorType==="InvalidValidator"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&t.errorType==="InvalidValidator"&&this.errorCounts.delete(e)}resetDataErrors(){const e=["ReferenceDataError","PropertyDataError","DataContainerError"];this.getErrors().forEach(t=>{t.type==="model"&&e.includes(t.errorGroup)&&this.removeError(t.key)});for(const[t,s]of this.errorCounts)s.type==="model"&&e.includes(s.errorGroup)&&this.errorCounts.delete(t)}cleanUpErrors(e,t){const s=this.dcupl?.getContainerSourceMetadata(t),o=t.model;if(s){const n=s.coercionFailureSamples??{};for(const i of Object.keys(n)){const a=n[i];if(!a||a.count<=0)continue;for(const u of this.getModelErrors(o))u.attribute===i&&u.itemKey!=null&&(u.errorType==="UndefinedValue"||u.errorType==="WrongDataType")&&this.removeError(u.key);const l=e.properties.get(i)?.type??a.expected;this.setError(this.buildColumnCoercionError(o,i,a.rawValue,l,a.count))}for(const[i]of e.properties){if(n[i]||s.sourceColumns.includes(i))continue;const a=this.getGroupCount(o,i,"UndefinedValue");if(a>0&&a===t.data.length){for(const l of this.getModelErrors(o))l.attribute===i&&l.itemKey!=null&&l.errorType==="UndefinedValue"&&this.removeError(l.key);this.setError(this.buildAbsentColumnError(o,i))}}}else{const n=new Set(this.getModelErrors(o).filter(l=>l.errorType==="UndefinedValue"&&l.attribute!=null).map(l=>l.attribute));for(const l of n){const u=this.getGroupCount(o,l,"UndefinedValue");if(u>0&&u===t.data.length){for(const c of this.getModelErrors(o))c.attribute===l&&c.itemKey!=null&&c.errorType==="UndefinedValue"&&this.removeError(c.key);this.setError(this.buildAbsentColumnError(o,l))}}const i=this.getModelErrors(o).filter(l=>l.errorType==="WrongDataType"&&l.errorGroup==="PropertyDataError"&&l.title==="Wrong Data Type"&&l.itemKey!=null),a=jr(i,"attribute");for(const l in a){const u=a[l];if(!u?.length)continue;const c=u[0].meta,d=e.properties.get(l)?.type??c?.expected??"unknown";for(const f of u)this.removeError(f.key);this.setError(this.buildColumnCoercionError(o,l,String(c?.rawValue??""),d,u.length))}}}buildColumnCoercionError(e,t,s,o,n){return{title:"Wrong Data Type",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",model:e,attribute:t,description:`${n} value(s) in column "${t}" of model "${e}" failed to coerce to the declared type "${o}" (e.g. "${s}")`,meta:{rawValue:s,declaredType:o,rowCount:n}}}buildAbsentColumnError(e,t){return{title:"Missing Data",type:"model",errorGroup:"DataContainerError",errorType:"UndefinedAttribute",model:e,attribute:t,description:`The Attribute "${t}" is not present in the dataset for model "${e}"`}}getModelErrors(e){return this.getErrors().filter(t=>t.type==="model"&&t.model===e)}cleanUpErrorsForItems(e,t,s,o){let n,i;typeof s=="string"?i=s:s instanceof Set&&(n=s,i=o);const a=this.getModelErrors(e.key),l=i?a.filter(u=>u.errorType===i):a;for(const u of l)if(u.itemKey&&t.has(u.itemKey)){if(n&&u.attribute&&!n.has(u.attribute))continue;this.removeError(u.key)}}getErrorsForItems(e,t){return this.getModelErrors(e).filter(s=>s.itemKey&&t.has(s.itemKey))}validateItemsPartial(e,t,s){if(!e)return[];const o=[],n=e.getData(),i=e.getAttributes();for(const a of i){if(!s.has(a.key))continue;const l=a.quality?.validators;if(l)for(const u of t){const c=n.get(u);if(!c)continue;const d=c[a.key],f=this.validateAttribute(d,l,a.key);for(const h of f)h.model=e.key,h.itemKey=c.key,o.push(h)}}return o}async initData(){if(!this.modelParser)return;const e=["$DcuplErrorTrackingErrors","$DcuplErrorTrackingSummary"];this.modelParser.unprocessedData=this.modelParser.unprocessedData.filter(o=>!e.includes(o.model));for(const o of e){const n=this.modelParser.models.get(o);n?.resetData(),n?.resetIndexMap()}const t=this.getErrorSummary();this.stampGroupTotals(t),this.modelParser.addData({data:this.getErrors(),model:"$DcuplErrorTrackingErrors",type:"set"}),this.modelParser.addData({data:t,model:"$DcuplErrorTrackingSummary",type:"set"});const s=this.modelParser.unprocessedData.filter(o=>e.includes(o.model));s.length>0&&await this.modelParser.handleDataContainer(s)}initErrorTrackingModels(){this.modelParser?.addModel({key:"$DcuplErrorTrackingErrors",autoGenerateKey:!0,supportsAutoCreation:!0,references:[{key:"model",type:"singleValued",model:"$DcuplErrorTrackingModel",filter:{calculateFacets:!0}},{key:"errorGroup",type:"singleValued",model:"$DcuplErrorTrackingGroup",filter:{calculateFacets:!0}},{key:"errorType",type:"singleValued",model:"$DcuplErrorTrackingType",filter:{calculateFacets:!0}}],properties:[{key:"title",type:"string",filter:!0},{key:"itemKey",type:"string",filter:!0},{key:"attribute",type:"string",filter:!0},{key:"description",type:"string"},{key:"meta",type:"json"},{key:"groupTotal",type:"int"},{key:"truncated",type:"boolean",filter:!0}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingSummary",supportsAutoCreation:!0,references:[{key:"model",type:"singleValued",model:"$DcuplErrorTrackingModel",filter:{calculateFacets:!0}},{key:"errorGroup",type:"singleValued",model:"$DcuplErrorTrackingGroup",filter:{calculateFacets:!0}},{key:"errorType",type:"singleValued",model:"$DcuplErrorTrackingType",filter:{calculateFacets:!0}}],properties:[{key:"attribute",type:"string",filter:!0},{key:"type",type:"string",filter:!0},{key:"totalCount",type:"int",filter:!0},{key:"storedCount",type:"int"},{key:"truncated",type:"boolean",filter:!0}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingType",data:[{key:"UndefinedAttribute"},{key:"InvalidValidator"},{key:"UndefinedValue"},{key:"NullValue"},{key:"WrongDataType"},{key:"MissingModel"},{key:"NonUniqueKey"},{key:"RemoteReferenceKeyNotFound"},{key:"InvalidModelDescription"},{key:"InvalidResource"},{key:"InvalidModelDefinition"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingGroup",data:[{key:"ReferenceDataError"},{key:"PropertyDataError"},{key:"DataContainerError"},{key:"ModelDescriptionError"},{key:"LoaderError"},{key:"ResourceError"},{key:"ModelDefinitionError"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingModel",supportsAutoCreation:!0,quality:{enabled:!1}})}initAnalyticsValues(){this.calculateTiming(),this.calculateSizes(),this.calculateErrorTrackingFacet(),this.calculateCounts(),this.calculateUnusedAttributes()}calculateUnusedAttributes(){this.values.unusedAttributes=[];const e=this.dcupl.models.keys();for(const t of e){const s=this.getUnusedAttributesFromModel(this.dcupl,t);for(const o of s)this.values.unusedAttributes?.push({model:t,attribute:o})}}calculateCounts(){this.values.counts={},this.values.counts.modelFiles=this.dcupl.modelParser.unprocessedModelDescriptions.size,this.values.counts.dataFiles=this.dcupl.modelParser.unprocessedData.length,this.values.counts.models=this.dcupl.models.keys().length;let e=0,t=0,s=0;this.dcupl.models.keys().forEach(o=>{const n=this.dcupl.modelParser.models.get(o);if(!n)return;const i=n?.getBasicProperties()||[],a=n?.getBasicReferences()||[],l=i.length+a.length;t+=l;const u=n.data?.size||0;e+=u,s+=l*u}),this.values.counts.rows=e,this.values.counts.attributes=t,this.values.counts.dataEntries=s}calculateTiming(){const e=this.dcupl.analyticsController.getByName("loader_processed");e&&e[0]&&(this.values.loading=e[0].value);const t=this.dcupl.analyticsController.getByName("dcupl_initialized");t&&t[0]&&(this.values.processing=t[0].value),this.values.startup=this.values.loading+this.values.processing}calculateSizes(){const e=this.calculateSizesForModels();this.values.sizes={},this.values.sizes.totalEncoded=e.reduce((t,s)=>t+s.encodedBodySize,0),this.values.sizes.totalDecoded=e.reduce((t,s)=>t+s.decodedBodySize,0),this.values.sizes.unusedDecoded=this.calculateUnusedData(),this.values.sizes.models=e.map(t=>({model:t.model,decodedBodySize:t.decodedBodySize,encodedBodySize:t.encodedBodySize})),this.values.sizes.models?.sort((t,s)=>(s.encodedBodySize||0)-(t.encodedBodySize||0))}calculateErrorTrackingFacet(){try{if(!this.enabled)return;const e=new Map;let t=0;for(const s of this.errorCounts.values())e.set(s.errorType,(e.get(s.errorType)??0)+s.count),t+=s.count;this.values.errors={size:t,UndefinedValue:e.get("UndefinedValue")??0,UndefinedAttribute:e.get("UndefinedAttribute")??0,WrongDataType:e.get("WrongDataType")??0,MissingModel:e.get("MissingModel")??0,InvalidModelDescription:e.get("InvalidModelDescription")??0,RemoteReferenceKeyNotFound:e.get("RemoteReferenceKeyNotFound")??0}}catch(e){this.log.error("Error calculating error tracking facet",e)}}calculateSizesForModels(){const e=this.dcupl.analyticsController.getByType("resource").filter(s=>s.value?.type==="data"),t=jr(e,s=>s.value?.model);return Object.keys(t).map(s=>{const o=t[s]?.reduce((i,a)=>{const l=a.value.encodedBodySize;return i+l},0),n=t[s]?.reduce((i,a)=>{const l=a.value.decodedBodySize;return i+l},0);return{model:s,decodedBodySize:n,encodedBodySize:o}})}calculateUnusedData(){const e=this.dcupl.models.keys();let t=0;return e.forEach(s=>{const o=this.dcupl.modelParser.unprocessedData.find(a=>a.model===s)?.data||[],n=this.getUnusedAttributesFromModel(this.dcupl,s);if(!n.length)return;const i=this.getDataWithAttributes(o,n);t+=JSON.stringify(i).length}),t}getDataWithAttributes(e,t){return e.map(s=>{const o={};return t.forEach(n=>{o[n]=s[n]}),o})}getUnusedAttributesFromModel(e,t){const s=e.modelParser.models.get(t),o=s?.getBasicProperties()||[],n=s?.getBasicReferences()||[],i=s?.keyProperty,a=[...o,...n].map(u=>u.key);typeof i=="string"?a.push(i):Array.isArray(i)?a.push(...i):a.push("key"),a.push("key");const l=e.modelParser.unprocessedData.find(u=>u.model===t)?.data||[];return this.getUnusedAttributes(l,a)}getUnusedAttributes(e,t){const s=new Set;return e.forEach(o=>{Object.keys(o).forEach(n=>{t.includes(n)||s.add(n)})}),Array.from(s.values())}validateAttribute(e,t,s){const o=[];if(t.email){const n=this.validateEmail(e,s);n&&o.push(n)}if(t.endsWith){const n=this.validateEndsWith(e,t.endsWith,s);n&&o.push(n)}if(t.enum){const n=this.validateEnum(e,t.enum,s);n&&o.push(n)}if(t.includes){const n=this.validateIncludes(e,t.includes,s);n&&o.push(n)}if(t.max){const n=this.validateMax(e,t.max,s);n&&o.push(n)}if(t.maxLength){const n=this.validateMaxLength(e,t.maxLength,s);n&&o.push(n)}if(t.min){const n=this.validateMin(e,t.min,s);n&&o.push(n)}if(t.minLength){const n=this.validateMinLength(e,t.minLength,s);n&&o.push(n)}if(t.pattern){const n=this.validatePattern(e,t.pattern,s);n&&o.push(n)}if(t.startsWith){const n=this.validateStartsWith(e,t.startsWith,s);n&&o.push(n)}return o}validateAttributesAfterInitialization(e){if(!e)return[];const t=e.getAttributes(),s=e.getDataAsArray(),o=[];for(const n of t){const i=n.quality?.validators;if(i&&i.unique){const a=this.validateUnique(s,n.key,e);o.push(...a)}}return o}validateUnique(e,t,s){const o=[],n=new Set,i=s.attributeQualityConfigs?.get(t)?.validatorHandling!=="loose";for(const a of e){const l=a[t];if(n.has(l)){const u={title:"Validator Error - Unique",type:"model",errorGroup:"PropertyDataError",model:s.key,errorType:"InvalidValidator",attribute:t,itemKey:a.key,description:`The value "${l}" is not unique`};o.push(u),i&&delete a[t]}else n.add(l)}return o}validateEmail(e,t){if(e!=null&&!/^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,6}$/.test(e))return{title:"Validator Error - Invalid Email",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:t,description:`The value "${e}" is not a valid email address`}}validateMin(e,t,s){if(e<t.value)return{title:"Validator Error - Min Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is smaller than the minimum value of "${t.value}"`}}validateMax(e,t,s){if(e>t.value)return{title:"Validator Error - Max Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is larger than the maximum value of "${t.value}"`}}validateStartsWith(e,t,s){if(e!=null&&!e.startsWith(t.value))return{title:"Validator Error - StartsWith",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not start with "${t.value}"`}}validateEndsWith(e,t,s){if(e!=null&&!zp(e,t.value))return{title:"Validator Error - EndsWith",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not end with "${t.value}"`}}validateIncludes(e,t,s){if(e!=null&&!Jp(e,t.value))return{title:"Validator Error - Includes",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not include "${t.value}"`}}validateMinLength(e,t,s){if(e!=null&&e.length<t.value)return{title:"Validator Error - Min Length",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is shorter than the minimum length of "${t.value}"`}}validateMaxLength(e,t,s){if(e!=null&&e.length>t.value)return{title:"Validator Error - Max Length",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is longer than the maximum length of "${t.value}"`}}validateEnum(e,t,s){if(!t.value.includes(e))return{title:"Validator Error - Enum",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is not in the enum values`}}validatePattern(e,t,s){if(e!=null)try{if(!new RegExp(t.value).test(e))return{title:"Validator Error - Pattern",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not match the pattern "${t.value}"`}}catch(o){this.log.error("Invalid pattern validation",o)}}};var sh=Object.defineProperty,oh=Object.getOwnPropertyDescriptor,G=(r,e,t,s)=>{for(var o=oh(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&sh(e,t,o),o};class Q{cdRef=new $r;analyticsController=new gf;containerSourceMetadata=new WeakMap;scriptController=new Zf;qualityController=new rh(this.scriptController);log=Te.child({prefix:"Dcupl"});modelParser=new lt(this.cdRef,this.qualityController,this);globalItemService=new Go(this.modelParser,this.scriptController);queryManager=new Jf(this.scriptController,this.globalItemService,this.modelParser);_loaders=new Map;rootQueryBuilder=new ke;_defaultInitOptions={config:{projectId:void 0,apiKey:void 0,version:"draft"},errorTracking:{enabled:!1},quality:{enabled:!0},analytics:{enabled:!1},performance:{cache:{enabled:!0},clone:{enabled:!0},partialUpdates:{modelRatioThreshold:.5,itemRatioThreshold:.5,enableDetailedLogging:!1},autoUpdateLists:{enabled:!1}},referenceMetadata:{enabled:!1}};initOptions;lists=new Jo(this,this.cdRef);busy=!1;updateQueue=[];constructor(e){this.analyticsController.init(!!e?.analytics?.enabled),this.qualityController.dcupl=this,this.analyticsController.mark({name:"dcupl:constructor"}),this.initOptions=Mr({},this._defaultInitOptions,e),this.qualityController.enabled=this.initOptions.errorTracking?.enabled||this.initOptions.quality?.enabled||!1,this.qualityController.maxErrorsPerGroup=this.initOptions.quality?.maxErrorsPerGroup??1e3,this.modelParser.initOptions=Object.assign({},this.initOptions),this.cdRef._init({cdRefKey:"root",dcuplInitOptions:this.initOptions,analyticsController:this.analyticsController})}models={get:e=>this.modelParser.models.get(e)?.getModelDefinition(),set:e=>(this.modelParser.models.delete(e.key),this.modelParser.addModel(e)),update:e=>this.modelParser.addModel(e),remove:e=>{this.modelParser.models.delete(e)},keys:()=>this.modelParser._getModelKeys()};quality={errors:{summary:()=>this.qualityController.getErrorSummary()}};views={get:e=>this.modelParser.views.get(e),keys:e=>this.modelParser._getViewKeys(e),set:e=>this.modelParser.addView(e)};data={update:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"update",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},upsert:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"upsert",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},set:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"set",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},remove:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"remove",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},reset:e=>{e.model&&this.modelParser.addData({data:[],model:e.model,type:"set"})},apply:e=>this.modelParser.addData(e)};loaders={add:(e,t)=>{this.addLoader(e,t)},remove:e=>{this.removeLoader(e)},get:e=>this._loaders.get(e)};scripts={set:(e,t)=>{this.scriptController.setScript(e,t)},remove:e=>{this.scriptController.removeScript(e)},get:e=>{this.scriptController.getScript(e)},keys:()=>this.scriptController.keys(),execute:(e,t)=>{const s={dcupl:this,options:t};return this.scriptController.executeScript(e,"script",s)},executeAsync:(e,t)=>new Promise((s,o)=>{const n={dcupl:this,options:t,resolve:s,reject:o};return this.scriptController.executeScript(e,"async_script",n)})};fn={pivot:e=>this._pivot(e),aggregate:e=>this._aggregate(e),suggest:e=>this._suggest(e),groupBy:e=>this._groupBy(e),facets:e=>this._facets(e),metadata:e=>this._metadata(e)};_pivot(e){return this.getFnList(e).catalog.fn.pivot(e.options)}_aggregate(e){return this.getFnList(e).catalog.fn.aggregate(e.options)}_suggest(e){return this.getFnList(e).catalog.fn.suggest(e.options)}_groupBy(e){return this.getFnList(e).catalog.fn.groupBy(e.options)}_facets(e){return this.getFnList(e).catalog.fn.facets(e.options)}_metadata(e){return this.getFnList(e).catalog.fn.metadata()}registerContainer(e){this.modelParser.addData(e)}updateRegisteredContainer(e,t){const s=this.modelParser.unprocessedData.findIndex(o=>o.placeholderUid===e.placeholderUid);s>-1&&(delete e.placeholderUid,e.type||(e.type="set"),this.modelParser.unprocessedData[s]=e,this.modelParser.changeTracker.recordDataChange(e),t&&this.containerSourceMetadata.set(e,t))}removeRegisteredContainer(e){const t=this.modelParser.unprocessedData.findIndex(s=>s.placeholderUid===e.placeholderUid);t>-1&&this.modelParser.unprocessedData.splice(t,1)}getContainerSourceMetadata(e){return this.containerSourceMetadata.get(e)}setContainerSourceMetadata(e,t){this.containerSourceMetadata.set(e,t)}getFnList(e){let t=this.lists.get(`__global_list__${e.modelKey}`);return t||(t=this.lists.create({modelKey:e.modelKey,listKey:`__global_list__${e.modelKey}`})),e.query?t.catalog.query.apply(e.query,{mode:"set"}):t.catalog.query.reset(),t}snapshotChangedAttributes(){const e=this.modelParser.changeTracker;if(!e.hasChanges())return null;const t=e.getChangedAttributes(),s=new Map;for(const o of e.getEffectivelyChangedModels()){const n=new Set(t.get(o)??[]);if(n.size===0){const i=this.modelParser.models.get(o);for(const a of i?.properties.keys()??[])n.add(a);for(const a of i?.references.keys()??[])n.add(a)}s.set(o,n)}return s}getAffectedModels(e){const t=new Set(e.keys()),s=this.modelParser.dependencyGraph;if(s)for(const n of s.getImpactedNodes(Array.from(e.keys()),"downstream"))t.add(n);const o=this.modelParser.attributeDependencyGraph;if(o){const n=[];for(const[i,a]of e)for(const l of a)n.push({modelKey:i,attributeKey:l,type:"property",processingStep:1});for(const i of o.getImpactedAttributes(n))t.add(i.modelKey)}return Array.from(t)}updateFnLists(e,t){const s=this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1,o=[],n=e?new Set(e.affectedModels):null;for(const i of this.lists.getAll()){if(n&&!this.isListAffectedByChanges(i,n)){s&&this.log.debug("List skipped (not affected)",{listKey:i.key,modelKey:i.modelKey});continue}try{this.shouldAutoUpdateList(i,t)?(s&&this.log.debug("List auto-updating",{listKey:i.key,modelKey:i.modelKey,affectedModels:e?.affectedModels??"all"}),i.update()):(s&&this.log.debug("List caches invalidated (auto-update disabled)",{listKey:i.key,modelKey:i.modelKey}),i.invalidate()),o.push(i)}catch(a){this.log.error(`List refresh failed for '${i.key}'`,a)}}for(const i of o)if(!i.key.startsWith("__global_list__"))try{i.emitResultUpdated()}catch(a){this.log.error(`result_updated handler failed for list '${i.key}'`,a)}}isListAffectedByChanges(e,t){if(t.has(e.modelKey))return!0;for(const s of e.getDependencyModels())if(t.has(s))return!0;return!1}shouldAutoUpdateList(e,t){return e.key.startsWith("__global_list__")?!0:t!==void 0?t:e.options.autoUpdate!==void 0?e.options.autoUpdate:this.initOptions.performance?.autoUpdateLists?.enabled??!1}query={one:e=>this.getItem(e),many:e=>this._getManyItems(e),execute:e=>this.executeQuery(e),generate:(e,t)=>(this.rootQueryBuilder.init({modelKey:e}),this.rootQueryBuilder.applyQuery(t)),registerCustomOperator:(e,t)=>{this.queryManager.registerCustomOperator(e,t)}};on(e){return this.cdRef.on(e)}async init(){try{return await this.performUpdate(()=>this.modelParser.init()),this.updateFnLists(null),!0}catch(e){return this.log.error("Initialization failed",e),!1}}async update(e){try{const t=await this.performUpdate(async()=>{const s=this.snapshotChangedAttributes();return await this.modelParser.update(),s});if(t){const s={isPartialUpdate:!0,changedModels:Array.from(t.keys()),changedAttributes:t,affectedModels:this.getAffectedModels(t)};this.updateFnLists(s,e?.autoUpdateLists),this.cdRef.trigger({scope:"global",type:"dcupl_partial_update",args:[s]})}else this.updateFnLists(null,e?.autoUpdateLists);return!0}catch(t){return this.log.error("Update failed",t),!1}}destroy(){try{this.lists.destroy(),this._loaders.forEach(e=>{e.destroy()})}catch{}}getItem(e){const t=this.modelParser.models.get(e.modelKey);if(!t)throw new Error;return this.globalItemService.getItem(e.itemKey,t.data,t,e)}_getManyItems(e){const t=this.modelParser.models.get(e.modelKey);if(!t)throw new Error;return this.globalItemService.getManyItems(e.itemKeys,t.data,t,e)}executeQuery(e){if(!e?.modelKey)throw new Error("No modelKey provided");return this.getFnList({modelKey:e?.modelKey}).catalog.query.execute(e)}addLoader(e,t){const s=ce.now(),o=t||W();this._loaders.set(o,e),e.core=this,e.key=o;const n=new $r;n._init({cdRefKey:o,parentCd:this.cdRef,dcuplInitOptions:this.initOptions,analyticsController:this.analyticsController}),e.cdRef=n,this.initOptions.config?.projectId&&e.defaultVariables.set("projectId",{key:"projectId",value:this.initOptions.config?.projectId}),this.initOptions.config?.apiKey&&e.defaultVariables.set("apiKey",{key:"apiKey",value:this.initOptions.config?.apiKey}),this.initOptions.config?.version&&e.defaultVariables.set("version",{key:"version",value:this.initOptions.config?.version}),this.cdRef.trigger({scope:"global",type:"loader_added",connectMessage:!0,args:[o],start:s})}removeLoader(e){const t=this._loaders.get(e);t&&t.destroy(),this._loaders.delete(e)}performUpdate(e){return new Promise((t,s)=>{this.updateQueue.push(async()=>{try{t(await e())}catch(o){s(o)}}),this.busy||this.processQueue()})}async processQueue(){this.busy=!0;try{for(;this.updateQueue.length>0;)await this.updateQueue.shift()()}finally{this.busy=!1}}}G([b({scope:"global",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_pivot"),G([b({scope:"global",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_aggregate"),G([b({scope:"global",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_suggest"),G([b({scope:"global",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_groupBy"),G([b({scope:"global",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_facets"),G([b({scope:"global",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_metadata"),G([b({scope:"global",type:"dcupl_initialized",connectMessage:!0})],Q.prototype,"init"),G([b({scope:"global",type:"dcupl_updated_manually",action:"update",connectMessage:!0})],Q.prototype,"update"),G([b({scope:"global",type:"dcupl_destroyed",connectMessage:!0})],Q.prototype,"destroy"),G([b({scope:"global",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"getItem"),G([b({scope:"global",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_getManyItems"),G([b({scope:"global",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"executeQuery"),G([b({scope:"global",type:"loader_removed",connectMessage:!0})],Q.prototype,"removeLoader");let nh=class extends Q{version="2.0.0-beta.6";constructor(e){super(e)}};var Zo=typeof global=="object"&&global&&global.Object===Object&&global,ih=typeof self=="object"&&self&&self.Object===Object&&self,Y=Zo||ih||Function("return this")(),fe=Y.Symbol,Yo=Object.prototype,ah=Yo.hasOwnProperty,lh=Yo.toString,ut=fe?fe.toStringTag:void 0;function uh(r){var e=ah.call(r,ut),t=r[ut];try{r[ut]=void 0;var s=!0}catch{}var o=lh.call(r);return s&&(e?r[ut]=t:delete r[ut]),o}var ch=Object.prototype,dh=ch.toString;function fh(r){return dh.call(r)}var ph="[object Null]",hh="[object Undefined]",Xo=fe?fe.toStringTag:void 0;function Fe(r){return r==null?r===void 0?hh:ph:Xo&&Xo in Object(r)?uh(r):fh(r)}function qe(r){return r!=null&&typeof r=="object"}var yh="[object Symbol]";function Tr(r){return typeof r=="symbol"||qe(r)&&Fe(r)==yh}function gh(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var Qe=Array.isArray,en=fe?fe.prototype:void 0,tn=en?en.toString:void 0;function rn(r){if(typeof r=="string")return r;if(Qe(r))return gh(r,rn)+"";if(Tr(r))return tn?tn.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function It(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var mh="[object AsyncFunction]",vh="[object Function]",bh="[object GeneratorFunction]",kh="[object Proxy]";function sn(r){if(!It(r))return!1;var e=Fe(r);return e==vh||e==bh||e==mh||e==kh}var Or=Y["__core-js_shared__"],on=(function(){var r=/[^.]+$/.exec(Or&&Or.keys&&Or.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function wh(r){return!!on&&on in r}var Ah=Function.prototype,$h=Ah.toString;function Ae(r){if(r!=null){try{return $h.call(r)}catch{}try{return r+""}catch{}}return""}var Ch=/[\\^$.*+?()[\]{}|]/g,Dh=/^\[object .+?Constructor\]$/,_h=Function.prototype,Ph=Object.prototype,xh=_h.toString,Eh=Ph.hasOwnProperty,jh=RegExp("^"+xh.call(Eh).replace(Ch,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Mh(r){if(!It(r)||wh(r))return!1;var e=sn(r)?jh:Dh;return e.test(Ae(r))}function Sh(r,e){return r?.[e]}function $e(r,e){var t=Sh(r,e);return Mh(t)?t:void 0}var Kr=$e(Y,"WeakMap"),nn=Object.create,Rh=(function(){function r(){}return function(e){if(!It(e))return{};if(nn)return nn(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})(),an=(function(){try{var r=$e(Object,"defineProperty");return r({},"",{}),r}catch{}})();function Ih(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}var Th=9007199254740991,Oh=/^(?:0|[1-9]\d*)$/;function Kh(r,e){var t=typeof r;return e=e??Th,!!e&&(t=="number"||t!="symbol"&&Oh.test(r))&&r>-1&&r%1==0&&r<e}function Fh(r,e,t){e=="__proto__"&&an?an(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function ln(r,e){return r===e||r!==r&&e!==e}var qh=Object.prototype,Qh=qh.hasOwnProperty;function Vh(r,e,t){var s=r[e];(!(Qh.call(r,e)&&ln(s,t))||t===void 0&&!(e in r))&&Fh(r,e,t)}var Gh=9007199254740991;function un(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Gh}function Bh(r){return r!=null&&un(r.length)&&!sn(r)}var Uh=Object.prototype;function cn(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Uh;return r===t}function Nh(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var zh="[object Arguments]";function dn(r){return qe(r)&&Fe(r)==zh}var fn=Object.prototype,Lh=fn.hasOwnProperty,Wh=fn.propertyIsEnumerable,Hh=dn((function(){return arguments})())?dn:function(r){return qe(r)&&Lh.call(r,"callee")&&!Wh.call(r,"callee")};function Jh(){return!1}var pn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hn=pn&&typeof module=="object"&&module&&!module.nodeType&&module,Zh=hn&&hn.exports===pn,yn=Zh?Y.Buffer:void 0,Yh=yn?yn.isBuffer:void 0,gn=Yh||Jh,Xh="[object Arguments]",ey="[object Array]",ty="[object Boolean]",ry="[object Date]",sy="[object Error]",oy="[object Function]",ny="[object Map]",iy="[object Number]",ay="[object Object]",ly="[object RegExp]",uy="[object Set]",cy="[object String]",dy="[object WeakMap]",fy="[object ArrayBuffer]",py="[object DataView]",hy="[object Float32Array]",yy="[object Float64Array]",gy="[object Int8Array]",my="[object Int16Array]",vy="[object Int32Array]",by="[object Uint8Array]",ky="[object Uint8ClampedArray]",wy="[object Uint16Array]",Ay="[object Uint32Array]",D={};D[hy]=D[yy]=D[gy]=D[my]=D[vy]=D[by]=D[ky]=D[wy]=D[Ay]=!0,D[Xh]=D[ey]=D[fy]=D[ty]=D[py]=D[ry]=D[sy]=D[oy]=D[ny]=D[iy]=D[ay]=D[ly]=D[uy]=D[cy]=D[dy]=!1;function $y(r){return qe(r)&&un(r.length)&&!!D[Fe(r)]}function Fr(r){return function(e){return r(e)}}var mn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ct=mn&&typeof module=="object"&&module&&!module.nodeType&&module,Cy=ct&&ct.exports===mn,qr=Cy&&Zo.process,Ve=(function(){try{var r=ct&&ct.require&&ct.require("util").types;return r||qr&&qr.binding&&qr.binding("util")}catch{}})(),vn=Ve&&Ve.isTypedArray,Dy=vn?Fr(vn):$y,_y=Object.prototype,Py=_y.hasOwnProperty;function xy(r,e){var t=Qe(r),s=!t&&Hh(r),o=!t&&!s&&gn(r),n=!t&&!s&&!o&&Dy(r),i=t||s||o||n,a=i?Nh(r.length,String):[],l=a.length;for(var u in r)Py.call(r,u)&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||n&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Kh(u,l)))&&a.push(u);return a}function bn(r,e){return function(t){return r(e(t))}}var Ey=bn(Object.keys,Object),jy=Object.prototype,My=jy.hasOwnProperty;function Sy(r){if(!cn(r))return Ey(r);var e=[];for(var t in Object(r))My.call(r,t)&&t!="constructor"&&e.push(t);return e}function Ry(r){return Bh(r)?xy(r):Sy(r)}var Iy=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ty=/^\w*$/;function Oy(r,e){if(Qe(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Tr(r)?!0:Ty.test(r)||!Iy.test(r)||e!=null&&r in Object(e)}var dt=$e(Object,"create");function Ky(){this.__data__=dt?dt(null):{},this.size=0}function Fy(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var qy="__lodash_hash_undefined__",Qy=Object.prototype,Vy=Qy.hasOwnProperty;function Gy(r){var e=this.__data__;if(dt){var t=e[r];return t===qy?void 0:t}return Vy.call(e,r)?e[r]:void 0}var By=Object.prototype,Uy=By.hasOwnProperty;function Ny(r){var e=this.__data__;return dt?e[r]!==void 0:Uy.call(e,r)}var zy="__lodash_hash_undefined__";function Ly(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=dt&&e===void 0?zy:e,this}function Ce(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}Ce.prototype.clear=Ky,Ce.prototype.delete=Fy,Ce.prototype.get=Gy,Ce.prototype.has=Ny,Ce.prototype.set=Ly;function Wy(){this.__data__=[],this.size=0}function Tt(r,e){for(var t=r.length;t--;)if(ln(r[t][0],e))return t;return-1}var Hy=Array.prototype,Jy=Hy.splice;function Zy(r){var e=this.__data__,t=Tt(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Jy.call(e,t,1),--this.size,!0}function Yy(r){var e=this.__data__,t=Tt(e,r);return t<0?void 0:e[t][1]}function Xy(r){return Tt(this.__data__,r)>-1}function eg(r,e){var t=this.__data__,s=Tt(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function ne(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ne.prototype.clear=Wy,ne.prototype.delete=Zy,ne.prototype.get=Yy,ne.prototype.has=Xy,ne.prototype.set=eg;var ft=$e(Y,"Map");function tg(){this.size=0,this.__data__={hash:new Ce,map:new(ft||ne),string:new Ce}}function rg(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Ot(r,e){var t=r.__data__;return rg(e)?t[typeof e=="string"?"string":"hash"]:t.map}function sg(r){var e=Ot(this,r).delete(r);return this.size-=e?1:0,e}function og(r){return Ot(this,r).get(r)}function ng(r){return Ot(this,r).has(r)}function ig(r,e){var t=Ot(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function pe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}pe.prototype.clear=tg,pe.prototype.delete=sg,pe.prototype.get=og,pe.prototype.has=ng,pe.prototype.set=ig;var ag="Expected a function";function Qr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(ag);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(Qr.Cache||pe),t}Qr.Cache=pe;var lg=500;function ug(r){var e=Qr(r,function(s){return t.size===lg&&t.clear(),s}),t=e.cache;return e}var cg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,dg=/\\(\\)?/g,fg=ug(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(cg,function(t,s,o,n){e.push(o?n.replace(dg,"$1"):s||t)}),e});function pg(r){return r==null?"":rn(r)}function hg(r,e){return Qe(r)?r:Oy(r,e)?[r]:fg(pg(r))}function yg(r){if(typeof r=="string"||Tr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function gg(r,e){e=hg(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[yg(e[t++])];return t&&t==s?r:void 0}function mg(r,e,t){var s=r==null?void 0:gg(r,e);return s===void 0?t:s}function vg(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var bg=bn(Object.getPrototypeOf,Object);function kg(){this.__data__=new ne,this.size=0}function wg(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Ag(r){return this.__data__.get(r)}function $g(r){return this.__data__.has(r)}var Cg=200;function Dg(r,e){var t=this.__data__;if(t instanceof ne){var s=t.__data__;if(!ft||s.length<Cg-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new pe(s)}return t.set(r,e),this.size=t.size,this}function Ge(r){var e=this.__data__=new ne(r);this.size=e.size}Ge.prototype.clear=kg,Ge.prototype.delete=wg,Ge.prototype.get=Ag,Ge.prototype.has=$g,Ge.prototype.set=Dg;var kn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,wn=kn&&typeof module=="object"&&module&&!module.nodeType&&module,_g=wn&&wn.exports===kn,An=_g?Y.Buffer:void 0;An&&An.allocUnsafe;function Pg(r,e){return r.slice()}function xg(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function Eg(){return[]}var jg=Object.prototype,Mg=jg.propertyIsEnumerable,$n=Object.getOwnPropertySymbols,Sg=$n?function(r){return r==null?[]:(r=Object(r),xg($n(r),function(e){return Mg.call(r,e)}))}:Eg;function Rg(r,e,t){var s=e(r);return Qe(r)?s:vg(s,t(r))}function Ig(r){return Rg(r,Ry,Sg)}var Vr=$e(Y,"DataView"),Gr=$e(Y,"Promise"),Br=$e(Y,"Set"),Cn="[object Map]",Tg="[object Object]",Dn="[object Promise]",_n="[object Set]",Pn="[object WeakMap]",xn="[object DataView]",Og=Ae(Vr),Kg=Ae(ft),Fg=Ae(Gr),qg=Ae(Br),Qg=Ae(Kr),ie=Fe;(Vr&&ie(new Vr(new ArrayBuffer(1)))!=xn||ft&&ie(new ft)!=Cn||Gr&&ie(Gr.resolve())!=Dn||Br&&ie(new Br)!=_n||Kr&&ie(new Kr)!=Pn)&&(ie=function(r){var e=Fe(r),t=e==Tg?r.constructor:void 0,s=t?Ae(t):"";if(s)switch(s){case Og:return xn;case Kg:return Cn;case Fg:return Dn;case qg:return _n;case Qg:return Pn}return e});var Vg=Object.prototype,Gg=Vg.hasOwnProperty;function Bg(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Gg.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var En=Y.Uint8Array;function Ur(r){var e=new r.constructor(r.byteLength);return new En(e).set(new En(r)),e}function Ug(r,e){var t=Ur(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Ng=/\w*$/;function zg(r){var e=new r.constructor(r.source,Ng.exec(r));return e.lastIndex=r.lastIndex,e}var jn=fe?fe.prototype:void 0,Mn=jn?jn.valueOf:void 0;function Lg(r){return Mn?Object(Mn.call(r)):{}}function Wg(r,e){var t=Ur(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var Hg="[object Boolean]",Jg="[object Date]",Zg="[object Map]",Yg="[object Number]",Xg="[object RegExp]",em="[object Set]",tm="[object String]",rm="[object Symbol]",sm="[object ArrayBuffer]",om="[object DataView]",nm="[object Float32Array]",im="[object Float64Array]",am="[object Int8Array]",lm="[object Int16Array]",um="[object Int32Array]",cm="[object Uint8Array]",dm="[object Uint8ClampedArray]",fm="[object Uint16Array]",pm="[object Uint32Array]";function hm(r,e,t){var s=r.constructor;switch(e){case sm:return Ur(r);case Hg:case Jg:return new s(+r);case om:return Ug(r);case nm:case im:case am:case lm:case um:case cm:case dm:case fm:case pm:return Wg(r);case Zg:return new s;case Yg:case tm:return new s(r);case Xg:return zg(r);case em:return new s;case rm:return Lg(r)}}function ym(r){return typeof r.constructor=="function"&&!cn(r)?Rh(bg(r)):{}}var gm="[object Map]";function mm(r){return qe(r)&&ie(r)==gm}var Sn=Ve&&Ve.isMap,vm=Sn?Fr(Sn):mm,bm="[object Set]";function km(r){return qe(r)&&ie(r)==bm}var Rn=Ve&&Ve.isSet,wm=Rn?Fr(Rn):km,In="[object Arguments]",Am="[object Array]",$m="[object Boolean]",Cm="[object Date]",Dm="[object Error]",Tn="[object Function]",_m="[object GeneratorFunction]",Pm="[object Map]",xm="[object Number]",On="[object Object]",Em="[object RegExp]",jm="[object Set]",Mm="[object String]",Sm="[object Symbol]",Rm="[object WeakMap]",Im="[object ArrayBuffer]",Tm="[object DataView]",Om="[object Float32Array]",Km="[object Float64Array]",Fm="[object Int8Array]",qm="[object Int16Array]",Qm="[object Int32Array]",Vm="[object Uint8Array]",Gm="[object Uint8ClampedArray]",Bm="[object Uint16Array]",Um="[object Uint32Array]",A={};A[In]=A[Am]=A[Im]=A[Tm]=A[$m]=A[Cm]=A[Om]=A[Km]=A[Fm]=A[qm]=A[Qm]=A[Pm]=A[xm]=A[On]=A[Em]=A[jm]=A[Mm]=A[Sm]=A[Vm]=A[Gm]=A[Bm]=A[Um]=!0,A[Dm]=A[Tn]=A[Rm]=!1;function Kt(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!It(r))return r;var a=Qe(r);if(a)i=Bg(r);else{var l=ie(r),u=l==Tn||l==_m;if(gn(r))return Pg(r);if(l==On||l==In||u&&!o)i=u?{}:ym(r);else{if(!A[l])return o?r:{};i=hm(r,l)}}n||(n=new Ge);var c=n.get(r);if(c)return c;n.set(r,i),wm(r)?r.forEach(function(h){i.add(Kt(h,e,t,h,r,n))}):vm(r)&&r.forEach(function(h,p){i.set(p,Kt(h,e,t,p,r,n))});var d=Ig,f=a?void 0:d(r);return Ih(f||r,function(h,p){f&&(p=h,h=r[p]),Vh(i,p,Kt(h,e,t,p,r,n))}),i}var Nm=1,zm=4;function Lm(r){return Kt(r,Nm|zm)}function Wm(r){const e=Nr(r);return Hm(e)}function Nr(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(Nr).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+Nr(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function Hm(r){let e=0;for(let t=0;t<r.length;t++){const s=r.charCodeAt(t);e=(e<<5)-e+s,e|=0}return e.toString(16)}const F={now:()=>typeof performance<"u"&&performance.now?performance.now():new Date().getTime(),mark:r=>{typeof performance<"u"&&performance.mark&&performance.mark(r)},measure:(r,e,t)=>{typeof performance<"u"&&performance.measure&&performance.measure(r,e,t)},getEntriesByName(r){if(typeof performance<"u"&&performance.getEntriesByName)return performance.getEntriesByName(r)},getEntriesByType(r){if(typeof performance<"u"&&performance.getEntriesByType)return performance.getEntriesByType(r)}},Kn={silent:0,error:1,warn:2,info:3,debug:4};class M{config;static globalConfig={};constructor(e={}){this.config={level:e.level??M.globalConfig.level??this.getDefaultLevel(),format:e.format??M.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??M.globalConfig.onLog,onTrackError:e.onTrackError??M.globalConfig.onTrackError}}static setGlobalConfig(e){M.globalConfig={...M.globalConfig,...e}}static getGlobalConfig(){return{...M.globalConfig}}static setModuleLevel(e,t){M.globalConfig.onLog||(M.globalConfig.onLog=void 0),M._moduleOverrides||(M._moduleOverrides=new Map),M._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!M._moduleOverrides))return M._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=M.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return Kn[e]<=Kn[t]}formatMessage(e){if(this.config.format==="json"){const i={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(i.module=e.prefix),e.context&&(i.context=e.context),e.error&&(i.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(i)}const t=new Date(e.timestamp).toISOString().substring(11,23),s=e.prefix?`[${e.prefix}]`:"",o=this.getLevelIcon(e.level),n=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${o} ${s} ${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,s,o){if(!this.shouldLog(e))return;const n={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:s,error:o};if(this.config.onLog){this.config.onLog(n);return}const i=this.formatMessage(n);if(typeof console<"u")switch(e){case"error":o?console.error(i,o):console.error(i);break;case"warn":console.warn(i);break;case"debug":console.debug?console.debug(i):console.log(i);break;default:console.log(i)}}error(e,t,s){const o=t instanceof Error?t:void 0,n=t instanceof Error?s:t;this.log("error",e,n,o)}trackError(e,t,s){if(this.error(e,t,s?.context),this.config.onTrackError){const o={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:s?.context,error:t,errorType:s?.errorType,errorGroup:s?.errorGroup};this.config.onTrackError(o)}}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 M(t)}configure(e){Object.assign(this.config,e)}}const zr=new M;function Lr(r=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let s=0;s<r;s++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}let Jm=class{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=F.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 Fn=(r,e)=>e?typeof structuredClone<"u"?structuredClone(r):Lm(r):r,qn=(r,e,t,s,o,n)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=Fn(n,i);if(t.scope==="list"&&(t.listKey=r.cdRef?.key||r.key,t.modelKey=r.model?.key||r.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const l=F.now(),u=l-s,c=Math.round(u*1e3)/1e3;t.duration=c,t.start=s,t.end=l;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:o}),e.analyticsController.measure({name:t.type,start:`${t.type}:start`,end:`${t.type}:end`,context:o,detail:d}),a}catch{return n}},Qn=r=>(e,t,s)=>{const o=s.value;return s.value=function(...n){const i=F.now(),a=this.cdRef,l=Fn(r,!0);l.key||(a.increaseCounter(),l.key=a.getCounter());const u=Lr();a.analyticsController.mark({name:`${l.type}:start`,context:u});const c=this.model?.key;!l.originCdRefKey&&a.key&&(l.originCdRefKey=a.key),c&&(l.modelKey=c);const d=o.apply(this,n);return l.method=t,l.args=n,d&&typeof d=="object"&&"then"in d?d.then(f=>qn(this,a,l,i,u,f)):qn(this,a,l,i,u,d)},s},Zm=new Set(["apikey","api-key","managerkey","token","proxy-key","proxykey","manager-key","sdk-key"]);function Be(r){const e=r.indexOf("?");if(e<0)return r;const t=r.slice(e+1).split("&").map(s=>{const o=s.indexOf("=");if(o<0)return s;const n=s.slice(0,o);return Zm.has(n.toLowerCase())?`${n}=<redacted>`:s}).join("&");return`${r.slice(0,e)}?${t}`}const Ym="k:",Xm="h:";function Wr(r,e=0){if(r.key)return`${Ym}${r.key}`;const t=Wm({type:r.type,url:r.rawUrl??r.url,model:r.model??"",occurrence:e});return`${Xm}${t}`}function ev(r){const e=new Map,t=new Set;return r.map(s=>{const o=`${s.key??""}|${s.type}|${s.rawUrl??s.url}|${s.model??""}`;let n=e.get(o)??0,i=Wr(s,n);for(;t.has(i);)n+=1,i=s.key?`${Wr(s)}#${n}`:Wr(s,n);return e.set(o,n+1),t.add(i),i})}const Ft=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>mg(e,s.trim(),""))):"",tv=r=>{const e=new Set;return r.replace(/\$\{(.*?)\}/g,(t,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(t=>({name:t}))}};let rv=class{log=zr.child({prefix:"DcuplCsvParser"});parse(r,e={}){const{quoteChar:t=e.quoteChar||'"',escapeChar:s=e.escapeChar||'"',comments:o=e.comments||void 0,dynamicTyping:n=!1,header:i=!0,skipEmptyLines:a=!0,transformHeader:l,transform:u}=e,c=[],d=i?[]:null;let f=r.length,h=[],p="",y=!1,v=!0,g=0;if(a){for(;g<f&&(r[g]===`
|
|
9
|
+
`||r[g]==="\r"||r[g]===""||r[g]==="'"||r[g]==='"');)g++;r=r.slice(g),f=r.length,g=0}const k=e.delimiter||this.detectDelimiter(r);for(;g<f;g++){const m=r[g],S=r[g+1];if(o&&m===o&&!y&&p.length===0){for(;g<f&&r[g]!==`
|
|
10
10
|
`;)g++;continue}if(m===`
|
|
11
|
-
`||m==="\r"&&
|
|
12
|
-
`)if(y)p+=m;else{(p.length>0||!a)&&h.push(p),v&&d?h.forEach(N=>d.push(l?l(N):N)):d?c.push(this.buildObjectRow(d,h,n,u)):c.push([...h]),h=[],p="",v=!1,g+=m==="\r"&&
|
|
13
|
-
`?1:0;continue}else if(m===k&&!y)h.push(p),p="";else if(m===t)y?
|
|
11
|
+
`||m==="\r"&&S===`
|
|
12
|
+
`)if(y)p+=m;else{(p.length>0||!a)&&h.push(p),v&&d?h.forEach(N=>d.push(l?l(N):N)):d?c.push(this.buildObjectRow(d,h,n,u)):c.push([...h]),h=[],p="",v=!1,g+=m==="\r"&&S===`
|
|
13
|
+
`?1:0;continue}else if(m===k&&!y)h.push(p),p="";else if(m===t)y?S===s?(p+=t,g++):y=!1:p.length===0?y=!0:p+=m;else if((y||p.length===0)&&(m==="{"||m==="[")){const N=this.extractJson(r,g,k);p+=N.value,g+=N.length-1}else p+=m}return(p.length>0||!a)&&h.push(p),h.length&&(v&&d?h.forEach(m=>d.push(l?l(m):m)):d?c.push(this.buildObjectRow(d,h,n,u)):c.push([...h])),c}buildObjectRow(r,e,t,s){const o={};for(let n=0;n<r.length;n++){const i=r[n];let a=e[n];t&&(a=this.dynamicType(a)),o[i]=s?s(a,i):a}return o}detectDelimiter(r){const e=r.slice(0,r.indexOf(`
|
|
14
14
|
`)),t=[",",";"," ","|"],s=t.map(o=>{const n=new RegExp(`\\${o}`,"g");return(e.match(n)||[]).length});return t[s.indexOf(Math.max(...s))]||","}dynamicType(r){if(r==="true")return!0;if(r==="false")return!1;if(!isNaN(Number(r)))return Number(r);try{return JSON.parse(r)}catch{return r}}extractJson(r,e,t){const s=[];let o=e,n=!1,i="";for(;o<r.length;){const a=r[o];if(!n&&a===t)break;if(!n&&(a===`
|
|
15
|
-
`||a==="\r")){this.log.error("JSON block spans multiple lines",void 0,{startIndex:e,endIndex:o});break}if(a==='"'&&i!=="\\"&&(n=!n),n||(a==="{"||a==="["?s.push(a):(a==="}"&&s[s.length-1]==="{"||a==="]"&&s[s.length-1]==="[")&&s.pop()),o++,i=a,s.length===0&&!n)break}return{value:r.slice(e,o),length:o-e}}};function Vn(r,e=","){return r&&typeof r=="string"?r.split(e).map(t=>t.trim()):[]}class sv{loader;log=zr.child({prefix:"CsvParser"});constructor(e){this.loader=e}getParserConfig(e,t,s,o){const n=this.loader.config.get()?.options,i=this.loader.options,a=this.log,l={};typeof t?.csvParserOptions?.quoteChar<"u"?l.quoteChar=t?.csvParserOptions?.quoteChar:typeof n?.csvParserOptions?.quoteChar<"u"?l.quoteChar=n?.csvParserOptions?.quoteChar:l.quoteChar=i.csvParserOptions?.quoteChar,typeof t?.csvParserOptions?.delimiter<"u"?l.delimiter=t?.csvParserOptions?.delimiter:typeof n?.csvParserOptions?.delimiter<"u"?l.delimiter=n?.csvParserOptions?.delimiter:l.delimiter=i.csvParserOptions?.delimiter,typeof t?.csvParserOptions?.escapeChar<"u"?l.escapeChar=t?.csvParserOptions?.escapeChar:typeof n?.csvParserOptions?.escapeChar<"u"?l.escapeChar=n?.csvParserOptions?.escapeChar:l.escapeChar=i.csvParserOptions?.escapeChar,typeof t?.csvParserOptions?.commentChar<"u"?l.commentChar=t?.csvParserOptions?.commentChar:typeof n?.csvParserOptions?.commentChar<"u"?l.commentChar=n?.csvParserOptions?.commentChar:l.commentChar=i.csvParserOptions?.commentChar;const u=new Map,c=new Map;if(e.references)for(const p of e.references)u.set(p.key,p),p.origin&&u.set(p.origin,p);if(e.properties)for(const p of e.properties)c.set(p.key,p),p.origin&&c.set(p.origin,p);const d=t?.keyProperty??e.keyProperty??"key",f=Array.isArray(d)?d:[d],h=new Set(f);return{delimiter:l?.delimiter,quoteChar:l?.quoteChar,escapeChar:l?.escapeChar,comments:l.commentChar,dynamicTyping:!1,header:!0,skipEmptyLines:!0,transformHeader:p=>{const y=p?.trim().replace(/"/g,"");return s&&y&&s.push(y),y},transform:function(p,y){if(typeof y>"u"||h.has(y))return p;if(p==="null")return null;if(p===""||typeof p>"u")return;const v=m=>{if(!o)return;const M=o[y];M?M.count+=1:o[y]={rawValue:p,expected:m,count:1}},g=u.get(y);if(g)if(p[0]==="{"||p[0]==="[")try{return JSON.parse(p)}catch(m){a.error("Failed to parse JSON in CSV reference field",m,{header:y,value:p});return}else return g.type==="singleValued"?p:p?.length>0&&g.type==="multiValued"?Vn(p,g?.separator):p;const k=c.get(y);if(!(!e.autoGenerateProperties&&!k))switch(k?.type){case"string":return p;case"int":{const m=parseInt(p,10);if(isNaN(m)){v("int");return}return m}case"float":{const m=parseFloat(p);if(isNaN(m)){v("float");return}return m}case"boolean":if(p==="true")return!0;if(p==="false")return!1;v("boolean");return;case"json":try{return p=p.replace(/[\x00-\x1F\x7F-\x9F]/g,""),JSON.parse(p)}catch(m){a.error("Failed to parse JSON in CSV property field",m,{header:y,value:p}),v("json");return}case"Array<string>":case"Array<int>":case"Array<float>":case"Array<date>":if(p&&typeof p=="string"&&p[0]==="[")try{return JSON.parse(p)}catch{v(k.type);return}if(p&&typeof p=="string")return Vn(p,k?.separator);v(k.type);return;default:return p}}}}getJsonFromCSVString(e,t,s){return this.getJsonFromCSVStringWithMetadata(e,t,s).data}getJsonFromCSVStringWithMetadata(e,t,s){const o=[],n={},i=this.getParserConfig(t,s.options,o,n);return{data:new rv().parse(e,i),sourceColumns:o,coercionFailureSamples:n}}}var Gn=typeof global=="object"&&global&&global.Object===Object&&global,ov=typeof self=="object"&&self&&self.Object===Object&&self,X=Gn||ov||Function("return this")(),he=X.Symbol,Bn=Object.prototype,nv=Bn.hasOwnProperty,iv=Bn.toString,ht=he?he.toStringTag:void 0;function av(r){var e=nv.call(r,ht),t=r[ht];try{r[ht]=void 0;var s=!0}catch{}var o=iv.call(r);return s&&(e?r[ht]=t:delete r[ht]),o}var lv=Object.prototype,uv=lv.toString;function cv(r){return uv.call(r)}var dv="[object Null]",fv="[object Undefined]",Un=he?he.toStringTag:void 0;function Ue(r){return r==null?r===void 0?fv:dv:Un&&Un in Object(r)?av(r):cv(r)}function De(r){return r!=null&&typeof r=="object"}var pv="[object Symbol]";function Hr(r){return typeof r=="symbol"||De(r)&&Ue(r)==pv}function Nn(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var Ne=Array.isArray,zn=he?he.prototype:void 0,Ln=zn?zn.toString:void 0;function Wn(r){if(typeof r=="string")return r;if(Ne(r))return Nn(r,Wn)+"";if(Hr(r))return Ln?Ln.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Qt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}function Hn(r){return r}var hv="[object AsyncFunction]",yv="[object Function]",gv="[object GeneratorFunction]",mv="[object Proxy]";function Jn(r){if(!Qt(r))return!1;var e=Ue(r);return e==yv||e==gv||e==hv||e==mv}var Jr=X["__core-js_shared__"],Zn=(function(){var r=/[^.]+$/.exec(Jr&&Jr.keys&&Jr.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function vv(r){return!!Zn&&Zn in r}var bv=Function.prototype,kv=bv.toString;function _e(r){if(r!=null){try{return kv.call(r)}catch{}try{return r+""}catch{}}return""}var wv=/[\\^$.*+?()[\]{}|]/g,Av=/^\[object .+?Constructor\]$/,$v=Function.prototype,Cv=Object.prototype,Dv=$v.toString,_v=Cv.hasOwnProperty,Pv=RegExp("^"+Dv.call(_v).replace(wv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function xv(r){if(!Qt(r)||vv(r))return!1;var e=Jn(r)?Pv:Av;return e.test(_e(r))}function Ev(r,e){return r?.[e]}function Pe(r,e){var t=Ev(r,e);return xv(t)?t:void 0}var Zr=Pe(X,"WeakMap"),Yn=Object.create,jv=(function(){function r(){}return function(e){if(!Qt(e))return{};if(Yn)return Yn(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function Sv(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var Mv=800,Rv=16,Iv=Date.now;function Tv(r){var e=0,t=0;return function(){var s=Iv(),o=Rv-(s-t);if(t=s,o>0){if(++e>=Mv)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function Ov(r){return function(){return r}}var Vt=(function(){try{var r=Pe(Object,"defineProperty");return r({},"",{}),r}catch{}})(),Kv=Vt?function(r,e){return Vt(r,"toString",{configurable:!0,enumerable:!1,value:Ov(e),writable:!0})}:Hn,Fv=Tv(Kv);function qv(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function Qv(r,e,t,s){for(var o=r.length,n=t+-1;++n<o;)if(e(r[n],n,r))return n;return-1}function Vv(r){return r!==r}function Gv(r,e,t){for(var s=t-1,o=r.length;++s<o;)if(r[s]===e)return s;return-1}function Bv(r,e,t){return e===e?Gv(r,e,t):Qv(r,Vv,t)}function Uv(r,e){var t=r==null?0:r.length;return!!t&&Bv(r,e,0)>-1}var Nv=9007199254740991,zv=/^(?:0|[1-9]\d*)$/;function Lv(r,e){var t=typeof r;return e=e??Nv,!!e&&(t=="number"||t!="symbol"&&zv.test(r))&&r>-1&&r%1==0&&r<e}function Wv(r,e,t){e=="__proto__"&&Vt?Vt(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function Xn(r,e){return r===e||r!==r&&e!==e}var Hv=Object.prototype,Jv=Hv.hasOwnProperty;function Zv(r,e,t){var s=r[e];(!(Jv.call(r,e)&&Xn(s,t))||t===void 0&&!(e in r))&&Wv(r,e,t)}var ei=Math.max;function Yv(r,e,t){return e=ei(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=ei(s.length-e,0),i=Array(n);++o<n;)i[o]=s[e+o];o=-1;for(var a=Array(e+1);++o<e;)a[o]=s[o];return a[e]=t(i),Sv(r,this,a)}}function Xv(r,e){return Fv(Yv(r,e,Hn),r+"")}var eb=9007199254740991;function ti(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=eb}function ri(r){return r!=null&&ti(r.length)&&!Jn(r)}var tb=Object.prototype;function si(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||tb;return r===t}function rb(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var sb="[object Arguments]";function oi(r){return De(r)&&Ue(r)==sb}var ni=Object.prototype,ob=ni.hasOwnProperty,nb=ni.propertyIsEnumerable,ib=oi((function(){return arguments})())?oi:function(r){return De(r)&&ob.call(r,"callee")&&!nb.call(r,"callee")};function ab(){return!1}var ii=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ai=ii&&typeof module=="object"&&module&&!module.nodeType&&module,lb=ai&&ai.exports===ii,li=lb?X.Buffer:void 0,ub=li?li.isBuffer:void 0,ui=ub||ab,cb="[object Arguments]",db="[object Array]",fb="[object Boolean]",pb="[object Date]",hb="[object Error]",yb="[object Function]",gb="[object Map]",mb="[object Number]",vb="[object Object]",bb="[object RegExp]",kb="[object Set]",wb="[object String]",Ab="[object WeakMap]",$b="[object ArrayBuffer]",Cb="[object DataView]",Db="[object Float32Array]",_b="[object Float64Array]",Pb="[object Int8Array]",xb="[object Int16Array]",Eb="[object Int32Array]",jb="[object Uint8Array]",Sb="[object Uint8ClampedArray]",Mb="[object Uint16Array]",Rb="[object Uint32Array]",_={};_[Db]=_[_b]=_[Pb]=_[xb]=_[Eb]=_[jb]=_[Sb]=_[Mb]=_[Rb]=!0,_[cb]=_[db]=_[$b]=_[fb]=_[Cb]=_[pb]=_[hb]=_[yb]=_[gb]=_[mb]=_[vb]=_[bb]=_[kb]=_[wb]=_[Ab]=!1;function Ib(r){return De(r)&&ti(r.length)&&!!_[Ue(r)]}function Yr(r){return function(e){return r(e)}}var ci=typeof exports=="object"&&exports&&!exports.nodeType&&exports,yt=ci&&typeof module=="object"&&module&&!module.nodeType&&module,Tb=yt&&yt.exports===ci,Xr=Tb&&Gn.process,ze=(function(){try{var r=yt&&yt.require&&yt.require("util").types;return r||Xr&&Xr.binding&&Xr.binding("util")}catch{}})(),di=ze&&ze.isTypedArray,Ob=di?Yr(di):Ib,Kb=Object.prototype,Fb=Kb.hasOwnProperty;function qb(r,e){var t=Ne(r),s=!t&&ib(r),o=!t&&!s&&ui(r),n=!t&&!s&&!o&&Ob(r),i=t||s||o||n,a=i?rb(r.length,String):[],l=a.length;for(var u in r)Fb.call(r,u)&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||n&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Lv(u,l)))&&a.push(u);return a}function fi(r,e){return function(t){return r(e(t))}}var Qb=fi(Object.keys,Object),Vb=Object.prototype,Gb=Vb.hasOwnProperty;function Bb(r){if(!si(r))return Qb(r);var e=[];for(var t in Object(r))Gb.call(r,t)&&t!="constructor"&&e.push(t);return e}function Ub(r){return ri(r)?qb(r):Bb(r)}var Nb=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,zb=/^\w*$/;function Lb(r,e){if(Ne(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Hr(r)?!0:zb.test(r)||!Nb.test(r)||e!=null&&r in Object(e)}var gt=Pe(Object,"create");function Wb(){this.__data__=gt?gt(null):{},this.size=0}function Hb(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Jb="__lodash_hash_undefined__",Zb=Object.prototype,Yb=Zb.hasOwnProperty;function Xb(r){var e=this.__data__;if(gt){var t=e[r];return t===Jb?void 0:t}return Yb.call(e,r)?e[r]:void 0}var ek=Object.prototype,tk=ek.hasOwnProperty;function rk(r){var e=this.__data__;return gt?e[r]!==void 0:tk.call(e,r)}var sk="__lodash_hash_undefined__";function ok(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=gt&&e===void 0?sk:e,this}function xe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}xe.prototype.clear=Wb,xe.prototype.delete=Hb,xe.prototype.get=Xb,xe.prototype.has=rk,xe.prototype.set=ok;function nk(){this.__data__=[],this.size=0}function Gt(r,e){for(var t=r.length;t--;)if(Xn(r[t][0],e))return t;return-1}var ik=Array.prototype,ak=ik.splice;function lk(r){var e=this.__data__,t=Gt(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():ak.call(e,t,1),--this.size,!0}function uk(r){var e=this.__data__,t=Gt(e,r);return t<0?void 0:e[t][1]}function ck(r){return Gt(this.__data__,r)>-1}function dk(r,e){var t=this.__data__,s=Gt(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function ae(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ae.prototype.clear=nk,ae.prototype.delete=lk,ae.prototype.get=uk,ae.prototype.has=ck,ae.prototype.set=dk;var mt=Pe(X,"Map");function fk(){this.size=0,this.__data__={hash:new xe,map:new(mt||ae),string:new xe}}function pk(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Bt(r,e){var t=r.__data__;return pk(e)?t[typeof e=="string"?"string":"hash"]:t.map}function hk(r){var e=Bt(this,r).delete(r);return this.size-=e?1:0,e}function yk(r){return Bt(this,r).get(r)}function gk(r){return Bt(this,r).has(r)}function mk(r,e){var t=Bt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function le(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}le.prototype.clear=fk,le.prototype.delete=hk,le.prototype.get=yk,le.prototype.has=gk,le.prototype.set=mk;var vk="Expected a function";function es(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(vk);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(es.Cache||le),t}es.Cache=le;var bk=500;function kk(r){var e=es(r,function(s){return t.size===bk&&t.clear(),s}),t=e.cache;return e}var wk=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Ak=/\\(\\)?/g,$k=kk(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(wk,function(t,s,o,n){e.push(o?n.replace(Ak,"$1"):s||t)}),e});function Ck(r){return r==null?"":Wn(r)}function Dk(r,e){return Ne(r)?r:Lb(r,e)?[r]:$k(Ck(r))}function _k(r){if(typeof r=="string"||Hr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Pk(r,e){e=Dk(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[_k(e[t++])];return t&&t==s?r:void 0}function xk(r,e,t){var s=r==null?void 0:Pk(r,e);return s===void 0?t:s}function Ek(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var jk=fi(Object.getPrototypeOf,Object);function Sk(){this.__data__=new ae,this.size=0}function Mk(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Rk(r){return this.__data__.get(r)}function Ik(r){return this.__data__.has(r)}var Tk=200;function Ok(r,e){var t=this.__data__;if(t instanceof ae){var s=t.__data__;if(!mt||s.length<Tk-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new le(s)}return t.set(r,e),this.size=t.size,this}function Le(r){var e=this.__data__=new ae(r);this.size=e.size}Le.prototype.clear=Sk,Le.prototype.delete=Mk,Le.prototype.get=Rk,Le.prototype.has=Ik,Le.prototype.set=Ok;var pi=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hi=pi&&typeof module=="object"&&module&&!module.nodeType&&module,Kk=hi&&hi.exports===pi,yi=Kk?X.Buffer:void 0;yi&&yi.allocUnsafe;function Fk(r,e){return r.slice()}function qk(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function Qk(){return[]}var Vk=Object.prototype,Gk=Vk.propertyIsEnumerable,gi=Object.getOwnPropertySymbols,Bk=gi?function(r){return r==null?[]:(r=Object(r),qk(gi(r),function(e){return Gk.call(r,e)}))}:Qk;function Uk(r,e,t){var s=e(r);return Ne(r)?s:Ek(s,t(r))}function Nk(r){return Uk(r,Ub,Bk)}var ts=Pe(X,"DataView"),rs=Pe(X,"Promise"),ss=Pe(X,"Set"),mi="[object Map]",zk="[object Object]",vi="[object Promise]",bi="[object Set]",ki="[object WeakMap]",wi="[object DataView]",Lk=_e(ts),Wk=_e(mt),Hk=_e(rs),Jk=_e(ss),Zk=_e(Zr),ue=Ue;(ts&&ue(new ts(new ArrayBuffer(1)))!=wi||mt&&ue(new mt)!=mi||rs&&ue(rs.resolve())!=vi||ss&&ue(new ss)!=bi||Zr&&ue(new Zr)!=ki)&&(ue=function(r){var e=Ue(r),t=e==zk?r.constructor:void 0,s=t?_e(t):"";if(s)switch(s){case Lk:return wi;case Wk:return mi;case Hk:return vi;case Jk:return bi;case Zk:return ki}return e});var Yk=Object.prototype,Xk=Yk.hasOwnProperty;function ew(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Xk.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var Ai=X.Uint8Array;function os(r){var e=new r.constructor(r.byteLength);return new Ai(e).set(new Ai(r)),e}function tw(r,e){var t=os(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var rw=/\w*$/;function sw(r){var e=new r.constructor(r.source,rw.exec(r));return e.lastIndex=r.lastIndex,e}var $i=he?he.prototype:void 0,Ci=$i?$i.valueOf:void 0;function ow(r){return Ci?Object(Ci.call(r)):{}}function nw(r,e){var t=os(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var iw="[object Boolean]",aw="[object Date]",lw="[object Map]",uw="[object Number]",cw="[object RegExp]",dw="[object Set]",fw="[object String]",pw="[object Symbol]",hw="[object ArrayBuffer]",yw="[object DataView]",gw="[object Float32Array]",mw="[object Float64Array]",vw="[object Int8Array]",bw="[object Int16Array]",kw="[object Int32Array]",ww="[object Uint8Array]",Aw="[object Uint8ClampedArray]",$w="[object Uint16Array]",Cw="[object Uint32Array]";function Dw(r,e,t){var s=r.constructor;switch(e){case hw:return os(r);case iw:case aw:return new s(+r);case yw:return tw(r);case gw:case mw:case vw:case bw:case kw:case ww:case Aw:case $w:case Cw:return nw(r);case lw:return new s;case uw:case fw:return new s(r);case cw:return sw(r);case dw:return new s;case pw:return ow(r)}}function _w(r){return typeof r.constructor=="function"&&!si(r)?jv(jk(r)):{}}var Pw="[object Map]";function xw(r){return De(r)&&ue(r)==Pw}var Di=ze&&ze.isMap,Ew=Di?Yr(Di):xw,jw="[object Set]";function Sw(r){return De(r)&&ue(r)==jw}var _i=ze&&ze.isSet,Mw=_i?Yr(_i):Sw,Pi="[object Arguments]",Rw="[object Array]",Iw="[object Boolean]",Tw="[object Date]",Ow="[object Error]",xi="[object Function]",Kw="[object GeneratorFunction]",Fw="[object Map]",qw="[object Number]",Ei="[object Object]",Qw="[object RegExp]",Vw="[object Set]",Gw="[object String]",Bw="[object Symbol]",Uw="[object WeakMap]",Nw="[object ArrayBuffer]",zw="[object DataView]",Lw="[object Float32Array]",Ww="[object Float64Array]",Hw="[object Int8Array]",Jw="[object Int16Array]",Zw="[object Int32Array]",Yw="[object Uint8Array]",Xw="[object Uint8ClampedArray]",eA="[object Uint16Array]",tA="[object Uint32Array]",$={};$[Pi]=$[Rw]=$[Nw]=$[zw]=$[Iw]=$[Tw]=$[Lw]=$[Ww]=$[Hw]=$[Jw]=$[Zw]=$[Fw]=$[qw]=$[Ei]=$[Qw]=$[Vw]=$[Gw]=$[Bw]=$[Yw]=$[Xw]=$[eA]=$[tA]=!0,$[Ow]=$[xi]=$[Uw]=!1;function Ut(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Qt(r))return r;var a=Ne(r);if(a)i=ew(r);else{var l=ue(r),u=l==xi||l==Kw;if(ui(r))return Fk(r);if(l==Ei||l==Pi||u&&!o)i=u?{}:_w(r);else{if(!$[l])return o?r:{};i=Dw(r,l)}}n||(n=new Le);var c=n.get(r);if(c)return c;n.set(r,i),Mw(r)?r.forEach(function(h){i.add(Ut(h,e,t,h,r,n))}):Ew(r)&&r.forEach(function(h,p){i.set(p,Ut(h,e,t,p,r,n))});var d=Nk,f=a?void 0:d(r);return qv(f||r,function(h,p){f&&(p=h,h=r[p]),Zv(i,p,Ut(h,e,t,p,r,n))}),i}var rA=1,sA=4;function vt(r){return Ut(r,rA|sA)}var oA="__lodash_hash_undefined__";function nA(r){return this.__data__.set(r,oA),this}function iA(r){return this.__data__.has(r)}function Nt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new le;++e<t;)this.add(r[e])}Nt.prototype.add=Nt.prototype.push=nA,Nt.prototype.has=iA;function ji(r,e){return r.has(e)}function aA(r){return De(r)&&ri(r)}var lA=Math.min;function uA(r,e,t){for(var s=Uv,o=r[0].length,n=r.length,i=n,a=Array(n),l=1/0,u=[];i--;){var c=r[i];l=lA(c.length,l),a[i]=o>=120&&c.length>=120?new Nt(i&&c):void 0}c=r[0];var d=-1,f=a[0];e:for(;++d<o&&u.length<l;){var h=c[d],p=h;if(h=h!==0?h:0,!(f?ji(f,p):s(u,p))){for(i=n;--i;){var y=a[i];if(!(y?ji(y,p):s(r[i],p)))continue e}f&&f.push(p),u.push(h)}}return u}function cA(r){return aA(r)?r:[]}var Si=Xv(function(r){var e=Nn(r,cA);return e.length&&e[0]===r[0]?uA(e):[]});class Mi{context="";total=0;totalItems=[];processedItems=new Set;downloadedItems=new Set;failedItems=new Set;remainingItems=new Set;skippedItems=[];run;processed=0;remaining=0;progress=0;currentItem;constructor(){}init(e,t){return this.total=e.length,this.totalItems=[...e],this.remaining=e.length,this.remainingItems=new Set(e),this.skippedItems=t?.skipped??[],this.run=t?.run,this.getProgress()}update(e,t,s,o){const n=vt(e);return n.success=t,o&&(n.status=o),t?this.downloadedItems.add(n):this.failedItems.add(n),this.currentItem=n,this.context=s,this.processed++,this.remaining--,this.progress=Math.round(this.processed*100/this.total),this.currentItem=n,this.processedItems.add(n),this.remainingItems.delete(e),this.getProgress()}getProgress(){return{total:this.total,processed:this.processed,remaining:this.remaining,downloadedItems:Array.from(this.downloadedItems.values()),failedItems:Array.from(this.failedItems.values()),progress:this.progress,context:this.context,currentItem:this.currentItem,totalItems:this.totalItems,processedItems:Array.from(this.processedItems.values()),remainingItems:Array.from(this.remainingItems.values()),skippedItems:this.skippedItems,run:this.run}}}function dA(r,e){for(const t of e)if(Array.isArray(t)){if(t.every(s=>r.includes(s)))return!0}else if(r.includes(t))return!0;return!1}function fA(r,e){return tv(r).variables.map(t=>t.name).filter(t=>xk(e,t)===void 0)}function Ri(r,e,t){const s={applicationKey:t?.applicationKey,resourceTags:t?.resourceTags,environmentKeys:t?.environmentKeys},o=r?.resources??[],n=ev(o),i=[],a=[],l=Array.isArray(t?.resourceTags)&&t.resourceTags.length>0;return o.forEach((u,c)=>{if(l){if(!Array.isArray(u.tags)||!u.tags.length){a.push({resource:u,reason:"no-tags",id:n[c]});return}if(!dA(u.tags,t.resourceTags)){a.push({resource:u,reason:"tag-mismatch",id:n[c]});return}}const d=u.url??"",f=fA(d,e),h={...u,id:n[c],rawUrl:d,url:qt(d,{...e})};f.length&&(h.unresolvedVariables=f),i.push(h)}),{scheduled:i,skipped:a,variables:e,run:s}}var pA=Object.defineProperty,hA=Object.getOwnPropertyDescriptor,Ii=(r,e,t,s)=>{for(var o=hA(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&pA(e,t,o),o};const yA={missingModelHandling:{autoGenerateProperties:!0},defaultDataContainerUpdateType:"set",csvParserOptions:{delimiter:"",quoteChar:'"',escapeChar:'"',commentChar:void 0}};let ns=class{key;core;cdRef=new Jm;log=zr.child({prefix:"AppLoader"});registeredTransformers=[];options=yA;csvParser=new sv(this);currentConfig;globalVariables=new Map;defaultVariables=new Map;progressListeners=new Set;currentProcessOptions;currentContext="";progressHandler=new Mi;constructor(){this.initDefaultVariables()}destroy(){this.core=null,this.cdRef=null,this.csvParser=null,this.progressListeners=null,this.progressHandler=null}initDefaultVariables(){this.defaultVariables.set("projectId",{key:"projectId",value:void 0,description:"Your dcupl console project id"}),this.defaultVariables.set("apiKey",{key:"apiKey",value:void 0,description:"Your dcupl console project API key"}),this.defaultVariables.set("version",{key:"version",value:"draft",description:"The version of uploaded files to the dcupl CDN - draft/published/..."}),this.defaultVariables.set("cdnBaseUrl",{key:"cdnBaseUrl",value:"https://cdn.dcupl.com/files/projects",description:"The url to your dcupl folder - might be the dcupl CDN or any other "}),this.defaultVariables.set("baseUrl",{key:"baseUrl",value:"${cdnBaseUrl}/${projectId}/${version}",description:"The base url to your hosted models and data files"}),this.defaultVariables.set("modelUrl",{key:"modelUrl",value:"${baseUrl}/models",description:"The url to the your model files"}),this.defaultVariables.set("dataUrl",{key:"dataUrl",value:"${baseUrl}/data",description:"The url to the your data files"}),this.defaultVariables.set("transformerUrl",{key:"transformerUrl",value:"${baseUrl}/transformers",description:"The url to the your data files"}),this.defaultVariables.set("loaderFileName",{key:"loaderFileName",value:"dcupl.lc.json",description:"The file name of the loader json"}),this.defaultVariables.set("cdnVersion",{key:"cdnVersion",value:void 0,description:"The file-version of the CDN data"}),this.defaultVariables.set("consoleApiUrl",{key:"consoleApiUrl",value:"https://api.dcupl.com",description:"The dcupl console API Url"})}resources={get:r=>this.currentConfig?.resources.find(e=>e.key===r),getAll:()=>this.currentConfig?.resources||[],getWithTag:r=>this.currentConfig?.resources.filter(e=>e.tags?.includes(r))||[],set:r=>{this.currentConfig.resources=r},add:r=>{this.currentConfig.resources.push(r)},delete:r=>{const e=this.currentConfig.resources.findIndex(t=>t.key===r);e>-1&&this.currentConfig.resources.splice(e,1)},plan:r=>{const{config:e,options:t,variables:s}=this.resolveRunContext(r);return Ri(e,s,t)}};variables={get:(r,e)=>{const t=this.currentConfig?.environments?.filter(s=>s.key===e);return this.evaluateVariables(t,this.currentProcessOptions).find(s=>s.key===r)},getAll:r=>{const e=this.currentConfig?.environments?.filter(t=>t.key===r);return this.evaluateVariables(e,this.currentProcessOptions)},getAllAsObject:r=>{const e=this.currentConfig?.environments?.filter(t=>t.key===r);return this.getEvaluatedVariablesAsRecord(e,this.currentProcessOptions)},default:{get:r=>this.defaultVariables.get(r),getAll:()=>Array.from(this.defaultVariables.values())},environment:{get:(r,e)=>{if(!r)return;const t=this.currentConfig?.environments?.find(s=>s.key===r);if(t)return t.variables?.find(s=>s.key===e)},getAll:r=>this.currentConfig?.environments?.find(e=>e.key===r)?.variables||[]},process:{get:r=>this.currentProcessOptions?.variables?.find(e=>e.key===r),getAll:()=>this.currentProcessOptions?.variables||[]},global:{get:r=>this.globalVariables.get(r),getAll:()=>Array.from(this.globalVariables.values()),set:(r,e)=>{this.globalVariables.set(r,{key:r,value:e})},delete:r=>{this.globalVariables.delete(r)}}};transformers={get:r=>this.registeredTransformers.filter(e=>Si(e.applyTo,r.appyTo).length>0),getAll:()=>this.registeredTransformers,set:r=>{this.transformers.remove(r.key),this.registeredTransformers.push(r)},remove:r=>{const e=this.registeredTransformers.findIndex(t=>t.key===r);e>-1&&this.registeredTransformers.splice(e,1)}};config={get:()=>vt(this.currentConfig),set:r=>{this.currentConfig=vt(r)},fetch:async r=>this.fetchConfig(r)};async fetchConfig(r){if(!this.core)throw this.log.error("dcupl not connected. Did you add your loader to dcupl? -> dcupl.addRunner(loader)"),new Error;let e;r?.baseUrl&&this.defaultVariables.set("baseUrl",{key:"baseUrl",value:String(r.baseUrl)}),r?.loaderFileName&&this.defaultVariables.set("loaderFileName",{key:"loaderFileName",value:String(r.loaderFileName)});const t=this.variables.get("baseUrl")?.value;if(t&&this.isDcuplCdn(t))await this.setCdnVersion(),e=await this.loadConfigFromApi();else{const s=this.variables.get("loaderFileName")?.value,o=`${t}/${s}`;e=await this.loadConfigFromUrl(o,r?.headers)}if(this.isValidConfig(e))return r?.skipApply||this.config.set(e),e;throw new Error("Invalid Loader Configuration")}isValidConfig(r){return!!r}async loadConfigFromUrl(r,e){try{const t={};e&&(t.headers=e.reduce((o,n)=>(o[n.key]=n.value,o),{}));const s=await fetch(r,t);if(!s.ok)throw new Error(`Failed to fetch loader configuration from ${Be(r)}`);return s.json()}catch(t){this.log.error("Could not fetch loader configuration",t,{url:r});return}}async loadConfigFromApi(){const r=this.variables.get("baseUrl")?.value,e=this.variables.get("loaderFileName")?.value,t=this.variables.get("cdnVersion")?.value,s=this.variables.get("apiKey")?.value;try{let o=`${r}/${e}`;this.isDcuplCdn(o)&&(t&&(o=this.appendSearchParamToUrl(o,"v",String(t))),s&&(o=this.appendSearchParamToUrl(o,"api-key",s)));const n=await fetch(o);if(!n.ok)throw new Error(`Failed to fetch loader configuration from ${Be(o)}`);return n.json()}catch(o){this.log.error("Could not fetch loader configuration. Are you sure your projectId + apiKey are correct?",o,{baseUrl:r,loaderFileName:e});return}}appendSearchParamToUrl(r,e,t){const s=r.includes("?")?"&":"?";return`${r}${s}${e}=${t}`}async setCdnVersion(){let r;try{const e=this.variables.get("consoleApiUrl")?.value,t=this.variables.get("projectId")?.value,s=this.variables.get("version")?.value;r=`${e}/projects/${t}/files/versions/${s}/status`;const o=await(await fetch(r)).json();o&&o.changedAt&&this.defaultVariables.set("cdnVersion",{key:"cdnVersion",value:String(o.changedAt)})}catch(e){this.log.error("Could not fetch version status",e,{url:r})}}async process(r){if(!this.currentConfig)throw new Error("There is no config present. Make sure to call loader.setConfig(..) or loader.fetchConfig(...)");this.currentContext=Lr();const{config:e,options:t,environments:s,variables:o}=this.resolveRunContext(r),n=this.getHeaderConfigs(s),i=this.getQueryParamConfigs(s),a=Ri(e,o,t),l=this.getLoaderOptions(e,t),u=await this.fetchResources(a,o,l,n,i);return this.currentProcessOptions=t,u}getHeaderConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.headers&&e.push(...t.headers)}),e}getQueryParamConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.queryParams&&e.push(...t.queryParams)}),e}getLoaderOptions(r,e){return e?.options?Object.assign({},this.options,e.options):r?.options?Object.assign({},this.options,r.options):Object.assign({},this.options)}resolveRunContext(r){if(!this.currentConfig)throw new Error("There is no config present. Make sure to call loader.setConfig(..) or loader.fetchConfig(...)");const e=vt(r),t=vt(this.currentConfig);if(e?.applicationKey){const n=this.getAppPreset(t,e);if(!n)throw new Error(`The applicationKey ${e.applicationKey} does not exist`);e.resourceTags=e.resourceTags||n?.resourceTags,e.variables=e.variables||n?.variables}const s=this.getEnvironments(t,e),o=this.getEvaluatedVariablesAsRecord(s,e);return{config:t,options:e,environments:s,variables:o}}evaluateVariables(r,e){const t=new Map;this.defaultVariables&&this.defaultVariables.forEach(n=>{t.set(n.key,n)}),r?.forEach(n=>{n?.variables&&n.variables.forEach(i=>{t.set(i.key,i)})}),e?.variables&&e.variables.forEach(n=>{t.set(n.key,n)}),this.globalVariables&&this.globalVariables.forEach(n=>{t.set(n.key,n)});const s=Array.from(t.values()).map(n=>({...n})),o={};for(const n of s)o[n.key]=n.value||"";for(const n of s)n.value=qt(n.value,o);return s}getEvaluatedVariablesAsRecord(r,e){const t=this.evaluateVariables(r,e),s={};for(const o of t)s[o.key]=o.value||"";return s}getEnvironments(r,e){if(!(!r.environments||!r.environments[0])&&e&&e.environmentKeys&&e.environmentKeys.length>0)return r.environments.filter(t=>e.environmentKeys.indexOf(t.key)>-1)}getAppPreset(r,e){if(!(!r.applications||!r.applications[0])&&e?.applicationKey)return r.applications?.find(t=>t.key===e.applicationKey)}getHeaderForUrl(r,e,t){if(!t||!t.length||!r.tags?.length)return;const s=[];t?.forEach(n=>{if(!n.tags?.length){this.isValidCondition(n,e)&&s.push(n);return}n.tags.find(i=>r.tags?.includes(i))&&this.isValidCondition(n,e)&&s.push(n)});const o={};if(s.forEach(n=>{const i=qt(n.value,{...e});o[n.key]=i}),Object.keys(o).length!==0)return o}getQueryParamsForUrl(r,e,t){const s=[];if(t?.forEach(o=>{if(!o.tags?.length){this.isValidCondition(o,e)&&s.push(o);return}o.tags.find(n=>r.tags?.includes(n))&&this.isValidCondition(o,e)&&s.push(o)}),this.isDcuplCdn(r.url)){const o=e.cdnVersion;o&&s.push({key:"v",value:o}),e.apiKey&&s?.push({key:"api-key",value:e.apiKey})}return s.map(o=>(o.value=qt(o.value,{...e}),o))}isDcuplCdn(r){let e;try{e=new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(r)?r:`https://${r}`).hostname.toLowerCase()}catch{return!1}return e.endsWith(".dcupl.com")&&e.split(".").some(t=>/^(dev-)?cdn\d*$/.test(t))}isValidCondition(r,e){return r.condition?.applyIfVariableHasValue?typeof e[r.condition?.applyIfVariableHasValue]<"u"&&e[r.condition?.applyIfVariableHasValue]!=="":!0}async handleScriptResources(r,e,t,s){return await Promise.all(r.map(async o=>{try{const n=o.scriptKey;if(this.core.scriptController.hasScript(n)){const l=this.progressHandler.update(o,!0,"script");return this.updateProgressListeners(l),null}const i=await this.fetchScript(o,e,t,s);this.core.scriptController.setScript(n,i);const a=this.progressHandler.update(o,!0,"script");this.updateProgressListeners(a);return}catch(n){this.log.error("Failed to load script resource",n,{url:o.url,scriptKey:o.scriptKey});const i={title:o.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:o,description:n?.message};this.setError(i);const a=this.progressHandler.update(o,!1,"script");this.updateProgressListeners(a);return}})),!0}async handleOperatorResources(r,e,t,s){return await Promise.all(r.map(async o=>{try{const n=o.operator;if(this.core.queryManager.registeredCustomOperator.has(n)){const l=this.progressHandler.update(o,!0,"operator");return this.updateProgressListeners(l),null}const i=await this.fetchJavascriptFile(o,e,t,s);this.core.query.registerCustomOperator(n,i);const a=this.progressHandler.update(o,!0,"operator");this.updateProgressListeners(a);return}catch(n){this.log.error("Failed to load operator resource",n,{url:o.url,operator:o.operator});const i={title:o.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:o,description:n?.message};this.setError(i);const a=this.progressHandler.update(o,!1,"operator");this.updateProgressListeners(a);return}})),!0}async handleTransformerResources(r,e,t,s){const o=[];return await Promise.all(r.map(async n=>{try{const i=this.registeredTransformers.find(c=>c.key===n.url);if(i){o.push(i);const c=this.progressHandler.update(n,!0,"transformer");this.updateProgressListeners(c);return}const a=await this.fetchJavascriptFile(n,e,t,s),l={key:n.url,applyTo:n.applyTo||[],type:n.transformerType||"parsedFileTransformer",transformer:a};this.registeredTransformers.push(l),o.push(l);const u=this.progressHandler.update(n,!0,"transformer");this.updateProgressListeners(u)}catch(i){this.log.error("Failed to load transformer resource",i,{url:n.url,transformerType:n.transformerType});const a={title:n.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:n,description:i?.message};this.setError(a);const l=this.progressHandler.update(n,!1,"transformer");this.updateProgressListeners(l)}})),o}getRequestOptions(r,e,t,s){const o=this.getHeaderForUrl(r,e,t),n=this.getQueryParamsForUrl(r,e,s);return{url:this.appendQueryParamsToUrl(r.url,n),headers:o}}async fetchScript(r,e,t,s){const{url:o,headers:n}=this.getRequestOptions(r,e,t,s),i=await fetch(o,{headers:n});if(!i.ok)throw new Error(`Failed to fetch data from ${Be(o)}`);return await i.text()}async fetchJavascriptFile(r,e,t,s){const{url:o,headers:n}=this.getRequestOptions(r,e,t,s),i=await fetch(o,{headers:n});if(!i.ok)throw new Error(`Failed to fetch data from ${Be(o)}`);const a=await i.text();return new Function(a)()}isValidModelDefinitionShape(r){if(typeof r!="object"||r===null||Array.isArray(r))return!1;const e=r;return!(typeof e.key!="string"||e.key.length===0||typeof e.properties<"u"&&!Array.isArray(e.properties))}emitInvalidModelDefinitionError(r,e,t){const s={title:r.url,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:t??"",meta:r,description:e};this.setError(s)}async handleModelResources(r,e,t,s){const o=r.map(async n=>{const i=new Date().getTime();let a;try{const{url:l,headers:u}=this.getRequestOptions(n,e,t,s),c=await fetch(l,{headers:u});if(a=c.status,!c.ok)throw new Error(`Failed to fetch data from ${Be(l)}`);const d=F.now(),f=await c.json(),h=F.now(),p=Array.isArray(f)?f:[f],y=[];for(const m of p)this.isValidModelDefinitionShape(m)?y.push(m):this.emitInvalidModelDefinitionError(n,"Resource body is not a valid ModelDefinition (missing or invalid `key`/`properties`)",typeof m?.key=="string"?m.key:void 0);if(y.length===0){const m=this.progressHandler.update(n,!1,"model",a);return this.updateProgressListeners(m),Promise.resolve(null)}const v=y.map(m=>m.key).join("__"),g=F.getEntriesByName(l.toString());if(Array.isArray(g)&&g[0]){const m=g[0],M={name:n.url,type:"resource",createdAt:new Date().getTime(),value:{model:v,type:"model",start:i,startTime:m.startTime,requestStart:m.requestStart,responseEnd:m.responseEnd,responseStart:m.responseStart,duration:m.duration,parseEnd:h,parseStart:d,decodedBodySize:m.decodedBodySize,encodedBodySize:m.encodedBodySize,end:h}};this.core.analyticsController.set({value:M,context:this.currentContext})}for(const m of y)this.addModelOrView(n,m);const k=this.progressHandler.update(n,!0,"model");return this.updateProgressListeners(k),Promise.resolve(f)}catch(l){this.log.error("Failed to load model resource",l,{url:n.url});const u={title:n.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:n,description:l?.message};this.setError(u);const c=this.progressHandler.update(n,!1,"model",a);return this.updateProgressListeners(c),Promise.resolve(null)}});return await Promise.all(o),!0}appendQueryParamsToUrl(r,e){const t=r.includes("?");let s=r;return e&&e.forEach((o,n)=>{s+=`${n===0&&!t?"?":"&"}${encodeURIComponent(o.key)}=${encodeURIComponent(o.value)}`}),s}async handleDataResources(r,e,t,s,o,n){const i=r.map(async a=>{const l=Lr(),u={placeholderUid:l,data:[],model:a.model};this.core.registerContainer(u);const c=new Date().getTime();let d;try{const{url:f,headers:h}=this.getRequestOptions(a,e,s,o),p=await fetch(f,{headers:h});if(d=p.status,!p.ok)throw new Error(`Failed to fetch data from ${Be(f)}`);const y=p.headers.get("content-type"),v=F.now();let g;a.url.endsWith(".csv")||y?.includes("text/csv")?g=await p.text():g=await p.json();const k=F.now(),m=F.now(),M=this.handleTransformerLogic(g,a,"rawFileTransformer",n||[]),N=F.now();let kt=[],zt=this.core.modelParser.unprocessedModelDescriptions.get(a.model);if(!zt&&(t?.missingModelHandling?.autoGenerateProperties||a.options?.autoGenerateProperties)){const q=a.options?.autoGenerateProperties??t?.missingModelHandling?.autoGenerateProperties??!0;this.addModelOrView(a,{key:a.model,autoGenerateProperties:q,autoGenerateKey:a.options?.autoGenerateKey||!1,keyProperty:a?.options?.keyProperty||"key",keyPropertySeparator:a?.options?.keyPropertySeparator}),zt=this.core.modelParser.unprocessedModelDescriptions.get(a.model)}const vA=F.now();let Ti={sourceColumns:[],coercionFailureSamples:{},origin:a.url};if(a.url.endsWith(".csv")||y?.includes("text/csv")){if(zt){const q=this.csvParser.getJsonFromCSVStringWithMetadata(M,zt,a);kt=q.data,Ti={sourceColumns:q.sourceColumns,coercionFailureSamples:q.coercionFailureSamples,origin:a.url}}}else kt=M;const bA=F.now(),kA=F.now();try{kt=this.handleTransformerLogic(kt,a,"parsedFileTransformer",n||[])}catch(q){this.log.error("Transformer error",q,{resource:a.url,model:a.model})}const wA=F.now(),Oi={placeholderUid:l,model:a.model,data:kt,type:a.options?.updateType||t.defaultDataContainerUpdateType,keyProperty:a?.options?.keyProperty,keyPropertySeparator:a?.options?.keyPropertySeparator,autoGenerateKey:a.options?.autoGenerateKey,autoGenerateProperties:a.options?.autoGenerateProperties},is=F.getEntriesByName(f.toString());if(Array.isArray(is)&&is[0]){const q=is[0],$A={name:a.url,type:"resource",createdAt:new Date().getTime(),value:{model:a.model,type:"data",start:c,startTime:q.startTime,requestStart:q.requestStart,responseEnd:q.responseEnd,responseStart:q.responseStart,duration:q.duration,parseEnd:k,rawTransformStart:m,rawTransformEnd:N,parseStart:v,csvToJsonStart:vA,csvToJsonEnd:bA,parsedTransformStart:kA,parsedTransformEnd:wA,decodedBodySize:q.decodedBodySize,encodedBodySize:q.encodedBodySize,end:k}};this.core.analyticsController.set({value:$A,context:this.currentContext})}this.core.updateRegisteredContainer(Oi,Ti);const AA=this.progressHandler.update(a,!0,"data",d);return this.updateProgressListeners(AA),Promise.resolve(Oi)}catch(f){this.log.error("Failed to load data resource",f,{url:a.url,model:a.model});const h={title:a.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:a,model:a.model,description:f?.message};this.setError(h),this.core.removeRegisteredContainer(u);const p=this.progressHandler.update(a,!1,"data",d);return this.updateProgressListeners(p),Promise.resolve()}});return await Promise.all(i),!0}async fetchResources(r,e,t,s,o){const n=r.scheduled;this.progressHandler=new Mi,this.progressHandler.init(n,{skipped:r.skipped,run:r.run}),this.updateProgressListeners(this.progressHandler.getProgress());try{if(!this.core)throw this.log.error("dcupl not connected. Did you add your loader to dcupl? -> dcupl.addRunner(loader)"),new Error;const i=n.filter(f=>f.type==="script");await this.handleScriptResources(i,e,s,o);const a=n.filter(f=>f.type==="operator");await this.handleOperatorResources(a,e,s,o);const l=n.filter(f=>f.type==="transformer"),u=await this.handleTransformerResources(l,e,s,o),c=n.filter(f=>f.type==="model");await this.handleModelResources(c,e,s,o);const d=n.filter(f=>f.type==="data");return await this.handleDataResources(d,e,t,s,o,u),!0}catch(i){return this.log.error("Failed to fetch resources",i),!1}}addModelOrView(r,e){try{"model"in e?this.core.views.set(e):this.core.models.set(e)}catch(t){const s={title:r.url,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:e.key,meta:r,description:t?.message};this.setError(s)}}handleTransformerLogic(r,e,t,s){for(const o of s)o.type===t&&o.transformer&&(!o.applyTo.length&&!e.tags?.length&&(r=o.transformer(e,r)),Si(o.applyTo,e.tags||[]).length&&(r=o.transformer(e,r)));return r}updateProgressListeners(r){this.progressListeners.forEach(e=>e(r))}on(r){return this.progressListeners.add(r),()=>{this.progressListeners.delete(r)}}setError(r){this.core.modelParser.qualityController.enabled&&this.core.modelParser.qualityController.setError(r)}};Ii([Qn({scope:"global",origin:"loader",type:"loader_config_fetched",connectMessage:!0,connectMessageResult:!0})],ns.prototype,"fetchConfig"),Ii([Qn({scope:"global",origin:"loader",type:"loader_processed",connectMessage:!0})],ns.prototype,"process");const gA=ns;let bt,We;async function mA(r){return bt=new nh(r.options),We=new gA,bt.loaders.add(We,"default"),r.appLoaderConfig?await We.config.fetch(r.appLoaderConfig):await We.config.fetch(),await We.process(r.processOptions),await bt.init(),globalThis.dcupl=bt,{dcupl:bt,loader:We}}globalThis.initDcupl=mA})();
|
|
15
|
+
`||a==="\r")){this.log.error("JSON block spans multiple lines",void 0,{startIndex:e,endIndex:o});break}if(a==='"'&&i!=="\\"&&(n=!n),n||(a==="{"||a==="["?s.push(a):(a==="}"&&s[s.length-1]==="{"||a==="]"&&s[s.length-1]==="[")&&s.pop()),o++,i=a,s.length===0&&!n)break}return{value:r.slice(e,o),length:o-e}}};function Vn(r,e=","){return r&&typeof r=="string"?r.split(e).map(t=>t.trim()):[]}class sv{loader;log=zr.child({prefix:"CsvParser"});constructor(e){this.loader=e}getParserConfig(e,t,s,o){const n=this.loader.config.get()?.options,i=this.loader.options,a=this.log,l={};typeof t?.csvParserOptions?.quoteChar<"u"?l.quoteChar=t?.csvParserOptions?.quoteChar:typeof n?.csvParserOptions?.quoteChar<"u"?l.quoteChar=n?.csvParserOptions?.quoteChar:l.quoteChar=i.csvParserOptions?.quoteChar,typeof t?.csvParserOptions?.delimiter<"u"?l.delimiter=t?.csvParserOptions?.delimiter:typeof n?.csvParserOptions?.delimiter<"u"?l.delimiter=n?.csvParserOptions?.delimiter:l.delimiter=i.csvParserOptions?.delimiter,typeof t?.csvParserOptions?.escapeChar<"u"?l.escapeChar=t?.csvParserOptions?.escapeChar:typeof n?.csvParserOptions?.escapeChar<"u"?l.escapeChar=n?.csvParserOptions?.escapeChar:l.escapeChar=i.csvParserOptions?.escapeChar,typeof t?.csvParserOptions?.commentChar<"u"?l.commentChar=t?.csvParserOptions?.commentChar:typeof n?.csvParserOptions?.commentChar<"u"?l.commentChar=n?.csvParserOptions?.commentChar:l.commentChar=i.csvParserOptions?.commentChar;const u=new Map,c=new Map;if(e.references)for(const p of e.references)u.set(p.key,p),p.origin&&u.set(p.origin,p);if(e.properties)for(const p of e.properties)c.set(p.key,p),p.origin&&c.set(p.origin,p);const d=t?.keyProperty??e.keyProperty??"key",f=Array.isArray(d)?d:[d],h=new Set(f);return{delimiter:l?.delimiter,quoteChar:l?.quoteChar,escapeChar:l?.escapeChar,comments:l.commentChar,dynamicTyping:!1,header:!0,skipEmptyLines:!0,transformHeader:p=>{const y=p?.trim().replace(/"/g,"");return s&&y&&s.push(y),y},transform:function(p,y){if(typeof y>"u"||h.has(y))return p;if(p==="null")return null;if(p===""||typeof p>"u")return;const v=m=>{if(!o)return;const S=o[y];S?S.count+=1:o[y]={rawValue:p,expected:m,count:1}},g=u.get(y);if(g)if(p[0]==="{"||p[0]==="[")try{return JSON.parse(p)}catch(m){a.error("Failed to parse JSON in CSV reference field",m,{header:y,value:p});return}else return g.type==="singleValued"?p:p?.length>0&&g.type==="multiValued"?Vn(p,g?.separator):p;const k=c.get(y);if(!(!e.autoGenerateProperties&&!k))switch(k?.type){case"string":return p;case"int":{const m=parseInt(p,10);if(isNaN(m)){v("int");return}return m}case"float":{const m=parseFloat(p);if(isNaN(m)){v("float");return}return m}case"boolean":if(p==="true")return!0;if(p==="false")return!1;v("boolean");return;case"json":try{return p=p.replace(/[\x00-\x1F\x7F-\x9F]/g,""),JSON.parse(p)}catch(m){a.error("Failed to parse JSON in CSV property field",m,{header:y,value:p}),v("json");return}case"Array<string>":case"Array<int>":case"Array<float>":case"Array<date>":if(p&&typeof p=="string"&&p[0]==="[")try{return JSON.parse(p)}catch{v(k.type);return}if(p&&typeof p=="string")return Vn(p,k?.separator);v(k.type);return;default:return p}}}}getJsonFromCSVString(e,t,s){return this.getJsonFromCSVStringWithMetadata(e,t,s).data}getJsonFromCSVStringWithMetadata(e,t,s){const o=[],n={},i=this.getParserConfig(t,s.options,o,n);return{data:new rv().parse(e,i),sourceColumns:o,coercionFailureSamples:n}}}var Gn=typeof global=="object"&&global&&global.Object===Object&&global,ov=typeof self=="object"&&self&&self.Object===Object&&self,X=Gn||ov||Function("return this")(),he=X.Symbol,Bn=Object.prototype,nv=Bn.hasOwnProperty,iv=Bn.toString,pt=he?he.toStringTag:void 0;function av(r){var e=nv.call(r,pt),t=r[pt];try{r[pt]=void 0;var s=!0}catch{}var o=iv.call(r);return s&&(e?r[pt]=t:delete r[pt]),o}var lv=Object.prototype,uv=lv.toString;function cv(r){return uv.call(r)}var dv="[object Null]",fv="[object Undefined]",Un=he?he.toStringTag:void 0;function Ue(r){return r==null?r===void 0?fv:dv:Un&&Un in Object(r)?av(r):cv(r)}function De(r){return r!=null&&typeof r=="object"}var pv="[object Symbol]";function Hr(r){return typeof r=="symbol"||De(r)&&Ue(r)==pv}function Nn(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var Ne=Array.isArray,zn=he?he.prototype:void 0,Ln=zn?zn.toString:void 0;function Wn(r){if(typeof r=="string")return r;if(Ne(r))return Nn(r,Wn)+"";if(Hr(r))return Ln?Ln.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function qt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}function Hn(r){return r}var hv="[object AsyncFunction]",yv="[object Function]",gv="[object GeneratorFunction]",mv="[object Proxy]";function Jn(r){if(!qt(r))return!1;var e=Ue(r);return e==yv||e==gv||e==hv||e==mv}var Jr=X["__core-js_shared__"],Zn=(function(){var r=/[^.]+$/.exec(Jr&&Jr.keys&&Jr.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function vv(r){return!!Zn&&Zn in r}var bv=Function.prototype,kv=bv.toString;function _e(r){if(r!=null){try{return kv.call(r)}catch{}try{return r+""}catch{}}return""}var wv=/[\\^$.*+?()[\]{}|]/g,Av=/^\[object .+?Constructor\]$/,$v=Function.prototype,Cv=Object.prototype,Dv=$v.toString,_v=Cv.hasOwnProperty,Pv=RegExp("^"+Dv.call(_v).replace(wv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function xv(r){if(!qt(r)||vv(r))return!1;var e=Jn(r)?Pv:Av;return e.test(_e(r))}function Ev(r,e){return r?.[e]}function Pe(r,e){var t=Ev(r,e);return xv(t)?t:void 0}var Zr=Pe(X,"WeakMap"),Yn=Object.create,jv=(function(){function r(){}return function(e){if(!qt(e))return{};if(Yn)return Yn(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function Mv(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var Sv=800,Rv=16,Iv=Date.now;function Tv(r){var e=0,t=0;return function(){var s=Iv(),o=Rv-(s-t);if(t=s,o>0){if(++e>=Sv)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function Ov(r){return function(){return r}}var Qt=(function(){try{var r=Pe(Object,"defineProperty");return r({},"",{}),r}catch{}})(),Kv=Qt?function(r,e){return Qt(r,"toString",{configurable:!0,enumerable:!1,value:Ov(e),writable:!0})}:Hn,Fv=Tv(Kv);function qv(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function Qv(r,e,t,s){for(var o=r.length,n=t+-1;++n<o;)if(e(r[n],n,r))return n;return-1}function Vv(r){return r!==r}function Gv(r,e,t){for(var s=t-1,o=r.length;++s<o;)if(r[s]===e)return s;return-1}function Bv(r,e,t){return e===e?Gv(r,e,t):Qv(r,Vv,t)}function Uv(r,e){var t=r==null?0:r.length;return!!t&&Bv(r,e,0)>-1}var Nv=9007199254740991,zv=/^(?:0|[1-9]\d*)$/;function Lv(r,e){var t=typeof r;return e=e??Nv,!!e&&(t=="number"||t!="symbol"&&zv.test(r))&&r>-1&&r%1==0&&r<e}function Wv(r,e,t){e=="__proto__"&&Qt?Qt(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function Xn(r,e){return r===e||r!==r&&e!==e}var Hv=Object.prototype,Jv=Hv.hasOwnProperty;function Zv(r,e,t){var s=r[e];(!(Jv.call(r,e)&&Xn(s,t))||t===void 0&&!(e in r))&&Wv(r,e,t)}var ei=Math.max;function Yv(r,e,t){return e=ei(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=ei(s.length-e,0),i=Array(n);++o<n;)i[o]=s[e+o];o=-1;for(var a=Array(e+1);++o<e;)a[o]=s[o];return a[e]=t(i),Mv(r,this,a)}}function Xv(r,e){return Fv(Yv(r,e,Hn),r+"")}var eb=9007199254740991;function ti(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=eb}function ri(r){return r!=null&&ti(r.length)&&!Jn(r)}var tb=Object.prototype;function si(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||tb;return r===t}function rb(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var sb="[object Arguments]";function oi(r){return De(r)&&Ue(r)==sb}var ni=Object.prototype,ob=ni.hasOwnProperty,nb=ni.propertyIsEnumerable,ib=oi((function(){return arguments})())?oi:function(r){return De(r)&&ob.call(r,"callee")&&!nb.call(r,"callee")};function ab(){return!1}var ii=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ai=ii&&typeof module=="object"&&module&&!module.nodeType&&module,lb=ai&&ai.exports===ii,li=lb?X.Buffer:void 0,ub=li?li.isBuffer:void 0,ui=ub||ab,cb="[object Arguments]",db="[object Array]",fb="[object Boolean]",pb="[object Date]",hb="[object Error]",yb="[object Function]",gb="[object Map]",mb="[object Number]",vb="[object Object]",bb="[object RegExp]",kb="[object Set]",wb="[object String]",Ab="[object WeakMap]",$b="[object ArrayBuffer]",Cb="[object DataView]",Db="[object Float32Array]",_b="[object Float64Array]",Pb="[object Int8Array]",xb="[object Int16Array]",Eb="[object Int32Array]",jb="[object Uint8Array]",Mb="[object Uint8ClampedArray]",Sb="[object Uint16Array]",Rb="[object Uint32Array]",_={};_[Db]=_[_b]=_[Pb]=_[xb]=_[Eb]=_[jb]=_[Mb]=_[Sb]=_[Rb]=!0,_[cb]=_[db]=_[$b]=_[fb]=_[Cb]=_[pb]=_[hb]=_[yb]=_[gb]=_[mb]=_[vb]=_[bb]=_[kb]=_[wb]=_[Ab]=!1;function Ib(r){return De(r)&&ti(r.length)&&!!_[Ue(r)]}function Yr(r){return function(e){return r(e)}}var ci=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ht=ci&&typeof module=="object"&&module&&!module.nodeType&&module,Tb=ht&&ht.exports===ci,Xr=Tb&&Gn.process,ze=(function(){try{var r=ht&&ht.require&&ht.require("util").types;return r||Xr&&Xr.binding&&Xr.binding("util")}catch{}})(),di=ze&&ze.isTypedArray,Ob=di?Yr(di):Ib,Kb=Object.prototype,Fb=Kb.hasOwnProperty;function qb(r,e){var t=Ne(r),s=!t&&ib(r),o=!t&&!s&&ui(r),n=!t&&!s&&!o&&Ob(r),i=t||s||o||n,a=i?rb(r.length,String):[],l=a.length;for(var u in r)Fb.call(r,u)&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||n&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Lv(u,l)))&&a.push(u);return a}function fi(r,e){return function(t){return r(e(t))}}var Qb=fi(Object.keys,Object),Vb=Object.prototype,Gb=Vb.hasOwnProperty;function Bb(r){if(!si(r))return Qb(r);var e=[];for(var t in Object(r))Gb.call(r,t)&&t!="constructor"&&e.push(t);return e}function Ub(r){return ri(r)?qb(r):Bb(r)}var Nb=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,zb=/^\w*$/;function Lb(r,e){if(Ne(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Hr(r)?!0:zb.test(r)||!Nb.test(r)||e!=null&&r in Object(e)}var yt=Pe(Object,"create");function Wb(){this.__data__=yt?yt(null):{},this.size=0}function Hb(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Jb="__lodash_hash_undefined__",Zb=Object.prototype,Yb=Zb.hasOwnProperty;function Xb(r){var e=this.__data__;if(yt){var t=e[r];return t===Jb?void 0:t}return Yb.call(e,r)?e[r]:void 0}var ek=Object.prototype,tk=ek.hasOwnProperty;function rk(r){var e=this.__data__;return yt?e[r]!==void 0:tk.call(e,r)}var sk="__lodash_hash_undefined__";function ok(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=yt&&e===void 0?sk:e,this}function xe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}xe.prototype.clear=Wb,xe.prototype.delete=Hb,xe.prototype.get=Xb,xe.prototype.has=rk,xe.prototype.set=ok;function nk(){this.__data__=[],this.size=0}function Vt(r,e){for(var t=r.length;t--;)if(Xn(r[t][0],e))return t;return-1}var ik=Array.prototype,ak=ik.splice;function lk(r){var e=this.__data__,t=Vt(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():ak.call(e,t,1),--this.size,!0}function uk(r){var e=this.__data__,t=Vt(e,r);return t<0?void 0:e[t][1]}function ck(r){return Vt(this.__data__,r)>-1}function dk(r,e){var t=this.__data__,s=Vt(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function ae(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ae.prototype.clear=nk,ae.prototype.delete=lk,ae.prototype.get=uk,ae.prototype.has=ck,ae.prototype.set=dk;var gt=Pe(X,"Map");function fk(){this.size=0,this.__data__={hash:new xe,map:new(gt||ae),string:new xe}}function pk(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Gt(r,e){var t=r.__data__;return pk(e)?t[typeof e=="string"?"string":"hash"]:t.map}function hk(r){var e=Gt(this,r).delete(r);return this.size-=e?1:0,e}function yk(r){return Gt(this,r).get(r)}function gk(r){return Gt(this,r).has(r)}function mk(r,e){var t=Gt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function le(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}le.prototype.clear=fk,le.prototype.delete=hk,le.prototype.get=yk,le.prototype.has=gk,le.prototype.set=mk;var vk="Expected a function";function es(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(vk);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(es.Cache||le),t}es.Cache=le;var bk=500;function kk(r){var e=es(r,function(s){return t.size===bk&&t.clear(),s}),t=e.cache;return e}var wk=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Ak=/\\(\\)?/g,$k=kk(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(wk,function(t,s,o,n){e.push(o?n.replace(Ak,"$1"):s||t)}),e});function Ck(r){return r==null?"":Wn(r)}function Dk(r,e){return Ne(r)?r:Lb(r,e)?[r]:$k(Ck(r))}function _k(r){if(typeof r=="string"||Hr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Pk(r,e){e=Dk(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[_k(e[t++])];return t&&t==s?r:void 0}function xk(r,e,t){var s=r==null?void 0:Pk(r,e);return s===void 0?t:s}function Ek(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var jk=fi(Object.getPrototypeOf,Object);function Mk(){this.__data__=new ae,this.size=0}function Sk(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Rk(r){return this.__data__.get(r)}function Ik(r){return this.__data__.has(r)}var Tk=200;function Ok(r,e){var t=this.__data__;if(t instanceof ae){var s=t.__data__;if(!gt||s.length<Tk-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new le(s)}return t.set(r,e),this.size=t.size,this}function Le(r){var e=this.__data__=new ae(r);this.size=e.size}Le.prototype.clear=Mk,Le.prototype.delete=Sk,Le.prototype.get=Rk,Le.prototype.has=Ik,Le.prototype.set=Ok;var pi=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hi=pi&&typeof module=="object"&&module&&!module.nodeType&&module,Kk=hi&&hi.exports===pi,yi=Kk?X.Buffer:void 0;yi&&yi.allocUnsafe;function Fk(r,e){return r.slice()}function qk(r,e){for(var t=-1,s=r==null?0:r.length,o=0,n=[];++t<s;){var i=r[t];e(i,t,r)&&(n[o++]=i)}return n}function Qk(){return[]}var Vk=Object.prototype,Gk=Vk.propertyIsEnumerable,gi=Object.getOwnPropertySymbols,Bk=gi?function(r){return r==null?[]:(r=Object(r),qk(gi(r),function(e){return Gk.call(r,e)}))}:Qk;function Uk(r,e,t){var s=e(r);return Ne(r)?s:Ek(s,t(r))}function Nk(r){return Uk(r,Ub,Bk)}var ts=Pe(X,"DataView"),rs=Pe(X,"Promise"),ss=Pe(X,"Set"),mi="[object Map]",zk="[object Object]",vi="[object Promise]",bi="[object Set]",ki="[object WeakMap]",wi="[object DataView]",Lk=_e(ts),Wk=_e(gt),Hk=_e(rs),Jk=_e(ss),Zk=_e(Zr),ue=Ue;(ts&&ue(new ts(new ArrayBuffer(1)))!=wi||gt&&ue(new gt)!=mi||rs&&ue(rs.resolve())!=vi||ss&&ue(new ss)!=bi||Zr&&ue(new Zr)!=ki)&&(ue=function(r){var e=Ue(r),t=e==zk?r.constructor:void 0,s=t?_e(t):"";if(s)switch(s){case Lk:return wi;case Wk:return mi;case Hk:return vi;case Jk:return bi;case Zk:return ki}return e});var Yk=Object.prototype,Xk=Yk.hasOwnProperty;function ew(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Xk.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var Ai=X.Uint8Array;function os(r){var e=new r.constructor(r.byteLength);return new Ai(e).set(new Ai(r)),e}function tw(r,e){var t=os(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var rw=/\w*$/;function sw(r){var e=new r.constructor(r.source,rw.exec(r));return e.lastIndex=r.lastIndex,e}var $i=he?he.prototype:void 0,Ci=$i?$i.valueOf:void 0;function ow(r){return Ci?Object(Ci.call(r)):{}}function nw(r,e){var t=os(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var iw="[object Boolean]",aw="[object Date]",lw="[object Map]",uw="[object Number]",cw="[object RegExp]",dw="[object Set]",fw="[object String]",pw="[object Symbol]",hw="[object ArrayBuffer]",yw="[object DataView]",gw="[object Float32Array]",mw="[object Float64Array]",vw="[object Int8Array]",bw="[object Int16Array]",kw="[object Int32Array]",ww="[object Uint8Array]",Aw="[object Uint8ClampedArray]",$w="[object Uint16Array]",Cw="[object Uint32Array]";function Dw(r,e,t){var s=r.constructor;switch(e){case hw:return os(r);case iw:case aw:return new s(+r);case yw:return tw(r);case gw:case mw:case vw:case bw:case kw:case ww:case Aw:case $w:case Cw:return nw(r);case lw:return new s;case uw:case fw:return new s(r);case cw:return sw(r);case dw:return new s;case pw:return ow(r)}}function _w(r){return typeof r.constructor=="function"&&!si(r)?jv(jk(r)):{}}var Pw="[object Map]";function xw(r){return De(r)&&ue(r)==Pw}var Di=ze&&ze.isMap,Ew=Di?Yr(Di):xw,jw="[object Set]";function Mw(r){return De(r)&&ue(r)==jw}var _i=ze&&ze.isSet,Sw=_i?Yr(_i):Mw,Pi="[object Arguments]",Rw="[object Array]",Iw="[object Boolean]",Tw="[object Date]",Ow="[object Error]",xi="[object Function]",Kw="[object GeneratorFunction]",Fw="[object Map]",qw="[object Number]",Ei="[object Object]",Qw="[object RegExp]",Vw="[object Set]",Gw="[object String]",Bw="[object Symbol]",Uw="[object WeakMap]",Nw="[object ArrayBuffer]",zw="[object DataView]",Lw="[object Float32Array]",Ww="[object Float64Array]",Hw="[object Int8Array]",Jw="[object Int16Array]",Zw="[object Int32Array]",Yw="[object Uint8Array]",Xw="[object Uint8ClampedArray]",eA="[object Uint16Array]",tA="[object Uint32Array]",$={};$[Pi]=$[Rw]=$[Nw]=$[zw]=$[Iw]=$[Tw]=$[Lw]=$[Ww]=$[Hw]=$[Jw]=$[Zw]=$[Fw]=$[qw]=$[Ei]=$[Qw]=$[Vw]=$[Gw]=$[Bw]=$[Yw]=$[Xw]=$[eA]=$[tA]=!0,$[Ow]=$[xi]=$[Uw]=!1;function Bt(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!qt(r))return r;var a=Ne(r);if(a)i=ew(r);else{var l=ue(r),u=l==xi||l==Kw;if(ui(r))return Fk(r);if(l==Ei||l==Pi||u&&!o)i=u?{}:_w(r);else{if(!$[l])return o?r:{};i=Dw(r,l)}}n||(n=new Le);var c=n.get(r);if(c)return c;n.set(r,i),Sw(r)?r.forEach(function(h){i.add(Bt(h,e,t,h,r,n))}):Ew(r)&&r.forEach(function(h,p){i.set(p,Bt(h,e,t,p,r,n))});var d=Nk,f=a?void 0:d(r);return qv(f||r,function(h,p){f&&(p=h,h=r[p]),Zv(i,p,Bt(h,e,t,p,r,n))}),i}var rA=1,sA=4;function mt(r){return Bt(r,rA|sA)}var oA="__lodash_hash_undefined__";function nA(r){return this.__data__.set(r,oA),this}function iA(r){return this.__data__.has(r)}function Ut(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new le;++e<t;)this.add(r[e])}Ut.prototype.add=Ut.prototype.push=nA,Ut.prototype.has=iA;function ji(r,e){return r.has(e)}function aA(r){return De(r)&&ri(r)}var lA=Math.min;function uA(r,e,t){for(var s=Uv,o=r[0].length,n=r.length,i=n,a=Array(n),l=1/0,u=[];i--;){var c=r[i];l=lA(c.length,l),a[i]=o>=120&&c.length>=120?new Ut(i&&c):void 0}c=r[0];var d=-1,f=a[0];e:for(;++d<o&&u.length<l;){var h=c[d],p=h;if(h=h!==0?h:0,!(f?ji(f,p):s(u,p))){for(i=n;--i;){var y=a[i];if(!(y?ji(y,p):s(r[i],p)))continue e}f&&f.push(p),u.push(h)}}return u}function cA(r){return aA(r)?r:[]}var Mi=Xv(function(r){var e=Nn(r,cA);return e.length&&e[0]===r[0]?uA(e):[]});class Si{context="";total=0;totalItems=[];processedItems=new Set;downloadedItems=new Set;failedItems=new Set;remainingItems=new Set;skippedItems=[];run;processed=0;remaining=0;progress=0;currentItem;constructor(){}init(e,t){return this.total=e.length,this.totalItems=[...e],this.remaining=e.length,this.remainingItems=new Set(e),this.skippedItems=t?.skipped??[],this.run=t?.run,this.getProgress()}update(e,t,s,o){const n=mt(e);return n.success=t,o&&(n.status=o),t?this.downloadedItems.add(n):this.failedItems.add(n),this.currentItem=n,this.context=s,this.processed++,this.remaining--,this.progress=Math.round(this.processed*100/this.total),this.currentItem=n,this.processedItems.add(n),this.remainingItems.delete(e),this.getProgress()}getProgress(){return{total:this.total,processed:this.processed,remaining:this.remaining,downloadedItems:Array.from(this.downloadedItems.values()),failedItems:Array.from(this.failedItems.values()),progress:this.progress,context:this.context,currentItem:this.currentItem,totalItems:this.totalItems,processedItems:Array.from(this.processedItems.values()),remainingItems:Array.from(this.remainingItems.values()),skippedItems:this.skippedItems,run:this.run}}}function dA(r,e){for(const t of e)if(Array.isArray(t)){if(t.every(s=>r.includes(s)))return!0}else if(r.includes(t))return!0;return!1}function fA(r,e){return tv(r).variables.map(t=>t.name).filter(t=>xk(e,t)===void 0)}function Ri(r,e,t){const s={applicationKey:t?.applicationKey,resourceTags:t?.resourceTags,environmentKeys:t?.environmentKeys},o=r?.resources??[],n=ev(o),i=[],a=[],l=Array.isArray(t?.resourceTags)&&t.resourceTags.length>0;return o.forEach((u,c)=>{if(l){if(!Array.isArray(u.tags)||!u.tags.length){a.push({resource:u,reason:"no-tags",id:n[c]});return}if(!dA(u.tags,t.resourceTags)){a.push({resource:u,reason:"tag-mismatch",id:n[c]});return}}const d=u.url??"",f=fA(d,e),h={...u,id:n[c],rawUrl:d,url:Ft(d,{...e})};f.length&&(h.unresolvedVariables=f),i.push(h)}),{scheduled:i,skipped:a,variables:e,run:s}}var pA=Object.defineProperty,hA=Object.getOwnPropertyDescriptor,Ii=(r,e,t,s)=>{for(var o=hA(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&pA(e,t,o),o};const yA={missingModelHandling:{autoGenerateProperties:!0},defaultDataContainerUpdateType:"set",csvParserOptions:{delimiter:"",quoteChar:'"',escapeChar:'"',commentChar:void 0}};let ns=class{key;core;cdRef=new Jm;log=zr.child({prefix:"AppLoader"});registeredTransformers=[];options=yA;csvParser=new sv(this);currentConfig;globalVariables=new Map;defaultVariables=new Map;progressListeners=new Set;currentProcessOptions;currentContext="";progressHandler=new Si;constructor(){this.initDefaultVariables()}destroy(){this.core=null,this.cdRef=null,this.csvParser=null,this.progressListeners=null,this.progressHandler=null}initDefaultVariables(){this.defaultVariables.set("projectId",{key:"projectId",value:void 0,description:"Your dcupl console project id"}),this.defaultVariables.set("apiKey",{key:"apiKey",value:void 0,description:"Your dcupl console project API key"}),this.defaultVariables.set("version",{key:"version",value:"draft",description:"The version of uploaded files to the dcupl CDN - draft/published/..."}),this.defaultVariables.set("cdnBaseUrl",{key:"cdnBaseUrl",value:"https://cdn.dcupl.com/files/projects",description:"The url to your dcupl folder - might be the dcupl CDN or any other "}),this.defaultVariables.set("baseUrl",{key:"baseUrl",value:"${cdnBaseUrl}/${projectId}/${version}",description:"The base url to your hosted models and data files"}),this.defaultVariables.set("modelUrl",{key:"modelUrl",value:"${baseUrl}/models",description:"The url to the your model files"}),this.defaultVariables.set("dataUrl",{key:"dataUrl",value:"${baseUrl}/data",description:"The url to the your data files"}),this.defaultVariables.set("transformerUrl",{key:"transformerUrl",value:"${baseUrl}/transformers",description:"The url to the your data files"}),this.defaultVariables.set("loaderFileName",{key:"loaderFileName",value:"dcupl.lc.json",description:"The file name of the loader json"}),this.defaultVariables.set("cdnVersion",{key:"cdnVersion",value:void 0,description:"The file-version of the CDN data"}),this.defaultVariables.set("consoleApiUrl",{key:"consoleApiUrl",value:"https://api.dcupl.com",description:"The dcupl console API Url"})}resources={get:r=>this.currentConfig?.resources.find(e=>e.key===r),getAll:()=>this.currentConfig?.resources||[],getWithTag:r=>this.currentConfig?.resources.filter(e=>e.tags?.includes(r))||[],set:r=>{this.currentConfig.resources=r},add:r=>{this.currentConfig.resources.push(r)},delete:r=>{const e=this.currentConfig.resources.findIndex(t=>t.key===r);e>-1&&this.currentConfig.resources.splice(e,1)},plan:r=>{const{config:e,options:t,variables:s}=this.resolveRunContext(r);return Ri(e,s,t)}};variables={get:(r,e)=>{const t=this.currentConfig?.environments?.filter(s=>s.key===e);return this.evaluateVariables(t,this.currentProcessOptions).find(s=>s.key===r)},getAll:r=>{const e=this.currentConfig?.environments?.filter(t=>t.key===r);return this.evaluateVariables(e,this.currentProcessOptions)},getAllAsObject:r=>{const e=this.currentConfig?.environments?.filter(t=>t.key===r);return this.getEvaluatedVariablesAsRecord(e,this.currentProcessOptions)},default:{get:r=>this.defaultVariables.get(r),getAll:()=>Array.from(this.defaultVariables.values())},environment:{get:(r,e)=>{if(!r)return;const t=this.currentConfig?.environments?.find(s=>s.key===r);if(t)return t.variables?.find(s=>s.key===e)},getAll:r=>this.currentConfig?.environments?.find(e=>e.key===r)?.variables||[]},process:{get:r=>this.currentProcessOptions?.variables?.find(e=>e.key===r),getAll:()=>this.currentProcessOptions?.variables||[]},global:{get:r=>this.globalVariables.get(r),getAll:()=>Array.from(this.globalVariables.values()),set:(r,e)=>{this.globalVariables.set(r,{key:r,value:e})},delete:r=>{this.globalVariables.delete(r)}}};transformers={get:r=>this.registeredTransformers.filter(e=>Mi(e.applyTo,r.appyTo).length>0),getAll:()=>this.registeredTransformers,set:r=>{this.transformers.remove(r.key),this.registeredTransformers.push(r)},remove:r=>{const e=this.registeredTransformers.findIndex(t=>t.key===r);e>-1&&this.registeredTransformers.splice(e,1)}};config={get:()=>mt(this.currentConfig),set:r=>{this.currentConfig=mt(r)},fetch:async r=>this.fetchConfig(r)};async fetchConfig(r){if(!this.core)throw this.log.error("dcupl not connected. Did you add your loader to dcupl? -> dcupl.addRunner(loader)"),new Error;let e;r?.baseUrl&&this.defaultVariables.set("baseUrl",{key:"baseUrl",value:String(r.baseUrl)}),r?.loaderFileName&&this.defaultVariables.set("loaderFileName",{key:"loaderFileName",value:String(r.loaderFileName)});const t=this.variables.get("baseUrl")?.value;if(t&&this.isDcuplCdn(t))await this.setCdnVersion(),e=await this.loadConfigFromApi();else{const s=this.variables.get("loaderFileName")?.value,o=`${t}/${s}`;e=await this.loadConfigFromUrl(o,r?.headers)}if(this.isValidConfig(e))return r?.skipApply||this.config.set(e),e;throw new Error("Invalid Loader Configuration")}isValidConfig(r){return!!r}async loadConfigFromUrl(r,e){try{const t={};e&&(t.headers=e.reduce((o,n)=>(o[n.key]=n.value,o),{}));const s=await fetch(r,t);if(!s.ok)throw new Error(`Failed to fetch loader configuration from ${Be(r)}`);return s.json()}catch(t){this.log.error("Could not fetch loader configuration",t,{url:r});return}}async loadConfigFromApi(){const r=this.variables.get("baseUrl")?.value,e=this.variables.get("loaderFileName")?.value,t=this.variables.get("cdnVersion")?.value,s=this.variables.get("apiKey")?.value;try{let o=`${r}/${e}`;this.isDcuplCdn(o)&&(t&&(o=this.appendSearchParamToUrl(o,"v",String(t))),s&&(o=this.appendSearchParamToUrl(o,"api-key",s)));const n=await fetch(o);if(!n.ok)throw new Error(`Failed to fetch loader configuration from ${Be(o)}`);return n.json()}catch(o){this.log.error("Could not fetch loader configuration. Are you sure your projectId + apiKey are correct?",o,{baseUrl:r,loaderFileName:e});return}}appendSearchParamToUrl(r,e,t){const s=r.includes("?")?"&":"?";return`${r}${s}${e}=${t}`}async setCdnVersion(){let r;try{const e=this.variables.get("consoleApiUrl")?.value,t=this.variables.get("projectId")?.value,s=this.variables.get("version")?.value;r=`${e}/projects/${t}/files/versions/${s}/status`;const o=await(await fetch(r)).json();o&&o.changedAt&&this.defaultVariables.set("cdnVersion",{key:"cdnVersion",value:String(o.changedAt)})}catch(e){this.log.error("Could not fetch version status",e,{url:r})}}async process(r){if(!this.currentConfig)throw new Error("There is no config present. Make sure to call loader.setConfig(..) or loader.fetchConfig(...)");this.currentContext=Lr();const{config:e,options:t,environments:s,variables:o}=this.resolveRunContext(r),n=this.getHeaderConfigs(s),i=this.getQueryParamConfigs(s),a=Ri(e,o,t),l=this.getLoaderOptions(e,t),u=await this.fetchResources(a,o,l,n,i);return this.currentProcessOptions=t,u}getHeaderConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.headers&&e.push(...t.headers)}),e}getQueryParamConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.queryParams&&e.push(...t.queryParams)}),e}getLoaderOptions(r,e){return e?.options?Object.assign({},this.options,e.options):r?.options?Object.assign({},this.options,r.options):Object.assign({},this.options)}resolveRunContext(r){if(!this.currentConfig)throw new Error("There is no config present. Make sure to call loader.setConfig(..) or loader.fetchConfig(...)");const e=mt(r),t=mt(this.currentConfig);if(e?.applicationKey){const n=this.getAppPreset(t,e);if(!n)throw new Error(`The applicationKey ${e.applicationKey} does not exist`);e.resourceTags=e.resourceTags||n?.resourceTags,e.variables=e.variables||n?.variables}const s=this.getEnvironments(t,e),o=this.getEvaluatedVariablesAsRecord(s,e);return{config:t,options:e,environments:s,variables:o}}evaluateVariables(r,e){const t=new Map;this.defaultVariables&&this.defaultVariables.forEach(n=>{t.set(n.key,n)}),r?.forEach(n=>{n?.variables&&n.variables.forEach(i=>{t.set(i.key,i)})}),e?.variables&&e.variables.forEach(n=>{t.set(n.key,n)}),this.globalVariables&&this.globalVariables.forEach(n=>{t.set(n.key,n)});const s=Array.from(t.values()).map(n=>({...n})),o={};for(const n of s)o[n.key]=n.value||"";for(const n of s)n.value=Ft(n.value,o);return s}getEvaluatedVariablesAsRecord(r,e){const t=this.evaluateVariables(r,e),s={};for(const o of t)s[o.key]=o.value||"";return s}getEnvironments(r,e){if(!(!r.environments||!r.environments[0])&&e&&e.environmentKeys&&e.environmentKeys.length>0)return r.environments.filter(t=>e.environmentKeys.indexOf(t.key)>-1)}getAppPreset(r,e){if(!(!r.applications||!r.applications[0])&&e?.applicationKey)return r.applications?.find(t=>t.key===e.applicationKey)}getHeaderForUrl(r,e,t){if(!t||!t.length||!r.tags?.length)return;const s=[];t?.forEach(n=>{if(!n.tags?.length){this.isValidCondition(n,e)&&s.push(n);return}n.tags.find(i=>r.tags?.includes(i))&&this.isValidCondition(n,e)&&s.push(n)});const o={};if(s.forEach(n=>{const i=Ft(n.value,{...e});o[n.key]=i}),Object.keys(o).length!==0)return o}getQueryParamsForUrl(r,e,t){const s=[];if(t?.forEach(o=>{if(!o.tags?.length){this.isValidCondition(o,e)&&s.push(o);return}o.tags.find(n=>r.tags?.includes(n))&&this.isValidCondition(o,e)&&s.push(o)}),this.isDcuplCdn(r.url)){const o=e.cdnVersion;o&&s.push({key:"v",value:o}),e.apiKey&&s?.push({key:"api-key",value:e.apiKey})}return s.map(o=>(o.value=Ft(o.value,{...e}),o))}isDcuplCdn(r){let e;try{e=new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(r)?r:`https://${r}`).hostname.toLowerCase()}catch{return!1}return e.endsWith(".dcupl.com")&&e.split(".").some(t=>/^(dev-)?cdn\d*$/.test(t))}isValidCondition(r,e){return r.condition?.applyIfVariableHasValue?typeof e[r.condition?.applyIfVariableHasValue]<"u"&&e[r.condition?.applyIfVariableHasValue]!=="":!0}async handleScriptResources(r,e,t,s){return await Promise.all(r.map(async o=>{try{const n=o.scriptKey;if(this.core.scriptController.hasScript(n)){const l=this.progressHandler.update(o,!0,"script");return this.updateProgressListeners(l),null}const i=await this.fetchScript(o,e,t,s);this.core.scriptController.setScript(n,i);const a=this.progressHandler.update(o,!0,"script");this.updateProgressListeners(a);return}catch(n){this.log.error("Failed to load script resource",n,{url:o.url,scriptKey:o.scriptKey});const i={title:o.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:o,description:n?.message};this.setError(i);const a=this.progressHandler.update(o,!1,"script");this.updateProgressListeners(a);return}})),!0}async handleOperatorResources(r,e,t,s){return await Promise.all(r.map(async o=>{try{const n=o.operator;if(this.core.queryManager.registeredCustomOperator.has(n)){const l=this.progressHandler.update(o,!0,"operator");return this.updateProgressListeners(l),null}const i=await this.fetchJavascriptFile(o,e,t,s);this.core.query.registerCustomOperator(n,i);const a=this.progressHandler.update(o,!0,"operator");this.updateProgressListeners(a);return}catch(n){this.log.error("Failed to load operator resource",n,{url:o.url,operator:o.operator});const i={title:o.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:o,description:n?.message};this.setError(i);const a=this.progressHandler.update(o,!1,"operator");this.updateProgressListeners(a);return}})),!0}async handleTransformerResources(r,e,t,s){const o=[];return await Promise.all(r.map(async n=>{try{const i=this.registeredTransformers.find(c=>c.key===n.url);if(i){o.push(i);const c=this.progressHandler.update(n,!0,"transformer");this.updateProgressListeners(c);return}const a=await this.fetchJavascriptFile(n,e,t,s),l={key:n.url,applyTo:n.applyTo||[],type:n.transformerType||"parsedFileTransformer",transformer:a};this.registeredTransformers.push(l),o.push(l);const u=this.progressHandler.update(n,!0,"transformer");this.updateProgressListeners(u)}catch(i){this.log.error("Failed to load transformer resource",i,{url:n.url,transformerType:n.transformerType});const a={title:n.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:n,description:i?.message};this.setError(a);const l=this.progressHandler.update(n,!1,"transformer");this.updateProgressListeners(l)}})),o}getRequestOptions(r,e,t,s){const o=this.getHeaderForUrl(r,e,t),n=this.getQueryParamsForUrl(r,e,s);return{url:this.appendQueryParamsToUrl(r.url,n),headers:o}}async fetchScript(r,e,t,s){const{url:o,headers:n}=this.getRequestOptions(r,e,t,s),i=await fetch(o,{headers:n});if(!i.ok)throw new Error(`Failed to fetch data from ${Be(o)}`);return await i.text()}async fetchJavascriptFile(r,e,t,s){const{url:o,headers:n}=this.getRequestOptions(r,e,t,s),i=await fetch(o,{headers:n});if(!i.ok)throw new Error(`Failed to fetch data from ${Be(o)}`);const a=await i.text();return new Function(a)()}isValidModelDefinitionShape(r){if(typeof r!="object"||r===null||Array.isArray(r))return!1;const e=r;return!(typeof e.key!="string"||e.key.length===0||typeof e.properties<"u"&&!Array.isArray(e.properties))}emitInvalidModelDefinitionError(r,e,t){const s={title:r.url,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:t??"",meta:r,description:e};this.setError(s)}async handleModelResources(r,e,t,s){const o=r.map(async n=>{const i=new Date().getTime();let a;try{const{url:l,headers:u}=this.getRequestOptions(n,e,t,s),c=await fetch(l,{headers:u});if(a=c.status,!c.ok)throw new Error(`Failed to fetch data from ${Be(l)}`);const d=F.now(),f=await c.json(),h=F.now(),p=Array.isArray(f)?f:[f],y=[];for(const m of p)this.isValidModelDefinitionShape(m)?y.push(m):this.emitInvalidModelDefinitionError(n,"Resource body is not a valid ModelDefinition (missing or invalid `key`/`properties`)",typeof m?.key=="string"?m.key:void 0);if(y.length===0){const m=this.progressHandler.update(n,!1,"model",a);return this.updateProgressListeners(m),Promise.resolve(null)}const v=y.map(m=>m.key).join("__"),g=F.getEntriesByName(l.toString());if(Array.isArray(g)&&g[0]){const m=g[0],S={name:n.url,type:"resource",createdAt:new Date().getTime(),value:{model:v,type:"model",start:i,startTime:m.startTime,requestStart:m.requestStart,responseEnd:m.responseEnd,responseStart:m.responseStart,duration:m.duration,parseEnd:h,parseStart:d,decodedBodySize:m.decodedBodySize,encodedBodySize:m.encodedBodySize,end:h}};this.core.analyticsController.set({value:S,context:this.currentContext})}for(const m of y)this.addModelOrView(n,m);const k=this.progressHandler.update(n,!0,"model");return this.updateProgressListeners(k),Promise.resolve(f)}catch(l){this.log.error("Failed to load model resource",l,{url:n.url});const u={title:n.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:n,description:l?.message};this.setError(u);const c=this.progressHandler.update(n,!1,"model",a);return this.updateProgressListeners(c),Promise.resolve(null)}});return await Promise.all(o),!0}appendQueryParamsToUrl(r,e){const t=r.includes("?");let s=r;return e&&e.forEach((o,n)=>{s+=`${n===0&&!t?"?":"&"}${encodeURIComponent(o.key)}=${encodeURIComponent(o.value)}`}),s}async handleDataResources(r,e,t,s,o,n){const i=r.map(async a=>{const l=Lr(),u={placeholderUid:l,data:[],model:a.model};this.core.registerContainer(u);const c=new Date().getTime();let d;try{const{url:f,headers:h}=this.getRequestOptions(a,e,s,o),p=await fetch(f,{headers:h});if(d=p.status,!p.ok)throw new Error(`Failed to fetch data from ${Be(f)}`);const y=p.headers.get("content-type"),v=F.now();let g;a.url.endsWith(".csv")||y?.includes("text/csv")?g=await p.text():g=await p.json();const k=F.now(),m=F.now(),S=this.handleTransformerLogic(g,a,"rawFileTransformer",n||[]),N=F.now();let bt=[],Nt=this.core.modelParser.unprocessedModelDescriptions.get(a.model);if(!Nt&&(t?.missingModelHandling?.autoGenerateProperties||a.options?.autoGenerateProperties)){const q=a.options?.autoGenerateProperties??t?.missingModelHandling?.autoGenerateProperties??!0;this.addModelOrView(a,{key:a.model,autoGenerateProperties:q,autoGenerateKey:a.options?.autoGenerateKey||!1,keyProperty:a?.options?.keyProperty||"key",keyPropertySeparator:a?.options?.keyPropertySeparator}),Nt=this.core.modelParser.unprocessedModelDescriptions.get(a.model)}const vA=F.now();let Ti={sourceColumns:[],coercionFailureSamples:{},origin:a.url};if(a.url.endsWith(".csv")||y?.includes("text/csv")){if(Nt){const q=this.csvParser.getJsonFromCSVStringWithMetadata(S,Nt,a);bt=q.data,Ti={sourceColumns:q.sourceColumns,coercionFailureSamples:q.coercionFailureSamples,origin:a.url}}}else bt=S;const bA=F.now(),kA=F.now();try{bt=this.handleTransformerLogic(bt,a,"parsedFileTransformer",n||[])}catch(q){this.log.error("Transformer error",q,{resource:a.url,model:a.model})}const wA=F.now(),Oi={placeholderUid:l,model:a.model,data:bt,type:a.options?.updateType||t.defaultDataContainerUpdateType,keyProperty:a?.options?.keyProperty,keyPropertySeparator:a?.options?.keyPropertySeparator,autoGenerateKey:a.options?.autoGenerateKey,autoGenerateProperties:a.options?.autoGenerateProperties},is=F.getEntriesByName(f.toString());if(Array.isArray(is)&&is[0]){const q=is[0],$A={name:a.url,type:"resource",createdAt:new Date().getTime(),value:{model:a.model,type:"data",start:c,startTime:q.startTime,requestStart:q.requestStart,responseEnd:q.responseEnd,responseStart:q.responseStart,duration:q.duration,parseEnd:k,rawTransformStart:m,rawTransformEnd:N,parseStart:v,csvToJsonStart:vA,csvToJsonEnd:bA,parsedTransformStart:kA,parsedTransformEnd:wA,decodedBodySize:q.decodedBodySize,encodedBodySize:q.encodedBodySize,end:k}};this.core.analyticsController.set({value:$A,context:this.currentContext})}this.core.updateRegisteredContainer(Oi,Ti);const AA=this.progressHandler.update(a,!0,"data",d);return this.updateProgressListeners(AA),Promise.resolve(Oi)}catch(f){this.log.error("Failed to load data resource",f,{url:a.url,model:a.model});const h={title:a.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:a,model:a.model,description:f?.message};this.setError(h),this.core.removeRegisteredContainer(u);const p=this.progressHandler.update(a,!1,"data",d);return this.updateProgressListeners(p),Promise.resolve()}});return await Promise.all(i),!0}async fetchResources(r,e,t,s,o){const n=r.scheduled;this.progressHandler=new Si,this.progressHandler.init(n,{skipped:r.skipped,run:r.run}),this.updateProgressListeners(this.progressHandler.getProgress());try{if(!this.core)throw this.log.error("dcupl not connected. Did you add your loader to dcupl? -> dcupl.addRunner(loader)"),new Error;const i=n.filter(f=>f.type==="script");await this.handleScriptResources(i,e,s,o);const a=n.filter(f=>f.type==="operator");await this.handleOperatorResources(a,e,s,o);const l=n.filter(f=>f.type==="transformer"),u=await this.handleTransformerResources(l,e,s,o),c=n.filter(f=>f.type==="model");await this.handleModelResources(c,e,s,o);const d=n.filter(f=>f.type==="data");return await this.handleDataResources(d,e,t,s,o,u),!0}catch(i){return this.log.error("Failed to fetch resources",i),!1}}addModelOrView(r,e){try{"model"in e?this.core.views.set(e):this.core.models.set(e)}catch(t){const s={title:r.url,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:e.key,meta:r,description:t?.message};this.setError(s)}}handleTransformerLogic(r,e,t,s){for(const o of s)o.type===t&&o.transformer&&(!o.applyTo.length&&!e.tags?.length&&(r=o.transformer(e,r)),Mi(o.applyTo,e.tags||[]).length&&(r=o.transformer(e,r)));return r}updateProgressListeners(r){this.progressListeners.forEach(e=>e(r))}on(r){return this.progressListeners.add(r),()=>{this.progressListeners.delete(r)}}setError(r){this.core.modelParser.qualityController.enabled&&this.core.modelParser.qualityController.setError(r)}};Ii([Qn({scope:"global",origin:"loader",type:"loader_config_fetched",connectMessage:!0,connectMessageResult:!0})],ns.prototype,"fetchConfig"),Ii([Qn({scope:"global",origin:"loader",type:"loader_processed",connectMessage:!0})],ns.prototype,"process");const gA=ns;let vt,We;async function mA(r){return vt=new nh(r.options),We=new gA,vt.loaders.add(We,"default"),r.appLoaderConfig?await We.config.fetch(r.appLoaderConfig):await We.config.fetch(),await We.process(r.processOptions),await vt.init(),globalThis.dcupl=vt,{dcupl:vt,loader:We}}globalThis.initDcupl=mA})();
|
|
16
16
|
//# sourceMappingURL=dcupl.bundle.min.js.map
|