@dcupl/bundle 2.0.0-beta.10

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.
@@ -0,0 +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 xe(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 Wt(r){return typeof r!="string"&&(r=String(r)),r}function Ht(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=xe(r),e=Wt(e);var t=this.map[r];this.map[r]=t?t+", "+e:e},x.prototype.delete=function(r){delete this.map[xe(r)]},x.prototype.get=function(r){return r=xe(r),this.has(r)?this.map[r]:null},x.prototype.has=function(r){return this.map.hasOwnProperty(xe(r))},x.prototype.set=function(r,e){this.map[xe(r)]=Wt(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)}),Ht(r)},x.prototype.values=function(){var r=[];return this.forEach(function(e){r.push(e)}),Ht(r)},x.prototype.entries=function(){var r=[];return this.forEach(function(e,t){r.push([t,e])}),Ht(r)},O.iterable&&(x.prototype[Symbol.iterator]=x.prototype.entries);function Jt(r){if(!r._noBody){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}}function ns(r){return new Promise(function(e,t){r.onload=function(){e(r.result)},r.onerror=function(){t(r.error)}})}function Bi(r){var e=new FileReader,t=ns(e);return e.readAsArrayBuffer(r),t}function Vi(r){var e=new FileReader,t=ns(e),s=/charset=([A-Za-z0-9_-]+)/.exec(r.type),o=s?s[1]:"utf-8";return e.readAsText(r,o),t}function Gi(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 is(r){if(r.slice)return r.slice(0);var e=new Uint8Array(r.byteLength);return e.set(new Uint8Array(r)),e.buffer}function as(){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=is(r.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):O.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(r)||Qi(r))?this._bodyArrayBuffer=is(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=Jt(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=Jt(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(Bi);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var r=Jt(this);if(r)return r;if(this._bodyBlob)return Vi(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(Gi(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 fe(r,e){if(!(this instanceof fe))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 fe){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()}}}fe.prototype.clone=function(){return new fe(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}as.call(fe.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)}as.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 pe=R.DOMException;try{new pe}catch{pe=function(e,t){this.message=e,this.name=t;var s=Error(e);this.stack=s.stack},pe.prototype=Object.create(Error.prototype),pe.prototype.constructor=pe}function ls(r,e){return new Promise(function(t,s){var o=new fe(r,e);if(o.signal&&o.signal.aborted)return s(new pe("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 pe("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(xe(u)),n.setRequestHeader(u,Wt(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)})}ls.polyfill=!0,R.fetch||(R.fetch=ls,R.Headers=x,R.Request=fe,R.Response=H);var us=typeof global=="object"&&global&&global.Object===Object&&global,Hi=typeof self=="object"&&self&&self.Object===Object&&self,J=us||Hi||Function("return this")(),G=J.Symbol,cs=Object.prototype,Ji=cs.hasOwnProperty,Zi=cs.toString,ze=G?G.toStringTag:void 0;function Yi(r){var e=Ji.call(r,ze),t=r[ze];try{r[ze]=void 0;var s=!0}catch{}var o=Zi.call(r);return s&&(e?r[ze]=t:delete r[ze]),o}var Xi=Object.prototype,ea=Xi.toString;function ta(r){return ea.call(r)}var ra="[object Null]",sa="[object Undefined]",ds=G?G.toStringTag:void 0;function X(r){return r==null?r===void 0?sa:ra:ds&&ds in Object(r)?Yi(r):ta(r)}function K(r){return r!=null&&typeof r=="object"}var oa="[object Symbol]";function Ee(r){return typeof r=="symbol"||K(r)&&X(r)==oa}function je(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,fs=G?G.prototype:void 0,ps=fs?fs.toString:void 0;function bt(r){if(typeof r=="string")return r;if(E(r))return je(r,bt)+"";if(Ee(r))return ps?ps.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 hs=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(Ee(r))return hs;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)?hs:+r}var ys=1/0,ha=17976931348623157e292;function ya(r){if(!r)return r===0?r:0;if(r=pa(r),r===ys||r===-ys){var e=r<0?-1:1;return e*ha}return r===r?r:0}function kt(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 Zt(r){if(!z(r))return!1;var e=X(r);return e==ma||e==va||e==ga||e==ba}var Yt=J["__core-js_shared__"],gs=(function(){var r=/[^.]+$/.exec(Yt&&Yt.keys&&Yt.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function ka(r){return!!gs&&gs in r}var wa=Function.prototype,Aa=wa.toString;function he(r){if(r!=null){try{return Aa.call(r)}catch{}try{return r+""}catch{}}return""}var $a=/[\\^$.*+?()[\]{}|]/g,Ca=/^\[object .+?Constructor\]$/,Da=Function.prototype,Pa=Object.prototype,_a=Da.toString,xa=Pa.hasOwnProperty,Ea=RegExp("^"+_a.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(he(r))}function Sa(r,e){return r?.[e]}function ye(r,e){var t=Sa(r,e);return ja(t)?t:void 0}var Xt=ye(J,"WeakMap"),ms=Object.create,Ma=(function(){function r(){}return function(e){if(!z(e))return{};if(ms)return ms(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=ye(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 Ba(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function vs(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 Va(r){return r!==r}function Ga(r,e,t){for(var s=t-1,o=r.length;++s<o;)if(r[s]===e)return s;return-1}function bs(r,e,t){return e===e?Ga(r,e,t):vs(r,Va,t)}function Ua(r,e){var t=r==null?0:r.length;return!!t&&bs(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 $t(r,e,t){e=="__proto__"&&At?At(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function Le(r,e){return r===e||r!==r&&e!==e}var La=Object.prototype,Wa=La.hasOwnProperty;function ks(r,e,t){var s=r[e];(!(Wa.call(r,e)&&Le(s,t))||t===void 0&&!(e in r))&&$t(r,e,t)}var ws=Math.max;function Ha(r,e,t){return e=ws(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=ws(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,wt),r+"")}var Ja=9007199254740991;function rr(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ja}function ee(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 As(r){return K(r)&&X(r)==Xa}var $s=Object.prototype,el=$s.hasOwnProperty,tl=$s.propertyIsEnumerable,We=As((function(){return arguments})())?As:function(r){return K(r)&&el.call(r,"callee")&&!tl.call(r,"callee")};function rl(){return!1}var Cs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ds=Cs&&typeof module=="object"&&module&&!module.nodeType&&module,sl=Ds&&Ds.exports===Cs,Ps=sl?J.Buffer:void 0,ol=Ps?Ps.isBuffer:void 0,He=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]",Pl="[object Uint8ClampedArray]",_l="[object Uint16Array]",xl="[object Uint32Array]",C={};C[kl]=C[wl]=C[Al]=C[$l]=C[Cl]=C[Dl]=C[Pl]=C[_l]=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[X(r)]}function Je(r){return function(e){return r(e)}}var _s=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ze=_s&&typeof module=="object"&&module&&!module.nodeType&&module,jl=Ze&&Ze.exports===_s,or=jl&&us.process,Se=(function(){try{var r=Ze&&Ze.require&&Ze.require("util").types;return r||or&&or.binding&&or.binding("util")}catch{}})(),xs=Se&&Se.isTypedArray,nr=xs?Je(xs):El,Sl=Object.prototype,Ml=Sl.hasOwnProperty;function Es(r,e){var t=E(r),s=!t&&We(r),o=!t&&!s&&He(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||Ml.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 js(r,e){return function(t){return r(e(t))}}var Rl=js(Object.keys,Object),Il=Object.prototype,Tl=Il.hasOwnProperty;function Ss(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 Ye(r){return ee(r)?Es(r):Ss(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||Ee(r)?!0:Kl.test(r)||!Ol.test(r)||e!=null&&r in Object(e)}var Xe=ye(Object,"create");function Fl(){this.__data__=Xe?Xe(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__",Bl=Object.prototype,Vl=Bl.hasOwnProperty;function Gl(r){var e=this.__data__;if(Xe){var t=e[r];return t===Ql?void 0:t}return Vl.call(e,r)?e[r]:void 0}var Ul=Object.prototype,Nl=Ul.hasOwnProperty;function zl(r){var e=this.__data__;return Xe?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]=Xe&&e===void 0?Ll:e,this}function ge(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])}}ge.prototype.clear=Fl,ge.prototype.delete=ql,ge.prototype.get=Gl,ge.prototype.has=zl,ge.prototype.set=Wl;function Hl(){this.__data__=[],this.size=0}function Ct(r,e){for(var t=r.length;t--;)if(Le(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 te(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])}}te.prototype.clear=Hl,te.prototype.delete=Yl,te.prototype.get=Xl,te.prototype.has=eu,te.prototype.set=tu;var et=ye(J,"Map");function ru(){this.size=0,this.__data__={hash:new ge,map:new(et||te),string:new ge}}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 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=ru,re.prototype.delete=ou,re.prototype.get=nu,re.prototype.has=iu,re.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||re),t}ar.Cache=re;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 lr(r){return r==null?"":bt(r)}function Ms(r,e){return E(r)?r:ir(r,e)?[r]:pu(lr(r))}function Pt(r){if(typeof r=="string"||Ee(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ur(r,e){e=Ms(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[Pt(e[t++])];return t&&t==s?r:void 0}function tt(r,e,t){var s=r==null?void 0:ur(r,e);return s===void 0?t:s}function Rs(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var Is=G?G.isConcatSpreadable:void 0;function hu(r){return E(r)||We(r)||!!(Is&&r&&r[Is])}function Ts(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)&&Rs(o,a)}return o}var Os=js(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 Ks(r,e,t){return r===r&&(t!==void 0&&(r=r<=t?r:t),r=r>=e?r:e),r}function Cu(){this.__data__=new te,this.size=0}function Du(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Pu(r){return this.__data__.get(r)}function _u(r){return this.__data__.has(r)}var xu=200;function Eu(r,e){var t=this.__data__;if(t instanceof te){var s=t.__data__;if(!et||s.length<xu-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new re(s)}return t.set(r,e),this.size=t.size,this}function L(r){var e=this.__data__=new te(r);this.size=e.size}L.prototype.clear=Cu,L.prototype.delete=Du,L.prototype.get=Pu,L.prototype.has=_u,L.prototype.set=Eu;var Fs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,qs=Fs&&typeof module=="object"&&module&&!module.nodeType&&module,ju=qs&&qs.exports===Fs,Qs=ju?J.Buffer:void 0,Bs=Qs?Qs.allocUnsafe:void 0;function Vs(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,Gs=Object.getOwnPropertySymbols,Tu=Gs?function(r){return r==null?[]:(r=Object(r),Su(Gs(r),function(e){return Iu.call(r,e)}))}:Mu;function Ou(r,e,t){var s=e(r);return E(r)?s:Rs(s,t(r))}function cr(r){return Ou(r,Ye,Tu)}var dr=ye(J,"DataView"),fr=ye(J,"Promise"),pr=ye(J,"Set"),Us="[object Map]",Ku="[object Object]",Ns="[object Promise]",zs="[object Set]",Ls="[object WeakMap]",Ws="[object DataView]",Fu=he(dr),qu=he(et),Qu=he(fr),Bu=he(pr),Vu=he(Xt),U=X;(dr&&U(new dr(new ArrayBuffer(1)))!=Ws||et&&U(new et)!=Us||fr&&U(fr.resolve())!=Ns||pr&&U(new pr)!=zs||Xt&&U(new Xt)!=Ls)&&(U=function(r){var e=X(r),t=e==Ku?r.constructor:void 0,s=t?he(t):"";if(s)switch(s){case Fu:return Ws;case qu:return Us;case Qu:return Ns;case Bu:return zs;case Vu:return Ls}return e});var Gu=Object.prototype,Uu=Gu.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 hr(r){var e=new r.constructor(r.byteLength);return new _t(e).set(new _t(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 Hs=G?G.prototype:void 0,Js=Hs?Hs.valueOf:void 0;function Hu(r){return Js?Object(Js.call(r)):{}}function Zs(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 Zs(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 Ys(r){return typeof r.constructor=="function"&&!sr(r)?Ma(Os(r)):{}}var gc="[object Map]";function mc(r){return K(r)&&U(r)==gc}var Xs=Se&&Se.isMap,vc=Xs?Je(Xs):mc,bc="[object Set]";function kc(r){return K(r)&&U(r)==bc}var eo=Se&&Se.isSet,wc=eo?Je(eo):kc,Ac=1,to="[object Arguments]",$c="[object Array]",Cc="[object Boolean]",Dc="[object Date]",Pc="[object Error]",ro="[object Function]",_c="[object GeneratorFunction]",xc="[object Map]",Ec="[object Number]",so="[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]",Bc="[object Int32Array]",Vc="[object Uint8Array]",Gc="[object Uint8ClampedArray]",Uc="[object Uint16Array]",Nc="[object Uint32Array]",w={};w[to]=w[$c]=w[Tc]=w[Oc]=w[Cc]=w[Dc]=w[Kc]=w[Fc]=w[qc]=w[Qc]=w[Bc]=w[xc]=w[Ec]=w[so]=w[jc]=w[Sc]=w[Mc]=w[Rc]=w[Vc]=w[Gc]=w[Uc]=w[Nc]=!0,w[Pc]=w[ro]=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==ro||u==_c;if(He(r))return Vs(r,a);if(u==so||u==to||c&&!o)i=c?{}:Ys(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 Ba(h||r,function(p,y){h&&(y=p,p=r[y]),ks(i,y,xt(p,e,t,y,r,n))}),i}var zc=1,Lc=4;function se(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 rt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new re;++e<t;)this.add(r[e])}rt.prototype.add=rt.prototype.push=Hc,rt.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 oo(r,e){return r.has(e)}var Yc=1,Xc=2;function no(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 rt: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(!oo(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]",io=G?G.prototype:void 0,yr=io?io.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 Le(+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=no(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,ao="[object Arguments]",lo="[object Array]",Et="[object Object]",wd=Object.prototype,uo=wd.hasOwnProperty;function Ad(r,e,t,s,o,n){var i=E(r),a=E(e),l=i?lo:U(r),u=a?lo:U(e);l=l==ao?Et:l,u=u==ao?Et:u;var c=l==Et,d=u==Et,f=l==u;if(f&&He(r)){if(!He(e))return!1;i=!0,c=!1}if(f&&!c)return n||(n=new L),i||nr(r)?no(r,e,t,s,o,n):yd(r,e,l,t,s,o,n);if(!(t&kd)){var h=c&&uo.call(r,"__wrapped__"),p=d&&uo.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 st(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,st,o)}var $d=1,Cd=2;function co(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?st(u,l,$d|Cd,s,c):d))return!1}}return!0}function fo(r){return r===r&&!z(r)}function po(r){for(var e=Ye(r),t=e.length;t--;){var s=e[t],o=r[s];e[t]=[s,o,fo(o)]}return e}function ho(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Dd(r){var e=po(r);return e.length==1&&e[0][2]?ho(e[0][0],e[0][1]):function(t){return t===r||co(t,r,e)}}function Pd(r,e){return r!=null&&e in Object(r)}function _d(r,e,t){e=Ms(e,r);for(var s=-1,o=e.length,n=!1;++s<o;){var i=Pt(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)||We(r)))}function xd(r,e){return r!=null&&_d(r,e,Pd)}var Ed=1,jd=2;function Sd(r,e){return ir(r)&&fo(e)?ho(Pt(r),e):function(t){var s=tt(t,r);return s===void 0&&s===e?xd(t,r):st(e,s,Ed|jd)}}function yo(r){return function(e){return e?.[r]}}function Md(r){return function(e){return ur(e,r)}}function Rd(r){return ir(r)?yo(Pt(r)):Md(r)}function Me(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 go=Id();function Td(r,e){return r&&go(r,e,Ye)}function Od(r,e){return function(t,s){if(t==null)return t;if(!ee(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 Re(r){return K(r)&&ee(r)}var Kd=200;function mo(r,e,t,s){var o=-1,n=Ua,i=!0,a=r.length,l=[],u=e.length;if(!a)return l;t&&(e=je(e,Je(t))),e.length>=Kd&&(n=oo,i=!1,e=new rt(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 vo=tr(function(r,e){var t=Fd(e);return Re(t)&&(t=void 0),Re(r)?mo(r,Ts(e,1,Re),Me(t)):[]});function bo(r,e,t){r=lr(r),e=bt(e);var s=r.length;t=t===void 0?s:Ks(kt(t),0,s);var o=t;return t-=e.length,t>=0&&r.slice(t,o)==e}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 ko(r,e,t){var s=E(r)?qd:Qd;return s(r,Me(e))}function Bd(r){return function(e,t,s){var o=Object(e);if(!ee(e)){var n=Me(t);e=Ye(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 Vd=Math.max;function mr(r,e,t){var s=r==null?0:r.length;if(!s)return-1;var o=t==null?0:kt(t);return o<0&&(o=Vd(s+o,0)),vs(r,Me(e),o)}var Gd=Bd(mr);function Ud(r,e){var t=-1,s=ee(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)&&X(r)==Nd}function wo(r,e){return st(r,e)}function St(r,e,t){t=typeof t=="function"?t:void 0;var s=t?t(r,e):void 0;return s===void 0?st(r,e,void 0,t):!!s}function zd(r,e){return r===e||co(r,e,po(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=Ee(r),i=e!==void 0,a=e===null,l=e===e,u=Ee(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=je(e,function(n){return E(n)?function(i){return ur(i,n.length===1?n[0]:n)}:n}):e=[wt];var s=-1;e=je(e,Je(Me));var o=Ud(r,function(n,i,a){var l=je(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 Ao(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=yo("length"),$o="\\ud800-\\udfff",Yd="\\u0300-\\u036f",Xd="\\ufe20-\\ufe2f",ef="\\u20d0-\\u20ff",tf=Yd+Xd+ef,rf="\\ufe0e\\ufe0f",sf="["+$o+"]",vr="["+tf+"]",br="\\ud83c[\\udffb-\\udfff]",of="(?:"+vr+"|"+br+")",Co="[^"+$o+"]",Do="(?:\\ud83c[\\udde6-\\uddff]){2}",Po="[\\ud800-\\udbff][\\udc00-\\udfff]",nf="\\u200d",_o=of+"?",xo="["+rf+"]?",af="(?:"+nf+"(?:"+[Co,Do,Po].join("|")+")"+xo+_o+")*",lf=xo+_o+af,uf="(?:"+[Co+vr+"?",vr,Do,Po,sf].join("|")+")",Eo=RegExp(br+"(?="+br+")|"+uf+lf,"g");function cf(r){for(var e=Eo.lastIndex=0;Eo.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(ee(r))return jt(r)?df(r):r.length;var e=U(r);return e==ff||e==pf?r.size:Ss(r).length}function yf(r,e,t){return r=lr(r),t=t==null?0:Ks(kt(t),0,r.length),e=bt(e),r.slice(t,t+e.length)==e}function kr(r){const e=wr(r);return gf(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 gf(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 me={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 mf{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:me.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"?[]:me.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 jo=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 vf{graph;nodeIndex;constructor(){this.graph=new jo,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 bf=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 Ie=new bf;class Mo{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}enabled;cache;cacheDependencies;hitCount=0;missCount=0;log=Ie.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 se(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}}}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 Ar{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=me.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):se(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=me.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=me.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&&typeof n=="string"&&n.startsWith("/")&&n.endsWith("/")){if(s.queryFind(u,n,"some")){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 Pf(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 _f{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 _f(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 _=new Ef;function ve(r,e){if(e.includes("[*]")){const n=e.indexOf("[*]"),i=e.substring(0,n),a=e.substring(n+3),l=i?tt(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(...ve(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 $r(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 ot=(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=_.parse(r).isDeepQuery;let s=0;for(const o of e.values())if(o)if(t)s+=ve(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=_.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=ve(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=_.parse(r.attribute).isDeepQuery;for(const n of e.values()){let i;o?i=ve(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=_.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=ve(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,$r([t,l])),s++);else typeof a=="number"&&(t=Oo(t,a,$r([t,a])),s++)}return s===0?void 0:{average:jf(t,s,$r([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 nt=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"}},be=class{_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=se(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||_}init(e){this._initOptions=se(e),this.currentQuery=se(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=se(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 se(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:ko(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=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 nt("Missing attribute",e)),e.operator||t.push(new nt("Missing operator",e)),typeof e.value>"u"&&t.push(new nt("Missing value",e)),e.operator==="find"&&Array.isArray(e.value)&&t.push(new nt("find operator cannot have 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 nt("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 Cr=new be;function Of(r,e,t,s,o,n,i){const a=Cr.removeQuery({groupKey:o},se(s)),l=i.queryData(r,a,!1,n),u=e?[...e.keys()]:[],c=new Set(u),d=n.get(o)??new Map;if(!t.excludeUnresolved)for(const h of d.keys())c.add(h);if(t.excludeUndefineds?c.delete(void 0):c.add(void 0),t.sort){const h=[];for(const y of c.values())h.push(Ko(y,d,l,e,o,s,!0));const p=t.excludeZeros?h.filter(y=>y.size>0):h;return p.sort(Kf(t.sort)),t.count?p.slice(0,t.count):p}const f=[];for(const h of c.values()){const p=Ko(h,d,l,e,o,s,!!t?.calculateFacets);if(!(t?.excludeZeros&&p.size===0)){if(t?.count&&f.length===t?.count)return f;f.push(p)}}return f}function Ko(r,e,t,s,o,n,i){const a=new Map,l=e.get(r)||new Set;for(const u of l){const c=t.get(u);if(c&&(a.set(u,c),!i))break}return{key:String(r),value:r,selected:Ff(o,r,n),enabled:a.size>0,size:a.size,entry:s?.get(r),resultKeys:Array.from(a.keys())}}function Mt(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||Mt(e.value,t.value);case"size-asc":return(e,t)=>e.size-t.size||Mt(e.value,t.value);case"value-asc":return(e,t)=>Mt(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:-Mt(e.value,t.value)}}const Ff=(r,e,t)=>{const s=t.queries.findIndex(o=>Cr.isQueryGroup(o)&&o.groupKey===r);return s>-1?!!t.queries[s].queries.find(o=>{if(Cr.isQuery(o)){const n=o.value?.key||o.value;return o.attribute===r&&n===e}return!1}):!1};class Rt{indexMap=new Map;dataMap=new Map;indexMetadata=new Map;constructor(){}reset(e){e?(this.indexMap.delete(e),this.dataMap.delete(e),this.indexMetadata.delete(e)):(this.indexMap.clear(),this.dataMap.clear(),this.indexMetadata.clear())}fillDataMap(e,t){let 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=_.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=_.parse(e).isDeepQuery;for(const l of t.values()){let u;a?(u=ve(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 _.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 Te="__";function Dr(r,e,t={key:"root"},s="root",o=new Rt,n){const i=n||r;for(const a of e.columns)a.attribute&&(_.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.rows)a.attribute&&(_.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.values)a.attribute&&(_.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=ot(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=ot(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)};Dr(d,f,c,o+Te+e.attribute+Te+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+Te+e.attribute+Te+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=ot(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)};Dr(d,f,c,o+Te+e.attribute+Te+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})?)?$/,Bf=/^-?\d+$/,Vf=/^-?\d+\.\d+$/,Gf=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,Uf=r=>r==="true"||r==="false"?"boolean":Bf.test(r)?"int":Vf.test(r)?"float":Qf.test(r)&&!Number.isNaN(Date.parse(r))?"date":"string",Nf=r=>Gf.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,Bo=r=>Number(r)===r&&r%1!==0,Hf=r=>{switch(typeof r){case"string":return"string";case"number":return Qo(r)?"int":Bo(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 be;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,o=e.value;const n=e.options?.arrayValueHandling||"some";if(Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(o=this.transformValue(o,e.options.transform)),e.attribute.includes(".")||e.attribute.includes("[")?s=tt(t,e.attribute):s=t[e.attribute],Array.isArray(e.options?.transform)&&e.options.transform.length>0&&(s=this.transformValue(s,e.options.transform)),(typeof s>"u"||s===null)&&!["typeof","isTruthy","eq"].includes(e.operator))return!1;switch(e.operator){case"eq":return e.options?.invert?!wo(s,o):wo(s,o);case"find":return e.options?.invert?!this.queryFind(s,o,n):this.queryFind(s,o,n);case"lt":return Array.isArray(s)?n==="some"?s.some(i=>i<o):s.every(i=>i<o):s<o;case"gt":return Array.isArray(s)?n==="some"?s.some(i=>i>o):s.every(i=>i>o):s>o;case"lte":return Array.isArray(s)?n==="some"?s.some(i=>i<=o):s.every(i=>i<=o):s<=o;case"gte":return Array.isArray(s)?n==="some"?s.some(i=>i>=o):s.every(i=>i>=o):s>=o;case"typeof":return e.options?.invert?typeof s!==o:Array.isArray(s)?n==="some"?s.some(i=>typeof i===o):s.every(i=>typeof i===o):typeof s===o;case"isTruthy":return o===!0?Array.isArray(s)?n==="some"?s.some(i=>typeof!!i):s.every(i=>typeof!!i):!!s:!s;case"size":return typeof s=="string"?s.length===o:hf(s)===o;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 i=this.registeredCustomOperator.get(e.operator);if(typeof i=="function")return i(e,t)}}return!1}evaluateEqOperator(e,t,s,o){const n=new Map,i=o.get(t.attribute);if(i){let a;if(typeof t.value=="string"?a=t.value:t.value?.key&&Object.keys(t.value).length===1&&(a=t.value.key),typeof a<"u"){const l=i.get(a);if(l)if(l.forEach(u=>{s.has(u)&&n.set(u,s.get(u))}),t.options?.invert){const u=vo(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}}for(let[a,l]of s){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(c=>c.isDeepQuery)){const c=this.queryBuilder.getProjectionForAttributeEntries(u.filter(d=>d.isDeepQuery));l=this.globalItemService.getProjectedData(c,this.modelParser.models.get(e.modelKey),l)}this.evaluateQuery(t,l)&&n.set(a,l)}return n}equalRegexFn(e,t){if(typeof t=="string"&&yf(t,"/")&&bo(t,"/"))try{return new RegExp(t.slice(1,-1)).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(s=>St(s,t,this.equalRegexFn)):typeof t=="object"?zd(e,t):e===t}queryFind(e,t,s){return Array.isArray(e)?typeof t=="string"||typeof t=="number"||typeof t=="boolean"?s==="some"?e.some(o=>St(o,t,this.equalRegexFn)):e.every(o=>St(o,t,this.equalRegexFn)):!!Gd(e,t):St(e,t,this.equalRegexFn)}validateQuery(e){if(this.queryBuilder.isQuery(e)){if(!e.attribute||!e.operator)throw new Error("invalid query - missing attribute or operator");if(e.operator==="find"&&Array.isArray(e.value))throw new Error("invalid query - find operator cannot have array value");return!0}else{if(this.queryBuilder.isQueryGroup(e))return ko(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(f=>f.isDeepQuery)){const f=this.queryBuilder.getProjectionForAttributeEntries(u.filter(h=>h.isDeepQuery));l=this.globalItemService.getProjectedData(f,this.modelParser.models.get(e.modelKey),l)}const c=this.handleArrayStarQuery(t,l);let d=!1;for(const f of c.queries){const h={...f,options:{...f.options,invert:!1}};if(this.evaluateQuery(h,l)){d=!0;break}}d&&(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{if(t.operator==="eq")return this.evaluateEqOperator(e,t,s,o);for(let[i,a]of s){const l=this.queryBuilder.extractQueryAttributes({queries:[t]});if(l.some(u=>u.isDeepQuery)){const u=this.queryBuilder.getProjectionForAttributeEntries(l.filter(c=>c.isDeepQuery));a=this.globalItemService.getProjectedData(u,this.modelParser.models.get(e.modelKey),a)}this.evaluateQuery(t,a)&&n.set(i,a)}}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(".")?tt(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=vo(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){const n=new Map(e);return t.queries.length===0?e:(t.groupKey||(t.groupKey="root"),t.groupType||(t.groupType="and"),t.queries||(t.queries=[]),this.validateQuery(t),this.evaluateQueryGroup(t,t,n,s,o))}}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
+ "use strict";
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 It=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>tt(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 Re(r)?mo(r,Ts(e,1,Re)):[]});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 Mo(!!this.cdRef.dcuplInitOptions.performance?.cache?.enabled)}modelParser;cdRef;item;indicesController;queryManager;initialData;filteredData;model;filterItems=new Map;queryBuilder;cacheCtrl;projectionCache=new Map;init(e,t){this.model=e,this.initialData=t,this.filteredData=this.initialData,this.queryBuilder=new be,this.queryBuilder.init({modelKey:e.key}),this.initFilterItems({skipProcessing:!0})}indexDependsOnAttributes(e,t){const s=e.includes("_")?e.split("_")[0]:e;try{const o=_.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()}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&&_.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=>_.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}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(_.parse(e.attribute).isDeepQuery)return ot(e,t,s,e.attribute);{const o=this.model.getAttribute(e.attribute);if(!o)throw new Error("Attribute not found");return ot(e,t,s,o.key)}}getSections(e){const t={_meta:{currentSize:0,initialSize:0},items:[]},s=_.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=_.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=ve(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=me.now();e?.skipProcessing||(this.filteredData=this.getFilteredData(this.initialData,!1),this.cdRef.trigger({scope:"list",type:"result_updated",action:"update",connectMessage:!0,listKey:this.cdRef.key,modelKey:this.model.key,start:t}))}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)}},Vo=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=Ao(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 Vo(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=Ie.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});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=_.parse(e.attribute).isDeepQuery;if(!s&&!this.model.getAttribute(e.attribute))throw new Error(`Attribute ${e.attribute} does not exist`);if(typeof e.value=="string"&&e.value.startsWith("/")&&e.value.endsWith("/"))try{new RegExp(e.value.slice(1,-1))}catch{return[]}let o,n;if(e.relevantData==="all")o=this.filter.initialData,n={modelKey:this.model.key,queries:[]};else if(e.relevantData==="filtered")o=this.filter.filteredData,n=this.filter.queryBuilder.getQuery();else if(e.relevantData==="excludeQuery"&&e.excludeQuery){const u=new be;u.init(this.filter.queryBuilder.getQuery()),u.removeQuery(e.excludeQuery),n=u.getQuery(),o=this.dcuplApi.queryManager.queryData(this.filter.initialData,n,!1,this.filter.indicesController.indexMap)}else o=this.filter.filteredData,n=this.filter.queryBuilder.getQuery();let i=o;if(s){const u=_.parse(e.attribute),c=this.filter.queryBuilder.getProjectionForAttributeEntries([u]),d=new Map;for(const[f,h]of o){const p=this.filter.item.getProjectedData(c,this.model,h);d.set(f,p)}i=d}const a=this.filter.indicesController.getOrCreateIndex(e.attribute,i,{query:n}),l=kf(i,a,e,this.dcuplApi.queryManager);return this.filter.cacheCtrl.set("suggestions",t,l),l}_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=_.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))}let n;if(s){const i=_.parse(e.attribute),a=this.filter.queryBuilder.getProjectionForAttributeEntries([i]);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)}}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,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=_.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 Rt;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=>_.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=Dr(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):ks(t,a,l)}return t}function np(r,e,t){if(!z(t))return!1;var s=typeof e;return(s=="number"?ee(t)&&er(e,t.length):s=="string"&&e in t)?Le(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 Go(r){return ee(r)?Es(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)||X(r)!=dp)return!1;var e=Os(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,Me(s),n)}}function _r(r,e,t){(t!==void 0&&!Le(r[e],t)||t===void 0&&!(e in r))&&$t(r,e,t)}function xr(r,e){if(!(e==="constructor"&&typeof r[e]=="function")&&e!="__proto__")return r[e]}function kp(r){return op(r,Go(r))}function wp(r,e,t,s,o,n,i){var a=xr(r,t),l=xr(e,t),u=i.get(l);if(u){_r(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&&He(l),p=!f&&!h&&nr(l);c=l,f||h||p?E(a)?c=a:Re(a)?c=sp(a):h?(d=!1,c=Vs(l,!0)):p?(d=!1,c=Zs(l,!0)):c=[]:gp(l)||We(l)?(c=a,We(a)?c=kp(a):(!z(a)||Zt(a))&&(c=Ys(l))):d=!1}d&&(i.set(l,c),o(c,l,s,n,i),i.delete(l)),_r(r,t,c)}function No(r,e,t,s,o){r!==e&&go(e,function(n,i){if(o||(o=new L),z(n))wp(r,e,i,t,No,s,o);else{var a=s?s(xr(r,i),n,i+"",r,e,o):void 0;a===void 0&&(a=n),_r(r,i,a)}},Go)}var Ap=Object.prototype,$p=Ap.hasOwnProperty,Er=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)&&X(r)==Cp}var it=ip(function(r,e,t){No(r,e,t)});const B=(r,e,t)=>({title:r,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",attribute:e,description:t}),Pp=r=>{const e=["any","Array<date>","Array<float>","Array<int>","Array<string>","boolean","date","float","int","json","string"];if(!r.key)return B("Invalid Property",r.key,"Property key is missing");if(!r.type||e.indexOf(r.type)===-1)return B("Invalid Property",r.key,"Property type is invalid");if("derive"in r){if(!r.derive?.localReference)return B("Invalid Property",r.key,"Derived Property localReference is missing");if(!r.derive.remoteProperty)return B("Invalid Property",r.key,"Derived Property remoteProperty is missing")}if("expression"in r&&typeof r.expression!="string")return B("Invalid Property",r.key,"Expression is invalid")},_p=r=>{const e=["multiValued","singleValued"];if(!r.key)return B("Invalid Reference",r.key,"Reference key is missing");if(!r.type||e.indexOf(r.type)===-1)return B("Invalid Reference",r.key,"Reference type is invalid");if(!r.model)return B("Invalid Reference",r.key,"Reference model is missing");if("derive"in r){if(!r.derive.localReference)return B("Invalid Reference",r.key,"Derived Reference localReference is missing");if(!r.derive.remoteReference)return B("Invalid Reference",r.key,"Derived Reference remoteReference is missing")}if("resolve"in r){if(!r.resolve.reference)return B("Invalid Reference",r.key,"Resolved Reference reference is missing");if(!r.resolve.model)return B("Invalid Reference",r.key,"Resolved Reference model is missing")}if("groupBy"in r&&!r.groupBy.reference)return B("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 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},ke="::";function Tp(r){return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function zo(r,e,t=ke){return typeof e=="string"?String(r[e]):e.length===1?String(r[e[0]]):e.map(s=>String(r[s])).join(t)}function jr(r,e=ke){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=Ie.child({prefix:"Model"});initialDefinition;data=new Map;supportsAutoCreation=!1;autoGenerateKey=!1;autoGenerateProperties=!1;autoGeneratePropertiesOption=!1;keyProperty="key";keyPropertySeparator;valueMappings=[];meta;qualityConfig=Wo;indicesController=new Rt;cdRef;groupedRefReverseIndex=new Map;init(e){this.key=e.key,this.initialDefinition=e,e.quality&&(this.qualityConfig=it({},Wo,e.quality))}applyPropertiesAndReferences(e){const t=new Set;e.properties?.map(s=>{const o=Pp(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=_p(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=it({},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(!Bo(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=Pf(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??ke,d=jr(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??ke,d=jr(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=It(o,{...n}),l=JSON.parse(a),u=new be;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??ke;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 setTimeout(()=>{e.addContainer(i)},0),{key:n}}if(typeof t=="string"){e.data.set(t,{key:t});const s={model:e.key,data:[{key:t}]};setTimeout(()=>{e.addContainer(s)},0)}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=It(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),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()}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??ke,d=jr(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(!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=It(n,{...i}),u=JSON.parse(l),c=new be;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=It(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.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)}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;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 Sr(r){return"resolve"in r}function Bp(r){return"derive"in r}function Vp(r){return"groupBy"in r}var Gp=Object.defineProperty,Up=Object.getOwnPropertyDescriptor,Tt=(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&&Gp(e,t,o),o};let at=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=Ie.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 jo,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
+ This will cause unpredictable update ordering. Please restructure your models to remove the circular dependency.`),new Error(`Circular dependency detected: ${t}
7
+ Models cannot have circular references as this leads to unpredictable behavior during updates.`)}}buildAttributeDependencyGraph(){this.attributeDependencyGraph=new vf,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(Sr(s))this.processResolvedReference(t,o,s.resolve);else if(Bp(s))this.processDerivedReference(t,o,s.derive);else if(Vp(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}=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(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 Ao(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=Er(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=it(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=it(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 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&&Sr(f)){const h=f.resolve.model,p=f.resolve.reference,y=this.models.get(h);if(y){const v=y.references.get(p);v&&Sr(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??ke,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 new Promise(l=>setTimeout(l,0)):await new Promise(l=>setTimeout(l,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_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 new Promise(l=>setTimeout(l,0)):await new Promise(l=>setTimeout(l,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_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 new Promise(l=>setTimeout(l,0)):await new Promise(l=>setTimeout(l,0))}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 new Promise(l=>setTimeout(l,0)):await new Promise(l=>setTimeout(l,0))}}_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}};Tt([b({scope:"global",type:"model_add",connectMessage:!0})],at.prototype,"addModel"),Tt([b({scope:"global",type:"data_change",connectMessage:!0})],at.prototype,"addData"),Tt([b({scope:"global",type:"view_add",connectMessage:!0})],at.prototype,"addView"),Tt([b({scope:"global",type:"dcupl_handle_datacontainer"})],at.prototype,"handleDataContainer");function Np(r,e){return je(e,function(t){return r[t]})}function zp(r){return r==null?[]:Np(r,Ye(r))}var Lp=Math.max;function Wp(r,e,t,s){r=ee(r)?r:zp(r),t=t?kt(t):0;var o=r.length;return t<0&&(t=Lp(o+t,0)),jt(r)?t<=o&&r.indexOf(e,t)>-1:!!o&&bs(r,e,t)>-1}var Hp=Object.defineProperty,Jp=Object.getOwnPropertyDescriptor,Ho=(r,e,t,s)=>{for(var o=Jp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Hp(e,t,o),o};let Mr=class{constructor(e,t){this.dcuplApi=e,this.cdRef=t}dcuplApi;cdRef;options;key;modelKey;catalog;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 Rt;for(const n of t.indicesController.indexMap.keys())o.getOrCreateIndex(n,s)}else o=t.indicesController;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=se(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)}on(e){return this.cdRef.on(e)}};Ho([b({scope:"list",type:"list_destroyed",connectMessage:!0})],Mr.prototype,"_destroy"),Ho([b({scope:"list",type:"list_updated",action:"update",connectMessage:!0})],Mr.prototype,"update");var Zp=Object.defineProperty,Yp=Object.getOwnPropertyDescriptor,Xp=(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};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 Ar;t._init({cdRefKey:e.listKey,parentCd:this.dcuplInstance.cdRef,dcuplInitOptions:this.dcuplInstance.initOptions,analyticsController:this.dcuplInstance.analyticsController});const s=new Mr(this.dcuplInstance,t);return s.init(e),this.lists.push(s),s}}Xp([b({scope:"global",type:"list_created",connectMessage:!0})],Jo.prototype,"create");let eh=class{constructor(e){this.scriptsController=e}scriptsController;enabled=!1;maxErrorsPerGroup=1e3;errors=new Map;errorCounts=new Map;log=Ie.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}))}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=Er(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;this.modelParser.unprocessedData=this.modelParser.unprocessedData.filter(s=>s.model!=="$DcuplErrorTrackingErrors");const e=this.modelParser.models.get("$DcuplErrorTrackingErrors");e?.resetData(),e?.resetIndexMap(),this.modelParser.addData({data:this.getErrors(),model:"$DcuplErrorTrackingErrors",type:"set"});const t=this.modelParser.unprocessedData.find(s=>s.model==="$DcuplErrorTrackingErrors");t&&await this.modelParser.handleDataContainer([t])}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"}],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=this.dcupl.lists.create({modelKey:"$DcuplErrorTrackingErrors"}),t=e.catalog.fn.facets({attribute:"errorType",calculateResults:!0,excludeUndefineds:!1,excludeUnresolved:!1,excludeZeros:!1});this.values.errors={},t&&(this.values.errors.size=e.catalog.fn.metadata().currentSize,this.values.errors.UndefinedValue=t.find(s=>s.key==="UndefinedValue")?.size||0,this.values.errors.UndefinedAttribute=t.find(s=>s.key==="UndefinedAttribute")?.size||0,this.values.errors.WrongDataType=t.find(s=>s.key==="WrongDataType")?.size||0,this.values.errors.MissingModel=t.find(s=>s.key==="MissingModel")?.size||0,this.values.errors.InvalidModelDescription=t.find(s=>s.key==="InvalidModelDescription")?.size||0,this.values.errors.RemoteReferenceKeyNotFound=t.find(s=>s.key==="RemoteReferenceKeyNotFound")?.size||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=Er(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&&!bo(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&&!Wp(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 th=Object.defineProperty,rh=Object.getOwnPropertyDescriptor,V=(r,e,t,s)=>{for(var o=rh(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&th(e,t,o),o};let Q=class{cdRef=new Ar;analyticsController=new mf;containerSourceMetadata=new WeakMap;scriptController=new Zf;qualityController=new eh(this.scriptController);log=Ie.child({prefix:"Dcupl"});modelParser=new at(this.cdRef,this.qualityController,this);globalItemService=new Vo(this.modelParser,this.scriptController);cacheCtrl=new Mo(!1);queryManager=new Jf(this.scriptController,this.globalItemService,this.modelParser);_loaders=new Map;rootQueryBuilder=new be;_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,cacheInvalidationThreshold:.7,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=it({},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}),this.cacheCtrl.enabled=!!this.initOptions.performance?.cache?.enabled}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()};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.models.get(e.model)?.resetData(),this.modelParser.models.get(e.model)?.resetIndexMap())},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}getAffectedModels(e){const t=new Set;for(const o of e.keys())t.add(o);const s=this.modelParser.dependencyGraph;if(s)for(const o of e.keys())this.getDownstreamDependencies(o,s).forEach(n=>t.add(n));return Array.from(t)}getDownstreamDependencies(e,t){const s=new Set,o=new Set,n=i=>{if(!o.has(i)){o.add(i);for(const[a,l]of Object.entries(t.dependencies||{}))Array.isArray(l)&&l.includes(i)&&(s.add(a),n(a))}};return n(e),s}updateFnLists(e,t){const s=this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1;for(const o of this.lists.getAll()){if(!this.shouldAutoUpdateList(o,t)){s&&this.log.debug("List skipped (auto-update disabled)",{listKey:o.key,modelKey:o.modelKey});continue}e?this.isListAffectedByChanges(o,e.affectedModels)?(s&&this.log.debug("List auto-updating (affected by changes)",{listKey:o.key,modelKey:o.modelKey,affectedModels:e.affectedModels}),o.update()):s&&this.log.debug("List skipped (not affected)",{listKey:o.key,modelKey:o.modelKey}):(s&&this.log.debug("List auto-updating (full update)",{listKey:o.key,modelKey:o.modelKey}),o.update())}}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.cacheCtrl.clear(),!0}catch(e){return this.log.error("Initialization failed",e),!1}}async update(e){try{const t=this.modelParser.changeTracker,s=t.hasChanges(),o=s?new Map(t.getChangedAttributes()):null,n=s?new Set(t.getModelsWithFullReset()):null,i=s?t.getTotalChangedItemCount():0,a=this.cacheCtrl.getStats();if(await this.performUpdate(()=>this.modelParser.update()),s&&this.cacheCtrl.enabled&&o){const l=this.modelParser.getTotalItemCount(),u=i,c=l>0?u/l:0,d=this.initOptions.performance?.partialUpdates?.cacheInvalidationThreshold??.7,f=this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1;n&&n.size>0?(f&&this.log.debug("Cache invalidation: Full clear",{reason:"full_reset_detected"}),this.cacheCtrl.clear()):c>d?(f&&this.log.debug("Cache invalidation: Full clear",{reason:"high_item_ratio",ratio:c.toFixed(2),threshold:d,changedItems:u,totalItems:l}),this.cacheCtrl.clear()):(f&&this.log.debug("Cache invalidation: Selective",{changedItems:u,totalItems:l,ratio:c.toFixed(2)}),this.cacheCtrl.invalidateByDependencies(o))}else(this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1)&&this.log.debug("Cache invalidation: Full clear",{reason:"full_update"}),this.cacheCtrl.clear();if(this.cacheCtrl.getStats){const l=this.cacheCtrl.getStats(),u=this.modelParser.partialUpdateMetrics.getLastUpdates(1);if(u.length>0&&u[0]){const c=u[0];c.cacheStats={entriesInvalidated:a.totalEntries-l.totalEntries,totalEntries:a.totalEntries}}}if(s&&o){const l={isPartialUpdate:!0,changedModels:Array.from(o.keys()),changedAttributes:o,affectedModels:this.getAffectedModels(o)};this.cdRef.trigger({scope:"global",type:"dcupl_partial_update",args:[l]}),this.updateFnLists(l,e?.autoUpdateLists)}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=me.now(),o=t||W();this._loaders.set(o,e),e.core=this,e.key=o;const n=new Ar;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())}}};V([b({scope:"global",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_pivot"),V([b({scope:"global",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_aggregate"),V([b({scope:"global",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_suggest"),V([b({scope:"global",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_groupBy"),V([b({scope:"global",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_facets"),V([b({scope:"global",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_metadata"),V([b({scope:"global",type:"dcupl_initialized",connectMessage:!0})],Q.prototype,"init"),V([b({scope:"global",type:"dcupl_updated_manually",action:"update",connectMessage:!0})],Q.prototype,"update"),V([b({scope:"global",type:"dcupl_destroyed",connectMessage:!0})],Q.prototype,"destroy"),V([b({scope:"global",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"getItem"),V([b({scope:"global",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_getManyItems"),V([b({scope:"global",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"executeQuery"),V([b({scope:"global",type:"loader_removed",connectMessage:!0})],Q.prototype,"removeLoader");let sh=class extends Q{version="2.0.0-beta.6";constructor(e){super(e)}};var Zo=typeof global=="object"&&global&&global.Object===Object&&global,oh=typeof self=="object"&&self&&self.Object===Object&&self,Z=Zo||oh||Function("return this")(),ue=Z.Symbol,Yo=Object.prototype,nh=Yo.hasOwnProperty,ih=Yo.toString,lt=ue?ue.toStringTag:void 0;function ah(r){var e=nh.call(r,lt),t=r[lt];try{r[lt]=void 0;var s=!0}catch{}var o=ih.call(r);return s&&(e?r[lt]=t:delete r[lt]),o}var lh=Object.prototype,uh=lh.toString;function ch(r){return uh.call(r)}var dh="[object Null]",fh="[object Undefined]",Xo=ue?ue.toStringTag:void 0;function Oe(r){return r==null?r===void 0?fh:dh:Xo&&Xo in Object(r)?ah(r):ch(r)}function Ke(r){return r!=null&&typeof r=="object"}var ph="[object Symbol]";function Rr(r){return typeof r=="symbol"||Ke(r)&&Oe(r)==ph}function hh(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 Fe=Array.isArray,en=ue?ue.prototype:void 0,tn=en?en.toString:void 0;function rn(r){if(typeof r=="string")return r;if(Fe(r))return hh(r,rn)+"";if(Rr(r))return tn?tn.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Ot(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var yh="[object AsyncFunction]",gh="[object Function]",mh="[object GeneratorFunction]",vh="[object Proxy]";function sn(r){if(!Ot(r))return!1;var e=Oe(r);return e==gh||e==mh||e==yh||e==vh}var Ir=Z["__core-js_shared__"],on=(function(){var r=/[^.]+$/.exec(Ir&&Ir.keys&&Ir.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function bh(r){return!!on&&on in r}var kh=Function.prototype,wh=kh.toString;function we(r){if(r!=null){try{return wh.call(r)}catch{}try{return r+""}catch{}}return""}var Ah=/[\\^$.*+?()[\]{}|]/g,$h=/^\[object .+?Constructor\]$/,Ch=Function.prototype,Dh=Object.prototype,Ph=Ch.toString,_h=Dh.hasOwnProperty,xh=RegExp("^"+Ph.call(_h).replace(Ah,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Eh(r){if(!Ot(r)||bh(r))return!1;var e=sn(r)?xh:$h;return e.test(we(r))}function jh(r,e){return r?.[e]}function Ae(r,e){var t=jh(r,e);return Eh(t)?t:void 0}var Tr=Ae(Z,"WeakMap"),nn=Object.create,Sh=(function(){function r(){}return function(e){if(!Ot(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=Ae(Object,"defineProperty");return r({},"",{}),r}catch{}})();function Mh(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}var Rh=9007199254740991,Ih=/^(?:0|[1-9]\d*)$/;function Th(r,e){var t=typeof r;return e=e??Rh,!!e&&(t=="number"||t!="symbol"&&Ih.test(r))&&r>-1&&r%1==0&&r<e}function Oh(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 Kh=Object.prototype,Fh=Kh.hasOwnProperty;function qh(r,e,t){var s=r[e];(!(Fh.call(r,e)&&ln(s,t))||t===void 0&&!(e in r))&&Oh(r,e,t)}var Qh=9007199254740991;function un(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Qh}function Bh(r){return r!=null&&un(r.length)&&!sn(r)}var Vh=Object.prototype;function cn(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Vh;return r===t}function Gh(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var Uh="[object Arguments]";function dn(r){return Ke(r)&&Oe(r)==Uh}var fn=Object.prototype,Nh=fn.hasOwnProperty,zh=fn.propertyIsEnumerable,Lh=dn((function(){return arguments})())?dn:function(r){return Ke(r)&&Nh.call(r,"callee")&&!zh.call(r,"callee")};function Wh(){return!1}var pn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hn=pn&&typeof module=="object"&&module&&!module.nodeType&&module,Hh=hn&&hn.exports===pn,yn=Hh?Z.Buffer:void 0,Jh=yn?yn.isBuffer:void 0,gn=Jh||Wh,Zh="[object Arguments]",Yh="[object Array]",Xh="[object Boolean]",ey="[object Date]",ty="[object Error]",ry="[object Function]",sy="[object Map]",oy="[object Number]",ny="[object Object]",iy="[object RegExp]",ay="[object Set]",ly="[object String]",uy="[object WeakMap]",cy="[object ArrayBuffer]",dy="[object DataView]",fy="[object Float32Array]",py="[object Float64Array]",hy="[object Int8Array]",yy="[object Int16Array]",gy="[object Int32Array]",my="[object Uint8Array]",vy="[object Uint8ClampedArray]",by="[object Uint16Array]",ky="[object Uint32Array]",D={};D[fy]=D[py]=D[hy]=D[yy]=D[gy]=D[my]=D[vy]=D[by]=D[ky]=!0,D[Zh]=D[Yh]=D[cy]=D[Xh]=D[dy]=D[ey]=D[ty]=D[ry]=D[sy]=D[oy]=D[ny]=D[iy]=D[ay]=D[ly]=D[uy]=!1;function wy(r){return Ke(r)&&un(r.length)&&!!D[Oe(r)]}function Or(r){return function(e){return r(e)}}var mn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ut=mn&&typeof module=="object"&&module&&!module.nodeType&&module,Ay=ut&&ut.exports===mn,Kr=Ay&&Zo.process,qe=(function(){try{var r=ut&&ut.require&&ut.require("util").types;return r||Kr&&Kr.binding&&Kr.binding("util")}catch{}})(),vn=qe&&qe.isTypedArray,$y=vn?Or(vn):wy,Cy=Object.prototype,Dy=Cy.hasOwnProperty;function Py(r,e){var t=Fe(r),s=!t&&Lh(r),o=!t&&!s&&gn(r),n=!t&&!s&&!o&&$y(r),i=t||s||o||n,a=i?Gh(r.length,String):[],l=a.length;for(var u in r)Dy.call(r,u)&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||n&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Th(u,l)))&&a.push(u);return a}function bn(r,e){return function(t){return r(e(t))}}var _y=bn(Object.keys,Object),xy=Object.prototype,Ey=xy.hasOwnProperty;function jy(r){if(!cn(r))return _y(r);var e=[];for(var t in Object(r))Ey.call(r,t)&&t!="constructor"&&e.push(t);return e}function Sy(r){return Bh(r)?Py(r):jy(r)}var My=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ry=/^\w*$/;function Iy(r,e){if(Fe(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Rr(r)?!0:Ry.test(r)||!My.test(r)||e!=null&&r in Object(e)}var ct=Ae(Object,"create");function Ty(){this.__data__=ct?ct(null):{},this.size=0}function Oy(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Ky="__lodash_hash_undefined__",Fy=Object.prototype,qy=Fy.hasOwnProperty;function Qy(r){var e=this.__data__;if(ct){var t=e[r];return t===Ky?void 0:t}return qy.call(e,r)?e[r]:void 0}var By=Object.prototype,Vy=By.hasOwnProperty;function Gy(r){var e=this.__data__;return ct?e[r]!==void 0:Vy.call(e,r)}var Uy="__lodash_hash_undefined__";function Ny(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=ct&&e===void 0?Uy:e,this}function $e(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])}}$e.prototype.clear=Ty,$e.prototype.delete=Oy,$e.prototype.get=Qy,$e.prototype.has=Gy,$e.prototype.set=Ny;function zy(){this.__data__=[],this.size=0}function Kt(r,e){for(var t=r.length;t--;)if(ln(r[t][0],e))return t;return-1}var Ly=Array.prototype,Wy=Ly.splice;function Hy(r){var e=this.__data__,t=Kt(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Wy.call(e,t,1),--this.size,!0}function Jy(r){var e=this.__data__,t=Kt(e,r);return t<0?void 0:e[t][1]}function Zy(r){return Kt(this.__data__,r)>-1}function Yy(r,e){var t=this.__data__,s=Kt(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function oe(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])}}oe.prototype.clear=zy,oe.prototype.delete=Hy,oe.prototype.get=Jy,oe.prototype.has=Zy,oe.prototype.set=Yy;var dt=Ae(Z,"Map");function Xy(){this.size=0,this.__data__={hash:new $e,map:new(dt||oe),string:new $e}}function eg(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Ft(r,e){var t=r.__data__;return eg(e)?t[typeof e=="string"?"string":"hash"]:t.map}function tg(r){var e=Ft(this,r).delete(r);return this.size-=e?1:0,e}function rg(r){return Ft(this,r).get(r)}function sg(r){return Ft(this,r).has(r)}function og(r,e){var t=Ft(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,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=Xy,ce.prototype.delete=tg,ce.prototype.get=rg,ce.prototype.has=sg,ce.prototype.set=og;var ng="Expected a function";function Fr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(ng);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(Fr.Cache||ce),t}Fr.Cache=ce;var ig=500;function ag(r){var e=Fr(r,function(s){return t.size===ig&&t.clear(),s}),t=e.cache;return e}var lg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ug=/\\(\\)?/g,cg=ag(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(lg,function(t,s,o,n){e.push(o?n.replace(ug,"$1"):s||t)}),e});function dg(r){return r==null?"":rn(r)}function fg(r,e){return Fe(r)?r:Iy(r,e)?[r]:cg(dg(r))}function pg(r){if(typeof r=="string"||Rr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function hg(r,e){e=fg(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[pg(e[t++])];return t&&t==s?r:void 0}function yg(r,e,t){var s=r==null?void 0:hg(r,e);return s===void 0?t:s}function gg(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var mg=bn(Object.getPrototypeOf,Object);function vg(){this.__data__=new oe,this.size=0}function bg(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function kg(r){return this.__data__.get(r)}function wg(r){return this.__data__.has(r)}var Ag=200;function $g(r,e){var t=this.__data__;if(t instanceof oe){var s=t.__data__;if(!dt||s.length<Ag-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new ce(s)}return t.set(r,e),this.size=t.size,this}function Qe(r){var e=this.__data__=new oe(r);this.size=e.size}Qe.prototype.clear=vg,Qe.prototype.delete=bg,Qe.prototype.get=kg,Qe.prototype.has=wg,Qe.prototype.set=$g;var kn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,wn=kn&&typeof module=="object"&&module&&!module.nodeType&&module,Cg=wn&&wn.exports===kn,An=Cg?Z.Buffer:void 0;An&&An.allocUnsafe;function Dg(r,e){return r.slice()}function Pg(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 _g(){return[]}var xg=Object.prototype,Eg=xg.propertyIsEnumerable,$n=Object.getOwnPropertySymbols,jg=$n?function(r){return r==null?[]:(r=Object(r),Pg($n(r),function(e){return Eg.call(r,e)}))}:_g;function Sg(r,e,t){var s=e(r);return Fe(r)?s:gg(s,t(r))}function Mg(r){return Sg(r,Sy,jg)}var qr=Ae(Z,"DataView"),Qr=Ae(Z,"Promise"),Br=Ae(Z,"Set"),Cn="[object Map]",Rg="[object Object]",Dn="[object Promise]",Pn="[object Set]",_n="[object WeakMap]",xn="[object DataView]",Ig=we(qr),Tg=we(dt),Og=we(Qr),Kg=we(Br),Fg=we(Tr),ne=Oe;(qr&&ne(new qr(new ArrayBuffer(1)))!=xn||dt&&ne(new dt)!=Cn||Qr&&ne(Qr.resolve())!=Dn||Br&&ne(new Br)!=Pn||Tr&&ne(new Tr)!=_n)&&(ne=function(r){var e=Oe(r),t=e==Rg?r.constructor:void 0,s=t?we(t):"";if(s)switch(s){case Ig:return xn;case Tg:return Cn;case Og:return Dn;case Kg:return Pn;case Fg:return _n}return e});var qg=Object.prototype,Qg=qg.hasOwnProperty;function Bg(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Qg.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var En=Z.Uint8Array;function Vr(r){var e=new r.constructor(r.byteLength);return new En(e).set(new En(r)),e}function Vg(r,e){var t=Vr(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Gg=/\w*$/;function Ug(r){var e=new r.constructor(r.source,Gg.exec(r));return e.lastIndex=r.lastIndex,e}var jn=ue?ue.prototype:void 0,Sn=jn?jn.valueOf:void 0;function Ng(r){return Sn?Object(Sn.call(r)):{}}function zg(r,e){var t=Vr(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var Lg="[object Boolean]",Wg="[object Date]",Hg="[object Map]",Jg="[object Number]",Zg="[object RegExp]",Yg="[object Set]",Xg="[object String]",em="[object Symbol]",tm="[object ArrayBuffer]",rm="[object DataView]",sm="[object Float32Array]",om="[object Float64Array]",nm="[object Int8Array]",im="[object Int16Array]",am="[object Int32Array]",lm="[object Uint8Array]",um="[object Uint8ClampedArray]",cm="[object Uint16Array]",dm="[object Uint32Array]";function fm(r,e,t){var s=r.constructor;switch(e){case tm:return Vr(r);case Lg:case Wg:return new s(+r);case rm:return Vg(r);case sm:case om:case nm:case im:case am:case lm:case um:case cm:case dm:return zg(r);case Hg:return new s;case Jg:case Xg:return new s(r);case Zg:return Ug(r);case Yg:return new s;case em:return Ng(r)}}function pm(r){return typeof r.constructor=="function"&&!cn(r)?Sh(mg(r)):{}}var hm="[object Map]";function ym(r){return Ke(r)&&ne(r)==hm}var Mn=qe&&qe.isMap,gm=Mn?Or(Mn):ym,mm="[object Set]";function vm(r){return Ke(r)&&ne(r)==mm}var Rn=qe&&qe.isSet,bm=Rn?Or(Rn):vm,In="[object Arguments]",km="[object Array]",wm="[object Boolean]",Am="[object Date]",$m="[object Error]",Tn="[object Function]",Cm="[object GeneratorFunction]",Dm="[object Map]",Pm="[object Number]",On="[object Object]",_m="[object RegExp]",xm="[object Set]",Em="[object String]",jm="[object Symbol]",Sm="[object WeakMap]",Mm="[object ArrayBuffer]",Rm="[object DataView]",Im="[object Float32Array]",Tm="[object Float64Array]",Om="[object Int8Array]",Km="[object Int16Array]",Fm="[object Int32Array]",qm="[object Uint8Array]",Qm="[object Uint8ClampedArray]",Bm="[object Uint16Array]",Vm="[object Uint32Array]",A={};A[In]=A[km]=A[Mm]=A[Rm]=A[wm]=A[Am]=A[Im]=A[Tm]=A[Om]=A[Km]=A[Fm]=A[Dm]=A[Pm]=A[On]=A[_m]=A[xm]=A[Em]=A[jm]=A[qm]=A[Qm]=A[Bm]=A[Vm]=!0,A[$m]=A[Tn]=A[Sm]=!1;function qt(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Ot(r))return r;var a=Fe(r);if(a)i=Bg(r);else{var l=ne(r),u=l==Tn||l==Cm;if(gn(r))return Dg(r);if(l==On||l==In||u&&!o)i=u?{}:pm(r);else{if(!A[l])return o?r:{};i=fm(r,l)}}n||(n=new Qe);var c=n.get(r);if(c)return c;n.set(r,i),bm(r)?r.forEach(function(h){i.add(qt(h,e,t,h,r,n))}):gm(r)&&r.forEach(function(h,p){i.set(p,qt(h,e,t,p,r,n))});var d=Mg,f=a?void 0:d(r);return Mh(f||r,function(h,p){f&&(p=h,h=r[p]),qh(i,p,qt(h,e,t,p,r,n))}),i}var Gm=1,Um=4;function Nm(r){return qt(r,Gm|Um)}function zm(r){const e=Gr(r);return Lm(e)}function Gr(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(Gr).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+Gr(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function Lm(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 Ur=new S;function Nr(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 Wm=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):Nm(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=Nr();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},Hm="k:",Jm="h:";function zr(r,e=0){if(r.key)return`${Hm}${r.key}`;const t=zm({type:r.type,url:r.rawUrl??r.url,model:r.model??"",occurrence:e});return`${Jm}${t}`}function Zm(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=zr(s,n);for(;t.has(i);)n+=1,i=s.key?`${zr(s)}#${n}`:zr(s,n);return e.set(o,n+1),t.add(i),i})}const Qt=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>yg(e,s.trim(),""))):"",Ym=r=>{const e=new Set;return r.replace(/\$\{(.*?)\}/g,(t,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(t=>({name:t}))}};let Xm=class{log=Ur.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],M=r[g+1];if(o&&m===o&&!y&&p.length===0){for(;g<f&&r[g]!==`
10
+ `;)g++;continue}if(m===`
11
+ `||m==="\r"&&M===`
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"&&M===`
13
+ `?1:0;continue}else if(m===k&&!y)h.push(p),p="";else if(m===t)y?M===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
+ `)),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 Bn(r,e=","){return r&&typeof r=="string"?r.split(e).map(t=>t.trim()):[]}class ev{loader;log=Ur.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"?Bn(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 Bn(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 Xm().parse(e,i),sourceColumns:o,coercionFailureSamples:n}}}var Vn=typeof global=="object"&&global&&global.Object===Object&&global,tv=typeof self=="object"&&self&&self.Object===Object&&self,Y=Vn||tv||Function("return this")(),de=Y.Symbol,Gn=Object.prototype,rv=Gn.hasOwnProperty,sv=Gn.toString,ft=de?de.toStringTag:void 0;function ov(r){var e=rv.call(r,ft),t=r[ft];try{r[ft]=void 0;var s=!0}catch{}var o=sv.call(r);return s&&(e?r[ft]=t:delete r[ft]),o}var nv=Object.prototype,iv=nv.toString;function av(r){return iv.call(r)}var lv="[object Null]",uv="[object Undefined]",Un=de?de.toStringTag:void 0;function Be(r){return r==null?r===void 0?uv:lv:Un&&Un in Object(r)?ov(r):av(r)}function Ce(r){return r!=null&&typeof r=="object"}var cv="[object Symbol]";function Lr(r){return typeof r=="symbol"||Ce(r)&&Be(r)==cv}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 Ve=Array.isArray,zn=de?de.prototype:void 0,Ln=zn?zn.toString:void 0;function Wn(r){if(typeof r=="string")return r;if(Ve(r))return Nn(r,Wn)+"";if(Lr(r))return Ln?Ln.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Bt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}function Hn(r){return r}var dv="[object AsyncFunction]",fv="[object Function]",pv="[object GeneratorFunction]",hv="[object Proxy]";function Jn(r){if(!Bt(r))return!1;var e=Be(r);return e==fv||e==pv||e==dv||e==hv}var Wr=Y["__core-js_shared__"],Zn=(function(){var r=/[^.]+$/.exec(Wr&&Wr.keys&&Wr.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function yv(r){return!!Zn&&Zn in r}var gv=Function.prototype,mv=gv.toString;function De(r){if(r!=null){try{return mv.call(r)}catch{}try{return r+""}catch{}}return""}var vv=/[\\^$.*+?()[\]{}|]/g,bv=/^\[object .+?Constructor\]$/,kv=Function.prototype,wv=Object.prototype,Av=kv.toString,$v=wv.hasOwnProperty,Cv=RegExp("^"+Av.call($v).replace(vv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Dv(r){if(!Bt(r)||yv(r))return!1;var e=Jn(r)?Cv:bv;return e.test(De(r))}function Pv(r,e){return r?.[e]}function Pe(r,e){var t=Pv(r,e);return Dv(t)?t:void 0}var Hr=Pe(Y,"WeakMap"),Yn=Object.create,_v=(function(){function r(){}return function(e){if(!Bt(e))return{};if(Yn)return Yn(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function xv(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 Ev=800,jv=16,Sv=Date.now;function Mv(r){var e=0,t=0;return function(){var s=Sv(),o=jv-(s-t);if(t=s,o>0){if(++e>=Ev)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function Rv(r){return function(){return r}}var Vt=(function(){try{var r=Pe(Object,"defineProperty");return r({},"",{}),r}catch{}})(),Iv=Vt?function(r,e){return Vt(r,"toString",{configurable:!0,enumerable:!1,value:Rv(e),writable:!0})}:Hn,Tv=Mv(Iv);function Ov(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function Kv(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 Fv(r){return r!==r}function qv(r,e,t){for(var s=t-1,o=r.length;++s<o;)if(r[s]===e)return s;return-1}function Qv(r,e,t){return e===e?qv(r,e,t):Kv(r,Fv,t)}function Bv(r,e){var t=r==null?0:r.length;return!!t&&Qv(r,e,0)>-1}var Vv=9007199254740991,Gv=/^(?:0|[1-9]\d*)$/;function Uv(r,e){var t=typeof r;return e=e??Vv,!!e&&(t=="number"||t!="symbol"&&Gv.test(r))&&r>-1&&r%1==0&&r<e}function Nv(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 zv=Object.prototype,Lv=zv.hasOwnProperty;function Wv(r,e,t){var s=r[e];(!(Lv.call(r,e)&&Xn(s,t))||t===void 0&&!(e in r))&&Nv(r,e,t)}var ei=Math.max;function Hv(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),xv(r,this,a)}}function Jv(r,e){return Tv(Hv(r,e,Hn),r+"")}var Zv=9007199254740991;function ti(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Zv}function ri(r){return r!=null&&ti(r.length)&&!Jn(r)}var Yv=Object.prototype;function si(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Yv;return r===t}function Xv(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var eb="[object Arguments]";function oi(r){return Ce(r)&&Be(r)==eb}var ni=Object.prototype,tb=ni.hasOwnProperty,rb=ni.propertyIsEnumerable,sb=oi((function(){return arguments})())?oi:function(r){return Ce(r)&&tb.call(r,"callee")&&!rb.call(r,"callee")};function ob(){return!1}var ii=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ai=ii&&typeof module=="object"&&module&&!module.nodeType&&module,nb=ai&&ai.exports===ii,li=nb?Y.Buffer:void 0,ib=li?li.isBuffer:void 0,ui=ib||ob,ab="[object Arguments]",lb="[object Array]",ub="[object Boolean]",cb="[object Date]",db="[object Error]",fb="[object Function]",pb="[object Map]",hb="[object Number]",yb="[object Object]",gb="[object RegExp]",mb="[object Set]",vb="[object String]",bb="[object WeakMap]",kb="[object ArrayBuffer]",wb="[object DataView]",Ab="[object Float32Array]",$b="[object Float64Array]",Cb="[object Int8Array]",Db="[object Int16Array]",Pb="[object Int32Array]",_b="[object Uint8Array]",xb="[object Uint8ClampedArray]",Eb="[object Uint16Array]",jb="[object Uint32Array]",P={};P[Ab]=P[$b]=P[Cb]=P[Db]=P[Pb]=P[_b]=P[xb]=P[Eb]=P[jb]=!0,P[ab]=P[lb]=P[kb]=P[ub]=P[wb]=P[cb]=P[db]=P[fb]=P[pb]=P[hb]=P[yb]=P[gb]=P[mb]=P[vb]=P[bb]=!1;function Sb(r){return Ce(r)&&ti(r.length)&&!!P[Be(r)]}function Jr(r){return function(e){return r(e)}}var ci=typeof exports=="object"&&exports&&!exports.nodeType&&exports,pt=ci&&typeof module=="object"&&module&&!module.nodeType&&module,Mb=pt&&pt.exports===ci,Zr=Mb&&Vn.process,Ge=(function(){try{var r=pt&&pt.require&&pt.require("util").types;return r||Zr&&Zr.binding&&Zr.binding("util")}catch{}})(),di=Ge&&Ge.isTypedArray,Rb=di?Jr(di):Sb,Ib=Object.prototype,Tb=Ib.hasOwnProperty;function Ob(r,e){var t=Ve(r),s=!t&&sb(r),o=!t&&!s&&ui(r),n=!t&&!s&&!o&&Rb(r),i=t||s||o||n,a=i?Xv(r.length,String):[],l=a.length;for(var u in r)Tb.call(r,u)&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||n&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Uv(u,l)))&&a.push(u);return a}function fi(r,e){return function(t){return r(e(t))}}var Kb=fi(Object.keys,Object),Fb=Object.prototype,qb=Fb.hasOwnProperty;function Qb(r){if(!si(r))return Kb(r);var e=[];for(var t in Object(r))qb.call(r,t)&&t!="constructor"&&e.push(t);return e}function Bb(r){return ri(r)?Ob(r):Qb(r)}var Vb=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Gb=/^\w*$/;function Ub(r,e){if(Ve(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Lr(r)?!0:Gb.test(r)||!Vb.test(r)||e!=null&&r in Object(e)}var ht=Pe(Object,"create");function Nb(){this.__data__=ht?ht(null):{},this.size=0}function zb(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Lb="__lodash_hash_undefined__",Wb=Object.prototype,Hb=Wb.hasOwnProperty;function Jb(r){var e=this.__data__;if(ht){var t=e[r];return t===Lb?void 0:t}return Hb.call(e,r)?e[r]:void 0}var Zb=Object.prototype,Yb=Zb.hasOwnProperty;function Xb(r){var e=this.__data__;return ht?e[r]!==void 0:Yb.call(e,r)}var ek="__lodash_hash_undefined__";function tk(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=ht&&e===void 0?ek:e,this}function _e(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])}}_e.prototype.clear=Nb,_e.prototype.delete=zb,_e.prototype.get=Jb,_e.prototype.has=Xb,_e.prototype.set=tk;function rk(){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 sk=Array.prototype,ok=sk.splice;function nk(r){var e=this.__data__,t=Gt(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():ok.call(e,t,1),--this.size,!0}function ik(r){var e=this.__data__,t=Gt(e,r);return t<0?void 0:e[t][1]}function ak(r){return Gt(this.__data__,r)>-1}function lk(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 ie(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])}}ie.prototype.clear=rk,ie.prototype.delete=nk,ie.prototype.get=ik,ie.prototype.has=ak,ie.prototype.set=lk;var yt=Pe(Y,"Map");function uk(){this.size=0,this.__data__={hash:new _e,map:new(yt||ie),string:new _e}}function ck(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Ut(r,e){var t=r.__data__;return ck(e)?t[typeof e=="string"?"string":"hash"]:t.map}function dk(r){var e=Ut(this,r).delete(r);return this.size-=e?1:0,e}function fk(r){return Ut(this,r).get(r)}function pk(r){return Ut(this,r).has(r)}function hk(r,e){var t=Ut(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,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=uk,ae.prototype.delete=dk,ae.prototype.get=fk,ae.prototype.has=pk,ae.prototype.set=hk;var yk="Expected a function";function Yr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(yk);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(Yr.Cache||ae),t}Yr.Cache=ae;var gk=500;function mk(r){var e=Yr(r,function(s){return t.size===gk&&t.clear(),s}),t=e.cache;return e}var vk=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,bk=/\\(\\)?/g,kk=mk(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(vk,function(t,s,o,n){e.push(o?n.replace(bk,"$1"):s||t)}),e});function wk(r){return r==null?"":Wn(r)}function Ak(r,e){return Ve(r)?r:Ub(r,e)?[r]:kk(wk(r))}function $k(r){if(typeof r=="string"||Lr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Ck(r,e){e=Ak(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 Dk(r,e,t){var s=r==null?void 0:Ck(r,e);return s===void 0?t:s}function Pk(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var _k=fi(Object.getPrototypeOf,Object);function xk(){this.__data__=new ie,this.size=0}function Ek(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function jk(r){return this.__data__.get(r)}function Sk(r){return this.__data__.has(r)}var Mk=200;function Rk(r,e){var t=this.__data__;if(t instanceof ie){var s=t.__data__;if(!yt||s.length<Mk-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new ae(s)}return t.set(r,e),this.size=t.size,this}function Ue(r){var e=this.__data__=new ie(r);this.size=e.size}Ue.prototype.clear=xk,Ue.prototype.delete=Ek,Ue.prototype.get=jk,Ue.prototype.has=Sk,Ue.prototype.set=Rk;var pi=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hi=pi&&typeof module=="object"&&module&&!module.nodeType&&module,Ik=hi&&hi.exports===pi,yi=Ik?Y.Buffer:void 0;yi&&yi.allocUnsafe;function Tk(r,e){return r.slice()}function Ok(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 Kk(){return[]}var Fk=Object.prototype,qk=Fk.propertyIsEnumerable,gi=Object.getOwnPropertySymbols,Qk=gi?function(r){return r==null?[]:(r=Object(r),Ok(gi(r),function(e){return qk.call(r,e)}))}:Kk;function Bk(r,e,t){var s=e(r);return Ve(r)?s:Pk(s,t(r))}function Vk(r){return Bk(r,Bb,Qk)}var Xr=Pe(Y,"DataView"),es=Pe(Y,"Promise"),ts=Pe(Y,"Set"),mi="[object Map]",Gk="[object Object]",vi="[object Promise]",bi="[object Set]",ki="[object WeakMap]",wi="[object DataView]",Uk=De(Xr),Nk=De(yt),zk=De(es),Lk=De(ts),Wk=De(Hr),le=Be;(Xr&&le(new Xr(new ArrayBuffer(1)))!=wi||yt&&le(new yt)!=mi||es&&le(es.resolve())!=vi||ts&&le(new ts)!=bi||Hr&&le(new Hr)!=ki)&&(le=function(r){var e=Be(r),t=e==Gk?r.constructor:void 0,s=t?De(t):"";if(s)switch(s){case Uk:return wi;case Nk:return mi;case zk:return vi;case Lk:return bi;case Wk:return ki}return e});var Hk=Object.prototype,Jk=Hk.hasOwnProperty;function Zk(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Jk.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var Ai=Y.Uint8Array;function rs(r){var e=new r.constructor(r.byteLength);return new Ai(e).set(new Ai(r)),e}function Yk(r,e){var t=rs(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Xk=/\w*$/;function ew(r){var e=new r.constructor(r.source,Xk.exec(r));return e.lastIndex=r.lastIndex,e}var $i=de?de.prototype:void 0,Ci=$i?$i.valueOf:void 0;function tw(r){return Ci?Object(Ci.call(r)):{}}function rw(r,e){var t=rs(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var sw="[object Boolean]",ow="[object Date]",nw="[object Map]",iw="[object Number]",aw="[object RegExp]",lw="[object Set]",uw="[object String]",cw="[object Symbol]",dw="[object ArrayBuffer]",fw="[object DataView]",pw="[object Float32Array]",hw="[object Float64Array]",yw="[object Int8Array]",gw="[object Int16Array]",mw="[object Int32Array]",vw="[object Uint8Array]",bw="[object Uint8ClampedArray]",kw="[object Uint16Array]",ww="[object Uint32Array]";function Aw(r,e,t){var s=r.constructor;switch(e){case dw:return rs(r);case sw:case ow:return new s(+r);case fw:return Yk(r);case pw:case hw:case yw:case gw:case mw:case vw:case bw:case kw:case ww:return rw(r);case nw:return new s;case iw:case uw:return new s(r);case aw:return ew(r);case lw:return new s;case cw:return tw(r)}}function $w(r){return typeof r.constructor=="function"&&!si(r)?_v(_k(r)):{}}var Cw="[object Map]";function Dw(r){return Ce(r)&&le(r)==Cw}var Di=Ge&&Ge.isMap,Pw=Di?Jr(Di):Dw,_w="[object Set]";function xw(r){return Ce(r)&&le(r)==_w}var Pi=Ge&&Ge.isSet,Ew=Pi?Jr(Pi):xw,_i="[object Arguments]",jw="[object Array]",Sw="[object Boolean]",Mw="[object Date]",Rw="[object Error]",xi="[object Function]",Iw="[object GeneratorFunction]",Tw="[object Map]",Ow="[object Number]",Ei="[object Object]",Kw="[object RegExp]",Fw="[object Set]",qw="[object String]",Qw="[object Symbol]",Bw="[object WeakMap]",Vw="[object ArrayBuffer]",Gw="[object DataView]",Uw="[object Float32Array]",Nw="[object Float64Array]",zw="[object Int8Array]",Lw="[object Int16Array]",Ww="[object Int32Array]",Hw="[object Uint8Array]",Jw="[object Uint8ClampedArray]",Zw="[object Uint16Array]",Yw="[object Uint32Array]",$={};$[_i]=$[jw]=$[Vw]=$[Gw]=$[Sw]=$[Mw]=$[Uw]=$[Nw]=$[zw]=$[Lw]=$[Ww]=$[Tw]=$[Ow]=$[Ei]=$[Kw]=$[Fw]=$[qw]=$[Qw]=$[Hw]=$[Jw]=$[Zw]=$[Yw]=!0,$[Rw]=$[xi]=$[Bw]=!1;function Nt(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Bt(r))return r;var a=Ve(r);if(a)i=Zk(r);else{var l=le(r),u=l==xi||l==Iw;if(ui(r))return Tk(r);if(l==Ei||l==_i||u&&!o)i=u?{}:$w(r);else{if(!$[l])return o?r:{};i=Aw(r,l)}}n||(n=new Ue);var c=n.get(r);if(c)return c;n.set(r,i),Ew(r)?r.forEach(function(h){i.add(Nt(h,e,t,h,r,n))}):Pw(r)&&r.forEach(function(h,p){i.set(p,Nt(h,e,t,p,r,n))});var d=Vk,f=a?void 0:d(r);return Ov(f||r,function(h,p){f&&(p=h,h=r[p]),Wv(i,p,Nt(h,e,t,p,r,n))}),i}var Xw=1,eA=4;function gt(r){return Nt(r,Xw|eA)}var tA="__lodash_hash_undefined__";function rA(r){return this.__data__.set(r,tA),this}function sA(r){return this.__data__.has(r)}function zt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new ae;++e<t;)this.add(r[e])}zt.prototype.add=zt.prototype.push=rA,zt.prototype.has=sA;function ji(r,e){return r.has(e)}function oA(r){return Ce(r)&&ri(r)}var nA=Math.min;function iA(r,e,t){for(var s=Bv,o=r[0].length,n=r.length,i=n,a=Array(n),l=1/0,u=[];i--;){var c=r[i];l=nA(c.length,l),a[i]=o>=120&&c.length>=120?new zt(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 aA(r){return oA(r)?r:[]}var Si=Jv(function(r){var e=Nn(r,aA);return e.length&&e[0]===r[0]?iA(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=gt(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 lA(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 uA(r,e){return Ym(r).variables.map(t=>t.name).filter(t=>Dk(e,t)===void 0)}function Ri(r,e,t){const s={applicationKey:t?.applicationKey,resourceTags:t?.resourceTags,environmentKeys:t?.environmentKeys},o=r?.resources??[],n=Zm(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(!lA(u.tags,t.resourceTags)){a.push({resource:u,reason:"tag-mismatch",id:n[c]});return}}const d=u.url??"",f=uA(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 cA=Object.defineProperty,dA=Object.getOwnPropertyDescriptor,Ii=(r,e,t,s)=>{for(var o=dA(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&cA(e,t,o),o};const fA={missingModelHandling:{autoGenerateProperties:!0},defaultDataContainerUpdateType:"set",csvParserOptions:{delimiter:"",quoteChar:'"',escapeChar:'"',commentChar:void 0}};let ss=class{key;core;cdRef=new Wm;log=Ur.child({prefix:"AppLoader"});registeredTransformers=[];options=fA;csvParser=new ev(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:()=>gt(this.currentConfig),set:r=>{this.currentConfig=gt(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 ${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 ${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=Nr();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=gt(r),t=gt(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){return r.includes("cdn.dcupl.com")}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 ${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 ${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 ${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=Nr(),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 ${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 vt=[],Lt=this.core.modelParser.unprocessedModelDescriptions.get(a.model);if(!Lt&&(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}),Lt=this.core.modelParser.unprocessedModelDescriptions.get(a.model)}const yA=F.now();let Ti={sourceColumns:[],coercionFailureSamples:{},origin:a.url};if(a.url.endsWith(".csv")||y?.includes("text/csv")){if(Lt){const q=this.csvParser.getJsonFromCSVStringWithMetadata(M,Lt,a);vt=q.data,Ti={sourceColumns:q.sourceColumns,coercionFailureSamples:q.coercionFailureSamples,origin:a.url}}}else vt=M;const gA=F.now(),mA=F.now();try{vt=this.handleTransformerLogic(vt,a,"parsedFileTransformer",n||[])}catch(q){this.log.error("Transformer error",q,{resource:a.url,model:a.model})}const vA=F.now(),Oi={placeholderUid:l,model:a.model,data:vt,type:a.options?.updateType||t.defaultDataContainerUpdateType,keyProperty:a?.options?.keyProperty,keyPropertySeparator:a?.options?.keyPropertySeparator,autoGenerateKey:a.options?.autoGenerateKey,autoGenerateProperties:a.options?.autoGenerateProperties},os=F.getEntriesByName(f.toString());if(Array.isArray(os)&&os[0]){const q=os[0],kA={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:yA,csvToJsonEnd:gA,parsedTransformStart:mA,parsedTransformEnd:vA,decodedBodySize:q.decodedBodySize,encodedBodySize:q.encodedBodySize,end:k}};this.core.analyticsController.set({value:kA,context:this.currentContext})}this.core.updateRegisteredContainer(Oi,Ti);const bA=this.progressHandler.update(a,!0,"data",d);return this.updateProgressListeners(bA),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})],ss.prototype,"fetchConfig"),Ii([Qn({scope:"global",origin:"loader",type:"loader_processed",connectMessage:!0})],ss.prototype,"process");const pA=ss;let mt,Ne;async function hA(r){return mt=new sh(r.options),Ne=new pA,mt.loaders.add(Ne,"default"),r.appLoaderConfig?await Ne.config.fetch(r.appLoaderConfig):await Ne.config.fetch(),await Ne.process(r.processOptions),await mt.init(),globalThis.dcupl=mt,{dcupl:mt,loader:Ne}}globalThis.initDcupl=hA})();
16
+ //# sourceMappingURL=dcupl.bundle.min.js.map