@dcupl/bundle 2.0.0-beta.13 → 2.0.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
- (function(){"use strict";var R=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},O={searchParams:"URLSearchParams"in R,iterable:"Symbol"in R&&"iterator"in Symbol,blob:"FileReader"in R&&"Blob"in R&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in R,arrayBuffer:"ArrayBuffer"in R};function qi(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]"],Bi=ArrayBuffer.isView||function(r){return r&&Qi.indexOf(Object.prototype.toString.call(r))>-1};function Ee(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(r)||r==="")throw new TypeError('Invalid character in header field name: "'+r+'"');return r.toLowerCase()}function Ht(r){return typeof r!="string"&&(r=String(r)),r}function Jt(r){var e={next:function(){var t=r.shift();return{done:t===void 0,value:t}}};return O.iterable&&(e[Symbol.iterator]=function(){return e}),e}function x(r){this.map={},r instanceof x?r.forEach(function(e,t){this.append(t,e)},this):Array.isArray(r)?r.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(e){this.append(e,r[e])},this)}x.prototype.append=function(r,e){r=Ee(r),e=Ht(e);var t=this.map[r];this.map[r]=t?t+", "+e:e},x.prototype.delete=function(r){delete this.map[Ee(r)]},x.prototype.get=function(r){return r=Ee(r),this.has(r)?this.map[r]:null},x.prototype.has=function(r){return this.map.hasOwnProperty(Ee(r))},x.prototype.set=function(r,e){this.map[Ee(r)]=Ht(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)}),Jt(r)},x.prototype.values=function(){var r=[];return this.forEach(function(e){r.push(e)}),Jt(r)},x.prototype.entries=function(){var r=[];return this.forEach(function(e,t){r.push([t,e])}),Jt(r)},O.iterable&&(x.prototype[Symbol.iterator]=x.prototype.entries);function Zt(r){if(!r._noBody){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}}function is(r){return new Promise(function(e,t){r.onload=function(){e(r.result)},r.onerror=function(){t(r.error)}})}function Vi(r){var e=new FileReader,t=is(e);return e.readAsArrayBuffer(r),t}function Gi(r){var e=new FileReader,t=is(e),s=/charset=([A-Za-z0-9_-]+)/.exec(r.type),o=s?s[1]:"utf-8";return e.readAsText(r,o),t}function Ui(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 as(r){if(r.slice)return r.slice(0);var e=new Uint8Array(r.byteLength);return e.set(new Uint8Array(r)),e.buffer}function ls(){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&&qi(r)?(this._bodyArrayBuffer=as(r.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):O.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(r)||Bi(r))?this._bodyArrayBuffer=as(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=Zt(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=Zt(this);return r||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(O.blob)return this.blob().then(Vi);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var r=Zt(this);if(r)return r;if(this._bodyBlob)return Gi(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(Ui(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(Li)}),this.json=function(){return this.text().then(JSON.parse)},this}var Ni=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function zi(r){var e=r.toUpperCase();return Ni.indexOf(e)>-1?e:r}function pe(r,e){if(!(this instanceof pe))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 pe){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=zi(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()}}}pe.prototype.clone=function(){return new pe(this,{body:this._bodyInit})};function Li(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 Wi(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}ls.call(pe.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)}ls.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 Hi=[301,302,303,307,308];H.redirect=function(r,e){if(Hi.indexOf(e)===-1)throw new RangeError("Invalid status code");return new H(null,{status:e,headers:{location:r}})};var he=R.DOMException;try{new he}catch{he=function(e,t){this.message=e,this.name=t;var s=Error(e);this.stack=s.stack},he.prototype=Object.create(Error.prototype),he.prototype.constructor=he}function cs(r,e){return new Promise(function(t,s){var o=new pe(r,e);if(o.signal&&o.signal.aborted)return s(new he("Aborted","AbortError"));var n=new XMLHttpRequest;function i(){n.abort()}n.onload=function(){var c={statusText:n.statusText,headers:Wi(n.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(n.status<200||n.status>599)?c.status=200:c.status=n.status,c.url="responseURL"in n?n.responseURL:c.headers.get("X-Request-URL");var u="response"in n?n.response:n.responseText;setTimeout(function(){t(new H(u,c))},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 he("Aborted","AbortError"))},0)};function a(c){try{return c===""&&R.location.href?R.location.href:c}catch{return c}}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(c){l.push(Ee(c)),n.setRequestHeader(c,Ht(e.headers[c]))}),o.headers.forEach(function(c,u){l.indexOf(u)===-1&&n.setRequestHeader(u,c)})}else o.headers.forEach(function(c,u){n.setRequestHeader(u,c)});o.signal&&(o.signal.addEventListener("abort",i),n.onreadystatechange=function(){n.readyState===4&&o.signal.removeEventListener("abort",i)}),n.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}cs.polyfill=!0,R.fetch||(R.fetch=cs,R.Headers=x,R.Request=pe,R.Response=H);var us=typeof global=="object"&&global&&global.Object===Object&&global,Ji=typeof self=="object"&&self&&self.Object===Object&&self,J=us||Ji||Function("return this")(),G=J.Symbol,ds=Object.prototype,Zi=ds.hasOwnProperty,Yi=ds.toString,Le=G?G.toStringTag:void 0;function Xi(r){var e=Zi.call(r,Le),t=r[Le];try{r[Le]=void 0;var s=!0}catch{}var o=Yi.call(r);return s&&(e?r[Le]=t:delete r[Le]),o}var ea=Object.prototype,ta=ea.toString;function ra(r){return ta.call(r)}var sa="[object Null]",oa="[object Undefined]",fs=G?G.toStringTag:void 0;function ee(r){return r==null?r===void 0?oa:sa:fs&&fs in Object(r)?Xi(r):ra(r)}function K(r){return r!=null&&typeof r=="object"}var na="[object Symbol]";function Se(r){return typeof r=="symbol"||K(r)&&ee(r)==na}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,ps=G?G.prototype:void 0,hs=ps?ps.toString:void 0;function kt(r){if(typeof r=="string")return r;if(E(r))return je(r,kt)+"";if(Se(r))return hs?hs.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var ia=/\s/;function aa(r){for(var e=r.length;e--&&ia.test(r.charAt(e)););return e}var la=/^\s+/;function ca(r){return r&&r.slice(0,aa(r)+1).replace(la,"")}function z(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var ys=NaN,ua=/^[-+]0x[0-9a-f]+$/i,da=/^0b[01]+$/i,fa=/^0o[0-7]+$/i,pa=parseInt;function ha(r){if(typeof r=="number")return r;if(Se(r))return ys;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=ca(r);var t=da.test(r);return t||fa.test(r)?pa(r.slice(2),t?2:8):ua.test(r)?ys:+r}var gs=1/0,ya=17976931348623157e292;function ga(r){if(!r)return r===0?r:0;if(r=ha(r),r===gs||r===-gs){var e=r<0?-1:1;return e*ya}return r===r?r:0}function wt(r){var e=ga(r),t=e%1;return e===e?t?e-t:e:0}function At(r){return r}var ma="[object AsyncFunction]",va="[object Function]",ba="[object GeneratorFunction]",ka="[object Proxy]";function Yt(r){if(!z(r))return!1;var e=ee(r);return e==va||e==ba||e==ma||e==ka}var Xt=J["__core-js_shared__"],ms=(function(){var r=/[^.]+$/.exec(Xt&&Xt.keys&&Xt.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function wa(r){return!!ms&&ms in r}var Aa=Function.prototype,$a=Aa.toString;function ye(r){if(r!=null){try{return $a.call(r)}catch{}try{return r+""}catch{}}return""}var Ca=/[\\^$.*+?()[\]{}|]/g,Da=/^\[object .+?Constructor\]$/,_a=Function.prototype,Pa=Object.prototype,xa=_a.toString,Ea=Pa.hasOwnProperty,Sa=RegExp("^"+xa.call(Ea).replace(Ca,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ja(r){if(!z(r)||wa(r))return!1;var e=Yt(r)?Sa:Da;return e.test(ye(r))}function Ma(r,e){return r?.[e]}function ge(r,e){var t=Ma(r,e);return ja(t)?t:void 0}var er=ge(J,"WeakMap"),vs=Object.create,Ra=(function(){function r(){}return function(e){if(!z(e))return{};if(vs)return vs(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function Ia(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 Ta=800,Oa=16,Ka=Date.now;function Fa(r){var e=0,t=0;return function(){var s=Ka(),o=Oa-(s-t);if(t=s,o>0){if(++e>=Ta)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function qa(r){return function(){return r}}var $t=(function(){try{var r=ge(Object,"defineProperty");return r({},"",{}),r}catch{}})(),Qa=$t?function(r,e){return $t(r,"toString",{configurable:!0,enumerable:!1,value:qa(e),writable:!0})}:At,Ba=Fa(Qa);function Va(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function bs(r,e,t,s){for(var o=r.length,n=t+-1;++n<o;)if(e(r[n],n,r))return n;return-1}function Ga(r){return r!==r}function Ua(r,e,t){for(var s=t-1,o=r.length;++s<o;)if(r[s]===e)return s;return-1}function ks(r,e,t){return e===e?Ua(r,e,t):bs(r,Ga,t)}function Na(r,e){var t=r==null?0:r.length;return!!t&&ks(r,e,0)>-1}var za=9007199254740991,La=/^(?:0|[1-9]\d*)$/;function tr(r,e){var t=typeof r;return e=e??za,!!e&&(t=="number"||t!="symbol"&&La.test(r))&&r>-1&&r%1==0&&r<e}function Ct(r,e,t){e=="__proto__"&&$t?$t(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function We(r,e){return r===e||r!==r&&e!==e}var Wa=Object.prototype,Ha=Wa.hasOwnProperty;function ws(r,e,t){var s=r[e];(!(Ha.call(r,e)&&We(s,t))||t===void 0&&!(e in r))&&Ct(r,e,t)}var As=Math.max;function Ja(r,e,t){return e=As(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=As(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),Ia(r,this,a)}}function rr(r,e){return Ba(Ja(r,e,At),r+"")}var Za=9007199254740991;function sr(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Za}function te(r){return r!=null&&sr(r.length)&&!Yt(r)}var Ya=Object.prototype;function or(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Ya;return r===t}function Xa(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var el="[object Arguments]";function $s(r){return K(r)&&ee(r)==el}var Cs=Object.prototype,tl=Cs.hasOwnProperty,rl=Cs.propertyIsEnumerable,He=$s((function(){return arguments})())?$s:function(r){return K(r)&&tl.call(r,"callee")&&!rl.call(r,"callee")};function sl(){return!1}var Ds=typeof exports=="object"&&exports&&!exports.nodeType&&exports,_s=Ds&&typeof module=="object"&&module&&!module.nodeType&&module,ol=_s&&_s.exports===Ds,Ps=ol?J.Buffer:void 0,nl=Ps?Ps.isBuffer:void 0,Je=nl||sl,il="[object Arguments]",al="[object Array]",ll="[object Boolean]",cl="[object Date]",ul="[object Error]",dl="[object Function]",fl="[object Map]",pl="[object Number]",hl="[object Object]",yl="[object RegExp]",gl="[object Set]",ml="[object String]",vl="[object WeakMap]",bl="[object ArrayBuffer]",kl="[object DataView]",wl="[object Float32Array]",Al="[object Float64Array]",$l="[object Int8Array]",Cl="[object Int16Array]",Dl="[object Int32Array]",_l="[object Uint8Array]",Pl="[object Uint8ClampedArray]",xl="[object Uint16Array]",El="[object Uint32Array]",C={};C[wl]=C[Al]=C[$l]=C[Cl]=C[Dl]=C[_l]=C[Pl]=C[xl]=C[El]=!0,C[il]=C[al]=C[bl]=C[ll]=C[kl]=C[cl]=C[ul]=C[dl]=C[fl]=C[pl]=C[hl]=C[yl]=C[gl]=C[ml]=C[vl]=!1;function Sl(r){return K(r)&&sr(r.length)&&!!C[ee(r)]}function Ze(r){return function(e){return r(e)}}var xs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ye=xs&&typeof module=="object"&&module&&!module.nodeType&&module,jl=Ye&&Ye.exports===xs,nr=jl&&us.process,Me=(function(){try{var r=Ye&&Ye.require&&Ye.require("util").types;return r||nr&&nr.binding&&nr.binding("util")}catch{}})(),Es=Me&&Me.isTypedArray,ir=Es?Ze(Es):Sl,Ml=Object.prototype,Rl=Ml.hasOwnProperty;function Ss(r,e){var t=E(r),s=!t&&He(r),o=!t&&!s&&Je(r),n=!t&&!s&&!o&&ir(r),i=t||s||o||n,a=i?Xa(r.length,String):[],l=a.length;for(var c in r)(e||Rl.call(r,c))&&!(i&&(c=="length"||o&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||tr(c,l)))&&a.push(c);return a}function js(r,e){return function(t){return r(e(t))}}var Il=js(Object.keys,Object),Tl=Object.prototype,Ol=Tl.hasOwnProperty;function Ms(r){if(!or(r))return Il(r);var e=[];for(var t in Object(r))Ol.call(r,t)&&t!="constructor"&&e.push(t);return e}function Xe(r){return te(r)?Ss(r):Ms(r)}var Kl=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Fl=/^\w*$/;function ar(r,e){if(E(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Se(r)?!0:Fl.test(r)||!Kl.test(r)||e!=null&&r in Object(e)}var et=ge(Object,"create");function ql(){this.__data__=et?et(null):{},this.size=0}function Ql(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Bl="__lodash_hash_undefined__",Vl=Object.prototype,Gl=Vl.hasOwnProperty;function Ul(r){var e=this.__data__;if(et){var t=e[r];return t===Bl?void 0:t}return Gl.call(e,r)?e[r]:void 0}var Nl=Object.prototype,zl=Nl.hasOwnProperty;function Ll(r){var e=this.__data__;return et?e[r]!==void 0:zl.call(e,r)}var Wl="__lodash_hash_undefined__";function Hl(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=et&&e===void 0?Wl:e,this}function me(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])}}me.prototype.clear=ql,me.prototype.delete=Ql,me.prototype.get=Ul,me.prototype.has=Ll,me.prototype.set=Hl;function Jl(){this.__data__=[],this.size=0}function Dt(r,e){for(var t=r.length;t--;)if(We(r[t][0],e))return t;return-1}var Zl=Array.prototype,Yl=Zl.splice;function Xl(r){var e=this.__data__,t=Dt(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Yl.call(e,t,1),--this.size,!0}function ec(r){var e=this.__data__,t=Dt(e,r);return t<0?void 0:e[t][1]}function tc(r){return Dt(this.__data__,r)>-1}function rc(r,e){var t=this.__data__,s=Dt(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function re(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}re.prototype.clear=Jl,re.prototype.delete=Xl,re.prototype.get=ec,re.prototype.has=tc,re.prototype.set=rc;var tt=ge(J,"Map");function sc(){this.size=0,this.__data__={hash:new me,map:new(tt||re),string:new me}}function oc(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function _t(r,e){var t=r.__data__;return oc(e)?t[typeof e=="string"?"string":"hash"]:t.map}function nc(r){var e=_t(this,r).delete(r);return this.size-=e?1:0,e}function ic(r){return _t(this,r).get(r)}function ac(r){return _t(this,r).has(r)}function lc(r,e){var t=_t(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function se(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}se.prototype.clear=sc,se.prototype.delete=nc,se.prototype.get=ic,se.prototype.has=ac,se.prototype.set=lc;var cc="Expected a function";function lr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(cc);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(lr.Cache||se),t}lr.Cache=se;var uc=500;function dc(r){var e=lr(r,function(s){return t.size===uc&&t.clear(),s}),t=e.cache;return e}var fc=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,pc=/\\(\\)?/g,hc=dc(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(fc,function(t,s,o,n){e.push(o?n.replace(pc,"$1"):s||t)}),e});function cr(r){return r==null?"":kt(r)}function Rs(r,e){return E(r)?r:ar(r,e)?[r]:hc(cr(r))}function Pt(r){if(typeof r=="string"||Se(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ur(r,e){e=Rs(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 rt(r,e,t){var s=r==null?void 0:ur(r,e);return s===void 0?t:s}function Is(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var Ts=G?G.isConcatSpreadable:void 0;function yc(r){return E(r)||He(r)||!!(Ts&&r&&r[Ts])}function Os(r,e,t,s,o){var n=-1,i=r.length;for(t||(t=yc),o||(o=[]);++n<i;){var a=r[n];t(a)&&Is(o,a)}return o}var Ks=js(Object.getPrototypeOf,Object),gc="\\ud800-\\udfff",mc="\\u0300-\\u036f",vc="\\ufe20-\\ufe2f",bc="\\u20d0-\\u20ff",kc=mc+vc+bc,wc="\\ufe0e\\ufe0f",Ac="\\u200d",$c=RegExp("["+Ac+gc+kc+wc+"]");function Cc(r){return $c.test(r)}function Fs(r,e,t){return r===r&&(t!==void 0&&(r=r<=t?r:t),r=r>=e?r:e),r}function Dc(){this.__data__=new re,this.size=0}function _c(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Pc(r){return this.__data__.get(r)}function xc(r){return this.__data__.has(r)}var Ec=200;function Sc(r,e){var t=this.__data__;if(t instanceof re){var s=t.__data__;if(!tt||s.length<Ec-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new se(s)}return t.set(r,e),this.size=t.size,this}function L(r){var e=this.__data__=new re(r);this.size=e.size}L.prototype.clear=Dc,L.prototype.delete=_c,L.prototype.get=Pc,L.prototype.has=xc,L.prototype.set=Sc;var qs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Qs=qs&&typeof module=="object"&&module&&!module.nodeType&&module,jc=Qs&&Qs.exports===qs,Bs=jc?J.Buffer:void 0,Vs=Bs?Bs.allocUnsafe:void 0;function Gs(r,e){if(e)return r.slice();var t=r.length,s=Vs?Vs(t):new r.constructor(t);return r.copy(s),s}function Mc(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 Rc(){return[]}var Ic=Object.prototype,Tc=Ic.propertyIsEnumerable,Us=Object.getOwnPropertySymbols,Oc=Us?function(r){return r==null?[]:(r=Object(r),Mc(Us(r),function(e){return Tc.call(r,e)}))}:Rc;function Kc(r,e,t){var s=e(r);return E(r)?s:Is(s,t(r))}function dr(r){return Kc(r,Xe,Oc)}var fr=ge(J,"DataView"),pr=ge(J,"Promise"),hr=ge(J,"Set"),Ns="[object Map]",Fc="[object Object]",zs="[object Promise]",Ls="[object Set]",Ws="[object WeakMap]",Hs="[object DataView]",qc=ye(fr),Qc=ye(tt),Bc=ye(pr),Vc=ye(hr),Gc=ye(er),U=ee;(fr&&U(new fr(new ArrayBuffer(1)))!=Hs||tt&&U(new tt)!=Ns||pr&&U(pr.resolve())!=zs||hr&&U(new hr)!=Ls||er&&U(new er)!=Ws)&&(U=function(r){var e=ee(r),t=e==Fc?r.constructor:void 0,s=t?ye(t):"";if(s)switch(s){case qc:return Hs;case Qc:return Ns;case Bc:return zs;case Vc:return Ls;case Gc:return Ws}return e});var Uc=Object.prototype,Nc=Uc.hasOwnProperty;function zc(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Nc.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var xt=J.Uint8Array;function yr(r){var e=new r.constructor(r.byteLength);return new xt(e).set(new xt(r)),e}function Lc(r,e){var t=yr(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Wc=/\w*$/;function Hc(r){var e=new r.constructor(r.source,Wc.exec(r));return e.lastIndex=r.lastIndex,e}var Js=G?G.prototype:void 0,Zs=Js?Js.valueOf:void 0;function Jc(r){return Zs?Object(Zs.call(r)):{}}function Ys(r,e){var t=e?yr(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.length)}var Zc="[object Boolean]",Yc="[object Date]",Xc="[object Map]",eu="[object Number]",tu="[object RegExp]",ru="[object Set]",su="[object String]",ou="[object Symbol]",nu="[object ArrayBuffer]",iu="[object DataView]",au="[object Float32Array]",lu="[object Float64Array]",cu="[object Int8Array]",uu="[object Int16Array]",du="[object Int32Array]",fu="[object Uint8Array]",pu="[object Uint8ClampedArray]",hu="[object Uint16Array]",yu="[object Uint32Array]";function gu(r,e,t){var s=r.constructor;switch(e){case nu:return yr(r);case Zc:case Yc:return new s(+r);case iu:return Lc(r);case au:case lu:case cu:case uu:case du:case fu:case pu:case hu:case yu:return Ys(r,t);case Xc:return new s;case eu:case su:return new s(r);case tu:return Hc(r);case ru:return new s;case ou:return Jc(r)}}function Xs(r){return typeof r.constructor=="function"&&!or(r)?Ra(Ks(r)):{}}var mu="[object Map]";function vu(r){return K(r)&&U(r)==mu}var eo=Me&&Me.isMap,bu=eo?Ze(eo):vu,ku="[object Set]";function wu(r){return K(r)&&U(r)==ku}var to=Me&&Me.isSet,Au=to?Ze(to):wu,$u=1,ro="[object Arguments]",Cu="[object Array]",Du="[object Boolean]",_u="[object Date]",Pu="[object Error]",so="[object Function]",xu="[object GeneratorFunction]",Eu="[object Map]",Su="[object Number]",oo="[object Object]",ju="[object RegExp]",Mu="[object Set]",Ru="[object String]",Iu="[object Symbol]",Tu="[object WeakMap]",Ou="[object ArrayBuffer]",Ku="[object DataView]",Fu="[object Float32Array]",qu="[object Float64Array]",Qu="[object Int8Array]",Bu="[object Int16Array]",Vu="[object Int32Array]",Gu="[object Uint8Array]",Uu="[object Uint8ClampedArray]",Nu="[object Uint16Array]",zu="[object Uint32Array]",w={};w[ro]=w[Cu]=w[Ou]=w[Ku]=w[Du]=w[_u]=w[Fu]=w[qu]=w[Qu]=w[Bu]=w[Vu]=w[Eu]=w[Su]=w[oo]=w[ju]=w[Mu]=w[Ru]=w[Iu]=w[Gu]=w[Uu]=w[Nu]=w[zu]=!0,w[Pu]=w[so]=w[Tu]=!1;function Et(r,e,t,s,o,n){var i,a=e&$u;if(i!==void 0)return i;if(!z(r))return r;var l=E(r);if(l)i=zc(r);else{var c=U(r),u=c==so||c==xu;if(Je(r))return Gs(r,a);if(c==oo||c==ro||u&&!o)i=u?{}:Xs(r);else{if(!w[c])return o?r:{};i=gu(r,c,a)}}n||(n=new L);var d=n.get(r);if(d)return d;n.set(r,i),Au(r)?r.forEach(function(p){i.add(Et(p,e,t,p,r,n))}):bu(r)&&r.forEach(function(p,y){i.set(y,Et(p,e,t,y,r,n))});var f=dr,h=l?void 0:f(r);return Va(h||r,function(p,y){h&&(y=p,p=r[y]),ws(i,y,Et(p,e,t,y,r,n))}),i}var Lu=1,Wu=4;function oe(r){return Et(r,Lu|Wu)}var Hu="__lodash_hash_undefined__";function Ju(r){return this.__data__.set(r,Hu),this}function Zu(r){return this.__data__.has(r)}function st(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new se;++e<t;)this.add(r[e])}st.prototype.add=st.prototype.push=Ju,st.prototype.has=Zu;function Yu(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 no(r,e){return r.has(e)}var Xu=1,ed=2;function io(r,e,t,s,o,n){var i=t&Xu,a=r.length,l=e.length;if(a!=l&&!(i&&l>a))return!1;var c=n.get(r),u=n.get(e);if(c&&u)return c==e&&u==r;var d=-1,f=!0,h=t&ed?new st: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(!Yu(e,function(g,k){if(!no(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 td(r){var e=-1,t=Array(r.size);return r.forEach(function(s,o){t[++e]=[o,s]}),t}function rd(r){var e=-1,t=Array(r.size);return r.forEach(function(s){t[++e]=s}),t}var sd=1,od=2,nd="[object Boolean]",id="[object Date]",ad="[object Error]",ld="[object Map]",cd="[object Number]",ud="[object RegExp]",dd="[object Set]",fd="[object String]",pd="[object Symbol]",hd="[object ArrayBuffer]",yd="[object DataView]",ao=G?G.prototype:void 0,gr=ao?ao.valueOf:void 0;function gd(r,e,t,s,o,n,i){switch(t){case yd:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case hd:return!(r.byteLength!=e.byteLength||!n(new xt(r),new xt(e)));case nd:case id:case cd:return We(+r,+e);case ad:return r.name==e.name&&r.message==e.message;case ud:case fd:return r==e+"";case ld:var a=td;case dd:var l=s&sd;if(a||(a=rd),r.size!=e.size&&!l)return!1;var c=i.get(r);if(c)return c==e;s|=od,i.set(r,e);var u=io(a(r),a(e),s,o,n,i);return i.delete(r),u;case pd:if(gr)return gr.call(r)==gr.call(e)}return!1}var md=1,vd=Object.prototype,bd=vd.hasOwnProperty;function kd(r,e,t,s,o,n){var i=t&md,a=dr(r),l=a.length,c=dr(e),u=c.length;if(l!=u&&!i)return!1;for(var d=l;d--;){var f=a[d];if(!(i?f in e:bd.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 wd=1,lo="[object Arguments]",co="[object Array]",St="[object Object]",Ad=Object.prototype,uo=Ad.hasOwnProperty;function $d(r,e,t,s,o,n){var i=E(r),a=E(e),l=i?co:U(r),c=a?co:U(e);l=l==lo?St:l,c=c==lo?St:c;var u=l==St,d=c==St,f=l==c;if(f&&Je(r)){if(!Je(e))return!1;i=!0,u=!1}if(f&&!u)return n||(n=new L),i||ir(r)?io(r,e,t,s,o,n):gd(r,e,l,t,s,o,n);if(!(t&wd)){var h=u&&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),kd(r,e,t,s,o,n)):!1}function ot(r,e,t,s,o){return r===e?!0:r==null||e==null||!K(r)&&!K(e)?r!==r&&e!==e:$d(r,e,t,s,ot,o)}var Cd=1,Dd=2;function fo(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],c=i[1];if(i[2]){if(l===void 0&&!(a in r))return!1}else{var u=new L,d;if(!(d===void 0?ot(c,l,Cd|Dd,s,u):d))return!1}}return!0}function po(r){return r===r&&!z(r)}function ho(r){for(var e=Xe(r),t=e.length;t--;){var s=e[t],o=r[s];e[t]=[s,o,po(o)]}return e}function yo(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function _d(r){var e=ho(r);return e.length==1&&e[0][2]?yo(e[0][0],e[0][1]):function(t){return t===r||fo(t,r,e)}}function Pd(r,e){return r!=null&&e in Object(r)}function xd(r,e,t){e=Rs(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&&sr(o)&&tr(i,o)&&(E(r)||He(r)))}function Ed(r,e){return r!=null&&xd(r,e,Pd)}var Sd=1,jd=2;function Md(r,e){return ar(r)&&po(e)?yo(Pt(r),e):function(t){var s=rt(t,r);return s===void 0&&s===e?Ed(t,r):ot(e,s,Sd|jd)}}function go(r){return function(e){return e?.[r]}}function Rd(r){return function(e){return ur(e,r)}}function Id(r){return ar(r)?go(Pt(r)):Rd(r)}function Re(r){return typeof r=="function"?r:r==null?At:typeof r=="object"?E(r)?Md(r[0],r[1]):_d(r):Id(r)}function Td(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 mo=Td();function Od(r,e){return r&&mo(r,e,Xe)}function Kd(r,e){return function(t,s){if(t==null)return t;if(!te(t))return r(t,s);for(var o=t.length,n=-1,i=Object(t);++n<o&&s(i[n],n,i)!==!1;);return t}}var mr=Kd(Od);function Ie(r){return K(r)&&te(r)}var Fd=200;function vo(r,e,t,s){var o=-1,n=Na,i=!0,a=r.length,l=[],c=e.length;if(!a)return l;t&&(e=je(e,Ze(t))),e.length>=Fd&&(n=no,i=!1,e=new st(e));e:for(;++o<a;){var u=r[o],d=t==null?u:t(u);if(u=u!==0?u:0,i&&d===d){for(var f=c;f--;)if(e[f]===d)continue e;l.push(u)}else n(e,d,s)||l.push(u)}return l}function qd(r){var e=r==null?0:r.length;return e?r[e-1]:void 0}var bo=rr(function(r,e){var t=qd(e);return Ie(t)&&(t=void 0),Ie(r)?vo(r,Os(e,1,Ie),Re(t)):[]});function ko(r,e,t){r=cr(r),e=kt(e);var s=r.length;t=t===void 0?s:Fs(wt(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 Bd(r,e){var t=!0;return mr(r,function(s,o,n){return t=!!e(s,o,n),t}),t}function wo(r,e,t){var s=E(r)?Qd:Bd;return s(r,Re(e))}function Vd(r){return function(e,t,s){var o=Object(e);if(!te(e)){var n=Re(t);e=Xe(e),t=function(a){return n(o[a],a,o)}}var i=r(e,t,s);return i>-1?o[n?e[i]:i]:void 0}}var Gd=Math.max;function vr(r,e,t){var s=r==null?0:r.length;if(!s)return-1;var o=t==null?0:wt(t);return o<0&&(o=Gd(s+o,0)),bs(r,Re(e),o)}var Ud=Vd(vr);function Nd(r,e){var t=-1,s=te(r)?Array(r.length):[];return mr(r,function(o,n,i){s[++t]=e(o,n,i)}),s}var zd="[object String]";function jt(r){return typeof r=="string"||!E(r)&&K(r)&&ee(r)==zd}function Ao(r,e){return ot(r,e)}function Mt(r,e,t){t=typeof t=="function"?t:void 0;var s=t?t(r,e):void 0;return s===void 0?ot(r,e,void 0,t):!!s}function Ld(r,e){return r===e||fo(r,e,ho(e))}function Wd(r,e){var t=r.length;for(r.sort(e);t--;)r[t]=r[t].value;return r}function Hd(r,e){if(r!==e){var t=r!==void 0,s=r===null,o=r===r,n=Se(r),i=e!==void 0,a=e===null,l=e===e,c=Se(e);if(!a&&!c&&!n&&r>e||n&&i&&l&&!a&&!c||s&&i&&l||!t&&l||!o)return 1;if(!s&&!n&&!c&&r<e||c&&t&&o&&!s&&!n||a&&t&&o||!i&&o||!l)return-1}return 0}function Jd(r,e,t){for(var s=-1,o=r.criteria,n=e.criteria,i=o.length,a=t.length;++s<i;){var l=Hd(o[s],n[s]);if(l){if(s>=a)return l;var c=t[s];return l*(c=="desc"?-1:1)}}return r.index-e.index}function Zd(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=[At];var s=-1;e=je(e,Ze(Re));var o=Nd(r,function(n,i,a){var l=je(e,function(c){return c(n)});return{criteria:l,index:++s,value:n}});return Wd(o,function(n,i){return Jd(n,i,t)})}function $o(r,e,t,s){return r==null?[]:(E(e)||(e=e==null?[]:[e]),t=t,E(t)||(t=t==null?[]:[t]),Zd(r,e,t))}var Yd=go("length"),Co="\\ud800-\\udfff",Xd="\\u0300-\\u036f",ef="\\ufe20-\\ufe2f",tf="\\u20d0-\\u20ff",rf=Xd+ef+tf,sf="\\ufe0e\\ufe0f",of="["+Co+"]",br="["+rf+"]",kr="\\ud83c[\\udffb-\\udfff]",nf="(?:"+br+"|"+kr+")",Do="[^"+Co+"]",_o="(?:\\ud83c[\\udde6-\\uddff]){2}",Po="[\\ud800-\\udbff][\\udc00-\\udfff]",af="\\u200d",xo=nf+"?",Eo="["+sf+"]?",lf="(?:"+af+"(?:"+[Do,_o,Po].join("|")+")"+Eo+xo+")*",cf=Eo+xo+lf,uf="(?:"+[Do+br+"?",br,_o,Po,of].join("|")+")",So=RegExp(kr+"(?="+kr+")|"+uf+cf,"g");function df(r){for(var e=So.lastIndex=0;So.test(r);)++e;return e}function ff(r){return Cc(r)?df(r):Yd(r)}var pf="[object Map]",hf="[object Set]";function yf(r){if(r==null)return 0;if(te(r))return jt(r)?ff(r):r.length;var e=U(r);return e==pf||e==hf?r.size:Ms(r).length}function gf(r,e,t){return r=cr(r),t=t==null?0:Fs(wt(t),0,r.length),e=kt(e),r.slice(t,t+e.length)==e}function wr(r){const e=Ar(r);return mf(e)}function Ar(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(Ar).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+Ar(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function mf(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 ve={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 vf{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:ve.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 c=a.value+i,u={...a,value:c};return this.data.set(t,u),u}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"?[]:ve.getEntriesByType("resource")}get(e){const t=this.getKey(e.name,e.context);return this.data.get(t)}getByType(e){return Array.from(this.data.values()).filter(t=>t.type===e)}getByName(e){return Array.from(this.data.values()).filter(t=>t.name===e)}clear(){this.data.clear()}getKey(e,t){if(!t)return e;const s=wr(t);return e+"_"+s}}let jo=class Fi{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 c of l)i(c);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 c of l)t.set(c,(t.get(c)||0)-1),(t.get(c)||0)===0&&o.push(c)}}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=c=>!s||s.length===0||s.includes(this.nodeKinds.get(c)??void 0),i=()=>{const c=new Set,u=Array.from(o);for(;u.length;){const d=u.shift();for(const[f,h]of this.edges)h.has(d)&&!c.has(f)&&(c.add(f),u.push(f))}return c},a=()=>{const c=new Set,u=Array.from(o);for(;u.length;){const d=u.shift(),f=this.edges.get(d);if(f)for(const h of f)c.has(h)||(c.add(h),u.push(h))}return c};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 Fi;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("→")),c=Array.from(i).filter(d=>!a.has(d)).map(d=>d.split("→")),u=[];for(const d of new Set([...t,...s])){const f=this.nodeKinds.get(d),h=e.nodeKinds.get(d);f!==h&&u.push({name:d,from:f,to:h})}return{addedNodes:o,removedNodes:n,addedEdges:l,removedEdges:c,kindChanges:u}}};class bf{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 Mo={silent:0,error:1,warn:2,info:3,debug:4};let kf=class T{config;static globalConfig={};constructor(e={}){this.config={level:e.level??T.globalConfig.level??this.getDefaultLevel(),format:e.format??T.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??T.globalConfig.onLog,onTrackError:e.onTrackError??T.globalConfig.onTrackError}}static setGlobalConfig(e){T.globalConfig={...T.globalConfig,...e}}static getGlobalConfig(){return{...T.globalConfig}}static setModuleLevel(e,t){T.globalConfig.onLog||(T.globalConfig.onLog=void 0),T._moduleOverrides||(T._moduleOverrides=new Map),T._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!T._moduleOverrides))return T._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=T.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return Mo[e]<=Mo[t]}formatMessage(e){if(this.config.format==="json"){const i={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(i.module=e.prefix),e.context&&(i.context=e.context),e.error&&(i.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(i)}const t=new Date(e.timestamp).toISOString().substring(11,23),s=e.prefix?`[${e.prefix}]`:"",o=this.getLevelIcon(e.level),n=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${o} ${s} ${e.message}${n}`.trim()}getLevelIcon(e){switch(e){case"error":return"✖";case"warn":return"⚠";case"info":return"ℹ";case"debug":return"⚙";default:return" "}}log(e,t,s,o){if(!this.shouldLog(e))return;const n={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:s,error:o};if(this.config.onLog){this.config.onLog(n);return}const i=this.formatMessage(n);if(typeof console<"u")switch(e){case"error":o?console.error(i,o):console.error(i);break;case"warn":console.warn(i);break;case"debug":console.debug?console.debug(i):console.log(i);break;default:console.log(i)}}error(e,t,s){const o=t instanceof Error?t:void 0,n=t instanceof Error?s:t;this.log("error",e,n,o)}trackError(e,t,s){if(this.error(e,t,s?.context),this.config.onTrackError){const o={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:s?.context,error:t,errorType:s?.errorType,errorGroup:s?.errorGroup};this.config.onTrackError(o)}}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}child(e){const t={...this.config,...e,prefix:e.prefix?this.config.prefix?`${this.config.prefix}:${e.prefix}`:e.prefix:this.config.prefix};return new T(t)}configure(e){Object.assign(this.config,e)}};const Te=new kf;class Ro{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}enabled;cache;cacheDependencies;hitCount=0;missCount=0;log=Te.child({prefix:"CacheController"});get(e,t){if(!this.enabled)return;const s=this.getCacheName(e,t);return this.cache.has(s)?this.hitCount++:this.missCount++,this.cache.get(s)}set(e,t,s,o){if(!this.enabled)return;const n=this.getCacheName(e,t);this.cache.set(n,s),o?this.cacheDependencies.set(n,o):this.log.debug(`Cache entry '${e}' stored without dependencies. This prevents granular invalidation and may cause stale data.`)}has(e,t){return this.cache.has(this.getCacheName(e,t))}clear(){this.cache.clear(),this.cacheDependencies.clear(),this.hitCount=0,this.missCount=0}invalidateByDependencies(e){if(!this.enabled)return;const t=[];for(const[s,o]of this.cacheDependencies){let n=!1;for(const[i,a]of e){if(o.models.has(i))if(o.modelAttributes.has(i)){const l=o.modelAttributes.get(i);for(const c of a)if(l.has(c)){n=!0;break}}else n=!0;if(n)break}n&&t.push(s)}for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateByModels(e){if(!this.enabled)return;const t=new Set(e),s=[];for(const[o,n]of this.cacheDependencies)for(const i of t)if(n.models.has(i)){s.push(o);break}for(const o of s)this.cache.delete(o),this.cacheDependencies.delete(o)}invalidateByKeyPrefix(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())s.startsWith(e+"_")&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateForModel(e){this.invalidateByModels([e])}invalidateForAttribute(e,t){if(!this.enabled)return;const s=new Map;s.set(e,new Set([t])),this.invalidateByDependencies(s)}invalidateMatching(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())e(s)&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}generateContext(e){try{return oe(e)}catch(t){return this.log.error("Error in cache generateContext",t),e}}getCacheName(e,t){const s=wr(t);return e+"_"+s}getStats(){const e=this.hitCount+this.missCount,t=e>0?this.hitCount/e:0;return{size:this.cache.size,hitRate:t,totalEntries:this.cache.size,entriesWithDependencies:this.cacheDependencies.size,hits:this.hitCount,misses:this.missCount}}}function W(r=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let s=0;s<r;s++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}class $r{key;parentCd;dcuplInitOptions;analyticsController;off;updateListener=new Set;counter=0;constructor(){}_init(e){this.key=e.cdRefKey,this.analyticsController=e.analyticsController,this.parentCd=e.parentCd,this.dcuplInitOptions=e.dcuplInitOptions,this.parentCd&&(this.off=this.parentCd.on(t=>{t.action==="update"&&t.originCdRefKey===this.parentCd?.key&&(t.connectMessage=!1,this.trigger(t))}))}getCounter(){return this.parentCd?this.parentCd.getCounter():this.counter}increaseCounter(){this.parentCd?this.parentCd.increaseCounter():this.counter++}destroy(){this.off&&this.off()}trigger(e){e.originCdRefKey||(e.originCdRefKey=this.key),e.key||(this.increaseCounter(),e.key=this.getCounter()),e.end||(e.end=ve.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 Io=(r,e)=>e?typeof structuredClone<"u"?structuredClone(r):oe(r):r,To=(r,e,t,s,o,n)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=Io(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=ve.now(),c=l-s,u=Math.round(c*1e3)/1e3;t.duration=u,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=ve.now(),a=this.cdRef,l=Io(r,!0);l.key||(a.increaseCounter(),l.key=a.getCounter());const c=W();a.analyticsController.mark({name:`${l.type}:start`,context:c});const u=this.model?.key;!l.originCdRefKey&&a.key&&(l.originCdRefKey=a.key),u&&(l.modelKey=u);const d=o.apply(this,n);return l.method=t,l.args=n,d&&typeof d=="object"&&"then"in d?d.then(f=>To(this,a,l,i,c,f)):To(this,a,l,i,c,d)},s};function wf(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(u=>r.has(u)),c=t.transform?s.transformValue(i,t.transform):i;if(!(t.excludeUndefineds&&typeof i>"u")&&!(t.excludeNulls&&i===null)){if(l&&(n===""||n==="//")){const u={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(u)}else if(l&&typeof n=="string"&&n.startsWith("/")&&n.endsWith("/")){if(s.queryFind(c,n,"some")){const u={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(u)}}else if(l&&typeof n=="string"){const u=String(c??""),d=n;if(u.toLowerCase().startsWith(d.toLowerCase())){const f={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(f)}}else if(l&&s.queryFind(c,n,"some")){const u={value:i,keys:t.calculateResultKeys?Array.from(a):[]};o.push(u)}if(o.length===t.max)break}}return o}function Af(r){return r instanceof Date}function Oo(r){return r instanceof Date&&!isNaN(r.getTime())}const $f={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 Cf(r){let e="^";const t=[];let s=r;const o=Object.entries($f).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 Df(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 _f(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 Oo(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}=Cf(e),n=r.match(s);if(!n)return new Date(NaN);const i=Df(n,o);return _f(i)}class xf{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 Ef{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 Sf{parseCache;circularRefDetector;cacheHits=0;cacheMisses=0;constructor(e=1e3){this.parseCache=new xf(e),this.circularRefDetector=new Ef}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("."),c=e.indexOf("[");if(n&&(l===-1||c<l)){const u=e.indexOf("]");if(u>-1){const d=e.indexOf(".",u+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 u=a[1];u&&u!=="*"&&!/^\d+$/.test(u)&&s.push(`Invalid bracket content: Must be a number or '*', got '${u}' 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 c=e.match(/[^a-zA-Z0-9._[\]*-]/g);return c&&s.push(`Invalid characters in path: ${c.join(", ")} in ${e}`),{valid:s.length===0,errors:s.length>0?s:void 0}}clearCache(){this.parseCache.clear(),this.cacheHits=0,this.cacheMisses=0}clearCircularDetector(){this.circularRefDetector.clear()}getCacheStats(){const e=this.parseCache.getStats(),t=this.cacheHits+this.cacheMisses,s=t>0?this.cacheHits/t:0;return{...e,hits:this.cacheHits,misses:this.cacheMisses,hitRate:s}}getPathSegments(e){return e.replace(/\[[^\]]+\]/g,"").split(".").filter(t=>t.length>0)}getPathDepth(e){return this.getPathSegments(e).length}}const P=new Sf;function be(r,e){if(e.includes("[*]")){const n=e.indexOf("[*]"),i=e.substring(0,n),a=e.substring(n+3),l=i?rt(r,i):r;if(!Array.isArray(l))return[];const c=[];for(const u of l)!a||a===""?u!==void 0&&c.push(u):a.startsWith(".")&&c.push(...be(u,a.slice(1)));return c}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 c=l[n];c!==void 0&&i.push(c)}else{const l=a[n];l!==void 0&&i.push(l)}if(s=i,s.length===0)return[]}const o=[];for(const n of s)if(Array.isArray(n))for(const i of n)i!==void 0&&o.push(i);else n!==void 0&&o.push(n);return o}function Cr(r){let e=0;for(let t of r){const s=t.toString().split(".")[1];s&&(e=Math.max(e,s.length))}return Math.pow(10,e)}function Ko(r,e,t){return(r*t+e*t)/t}function jf(r,e,t){return r*t/(e*t)}const nt=(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=Tf(s,e));let i;return(o.types.includes("min")||o.types.includes("max"))&&(i=Rf(s,e)),r.types.forEach(a=>{a==="sum"?o.sum=n?.sum:a==="avg"?o.avg=n?.average:a==="count"?o.count=Mf(s,e):a==="min"?o.min=i&&i[0]:a==="max"?o.max=i&&i[1]:a==="distinct"?o.distinct=Of(r,e,t):a==="group"&&(o.group=If(r,e))}),o},Mf=(r,e)=>{const t=P.parse(r).isDeepQuery;let s=0;for(const o of e.values())if(o)if(t)s+=be(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},Rf=(r,e)=>{let t,s;const o=P.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=be(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]},If=(r,e)=>{const t=[];r.groupOptions?.groups?.forEach(n=>{t.push({option:n,count:0,keys:[]})});const s={option:{value:["$dcupl_not_found"]},count:0,keys:[]},o=P.parse(r.attribute).isDeepQuery;for(const n of e.values()){let i;o?i=be(n,r.attribute):i=[n[r.attribute]];let a=!1;for(const l of i)for(const c of t)(typeof c.option.value<"u"&&c.option.value.includes(l)||typeof c.option.from<"u"&&c.option.from<l&&typeof c.option.to<"u"&&c.option.to>l)&&(c.keys.includes(n.key)||(c.count++,c.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},Tf=(r,e)=>{let t=0,s=0;const o=P.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=be(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=Ko(t,l,Cr([t,l])),s++);else typeof a=="number"&&(t=Ko(t,a,Cr([t,a])),s++)}return s===0?void 0:{average:jf(t,s,Cr([t,s])),count:s,sum:t}},Of=(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 it=class extends Error{query;constructor(e,t){const s=`Query Error: ${e} in ${JSON.stringify(t,null,2)}`;super(s),this.query=t,this.name="DcuplQueryError"}},ke=class{_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=oe(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||P}init(e){this._initOptions=oe(e),this.currentQuery=oe(this._defaultQueryOptions),this.currentQuery.modelKey=e.modelKey,"queries"in e&&Array.isArray(e.queries)&&(e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&(this.currentQuery.queries=oe(e.queries)),e.count!==void 0&&(this.currentQuery.count=e.count),e.start!==void 0&&(this.currentQuery.start=e.start),e.sort&&(this.currentQuery.sort=e.sort),e.projection&&(this.currentQuery.projection=e.projection))}reset(){return this.init(this._initOptions),this.getQuery()}isQuery(e){return"attribute"in e}isQueryGroup(e){return"queries"in e||"groupKey"in e}isRootQueryGroup(e){return this.isQueryGroup(e)&&e.groupKey==="root"}getQueryGroup(e){return this.currentQuery.queries.find(t=>this.isQueryGroup(t)&&t.groupKey===e)}getQuery(){return oe(this.currentQuery)}hasQueryGroup(e){return this.currentQuery.queries.some(t=>this.isQueryGroup(t)&&t.groupKey===e)}has(e){if(e.groupKey&&e.queryKey){const t=this.getQueryGroup(e.groupKey);if(t)return t.queries.some(s=>this.isQuery(s)&&s.queryKey===e.queryKey)}else if(e.groupKey)return this.hasQueryGroup(e.groupKey);return!1}validate(e){const t=e.queries.map(s=>this.validateQuery(s));return{valid:wo(t,s=>s.valid),errors:t.map(s=>s.errors).flat()}}applyOptions(e,t="update"){return t==="set"?(this.currentQuery.count=e.count,this.currentQuery.start=e.start,this.currentQuery.sort=e.sort,this.currentQuery.projection=e.projection):(typeof e?.sort<"u"&&(this.currentQuery.sort=e.sort),typeof e?.count<"u"&&(this.currentQuery.count=e.count),typeof e?.start<"u"&&(this.currentQuery.start=e?.start),typeof e?.projection<"u"&&(this.currentQuery.projection=e?.projection)),this.getQuery()}applyQuery(e,t,s){if(s||(s=this.currentQuery),Array.isArray(e))for(const o of e)this.applyQuery(o,t,s);else if(this.isRootQueryGroup(e))e.groupType&&(s.groupType=e.groupType),t?.mode==="set"?s.queries=e.queries:s.queries=[...s.queries,...e.queries],this.applyOptions(e,"set");else if(this.isQuery(e)){const o=s.queries.findIndex(n=>this.isQueryGroup(n)&&n.groupKey===e.attribute);if(o>-1){const n=s.queries[o];t?.mode==="set"?n.queries=[e]:n.queries.push(e)}else s.queries.push({groupKey:e.attribute,groupType:"or",queries:[e]})}else if(this.isQueryGroup(e)){const o=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=vr(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=vr(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 it("Missing attribute",e)),e.operator||t.push(new it("Missing operator",e)),typeof e.value>"u"&&t.push(new it("Missing value",e)),e.operator==="find"&&Array.isArray(e.value)&&t.push(new it("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 it("Invalid query definition",e)),{valid:!1,errors:t}}getQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)this.isQuery(i)?i.attribute&&!s.has(i.attribute)&&(t.push(i.attribute),s.add(i.attribute)):this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)if(this.isQuery(i)){if(i.attribute&&!s.has(i.attribute)){const a=this.getQueryAttributeForString(i.attribute);t.push(a),s.add(i.attribute)}}else this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}getQueryAttributeForString(e){return this.deepQueryService.parse(e)}getDeepQueryService(){return this.deepQueryService}getProjectionForAttributes(e){const t={};return e.forEach(s=>{t[s]=!0}),t}getProjectionForAttributeEntries(e){const t={$:!0};return e.forEach(s=>{if(s.isDeepQuery){if(s.reference)if(s.referenceAttribute&&s.referenceAttribute.length>0){t[s.reference]||(t[s.reference]={$:!0});const o=this.deepQueryService.parse(s.referenceAttribute);if(o.isDeepQuery&&s.reference){const n=this.getProjectionForAttributeEntries([o]);Object.keys(n).forEach(i=>{i!=="$"&&s.reference&&(t[s.reference][i]=n[i])})}else s.reference&&(t[s.reference][s.referenceAttribute]=!0)}else t[s.reference]=!0}else t[s.attribute]=!0}),t}getAttributeNames(e){return this.getQueryAttributes(e)}getAttributeDetails(e){return this.extractQueryAttributes(e||this.currentQuery)}getCurrentAttributeNames(){return this.getAttributeNames(this.currentQuery)}getCurrentAttributeDetails(){return this.getAttributeDetails(this.currentQuery)}addCondition(e){return this.applyQuery(e,{mode:"add"})}addGroup(e){return this.applyQuery(e,{mode:"add"})}setCondition(e){return this.applyQuery(e,{mode:"set"})}setGroup(e){return this.applyQuery(e,{mode:"set"})}mergeQuery(e){if(e.queries&&Array.isArray(e.queries))for(const t of e.queries)this.applyQuery(t,{mode:"add"});return this.currentQuery}replaceQuery(e){return this.currentQuery.queries=[],e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&Array.isArray(e.queries)&&(this.currentQuery.queries=e.queries),this.currentQuery}clear(){return this.reset()}clearConditions(){return this.removeAllQueries()}getCurrentQuery(){return this.getQuery()}isEmpty(){return this.currentQuery.queries.length===0}hasCondition(e){const t=s=>{for(const o of s)if(this.isQuery(o)){let n=!0;for(const i in e)if(o[i]!==e[i]){n=!1;break}if(n)return!0}else if(this.isQueryGroup(o)&&t(o.queries))return!0;return!1};return t(this.currentQuery.queries)}hasGroup(e){return this.hasQueryGroup(e)}getUsedAttributes(){return this.getAttributeNames()}getDeepQueryAttributes(){return this.getAttributeDetails().filter(e=>e.isDeepQuery)}getGroups(){return this.currentQuery.queries.filter(e=>this.isQueryGroup(e))}getTopLevelConditions(){return this.currentQuery.queries.filter(e=>this.isQuery(e))}getGroup(e){return this.getQueryGroup(e)}getConditionCount(){const e=t=>{let s=0;for(const o of t)this.isQuery(o)?s++:this.isQueryGroup(o)&&(s+=e(o.queries));return s};return e(this.currentQuery.queries)}};const Dr=new ke;function Kf(r,e,t,s,o,n,i){const a=Dr.removeQuery({groupKey:o},oe(s)),l=i.queryData(r,a,!1,n),c=e?[...e.keys()]:[],u=new Set(c),d=n.get(o)??new Map;if(!t.excludeUnresolved)for(const h of d.keys())u.add(h);if(t.excludeUndefineds?u.delete(void 0):u.add(void 0),t.sort){const h=[];for(const y of u.values())h.push(Fo(y,d,l,e,o,s,!0));const p=t.excludeZeros?h.filter(y=>y.size>0):h;return p.sort(Ff(t.sort)),t.count?p.slice(0,t.count):p}const f=[];for(const h of u.values()){const p=Fo(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 Fo(r,e,t,s,o,n,i){const a=new Map,l=e.get(r)||new Set;for(const c of l){const u=t.get(c);if(u&&(a.set(c,u),!i))break}return{key:String(r),value:r,selected:qf(o,r,n),enabled:a.size>0,size:a.size,entry:s?.get(r),resultKeys:Array.from(a.keys())}}function Rt(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 Ff(r){switch(r){case"size-desc":return(e,t)=>t.size-e.size||Rt(e.value,t.value);case"size-asc":return(e,t)=>e.size-t.size||Rt(e.value,t.value);case"value-asc":return(e,t)=>Rt(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:-Rt(e.value,t.value)}}const qf=(r,e,t)=>{const s=t.queries.findIndex(o=>Dr.isQueryGroup(o)&&o.groupKey===r);return s>-1?!!t.queries[s].queries.find(o=>{if(Dr.isQuery(o)){const n=o.value?.key||o.value;return o.attribute===r&&n===e}return!1}):!1};class It{indexMap=new Map;dataMap=new Map;indexMetadata=new Map;constructor(){}reset(e){e?(this.indexMap.delete(e),this.dataMap.delete(e),this.indexMetadata.delete(e)):(this.indexMap.clear(),this.dataMap.clear(),this.indexMetadata.clear())}resetIndicesWhere(e){for(const t of Array.from(this.indexMap.keys()))e(t)&&this.reset(t)}fillDataMap(e,t){let s=this.dataMap.get(e);s||(s=new Map,this.dataMap.set(e,s));for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const a of o)this.fillDataMap(e,[a]);return}else o instanceof Date?n=o.toISOString():n=o;let i=s.get(n);i||(i={key:n},this.dataMap.get(e)?.set(n,i))}}fillInverseIndex(e,t,s){if(!e||!t||!s||!Array.isArray(s))return;const o=this.indexMap.get(e)||new Map;for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const l of n)this.fillInverseIndex(e,t,[l]);return}else n instanceof Date?i=n.toISOString():i=n;let a=o.get(i);a||(a=new Set,o.set(i,a)),a.add(t)}this.indexMap.set(e,o)}getIndex(e,t){const s=this.getIndexName(e,t);return this.indexMap.get(s)}getData(e,t){const s=this.getIndexName(e,t);return this.dataMap.get(s)}getOrCreateIndex(e,t,s){const o=this.getIndexName(e,s);let n=this.getIndex(o);const i=this.indexMetadata.get(o);if(i)i.lastAccessedAt=Date.now();else if(!n){const a=P.parse(e).isDeepQuery??!1;this.indexMetadata.set(o,{createdAt:Date.now(),lastAccessedAt:Date.now(),context:s,type:a?"deep":"shallow"})}if(!n){this.reset(o),this.indexMap.set(o,new Map);const a=P.parse(e).isDeepQuery;for(const l of t.values()){let c;a?(c=be(l,e),c.length===0&&(c=[void 0])):c=[l[e]],this.fillInverseIndex(o,l.key,c),this.fillDataMap(o,c)}n=this.getIndex(o)||new Map}return n}getIndexName(e,t){return t?e+"_"+wr(t):e}removeFromInverseIndex(e,t,s){const o=this.indexMap.get(e);if(o)for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const l of n)this.removeFromInverseIndex(e,t,[l]);return}else n instanceof Date?i=n.toISOString():i=n;const a=o.get(i);a&&(a.delete(t),a.size===0&&o.delete(i))}}updateInverseIndex(e,t,s,o){this.removeFromInverseIndex(e,t,s),this.fillInverseIndex(e,t,o)}removeFromDataMap(e,t){const s=this.dataMap.get(e);if(s)for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const i of o)this.removeFromDataMap(e,[i]);return}else o instanceof Date?n=o.toISOString():n=o;s.delete(n)}}updateDataMap(e,t,s){this.removeFromDataMap(e,t),this.fillDataMap(e,s)}removeItemFromAllIndices(e){for(const t of this.indexMap.values())for(const[s,o]of t)o.delete(e)&&o.size===0&&t.delete(s);for(const t of this.dataMap.values())t.has(e)&&t.delete(e)}resetAttributes(e){for(const t of e)this.reset(t)}isDeepQueryIndex(e){const t=e.includes("_")?e.split("_")[0]:e;try{return P.parse(t).isDeepQuery??!1}catch{return!1}}getDeepIndexKeys(){const e=[];for(const t of this.indexMap.keys())this.isDeepQueryIndex(t)&&e.push(t);return e}resetAllDeepIndices(){const e=this.getDeepIndexKeys();for(const t of e)this.indexMap.delete(t),this.dataMap.delete(t)}getIndexCount(){let e=0,t=0;for(const s of this.indexMap.keys())this.isDeepQueryIndex(s)?t++:e++;return{shallow:e,deep:t,total:e+t}}cleanupStaleIndices(e=300*1e3){const t=Date.now();let s=0;for(const[o,n]of this.indexMetadata)t-n.lastAccessedAt>e&&(this.reset(o),s++);return s}getStats(){const e=this.getIndexCount(),t=Date.now();let s=0,o=0;for(const i of this.indexMetadata.values()){const a=t-i.createdAt;s+=a,a>o&&(o=a)}const n=this.indexMetadata.size>0?s/this.indexMetadata.size:0;return{shallow:e.shallow,deep:e.deep,total:e.total,oldestAge:o,avgAge:n}}}const Oe="__";function _r(r,e,t={key:"root"},s="root",o=new It,n){const i=n||r;for(const a of e.columns)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.rows)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));for(const a of e.values)a.attribute&&(P.parse(a.attribute),o.getOrCreateIndex(a.attribute,i));if(e.rows&&e.rows.length>0){t.rows=t.rows||[];const a=Qf(r,e.rows[0],e,o,s,n);t.rows.push(a)}if(e.columns&&e.columns.length>0){t.columns=t.columns||[];const a=qo(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=nt(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,c]of a.entries()){const u={key:l,value:l},d=new Map;for(const f of c)r.has(f)&&d.set(f,r.get(f));if(d.size){for(const f of t.values){if(u.values=u.values||[],o==="root"&&e?.calculateTotals===!1)continue;const h=nt(f,d,s.getIndex(f.attribute),f.attribute);u.values.push(h)}if(i.rows=i.rows||[],i.rows.push(u),t.rows.length>1){const f={...t,rows:t.rows.slice(1)};_r(d,f,u,o+Oe+e.attribute+Oe+l,s,n)}else if(t.columns)for(const f of t.columns){u.columns=u.columns||[];const h=qo(d,f,t,s,o+Oe+e.attribute+Oe+l,n);u.columns.push(h)}}}return i}function qo(r,e,t,s,o="",n){const i={key:e.attribute},a=s.getIndex(e.attribute);if(!a)return i;for(const[l,c]of a.entries()){const u={key:l,value:l},d=new Map;for(const f of c)r.has(f)&&d.set(f,r.get(f));if(d.size){for(const f of t.values){if(u.values=u.values||[],o==="root"&&e?.calculateTotals===!1)continue;const h=nt(f,d,s.getIndex(f.attribute),f.attribute);u.values.push(h)}if(i.columns=i.columns||[],i.columns.push(u),t.columns.length>1){const f={...t,columns:t.columns.slice(1)};_r(d,f,u,o+Oe+e.attribute+Oe+l,s,n)}}}return i}const Bf=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/,Vf=/^-?\d+$/,Gf=/^-?\d+\.\d+$/,Uf=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,Nf=r=>r==="true"||r==="false"?"boolean":Vf.test(r)?"int":Gf.test(r)?"float":Bf.test(r)&&!Number.isNaN(Date.parse(r))?"date":"string",zf=r=>Uf.test(r),Lf=r=>r==null||r==="",Wf=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}},Hf=(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 c=0;c<i;c++){const u=r[c];if(u)for(const[d,f]of Object.entries(u)){let h=o.get(d);if(h||(h={observed:new Set,empty:0,scanned:0},o.set(d,h),n.push(d)),h.scanned++,Lf(f)){h.empty++;continue}let p;typeof f=="string"&&s?(p=Nf(f),p==="string"&&!h.hint&&zf(f)&&(h.hint="column looks date-like (non-ISO) — review manually")):p=Jf(f),h.observed.add(p)}}const a=[],l=[];for(const c of n){const u=o.get(c),{type:d,conflict:f}=Wf(u.observed.size?u.observed:new Set(["string"]));a.push({key:c,type:d}),l.push({column:c,inferredType:d,observedTypes:[...u.observed].sort(),emptyRate:u.scanned===0?0:u.empty/u.scanned,conflict:f,hint:u.hint})}return{properties:a,diagnostics:l}},Qo=(r,e=!1)=>Hf(r,typeof e=="boolean"?{deep:e}:e).properties,Bo=r=>Number(r)===r&&r%1===0,Vo=r=>Number(r)===r&&r%1!==0,Jf=r=>{switch(typeof r){case"string":return"string";case"number":return Bo(r)?"int":Vo(r)?"float":"any";case"boolean":return"boolean";case"object":return Af(r)?"date":"json";default:return"any"}};class Zf{constructor(e,t,s){this.scriptController=e,this.globalItemService=t,this.modelParser=s}scriptController;globalItemService;modelParser;registeredCustomOperator=new Map;queryBuilder=new ke;registerCustomOperator(e,t){this.registeredCustomOperator.set(e,t)}transformValue(e,t){if(Array.isArray(e))return e.map(s=>this.transformValue(s,t));if(typeof e!="string")return e;for(const s of t)s==="lowercase"?e=e.toLowerCase():s==="trim"?e=e.trim():s==="removeWhitespace"&&(e=e.replace(/\s/g,""));return e}evaluateQuery(e,t){let s,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=rt(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?!Ao(s,o):Ao(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:yf(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(c=>{s.has(c)&&n.set(c,s.get(c))}),t.options?.invert){const c=bo(Array.from(s.values()),Array.from(n.values()),"key"),u=new Map;return c.forEach(d=>{u.set(d.key,d)}),u}else return n}}for(let[a,l]of s){const c=this.queryBuilder.extractQueryAttributes({queries:[t]});if(c.some(u=>u.isDeepQuery)){const u=this.queryBuilder.getProjectionForAttributeEntries(c.filter(d=>d.isDeepQuery));l=this.globalItemService.getProjectedData(u,this.modelParser.models.get(e.modelKey),l)}this.evaluateQuery(t,l)&&n.set(a,l)}return n}equalRegexFn(e,t){if(typeof t=="string"&&gf(t,"/")&&ko(t,"/"))try{return new RegExp(t.slice(1,-1)).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(s=>Mt(s,t,this.equalRegexFn)):typeof t=="object"?Ld(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=>Mt(o,t,this.equalRegexFn)):e.every(o=>Mt(o,t,this.equalRegexFn)):!!Ud(e,t):Mt(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 wo(e.queries,t=>this.validateQuery(t));throw new Error("invalid query - missing query or attribute")}}getEvaluatedQueryDataset(e,t,s,o){const n=new Map;if(t.attribute.includes("[*]")){const i=t.options?.invert===!0,a=new Set;for(let l of s.values()){const c=this.queryBuilder.extractQueryAttributes({queries:[t]});if(c.some(f=>f.isDeepQuery)){const f=this.queryBuilder.getProjectionForAttributeEntries(c.filter(h=>h.isDeepQuery));l=this.globalItemService.getProjectedData(f,this.modelParser.models.get(e.modelKey),l)}const u=this.handleArrayStarQuery(t,l);let d=!1;for(const f of u.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,c]of s)a.has(l)||n.set(l,c)}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(c=>c.isDeepQuery)){const c=this.queryBuilder.getProjectionForAttributeEntries(l.filter(u=>u.isDeepQuery));a=this.globalItemService.getProjectedData(c,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(".")?rt(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 c=new Map;if(this.queryBuilder.isQuery(l)?c=this.getEvaluatedQueryDataset(e,l,a,n):c=this.evaluateQueryGroup(e,l,a,o,n),i.size===0&&(i=c),t.groupType==="or")c.forEach(u=>{i.set(u.key,u)});else{const u=bo(Array.from(i.values()),Array.from(c.values()),"key");for(const d of u)i.delete(d.key)}t.groupType==="and"?a=i:a=s}return i}queryData(e,t,s,o){if(t.queries.length===0)return e;const n=new Map(e);return t.groupKey||(t.groupKey="root"),t.groupType||(t.groupType="and"),t.queries||(t.queries=[]),this.validateQuery(t),this.evaluateQueryGroup(t,t,n,s,o)}}function Z(){const r=globalThis;return typeof r.scheduler?.yield=="function"?r.scheduler.yield():typeof r.setImmediate=="function"?new Promise(e=>r.setImmediate(()=>e())):typeof r.MessageChannel=="function"?new Promise(e=>{const t=new r.MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)}):new Promise(e=>setTimeout(e,0))}class Yf{scripts=new Map;scriptFunctions=new Map;constructor(){}keys(){return Array.from(this.scripts.keys())}setScript(e,t){this.scripts.set(e,t)}removeScript(e){this.scripts.delete(e)}getScript(e){return this.scripts.get(e)}hasScript(e){return this.scripts.has(e)}getScriptAsFn(e,t){if(this.scriptFunctions.has(e))return this.scriptFunctions.get(e);const s=this.getScript(e);if(!s)throw new Error(`Script ${e} not found`);const o=this.getWrapperScript(s),n=new Function("script_type",...t,o);return this.scriptFunctions.set(e,n),n}getWrapperScript(e){return`
1
+ (function(){"use strict";var R=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},O={searchParams:"URLSearchParams"in R,iterable:"Symbol"in R&&"iterator"in Symbol,blob:"FileReader"in R&&"Blob"in R&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in R,arrayBuffer:"ArrayBuffer"in R};function Fi(r){return r&&DataView.prototype.isPrototypeOf(r)}if(O.arrayBuffer)var qi=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Qi=ArrayBuffer.isView||function(r){return r&&qi.indexOf(Object.prototype.toString.call(r))>-1};function Ee(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(r)||r==="")throw new TypeError('Invalid character in header field name: "'+r+'"');return r.toLowerCase()}function Ht(r){return typeof r!="string"&&(r=String(r)),r}function Jt(r){var e={next:function(){var t=r.shift();return{done:t===void 0,value:t}}};return O.iterable&&(e[Symbol.iterator]=function(){return e}),e}function x(r){this.map={},r instanceof x?r.forEach(function(e,t){this.append(t,e)},this):Array.isArray(r)?r.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(e){this.append(e,r[e])},this)}x.prototype.append=function(r,e){r=Ee(r),e=Ht(e);var t=this.map[r];this.map[r]=t?t+", "+e:e},x.prototype.delete=function(r){delete this.map[Ee(r)]},x.prototype.get=function(r){return r=Ee(r),this.has(r)?this.map[r]:null},x.prototype.has=function(r){return this.map.hasOwnProperty(Ee(r))},x.prototype.set=function(r,e){this.map[Ee(r)]=Ht(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)}),Jt(r)},x.prototype.values=function(){var r=[];return this.forEach(function(e){r.push(e)}),Jt(r)},x.prototype.entries=function(){var r=[];return this.forEach(function(e,t){r.push([t,e])}),Jt(r)},O.iterable&&(x.prototype[Symbol.iterator]=x.prototype.entries);function Zt(r){if(!r._noBody){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}}function is(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=is(e);return e.readAsArrayBuffer(r),t}function Vi(r){var e=new FileReader,t=is(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 as(r){if(r.slice)return r.slice(0);var e=new Uint8Array(r.byteLength);return e.set(new Uint8Array(r)),e.buffer}function ls(){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=as(r.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):O.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(r)||Qi(r))?this._bodyArrayBuffer=as(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=Zt(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=Zt(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=Zt(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 pe(r,e){if(!(this instanceof pe))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 pe){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()}}}pe.prototype.clone=function(){return new pe(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}ls.call(pe.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)}ls.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 he=R.DOMException;try{new he}catch{he=function(e,t){this.message=e,this.name=t;var s=Error(e);this.stack=s.stack},he.prototype=Object.create(Error.prototype),he.prototype.constructor=he}function us(r,e){return new Promise(function(t,s){var o=new pe(r,e);if(o.signal&&o.signal.aborted)return s(new he("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 he("Aborted","AbortError"))},0)};function a(u){try{return u===""&&R.location.href?R.location.href:u}catch{return u}}if(n.open(o.method,a(o.url),!0),o.credentials==="include"?n.withCredentials=!0:o.credentials==="omit"&&(n.withCredentials=!1),"responseType"in n&&(O.blob?n.responseType="blob":O.arrayBuffer&&(n.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof x||R.Headers&&e.headers instanceof R.Headers)){var l=[];Object.getOwnPropertyNames(e.headers).forEach(function(u){l.push(Ee(u)),n.setRequestHeader(u,Ht(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)})}us.polyfill=!0,R.fetch||(R.fetch=us,R.Headers=x,R.Request=pe,R.Response=H);var cs=typeof global=="object"&&global&&global.Object===Object&&global,Hi=typeof self=="object"&&self&&self.Object===Object&&self,J=cs||Hi||Function("return this")(),G=J.Symbol,ds=Object.prototype,Ji=ds.hasOwnProperty,Zi=ds.toString,Le=G?G.toStringTag:void 0;function Yi(r){var e=Ji.call(r,Le),t=r[Le];try{r[Le]=void 0;var s=!0}catch{}var o=Zi.call(r);return s&&(e?r[Le]=t:delete r[Le]),o}var Xi=Object.prototype,ea=Xi.toString;function ta(r){return ea.call(r)}var ra="[object Null]",sa="[object Undefined]",fs=G?G.toStringTag:void 0;function ee(r){return r==null?r===void 0?sa:ra:fs&&fs in Object(r)?Yi(r):ta(r)}function K(r){return r!=null&&typeof r=="object"}var oa="[object Symbol]";function je(r){return typeof r=="symbol"||K(r)&&ee(r)==oa}function Se(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var E=Array.isArray,ps=G?G.prototype:void 0,hs=ps?ps.toString:void 0;function kt(r){if(typeof r=="string")return r;if(E(r))return Se(r,kt)+"";if(je(r))return hs?hs.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 ys=NaN,ua=/^[-+]0x[0-9a-f]+$/i,ca=/^0b[01]+$/i,da=/^0o[0-7]+$/i,fa=parseInt;function pa(r){if(typeof r=="number")return r;if(je(r))return ys;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)?ys:+r}var gs=1/0,ha=17976931348623157e292;function ya(r){if(!r)return r===0?r:0;if(r=pa(r),r===gs||r===-gs){var e=r<0?-1:1;return e*ha}return r===r?r:0}function wt(r){var e=ya(r),t=e%1;return e===e?t?e-t:e:0}function At(r){return r}var ga="[object AsyncFunction]",ma="[object Function]",va="[object GeneratorFunction]",ba="[object Proxy]";function Yt(r){if(!z(r))return!1;var e=ee(r);return e==ma||e==va||e==ga||e==ba}var Xt=J["__core-js_shared__"],ms=(function(){var r=/[^.]+$/.exec(Xt&&Xt.keys&&Xt.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function ka(r){return!!ms&&ms in r}var wa=Function.prototype,Aa=wa.toString;function ye(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=Yt(r)?Ea:Ca;return e.test(ye(r))}function Sa(r,e){return r?.[e]}function ge(r,e){var t=Sa(r,e);return ja(t)?t:void 0}var er=ge(J,"WeakMap"),vs=Object.create,Ma=(function(){function r(){}return function(e){if(!z(e))return{};if(vs)return vs(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 $t=(function(){try{var r=ge(Object,"defineProperty");return r({},"",{}),r}catch{}})(),qa=$t?function(r,e){return $t(r,"toString",{configurable:!0,enumerable:!1,value:Fa(e),writable:!0})}:At,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 bs(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 ks(r,e,t){return e===e?Ga(r,e,t):bs(r,Va,t)}function Ua(r,e){var t=r==null?0:r.length;return!!t&&ks(r,e,0)>-1}var Na=9007199254740991,za=/^(?:0|[1-9]\d*)$/;function tr(r,e){var t=typeof r;return e=e??Na,!!e&&(t=="number"||t!="symbol"&&za.test(r))&&r>-1&&r%1==0&&r<e}function Ct(r,e,t){e=="__proto__"&&$t?$t(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function We(r,e){return r===e||r!==r&&e!==e}var La=Object.prototype,Wa=La.hasOwnProperty;function ws(r,e,t){var s=r[e];(!(Wa.call(r,e)&&We(s,t))||t===void 0&&!(e in r))&&Ct(r,e,t)}var As=Math.max;function Ha(r,e,t){return e=As(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=As(s.length-e,0),i=Array(n);++o<n;)i[o]=s[e+o];o=-1;for(var a=Array(e+1);++o<e;)a[o]=s[o];return a[e]=t(i),Ra(r,this,a)}}function rr(r,e){return Qa(Ha(r,e,At),r+"")}var Ja=9007199254740991;function sr(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ja}function te(r){return r!=null&&sr(r.length)&&!Yt(r)}var Za=Object.prototype;function or(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Za;return r===t}function Ya(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var Xa="[object Arguments]";function $s(r){return K(r)&&ee(r)==Xa}var Cs=Object.prototype,el=Cs.hasOwnProperty,tl=Cs.propertyIsEnumerable,He=$s((function(){return arguments})())?$s:function(r){return K(r)&&el.call(r,"callee")&&!tl.call(r,"callee")};function rl(){return!1}var Ds=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ps=Ds&&typeof module=="object"&&module&&!module.nodeType&&module,sl=Ps&&Ps.exports===Ds,_s=sl?J.Buffer:void 0,ol=_s?_s.isBuffer:void 0,Je=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)&&sr(r.length)&&!!C[ee(r)]}function Ze(r){return function(e){return r(e)}}var xs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ye=xs&&typeof module=="object"&&module&&!module.nodeType&&module,jl=Ye&&Ye.exports===xs,nr=jl&&cs.process,Me=(function(){try{var r=Ye&&Ye.require&&Ye.require("util").types;return r||nr&&nr.binding&&nr.binding("util")}catch{}})(),Es=Me&&Me.isTypedArray,ir=Es?Ze(Es):El,Sl=Object.prototype,Ml=Sl.hasOwnProperty;function js(r,e){var t=E(r),s=!t&&He(r),o=!t&&!s&&Je(r),n=!t&&!s&&!o&&ir(r),i=t||s||o||n,a=i?Ya(r.length,String):[],l=a.length;for(var u in r)(e||Ml.call(r,u))&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||n&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||tr(u,l)))&&a.push(u);return a}function Ss(r,e){return function(t){return r(e(t))}}var Rl=Ss(Object.keys,Object),Il=Object.prototype,Tl=Il.hasOwnProperty;function Ms(r){if(!or(r))return Rl(r);var e=[];for(var t in Object(r))Tl.call(r,t)&&t!="constructor"&&e.push(t);return e}function Xe(r){return te(r)?js(r):Ms(r)}var Ol=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Kl=/^\w*$/;function ar(r,e){if(E(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||je(r)?!0:Kl.test(r)||!Ol.test(r)||e!=null&&r in Object(e)}var et=ge(Object,"create");function Fl(){this.__data__=et?et(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(et){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 et?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]=et&&e===void 0?Ll:e,this}function me(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])}}me.prototype.clear=Fl,me.prototype.delete=ql,me.prototype.get=Gl,me.prototype.has=zl,me.prototype.set=Wl;function Hl(){this.__data__=[],this.size=0}function Dt(r,e){for(var t=r.length;t--;)if(We(r[t][0],e))return t;return-1}var Jl=Array.prototype,Zl=Jl.splice;function Yl(r){var e=this.__data__,t=Dt(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=Dt(e,r);return t<0?void 0:e[t][1]}function eu(r){return Dt(this.__data__,r)>-1}function tu(r,e){var t=this.__data__,s=Dt(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function re(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}re.prototype.clear=Hl,re.prototype.delete=Yl,re.prototype.get=Xl,re.prototype.has=eu,re.prototype.set=tu;var tt=ge(J,"Map");function ru(){this.size=0,this.__data__={hash:new me,map:new(tt||re),string:new me}}function su(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Pt(r,e){var t=r.__data__;return su(e)?t[typeof e=="string"?"string":"hash"]:t.map}function ou(r){var e=Pt(this,r).delete(r);return this.size-=e?1:0,e}function nu(r){return Pt(this,r).get(r)}function iu(r){return Pt(this,r).has(r)}function au(r,e){var t=Pt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function se(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}se.prototype.clear=ru,se.prototype.delete=ou,se.prototype.get=nu,se.prototype.has=iu,se.prototype.set=au;var lu="Expected a function";function lr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(lu);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(lr.Cache||se),t}lr.Cache=se;var uu=500;function cu(r){var e=lr(r,function(s){return t.size===uu&&t.clear(),s}),t=e.cache;return e}var du=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,fu=/\\(\\)?/g,pu=cu(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(du,function(t,s,o,n){e.push(o?n.replace(fu,"$1"):s||t)}),e});function ur(r){return r==null?"":kt(r)}function Rs(r,e){return E(r)?r:ar(r,e)?[r]:pu(ur(r))}function _t(r){if(typeof r=="string"||je(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function cr(r,e){e=Rs(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[_t(e[t++])];return t&&t==s?r:void 0}function rt(r,e,t){var s=r==null?void 0:cr(r,e);return s===void 0?t:s}function Is(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var Ts=G?G.isConcatSpreadable:void 0;function hu(r){return E(r)||He(r)||!!(Ts&&r&&r[Ts])}function Os(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)&&Is(o,a)}return o}var Ks=Ss(Object.getPrototypeOf,Object),yu="\\ud800-\\udfff",gu="\\u0300-\\u036f",mu="\\ufe20-\\ufe2f",vu="\\u20d0-\\u20ff",bu=gu+mu+vu,ku="\\ufe0e\\ufe0f",wu="\\u200d",Au=RegExp("["+wu+yu+bu+ku+"]");function $u(r){return Au.test(r)}function Fs(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 re,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 re){var s=t.__data__;if(!tt||s.length<xu-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new se(s)}return t.set(r,e),this.size=t.size,this}function L(r){var e=this.__data__=new re(r);this.size=e.size}L.prototype.clear=Cu,L.prototype.delete=Du,L.prototype.get=Pu,L.prototype.has=_u,L.prototype.set=Eu;var qs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Qs=qs&&typeof module=="object"&&module&&!module.nodeType&&module,ju=Qs&&Qs.exports===qs,Bs=ju?J.Buffer:void 0,Vs=Bs?Bs.allocUnsafe:void 0;function Gs(r,e){if(e)return r.slice();var t=r.length,s=Vs?Vs(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,Us=Object.getOwnPropertySymbols,Tu=Us?function(r){return r==null?[]:(r=Object(r),Su(Us(r),function(e){return Iu.call(r,e)}))}:Mu;function Ou(r,e,t){var s=e(r);return E(r)?s:Is(s,t(r))}function dr(r){return Ou(r,Xe,Tu)}var fr=ge(J,"DataView"),pr=ge(J,"Promise"),hr=ge(J,"Set"),Ns="[object Map]",Ku="[object Object]",zs="[object Promise]",Ls="[object Set]",Ws="[object WeakMap]",Hs="[object DataView]",Fu=ye(fr),qu=ye(tt),Qu=ye(pr),Bu=ye(hr),Vu=ye(er),U=ee;(fr&&U(new fr(new ArrayBuffer(1)))!=Hs||tt&&U(new tt)!=Ns||pr&&U(pr.resolve())!=zs||hr&&U(new hr)!=Ls||er&&U(new er)!=Ws)&&(U=function(r){var e=ee(r),t=e==Ku?r.constructor:void 0,s=t?ye(t):"";if(s)switch(s){case Fu:return Hs;case qu:return Ns;case Qu:return zs;case Bu:return Ls;case Vu:return Ws}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 xt=J.Uint8Array;function yr(r){var e=new r.constructor(r.byteLength);return new xt(e).set(new xt(r)),e}function zu(r,e){var t=yr(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 Js=G?G.prototype:void 0,Zs=Js?Js.valueOf:void 0;function Hu(r){return Zs?Object(Zs.call(r)):{}}function Ys(r,e){var t=e?yr(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 yr(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 Ys(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 Xs(r){return typeof r.constructor=="function"&&!or(r)?Ma(Ks(r)):{}}var gc="[object Map]";function mc(r){return K(r)&&U(r)==gc}var eo=Me&&Me.isMap,vc=eo?Ze(eo):mc,bc="[object Set]";function kc(r){return K(r)&&U(r)==bc}var to=Me&&Me.isSet,wc=to?Ze(to):kc,Ac=1,ro="[object Arguments]",$c="[object Array]",Cc="[object Boolean]",Dc="[object Date]",Pc="[object Error]",so="[object Function]",_c="[object GeneratorFunction]",xc="[object Map]",Ec="[object Number]",oo="[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[ro]=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[oo]=w[jc]=w[Sc]=w[Mc]=w[Rc]=w[Vc]=w[Gc]=w[Uc]=w[Nc]=!0,w[Pc]=w[so]=w[Ic]=!1;function Et(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==so||u==_c;if(Je(r))return Gs(r,a);if(u==oo||u==ro||c&&!o)i=c?{}:Xs(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(Et(p,e,t,p,r,n))}):vc(r)&&r.forEach(function(p,y){i.set(y,Et(p,e,t,y,r,n))});var f=dr,h=l?void 0:f(r);return Ba(h||r,function(p,y){h&&(y=p,p=r[y]),ws(i,y,Et(p,e,t,y,r,n))}),i}var zc=1,Lc=4;function oe(r){return Et(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 st(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new se;++e<t;)this.add(r[e])}st.prototype.add=st.prototype.push=Hc,st.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 no(r,e){return r.has(e)}var Yc=1,Xc=2;function io(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 st: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(!no(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]",ao=G?G.prototype:void 0,gr=ao?ao.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 xt(r),new xt(e)));case od:case nd:case ld:return We(+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=io(a(r),a(e),s,o,n,i);return i.delete(r),c;case fd:if(gr)return gr.call(r)==gr.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=dr(r),l=a.length,u=dr(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,lo="[object Arguments]",uo="[object Array]",jt="[object Object]",wd=Object.prototype,co=wd.hasOwnProperty;function Ad(r,e,t,s,o,n){var i=E(r),a=E(e),l=i?uo:U(r),u=a?uo:U(e);l=l==lo?jt:l,u=u==lo?jt:u;var c=l==jt,d=u==jt,f=l==u;if(f&&Je(r)){if(!Je(e))return!1;i=!0,c=!1}if(f&&!c)return n||(n=new L),i||ir(r)?io(r,e,t,s,o,n):yd(r,e,l,t,s,o,n);if(!(t&kd)){var h=c&&co.call(r,"__wrapped__"),p=d&&co.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 ot(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,ot,o)}var $d=1,Cd=2;function fo(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?ot(u,l,$d|Cd,s,c):d))return!1}}return!0}function po(r){return r===r&&!z(r)}function ho(r){for(var e=Xe(r),t=e.length;t--;){var s=e[t],o=r[s];e[t]=[s,o,po(o)]}return e}function yo(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Dd(r){var e=ho(r);return e.length==1&&e[0][2]?yo(e[0][0],e[0][1]):function(t){return t===r||fo(t,r,e)}}function Pd(r,e){return r!=null&&e in Object(r)}function _d(r,e,t){e=Rs(e,r);for(var s=-1,o=e.length,n=!1;++s<o;){var i=_t(e[s]);if(!(n=r!=null&&t(r,i)))break;r=r[i]}return n||++s!=o?n:(o=r==null?0:r.length,!!o&&sr(o)&&tr(i,o)&&(E(r)||He(r)))}function xd(r,e){return r!=null&&_d(r,e,Pd)}var Ed=1,jd=2;function Sd(r,e){return ar(r)&&po(e)?yo(_t(r),e):function(t){var s=rt(t,r);return s===void 0&&s===e?xd(t,r):ot(e,s,Ed|jd)}}function go(r){return function(e){return e?.[r]}}function Md(r){return function(e){return cr(e,r)}}function Rd(r){return ar(r)?go(_t(r)):Md(r)}function Re(r){return typeof r=="function"?r:r==null?At: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 mo=Id();function Td(r,e){return r&&mo(r,e,Xe)}function Od(r,e){return function(t,s){if(t==null)return t;if(!te(t))return r(t,s);for(var o=t.length,n=-1,i=Object(t);++n<o&&s(i[n],n,i)!==!1;);return t}}var mr=Od(Td);function Ie(r){return K(r)&&te(r)}var Kd=200;function vo(r,e,t,s){var o=-1,n=Ua,i=!0,a=r.length,l=[],u=e.length;if(!a)return l;t&&(e=Se(e,Ze(t))),e.length>=Kd&&(n=no,i=!1,e=new st(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 bo=rr(function(r,e){var t=Fd(e);return Ie(t)&&(t=void 0),Ie(r)?vo(r,Os(e,1,Ie),Re(t)):[]});function ko(r,e,t){r=ur(r),e=kt(e);var s=r.length;t=t===void 0?s:Fs(wt(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 mr(r,function(s,o,n){return t=!!e(s,o,n),t}),t}function wo(r,e,t){var s=E(r)?qd:Qd;return s(r,Re(e))}function Bd(r){return function(e,t,s){var o=Object(e);if(!te(e)){var n=Re(t);e=Xe(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 vr(r,e,t){var s=r==null?0:r.length;if(!s)return-1;var o=t==null?0:wt(t);return o<0&&(o=Vd(s+o,0)),bs(r,Re(e),o)}var Gd=Bd(vr);function Ud(r,e){var t=-1,s=te(r)?Array(r.length):[];return mr(r,function(o,n,i){s[++t]=e(o,n,i)}),s}var Nd="[object String]";function St(r){return typeof r=="string"||!E(r)&&K(r)&&ee(r)==Nd}function Ao(r,e){return ot(r,e)}function Mt(r,e,t){t=typeof t=="function"?t:void 0;var s=t?t(r,e):void 0;return s===void 0?ot(r,e,void 0,t):!!s}function zd(r,e){return r===e||fo(r,e,ho(e))}function Ld(r,e){var t=r.length;for(r.sort(e);t--;)r[t]=r[t].value;return r}function Wd(r,e){if(r!==e){var t=r!==void 0,s=r===null,o=r===r,n=je(r),i=e!==void 0,a=e===null,l=e===e,u=je(e);if(!a&&!u&&!n&&r>e||n&&i&&l&&!a&&!u||s&&i&&l||!t&&l||!o)return 1;if(!s&&!n&&!u&&r<e||u&&t&&o&&!s&&!n||a&&t&&o||!i&&o||!l)return-1}return 0}function Hd(r,e,t){for(var s=-1,o=r.criteria,n=e.criteria,i=o.length,a=t.length;++s<i;){var l=Wd(o[s],n[s]);if(l){if(s>=a)return l;var u=t[s];return l*(u=="desc"?-1:1)}}return r.index-e.index}function Jd(r,e,t){e.length?e=Se(e,function(n){return E(n)?function(i){return cr(i,n.length===1?n[0]:n)}:n}):e=[At];var s=-1;e=Se(e,Ze(Re));var o=Ud(r,function(n,i,a){var l=Se(e,function(u){return u(n)});return{criteria:l,index:++s,value:n}});return Ld(o,function(n,i){return Hd(n,i,t)})}function $o(r,e,t,s){return r==null?[]:(E(e)||(e=e==null?[]:[e]),t=t,E(t)||(t=t==null?[]:[t]),Jd(r,e,t))}var Zd=go("length"),Co="\\ud800-\\udfff",Yd="\\u0300-\\u036f",Xd="\\ufe20-\\ufe2f",ef="\\u20d0-\\u20ff",tf=Yd+Xd+ef,rf="\\ufe0e\\ufe0f",sf="["+Co+"]",br="["+tf+"]",kr="\\ud83c[\\udffb-\\udfff]",of="(?:"+br+"|"+kr+")",Do="[^"+Co+"]",Po="(?:\\ud83c[\\udde6-\\uddff]){2}",_o="[\\ud800-\\udbff][\\udc00-\\udfff]",nf="\\u200d",xo=of+"?",Eo="["+rf+"]?",af="(?:"+nf+"(?:"+[Do,Po,_o].join("|")+")"+Eo+xo+")*",lf=Eo+xo+af,uf="(?:"+[Do+br+"?",br,Po,_o,sf].join("|")+")",jo=RegExp(kr+"(?="+kr+")|"+uf+lf,"g");function cf(r){for(var e=jo.lastIndex=0;jo.test(r);)++e;return e}function df(r){return $u(r)?cf(r):Zd(r)}var ff="[object Map]",pf="[object Set]";function hf(r){if(r==null)return 0;if(te(r))return St(r)?df(r):r.length;var e=U(r);return e==ff||e==pf?r.size:Ms(r).length}function yf(r,e,t){return r=ur(r),t=t==null?0:Fs(wt(t),0,r.length),e=kt(e),r.slice(t,t+e.length)==e}function wr(r){const e=Ar(r);return gf(e)}function Ar(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(Ar).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+Ar(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function 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 ve={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:ve.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"?[]:ve.getEntriesByType("resource")}get(e){const t=this.getKey(e.name,e.context);return this.data.get(t)}getByType(e){return Array.from(this.data.values()).filter(t=>t.type===e)}getByName(e){return Array.from(this.data.values()).filter(t=>t.name===e)}clear(){this.data.clear()}getKey(e,t){if(!t)return e;const s=wr(t);return e+"_"+s}}let So=class Ki{nodes;edges;nodeKinds=new Map;nodeMeta=new Map;edgePolicy;constructor(){this.nodes=new Set,this.edges=new Map}addNode(e,t){this.nodes.has(e)||(this.nodes.add(e),this.edges.set(e,new Set)),t?.kind!==void 0&&this.nodeKinds.set(e,t.kind),t?.meta!==void 0&&this.nodeMeta.set(e,t.meta)}addDependency(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))throw new Error("Both nodes must exist before adding a dependency.");if(this.edgePolicy&&!this.edgePolicy({name:e,kind:this.nodeKinds.get(e)},{name:t,kind:this.nodeKinds.get(t)}))throw new Error(`Edge policy rejected dependency from "${e}" to "${t}".`);this.edges.get(e).add(t)}setEdgePolicy(e){this.edgePolicy=e}setNodeKind(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");t===void 0?this.nodeKinds.delete(e):this.nodeKinds.set(e,t)}getNodeKind(e){return this.nodeKinds.get(e)}setNodeMeta(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodeMeta.set(e,t)}getNodeMeta(e){return this.nodeMeta.get(e)}removeNode(e){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodes.delete(e),this.edges.delete(e);for(let t of this.edges.values())t.delete(e)}removeDependency(e,t){if(!this.edges.has(e))throw new Error("From node does not exist.");this.edges.get(e).delete(t)}hasNode(e){return this.nodes.has(e)}hasDependency(e,t){return this.edges.has(e)?this.edges.get(e).has(t):!1}getDependencies(e){if(!this.edges.has(e))throw new Error("Node does not exist.");return Array.from(this.edges.get(e))}getDependents(e){const t=[];for(let[s,o]of this.edges)o.has(e)&&t.push(s);return t}isCyclic(){const e=new Set,t=new Set,s=o=>{if(e.has(o))return!1;if(t.has(o))return!0;t.add(o);const n=this.edges.get(o);if(n){for(let i of n)if(s(i))return!0}return t.delete(o),e.add(o),!1};for(let o of this.nodes)if(s(o))return!0;return!1}validateNoCycles(){const e=new Set,t=new Set,s=[],o=n=>{if(e.has(n))return null;if(t.has(n)){const a=s.indexOf(n);return s.slice(a).concat([n])}t.add(n),s.push(n);const i=this.edges.get(n);if(i)for(let a of i){const l=o(a);if(l)return l}return s.pop(),t.delete(n),e.add(n),null};for(let n of this.nodes){const i=o(n);if(i)return{hasCycle:!0,path:i}}return{hasCycle:!1}}order(e){const t=new Set,s=new Set,o=[],n=e?.allowCycles??!1,i=a=>{if(t.has(a))return;if(s.has(a)){if(n)return;throw new Error("Graph has a cycle.")}s.add(a);const l=this.edges.get(a);if(l)for(let u of l)i(u);s.delete(a),t.add(a),o.push(a)};for(let a of this.nodes)t.has(a)||i(a);return o}clear(){this.nodes.clear(),this.edges.clear()}getNodes(){return Array.from(this.nodes)}getAllEdges(){const e=[];for(let[t,s]of this.edges)for(let o of s)e.push([t,o]);return e}getNodesWithNoDependants(){if(this.nodes.size===0)return[];const e=new Set;for(const s of this.edges.values())for(const o of s)e.add(o);const t=[];for(const s of this.nodes)e.has(s)||t.push(s);return t}getNodesByKind(e){const t=[];for(const s of this.nodes)this.nodeKinds.get(s)===e&&t.push(s);return t}getRootsByKind(e){const t=new Set(this.getNodesWithNoDependants()),s=Array.from(t);return e?s.filter(o=>this.nodeKinds.get(o)===e):s}getLeavesByKind(e){const t=[];for(const s of this.nodes){const o=this.edges.get(s);(!o||o.size===0)&&(!e||this.nodeKinds.get(s)===e)&&t.push(s)}return t}getDependenciesOfKind(e,t){return this.getDependencies(e).filter(s=>this.nodeKinds.get(s)===t)}getDependentsOfKind(e,t){return this.getDependents(e).filter(s=>this.nodeKinds.get(s)===t)}plan(e){const t=new Map;for(const i of this.nodes)t.set(i,0);for(const i of this.edges.values())for(const a of i)t.set(a,(t.get(a)||0)+1);const s=[];let o=Array.from(this.nodes).filter(i=>(t.get(i)||0)===0);const n=new Set;for(;o.length>0;){const i=o.slice();s.push(i),o=[];for(const a of i){if(n.has(a))continue;n.add(a);const l=this.edges.get(a);if(l)for(const u of l)t.set(u,(t.get(u)||0)-1),(t.get(u)||0)===0&&o.push(u)}}if(n.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const i=new Set(e.filterKinds);return{batches:s.map(a=>a.filter(l=>i.has(this.nodeKinds.get(l))))}}return{batches:s}}getImpactedNodes(e,t="downstream",s){const o=new Set(e),n=u=>!s||s.length===0||s.includes(this.nodeKinds.get(u)??void 0),i=()=>{const u=new Set,c=Array.from(o);for(;c.length;){const d=c.shift();for(const[f,h]of this.edges)h.has(d)&&!u.has(f)&&(u.add(f),c.push(f))}return u},a=()=>{const u=new Set,c=Array.from(o);for(;c.length;){const d=c.shift(),f=this.edges.get(d);if(f)for(const h of f)u.has(h)||(u.add(h),c.push(h))}return u};let l;return t==="both"?l=new Set([...i(),...a()]):t==="upstream"?l=a():l=i(),Array.from(l).filter(n)}toJSON(){const e=Array.from(this.nodes).map(s=>({name:s,kind:this.nodeKinds.get(s),meta:this.nodeMeta.get(s)})),t=this.getAllEdges().map(([s,o])=>({from:s,to:o}));return{nodes:e,edges:t}}static fromJSON(e){const t=new Ki;for(const s of e.nodes)t.addNode(s.name,{kind:s.kind,meta:s.meta});for(const s of e.edges)t.addDependency(s.from,s.to);return t}diff(e){const t=new Set(this.getNodes()),s=new Set(e.getNodes()),o=Array.from(s).filter(d=>!t.has(d)),n=Array.from(t).filter(d=>!s.has(d)),i=new Set(this.getAllEdges().map(d=>d.join("→"))),a=new Set(e.getAllEdges().map(d=>d.join("→"))),l=Array.from(a).filter(d=>!i.has(d)).map(d=>d.split("→")),u=Array.from(i).filter(d=>!a.has(d)).map(d=>d.split("→")),c=[];for(const d of new Set([...t,...s])){const f=this.nodeKinds.get(d),h=e.nodeKinds.get(d);f!==h&&c.push({name:d,from:f,to:h})}return{addedNodes:o,removedNodes:n,addedEdges:l,removedEdges:u,kindChanges:c}}};class vf{graph;nodeIndex;constructor(){this.graph=new So,this.nodeIndex=new Map}getNodeId(e,t){return`${e}.${t}`}parseNodeId(e){const t=e.split(".");return{modelKey:t[0],attributeKey:t.slice(1).join(".")}}addAttribute(e){const t=this.getNodeId(e.modelKey,e.attributeKey);this.nodeIndex.has(t)||(this.graph.addNode(t,{meta:e}),this.nodeIndex.set(t,e))}addAttributeDependency(e,t){this.addAttribute(e),this.addAttribute(t);const s=this.getNodeId(e.modelKey,e.attributeKey),o=this.getNodeId(t.modelKey,t.attributeKey);this.graph.hasDependency(s,o)||this.graph.addDependency(s,o)}getImpactedAttributes(e){const t=e.map(i=>this.getNodeId(i.modelKey,i.attributeKey)),s=this.graph.getImpactedNodes(t,"downstream").map(i=>this.nodeIndex.get(i)).filter(i=>i!==void 0),o=[...e,...s],n=new Set;return o.filter(i=>{const a=this.getNodeId(i.modelKey,i.attributeKey);return n.has(a)?!1:(n.add(a),!0)})}getProcessingOrder(e){const t=new Map,s=[...e].sort((o,n)=>o.processingStep-n.processingStep);for(const o of s){const{modelKey:n,attributeKey:i,processingStep:a}=o;t.has(n)||t.set(n,new Map);const l=t.get(n);l.has(a)||l.set(a,new Set),l.get(a).add(i)}return t}getAttributesForModel(e){const t=[];for(const s of this.nodeIndex.values())s.modelKey===e&&t.push(s);return t}getDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}getDependents(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependents(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}hasDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).length>0:!1}hasNode(e){return this.nodeIndex.has(e)}getAllAttributes(){return Array.from(this.nodeIndex.values())}getMaxDepth(){let e=0;const t=(s,o=new Set)=>{if(o.has(s))return 0;o.add(s);const n=this.graph.getDependencies(s);if(n.length===0)return 1;let i=0;for(const a of n){const l=t(a,new Set(o));i=Math.max(i,l)}return i+1};for(const s of this.graph.getNodes()){const o=t(s);e=Math.max(e,o)}return e}validateCompleteness(e){const t=[];for(const[s,o]of e)for(const n of o){const i=this.getNodeId(s,n);this.hasNode(i)||t.push({modelKey:s,attributeKey:n})}return{isComplete:t.length===0,missing:t}}clear(){this.graph.clear(),this.nodeIndex.clear()}getStats(){const e=new Map,t=new Map;for(const s of this.nodeIndex.values())e.set(s.modelKey,(e.get(s.modelKey)||0)+1),t.set(s.processingStep,(t.get(s.processingStep)||0)+1);return{totalAttributes:this.nodeIndex.size,totalDependencies:this.graph.getAllEdges().length,maxDepth:this.getMaxDepth(),attributesByModel:e,attributesByStep:t}}toJSON(){return{nodes:Array.from(this.nodeIndex.values()),edges:this.graph.getAllEdges().map(([e,t])=>{const s=this.parseNodeId(e),o=this.parseNodeId(t);return{from:s,to:o}})}}}const Mo={silent:0,error:1,warn:2,info:3,debug:4};let 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 Mo[e]<=Mo[t]}formatMessage(e){if(this.config.format==="json"){const i={timestamp:new Date(e.timestamp).toISOString(),level:e.level,message:e.message};return e.prefix&&(i.module=e.prefix),e.context&&(i.context=e.context),e.error&&(i.error={name:e.error.name,message:e.error.message,stack:e.error.stack}),JSON.stringify(i)}const t=new Date(e.timestamp).toISOString().substring(11,23),s=e.prefix?`[${e.prefix}]`:"",o=this.getLevelIcon(e.level),n=e.context?` ${JSON.stringify(e.context)}`:"";return`${t} ${o} ${s} ${e.message}${n}`.trim()}getLevelIcon(e){switch(e){case"error":return"✖";case"warn":return"⚠";case"info":return"ℹ";case"debug":return"⚙";default:return" "}}log(e,t,s,o){if(!this.shouldLog(e))return;const n={level:e,message:t,timestamp:Date.now(),prefix:this.config.prefix,context:s,error:o};if(this.config.onLog){this.config.onLog(n);return}const i=this.formatMessage(n);if(typeof console<"u")switch(e){case"error":o?console.error(i,o):console.error(i);break;case"warn":console.warn(i);break;case"debug":console.debug?console.debug(i):console.log(i);break;default:console.log(i)}}error(e,t,s){const o=t instanceof Error?t:void 0,n=t instanceof Error?s:t;this.log("error",e,n,o)}trackError(e,t,s){if(this.error(e,t,s?.context),this.config.onTrackError){const o={level:"error",message:e,timestamp:Date.now(),prefix:this.config.prefix,context:s?.context,error:t,errorType:s?.errorType,errorGroup:s?.errorGroup};this.config.onTrackError(o)}}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}child(e){const t={...this.config,...e,prefix:e.prefix?this.config.prefix?`${this.config.prefix}:${e.prefix}`:e.prefix:this.config.prefix};return new T(t)}configure(e){Object.assign(this.config,e)}};const Te=new bf;class kf{constructor(e){this.enabled=e,this.cache=new Map,this.cacheDependencies=new Map}enabled;cache;cacheDependencies;hitCount=0;missCount=0;log=Te.child({prefix:"CacheController"});get(e,t){if(!this.enabled)return;const s=this.getCacheName(e,t);return this.cache.has(s)?this.hitCount++:this.missCount++,this.cache.get(s)}set(e,t,s,o){if(!this.enabled)return;const n=this.getCacheName(e,t);this.cache.set(n,s),o?this.cacheDependencies.set(n,o):this.log.debug(`Cache entry '${e}' stored without dependencies. This prevents granular invalidation and may cause stale data.`)}has(e,t){return this.cache.has(this.getCacheName(e,t))}clear(){this.cache.clear(),this.cacheDependencies.clear(),this.hitCount=0,this.missCount=0}invalidateByDependencies(e){if(!this.enabled)return;const t=[];for(const[s,o]of this.cacheDependencies){let n=!1;for(const[i,a]of e){if(o.models.has(i))if(o.modelAttributes.has(i)){const l=o.modelAttributes.get(i);for(const u of a)if(l.has(u)){n=!0;break}}else n=!0;if(n)break}n&&t.push(s)}for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateByModels(e){if(!this.enabled)return;const t=new Set(e),s=[];for(const[o,n]of this.cacheDependencies)for(const i of t)if(n.models.has(i)){s.push(o);break}for(const o of s)this.cache.delete(o),this.cacheDependencies.delete(o)}invalidateByKeyPrefix(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())s.startsWith(e+"_")&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}invalidateForModel(e){this.invalidateByModels([e])}invalidateForAttribute(e,t){if(!this.enabled)return;const s=new Map;s.set(e,new Set([t])),this.invalidateByDependencies(s)}invalidateMatching(e){if(!this.enabled)return;const t=[];for(const s of this.cache.keys())e(s)&&t.push(s);for(const s of t)this.cache.delete(s),this.cacheDependencies.delete(s)}generateContext(e){try{return oe(e)}catch(t){return this.log.error("Error in cache generateContext",t),e}}getCacheName(e,t){const s=wr(t);return e+"_"+s}getStats(){const e=this.hitCount+this.missCount,t=e>0?this.hitCount/e:0;return{size:this.cache.size,hitRate:t,totalEntries:this.cache.size,entriesWithDependencies:this.cacheDependencies.size,hits:this.hitCount,misses:this.missCount}}}function W(r=10){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let s=0;s<r;s++)e+=t.charAt(Math.floor(Math.random()*t.length));return e}class $r{key;parentCd;dcuplInitOptions;analyticsController;off;updateListener=new Set;counter=0;constructor(){}_init(e){this.key=e.cdRefKey,this.analyticsController=e.analyticsController,this.parentCd=e.parentCd,this.dcuplInitOptions=e.dcuplInitOptions,this.parentCd&&(this.off=this.parentCd.on(t=>{t.action==="update"&&t.originCdRefKey===this.parentCd?.key&&(t.connectMessage=!1,this.trigger(t))}))}getCounter(){return this.parentCd?this.parentCd.getCounter():this.counter}increaseCounter(){this.parentCd?this.parentCd.increaseCounter():this.counter++}destroy(){this.off&&this.off()}trigger(e){e.originCdRefKey||(e.originCdRefKey=this.key),e.key||(this.increaseCounter(),e.key=this.getCounter()),e.end||(e.end=ve.now(),e.duration=e.start-e.end),this.updateListener.forEach(t=>{t(e)})}on(e){return this.updateListener.add(e),()=>{this.updateListener.delete(e)}}}const Ro=(r,e)=>e?typeof structuredClone<"u"?structuredClone(r):oe(r):r,Io=(r,e,t,s,o,n)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=Ro(n,i);if(t.scope==="list"&&(t.listKey=r.cdRef?.key||r.key,t.modelKey=r.model?.key||r.modelKey),t.type==="list_created"&&t.args[0].listKey.startsWith("__global_list__")||t.listKey?.startsWith("__global_list__"))return a;const l=ve.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=ve.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 wf(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 Af(r){return r instanceof Date}function To(r){return r instanceof Date&&!isNaN(r.getTime())}const $f={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 Cf(r){let e="^";const t=[];let s=r;const o=Object.entries($f).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 Df(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 Pf(r){if(r.month<1||r.month>12)return new Date(NaN);if(r.day<1||r.day>31)return new Date(NaN);if(r.hour<0||r.hour>23)return new Date(NaN);if(r.minute<0||r.minute>59)return new Date(NaN);if(r.second<0||r.second>59)return new Date(NaN);if(r.millisecond<0||r.millisecond>999)return new Date(NaN);const e=new Date(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return To(e)?e.getFullYear()!==r.year||e.getMonth()!==r.month-1||e.getDate()!==r.day?new Date(NaN):e:new Date(NaN)}function _f(r,e,t){if(r=r.trim(),e==="t"){const a=Number(r);return isNaN(a)?new Date(NaN):new Date(a*1e3)}if(e==="T"){const a=Number(r);return isNaN(a)?new Date(NaN):new Date(a)}const{regex:s,tokenOrder:o}=Cf(e),n=r.match(s);if(!n)return new Date(NaN);const i=Df(n,o);return Pf(i)}class xf{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 Ef{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 jf{parseCache;circularRefDetector;cacheHits=0;cacheMisses=0;constructor(e=1e3){this.parseCache=new xf(e),this.circularRefDetector=new Ef}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 jf;function be(r,e){if(e.includes("[*]")){const n=e.indexOf("[*]"),i=e.substring(0,n),a=e.substring(n+3),l=i?rt(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(...be(c,a.slice(1)));return u}const t=e.split(".");let s=[r];for(const n of t){const i=[];for(const a of s)if(a!=null)if(Array.isArray(a))for(const l of a){if(l==null)continue;const u=l[n];u!==void 0&&i.push(u)}else{const l=a[n];l!==void 0&&i.push(l)}if(s=i,s.length===0)return[]}const o=[];for(const n of s)if(Array.isArray(n))for(const i of n)i!==void 0&&o.push(i);else n!==void 0&&o.push(n);return o}function Cr(r){let e=0;for(let t of r){const s=t.toString().split(".")[1];s&&(e=Math.max(e,s.length))}return Math.pow(10,e)}function Oo(r,e,t){return(r*t+e*t)/t}function Sf(r,e,t){return r*t/(e*t)}const nt=(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=Tf(s,e));let i;return(o.types.includes("min")||o.types.includes("max"))&&(i=Rf(s,e)),r.types.forEach(a=>{a==="sum"?o.sum=n?.sum:a==="avg"?o.avg=n?.average:a==="count"?o.count=Mf(s,e):a==="min"?o.min=i&&i[0]:a==="max"?o.max=i&&i[1]:a==="distinct"?o.distinct=Of(r,e,t):a==="group"&&(o.group=If(r,e))}),o},Mf=(r,e)=>{const t=_.parse(r).isDeepQuery;let s=0;for(const o of e.values())if(o)if(t)s+=be(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},Rf=(r,e)=>{let t,s;const o=_.parse(r).isDeepQuery;for(const n of e.values()){if(!n)continue;let i;if(o)i=be(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]},If=(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=be(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},Tf=(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=be(n,r);else{const a=n[r];a===void 0?i=[]:Array.isArray(a)?i=a:i=[a]}for(const a of i)if(Array.isArray(a))for(const l of a)typeof l=="number"&&(t=Oo(t,l,Cr([t,l])),s++);else typeof a=="number"&&(t=Oo(t,a,Cr([t,a])),s++)}return s===0?void 0:{average:Sf(t,s,Cr([t,s])),count:s,sum:t}},Of=(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 it=class extends Error{query;constructor(e,t){const s=`Query Error: ${e} in ${JSON.stringify(t,null,2)}`;super(s),this.query=t,this.name="DcuplQueryError"}},ke=class{_defaultQueryOptions={modelKey:"",groupKey:"root",groupType:"and",queries:[]};_initOptions;currentQuery=oe(this._defaultQueryOptions);deepQueryService;constructor(e){this.deepQueryService=e||_}init(e){this._initOptions=oe(e),this.currentQuery=oe(this._defaultQueryOptions),this.currentQuery.modelKey=e.modelKey,"queries"in e&&Array.isArray(e.queries)&&(e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&(this.currentQuery.queries=oe(e.queries)),e.count!==void 0&&(this.currentQuery.count=e.count),e.start!==void 0&&(this.currentQuery.start=e.start),e.sort&&(this.currentQuery.sort=e.sort),e.projection&&(this.currentQuery.projection=e.projection))}reset(){return this.init(this._initOptions),this.getQuery()}isQuery(e){return"attribute"in e}isQueryGroup(e){return"queries"in e||"groupKey"in e}isRootQueryGroup(e){return this.isQueryGroup(e)&&e.groupKey==="root"}getQueryGroup(e){return this.currentQuery.queries.find(t=>this.isQueryGroup(t)&&t.groupKey===e)}getQuery(){return oe(this.currentQuery)}hasQueryGroup(e){return this.currentQuery.queries.some(t=>this.isQueryGroup(t)&&t.groupKey===e)}has(e){if(e.groupKey&&e.queryKey){const t=this.getQueryGroup(e.groupKey);if(t)return t.queries.some(s=>this.isQuery(s)&&s.queryKey===e.queryKey)}else if(e.groupKey)return this.hasQueryGroup(e.groupKey);return!1}validate(e){const t=e.queries.map(s=>this.validateQuery(s));return{valid:wo(t,s=>s.valid),errors:t.map(s=>s.errors).flat()}}applyOptions(e,t="update"){return t==="set"?(this.currentQuery.count=e.count,this.currentQuery.start=e.start,this.currentQuery.sort=e.sort,this.currentQuery.projection=e.projection):(typeof e?.sort<"u"&&(this.currentQuery.sort=e.sort),typeof e?.count<"u"&&(this.currentQuery.count=e.count),typeof e?.start<"u"&&(this.currentQuery.start=e?.start),typeof e?.projection<"u"&&(this.currentQuery.projection=e?.projection)),this.getQuery()}applyQuery(e,t,s){if(s||(s=this.currentQuery),Array.isArray(e))for(const o of e)this.applyQuery(o,t,s);else if(this.isRootQueryGroup(e))e.groupType&&(s.groupType=e.groupType),t?.mode==="set"?s.queries=e.queries:s.queries=[...s.queries,...e.queries],this.applyOptions(e,"set");else if(this.isQuery(e)){const o=s.queries.findIndex(n=>this.isQueryGroup(n)&&n.groupKey===e.attribute);if(o>-1){const n=s.queries[o];t?.mode==="set"?n.queries=[e]:n.queries.push(e)}else s.queries.push({groupKey:e.attribute,groupType:"or",queries:[e]})}else if(this.isQueryGroup(e)){const o=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=vr(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=vr(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 it("Missing attribute",e)),e.operator||t.push(new it("Missing operator",e)),typeof e.value>"u"&&t.push(new it("Missing value",e)),e.operator==="find"&&Array.isArray(e.value)&&t.push(new it("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 it("Invalid query definition",e)),{valid:!1,errors:t}}getQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)this.isQuery(i)?i.attribute&&!s.has(i.attribute)&&(t.push(i.attribute),s.add(i.attribute)):this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}extractQueryAttributes(e){const t=[],s=new Set,o=n=>{for(const i of n)if(this.isQuery(i)){if(i.attribute&&!s.has(i.attribute)){const a=this.getQueryAttributeForString(i.attribute);t.push(a),s.add(i.attribute)}}else this.isQueryGroup(i)&&o(i.queries)};return o(e?.queries||this.currentQuery.queries),t}getQueryAttributeForString(e){return this.deepQueryService.parse(e)}getDeepQueryService(){return this.deepQueryService}getProjectionForAttributes(e){const t={};return e.forEach(s=>{t[s]=!0}),t}getProjectionForAttributeEntries(e){const t={$:!0};return e.forEach(s=>{if(s.isDeepQuery){if(s.reference)if(s.referenceAttribute&&s.referenceAttribute.length>0){t[s.reference]||(t[s.reference]={$:!0});const o=this.deepQueryService.parse(s.referenceAttribute);if(o.isDeepQuery&&s.reference){const n=this.getProjectionForAttributeEntries([o]);Object.keys(n).forEach(i=>{i!=="$"&&s.reference&&(t[s.reference][i]=n[i])})}else s.reference&&(t[s.reference][s.referenceAttribute]=!0)}else t[s.reference]=!0}else t[s.attribute]=!0}),t}getAttributeNames(e){return this.getQueryAttributes(e)}getAttributeDetails(e){return this.extractQueryAttributes(e||this.currentQuery)}getCurrentAttributeNames(){return this.getAttributeNames(this.currentQuery)}getCurrentAttributeDetails(){return this.getAttributeDetails(this.currentQuery)}addCondition(e){return this.applyQuery(e,{mode:"add"})}addGroup(e){return this.applyQuery(e,{mode:"add"})}setCondition(e){return this.applyQuery(e,{mode:"set"})}setGroup(e){return this.applyQuery(e,{mode:"set"})}mergeQuery(e){if(e.queries&&Array.isArray(e.queries))for(const t of e.queries)this.applyQuery(t,{mode:"add"});return this.currentQuery}replaceQuery(e){return this.currentQuery.queries=[],e.groupType&&(this.currentQuery.groupType=e.groupType),e.queries&&Array.isArray(e.queries)&&(this.currentQuery.queries=e.queries),this.currentQuery}clear(){return this.reset()}clearConditions(){return this.removeAllQueries()}getCurrentQuery(){return this.getQuery()}isEmpty(){return this.currentQuery.queries.length===0}hasCondition(e){const t=s=>{for(const o of s)if(this.isQuery(o)){let n=!0;for(const i in e)if(o[i]!==e[i]){n=!1;break}if(n)return!0}else if(this.isQueryGroup(o)&&t(o.queries))return!0;return!1};return t(this.currentQuery.queries)}hasGroup(e){return this.hasQueryGroup(e)}getUsedAttributes(){return this.getAttributeNames()}getDeepQueryAttributes(){return this.getAttributeDetails().filter(e=>e.isDeepQuery)}getGroups(){return this.currentQuery.queries.filter(e=>this.isQueryGroup(e))}getTopLevelConditions(){return this.currentQuery.queries.filter(e=>this.isQuery(e))}getGroup(e){return this.getQueryGroup(e)}getConditionCount(){const e=t=>{let s=0;for(const o of t)this.isQuery(o)?s++:this.isQueryGroup(o)&&(s+=e(o.queries));return s};return e(this.currentQuery.queries)}};const Dr=new ke;function Kf(r,e,t,s,o,n,i){const a=Dr.removeQuery({groupKey:o},oe(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(Ff(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:qf(o,r,n),enabled:a.size>0,size:a.size,entry:s?.get(r),resultKeys:Array.from(a.keys())}}function Rt(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 Ff(r){switch(r){case"size-desc":return(e,t)=>t.size-e.size||Rt(e.value,t.value);case"size-asc":return(e,t)=>e.size-t.size||Rt(e.value,t.value);case"value-asc":return(e,t)=>Rt(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:-Rt(e.value,t.value)}}const qf=(r,e,t)=>{const s=t.queries.findIndex(o=>Dr.isQueryGroup(o)&&o.groupKey===r);return s>-1?!!t.queries[s].queries.find(o=>{if(Dr.isQuery(o)){const n=o.value?.key||o.value;return o.attribute===r&&n===e}return!1}):!1};class It{indexMap=new Map;dataMap=new Map;indexMetadata=new Map;constructor(){}reset(e){e?(this.indexMap.delete(e),this.dataMap.delete(e),this.indexMetadata.delete(e)):(this.indexMap.clear(),this.dataMap.clear(),this.indexMetadata.clear())}resetIndicesWhere(e){for(const t of Array.from(this.indexMap.keys()))e(t)&&this.reset(t)}fillDataMap(e,t){let s=this.dataMap.get(e);s||(s=new Map,this.dataMap.set(e,s));for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const a of o)this.fillDataMap(e,[a]);return}else o instanceof Date?n=o.toISOString():n=o;let i=s.get(n);i||(i={key:n},this.dataMap.get(e)?.set(n,i))}}fillInverseIndex(e,t,s){if(!e||!t||!s||!Array.isArray(s))return;const o=this.indexMap.get(e)||new Map;for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const l of n)this.fillInverseIndex(e,t,[l]);return}else n instanceof Date?i=n.toISOString():i=n;let a=o.get(i);a||(a=new Set,o.set(i,a)),a.add(t)}this.indexMap.set(e,o)}getIndex(e,t){const s=this.getIndexName(e,t);return this.indexMap.get(s)}getData(e,t){const s=this.getIndexName(e,t);return this.dataMap.get(s)}getOrCreateIndex(e,t,s){const o=this.getIndexName(e,s);let n=this.getIndex(o);const i=this.indexMetadata.get(o);if(i)i.lastAccessedAt=Date.now();else if(!n){const a=_.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=be(l,e),u.length===0&&(u=[void 0])):u=[l[e]],this.fillInverseIndex(o,l.key,u),this.fillDataMap(o,u)}n=this.getIndex(o)||new Map}return n}getIndexName(e,t){return t?e+"_"+wr(t):e}removeFromInverseIndex(e,t,s){const o=this.indexMap.get(e);if(o)for(const n of s){let i;if(typeof n=="object"&&n&&n.key)i=n.key;else if(Array.isArray(n)){for(const l of n)this.removeFromInverseIndex(e,t,[l]);return}else n instanceof Date?i=n.toISOString():i=n;const a=o.get(i);a&&(a.delete(t),a.size===0&&o.delete(i))}}updateInverseIndex(e,t,s,o){this.removeFromInverseIndex(e,t,s),this.fillInverseIndex(e,t,o)}removeFromDataMap(e,t){const s=this.dataMap.get(e);if(s)for(const o of t){let n;if(typeof o=="object"&&o&&o.key)n=o.key;else if(Array.isArray(o)){for(const i of o)this.removeFromDataMap(e,[i]);return}else o instanceof Date?n=o.toISOString():n=o;s.delete(n)}}updateDataMap(e,t,s){this.removeFromDataMap(e,t),this.fillDataMap(e,s)}removeItemFromAllIndices(e){for(const t of this.indexMap.values())for(const[s,o]of t)o.delete(e)&&o.size===0&&t.delete(s);for(const t of this.dataMap.values())t.has(e)&&t.delete(e)}resetAttributes(e){for(const t of e)this.reset(t)}isDeepQueryIndex(e){const t=e.includes("_")?e.split("_")[0]:e;try{return _.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 Oe="__";function Pr(r,e,t={key:"root"},s="root",o=new It,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=nt(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=nt(f,d,s.getIndex(f.attribute),f.attribute);c.values.push(h)}if(i.rows=i.rows||[],i.rows.push(c),t.rows.length>1){const f={...t,rows:t.rows.slice(1)};Pr(d,f,c,o+Oe+e.attribute+Oe+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+Oe+e.attribute+Oe+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=nt(f,d,s.getIndex(f.attribute),f.attribute);c.values.push(h)}if(i.columns=i.columns||[],i.columns.push(c),t.columns.length>1){const f={...t,columns:t.columns.slice(1)};Pr(d,f,c,o+Oe+e.attribute+Oe+l,s,n)}}}return i}const Bf=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/,Vf=/^-?\d+$/,Gf=/^-?\d+\.\d+$/,Uf=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,Nf=r=>r==="true"||r==="false"?"boolean":Vf.test(r)?"int":Gf.test(r)?"float":Bf.test(r)&&!Number.isNaN(Date.parse(r))?"date":"string",zf=r=>Uf.test(r),Lf=r=>r==null||r==="",Wf=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}},Hf=(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++,Lf(f)){h.empty++;continue}let p;typeof f=="string"&&s?(p=Nf(f),p==="string"&&!h.hint&&zf(f)&&(h.hint="column looks date-like (non-ISO) — review manually")):p=Jf(f),h.observed.add(p)}}const a=[],l=[];for(const u of n){const c=o.get(u),{type:d,conflict:f}=Wf(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)=>Hf(r,typeof e=="boolean"?{deep:e}:e).properties,Qo=r=>Number(r)===r&&r%1===0,Bo=r=>Number(r)===r&&r%1!==0,Jf=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 Af(r)?"date":"json";default:return"any"}};class Zf{constructor(e,t,s){this.scriptController=e,this.globalItemService=t,this.modelParser=s}scriptController;globalItemService;modelParser;registeredCustomOperator=new Map;queryBuilder=new ke;registerCustomOperator(e,t){this.registeredCustomOperator.set(e,t)}transformValue(e,t){if(Array.isArray(e))return e.map(s=>this.transformValue(s,t));if(typeof e!="string")return e;for(const s of t)s==="lowercase"?e=e.toLowerCase():s==="trim"?e=e.trim():s==="removeWhitespace"&&(e=e.replace(/\s/g,""));return e}evaluateQuery(e,t){let s,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=rt(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?!Ao(s,o):Ao(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=bo(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,"/")&&ko(t,"/"))try{return new RegExp(t.slice(1,-1)).test(e)}catch{return!1}else return Array.isArray(e)?!!e.find(s=>Mt(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=>Mt(o,t,this.equalRegexFn)):e.every(o=>Mt(o,t,this.equalRegexFn)):!!Gd(e,t):Mt(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 wo(e.queries,t=>this.validateQuery(t));throw new Error("invalid query - missing query or attribute")}}getEvaluatedQueryDataset(e,t,s,o){const n=new Map;if(t.attribute.includes("[*]")){const i=t.options?.invert===!0,a=new Set;for(let l of s.values()){const u=this.queryBuilder.extractQueryAttributes({queries:[t]});if(u.some(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(".")?rt(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=bo(Array.from(i.values()),Array.from(u.values()),"key");for(const d of c)i.delete(d.key)}t.groupType==="and"?a=i:a=s}return i}queryData(e,t,s,o){if(t.queries.length===0)return e;const n=new Map(e);return t.groupKey||(t.groupKey="root"),t.groupType||(t.groupType="and"),t.queries||(t.queries=[]),this.validateQuery(t),this.evaluateQueryGroup(t,t,n,s,o)}}function Z(){const r=globalThis;return typeof r.scheduler?.yield=="function"?r.scheduler.yield():typeof r.setImmediate=="function"?new Promise(e=>r.setImmediate(()=>e())):typeof r.MessageChannel=="function"?new Promise(e=>{const t=new r.MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(null)}):new Promise(e=>setTimeout(e,0))}class Yf{scripts=new Map;scriptFunctions=new Map;constructor(){}keys(){return Array.from(this.scripts.keys())}setScript(e,t){this.scripts.set(e,t)}removeScript(e){this.scripts.delete(e)}getScript(e){return this.scripts.get(e)}hasScript(e){return this.scripts.has(e)}getScriptAsFn(e,t){if(this.scriptFunctions.has(e))return this.scriptFunctions.get(e);const s=this.getScript(e);if(!s)throw new Error(`Script ${e} not found`);const o=this.getWrapperScript(s),n=new Function("script_type",...t,o);return this.scriptFunctions.set(e,n),n}getWrapperScript(e){return`
3
3
  "use strict";
4
4
  ${e}
5
- `}executeScript(e,t,s){if(!this.getScript(e))throw new Error(`Script ${e} not found`);s.context||(s.context=s.options||{});const o=Object.keys(s),n=Object.values(s);return this.getScriptAsFn(e,o)(t,...n)}}const Tt=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>rt(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 Xf=rr(function(r,e){return Ie(r)?vo(r,Os(e,1,Ie)):[]});let ep=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 Ro(!!this.cdRef.dcuplInitOptions.performance?.cache?.enabled)}modelParser;cdRef;item;indicesController;queryManager;initialData;_filteredData;filteredDataStale=!1;model;get filteredData(){return this.filteredDataStale&&(this.filteredDataStale=!1,this._filteredData=this.getFilteredData(this.initialData,!1)),this._filteredData}set filteredData(e){this._filteredData=e,this.filteredDataStale=!1}filterItems=new Map;queryBuilder;cacheCtrl;projectionCache=new Map;init(e,t){this.model=e,this.initialData=t,this.filteredData=this.initialData,this.queryBuilder=new ke,this.queryBuilder.init({modelKey:e.key}),this.initFilterItems({skipProcessing:!0})}indexDependsOnAttributes(e,t){const s=e.includes("_")?e.split("_")[0]:e;try{const o=P.parse(s);if(!o.isDeepQuery)return!1;const n=o.attribute.split(".");for(let i=0;i<n.length-1;i++)if(t.has(n[i]))return!0;return!1}catch{return!0}}invalidateAllCaches(e){this.cacheCtrl.clear(),this.projectionCache.clear();let t=0;if(e&&e.size>0){const o=this.indicesController.getDeepIndexKeys(),n=[];for(const i of o)this.indexDependsOnAttributes(i,e)&&n.push(i);for(const i of n)this.indicesController.reset(i);t=n.length}else{const o=this.indicesController.getIndexCount().deep;this.indicesController.resetAllDeepIndices(),t=o}const s=this.cdRef.dcuplInitOptions.logging;if(s&&s.level==="debug"){const o=this.indicesController.getIndexCount();console.debug("[Filter] Caches invalidated",{granular:e!==void 0,changedAttributes:e?Array.from(e):"all",deepIndicesReset:t,shallowIndicesPreserved:o.shallow,totalIndices:o.total})}}update(e,t,s){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}updateWithChanges(e,t,s,o){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(o),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}resetCache(){this.invalidateAllCaches(),this.filteredDataStale=!0}getDeepQueryAttributes(e){const t=new Set;if(!e||!e.queries)return[];for(const s of e.queries)if(s.queries)for(const o of s.queries)o.attribute&&P.parse(o.attribute).isDeepQuery&&t.add(o.attribute);return Array.from(t)}getProjectionForQuery(e){const t=this.getDeepQueryAttributes(e);if(t.length===0)return null;const s=t.map(o=>P.parse(o));return this.queryBuilder.getProjectionForAttributeEntries(s)}getProjectionCacheKey(e){const t=this.getDeepQueryAttributes(e);return t.length===0?"":t.sort().join("|")}getProjectedData(e,t,s){if(s&&this.projectionCache.has(s))return this.projectionCache.get(s);const o=new Map;for(const[n,i]of e){const a=this.item.getProjectedData(t,this.model,i);o.set(n,a)}return s&&this.projectionCache.set(s,o),o}initFilterItems(e){[...this.model.properties.values(),...this.model.references.values()].forEach(t=>{t.filter&&(Array.isArray(e?.filterKeys)?e?.filterKeys.includes(t.key)&&this.updateFilterItem(t.key,e):this.updateFilterItem(t.key,e))})}getAggregate(e,t,s){if(P.parse(e.attribute).isDeepQuery)return nt(e,t,s,e.attribute);{const o=this.model.getAttribute(e.attribute);if(!o)throw new Error("Attribute not found");return nt(e,t,s,o.key)}}getSections(e){const t={_meta:{currentSize:0,initialSize:0},items:[]},s=P.parse(e.attribute),o=s.isDeepQuery;let n;if(!o&&(n=this.model.getAttribute(e.attribute),!n))throw new Error("Attribute not found");let i=new Map,a;!o&&n&&(n.type==="singleValued"||n.type==="multiValued")&&(a=this.modelParser.models.get(n.model));const l={},c=this.getSortingProjectionForModel(e,this.model);l.sort=c;let u=this.item.getItemsAsMap(this.filteredData,this.model,l);if(o){const p=this.queryBuilder.getProjectionForAttributeEntries([s]),y=new Map;for(const[v,g]of u){const k=this.item.getProjectedData(p,this.model,g);y.set(v,k)}u=y}const d=this.indicesController.getOrCreateIndex(`${e.attribute}`,u,{childLevelSorting:c,query:this.queryBuilder.getQuery()}),f=this.getAggregate({attribute:e.attribute,types:["distinct"],excludeUndefineds:!0},u,d);if(f.distinct)for(const p of f.distinct){let y={key:p.value,value:p.value};const v=p.keys.filter(k=>u.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(u,y.keys);p._aggregates=e.aggregates.map(g=>{const k=this.indicesController.getOrCreateIndex(`${g.attribute}`,v,{section:p.key,childLevelSorting:c,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(u,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(u,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 c=l?.comparisonType||"containsIgnoreCase";this.updateFilterItemProperty(l.key,a.key,a.type,c,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 c=this.getFacets(l.attributeKey,void 0,n);l.entries=c}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 c of l)typeof c=="number"&&(c<s&&(s=c),c>o&&(o=c));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 c of l)typeof c=="number"&&(c<n&&(n=c),c>i&&(i=c));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 c=l[e];if(typeof c>"u"||c===null)continue;const u=Array.isArray(c)?c:[c];for(const d of u)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 c=l[e];if(typeof c>"u"||c===null)continue;const u=Array.isArray(c)?c:[c];for(const d of u)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 c=o||this.initialData;if(!o){const d=this.queryBuilder.getQueryAttributeForString(e);if(d.isDeepQuery){const f=this.queryBuilder.getProjectionForAttributeEntries([d]);c=this.item.getItemsAsMap(c,this.model,{projection:f})}}if(!n||!l){this.indicesController.reset(e);const d=P.parse(e),f=d.isDeepQuery;let h=c;if(f){const p=this.queryBuilder.getProjectionForAttributeEntries([d]);h=new Map;for(const[y,v]of c){const g=this.item.getProjectedData(p,this.model,v);h.set(y,g)}}h.forEach(p=>{let y;f?(y=be(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 u=Kf(c,l,s,this.queryBuilder.getQuery(),e,this.indicesController.indexMap,this.queryManager);return this.cacheCtrl.set("facets",i,u,{models:new Set([this.model.key]),modelAttributes:new Map([[this.model.key,new Set([e])]])}),u}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=ve.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),c=this.getProjectedData(e,i,l),u=this.queryManager.queryData(c,n,t,this.indicesController.indexMap);a=new Map;for(const d of u.keys())e.has(d)&&a.set(d,e.get(d))}else a=this.queryManager.queryData(e,n,t,this.indicesController.indexMap);return this.cacheCtrl.set("data",s,a,{models:new Set([this.model.key]),modelAttributes:new Map}),a}getFilterItems(e){if(Array.isArray(e?.filterKeys)){const t=[];return e?.filterKeys.forEach(s=>{const o=this.getFilterItem(s,e);o&&t.push(o)}),t}else return e?.skipProcessing||this.initFilterItems(e),Array.from(this.filterItems.values())}getFilterItem(e,t){return this.filterItems.has(e)&&(t?.skipProcessing||this.updateFilterItem(e,t)),this.filterItems.get(e)}},Go=class{constructor(e,t){this.modelParser=e,this.scriptController=t}modelParser;scriptController;getItem(e,t,s,o){const n=o?.projection||{$:!0},i=t.get(e);return i?this.getProjectedData(n,s,i):null}getManyItems(e,t,s,o){const n=[];for(const i of e){const a=o?.projection||{$:!0},l=t.get(i);if(!l)continue;const c=this.getProjectedData(a,s,l);n.push(c)}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=(u,d,f)=>{const h=u[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((u,d)=>f=>{const h=t.sort.order.at(d),p=this.getUndefinedValueForSorting(u,h,s);return i(f,u,p)}),l=[...t.sort.order].map(u=>u.toLowerCase()),c=$o(n,[...a],l);return new Map(c.map(u=>[u.key,u]))}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 c=i.next().value;if(c)if(n&&o&&this.isValidProjection(o)){const u=this.getProjectedData(o,n,c[1]);a.set(c[0],u)}else a.set(c[0],c[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||Xf(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 c=s[n]||[];o[n]=c.map(u=>{const d=typeof u=="string"?u:u.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 c=s[n];if(c){const u=typeof c=="string"?c:c.key,d=l?.getEntry(u);d?o[n]=this.getProjectedData(i,l,d):this.modelParser.initOptions.referenceMetadata?.enabled?o[n]={key:u,_dcupl_ref_:"miss"}:delete o[n]}}}}}}),o}};var tp=Object.defineProperty,rp=Object.getOwnPropertyDescriptor,I=(r,e,t,s)=>{for(var o=rp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&tp(e,t,o),o};let S=class{constructor(e,t,s){this.dcuplApi=e,this.cdRef=t,this.indicesController=s,this.itemService=new Go(this.dcuplApi.modelParser,this.dcuplApi.scriptController),this.filter=new ep(this.dcuplApi.modelParser,this.cdRef,this.itemService,this.indicesController,this.dcuplApi.queryManager)}dcuplApi;cdRef;indicesController;metadata;model;filter;itemService;log=Te.child({prefix:"Catalog"});initListeners(){this.initListMetadata()}initListMetadata(){this.metadata={key:this.model.key,currentSize:this.filter.filteredData.size,initialSize:this.filter.initialData.size,attributes:this.getModelAttributes(),views:this.getViews(),appliedQuery:this.filter.queryBuilder.getQuery()}}getModelAttributes(){return[...this.model.references.values(),...this.model.properties.values()]}query={apply:(e,t)=>this.applyQuery(e,t),applyOptions:(e,t)=>this.applyOptions(e,t),remove:e=>this.removeQuery(e),reset:(e={skipProcessing:!1})=>this.resetQuery(e),execute:e=>this.executeQuery(e),one:e=>this._getItem(e),many:e=>this._getManyItems(e),get:()=>this.getQuery(),has:e=>this.hasGroupOrQueryKey(e),addCondition:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setCondition:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),addGroup:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setGroup:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),removeCondition:(e,t)=>{if(Array.isArray(e)){for(const s of e)this.removeQuery(s,t);return this.getQuery()}return this.removeQuery(e,t)},removeGroup:(e,t)=>this.removeQuery({groupKey:e},t),clear:e=>this.resetQuery(e),current:()=>this.getQuery(),isEmpty:()=>this.getQuery().queries.length===0,items:e=>this.executeQuery(e),first:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t)[0]},any:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t).length>0},count:e=>this.executeQuery(e).length};filters={get:e=>this.getFilter(e),getAll:e=>this.getFilters(e)};fn={pivot:e=>this._getPivot(e),aggregate:e=>this.getAggregate(e),suggest:e=>this._getSuggestions(e),groupBy:e=>this._getSections(e),facets:e=>this._getFacets(e),metadata:()=>this._getMetadata()};getViews(){const e=[];return this.filter.modelParser.views.forEach(t=>{t.model===this.model.key&&e.push(t)}),e}_getMetadata(){return this.initListMetadata(),this.metadata}getFilters(e){return this._getFilters(e)}_getFilters(e){const t=this.filter.getFilterItems(e);return e?.filterKeys?e.filterKeys.map(s=>{const o=t.find(n=>n.key===s);return o||this.log.error("Filter not found",void 0,{filterKey:s,model:this.model.key}),o}).filter(Boolean):t}getFilter(e){return this._getFilter(e)}_getFilter(e){return this.filter.getFilterItem(e.filterKey,e)}getQuery(){return this.filter.queryBuilder.getQuery()}hasGroupOrQueryKey(e){return this.filter.queryBuilder.has(e)}applyQuery(e,t){const s=this.filter.queryBuilder.applyQuery(e,t);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}applyOptions(e,t){const s=this.filter.queryBuilder.applyOptions(e,t?.mode);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}removeQuery(e,t){let s;return e?s=this.filter.queryBuilder.removeQuery(e):s=this.filter.queryBuilder.removeAllQueries(),this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}resetQuery(e){const t=this.filter.queryBuilder.reset();return this.filter.updateFilteredData({skipProcessing:e?.skipProcessing}),t}executeQuery(e){if(!e)e=this.filter.queryBuilder.getQuery();else if(!e.queries){const i=this.filter.queryBuilder.getQuery();e=Object.assign({},i,e)}const t=this.filter.cacheCtrl.generateContext({options:e});if(this.filter.cacheCtrl.has("query",t))return this.filter.cacheCtrl.get("query",t);const s=Object.assign({},e,{modelKey:this.model.key}),o=this.dcuplApi.queryManager.queryData(this.filter.filteredData,s,!1,this.filter.indicesController.indexMap),n=this.itemService.getItems(o,this.model,e);return this.filter.cacheCtrl.set("query",t,n),n}_getSections(e){const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("sections",t))return this.filter.cacheCtrl.get("sections",t);const s=this.filter.getSections(e);return this.filter.cacheCtrl.set("sections",t,s),s}_getItem(e){return this.itemService.getItem(e.itemKey,this.filter.filteredData,this.model,e)}_getManyItems(e){return this.itemService.getManyItems(e.itemKeys,this.filter.filteredData,this.model,e)}_getSuggestions(e){typeof e.excludeUndefineds>"u"&&(e.excludeUndefineds=!0),typeof e.excludeNulls>"u"&&(e.excludeNulls=!0),typeof e.calculateResultKeys>"u"&&(e.calculateResultKeys=!0);const t=this.filter.cacheCtrl.generateContext({options:e,query:this.filter.queryBuilder.getQuery()});if(this.filter.cacheCtrl.has("suggestions",t))return this.filter.cacheCtrl.get("suggestions",t);const s=P.parse(e.attribute).isDeepQuery;if(!s&&!this.model.getAttribute(e.attribute))throw new Error(`Attribute ${e.attribute} does not exist`);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 c=new ke;c.init(this.filter.queryBuilder.getQuery()),c.removeQuery(e.excludeQuery),n=c.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 c=P.parse(e.attribute),u=this.filter.queryBuilder.getProjectionForAttributeEntries([c]),d=new Map;for(const[f,h]of o){const p=this.filter.item.getProjectedData(u,this.model,h);d.set(f,p)}i=d}const a=this.filter.indicesController.getOrCreateIndex(e.attribute,i,{query:n}),l=wf(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=P.parse(e.attribute).isDeepQuery;let o;if(!s){const i=this.model.references.get(e.attribute);i&&(o=this.filter.modelParser.models.get(i.model))}let n;if(s){const i=P.parse(e.attribute),a=this.filter.queryBuilder.getProjectionForAttributeEntries([i]);n=new Map;for(const[l,c]of this.filter.filteredData){const u=this.filter.item.getProjectedData(a,this.model,c);n.set(l,u)}}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=P.parse(e.attribute);let o=this.filter.filteredData;if(s.isDeepQuery){const i=this.filter.queryBuilder.getProjectionForAttributeEntries([s]),a=new Map;for(const[l,c]of this.filter.filteredData){const u=this.filter.item.getProjectedData(i,this.model,c);a.set(l,u)}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 It;this.filter.filteredData.size===this.filter.initialData.size&&(s=this.filter.indicesController);const o=[...e.rows.map(a=>a.attribute),...e.columns.map(a=>a.attribute),...e.values.map(a=>a.attribute)].map(a=>P.parse(a)).filter(a=>a.isDeepQuery);let n;if(o.length>0){const a=this.filter.queryBuilder.getProjectionForAttributeEntries(o);n=new Map;for(const[l,c]of this.filter.filteredData){const u=this.filter.item.getProjectedData(a,this.model,c);n.set(l,u)}}const i=_r(this.filter.filteredData,e,{key:"root"},"root",s,n);return this.filter.cacheCtrl.set("pivot",t,i),i}};I([b({scope:"list",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"_getMetadata"),I([b({scope:"list",type:"filter_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"_getFilters"),I([b({scope:"list",type:"filter_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"_getFilter"),I([b({scope:"list",type:"query_get",cloneResult:!0})],S.prototype,"getQuery"),I([b({scope:"list",type:"query_has"})],S.prototype,"hasGroupOrQueryKey"),I([b({scope:"list",type:"query_apply",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"applyQuery"),I([b({scope:"list",type:"query_apply_options",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"applyOptions"),I([b({scope:"list",type:"query_remove",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"removeQuery"),I([b({scope:"list",type:"query_reset",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"resetQuery"),I([b({scope:"list",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"executeQuery"),I([b({scope:"list",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"_getSections"),I([b({scope:"list",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"_getItem"),I([b({scope:"list",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"_getManyItems"),I([b({scope:"list",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"_getSuggestions"),I([b({scope:"list",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"_getFacets"),I([b({scope:"list",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"getAggregate"),I([b({scope:"list",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],S.prototype,"_getPivot");let sp=class extends S{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 op(r,e){var t=-1,s=r.length;for(e||(e=Array(s));++t<s;)e[t]=r[t];return e}function np(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?Ct(t,a,l):ws(t,a,l)}return t}function ip(r,e,t){if(!z(t))return!1;var s=typeof e;return(s=="number"?te(t)&&tr(e,t.length):s=="string"&&e in t)?We(t[e],r):!1}function ap(r){return rr(function(e,t){var s=-1,o=t.length,n=o>1?t[o-1]:void 0,i=o>2?t[2]:void 0;for(n=r.length>3&&typeof n=="function"?(o--,n):void 0,i&&ip(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 lp(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var cp=Object.prototype,up=cp.hasOwnProperty;function dp(r){if(!z(r))return lp(r);var e=or(r),t=[];for(var s in r)s=="constructor"&&(e||!up.call(r,s))||t.push(s);return t}function Uo(r){return te(r)?Ss(r,!0):dp(r)}var fp="[object Object]",pp=Function.prototype,hp=Object.prototype,No=pp.toString,yp=hp.hasOwnProperty,gp=No.call(Object);function mp(r){if(!K(r)||ee(r)!=fp)return!1;var e=Ks(r);if(e===null)return!0;var t=yp.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&No.call(t)==gp}function vp(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 bp(r,e,t,s){return mr(r,function(o,n,i){e(s,o,t(o),i)}),s}function kp(r,e){return function(t,s){var o=E(t)?vp:bp,n={};return o(t,r,Re(s),n)}}function xr(r,e,t){(t!==void 0&&!We(r[e],t)||t===void 0&&!(e in r))&&Ct(r,e,t)}function Er(r,e){if(!(e==="constructor"&&typeof r[e]=="function")&&e!="__proto__")return r[e]}function wp(r){return np(r,Uo(r))}function Ap(r,e,t,s,o,n,i){var a=Er(r,t),l=Er(e,t),c=i.get(l);if(c){xr(r,t,c);return}var u=n?n(a,l,t+"",r,e,i):void 0,d=u===void 0;if(d){var f=E(l),h=!f&&Je(l),p=!f&&!h&&ir(l);u=l,f||h||p?E(a)?u=a:Ie(a)?u=op(a):h?(d=!1,u=Gs(l,!0)):p?(d=!1,u=Ys(l,!0)):u=[]:mp(l)||He(l)?(u=a,He(a)?u=wp(a):(!z(a)||Yt(a))&&(u=Xs(l))):d=!1}d&&(i.set(l,u),o(u,l,s,n,i),i.delete(l)),xr(r,t,u)}function zo(r,e,t,s,o){r!==e&&mo(e,function(n,i){if(o||(o=new L),z(n))Ap(r,e,i,t,zo,s,o);else{var a=s?s(Er(r,i),n,i+"",r,e,o):void 0;a===void 0&&(a=n),xr(r,i,a)}},Uo)}var $p=Object.prototype,Cp=$p.hasOwnProperty,Sr=kp(function(r,e,t){Cp.call(r,t)?r[t].push(e):Ct(r,t,[e])}),Dp="[object Boolean]";function _p(r){return r===!0||r===!1||K(r)&&ee(r)==Dp}var at=ap(function(r,e,t){zo(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")},xp=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")},Ep=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},Sp=(r,e)=>{const t=[];return r.references.forEach(s=>{e.has(s.model)||t.push({title:"Missing Model",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingModel",attribute:s.key,model:r.key,description:`Referenced model ${s.model} does not exist`}),"derive"in s&&t.push(...jp(s,r,e)),"resolve"in s&&t.push(...Mp(s,r,e)),"groupBy"in s&&t.push(...Rp(s,r))}),r.properties.forEach(s=>{"derive"in s&&t.push(...Ip(s,r,e)),"expression"in s&&t.push(...Tp(s,r))}),t},jp=(r,e,t)=>{const s=[],o=e.references.get(r.derive.localReference);if(!o)return s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Local Referenced ${r.derive.localReference} does not exist in model ${e.key}`}),s;const n=t.get(o.model);return n&&(n.references.get(r.derive.remoteReference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Remote Reference ${r.derive.remoteReference} does not exist in model ${n.key}`})),s},Mp=(r,e,t)=>{const s=[],o=t.get(r.resolve.model);return o?(o.references.get(r.resolve.reference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Resolved Reference ${r.resolve.reference} does not exist in model ${o.key}`}),s):(s.push({title:"Missing Model",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingModel",attribute:r.key,model:e.key,description:`Referenced model ${r.model} does not exist`}),s)},Rp=(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},Ip=(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},Tp=(r,e)=>{const t=[];return Pr(r.expression).variables.forEach(s=>{s.name==="key"||s.name.endsWith(".key")||!e.properties.get(s.name)&&!e.references.get(s.name)&&t.push({title:"Unknown Expression Variable",type:"model",errorGroup:"ModelDefinitionError",errorType:"UnknownExpressionVariable",attribute:r.key,model:e.key,description:`Expression Variable ${s.name} not found in expression ${r.key} in ${e.key}`})}),t},we="::";function Op(r){return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function Lo(r,e,t=we){return typeof e=="string"?String(r[e]):e.length===1?String(r[e[0]]):e.map(s=>String(r[s])).join(t)}function jr(r,e=we){if(r!==void 0)return typeof r=="string"?r:r.join(e)}const Kp={REF_VALUE:"_dcupl_ref_"},Wo={required:!0,forceStrictDataType:!1,nullable:!1,validatorHandling:"loose"},Ho={enabled:!0,attributes:Wo};let Fp=class{constructor(e){this.modelParser=e,this.cdRef=e.cdRef}modelParser;properties=new Map;references=new Map;attributeQualityConfigs=new Map;key;log=Te.child({prefix:"Model"});initialDefinition;data=new Map;supportsAutoCreation=!1;autoGenerateKey=!1;autoGenerateProperties=!1;autoGeneratePropertiesOption=!1;keyProperty="key";keyPropertySeparator;valueMappings=[];meta;qualityConfig=Ho;indicesController=new It;cdRef;groupedRefReverseIndex=new Map;init(e){this.key=e.key,this.initialDefinition=e,e.quality&&(this.qualityConfig=at({},Ho,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=xp(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=at({},Wo,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;Op(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(c=>{const u=this.processStringProperty(e,c,t);typeof u<"u"&&a.push(u)}))}else if(e.type==="Array<int>"){const l=this.getValueAsArray(n,e?.separator);Array.isArray(l)&&(a=[],l.forEach(c=>{const u=this.processIntProperty(e,c,t);typeof u<"u"&&a.push(u)}))}else if(e.type==="Array<float>"){const l=this.getValueAsArray(n,e?.separator);Array.isArray(l)&&(a=[],l.forEach(c=>{const u=this.processFloatProperty(e,c,t);typeof u<"u"&&a.push(u)}))}else if(e.type==="Array<date>"){const l=this.getValueAsArray(n,e?.separator);Array.isArray(l)&&(a=[],l.forEach(c=>{const u=this.processDateProperty(e,c,t);typeof u<"u"&&a.push(u)}))}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(!Bo(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}const n=parseInt(t,10);if(isNaN(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}if(this.isLossyNumericCoercion(t,n,!0)&&this.setError(this.getLossyCoercionError(e,t,n,s)),!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processFloatProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);if(o?.forceStrictDataType){if(!Vo(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}let n;const i=e.fractionDigits;if(typeof i>"u"?n=parseFloat(t):n=parseFloat(parseFloat(t).toFixed(i)),isNaN(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}if(this.isLossyNumericCoercion(t,n,!1)&&this.setError(this.getLossyCoercionError(e,t,n,s)),!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processJSONProperty(e,t,s){if(this.attributeQualityConfigs.get(e.key)?.forceStrictDataType){if(!K(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}if(K(t))return t;if(!K(t)&&typeof t=="string")try{return JSON.parse(t)}catch{this.setError(this.getWrongDataTypeError(e,t,s));return}}processBooleanProperty(e,t,s){if(this.attributeQualityConfigs.get(e.key)?.forceStrictDataType){if(!_p(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(!Oo(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 c=o.getEntry(String(a));if(!c){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 u={key:a};!c&&!o.supportsAutoCreation&&e.validity!=="strict"?this.setRefValue(u,"miss"):this.setRefValue(u,"hit"),i.push(u)}),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 c=e.keyProperty??this.keyProperty,u=e.keyPropertySeparator??this.keyPropertySeparator??we,d=jr(c,u);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 c=e.keyProperty??this.keyProperty,u=e.keyPropertySeparator??this.keyPropertySeparator??we,d=jr(c,u),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 c of t){c.origin&&(i[c.key]=i[c.origin]);const u=this.valueMappings.find(d=>d.attributes.includes(c.key));this.isValidValueMapping(u)&&(i=this.mapRawValueUsingValueMapping(i,c.key,u)),this.processBasicProperty(c,i,a,n)}for(const c of s){const u=this.attributeQualityConfigs.get(c.key);c.origin&&(i[c.key]=i[c.origin]);const d=this.valueMappings.find(h=>h.attributes.includes(c.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,c.key,d));let f=i[c.key];if(typeof f=="number"&&(f=String(f)),!f){this.indicesController.fillInverseIndex(c.key,a.key,[void 0]),u?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${c.type} reference "${c.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:c.key,model:e.model,meta:{rawValue:f,declaredType:c.type,origin:n}});continue}if(c.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?this.processSingleValuedReference(c,f,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.key,meta:{value:f}});else if(c.type==="multiValued"){const h=this.getValueAsArray(f,c?.separator);Array.isArray(h)?this.processMultiValuedReference(c,h,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.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=Tt(o,{...n}),l=JSON.parse(a),c=new ke;c.init({modelKey:s.model}),c.applyQuery(l,{mode:"set"}),l.projection||c.applyOptions({projection:{$:!1}});const u=c.getQuery();if(u.queries.length>0){const f=this.modelParser.dcuplInstance.query.execute(u);s.type==="singleValued"?f[0]&&(i[s.key]={key:f[0].key,_dcupl_ref_:"hit"}):s.type==="multiValued"&&(f.forEach(h=>{h._dcupl_ref_="hit"}),i[s.key]=f)}else s.type==="singleValued"?i[s.key]=null:s.type==="multiValued"&&(i[s.key]=[]);const d=String(i.key);i.key=d,this.data.set(d,i)}}}isValidValueMapping(e){if(!e||!Array.isArray(e.attributes)||!Array.isArray(e.values))return!1;const t=e.values.find(o=>!Array.isArray(o.from)),s=e.values.find(o=>o.to===void 0);return!(t||s)}mapRawValueUsingValueMapping(e,t,s){for(const o of s.values){if(o.from.includes("$dcupl_falsy")){if(typeof e[t]>"u"||e[t]===null||e[t]===""){e[t]=o.to;continue}continue}if(o.from.includes(e[t])){e[t]=o.to;continue}}return e}handleAutoCreationAndReturnKey(e,t){if(Array.isArray(t))return[];if(t===null)return{key:"null"};if(typeof t=="object"){const s=e.keyProperty,o=e.keyPropertySeparator??we;let n;e.autoGenerateKey?n=W():typeof s=="string"||Array.isArray(s)&&s.length>0?n=Lo(t,s,o):n=String(t.key),e.data.set(n,{key:n}),t.key=n;const i={model:e.key,data:[t]};return Z().then(()=>e.addContainer(i)),{key:n}}if(typeof t=="string"){e.data.set(t,{key:t});const s={model:e.key,data:[{key:t}]};Z().then(()=>e.addContainer(s))}return{key:String(t)}}addContainer(e){if(this.cdRef.analyticsController.mark({name:"model:autogenerate_data:start",context:e.model}),this.modelParser.handleAlternativeKey([e]),!Array.isArray(e.data)){this.setError({title:"Invalid Data",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",description:`Expect the data to be an Array but got ${typeof e.data}`,model:e.model});return}this.autoGenerateProperties&&this.generatePropertiesFromContainer(e),this.addBasicPropertiesAndReferences(e),this.addQueryReferences(e),this.addResolvedReferences(e),this.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(e),(this.hasDerivedPropertiesBasedOnResolvedReferences()||this?.hasDerivedReferencesBasedOnResolvedReferences())&&this.reRunDerivedPropertiesBasedOnResolves(e),this.cdRef.analyticsController.mark({name:"model:autogenerate_data:end",context:e.model}),this.cdRef.analyticsController.measure({name:"model:autogenerate_data",start:"model:autogenerate_data:start",end:"model:autogenerate_data:end",sum:!0,context:e.model,detail:{model:e.model,origin:this.key}})}addResolvedReferences(e){const t=this.getResolvedReferences().map(s=>{const o=this.modelParser.models.get(s.resolve.model);if(!o)return;const n=o.getDataAsArray(),i=o.indicesController.getIndex(s.resolve.reference);return{reference:s,model:o,remoteData:n,inverseKeys:i}}).filter(s=>!!s);for(const s of e.data){const o=String(s.key),n=this.data.get(o);for(const a of t){const l=a.reference.key;let c;if(a.inverseKeys){if(a.reference.type==="multiValued"){const u=a.inverseKeys.get(n.key)||new Set;c=Array.from(u).map(d=>({key:d}))}else{const u=a.inverseKeys.get(n.key),d=u&&Array.from(u)[0]||null;d?c={key:d}:c=null}n[l]=c,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(c=>({key:c}))}else{const l=n.inverseKeys.get(o.key),c=l?Array.from(l)[0]:null;c?a={key:c}: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(c=>{this.handleDerivedReferences(c,a)}),n.length>0&&n.forEach(c=>{this.handleGroupedReferences(c,a)}),t.length>0&&t.forEach(c=>{this.handleDerivedProperties(c,a)}),s.length>0&&s.forEach(c=>{const u=this.createExpressionContext(a),d=Tt(c.expression,u);a[c.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 c=this.modelParser.models.get(l.model);c&&(l.type==="singleValued"?this.handleSingleValuedDerivedProperties(c,n,l,a):l.type==="multiValued"&&this.handleMultiValuedDerivedProperties(c,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(u=>{const d=e?.getData().get(u.key);if(d)return d[o.derive.remoteProperty]}).filter(Boolean);let c;o.type.includes("Array<")?c=l:o.type==="string"||o.type==="int"||o.type==="float"||o.type==="date"?c=l.join(a):(o.type,c=l),t[o.key]=c}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(c=>{const u=o?.data.get(c.key);if(u){const d=u[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 c=l[e.derive.remoteReference];c?Array.isArray(c)?i=c.map(u=>u.key):"key"in c&&(i=[c.key]):i=[]}}let a;e.type==="singleValued"?a={key:i[0]}:a=i.map(l=>({key:l})),this.indicesController.fillInverseIndex(e.key,t.key,i),this.groupedRefReverseIndex.delete(e.key),t[e.key]=a}asStringArray(e){return e?Array.isArray(e)?e.map(t=>t.key):[e.key]:[]}buildReverseIndexForReference(e){const t=new Map;this.data.forEach(s=>{const o=this.asStringArray(s[e]);for(const n of o)t.has(n)||t.set(n,new Set),t.get(n).add(s.key)}),this.groupedRefReverseIndex.set(e,t)}ensureReverseIndex(e){return this.groupedRefReverseIndex.has(e)||this.buildReverseIndexForReference(e),this.groupedRefReverseIndex.get(e)}handleGroupedReferences(e,t){const s=[],o=this.references.get(e.groupBy.reference);if(o){const n=this.asStringArray(t[o.key]);if(!n.length)return;const i=this.ensureReverseIndex(o.key),a=new Set;for(const l of n){const c=i.get(l);c&&c.forEach(u=>a.add(u))}for(const l of a)e.groupBy.includeSelfInGroup?s.push({key:l}):t.key!==l&&s.push({key:l})}t[e.key]=s}resetData(){this.data.clear(),this.groupedRefReverseIndex.clear()}resetIndexMap(){this.indicesController.reset()}resetIndicesForChangedAttributes(e){this.indicesController.resetIndicesWhere(t=>{if(this.references.has(t))return!1;for(const s of e)if(t===s||t.startsWith(`${s}_`)||t.startsWith(`${s}.`))return!0;return!1})}deleteDataEntries(e){for(const t of e.data){const s=String(t.key);this.data.delete(s),this.indicesController.removeItemFromAllIndices(s),this.groupedRefReverseIndex.forEach(o=>{o.forEach(n=>{n.delete(s)})})}}getItemCount(){return this.data.size}getAttributes(){return[...this.references.values(),...this.properties.values()]}getAttribute(e){return e==="key"?{key:"key",type:"string"}:this.references.get(e)||this.properties.get(e)}getReferencesRelevantForDependencyGraph(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e))}getBasicReferences(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e)&&!("query"in e)&&!("groupBy"in e))}getQueryReferences(){return Array.from(this.references.values()).filter(e=>"query"in e)}getResolvedReferences(){return Array.from(this.references.values()).filter(e=>"resolve"in e)}getGroupedReferences(){return Array.from(this.references.values()).filter(e=>"groupBy"in e)}getDerivedReferences(){return Array.from(this.references.values()).filter(e=>"derive"in e)}getAggregatedReferences(){return Array.from(this.references.values()).filter(e=>"aggregate"in e)}getBasicProperties(){return Array.from(this.properties.values()).filter(e=>!("derive"in e)&&!("expression"in e))}getDerivedProperties(){return Array.from(this.properties.values()).filter(e=>"derive"in e)}getDerivedPropertiesForBasicAndDerivedReferences(){const e=this.getBasicReferences(),t=this.getDerivedReferences(),s=this.getQueryReferences(),o=this.getDerivedProperties(),n=[...e,...t,...s];return o.filter(i=>n.find(a=>a.key===i.derive?.localReference))}getDerivedPropertiesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedProperties().filter(t=>e.find(s=>s.key===t.derive?.localReference))}getDerivedReferencesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedReferences().filter(t=>e.find(s=>s.key===t.derive.localReference))}getExpressionProperties(){return Array.from(this.properties.values()).filter(e=>"expression"in e)}getAggregatedProperties(){return Array.from(this.properties.values()).filter(e=>"aggregate"in e)}hasBasicReferences(){return this.getBasicReferences().length>0}hasQueryReferences(){return this.getQueryReferences().length>0}hasResolvedReferences(){return this.getResolvedReferences().length>0}hasGroupedReferences(){return this.getGroupedReferences().length>0}hasDerivedReferences(){return this.getDerivedReferences().length>0}hasBasicProperties(){return this.getBasicProperties().length>0}hasDerivedProperties(){return this.getDerivedProperties().length>0}hasDerivedPropertiesForBasicReferences(){return this.getDerivedPropertiesForBasicAndDerivedReferences().length>0}hasDerivedPropertiesBasedOnResolvedReferences(){return this.getDerivedPropertiesForResolvedReferences().length>0}hasDerivedReferencesBasedOnResolvedReferences(){return this.getDerivedReferencesForResolvedReferences().length>0}hasExpressionProperties(){return this.getExpressionProperties().length>0}hasAggregatedProperties(){return this.getAggregatedProperties().length>0}getData(e){if(e?.itemKeys){const t=new Map;return e.itemKeys.forEach(s=>{const o=this.data.get(s);o&&t.set(o.key,o)}),t}return this.data}getDataAsArray(){return Array.from(this.data.values())}getEntry(e){return this.data.get(e)}setRefValue(e,t){this.modelParser.initOptions.referenceMetadata?.enabled&&Object.defineProperty(e,Kp.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 c=e.keyProperty??this.keyProperty,u=e.keyPropertySeparator??this.keyPropertySeparator??we,d=jr(c,u);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 c of s){c.origin&&(i[c.key]=i[c.origin]);const u=this.valueMappings.find(d=>d.attributes.includes(c.key));this.isValidValueMapping(u)&&(i=this.mapRawValueUsingValueMapping(i,c.key,u)),this.processBasicProperty(c,i,a,n)}for(const c of o){const u=this.attributeQualityConfigs.get(c.key);c.origin&&(i[c.key]=i[c.origin]);const d=this.valueMappings.find(p=>p.attributes.includes(c.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,c.key,d));let f=i[c.key];typeof f=="number"&&(f=String(f));const h=a[c.key];if(this.groupedRefReverseIndex.delete(c.key),!f){h&&this.indicesController.removeFromInverseIndex(c.key,a.key,[h]),this.indicesController.fillInverseIndex(c.key,a.key,[void 0]),delete a[c.key],u?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${c.type} reference "${c.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:c.key,model:e.model,meta:{rawValue:f,declaredType:c.type,origin:n}});continue}if(c.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?(h&&h.key!==f&&this.indicesController.removeFromInverseIndex(c.key,a.key,[h]),this.processSingleValuedReference(c,f,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.key,meta:{value:f}});else if(c.type==="multiValued"){const p=this.getValueAsArray(f,c?.separator);Array.isArray(p)?(h&&Array.isArray(h)&&this.indicesController.removeFromInverseIndex(c.key,a.key,h),this.processMultiValuedReference(c,p,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${c.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:c.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=Tt(n,{...i}),c=JSON.parse(l),u=new ke;u.init({modelKey:o.model}),u.applyQuery(c,{mode:"set"}),c.projection||u.applyOptions({projection:{$:!1}});const d=u.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(u=>{this.handleDerivedReferences(u,l)}),n.forEach(u=>{this.handleGroupedReferences(u,l)}),s.forEach(u=>{this.handleDerivedProperties(u,l)}),i.forEach(u=>{const d=this.createExpressionContext(l),f=Tt(u.expression,d);l[u.key]=f});const c=String(l.key);l.key=c,this.data.set(c,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)}}},qp=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;for(const t of this.deletedItems.values())e+=t.size;return e}getAffectedModelRatio(e){return e===0?0:(this.getModelsWithChanges().length+this.modelFullReset.size)/e}getAffectedItemRatio(e,t){return t===0?0:this.getChangedItems(e).size/t}clear(){this.changedAttributes.clear(),this.changedItems.clear(),this.deletedItems.clear(),this.modelFullReset.clear(),this.state="clean"}requiresFullReset(){return this.state==="full-reset"}getState(){return this.state}getStats(){let e=0,t=0,s=0;for(const o of this.changedItems.values())e+=o.size;for(const o of this.deletedItems.values())t+=o.size;for(const o of this.changedAttributes.values())s+=o.size;return{modelsWithChanges:this.getModelsWithChanges().length,modelsWithFullReset:this.modelFullReset.size,totalChangedItems:e,totalDeletedItems:t,totalChangedAttributes:s}}},Qp=class{metrics=[];enabled=!1;constructor(){}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}recordUpdate(e){this.enabled&&(this.metrics.push({...e,timestamp:Date.now()}),this.metrics.length>100&&this.metrics.shift())}getMetrics(){return[...this.metrics]}getSummary(){if(this.metrics.length===0)return{totalUpdates:0,partialUpdates:0,fullUpdates:0,avgPartialUpdateTime:0,avgFullUpdateTime:0,avgAttributesProcessed:0,avgModelsAffected:0,totalTimeSaved:0};const e=this.metrics.filter(l=>l.type==="partial"),t=this.metrics.filter(l=>l.type==="full"),s=e.length>0?e.reduce((l,c)=>l+c.durationMs,0)/e.length:0,o=t.length>0?t.reduce((l,c)=>l+c.durationMs,0)/t.length:0,n=e.length>0?e.reduce((l,c)=>l+(c.attributesProcessed||0),0)/e.length:0,i=e.length>0?e.reduce((l,c)=>l+(c.modelsAffected||0),0)/e.length:0,a=o>0?e.reduce((l,c)=>l+(o-c.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 Bp(r){return"query"in r}function Mr(r){return"resolve"in r}function Vp(r){return"derive"in r}function Gp(r){return"groupBy"in r}var Up=Object.defineProperty,Np=Object.getOwnPropertyDescriptor,Ot=(r,e,t,s)=>{for(var o=Np(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Up(e,t,o),o};let lt=class{constructor(e,t,s){this.cdRef=e,this.qualityController=t,this.dcuplInstance=s,this.qualityController.modelParser=this}cdRef;qualityController;dcuplInstance;unprocessedModelDescriptions=new Map;unprocessedData=[];keyedContainers=new WeakSet;dependencyGraph;attributeDependencyGraph;changeTracker=new qp;partialUpdateMetrics=new Qp;views=new Map;models=new Map;initOptions;calculationTimings=[];log=Te.child({prefix:"ModelParser"});async init(){this.changeTracker.clear(),this.qualityController.enabled&&(this.qualityController.resetDataErrors(),this.models.get("$DcuplErrorTrackingErrors")||this.qualityController.initErrorTrackingModels()),this.prepareModels(),this.qualityController.enabled&&this.validateModels(),this.initDependencyGraph(),this.buildAttributeDependencyGraph(),this.validateAttributeDependencyGraph();const e=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(e),this.consolidateUnprocessedData(e),this.qualityController.enabled&&await this.qualityController.initData(),this.changeTracker.clear()}prepareModels(){this.unprocessedModelDescriptions.forEach(e=>{if(this.models.has(e.key))this.models.get(e.key).resetData(),this.models.get(e.key).resetIndexMap(),this.models.get(e.key).applyPropertiesAndReferences(e);else{const t=new Fp(this);t.init(e),t.applyPropertiesAndReferences(e),this.models.set(t.key,t)}})}validateModels(){this.models.forEach(e=>{e.qualityConfig.enabled===!0&&Sp(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}
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 Tt=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>rt(e,s.trim(),""))):"",_r=r=>{const e=new Set;return r.replace(/\$\{(.*?)\}/g,(t,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(t=>({name:t}))}};var Xf=rr(function(r,e){return Ie(r)?vo(r,Os(e,1,Ie)):[]});let ep=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 kf(!!this.cdRef.dcuplInitOptions.performance?.cache?.enabled)}modelParser;cdRef;item;indicesController;queryManager;initialData;_filteredData;filteredDataStale=!1;model;get filteredData(){return this.filteredDataStale&&(this.filteredDataStale=!1,this._filteredData=this.getFilteredData(this.initialData,!1)),this._filteredData}set filteredData(e){this._filteredData=e,this.filteredDataStale=!1}filterItems=new Map;queryBuilder;cacheCtrl;projectionCache=new Map;init(e,t){this.model=e,this.initialData=t,this.filteredData=this.initialData,this.queryBuilder=new ke,this.queryBuilder.init({modelKey:e.key}),this.initFilterItems({skipProcessing:!0})}indexDependsOnAttributes(e,t){const s=e.includes("_")?e.split("_")[0]:e;try{const o=_.parse(s);if(!o.isDeepQuery)return!1;const n=o.attribute.split(".");for(let i=0;i<n.length-1;i++)if(t.has(n[i]))return!0;return!1}catch{return!0}}invalidateAllCaches(e){this.cacheCtrl.clear(),this.projectionCache.clear();let t=0;if(e&&e.size>0){const o=this.indicesController.getDeepIndexKeys(),n=[];for(const i of o)this.indexDependsOnAttributes(i,e)&&n.push(i);for(const i of n)this.indicesController.reset(i);t=n.length}else{const o=this.indicesController.getIndexCount().deep;this.indicesController.resetAllDeepIndices(),t=o}const s=this.cdRef.dcuplInitOptions.logging;if(s&&s.level==="debug"){const o=this.indicesController.getIndexCount();console.debug("[Filter] Caches invalidated",{granular:e!==void 0,changedAttributes:e?Array.from(e):"all",deepIndicesReset:t,shallowIndicesPreserved:o.shallow,totalIndices:o.total})}}update(e,t,s){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}updateWithChanges(e,t,s,o){this.model=e,this.initialData=t,this.indicesController=s,this.invalidateAllCaches(o),this.filteredData=this.getFilteredData(this.initialData,!1),this.initFilterItems({skipProcessing:!0})}resetCache(){this.invalidateAllCaches(),this.filteredDataStale=!0}getDeepQueryAttributes(e){const t=new Set;if(!e||!e.queries)return[];for(const s of e.queries)if(s.queries)for(const o of s.queries)o.attribute&&_.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 nt(e,t,s,e.attribute);{const o=this.model.getAttribute(e.attribute);if(!o)throw new Error("Attribute not found");return nt(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=be(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=Kf(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=ve.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=$o(n,[...a],l);return new Map(u.map(c=>[c.key,c]))}getUndefinedValueForSorting(e,t,s){const o=s?.properties.get(e);if(o){if(o.type==="string"){if(t=="ASC")return;if(t=="DESC")return""}if(o.type==="int"||o.type==="float"||o.type==="date"||o.type==="boolean"){if(t=="ASC")return 1/0;if(t=="DESC")return-1/0}}}isValidProjection(e){return!(!e||e.$===!0&&Object.keys(e).length===1)}getPagedData(e,t,s,o,n){const i=e.entries(),a=new Map;if(t===0&&s===e.size&&o?.$===!0&&Object.keys(o).length===1)return e;for(let l=0;l<t+s;l++){if(l<t){i.next();continue}if(l>t+s)break;const u=i.next().value;if(u)if(n&&o&&this.isValidProjection(o)){const c=this.getProjectedData(o,n,u[1]);a.set(u[0],c)}else a.set(u[0],u[1])}return a}isValidScriptSorting(e){return!(!e||!e.script)}isValidSortProjection(e){const t=["ASC","DESC"];return!(!e||!Array.isArray(e.attributes)||e.attributes.length===0||!Array.isArray(e.order)||e.attributes.length!==e.order.length||Xf(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 tp=Object.defineProperty,rp=Object.getOwnPropertyDescriptor,I=(r,e,t,s)=>{for(var o=rp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&tp(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 ep(this.dcuplApi.modelParser,this.cdRef,this.itemService,this.indicesController,this.dcuplApi.queryManager)}dcuplApi;cdRef;indicesController;metadata;model;filter;itemService;log=Te.child({prefix:"Catalog"});initListeners(){this.initListMetadata()}initListMetadata(){this.metadata={key:this.model.key,currentSize:this.filter.filteredData.size,initialSize:this.filter.initialData.size,attributes:this.getModelAttributes(),views:this.getViews(),appliedQuery:this.filter.queryBuilder.getQuery()}}getModelAttributes(){return[...this.model.references.values(),...this.model.properties.values()]}query={apply:(e,t)=>this.applyQuery(e,t),applyOptions:(e,t)=>this.applyOptions(e,t),remove:e=>this.removeQuery(e),reset:(e={skipProcessing:!1})=>this.resetQuery(e),execute:e=>this.executeQuery(e),one:e=>this._getItem(e),many:e=>this._getManyItems(e),get:()=>this.getQuery(),has:e=>this.hasGroupOrQueryKey(e),addCondition:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setCondition:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),addGroup:(e,t)=>this.applyQuery(e,{mode:"add",skipProcessing:t?.skipProcessing}),setGroup:(e,t)=>this.applyQuery(e,{mode:"set",skipProcessing:t?.skipProcessing}),removeCondition:(e,t)=>{if(Array.isArray(e)){for(const s of e)this.removeQuery(s,t);return this.getQuery()}return this.removeQuery(e,t)},removeGroup:(e,t)=>this.removeQuery({groupKey:e},t),clear:e=>this.resetQuery(e),current:()=>this.getQuery(),isEmpty:()=>this.getQuery().queries.length===0,items:e=>this.executeQuery(e),first:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t)[0]},any:e=>{const t=e?{...e,count:1}:{count:1};return this.executeQuery(t).length>0},count:e=>this.executeQuery(e).length};filters={get:e=>this.getFilter(e),getAll:e=>this.getFilters(e)};fn={pivot:e=>this._getPivot(e),aggregate:e=>this.getAggregate(e),suggest:e=>this._getSuggestions(e),groupBy:e=>this._getSections(e),facets:e=>this._getFacets(e),metadata:()=>this._getMetadata()};getViews(){const e=[];return this.filter.modelParser.views.forEach(t=>{t.model===this.model.key&&e.push(t)}),e}_getMetadata(){return this.initListMetadata(),this.metadata}getFilters(e){return this._getFilters(e)}_getFilters(e){const t=this.filter.getFilterItems(e);return e?.filterKeys?e.filterKeys.map(s=>{const o=t.find(n=>n.key===s);return o||this.log.error("Filter not found",void 0,{filterKey:s,model:this.model.key}),o}).filter(Boolean):t}getFilter(e){return this._getFilter(e)}_getFilter(e){return this.filter.getFilterItem(e.filterKey,e)}getQuery(){return this.filter.queryBuilder.getQuery()}hasGroupOrQueryKey(e){return this.filter.queryBuilder.has(e)}applyQuery(e,t){const s=this.filter.queryBuilder.applyQuery(e,t);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}applyOptions(e,t){const s=this.filter.queryBuilder.applyOptions(e,t?.mode);return this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}removeQuery(e,t){let s;return e?s=this.filter.queryBuilder.removeQuery(e):s=this.filter.queryBuilder.removeAllQueries(),this.filter.updateFilteredData({skipProcessing:t?.skipProcessing}),s}resetQuery(e){const t=this.filter.queryBuilder.reset();return this.filter.updateFilteredData({skipProcessing:e?.skipProcessing}),t}executeQuery(e){if(!e)e=this.filter.queryBuilder.getQuery();else if(!e.queries){const i=this.filter.queryBuilder.getQuery();e=Object.assign({},i,e)}const t=this.filter.cacheCtrl.generateContext({options:e});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 ke;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=wf(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 It;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=Pr(this.filter.filteredData,e,{key:"root"},"root",s,n);return this.filter.cacheCtrl.set("pivot",t,i),i}};I([b({scope:"list",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getMetadata"),I([b({scope:"list",type:"filter_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFilters"),I([b({scope:"list",type:"filter_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFilter"),I([b({scope:"list",type:"query_get",cloneResult:!0})],j.prototype,"getQuery"),I([b({scope:"list",type:"query_has"})],j.prototype,"hasGroupOrQueryKey"),I([b({scope:"list",type:"query_apply",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"applyQuery"),I([b({scope:"list",type:"query_apply_options",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"applyOptions"),I([b({scope:"list",type:"query_remove",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"removeQuery"),I([b({scope:"list",type:"query_reset",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"resetQuery"),I([b({scope:"list",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"executeQuery"),I([b({scope:"list",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getSections"),I([b({scope:"list",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getItem"),I([b({scope:"list",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getManyItems"),I([b({scope:"list",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getSuggestions"),I([b({scope:"list",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getFacets"),I([b({scope:"list",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"getAggregate"),I([b({scope:"list",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],j.prototype,"_getPivot");let sp=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 op(r,e){var t=-1,s=r.length;for(e||(e=Array(s));++t<s;)e[t]=r[t];return e}function np(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?Ct(t,a,l):ws(t,a,l)}return t}function ip(r,e,t){if(!z(t))return!1;var s=typeof e;return(s=="number"?te(t)&&tr(e,t.length):s=="string"&&e in t)?We(t[e],r):!1}function ap(r){return rr(function(e,t){var s=-1,o=t.length,n=o>1?t[o-1]:void 0,i=o>2?t[2]:void 0;for(n=r.length>3&&typeof n=="function"?(o--,n):void 0,i&&ip(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 lp(r){var e=[];if(r!=null)for(var t in Object(r))e.push(t);return e}var up=Object.prototype,cp=up.hasOwnProperty;function dp(r){if(!z(r))return lp(r);var e=or(r),t=[];for(var s in r)s=="constructor"&&(e||!cp.call(r,s))||t.push(s);return t}function Go(r){return te(r)?js(r,!0):dp(r)}var fp="[object Object]",pp=Function.prototype,hp=Object.prototype,Uo=pp.toString,yp=hp.hasOwnProperty,gp=Uo.call(Object);function mp(r){if(!K(r)||ee(r)!=fp)return!1;var e=Ks(r);if(e===null)return!0;var t=yp.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Uo.call(t)==gp}function vp(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 bp(r,e,t,s){return mr(r,function(o,n,i){e(s,o,t(o),i)}),s}function kp(r,e){return function(t,s){var o=E(t)?vp:bp,n={};return o(t,r,Re(s),n)}}function xr(r,e,t){(t!==void 0&&!We(r[e],t)||t===void 0&&!(e in r))&&Ct(r,e,t)}function Er(r,e){if(!(e==="constructor"&&typeof r[e]=="function")&&e!="__proto__")return r[e]}function wp(r){return np(r,Go(r))}function Ap(r,e,t,s,o,n,i){var a=Er(r,t),l=Er(e,t),u=i.get(l);if(u){xr(r,t,u);return}var c=n?n(a,l,t+"",r,e,i):void 0,d=c===void 0;if(d){var f=E(l),h=!f&&Je(l),p=!f&&!h&&ir(l);c=l,f||h||p?E(a)?c=a:Ie(a)?c=op(a):h?(d=!1,c=Gs(l,!0)):p?(d=!1,c=Ys(l,!0)):c=[]:mp(l)||He(l)?(c=a,He(a)?c=wp(a):(!z(a)||Yt(a))&&(c=Xs(l))):d=!1}d&&(i.set(l,c),o(c,l,s,n,i),i.delete(l)),xr(r,t,c)}function No(r,e,t,s,o){r!==e&&mo(e,function(n,i){if(o||(o=new L),z(n))Ap(r,e,i,t,No,s,o);else{var a=s?s(Er(r,i),n,i+"",r,e,o):void 0;a===void 0&&(a=n),xr(r,i,a)}},Go)}var $p=Object.prototype,Cp=$p.hasOwnProperty,jr=kp(function(r,e,t){Cp.call(r,t)?r[t].push(e):Ct(r,t,[e])}),Dp="[object Boolean]";function Pp(r){return r===!0||r===!1||K(r)&&ee(r)==Dp}var at=ap(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}),_p=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")},xp=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")},Ep=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},jp=(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(...Sp(s,r,e)),"resolve"in s&&t.push(...Mp(s,r,e)),"groupBy"in s&&t.push(...Rp(s,r))}),r.properties.forEach(s=>{"derive"in s&&t.push(...Ip(s,r,e)),"expression"in s&&t.push(...Tp(s,r))}),t},Sp=(r,e,t)=>{const s=[],o=e.references.get(r.derive.localReference);if(!o)return s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Local Referenced ${r.derive.localReference} does not exist in model ${e.key}`}),s;const n=t.get(o.model);return n&&(n.references.get(r.derive.remoteReference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Remote Reference ${r.derive.remoteReference} does not exist in model ${n.key}`})),s},Mp=(r,e,t)=>{const s=[],o=t.get(r.resolve.model);return o?(o.references.get(r.resolve.reference)||s.push({title:"Missing Reference",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingReference",attribute:r.key,model:e.key,description:`Resolved Reference ${r.resolve.reference} does not exist in model ${o.key}`}),s):(s.push({title:"Missing Model",type:"model",errorGroup:"ModelDefinitionError",errorType:"MissingModel",attribute:r.key,model:e.key,description:`Referenced model ${r.model} does not exist`}),s)},Rp=(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},Ip=(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},Tp=(r,e)=>{const t=[];return _r(r.expression).variables.forEach(s=>{s.name==="key"||s.name.endsWith(".key")||!e.properties.get(s.name)&&!e.references.get(s.name)&&t.push({title:"Unknown Expression Variable",type:"model",errorGroup:"ModelDefinitionError",errorType:"UnknownExpressionVariable",attribute:r.key,model:e.key,description:`Expression Variable ${s.name} not found in expression ${r.key} in ${e.key}`})}),t},we="::";function Op(r){return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function zo(r,e,t=we){return typeof e=="string"?String(r[e]):e.length===1?String(r[e[0]]):e.map(s=>String(r[s])).join(t)}function Sr(r,e=we){if(r!==void 0)return typeof r=="string"?r:r.join(e)}const Kp={REF_VALUE:"_dcupl_ref_"},Lo={required:!0,forceStrictDataType:!1,nullable:!1,validatorHandling:"loose"},Wo={enabled:!0,attributes:Lo};let Fp=class{constructor(e){this.modelParser=e,this.cdRef=e.cdRef}modelParser;properties=new Map;references=new Map;attributeQualityConfigs=new Map;key;log=Te.child({prefix:"Model"});initialDefinition;data=new Map;supportsAutoCreation=!1;autoGenerateKey=!1;autoGenerateProperties=!1;autoGeneratePropertiesOption=!1;keyProperty="key";keyPropertySeparator;valueMappings=[];meta;qualityConfig=Wo;indicesController=new It;cdRef;groupedRefReverseIndex=new Map;init(e){this.key=e.key,this.initialDefinition=e,e.quality&&(this.qualityConfig=at({},Wo,e.quality))}applyPropertiesAndReferences(e){const t=new Set;e.properties?.map(s=>{const o=_p(s);if(o)o.model=this.key,this.setError(o);else{if(t.has(s.key)){this.setError({title:"Duplicate Property Key",type:"model",errorGroup:"ModelDefinitionError",errorType:"DuplicatePropertyKey",description:`Model "${this.key}" declares property "${s.key}" more than once; the first definition is kept and the duplicate is ignored.`,attribute:s.key,model:this.key});return}t.add(s.key),this.setAttributeQualityConfig(s),this.properties.set(s.key,s)}}),e.references?.map(s=>{const o=xp(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=at({},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;Op(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(!St(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}}else if(n=String(t),!St(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(!Pp(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}return!!t}processDateProperty(e,t,s){if(t===""){this.setError(this.getWrongDataTypeError(e,t,s));return}const o=e.inputFormat;let n;try{if(o&&typeof o=="string"){let i=t;typeof i!="string"&&(i=String(i)),n=_f(i,o,new Date)}else n=new Date(t)}catch(i){this.log.error("Property extraction error",i,{property:e.key,model:this.key}),this.setError(this.getWrongDataTypeError(e,t,s));return}if(!To(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}return e.UTC&&(n=new Date(Date.UTC(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),n.getMilliseconds()))),n}processSingleValuedReference(e,t,s){const o=this.modelParser.models.get(e.model);if(!o)return;let n="";typeof t=="string"?n=t:typeof t=="object"&&t&&t.key&&(n=t.key);const i=o.getEntry(String(n));if(!i){if(o.supportsAutoCreation){const l=this.handleAutoCreationAndReturnKey(o,t);this.indicesController.fillInverseIndex(e.key,s.key,[t]),s[e.key]=l,this.setRefValue(l,"auto_hit");return}else if(this.indicesController.fillInverseIndex(e.key,s.key,[n]),this.setError({title:"Remote Reference Key Not Found",type:"model",errorGroup:"ReferenceDataError",errorType:"RemoteReferenceKeyNotFound",itemKey:s.key,attribute:e.key,description:`The reference "${e.key}" in the "${this.key}" model can not find the value "${t}" in the remote model "${e.model}"`,meta:{remoteModel:e.model,remoteKey:t}}),e.validity==="strict")return}this.indicesController.fillInverseIndex(e.key,s.key,[n]);const a={key:String(n)};s[e.key]=a,!i&&!o.supportsAutoCreation&&e.validity!=="strict"?this.setRefValue(a,"miss"):this.setRefValue(a,"hit")}processMultiValuedReference(e,t,s){const o=this.modelParser.models.get(e.model);if(!o)return;const n=this.getReferenceKeys(t),i=[];n.forEach((a,l)=>{const u=o.getEntry(String(a));if(!u){if(o.supportsAutoCreation){const d=this.handleAutoCreationAndReturnKey(o,t[l]);this.setRefValue(d,"auto_hit"),i.push(d);return}else if(this.setError({title:"Remote Reference Key Not Found",type:"model",errorGroup:"ReferenceDataError",errorType:"RemoteReferenceKeyNotFound",itemKey:s.key,attribute:e.key,description:`The reference "${e.key}" in the "${this.key}" model can not find the value "${a}" in the remote model "${e.model}"`,meta:{remoteModel:e.model,remoteKey:a}}),e.validity==="strict")return}const c={key:a};!u&&!o.supportsAutoCreation&&e.validity!=="strict"?this.setRefValue(c,"miss"):this.setRefValue(c,"hit"),i.push(c)}),this.indicesController.fillInverseIndex(e.key,s.key,i.map(a=>a.key)),s[e.key]=i}getViewKeys(){return this.modelParser._getViewKeys({modelKey:this.key})}addBasicPropertiesAndReferences(e){const t=this.getBasicProperties(),s=this.getBasicReferences(),o=this.modelParser.qualityController.dcupl?.getContainerSourceMetadata(e),n=o?.origin??"inline";o&&o.sourceColumns.length>0&&this.emitUnknownColumnErrors(e,o.sourceColumns,t,s,n);for(let i of e.data){if(i.key===void 0||i.key===null){const u=e.keyProperty??this.keyProperty,c=e.keyPropertySeparator??this.keyPropertySeparator??we,d=Sr(u,c);this.setError({title:"Missing Key",type:"model",errorGroup:"DataContainerError",errorType:"MissingKey",description:`A row in model "${e.model}" has no value for the key attribute "${d}"; the row is dropped.`,attribute:d,model:e.model});continue}let a=this.data.get(String(i.key));if(!a)a={key:String(i.key)};else if(e.type==="set"){const u=e.keyProperty??this.keyProperty,c=e.keyPropertySeparator??this.keyPropertySeparator??we,d=Sr(u,c),f=String(i.key);this.setError({title:"Non Unique Key",type:"model",errorGroup:"DataContainerError",errorType:"NonUniqueKey",description:`Row with key "${f}" in model "${e.model}" collides with an existing entry (key attribute "${d}"); the duplicate row is dropped`,itemKey:i.key,attribute:d,model:e.model,meta:{duplicateCount:1,droppedRows:[f]}})}for(const u of t){u.origin&&(i[u.key]=i[u.origin]);const c=this.valueMappings.find(d=>d.attributes.includes(u.key));this.isValidValueMapping(c)&&(i=this.mapRawValueUsingValueMapping(i,u.key,c)),this.processBasicProperty(u,i,a,n)}for(const u of s){const c=this.attributeQualityConfigs.get(u.key);u.origin&&(i[u.key]=i[u.origin]);const d=this.valueMappings.find(h=>h.attributes.includes(u.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,u.key,d));let f=i[u.key];if(typeof f=="number"&&(f=String(f)),!f){this.indicesController.fillInverseIndex(u.key,a.key,[void 0]),c?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${u.type} reference "${u.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:u.key,model:e.model,meta:{rawValue:f,declaredType:u.type,origin:n}});continue}if(u.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?this.processSingleValuedReference(u,f,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}});else if(u.type==="multiValued"){const h=this.getValueAsArray(f,u?.separator);Array.isArray(h)?this.processMultiValuedReference(u,h,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}})}}const l=String(a.key);a.key=l,this.data.set(l,a)}}addQueryReferences(e){const t=this.getQueryReferences();for(let s of t){const o=JSON.stringify(s.query);for(let n of e.data){let i=this.data.get(String(n.key));const a=Tt(o,{...n}),l=JSON.parse(a),u=new ke;u.init({modelKey:s.model}),u.applyQuery(l,{mode:"set"}),l.projection||u.applyOptions({projection:{$:!1}});const c=u.getQuery();if(c.queries.length>0){const f=this.modelParser.dcuplInstance.query.execute(c);s.type==="singleValued"?f[0]&&(i[s.key]={key:f[0].key,_dcupl_ref_:"hit"}):s.type==="multiValued"&&(f.forEach(h=>{h._dcupl_ref_="hit"}),i[s.key]=f)}else s.type==="singleValued"?i[s.key]=null:s.type==="multiValued"&&(i[s.key]=[]);const d=String(i.key);i.key=d,this.data.set(d,i)}}}isValidValueMapping(e){if(!e||!Array.isArray(e.attributes)||!Array.isArray(e.values))return!1;const t=e.values.find(o=>!Array.isArray(o.from)),s=e.values.find(o=>o.to===void 0);return!(t||s)}mapRawValueUsingValueMapping(e,t,s){for(const o of s.values){if(o.from.includes("$dcupl_falsy")){if(typeof e[t]>"u"||e[t]===null||e[t]===""){e[t]=o.to;continue}continue}if(o.from.includes(e[t])){e[t]=o.to;continue}}return e}handleAutoCreationAndReturnKey(e,t){if(Array.isArray(t))return[];if(t===null)return{key:"null"};if(typeof t=="object"){const s=e.keyProperty,o=e.keyPropertySeparator??we;let n;e.autoGenerateKey?n=W():typeof s=="string"||Array.isArray(s)&&s.length>0?n=zo(t,s,o):n=String(t.key),e.data.set(n,{key:n}),t.key=n;const i={model:e.key,data:[t]};return Z().then(()=>e.addContainer(i)),{key:n}}if(typeof t=="string"){e.data.set(t,{key:t});const s={model:e.key,data:[{key:t}]};Z().then(()=>e.addContainer(s))}return{key:String(t)}}addContainer(e){if(this.cdRef.analyticsController.mark({name:"model:autogenerate_data:start",context:e.model}),this.modelParser.handleAlternativeKey([e]),!Array.isArray(e.data)){this.setError({title:"Invalid Data",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",description:`Expect the data to be an Array but got ${typeof e.data}`,model:e.model});return}this.autoGenerateProperties&&this.generatePropertiesFromContainer(e),this.addBasicPropertiesAndReferences(e),this.addQueryReferences(e),this.addResolvedReferences(e),this.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(e),(this.hasDerivedPropertiesBasedOnResolvedReferences()||this?.hasDerivedReferencesBasedOnResolvedReferences())&&this.reRunDerivedPropertiesBasedOnResolves(e),this.cdRef.analyticsController.mark({name:"model:autogenerate_data:end",context:e.model}),this.cdRef.analyticsController.measure({name:"model:autogenerate_data",start:"model:autogenerate_data:start",end:"model:autogenerate_data:end",sum:!0,context:e.model,detail:{model:e.model,origin:this.key}})}addResolvedReferences(e){const t=this.getResolvedReferences().map(s=>{const o=this.modelParser.models.get(s.resolve.model);if(!o)return;const n=o.getDataAsArray(),i=o.indicesController.getIndex(s.resolve.reference);return{reference:s,model:o,remoteData:n,inverseKeys:i}}).filter(s=>!!s);for(const s of e.data){const o=String(s.key),n=this.data.get(o);for(const a of t){const l=a.reference.key;let u;if(a.inverseKeys){if(a.reference.type==="multiValued"){const c=a.inverseKeys.get(n.key)||new Set;u=Array.from(c).map(d=>({key:d}))}else{const c=a.inverseKeys.get(n.key),d=c&&Array.from(c)[0]||null;d?u={key:d}:u=null}n[l]=u,this.indicesController.fillInverseIndex(l,o,n[l])}}const i=String(n.key);n.key=i,this.data.set(i,n)}}rebuildResolvedReferencesForAllItems(e){let t=this.getResolvedReferences();if(t.length===0||e&&(t=t.filter(o=>e.has(o.key)),t.length===0))return;const s=t.map(o=>{const n=this.modelParser.models.get(o.resolve.model);if(!n)return;const i=n.indicesController.getIndex(o.resolve.reference);return{reference:o,model:n,remoteData:[],inverseKeys:i}}).filter(o=>!!o);for(const o of this.data.values())for(const n of s){const i=n.reference.key;let a;if(n.inverseKeys){if(n.reference.type==="multiValued"){const l=n.inverseKeys.get(o.key)||new Set;a=Array.from(l).map(u=>({key:u}))}else{const l=n.inverseKeys.get(o.key),u=l?Array.from(l)[0]:null;u?a={key:u}:a=null}o[i]=a,this.indicesController.fillInverseIndex(i,o.key,o[i])}}}addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(e){const t=this.getDerivedPropertiesForBasicAndDerivedReferences(),s=this.getExpressionProperties(),o=this.getDerivedReferences(),n=this.getGroupedReferences();for(const i of e.data){const a=this.data.get(String(i.key));o.length>0&&o.forEach(u=>{this.handleDerivedReferences(u,a)}),n.length>0&&n.forEach(u=>{this.handleGroupedReferences(u,a)}),t.length>0&&t.forEach(u=>{this.handleDerivedProperties(u,a)}),s.length>0&&s.forEach(u=>{const c=this.createExpressionContext(a),d=Tt(u.expression,c);a[u.key]=d});const l=String(a.key);a.key=l,this.data.set(l,a)}}handleDerivedProperties(e,t){const s=this.references.get(e.derive.localReference);if(s){const o=this.modelParser.models.get(s.model);o&&(s.type==="singleValued"?this.handleSingleValuedDerivedProperties(o,t,s,e):s.type==="multiValued"&&this.handleMultiValuedDerivedProperties(o,t,s,e))}}reRunDerivedPropertiesBasedOnResolves(e){const t=this.getDerivedProperties(),s=this.getDerivedReferences();for(const o of e.data){const n=this.data.get(String(o.key));s.forEach(a=>{this.handleDerivedReferences(a,n)}),t.forEach(a=>{const l=this.references.get(a.derive.localReference);if(l){const u=this.modelParser.models.get(l.model);u&&(l.type==="singleValued"?this.handleSingleValuedDerivedProperties(u,n,l,a):l.type==="multiValued"&&this.handleMultiValuedDerivedProperties(u,n,l,a))}});const i=String(n.key);n.key=i,this.data.set(i,n)}}handleSingleValuedDerivedProperties(e,t,s,o){const n=t[s.key];if(!n){delete t[o.key];return}const i=e?.getData().get(n.key);if(i){const a=i[o.derive.remoteProperty];typeof a<"u"&&(t[o.key]=a),o.index&&this.indicesController.fillInverseIndex(o.key,t.key,[a])}else delete t[o.key]}handleMultiValuedDerivedProperties(e,t,s,o){const n=t[s.key];let i;n?Array.isArray(n)?i=[...n]:n&&typeof n.key=="string"?i=[{key:n.key}]:i=[]:i=[];const a=o.derive?.separator||", ",l=i.map(c=>{const d=e?.getData().get(c.key);if(d)return d[o.derive.remoteProperty]}).filter(Boolean);let u;o.type.includes("Array<")?u=l:o.type==="string"||o.type==="int"||o.type==="float"||o.type==="date"?u=l.join(a):(o.type,u=l),t[o.key]=u}handleDerivedReferences(e,t){const s=this.references.get(e.derive.localReference);if(!s)return;const o=this.modelParser.models.get(s.model);if(!o)return;const n=t[s.key];if(!n)return;let i=[];if(Array.isArray(n)){const l=new Set;n.forEach(u=>{const c=o?.data.get(u.key);if(c){const d=c[e.derive.remoteReference];d&&(Array.isArray(d)?d.forEach(f=>{l.add(f.key)}):l.add(d.key))}}),i=Array.from(l.values())}else{const l=o?.data.get(n.key);if(l){const u=l[e.derive.remoteReference];u?Array.isArray(u)?i=u.map(c=>c.key):"key"in u&&(i=[u.key]):i=[]}}let a;e.type==="singleValued"?a={key:i[0]}:a=i.map(l=>({key:l})),this.indicesController.fillInverseIndex(e.key,t.key,i),this.groupedRefReverseIndex.delete(e.key),t[e.key]=a}asStringArray(e){return e?Array.isArray(e)?e.map(t=>t.key):[e.key]:[]}buildReverseIndexForReference(e){const t=new Map;this.data.forEach(s=>{const o=this.asStringArray(s[e]);for(const n of o)t.has(n)||t.set(n,new Set),t.get(n).add(s.key)}),this.groupedRefReverseIndex.set(e,t)}ensureReverseIndex(e){return this.groupedRefReverseIndex.has(e)||this.buildReverseIndexForReference(e),this.groupedRefReverseIndex.get(e)}handleGroupedReferences(e,t){const s=[],o=this.references.get(e.groupBy.reference);if(o){const n=this.asStringArray(t[o.key]);if(!n.length)return;const i=this.ensureReverseIndex(o.key),a=new Set;for(const l of n){const u=i.get(l);u&&u.forEach(c=>a.add(c))}for(const l of a)e.groupBy.includeSelfInGroup?s.push({key:l}):t.key!==l&&s.push({key:l})}t[e.key]=s}resetData(){this.data.clear(),this.groupedRefReverseIndex.clear()}resetIndexMap(){this.indicesController.reset()}resetIndicesForChangedAttributes(e){this.indicesController.resetIndicesWhere(t=>{if(this.references.has(t))return!1;for(const s of e)if(t===s||t.startsWith(`${s}_`)||t.startsWith(`${s}.`))return!0;return!1})}deleteDataEntries(e){for(const t of e.data){const s=String(t.key);this.data.delete(s),this.indicesController.removeItemFromAllIndices(s),this.groupedRefReverseIndex.forEach(o=>{o.forEach(n=>{n.delete(s)})})}}getItemCount(){return this.data.size}getAttributes(){return[...this.references.values(),...this.properties.values()]}getAttribute(e){return e==="key"?{key:"key",type:"string"}:this.references.get(e)||this.properties.get(e)}getReferencesRelevantForDependencyGraph(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e))}getBasicReferences(){return Array.from(this.references.values()).filter(e=>!("derive"in e)&&!("resolve"in e)&&!("query"in e)&&!("groupBy"in e))}getQueryReferences(){return Array.from(this.references.values()).filter(e=>"query"in e)}getResolvedReferences(){return Array.from(this.references.values()).filter(e=>"resolve"in e)}getGroupedReferences(){return Array.from(this.references.values()).filter(e=>"groupBy"in e)}getDerivedReferences(){return Array.from(this.references.values()).filter(e=>"derive"in e)}getAggregatedReferences(){return Array.from(this.references.values()).filter(e=>"aggregate"in e)}getBasicProperties(){return Array.from(this.properties.values()).filter(e=>!("derive"in e)&&!("expression"in e))}getDerivedProperties(){return Array.from(this.properties.values()).filter(e=>"derive"in e)}getDerivedPropertiesForBasicAndDerivedReferences(){const e=this.getBasicReferences(),t=this.getDerivedReferences(),s=this.getQueryReferences(),o=this.getDerivedProperties(),n=[...e,...t,...s];return o.filter(i=>n.find(a=>a.key===i.derive?.localReference))}getDerivedPropertiesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedProperties().filter(t=>e.find(s=>s.key===t.derive?.localReference))}getDerivedReferencesForResolvedReferences(){const e=this.getResolvedReferences();return this.getDerivedReferences().filter(t=>e.find(s=>s.key===t.derive.localReference))}getExpressionProperties(){return Array.from(this.properties.values()).filter(e=>"expression"in e)}getAggregatedProperties(){return Array.from(this.properties.values()).filter(e=>"aggregate"in e)}hasBasicReferences(){return this.getBasicReferences().length>0}hasQueryReferences(){return this.getQueryReferences().length>0}hasResolvedReferences(){return this.getResolvedReferences().length>0}hasGroupedReferences(){return this.getGroupedReferences().length>0}hasDerivedReferences(){return this.getDerivedReferences().length>0}hasBasicProperties(){return this.getBasicProperties().length>0}hasDerivedProperties(){return this.getDerivedProperties().length>0}hasDerivedPropertiesForBasicReferences(){return this.getDerivedPropertiesForBasicAndDerivedReferences().length>0}hasDerivedPropertiesBasedOnResolvedReferences(){return this.getDerivedPropertiesForResolvedReferences().length>0}hasDerivedReferencesBasedOnResolvedReferences(){return this.getDerivedReferencesForResolvedReferences().length>0}hasExpressionProperties(){return this.getExpressionProperties().length>0}hasAggregatedProperties(){return this.getAggregatedProperties().length>0}getData(e){if(e?.itemKeys){const t=new Map;return e.itemKeys.forEach(s=>{const o=this.data.get(s);o&&t.set(o.key,o)}),t}return this.data}getDataAsArray(){return Array.from(this.data.values())}getEntry(e){return this.data.get(e)}setRefValue(e,t){this.modelParser.initOptions.referenceMetadata?.enabled&&Object.defineProperty(e,Kp.REF_VALUE,{value:t,enumerable:!0,writable:!1,configurable:!1})}addBasicPropertiesAndReferencesPartial(e,t){const s=this.getBasicProperties().filter(i=>t.has(i.key)),o=this.getBasicReferences().filter(i=>t.has(i.key)),n=this.modelParser.qualityController.dcupl?.getContainerSourceMetadata(e)?.origin??"inline";for(let i of e.data){if(i.key===void 0||i.key===null){const u=e.keyProperty??this.keyProperty,c=e.keyPropertySeparator??this.keyPropertySeparator??we,d=Sr(u,c);this.setError({title:"Missing Key",type:"model",errorGroup:"DataContainerError",errorType:"MissingKey",description:`A row in model "${e.model}" has no value for the key attribute "${d}"; the row is dropped.`,attribute:d,model:e.model});continue}let a=this.data.get(String(i.key));a||(a={key:String(i.key)});for(const u of s){u.origin&&(i[u.key]=i[u.origin]);const c=this.valueMappings.find(d=>d.attributes.includes(u.key));this.isValidValueMapping(c)&&(i=this.mapRawValueUsingValueMapping(i,u.key,c)),this.processBasicProperty(u,i,a,n)}for(const u of o){const c=this.attributeQualityConfigs.get(u.key);u.origin&&(i[u.key]=i[u.origin]);const d=this.valueMappings.find(p=>p.attributes.includes(u.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,u.key,d));let f=i[u.key];typeof f=="number"&&(f=String(f));const h=a[u.key];if(this.groupedRefReverseIndex.delete(u.key),!f){h&&this.indicesController.removeFromInverseIndex(u.key,a.key,[h]),this.indicesController.fillInverseIndex(u.key,a.key,[void 0]),delete a[u.key],c?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${u.type} reference "${u.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:u.key,model:e.model,meta:{rawValue:f,declaredType:u.type,origin:n}});continue}if(u.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?(h&&h.key!==f&&this.indicesController.removeFromInverseIndex(u.key,a.key,[h]),this.processSingleValuedReference(u,f,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}});else if(u.type==="multiValued"){const p=this.getValueAsArray(f,u?.separator);Array.isArray(p)?(h&&Array.isArray(h)&&this.indicesController.removeFromInverseIndex(u.key,a.key,h),this.processMultiValuedReference(u,p,a)):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}})}}const l=String(a.key);a.key=l,this.data.set(l,a)}}addQueryAndResolvedReferencesPartial(e,t){if(this.hasQueryReferences()){const s=this.getQueryReferences().filter(o=>t.has(o.key));for(let o of s){const n=JSON.stringify(o.query);for(let i of e.data){let a=this.data.get(String(i.key));if(!a)continue;const l=Tt(n,{...i}),u=JSON.parse(l),c=new ke;c.init({modelKey:o.model}),c.applyQuery(u,{mode:"set"}),u.projection||c.applyOptions({projection:{$:!1}});const d=c.getQuery();if(d.queries.length>0){const h=this.modelParser.dcuplInstance.query.execute(d);o.type==="singleValued"?h[0]&&(a[o.key]={key:h[0].key,_dcupl_ref_:"hit"}):o.type==="multiValued"&&(h.forEach(p=>{p._dcupl_ref_="hit"}),a[o.key]=h)}else o.type==="singleValued"?a[o.key]=null:o.type==="multiValued"&&(a[o.key]=[]);const f=String(a.key);a.key=f,this.data.set(f,a)}}}this.hasResolvedReferences()&&this.getResolvedReferences().filter(s=>t.has(s.key)).length>0&&this.rebuildResolvedReferencesForAllItems()}createExpressionContext(e){const t={...e};return this.references.forEach((s,o)=>{const n=e[o];if(!n)return;const i=this.modelParser.models.get(s.model);if(i)if(s.type==="singleValued"&&typeof n=="object"&&"key"in n){const a=i.getData().get(n.key);a&&(t[o]=this.createNestedContext(a,i))}else s.type==="multiValued"&&Array.isArray(n)&&(t[o]=n.map(a=>{const l=i.getData().get(a.key);return l?this.createNestedContext(l,i):null}).filter(Boolean))}),t}createNestedContext(e,t){const s={...e};return t.references.forEach((o,n)=>{const i=e[n];if(!i)return;const a=this.modelParser.models.get(o.model);if(a&&o.type==="singleValued"&&typeof i=="object"&&"key"in i){const l=a.getData().get(i.key);l&&(s[n]={...l})}}),s}addDerivedAndExpressionAttributesPartial(e,t){const s=this.getDerivedPropertiesForBasicAndDerivedReferences().filter(a=>t.has(a.key)),o=this.getDerivedReferences().filter(a=>t.has(a.key)),n=this.getGroupedReferences().filter(a=>t.has(a.key)),i=this.getExpressionProperties().filter(a=>t.has(a.key));for(const a of e.data){const l=this.data.get(String(a.key));if(!l)continue;o.forEach(c=>{this.handleDerivedReferences(c,l)}),n.forEach(c=>{this.handleGroupedReferences(c,l)}),s.forEach(c=>{this.handleDerivedProperties(c,l)}),i.forEach(c=>{const d=this.createExpressionContext(l),f=Tt(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)}}},qp=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)}getEffectivelyChangedModels(){return new Set([...this.getModelsWithChanges(),...this.modelFullReset])}getModelsWithFullReset(){return this.modelFullReset}hasFullReset(e){return this.modelFullReset.has(e)}hasChanges(){return this.changedAttributes.size>0||this.changedItems.size>0||this.deletedItems.size>0||this.modelFullReset.size>0}getTotalChangedItemCount(){let e=0;for(const t of this.changedItems.values())e+=t.size;for(const t of this.deletedItems.values())e+=t.size;return e}getAffectedModelRatio(e){return e===0?0:(this.getModelsWithChanges().length+this.modelFullReset.size)/e}getAffectedItemRatio(e,t){return t===0?0:this.getChangedItems(e).size/t}clear(){this.changedAttributes.clear(),this.changedItems.clear(),this.deletedItems.clear(),this.modelFullReset.clear(),this.state="clean"}requiresFullReset(){return this.state==="full-reset"}getState(){return this.state}getStats(){let e=0,t=0,s=0;for(const o of this.changedItems.values())e+=o.size;for(const o of this.deletedItems.values())t+=o.size;for(const o of this.changedAttributes.values())s+=o.size;return{modelsWithChanges:this.getModelsWithChanges().length,modelsWithFullReset:this.modelFullReset.size,totalChangedItems:e,totalDeletedItems:t,totalChangedAttributes:s}}},Qp=class{metrics=[];enabled=!1;constructor(){}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}recordUpdate(e){this.enabled&&(this.metrics.push({...e,timestamp:Date.now()}),this.metrics.length>100&&this.metrics.shift())}getMetrics(){return[...this.metrics]}getSummary(){if(this.metrics.length===0)return{totalUpdates:0,partialUpdates:0,fullUpdates:0,avgPartialUpdateTime:0,avgFullUpdateTime:0,avgAttributesProcessed:0,avgModelsAffected:0,totalTimeSaved:0};const e=this.metrics.filter(l=>l.type==="partial"),t=this.metrics.filter(l=>l.type==="full"),s=e.length>0?e.reduce((l,u)=>l+u.durationMs,0)/e.length:0,o=t.length>0?t.reduce((l,u)=>l+u.durationMs,0)/t.length:0,n=e.length>0?e.reduce((l,u)=>l+(u.attributesProcessed||0),0)/e.length:0,i=e.length>0?e.reduce((l,u)=>l+(u.modelsAffected||0),0)/e.length:0,a=o>0?e.reduce((l,u)=>l+(o-u.durationMs),0):0;return{totalUpdates:this.metrics.length,partialUpdates:e.length,fullUpdates:t.length,avgPartialUpdateTime:s,avgFullUpdateTime:o,avgAttributesProcessed:n,avgModelsAffected:i,totalTimeSaved:a}}getLastUpdates(e=10){return this.metrics.slice(-e)}clear(){this.metrics=[]}getMetricsInRange(e,t){return this.metrics.filter(s=>s.timestamp>=e&&s.timestamp<=t)}};function Bp(r){return"query"in r}function Mr(r){return"resolve"in r}function Vp(r){return"derive"in r}function Gp(r){return"groupBy"in r}var Up=Object.defineProperty,Np=Object.getOwnPropertyDescriptor,Ot=(r,e,t,s)=>{for(var o=Np(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Up(e,t,o),o};let lt=class{constructor(e,t,s){this.cdRef=e,this.qualityController=t,this.dcuplInstance=s,this.qualityController.modelParser=this}cdRef;qualityController;dcuplInstance;unprocessedModelDescriptions=new Map;unprocessedData=[];keyedContainers=new WeakSet;dependencyGraph;attributeDependencyGraph;changeTracker=new qp;partialUpdateMetrics=new Qp;views=new Map;models=new Map;initOptions;calculationTimings=[];log=Te.child({prefix:"ModelParser"});async init(){this.changeTracker.clear(),this.qualityController.enabled&&(this.qualityController.resetDataErrors(),this.models.get("$DcuplErrorTrackingErrors")||this.qualityController.initErrorTrackingModels()),this.prepareModels(),this.qualityController.enabled&&this.validateModels(),this.initDependencyGraph(),this.buildAttributeDependencyGraph(),this.validateAttributeDependencyGraph();const e=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(e),this.consolidateUnprocessedData(e),this.qualityController.enabled&&await this.qualityController.initData(),this.changeTracker.clear()}prepareModels(){this.unprocessedModelDescriptions.forEach(e=>{if(this.models.has(e.key))this.models.get(e.key).resetData(),this.models.get(e.key).resetIndexMap(),this.models.get(e.key).applyPropertiesAndReferences(e);else{const t=new Fp(this);t.init(e),t.applyPropertiesAndReferences(e),this.models.set(t.key,t)}})}validateModels(){this.models.forEach(e=>{e.qualityConfig.enabled===!0&&jp(e,this.models).forEach(t=>{this.setError(t,e)})})}initDependencyGraph(){this.dependencyGraph=new So,this.models.forEach(t=>{this.dependencyGraph.addNode(t.key)}),this.models.forEach(t=>{t.getReferencesRelevantForDependencyGraph().forEach(s=>{t.key!==s.model&&(this.dependencyGraph.addNode(s.model),this.dependencyGraph.addDependency(t.key,s.model))})});const e=this.dependencyGraph.validateNoCycles();if(e.hasCycle){const t=e.path.join(" → ");throw this.log.error(`Circular dependency detected in model references: ${t}
6
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 bf,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(Bp(s))this.processQueryReference(t,o,s.query);else if(Mr(s))this.processResolvedReference(t,o,s.resolve);else if(Vp(s))this.processDerivedReference(t,o,s.derive);else if(Gp(s))this.processGroupedReference(t,o,s.groupBy);else{const n={modelKey:t,attributeKey:o,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttribute(n)}})})}validateAttributeDependencyGraph(){const e=new Map;this.models.forEach(s=>{const o=[];s.properties.forEach((n,i)=>{o.push(i)}),s.references.forEach((n,i)=>{o.push(i)}),o.length>0&&e.set(s.key,o)});const t=this.attributeDependencyGraph.validateCompleteness(e);if(!t.isComplete){const s=t.missing.length,o=t.missing.map(({modelKey:i,attributeKey:a})=>`${i}.${a}`).slice(0,10).join(", "),n=`Attribute dependency graph incomplete. ${s} attribute(s) missing: ${o}${s>10?` ... and ${s-10} more`:""}`;this.log.warn(`${n}
8
- These attributes will default to Step 1 processing which may be incorrect. This usually indicates a problem during expression or reference parsing.`)}}processExpressionProperty(e,t,s){const o={modelKey:e,attributeKey:t,type:"property",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const{variables:n}=Pr(s);n.forEach(i=>{const a=i.name.split("."),l=this.models.get(e);if(!l)return;const c=a[0];if(l.properties.has(c)){const u={modelKey:e,attributeKey:c,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,u)}else if(l.references.has(c)){const u={modelKey:e,attributeKey:c,type:"reference",processingStep:1};if(this.attributeDependencyGraph.addAttributeDependency(o,u),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,c=this.models.get(e);if(c){if(c.properties.has(l)){const u={modelKey:e,attributeKey:l,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,u)}else if(c.references.has(l)){const u={modelKey:e,attributeKey:l,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,u)}}})}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(u=>!u.startsWith("$")).length,i=this.changeTracker.getAffectedModelRatio(n);let a=0,l=0;for(const u of this.changeTracker.getModelsWithChanges()){const d=this.models.get(u);if(d){const f=d.getData().size;a+=f,l+=this.changeTracker.getChangedItems(u).size,l+=this.changeTracker.getDeletedItems(u).size}}const c=a>0?l/a:0;return i>t&&c>s?(o&&this.log.debug("Partial update decision: FULL",{reason:"both_ratios_high",modelRatio:i.toFixed(2),itemRatio:c.toFixed(2)}),{decision:!1,reason:`both_ratios_high:models=${i.toFixed(2)},items=${c.toFixed(2)}`}):(o&&this.log.debug("Partial update decision: PARTIAL",{modelRatio:i.toFixed(2),itemRatio:c.toFixed(2),modelThreshold:t,itemThreshold:s}),{decision:!0,reason:`optimal:models=${i.toFixed(2)},items=${c.toFixed(2)}`})}async partialUpdate(){const e=this.handleAlternativeKey(this.unprocessedData).filter(s=>!s.placeholderUid);for(const s of e)if(s.type==="remove"){const o=this.models.get(s.model);if(o){o.deleteDataEntries(s);for(const n of o.properties.values())this.changeTracker.recordAttributeChange(s.model,n.key);for(const n of o.references.values())this.changeTracker.recordAttributeChange(s.model,n.key)}}const t=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModelsPartial(t),this.consolidateUnprocessedData(t)}async reprocessData(){this.qualityController.enabled&&this.qualityController.resetModelErrors();const e=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(e)}getSortedCalculationTimings(){return $o(this.calculationTimings,"value")}addModel(e){if(e?.quality?.enabled!==!1)try{Ep(e)}catch(t){this.qualityController.enabled&&this.qualityController.setError({title:"Invalid Model Definition",type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:e.key,description:t.message});return}if(this.unprocessedModelDescriptions.has(e.key)){const t=this.unprocessedModelDescriptions.get(e.key),s=this.mergeModels(t,e);this.unprocessedModelDescriptions.set(e.key,s)}else this.unprocessedModelDescriptions.set(e.key,e);e.data&&this.addData({model:e.key,data:e.data,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty})}mergeModels(e,t){const s=Object.assign({},e,t);return(Array.isArray(e.properties)||Array.isArray(t.properties))&&(s.properties=[...Array.isArray(e.properties)?e.properties:[],...Array.isArray(t.properties)?t.properties:[]]),(Array.isArray(e.references)||Array.isArray(t.references))&&(s.references=[...Array.isArray(e.references)?e.references:[],...Array.isArray(t.references)?t.references:[]]),s}addData(e){if(!e||!e.model||!e.data)throw new Error("Invalid Data Container");if(!Array.isArray(e.data))throw new Error("Invalid Data - Data must be an Array");e.type||(e.type="set"),e.autoGenerateProperties&&this.addModel({key:e.model,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty||"key"}),this.changeTracker.recordDataChange(e),this.unprocessedData.push(e)}addView(e){this.views.set(e.key,e)}setError(e,t){this.qualityController.enabled&&t.qualityConfig.enabled===!0&&this.qualityController.setError(e)}getMergedContainers(e){const t=this.handleAlternativeKey(e).filter(n=>!n.placeholderUid),s=[],o=Sr(t,"model");for(const n in o){const i=o[n];if(i.length>1){const a=this.mergeContainers(i),l=this.mergeContainerSourceMetadata(i);l&&this.dcuplInstance.setContainerSourceMetadata(a,l),s.push(a)}else s.push(i[0])}return s}consolidateUnprocessedData(e){const t=this.unprocessedData.filter(s=>s.placeholderUid);for(const s of e)this.keyedContainers.add(s);this.unprocessedData=[...e,...t]}mergeContainers(e){let t;return e?.forEach(s=>{if(!t){if(s.type==="remove")return;t=new Map(s.data.map(o=>[o.key,o]));return}switch(s.type){case"upsert":s.data.forEach(o=>{if(t.has(o.key)){let n=t.get(o.key);n=at(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=at(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 c=this.attributeDependencyGraph.getAttributesForModel(i).find(u=>u.attributeKey===l);if(c)s.push(c);else{const u=this.models.get(i);if(u){const d=u.properties.get(l),f=u.references.get(l);(d||f)&&s.push({modelKey:i,attributeKey:l,type:d?"property":"reference",processingStep:1})}}}const o=this.attributeDependencyGraph.getImpactedAttributes(s),n=this.attributeDependencyGraph.getProcessingOrder(o);for(const i of e){const a=this.models.get(i.model);a?.autoGenerateProperties&&a.generatePropertiesFromContainer(i)}for(const i of[1,2,3,4])await this.processAttributesForStep(i,n,e);for(const[i,a]of n.entries()){const l=this.models.get(i);if(!l)continue;const c=new Set;for(const u of a.values())for(const d of u)c.add(d);l.resetIndicesForChangedAttributes(c)}for(const i of e){const a=this.models.get(i.model);if(a&&this.qualityController.enabled){const l=this.changeTracker.getChangedItems(a.key),c=this.changeTracker.getChangedAttributes().get(a.key);l.size>0&&c&&(this.qualityController.cleanUpErrorsForItems(a,l,c),this.qualityController.validateItemsPartial(a,l,c).forEach(u=>{this.setError(u,a)}))}}this.changeTracker.clear()}getResolvedReferenceProcessingOrder(e){const t=new Map,s=new Set;for(const[l,c]of e.entries()){const u=c.get(2);u&&u.size>0&&(s.add(l),t.set(l,new Set))}if(s.size===0)return this.dependencyGraph.order();for(const l of s){const c=this.models.get(l);if(!c)continue;const u=e.get(l)?.get(2);if(u)for(const d of u){const f=c.references.get(d);if(f&&Mr(f)){const h=f.resolve.model,p=f.resolve.reference,y=this.models.get(h);if(y){const v=y.references.get(p);v&&Mr(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 c=t.get(l);if(c)for(const u of c)a(u);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 c=W(),u=`dcupl:partial_process_data:step_${e}`;if(this.cdRef.analyticsController.mark({name:`${u}:start`,context:c}),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:`${u}:end`,context:c}),this.cdRef.analyticsController.measure({name:u,start:`${u}:start`,end:`${u}:end`,context:c,detail:{model:n,attributeCount:a.size}})}}handleAlternativeKey(e){return e.forEach(t=>{if(this.keyedContainers.has(t))return;const s=this.models.get(t.model),o=t.keyProperty??s?.keyProperty,n=t.keyPropertySeparator??s?.keyPropertySeparator??we,i=t.autoGenerateKey||s?.autoGenerateKey;(typeof o=="string"?o!==""&&o!=="key":Array.isArray(o)&&o.length>0)?t.data.forEach(a=>{a.key=Lo(a,o,n)}):i&&t.data.forEach(a=>{a.key||(a.key=W())}),this.keyedContainers.add(t)}),e}async handleDataContainer(e){for(const o of e){const n=this.models.get(o.model);n?.autoGenerateProperties&&n.generatePropertiesFromContainer(o)}const t=this.initOptions.performance?.containerBatchSize,s=t!==void 0;for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:start",context:a}),i&&(i.addBasicPropertiesAndReferences(n),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.cleanUpErrors(i,n)),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_1",start:"dcupl:process_data:step_1:start",end:"dcupl:process_data:step_1:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:start",context:a}),i&&i.hasQueryReferences()&&i.addQueryReferences(n),i&&i.hasResolvedReferences()&&i.addResolvedReferences(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_2",start:"dcupl:process_data:step_2:start",end:"dcupl:process_data:step_2:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:start",context:a}),i&&(i.hasDerivedPropertiesForBasicReferences()||i?.hasDerivedReferences()||i?.hasGroupedReferences()||i?.hasExpressionProperties())&&i.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_3",start:"dcupl:process_data:step_3:start",end:"dcupl:process_data:step_3:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model);if(!i){this.log.error("Model not found during data processing",void 0,{model:n.model,step:4});continue}const a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:start",context:a}),(i.hasDerivedPropertiesBasedOnResolvedReferences()||i.hasDerivedReferencesBasedOnResolvedReferences())&&i.reRunDerivedPropertiesBasedOnResolves(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_4",start:"dcupl:process_data:step_4:start",end:"dcupl:process_data:step_4:end",context:a,detail:{model:n.model}}),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.validateAttributesAfterInitialization(i).forEach(l=>{this.setError(l,i)}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}}_getModelKeys(){return Array.from(this.models.values()).map(e=>e.key).filter(e=>e&&!e.startsWith("$Dcupl"))}_getViewKeys(e){const t=e?.modelKey;return Array.from(this.views.values()).filter(s=>t?s.model===t:!0).map(s=>s.key)}getTotalItemCount(){let e=0;for(const t of this.models.values())e+=t.getItemCount();return e}};Ot([b({scope:"global",type:"model_add",connectMessage:!0})],lt.prototype,"addModel"),Ot([b({scope:"global",type:"data_change",connectMessage:!0})],lt.prototype,"addData"),Ot([b({scope:"global",type:"view_add",connectMessage:!0})],lt.prototype,"addView"),Ot([b({scope:"global",type:"dcupl_handle_datacontainer"})],lt.prototype,"handleDataContainer");function zp(r,e){return je(e,function(t){return r[t]})}function Lp(r){return r==null?[]:zp(r,Xe(r))}var Wp=Math.max;function Hp(r,e,t,s){r=te(r)?r:Lp(r),t=t?wt(t):0;var o=r.length;return t<0&&(t=Wp(o+t,0)),jt(r)?t<=o&&r.indexOf(e,t)>-1:!!o&&ks(r,e,t)>-1}var Jp=Object.defineProperty,Zp=Object.getOwnPropertyDescriptor,Jo=(r,e,t,s)=>{for(var o=Zp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Jp(e,t,o),o};let Rr=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 sp(this.dcuplApi,this.cdRef,n),this.catalog.init(this.modelKey,t,o))}initIndicesController(e,t,s){let o;if(e){o=new It;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=oe(e),this.key=this.options.listKey,this.modelKey=this.options.modelKey,this.setup(this.options)}initFromItemKeys(e,t){const s=new Map;return t.forEach(o=>{if(e.has(o)){const n=e.get(o);n&&s.set(o,n)}}),s}destroy(){try{this.dcuplApi.lists.destroy({listKey:this.key})}catch{}}_destroy(){this.catalog.filter.cdRef?.destroy()}update(e){(e&&e.reprocessData||!e)&&this.setup(this.options)}invalidate(){this.catalog&&this.catalog.filter.resetCache()}on(e){return this.cdRef.on(e)}};Jo([b({scope:"list",type:"list_destroyed",connectMessage:!0})],Rr.prototype,"_destroy"),Jo([b({scope:"list",type:"list_updated",action:"update",connectMessage:!0})],Rr.prototype,"update");var Yp=Object.defineProperty,Xp=Object.getOwnPropertyDescriptor,eh=(r,e,t,s)=>{for(var o=Xp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Yp(e,t,o),o};class Zo{constructor(e,t){this.dcuplInstance=e,this.cdRef=t}dcuplInstance;cdRef;lists=[];get(e){if(e)return this.lists.find(t=>t.key===e)}getAll(e){return e?this.lists.filter(t=>t.modelKey===e?.modelKey):this.lists}destroy(e){if(!e)this.lists.forEach(t=>t._destroy()),this.lists=[];else if(e.listKey){const t=this.lists.findIndex(s=>s.key===e.listKey);t>-1&&(this.lists[t]._destroy(),this.lists.splice(t,1))}else e.modelKey&&(this.lists=this.lists.filter(t=>t.modelKey===e.modelKey?(t._destroy(),!1):!0))}create(e){e.listKey=e.listKey||W();const t=new $r;t._init({cdRefKey:e.listKey,parentCd:this.dcuplInstance.cdRef,dcuplInitOptions:this.dcuplInstance.initOptions,analyticsController:this.dcuplInstance.analyticsController});const s=new Rr(this.dcuplInstance,t);return s.init(e),this.lists.push(s),s}}eh([b({scope:"global",type:"list_created",connectMessage:!0})],Zo.prototype,"create");let th=class{constructor(e){this.scriptsController=e}scriptsController;enabled=!1;maxErrorsPerGroup=1e3;errors=new Map;errorCounts=new Map;log=Te.child({prefix:"QualityController"});values={loading:0,processing:0,startup:0,counts:{resources:0,modelFiles:0,dataFiles:0,models:0,rows:0,attributes:0,dataEntries:0},unusedAttributes:[],errors:{size:0,UndefinedValue:0,UndefinedAttribute:0,WrongDataType:0,MissingModel:0,InvalidModelDescription:0,RemoteReferenceKeyNotFound:0},sizes:{totalEncoded:0,totalDecoded:0,unusedDecoded:0,models:[]}};modelParser;dcupl;getErrorGroupKey(e){const t="attribute"in e?e.attribute:void 0;return`${e.model??""}::${t??""}::${e.errorType}`}getGroupCount(e,t,s){const o=`${e??""}::${t??""}::${s}`;return this.errorCounts.get(o)?.count??0}setError(e){const t=this.getErrorGroupKey(e);let s=this.errorCounts.get(t);s||(s={model:e.model,attribute:"attribute"in e?e.attribute:void 0,errorGroup:e.errorGroup,errorType:e.errorType,type:e.type,count:0},this.errorCounts.set(t,s)),s.count+=1,!(s.count>this.maxErrorsPerGroup)&&(e.key||(e.key=W()),this.errors.set(e.key,e))}getErrorCounts(){return Array.from(this.errorCounts.values()).map(({model:e,attribute:t,errorType:s,count:o})=>({model:e,attribute:t,errorType:s,count:o}))}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 c of this.getModelErrors(o))c.attribute===i&&c.itemKey!=null&&(c.errorType==="UndefinedValue"||c.errorType==="WrongDataType")&&this.removeError(c.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 c=this.getGroupCount(o,l,"UndefinedValue");if(c>0&&c===t.data.length){for(const u of this.getModelErrors(o))u.attribute===l&&u.itemKey!=null&&u.errorType==="UndefinedValue"&&this.removeError(u.key);this.setError(this.buildAbsentColumnError(o,l))}}const i=this.getModelErrors(o).filter(l=>l.errorType==="WrongDataType"&&l.errorGroup==="PropertyDataError"&&l.title==="Wrong Data Type"&&l.itemKey!=null),a=Sr(i,"attribute");for(const l in a){const c=a[l];if(!c?.length)continue;const u=c[0].meta,d=e.properties.get(l)?.type??u?.expected??"unknown";for(const f of c)this.removeError(f.key);this.setError(this.buildColumnCoercionError(o,l,String(u?.rawValue??""),d,c.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(c=>c.errorType===i):a;for(const c of l)if(c.itemKey&&t.has(c.itemKey)){if(n&&c.attribute&&!n.has(c.attribute))continue;this.removeError(c.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 c of t){const u=n.get(c);if(!u)continue;const d=u[a.key],f=this.validateAttribute(d,l,a.key);for(const h of f)h.model=e.key,h.itemKey=u.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 c=n.data?.size||0;e+=c,s+=l*c}),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=Sr(e,s=>s.value?.model);return Object.keys(t).map(s=>{const o=t[s]?.reduce((i,a)=>{const l=a.value.encodedBodySize;return i+l},0),n=t[s]?.reduce((i,a)=>{const l=a.value.decodedBodySize;return i+l},0);return{model:s,decodedBodySize:n,encodedBodySize:o}})}calculateUnusedData(){const e=this.dcupl.models.keys();let t=0;return e.forEach(s=>{const o=this.dcupl.modelParser.unprocessedData.find(a=>a.model===s)?.data||[],n=this.getUnusedAttributesFromModel(this.dcupl,s);if(!n.length)return;const i=this.getDataWithAttributes(o,n);t+=JSON.stringify(i).length}),t}getDataWithAttributes(e,t){return e.map(s=>{const o={};return t.forEach(n=>{o[n]=s[n]}),o})}getUnusedAttributesFromModel(e,t){const s=e.modelParser.models.get(t),o=s?.getBasicProperties()||[],n=s?.getBasicReferences()||[],i=s?.keyProperty,a=[...o,...n].map(c=>c.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(c=>c.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 c={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(c),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&&!ko(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&&!Hp(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 rh=Object.defineProperty,sh=Object.getOwnPropertyDescriptor,V=(r,e,t,s)=>{for(var o=sh(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&rh(e,t,o),o};let Q=class{cdRef=new $r;analyticsController=new vf;containerSourceMetadata=new WeakMap;scriptController=new Yf;qualityController=new th(this.scriptController);log=Te.child({prefix:"Dcupl"});modelParser=new lt(this.cdRef,this.qualityController,this);globalItemService=new Go(this.modelParser,this.scriptController);cacheCtrl=new Ro(!1);queryManager=new Zf(this.scriptController,this.globalItemService,this.modelParser);_loaders=new Map;rootQueryBuilder=new ke;_defaultInitOptions={config:{projectId:void 0,apiKey:void 0,version:"draft"},errorTracking:{enabled:!1},quality:{enabled:!0},analytics:{enabled:!1},performance:{cache:{enabled:!0},clone:{enabled:!0},partialUpdates:{modelRatioThreshold:.5,itemRatioThreshold:.5,cacheInvalidationThreshold:.7,enableDetailedLogging:!1},autoUpdateLists:{enabled:!1}},referenceMetadata:{enabled:!1}};initOptions;lists=new Zo(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=at({},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(e.keys()),s=this.modelParser.dependencyGraph;if(s)for(const n of s.getImpactedNodes(Array.from(e.keys()),"downstream"))t.add(n);const o=this.modelParser.attributeDependencyGraph;if(o){const n=[];for(const[i,a]of e)if(a.size>0)for(const l of a)n.push({modelKey:i,attributeKey:l,type:"property",processingStep:1});else n.push(...o.getAttributesForModel(i));for(const i of o.getImpactedAttributes(n))t.add(i.modelKey)}return Array.from(t)}updateFnLists(e,t){const s=this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1;for(const o of this.lists.getAll()){if(e&&!this.isListAffectedByChanges(o,e.affectedModels)){s&&this.log.debug("List skipped (not affected)",{listKey:o.key,modelKey:o.modelKey});continue}try{this.shouldAutoUpdateList(o,t)?(s&&this.log.debug("List auto-updating",{listKey:o.key,modelKey:o.modelKey,affectedModels:e?.affectedModels??"all"}),o.update()):(s&&this.log.debug("List caches invalidated (auto-update disabled)",{listKey:o.key,modelKey:o.modelKey}),o.invalidate())}catch(n){this.log.error(`List refresh failed for '${o.key}'`,n)}}}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(),this.updateFnLists(null),!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?new Set(t.getModelsWithChanges()):null,a=s?t.getTotalChangedItemCount():0,l=this.cacheCtrl.getStats();if(await this.performUpdate(()=>this.modelParser.update()),s&&this.cacheCtrl.enabled&&o){const c=this.modelParser.getTotalItemCount(),u=a,d=c>0?u/c:0,f=this.initOptions.performance?.partialUpdates?.cacheInvalidationThreshold??.7,h=this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1;n&&n.size>0?(h&&this.log.debug("Cache invalidation: Full clear",{reason:"full_reset_detected"}),this.cacheCtrl.clear()):d>f?(h&&this.log.debug("Cache invalidation: Full clear",{reason:"high_item_ratio",ratio:d.toFixed(2),threshold:f,changedItems:u,totalItems:c}),this.cacheCtrl.clear()):(h&&this.log.debug("Cache invalidation: Selective",{changedItems:u,totalItems:c,ratio:d.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 c=this.cacheCtrl.getStats(),u=this.modelParser.partialUpdateMetrics.getLastUpdates(1);if(u.length>0&&u[0]){const d=u[0];d.cacheStats={entriesInvalidated:l.totalEntries-c.totalEntries,totalEntries:l.totalEntries}}}if(s&&o){const c=new Map(o);for(const d of[i,n])for(const f of d??[])c.has(f)||c.set(f,new Set);const u={isPartialUpdate:!0,changedModels:Array.from(c.keys()),changedAttributes:o,affectedModels:this.getAffectedModels(c)};this.updateFnLists(u,e?.autoUpdateLists),this.cdRef.trigger({scope:"global",type:"dcupl_partial_update",args:[u]})}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=ve.now(),o=t||W();this._loaders.set(o,e),e.core=this,e.key=o;const n=new $r;n._init({cdRefKey:o,parentCd:this.cdRef,dcuplInitOptions:this.initOptions,analyticsController:this.analyticsController}),e.cdRef=n,this.initOptions.config?.projectId&&e.defaultVariables.set("projectId",{key:"projectId",value:this.initOptions.config?.projectId}),this.initOptions.config?.apiKey&&e.defaultVariables.set("apiKey",{key:"apiKey",value:this.initOptions.config?.apiKey}),this.initOptions.config?.version&&e.defaultVariables.set("version",{key:"version",value:this.initOptions.config?.version}),this.cdRef.trigger({scope:"global",type:"loader_added",connectMessage:!0,args:[o],start:s})}removeLoader(e){const t=this._loaders.get(e);t&&t.destroy(),this._loaders.delete(e)}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 oh=class extends Q{version="2.0.0-beta.6";constructor(e){super(e)}};var Yo=typeof global=="object"&&global&&global.Object===Object&&global,nh=typeof self=="object"&&self&&self.Object===Object&&self,Y=Yo||nh||Function("return this")(),ue=Y.Symbol,Xo=Object.prototype,ih=Xo.hasOwnProperty,ah=Xo.toString,ct=ue?ue.toStringTag:void 0;function lh(r){var e=ih.call(r,ct),t=r[ct];try{r[ct]=void 0;var s=!0}catch{}var o=ah.call(r);return s&&(e?r[ct]=t:delete r[ct]),o}var ch=Object.prototype,uh=ch.toString;function dh(r){return uh.call(r)}var fh="[object Null]",ph="[object Undefined]",en=ue?ue.toStringTag:void 0;function Ke(r){return r==null?r===void 0?ph:fh:en&&en in Object(r)?lh(r):dh(r)}function Fe(r){return r!=null&&typeof r=="object"}var hh="[object Symbol]";function Ir(r){return typeof r=="symbol"||Fe(r)&&Ke(r)==hh}function yh(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var qe=Array.isArray,tn=ue?ue.prototype:void 0,rn=tn?tn.toString:void 0;function sn(r){if(typeof r=="string")return r;if(qe(r))return yh(r,sn)+"";if(Ir(r))return rn?rn.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Kt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var gh="[object AsyncFunction]",mh="[object Function]",vh="[object GeneratorFunction]",bh="[object Proxy]";function on(r){if(!Kt(r))return!1;var e=Ke(r);return e==mh||e==vh||e==gh||e==bh}var Tr=Y["__core-js_shared__"],nn=(function(){var r=/[^.]+$/.exec(Tr&&Tr.keys&&Tr.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function kh(r){return!!nn&&nn in r}var wh=Function.prototype,Ah=wh.toString;function Ae(r){if(r!=null){try{return Ah.call(r)}catch{}try{return r+""}catch{}}return""}var $h=/[\\^$.*+?()[\]{}|]/g,Ch=/^\[object .+?Constructor\]$/,Dh=Function.prototype,_h=Object.prototype,Ph=Dh.toString,xh=_h.hasOwnProperty,Eh=RegExp("^"+Ph.call(xh).replace($h,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Sh(r){if(!Kt(r)||kh(r))return!1;var e=on(r)?Eh:Ch;return e.test(Ae(r))}function jh(r,e){return r?.[e]}function $e(r,e){var t=jh(r,e);return Sh(t)?t:void 0}var Or=$e(Y,"WeakMap"),an=Object.create,Mh=(function(){function r(){}return function(e){if(!Kt(e))return{};if(an)return an(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})(),ln=(function(){try{var r=$e(Object,"defineProperty");return r({},"",{}),r}catch{}})();function Rh(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}var Ih=9007199254740991,Th=/^(?:0|[1-9]\d*)$/;function Oh(r,e){var t=typeof r;return e=e??Ih,!!e&&(t=="number"||t!="symbol"&&Th.test(r))&&r>-1&&r%1==0&&r<e}function Kh(r,e,t){e=="__proto__"&&ln?ln(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function cn(r,e){return r===e||r!==r&&e!==e}var Fh=Object.prototype,qh=Fh.hasOwnProperty;function Qh(r,e,t){var s=r[e];(!(qh.call(r,e)&&cn(s,t))||t===void 0&&!(e in r))&&Kh(r,e,t)}var Bh=9007199254740991;function un(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Bh}function Vh(r){return r!=null&&un(r.length)&&!on(r)}var Gh=Object.prototype;function dn(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Gh;return r===t}function Uh(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var Nh="[object Arguments]";function fn(r){return Fe(r)&&Ke(r)==Nh}var pn=Object.prototype,zh=pn.hasOwnProperty,Lh=pn.propertyIsEnumerable,Wh=fn((function(){return arguments})())?fn:function(r){return Fe(r)&&zh.call(r,"callee")&&!Lh.call(r,"callee")};function Hh(){return!1}var hn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,yn=hn&&typeof module=="object"&&module&&!module.nodeType&&module,Jh=yn&&yn.exports===hn,gn=Jh?Y.Buffer:void 0,Zh=gn?gn.isBuffer:void 0,mn=Zh||Hh,Yh="[object Arguments]",Xh="[object Array]",ey="[object Boolean]",ty="[object Date]",ry="[object Error]",sy="[object Function]",oy="[object Map]",ny="[object Number]",iy="[object Object]",ay="[object RegExp]",ly="[object Set]",cy="[object String]",uy="[object WeakMap]",dy="[object ArrayBuffer]",fy="[object DataView]",py="[object Float32Array]",hy="[object Float64Array]",yy="[object Int8Array]",gy="[object Int16Array]",my="[object Int32Array]",vy="[object Uint8Array]",by="[object Uint8ClampedArray]",ky="[object Uint16Array]",wy="[object Uint32Array]",D={};D[py]=D[hy]=D[yy]=D[gy]=D[my]=D[vy]=D[by]=D[ky]=D[wy]=!0,D[Yh]=D[Xh]=D[dy]=D[ey]=D[fy]=D[ty]=D[ry]=D[sy]=D[oy]=D[ny]=D[iy]=D[ay]=D[ly]=D[cy]=D[uy]=!1;function Ay(r){return Fe(r)&&un(r.length)&&!!D[Ke(r)]}function Kr(r){return function(e){return r(e)}}var vn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ut=vn&&typeof module=="object"&&module&&!module.nodeType&&module,$y=ut&&ut.exports===vn,Fr=$y&&Yo.process,Qe=(function(){try{var r=ut&&ut.require&&ut.require("util").types;return r||Fr&&Fr.binding&&Fr.binding("util")}catch{}})(),bn=Qe&&Qe.isTypedArray,Cy=bn?Kr(bn):Ay,Dy=Object.prototype,_y=Dy.hasOwnProperty;function Py(r,e){var t=qe(r),s=!t&&Wh(r),o=!t&&!s&&mn(r),n=!t&&!s&&!o&&Cy(r),i=t||s||o||n,a=i?Uh(r.length,String):[],l=a.length;for(var c in r)_y.call(r,c)&&!(i&&(c=="length"||o&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Oh(c,l)))&&a.push(c);return a}function kn(r,e){return function(t){return r(e(t))}}var xy=kn(Object.keys,Object),Ey=Object.prototype,Sy=Ey.hasOwnProperty;function jy(r){if(!dn(r))return xy(r);var e=[];for(var t in Object(r))Sy.call(r,t)&&t!="constructor"&&e.push(t);return e}function My(r){return Vh(r)?Py(r):jy(r)}var Ry=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Iy=/^\w*$/;function Ty(r,e){if(qe(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Ir(r)?!0:Iy.test(r)||!Ry.test(r)||e!=null&&r in Object(e)}var dt=$e(Object,"create");function Oy(){this.__data__=dt?dt(null):{},this.size=0}function Ky(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Fy="__lodash_hash_undefined__",qy=Object.prototype,Qy=qy.hasOwnProperty;function By(r){var e=this.__data__;if(dt){var t=e[r];return t===Fy?void 0:t}return Qy.call(e,r)?e[r]:void 0}var Vy=Object.prototype,Gy=Vy.hasOwnProperty;function Uy(r){var e=this.__data__;return dt?e[r]!==void 0:Gy.call(e,r)}var Ny="__lodash_hash_undefined__";function zy(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=dt&&e===void 0?Ny:e,this}function Ce(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}Ce.prototype.clear=Oy,Ce.prototype.delete=Ky,Ce.prototype.get=By,Ce.prototype.has=Uy,Ce.prototype.set=zy;function Ly(){this.__data__=[],this.size=0}function Ft(r,e){for(var t=r.length;t--;)if(cn(r[t][0],e))return t;return-1}var Wy=Array.prototype,Hy=Wy.splice;function Jy(r){var e=this.__data__,t=Ft(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Hy.call(e,t,1),--this.size,!0}function Zy(r){var e=this.__data__,t=Ft(e,r);return t<0?void 0:e[t][1]}function Yy(r){return Ft(this.__data__,r)>-1}function Xy(r,e){var t=this.__data__,s=Ft(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function ne(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ne.prototype.clear=Ly,ne.prototype.delete=Jy,ne.prototype.get=Zy,ne.prototype.has=Yy,ne.prototype.set=Xy;var ft=$e(Y,"Map");function eg(){this.size=0,this.__data__={hash:new Ce,map:new(ft||ne),string:new Ce}}function tg(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function qt(r,e){var t=r.__data__;return tg(e)?t[typeof e=="string"?"string":"hash"]:t.map}function rg(r){var e=qt(this,r).delete(r);return this.size-=e?1:0,e}function sg(r){return qt(this,r).get(r)}function og(r){return qt(this,r).has(r)}function ng(r,e){var t=qt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function de(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])}}de.prototype.clear=eg,de.prototype.delete=rg,de.prototype.get=sg,de.prototype.has=og,de.prototype.set=ng;var ig="Expected a function";function qr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(ig);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(qr.Cache||de),t}qr.Cache=de;var ag=500;function lg(r){var e=qr(r,function(s){return t.size===ag&&t.clear(),s}),t=e.cache;return e}var cg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ug=/\\(\\)?/g,dg=lg(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(cg,function(t,s,o,n){e.push(o?n.replace(ug,"$1"):s||t)}),e});function fg(r){return r==null?"":sn(r)}function pg(r,e){return qe(r)?r:Ty(r,e)?[r]:dg(fg(r))}function hg(r){if(typeof r=="string"||Ir(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function yg(r,e){e=pg(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[hg(e[t++])];return t&&t==s?r:void 0}function gg(r,e,t){var s=r==null?void 0:yg(r,e);return s===void 0?t:s}function mg(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var vg=kn(Object.getPrototypeOf,Object);function bg(){this.__data__=new ne,this.size=0}function kg(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function wg(r){return this.__data__.get(r)}function Ag(r){return this.__data__.has(r)}var $g=200;function Cg(r,e){var t=this.__data__;if(t instanceof ne){var s=t.__data__;if(!ft||s.length<$g-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new de(s)}return t.set(r,e),this.size=t.size,this}function Be(r){var e=this.__data__=new ne(r);this.size=e.size}Be.prototype.clear=bg,Be.prototype.delete=kg,Be.prototype.get=wg,Be.prototype.has=Ag,Be.prototype.set=Cg;var wn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,An=wn&&typeof module=="object"&&module&&!module.nodeType&&module,Dg=An&&An.exports===wn,$n=Dg?Y.Buffer:void 0;$n&&$n.allocUnsafe;function _g(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 xg(){return[]}var Eg=Object.prototype,Sg=Eg.propertyIsEnumerable,Cn=Object.getOwnPropertySymbols,jg=Cn?function(r){return r==null?[]:(r=Object(r),Pg(Cn(r),function(e){return Sg.call(r,e)}))}:xg;function Mg(r,e,t){var s=e(r);return qe(r)?s:mg(s,t(r))}function Rg(r){return Mg(r,My,jg)}var Qr=$e(Y,"DataView"),Br=$e(Y,"Promise"),Vr=$e(Y,"Set"),Dn="[object Map]",Ig="[object Object]",_n="[object Promise]",Pn="[object Set]",xn="[object WeakMap]",En="[object DataView]",Tg=Ae(Qr),Og=Ae(ft),Kg=Ae(Br),Fg=Ae(Vr),qg=Ae(Or),ie=Ke;(Qr&&ie(new Qr(new ArrayBuffer(1)))!=En||ft&&ie(new ft)!=Dn||Br&&ie(Br.resolve())!=_n||Vr&&ie(new Vr)!=Pn||Or&&ie(new Or)!=xn)&&(ie=function(r){var e=Ke(r),t=e==Ig?r.constructor:void 0,s=t?Ae(t):"";if(s)switch(s){case Tg:return En;case Og:return Dn;case Kg:return _n;case Fg:return Pn;case qg:return xn}return e});var Qg=Object.prototype,Bg=Qg.hasOwnProperty;function Vg(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Bg.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var Sn=Y.Uint8Array;function Gr(r){var e=new r.constructor(r.byteLength);return new Sn(e).set(new Sn(r)),e}function Gg(r,e){var t=Gr(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Ug=/\w*$/;function Ng(r){var e=new r.constructor(r.source,Ug.exec(r));return e.lastIndex=r.lastIndex,e}var jn=ue?ue.prototype:void 0,Mn=jn?jn.valueOf:void 0;function zg(r){return Mn?Object(Mn.call(r)):{}}function Lg(r,e){var t=Gr(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var Wg="[object Boolean]",Hg="[object Date]",Jg="[object Map]",Zg="[object Number]",Yg="[object RegExp]",Xg="[object Set]",em="[object String]",tm="[object Symbol]",rm="[object ArrayBuffer]",sm="[object DataView]",om="[object Float32Array]",nm="[object Float64Array]",im="[object Int8Array]",am="[object Int16Array]",lm="[object Int32Array]",cm="[object Uint8Array]",um="[object Uint8ClampedArray]",dm="[object Uint16Array]",fm="[object Uint32Array]";function pm(r,e,t){var s=r.constructor;switch(e){case rm:return Gr(r);case Wg:case Hg:return new s(+r);case sm:return Gg(r);case om:case nm:case im:case am:case lm:case cm:case um:case dm:case fm:return Lg(r);case Jg:return new s;case Zg:case em:return new s(r);case Yg:return Ng(r);case Xg:return new s;case tm:return zg(r)}}function hm(r){return typeof r.constructor=="function"&&!dn(r)?Mh(vg(r)):{}}var ym="[object Map]";function gm(r){return Fe(r)&&ie(r)==ym}var Rn=Qe&&Qe.isMap,mm=Rn?Kr(Rn):gm,vm="[object Set]";function bm(r){return Fe(r)&&ie(r)==vm}var In=Qe&&Qe.isSet,km=In?Kr(In):bm,Tn="[object Arguments]",wm="[object Array]",Am="[object Boolean]",$m="[object Date]",Cm="[object Error]",On="[object Function]",Dm="[object GeneratorFunction]",_m="[object Map]",Pm="[object Number]",Kn="[object Object]",xm="[object RegExp]",Em="[object Set]",Sm="[object String]",jm="[object Symbol]",Mm="[object WeakMap]",Rm="[object ArrayBuffer]",Im="[object DataView]",Tm="[object Float32Array]",Om="[object Float64Array]",Km="[object Int8Array]",Fm="[object Int16Array]",qm="[object Int32Array]",Qm="[object Uint8Array]",Bm="[object Uint8ClampedArray]",Vm="[object Uint16Array]",Gm="[object Uint32Array]",A={};A[Tn]=A[wm]=A[Rm]=A[Im]=A[Am]=A[$m]=A[Tm]=A[Om]=A[Km]=A[Fm]=A[qm]=A[_m]=A[Pm]=A[Kn]=A[xm]=A[Em]=A[Sm]=A[jm]=A[Qm]=A[Bm]=A[Vm]=A[Gm]=!0,A[Cm]=A[On]=A[Mm]=!1;function Qt(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Kt(r))return r;var a=qe(r);if(a)i=Vg(r);else{var l=ie(r),c=l==On||l==Dm;if(mn(r))return _g(r);if(l==Kn||l==Tn||c&&!o)i=c?{}:hm(r);else{if(!A[l])return o?r:{};i=pm(r,l)}}n||(n=new Be);var u=n.get(r);if(u)return u;n.set(r,i),km(r)?r.forEach(function(h){i.add(Qt(h,e,t,h,r,n))}):mm(r)&&r.forEach(function(h,p){i.set(p,Qt(h,e,t,p,r,n))});var d=Rg,f=a?void 0:d(r);return Rh(f||r,function(h,p){f&&(p=h,h=r[p]),Qh(i,p,Qt(h,e,t,p,r,n))}),i}var Um=1,Nm=4;function zm(r){return Qt(r,Um|Nm)}function Lm(r){const e=Ur(r);return Wm(e)}function Ur(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(Ur).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+Ur(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function Wm(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)}},Fn={silent:0,error:1,warn:2,info:3,debug:4};class j{config;static globalConfig={};constructor(e={}){this.config={level:e.level??j.globalConfig.level??this.getDefaultLevel(),format:e.format??j.globalConfig.format??this.getDefaultFormat(),prefix:e.prefix,onLog:e.onLog??j.globalConfig.onLog,onTrackError:e.onTrackError??j.globalConfig.onTrackError}}static setGlobalConfig(e){j.globalConfig={...j.globalConfig,...e}}static getGlobalConfig(){return{...j.globalConfig}}static setModuleLevel(e,t){j.globalConfig.onLog||(j.globalConfig.onLog=void 0),j._moduleOverrides||(j._moduleOverrides=new Map),j._moduleOverrides.set(e,t)}static getModuleLevel(e){if(!(!e||!j._moduleOverrides))return j._moduleOverrides.get(e)}getDefaultLevel(){return"info"}getDefaultFormat(){return"pretty"}getEffectiveLevel(){if(this.config.prefix){const e=j.getModuleLevel(this.config.prefix);if(e)return e}return this.config.level}shouldLog(e){const t=this.getEffectiveLevel();return Fn[e]<=Fn[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 j(t)}configure(e){Object.assign(this.config,e)}}const Nr=new j;function zr(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 Hm=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 qn=(r,e)=>e?typeof structuredClone<"u"?structuredClone(r):zm(r):r,Qn=(r,e,t,s,o,n)=>{try{const i=!!e.dcuplInitOptions.performance?.clone?.enabled&&!!t.cloneResult,a=qn(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(),c=l-s,u=Math.round(c*1e3)/1e3;t.duration=u,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}},Bn=r=>(e,t,s)=>{const o=s.value;return s.value=function(...n){const i=F.now(),a=this.cdRef,l=qn(r,!0);l.key||(a.increaseCounter(),l.key=a.getCounter());const c=zr();a.analyticsController.mark({name:`${l.type}:start`,context:c});const u=this.model?.key;!l.originCdRefKey&&a.key&&(l.originCdRefKey=a.key),u&&(l.modelKey=u);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,c,f)):Qn(this,a,l,i,c,d)},s},Jm="k:",Zm="h:";function Lr(r,e=0){if(r.key)return`${Jm}${r.key}`;const t=Lm({type:r.type,url:r.rawUrl??r.url,model:r.model??"",occurrence:e});return`${Zm}${t}`}function Ym(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=Lr(s,n);for(;t.has(i);)n+=1,i=s.key?`${Lr(s)}#${n}`:Lr(s,n);return e.set(o,n+1),t.add(i),i})}const Bt=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>gg(e,s.trim(),""))):"",Xm=r=>{const e=new Set;return r.replace(/\$\{(.*?)\}/g,(t,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(t=>({name:t}))}};let ev=class{log=Nr.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:c}=e,u=[],d=i?[]:null;let f=r.length,h=[],p="",y=!1,v=!0,g=0;if(a){for(;g<f&&(r[g]===`
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(Bp(s))this.processQueryReference(t,o,s.query);else if(Mr(s))this.processResolvedReference(t,o,s.resolve);else if(Vp(s))this.processDerivedReference(t,o,s.derive);else if(Gp(s))this.processGroupedReference(t,o,s.groupBy);else{const n={modelKey:t,attributeKey:o,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttribute(n)}})})}validateAttributeDependencyGraph(){const e=new Map;this.models.forEach(s=>{const o=[];s.properties.forEach((n,i)=>{o.push(i)}),s.references.forEach((n,i)=>{o.push(i)}),o.length>0&&e.set(s.key,o)});const t=this.attributeDependencyGraph.validateCompleteness(e);if(!t.isComplete){const s=t.missing.length,o=t.missing.map(({modelKey:i,attributeKey:a})=>`${i}.${a}`).slice(0,10).join(", "),n=`Attribute dependency graph incomplete. ${s} attribute(s) missing: ${o}${s>10?` ... and ${s-10} more`:""}`;this.log.warn(`${n}
8
+ These attributes will default to Step 1 processing which may be incorrect. This usually indicates a problem during expression or reference parsing.`)}}processExpressionProperty(e,t,s){const o={modelKey:e,attributeKey:t,type:"property",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const{variables:n}=_r(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}=_r(n);i.forEach(a=>{const l=a.name,u=this.models.get(e);if(u){if(u.properties.has(l)){const c={modelKey:e,attributeKey:l,type:"property",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,c)}else if(u.references.has(l)){const c={modelKey:e,attributeKey:l,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,c)}}})}catch{}}processResolvedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:2};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:s.model,attributeKey:s.reference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n)}processDerivedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.localReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n);const i=this.models.get(e);if(i){const a=i.references.get(s.localReference);if(a){const l={modelKey:a.model,attributeKey:s.remoteReference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,l)}}}processGroupedReference(e,t,s){const o={modelKey:e,attributeKey:t,type:"reference",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const n={modelKey:e,attributeKey:s.reference,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttributeDependency(o,n)}async update(){const e=performance.now(),t=this.shouldUsePartialUpdate();if(t.decision){const s=this.changeTracker.getModelsWithChanges().length,o=Array.from(this.changeTracker.getChangedAttributes().values()).reduce((a,l)=>a+l.size,0),n=this.changeTracker.getTotalChangedItemCount();await this.partialUpdate();const i=performance.now()-e;this.partialUpdateMetrics.recordUpdate({type:"partial",durationMs:i,modelsAffected:s,attributesProcessed:o,itemsChanged:n,decisionReason:t.reason,timestamp:Date.now()})}else{await this.init();const s=performance.now()-e;this.partialUpdateMetrics.recordUpdate({type:"full",durationMs:s,decisionReason:t.reason,timestamp:Date.now()})}}shouldUsePartialUpdate(){const e=this.dcuplInstance.initOptions.performance?.partialUpdates,t=e?.modelRatioThreshold??.5,s=e?.itemRatioThreshold??.5,o=e?.enableDetailedLogging??!1;if(!this.changeTracker.hasChanges())return o&&this.log.debug("Partial update decision: SKIP",{reason:"no_changes_detected"}),{decision:!1,reason:"no_changes_detected"};if(this.changeTracker.getModelsWithFullReset().size>0)return o&&this.log.debug("Partial update decision: FULL",{reason:"full_reset_detected"}),{decision:!1,reason:"full_reset_detected"};const n=Array.from(this.models.keys()).filter(c=>!c.startsWith("$")).length,i=this.changeTracker.getAffectedModelRatio(n);let a=0,l=0;for(const c of this.changeTracker.getModelsWithChanges()){const d=this.models.get(c);if(d){const f=d.getData().size;a+=f,l+=this.changeTracker.getChangedItems(c).size,l+=this.changeTracker.getDeletedItems(c).size}}const u=a>0?l/a:0;return i>t&&u>s?(o&&this.log.debug("Partial update decision: FULL",{reason:"both_ratios_high",modelRatio:i.toFixed(2),itemRatio:u.toFixed(2)}),{decision:!1,reason:`both_ratios_high:models=${i.toFixed(2)},items=${u.toFixed(2)}`}):(o&&this.log.debug("Partial update decision: PARTIAL",{modelRatio:i.toFixed(2),itemRatio:u.toFixed(2),modelThreshold:t,itemThreshold:s}),{decision:!0,reason:`optimal:models=${i.toFixed(2)},items=${u.toFixed(2)}`})}async partialUpdate(){const e=this.handleAlternativeKey(this.unprocessedData).filter(s=>!s.placeholderUid);for(const s of e)if(s.type==="remove"){const o=this.models.get(s.model);if(o){o.deleteDataEntries(s);for(const n of o.properties.values())this.changeTracker.recordAttributeChange(s.model,n.key);for(const n of o.references.values())this.changeTracker.recordAttributeChange(s.model,n.key)}}const t=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModelsPartial(t),this.consolidateUnprocessedData(t)}async reprocessData(){this.qualityController.enabled&&this.qualityController.resetModelErrors();const e=this.getMergedContainers(this.unprocessedData);await this.connectDataWithModels(e)}getSortedCalculationTimings(){return $o(this.calculationTimings,"value")}addModel(e){if(e?.quality?.enabled!==!1)try{Ep(e)}catch(t){this.qualityController.enabled&&this.qualityController.setError({title:"Invalid Model Definition",type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:e.key,description:t.message});return}if(this.unprocessedModelDescriptions.has(e.key)){const t=this.unprocessedModelDescriptions.get(e.key),s=this.mergeModels(t,e);this.unprocessedModelDescriptions.set(e.key,s)}else this.unprocessedModelDescriptions.set(e.key,e);e.data&&this.addData({model:e.key,data:e.data,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty})}mergeModels(e,t){const s=Object.assign({},e,t);return(Array.isArray(e.properties)||Array.isArray(t.properties))&&(s.properties=[...Array.isArray(e.properties)?e.properties:[],...Array.isArray(t.properties)?t.properties:[]]),(Array.isArray(e.references)||Array.isArray(t.references))&&(s.references=[...Array.isArray(e.references)?e.references:[],...Array.isArray(t.references)?t.references:[]]),s}addData(e){if(!e||!e.model||!e.data)throw new Error("Invalid Data Container");if(!Array.isArray(e.data))throw new Error("Invalid Data - Data must be an Array");e.type||(e.type="set"),e.autoGenerateProperties&&this.addModel({key:e.model,autoGenerateProperties:e.autoGenerateProperties,autoGenerateKey:e.autoGenerateKey,keyProperty:e.keyProperty||"key"}),this.changeTracker.recordDataChange(e),this.unprocessedData.push(e)}addView(e){this.views.set(e.key,e)}setError(e,t){this.qualityController.enabled&&t.qualityConfig.enabled===!0&&this.qualityController.setError(e)}getMergedContainers(e){const t=this.handleAlternativeKey(e).filter(n=>!n.placeholderUid),s=[],o=jr(t,"model");for(const n in o){const i=o[n];if(i.length>1){const a=this.mergeContainers(i),l=this.mergeContainerSourceMetadata(i);l&&this.dcuplInstance.setContainerSourceMetadata(a,l),s.push(a)}else s.push(i[0])}return s}consolidateUnprocessedData(e){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=at(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=at(n,o),t.set(o.key,n)}});break;case"remove":s.data.forEach(o=>{t.delete(o.key)});break;case"set":t=new Map(s.data.map(o=>[o.key,o]));break;default:t=new Map(s.data.map(o=>[o.key,o]));break}}),{model:e[0].model,data:Array.from(t.values()),type:"set"}}mergeContainerSourceMetadata(e){let t;for(const s of e){const o=this.dcuplInstance.getContainerSourceMetadata(s),n=s.type??"set";if(n==="set")t=o?{columns:new Set(o.sourceColumns),samples:this.cloneCoercionSamples(o.coercionFailureSamples),origin:o.origin}:void 0;else if((n==="upsert"||n==="update")&&o){t||(t={columns:new Set,samples:{},origin:o.origin}),o.sourceColumns.forEach(i=>t.columns.add(i));for(const i of Object.keys(o.coercionFailureSamples)){const a=o.coercionFailureSamples[i],l=t.samples[i];l?l.count+=a.count:t.samples[i]={...a}}}}if(t)return{sourceColumns:Array.from(t.columns),coercionFailureSamples:t.samples,origin:t.origin}}cloneCoercionSamples(e){const t={};for(const s of Object.keys(e))t[s]={...e[s]};return t}async connectDataWithModels(e){try{this.dependencyGraph.order()}catch(s){this.log.warn("Your models have circular dependencies which might lead to errors. Please consider changing your models"),this.log.error("Dependency graph error",s)}const t=this.dependencyGraph.order({allowCycles:!0});e.sort((s,o)=>t.indexOf(s.model)-t.indexOf(o.model)),await this.handleDataContainer(e)}async connectDataWithModelsPartial(e){const t=this.dependencyGraph.order({allowCycles:!0});e.sort((i,a)=>t.indexOf(i.model)-t.indexOf(a.model));const s=[];for(const[i,a]of this.changeTracker.getChangedAttributes())for(const l of a){const u=this.attributeDependencyGraph.getAttributesForModel(i).find(c=>c.attributeKey===l);if(u)s.push(u);else{const c=this.models.get(i);if(c){const d=c.properties.get(l),f=c.references.get(l);(d||f)&&s.push({modelKey:i,attributeKey:l,type:d?"property":"reference",processingStep:1})}}}const o=this.attributeDependencyGraph.getImpactedAttributes(s),n=this.attributeDependencyGraph.getProcessingOrder(o);for(const i of e){const a=this.models.get(i.model);a?.autoGenerateProperties&&a.generatePropertiesFromContainer(i)}for(const i of[1,2,3,4])await this.processAttributesForStep(i,n,e);for(const[i,a]of n.entries()){const l=this.models.get(i);if(!l)continue;const u=new Set;for(const c of a.values())for(const d of c)u.add(d);l.resetIndicesForChangedAttributes(u)}for(const i of e){const a=this.models.get(i.model);if(a&&this.qualityController.enabled){const l=this.changeTracker.getChangedItems(a.key),u=this.changeTracker.getChangedAttributes().get(a.key);l.size>0&&u&&(this.qualityController.cleanUpErrorsForItems(a,l,u),this.qualityController.validateItemsPartial(a,l,u).forEach(c=>{this.setError(c,a)}))}}this.changeTracker.clear()}getResolvedReferenceProcessingOrder(e){const t=new Map,s=new Set;for(const[l,u]of e.entries()){const c=u.get(2);c&&c.size>0&&(s.add(l),t.set(l,new Set))}if(s.size===0)return this.dependencyGraph.order();for(const l of s){const u=this.models.get(l);if(!u)continue;const c=e.get(l)?.get(2);if(c)for(const d of c){const f=u.references.get(d);if(f&&Mr(f)){const h=f.resolve.model,p=f.resolve.reference,y=this.models.get(h);if(y){const v=y.references.get(p);v&&Mr(v)&&t.get(l).add(h)}}}}const o=[],n=new Set,i=new Set,a=l=>{if(i.has(l)||n.has(l))return;n.add(l);const u=t.get(l);if(u)for(const c of u)a(c);n.delete(l),i.add(l),o.push(l)};for(const l of s)a(l);return o}async processAttributesForStep(e,t,s){let o=this.dependencyGraph.order({allowCycles:!0});e===2&&(o=this.getResolvedReferenceProcessingOrder(t));for(const n of o){const i=t.get(n);if(!i)continue;const a=i.get(e);if(!a||a.size===0)continue;const l=this.models.get(n);if(!l)continue;const u=W(),c=`dcupl:partial_process_data:step_${e}`;if(this.cdRef.analyticsController.mark({name:`${c}:start`,context:u}),e===2)l.rebuildResolvedReferencesForAllItems(a);else{const d=s.find(f=>f.model===n);if(!d)continue;switch(e){case 1:l.addBasicPropertiesAndReferencesPartial(d,a);break;case 3:l.addDerivedAndExpressionAttributesPartial(d,a);break;case 4:l.reRunDerivedPropertiesBasedOnResolvesPartial(d,a);break}}this.cdRef.analyticsController.mark({name:`${c}:end`,context:u}),this.cdRef.analyticsController.measure({name:c,start:`${c}:start`,end:`${c}:end`,context:u,detail:{model:n,attributeCount:a.size}})}}handleAlternativeKey(e){return e.forEach(t=>{if(this.keyedContainers.has(t))return;const s=this.models.get(t.model),o=t.keyProperty??s?.keyProperty,n=t.keyPropertySeparator??s?.keyPropertySeparator??we,i=t.autoGenerateKey||s?.autoGenerateKey;(typeof o=="string"?o!==""&&o!=="key":Array.isArray(o)&&o.length>0)?t.data.forEach(a=>{a.key=zo(a,o,n)}):i&&t.data.forEach(a=>{a.key||(a.key=W())}),this.keyedContainers.add(t)}),e}async handleDataContainer(e){for(const o of e){const n=this.models.get(o.model);n?.autoGenerateProperties&&n.generatePropertiesFromContainer(o)}const t=this.initOptions.performance?.containerBatchSize,s=t!==void 0;for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:start",context:a}),i&&(i.addBasicPropertiesAndReferences(n),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.cleanUpErrors(i,n)),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_1:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_1",start:"dcupl:process_data:step_1:start",end:"dcupl:process_data:step_1:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:start",context:a}),i&&i.hasQueryReferences()&&i.addQueryReferences(n),i&&i.hasResolvedReferences()&&i.addResolvedReferences(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_2:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_2",start:"dcupl:process_data:step_2:start",end:"dcupl:process_data:step_2:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model),a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:start",context:a}),i&&(i.hasDerivedPropertiesForBasicReferences()||i?.hasDerivedReferences()||i?.hasGroupedReferences()||i?.hasExpressionProperties())&&i.addDerivedReferencesGroupedReferencesDerivedPropertiesAndExpressionProperties(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_3:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_3",start:"dcupl:process_data:step_3:start",end:"dcupl:process_data:step_3:end",context:a,detail:{model:n.model}}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}for(let o=0;o<e.length;o++){const n=e[o],i=this.models.get(n.model);if(!i){this.log.error("Model not found during data processing",void 0,{model:n.model,step:4});continue}const a=W();this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:start",context:a}),(i.hasDerivedPropertiesBasedOnResolvedReferences()||i.hasDerivedReferencesBasedOnResolvedReferences())&&i.reRunDerivedPropertiesBasedOnResolves(n),this.cdRef.analyticsController.mark({name:"dcupl:process_data:step_4:end",context:a}),this.cdRef.analyticsController.measure({name:"dcupl:process_data:step_4",start:"dcupl:process_data:step_4:start",end:"dcupl:process_data:step_4:end",context:a,detail:{model:n.model}}),this.qualityController.enabled&&i.qualityConfig.enabled===!0&&this.qualityController.validateAttributesAfterInitialization(i).forEach(l=>{this.setError(l,i)}),s?t>0&&o>0&&o%t===0&&await Z():await Z()}}_getModelKeys(){return Array.from(this.models.values()).map(e=>e.key).filter(e=>e&&!e.startsWith("$Dcupl"))}_getViewKeys(e){const t=e?.modelKey;return Array.from(this.views.values()).filter(s=>t?s.model===t:!0).map(s=>s.key)}getTotalItemCount(){let e=0;for(const t of this.models.values())e+=t.getItemCount();return e}};Ot([b({scope:"global",type:"model_add",connectMessage:!0})],lt.prototype,"addModel"),Ot([b({scope:"global",type:"data_change",connectMessage:!0})],lt.prototype,"addData"),Ot([b({scope:"global",type:"view_add",connectMessage:!0})],lt.prototype,"addView"),Ot([b({scope:"global",type:"dcupl_handle_datacontainer"})],lt.prototype,"handleDataContainer");function zp(r,e){return Se(e,function(t){return r[t]})}function Lp(r){return r==null?[]:zp(r,Xe(r))}var Wp=Math.max;function Hp(r,e,t,s){r=te(r)?r:Lp(r),t=t?wt(t):0;var o=r.length;return t<0&&(t=Wp(o+t,0)),St(r)?t<=o&&r.indexOf(e,t)>-1:!!o&&ks(r,e,t)>-1}var Jp=Object.defineProperty,Zp=Object.getOwnPropertyDescriptor,Ho=(r,e,t,s)=>{for(var o=Zp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Jp(e,t,o),o};let Rr=class{constructor(e,t){this.dcuplApi=e,this.cdRef=t}dcuplApi;cdRef;options;key;modelKey;catalog;ownsIndicesController=!1;setup(e){const t=this.dcuplApi.modelParser.models.get(e.modelKey);if(!t)throw new Error(`Model with key ${e.modelKey} not found`);const s=this.getListItemKeys(e),o=this.getRelevantData(t,s),n=this.initIndicesController(s,t,o);this.catalog?this.catalog.filter.update(t,o,n):(this.catalog=new sp(this.dcuplApi,this.cdRef,n),this.catalog.init(this.modelKey,t,o))}initIndicesController(e,t,s){let o;if(e){o=new It;for(const n of t.indicesController.indexMap.keys())o.getOrCreateIndex(n,s);this.ownsIndicesController=!0}else o=t.indicesController,this.ownsIndicesController=!1;return o}getListItemKeys(e){let t;return e.listItemKeys?t=e.listItemKeys:e.query&&(t=this.dcuplApi.query.execute(e.query).map(s=>s.key)),t}getRelevantData(e,t){const s=e.getData();return t?this.initFromItemKeys(s,t):s}init(e){this.options=oe(e),this.key=this.options.listKey,this.modelKey=this.options.modelKey,this.setup(this.options)}initFromItemKeys(e,t){const s=new Map;return t.forEach(o=>{if(e.has(o)){const n=e.get(o);n&&s.set(o,n)}}),s}destroy(){try{this.dcuplApi.lists.destroy({listKey:this.key})}catch{}}_destroy(){this.catalog.filter.cdRef?.destroy()}update(e){(e&&e.reprocessData||!e)&&this.setup(this.options)}invalidate(){this.catalog&&(this.ownsIndicesController&&this.catalog.filter.indicesController.reset(),this.catalog.filter.resetCache())}on(e){return this.cdRef.on(e)}};Ho([b({scope:"list",type:"list_destroyed",connectMessage:!0})],Rr.prototype,"_destroy"),Ho([b({scope:"list",type:"list_updated",action:"update",connectMessage:!0})],Rr.prototype,"update");var Yp=Object.defineProperty,Xp=Object.getOwnPropertyDescriptor,eh=(r,e,t,s)=>{for(var o=Xp(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&Yp(e,t,o),o};let Jo=class{constructor(e,t){this.dcuplInstance=e,this.cdRef=t}dcuplInstance;cdRef;lists=[];get(e){if(e)return this.lists.find(t=>t.key===e)}getAll(e){return e?this.lists.filter(t=>t.modelKey===e?.modelKey):this.lists}destroy(e){if(!e)this.lists.forEach(t=>t._destroy()),this.lists=[];else if(e.listKey){const t=this.lists.findIndex(s=>s.key===e.listKey);t>-1&&(this.lists[t]._destroy(),this.lists.splice(t,1))}else e.modelKey&&(this.lists=this.lists.filter(t=>t.modelKey===e.modelKey?(t._destroy(),!1):!0))}create(e){e.listKey=e.listKey||W();const t=new $r;t._init({cdRefKey:e.listKey,parentCd:this.dcuplInstance.cdRef,dcuplInitOptions:this.dcuplInstance.initOptions,analyticsController:this.dcuplInstance.analyticsController});const s=new Rr(this.dcuplInstance,t);return s.init(e),this.lists.push(s),s}};eh([b({scope:"global",type:"list_created",connectMessage:!0})],Jo.prototype,"create");let th=class{constructor(e){this.scriptsController=e}scriptsController;enabled=!1;maxErrorsPerGroup=1e3;errors=new Map;errorCounts=new Map;log=Te.child({prefix:"QualityController"});values={loading:0,processing:0,startup:0,counts:{resources:0,modelFiles:0,dataFiles:0,models:0,rows:0,attributes:0,dataEntries:0},unusedAttributes:[],errors:{size:0,UndefinedValue:0,UndefinedAttribute:0,WrongDataType:0,MissingModel:0,InvalidModelDescription:0,RemoteReferenceKeyNotFound:0},sizes:{totalEncoded:0,totalDecoded:0,unusedDecoded:0,models:[]}};modelParser;dcupl;getErrorGroupKey(e){const t="attribute"in e?e.attribute:void 0;return`${e.model??""}::${t??""}::${e.errorType}`}getGroupCount(e,t,s){const o=`${e??""}::${t??""}::${s}`;return this.errorCounts.get(o)?.count??0}setError(e){const t=this.getErrorGroupKey(e);let s=this.errorCounts.get(t);s||(s={model:e.model,attribute:"attribute"in e?e.attribute:void 0,errorGroup:e.errorGroup,errorType:e.errorType,type:e.type,count:0},this.errorCounts.set(t,s)),s.count+=1,!(s.count>this.maxErrorsPerGroup)&&(e.key||(e.key=W()),this.errors.set(e.key,e))}getErrorCounts(){return Array.from(this.errorCounts.values()).map(({model:e,attribute:t,errorType:s,count:o})=>({model:e,attribute:t,errorType:s,count:o}))}removeError(e){const t=this.errors.get(e);if(t){const s=this.getErrorGroupKey(t),o=this.errorCounts.get(s);o&&(o.count-=1,o.count<=0&&this.errorCounts.delete(s))}this.errors.delete(e)}getError(e){return this.errors.get(e)}getErrors(){return Array.from(this.errors.values())}resetErrors(){this.errors.clear(),this.errorCounts.clear()}resetModelErrors(){this.getErrors().forEach(e=>{e.type==="model"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&this.errorCounts.delete(e)}resetValidationErrors(){this.getErrors().forEach(e=>{e.type==="model"&&e.errorType==="InvalidValidator"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&t.errorType==="InvalidValidator"&&this.errorCounts.delete(e)}resetDataErrors(){const e=["ReferenceDataError","PropertyDataError","DataContainerError"];this.getErrors().forEach(t=>{t.type==="model"&&e.includes(t.errorGroup)&&this.removeError(t.key)});for(const[t,s]of this.errorCounts)s.type==="model"&&e.includes(s.errorGroup)&&this.errorCounts.delete(t)}cleanUpErrors(e,t){const s=this.dcupl?.getContainerSourceMetadata(t),o=t.model;if(s){const n=s.coercionFailureSamples??{};for(const i of Object.keys(n)){const a=n[i];if(!a||a.count<=0)continue;for(const u of this.getModelErrors(o))u.attribute===i&&u.itemKey!=null&&(u.errorType==="UndefinedValue"||u.errorType==="WrongDataType")&&this.removeError(u.key);const l=e.properties.get(i)?.type??a.expected;this.setError(this.buildColumnCoercionError(o,i,a.rawValue,l,a.count))}for(const[i]of e.properties){if(n[i]||s.sourceColumns.includes(i))continue;const a=this.getGroupCount(o,i,"UndefinedValue");if(a>0&&a===t.data.length){for(const l of this.getModelErrors(o))l.attribute===i&&l.itemKey!=null&&l.errorType==="UndefinedValue"&&this.removeError(l.key);this.setError(this.buildAbsentColumnError(o,i))}}}else{const n=new Set(this.getModelErrors(o).filter(l=>l.errorType==="UndefinedValue"&&l.attribute!=null).map(l=>l.attribute));for(const l of n){const u=this.getGroupCount(o,l,"UndefinedValue");if(u>0&&u===t.data.length){for(const c of this.getModelErrors(o))c.attribute===l&&c.itemKey!=null&&c.errorType==="UndefinedValue"&&this.removeError(c.key);this.setError(this.buildAbsentColumnError(o,l))}}const i=this.getModelErrors(o).filter(l=>l.errorType==="WrongDataType"&&l.errorGroup==="PropertyDataError"&&l.title==="Wrong Data Type"&&l.itemKey!=null),a=jr(i,"attribute");for(const l in a){const u=a[l];if(!u?.length)continue;const c=u[0].meta,d=e.properties.get(l)?.type??c?.expected??"unknown";for(const f of u)this.removeError(f.key);this.setError(this.buildColumnCoercionError(o,l,String(c?.rawValue??""),d,u.length))}}}buildColumnCoercionError(e,t,s,o,n){return{title:"Wrong Data Type",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",model:e,attribute:t,description:`${n} value(s) in column "${t}" of model "${e}" failed to coerce to the declared type "${o}" (e.g. "${s}")`,meta:{rawValue:s,declaredType:o,rowCount:n}}}buildAbsentColumnError(e,t){return{title:"Missing Data",type:"model",errorGroup:"DataContainerError",errorType:"UndefinedAttribute",model:e,attribute:t,description:`The Attribute "${t}" is not present in the dataset for model "${e}"`}}getModelErrors(e){return this.getErrors().filter(t=>t.type==="model"&&t.model===e)}cleanUpErrorsForItems(e,t,s,o){let n,i;typeof s=="string"?i=s:s instanceof Set&&(n=s,i=o);const a=this.getModelErrors(e.key),l=i?a.filter(u=>u.errorType===i):a;for(const u of l)if(u.itemKey&&t.has(u.itemKey)){if(n&&u.attribute&&!n.has(u.attribute))continue;this.removeError(u.key)}}getErrorsForItems(e,t){return this.getModelErrors(e).filter(s=>s.itemKey&&t.has(s.itemKey))}validateItemsPartial(e,t,s){if(!e)return[];const o=[],n=e.getData(),i=e.getAttributes();for(const a of i){if(!s.has(a.key))continue;const l=a.quality?.validators;if(l)for(const u of t){const c=n.get(u);if(!c)continue;const d=c[a.key],f=this.validateAttribute(d,l,a.key);for(const h of f)h.model=e.key,h.itemKey=c.key,o.push(h)}}return o}async initData(){if(!this.modelParser)return;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=jr(e,s=>s.value?.model);return Object.keys(t).map(s=>{const o=t[s]?.reduce((i,a)=>{const l=a.value.encodedBodySize;return i+l},0),n=t[s]?.reduce((i,a)=>{const l=a.value.decodedBodySize;return i+l},0);return{model:s,decodedBodySize:n,encodedBodySize:o}})}calculateUnusedData(){const e=this.dcupl.models.keys();let t=0;return e.forEach(s=>{const o=this.dcupl.modelParser.unprocessedData.find(a=>a.model===s)?.data||[],n=this.getUnusedAttributesFromModel(this.dcupl,s);if(!n.length)return;const i=this.getDataWithAttributes(o,n);t+=JSON.stringify(i).length}),t}getDataWithAttributes(e,t){return e.map(s=>{const o={};return t.forEach(n=>{o[n]=s[n]}),o})}getUnusedAttributesFromModel(e,t){const s=e.modelParser.models.get(t),o=s?.getBasicProperties()||[],n=s?.getBasicReferences()||[],i=s?.keyProperty,a=[...o,...n].map(u=>u.key);typeof i=="string"?a.push(i):Array.isArray(i)?a.push(...i):a.push("key"),a.push("key");const l=e.modelParser.unprocessedData.find(u=>u.model===t)?.data||[];return this.getUnusedAttributes(l,a)}getUnusedAttributes(e,t){const s=new Set;return e.forEach(o=>{Object.keys(o).forEach(n=>{t.includes(n)||s.add(n)})}),Array.from(s.values())}validateAttribute(e,t,s){const o=[];if(t.email){const n=this.validateEmail(e,s);n&&o.push(n)}if(t.endsWith){const n=this.validateEndsWith(e,t.endsWith,s);n&&o.push(n)}if(t.enum){const n=this.validateEnum(e,t.enum,s);n&&o.push(n)}if(t.includes){const n=this.validateIncludes(e,t.includes,s);n&&o.push(n)}if(t.max){const n=this.validateMax(e,t.max,s);n&&o.push(n)}if(t.maxLength){const n=this.validateMaxLength(e,t.maxLength,s);n&&o.push(n)}if(t.min){const n=this.validateMin(e,t.min,s);n&&o.push(n)}if(t.minLength){const n=this.validateMinLength(e,t.minLength,s);n&&o.push(n)}if(t.pattern){const n=this.validatePattern(e,t.pattern,s);n&&o.push(n)}if(t.startsWith){const n=this.validateStartsWith(e,t.startsWith,s);n&&o.push(n)}return o}validateAttributesAfterInitialization(e){if(!e)return[];const t=e.getAttributes(),s=e.getDataAsArray(),o=[];for(const n of t){const i=n.quality?.validators;if(i&&i.unique){const a=this.validateUnique(s,n.key,e);o.push(...a)}}return o}validateUnique(e,t,s){const o=[],n=new Set,i=s.attributeQualityConfigs?.get(t)?.validatorHandling!=="loose";for(const a of e){const l=a[t];if(n.has(l)){const u={title:"Validator Error - Unique",type:"model",errorGroup:"PropertyDataError",model:s.key,errorType:"InvalidValidator",attribute:t,itemKey:a.key,description:`The value "${l}" is not unique`};o.push(u),i&&delete a[t]}else n.add(l)}return o}validateEmail(e,t){if(e!=null&&!/^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,6}$/.test(e))return{title:"Validator Error - Invalid Email",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:t,description:`The value "${e}" is not a valid email address`}}validateMin(e,t,s){if(e<t.value)return{title:"Validator Error - Min Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is smaller than the minimum value of "${t.value}"`}}validateMax(e,t,s){if(e>t.value)return{title:"Validator Error - Max Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is larger than the maximum value of "${t.value}"`}}validateStartsWith(e,t,s){if(e!=null&&!e.startsWith(t.value))return{title:"Validator Error - StartsWith",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not start with "${t.value}"`}}validateEndsWith(e,t,s){if(e!=null&&!ko(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&&!Hp(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 rh=Object.defineProperty,sh=Object.getOwnPropertyDescriptor,V=(r,e,t,s)=>{for(var o=sh(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&rh(e,t,o),o};let Q=class{cdRef=new $r;analyticsController=new mf;containerSourceMetadata=new WeakMap;scriptController=new Yf;qualityController=new th(this.scriptController);log=Te.child({prefix:"Dcupl"});modelParser=new lt(this.cdRef,this.qualityController,this);globalItemService=new Vo(this.modelParser,this.scriptController);queryManager=new Zf(this.scriptController,this.globalItemService,this.modelParser);_loaders=new Map;rootQueryBuilder=new ke;_defaultInitOptions={config:{projectId:void 0,apiKey:void 0,version:"draft"},errorTracking:{enabled:!1},quality:{enabled:!0},analytics:{enabled:!1},performance:{cache:{enabled:!0},clone:{enabled:!0},partialUpdates:{modelRatioThreshold:.5,itemRatioThreshold:.5,enableDetailedLogging:!1},autoUpdateLists:{enabled:!1}},referenceMetadata:{enabled:!1}};initOptions;lists=new Jo(this,this.cdRef);busy=!1;updateQueue=[];constructor(e){this.analyticsController.init(!!e?.analytics?.enabled),this.qualityController.dcupl=this,this.analyticsController.mark({name:"dcupl:constructor"}),this.initOptions=at({},this._defaultInitOptions,e),this.qualityController.enabled=this.initOptions.errorTracking?.enabled||this.initOptions.quality?.enabled||!1,this.qualityController.maxErrorsPerGroup=this.initOptions.quality?.maxErrorsPerGroup??1e3,this.modelParser.initOptions=Object.assign({},this.initOptions),this.cdRef._init({cdRefKey:"root",dcuplInitOptions:this.initOptions,analyticsController:this.analyticsController})}models={get:e=>this.modelParser.models.get(e)?.getModelDefinition(),set:e=>(this.modelParser.models.delete(e.key),this.modelParser.addModel(e)),update:e=>this.modelParser.addModel(e),remove:e=>{this.modelParser.models.delete(e)},keys:()=>this.modelParser._getModelKeys()};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}snapshotChangedAttributes(){const e=this.modelParser.changeTracker;if(!e.hasChanges())return null;const t=e.getChangedAttributes(),s=new Map;for(const o of e.getEffectivelyChangedModels()){const n=new Set(t.get(o)??[]);if(n.size===0){const i=this.modelParser.models.get(o);for(const a of i?.properties.keys()??[])n.add(a);for(const a of i?.references.keys()??[])n.add(a)}s.set(o,n)}return s}getAffectedModels(e){const t=new Set(e.keys()),s=this.modelParser.dependencyGraph;if(s)for(const n of s.getImpactedNodes(Array.from(e.keys()),"downstream"))t.add(n);const o=this.modelParser.attributeDependencyGraph;if(o){const n=[];for(const[i,a]of e)for(const l of a)n.push({modelKey:i,attributeKey:l,type:"property",processingStep:1});for(const i of o.getImpactedAttributes(n))t.add(i.modelKey)}return Array.from(t)}updateFnLists(e,t){const s=this.initOptions.performance?.partialUpdates?.enableDetailedLogging??!1;for(const o of this.lists.getAll()){if(e&&!this.isListAffectedByChanges(o,e.affectedModels)){s&&this.log.debug("List skipped (not affected)",{listKey:o.key,modelKey:o.modelKey});continue}try{this.shouldAutoUpdateList(o,t)?(s&&this.log.debug("List auto-updating",{listKey:o.key,modelKey:o.modelKey,affectedModels:e?.affectedModels??"all"}),o.update()):(s&&this.log.debug("List caches invalidated (auto-update disabled)",{listKey:o.key,modelKey:o.modelKey}),o.invalidate())}catch(n){this.log.error(`List refresh failed for '${o.key}'`,n)}}}isListAffectedByChanges(e,t){const s=e.modelKey;return t.includes(s)}shouldAutoUpdateList(e,t){return e.key.startsWith("__global_list__")?!0:t!==void 0?t:e.options.autoUpdate!==void 0?e.options.autoUpdate:this.initOptions.performance?.autoUpdateLists?.enabled??!1}query={one:e=>this.getItem(e),many:e=>this._getManyItems(e),execute:e=>this.executeQuery(e),generate:(e,t)=>(this.rootQueryBuilder.init({modelKey:e}),this.rootQueryBuilder.applyQuery(t)),registerCustomOperator:(e,t)=>{this.queryManager.registerCustomOperator(e,t)}};on(e){return this.cdRef.on(e)}async init(){try{return await this.performUpdate(()=>this.modelParser.init()),this.updateFnLists(null),!0}catch(e){return this.log.error("Initialization failed",e),!1}}async update(e){try{const t=this.snapshotChangedAttributes();if(await this.performUpdate(()=>this.modelParser.update()),t){const s={isPartialUpdate:!0,changedModels:Array.from(t.keys()),changedAttributes:t,affectedModels:this.getAffectedModels(t)};this.updateFnLists(s,e?.autoUpdateLists),this.cdRef.trigger({scope:"global",type:"dcupl_partial_update",args:[s]})}else this.updateFnLists(null,e?.autoUpdateLists);return!0}catch(t){return this.log.error("Update failed",t),!1}}destroy(){try{this.lists.destroy(),this._loaders.forEach(e=>{e.destroy()})}catch{}}getItem(e){const t=this.modelParser.models.get(e.modelKey);if(!t)throw new Error;return this.globalItemService.getItem(e.itemKey,t.data,t,e)}_getManyItems(e){const t=this.modelParser.models.get(e.modelKey);if(!t)throw new Error;return this.globalItemService.getManyItems(e.itemKeys,t.data,t,e)}executeQuery(e){if(!e?.modelKey)throw new Error("No modelKey provided");return this.getFnList({modelKey:e?.modelKey}).catalog.query.execute(e)}addLoader(e,t){const s=ve.now(),o=t||W();this._loaders.set(o,e),e.core=this,e.key=o;const n=new $r;n._init({cdRefKey:o,parentCd:this.cdRef,dcuplInitOptions:this.initOptions,analyticsController:this.analyticsController}),e.cdRef=n,this.initOptions.config?.projectId&&e.defaultVariables.set("projectId",{key:"projectId",value:this.initOptions.config?.projectId}),this.initOptions.config?.apiKey&&e.defaultVariables.set("apiKey",{key:"apiKey",value:this.initOptions.config?.apiKey}),this.initOptions.config?.version&&e.defaultVariables.set("version",{key:"version",value:this.initOptions.config?.version}),this.cdRef.trigger({scope:"global",type:"loader_added",connectMessage:!0,args:[o],start:s})}removeLoader(e){const t=this._loaders.get(e);t&&t.destroy(),this._loaders.delete(e)}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 oh=class extends Q{version="2.0.0-beta.6";constructor(e){super(e)}};var Zo=typeof global=="object"&&global&&global.Object===Object&&global,nh=typeof self=="object"&&self&&self.Object===Object&&self,Y=Zo||nh||Function("return this")(),ce=Y.Symbol,Yo=Object.prototype,ih=Yo.hasOwnProperty,ah=Yo.toString,ut=ce?ce.toStringTag:void 0;function lh(r){var e=ih.call(r,ut),t=r[ut];try{r[ut]=void 0;var s=!0}catch{}var o=ah.call(r);return s&&(e?r[ut]=t:delete r[ut]),o}var uh=Object.prototype,ch=uh.toString;function dh(r){return ch.call(r)}var fh="[object Null]",ph="[object Undefined]",Xo=ce?ce.toStringTag:void 0;function Ke(r){return r==null?r===void 0?ph:fh:Xo&&Xo in Object(r)?lh(r):dh(r)}function Fe(r){return r!=null&&typeof r=="object"}var hh="[object Symbol]";function Ir(r){return typeof r=="symbol"||Fe(r)&&Ke(r)==hh}function yh(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var qe=Array.isArray,en=ce?ce.prototype:void 0,tn=en?en.toString:void 0;function rn(r){if(typeof r=="string")return r;if(qe(r))return yh(r,rn)+"";if(Ir(r))return tn?tn.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Kt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var gh="[object AsyncFunction]",mh="[object Function]",vh="[object GeneratorFunction]",bh="[object Proxy]";function sn(r){if(!Kt(r))return!1;var e=Ke(r);return e==mh||e==vh||e==gh||e==bh}var Tr=Y["__core-js_shared__"],on=(function(){var r=/[^.]+$/.exec(Tr&&Tr.keys&&Tr.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function kh(r){return!!on&&on in r}var wh=Function.prototype,Ah=wh.toString;function Ae(r){if(r!=null){try{return Ah.call(r)}catch{}try{return r+""}catch{}}return""}var $h=/[\\^$.*+?()[\]{}|]/g,Ch=/^\[object .+?Constructor\]$/,Dh=Function.prototype,Ph=Object.prototype,_h=Dh.toString,xh=Ph.hasOwnProperty,Eh=RegExp("^"+_h.call(xh).replace($h,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function jh(r){if(!Kt(r)||kh(r))return!1;var e=sn(r)?Eh:Ch;return e.test(Ae(r))}function Sh(r,e){return r?.[e]}function $e(r,e){var t=Sh(r,e);return jh(t)?t:void 0}var Or=$e(Y,"WeakMap"),nn=Object.create,Mh=(function(){function r(){}return function(e){if(!Kt(e))return{};if(nn)return nn(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})(),an=(function(){try{var r=$e(Object,"defineProperty");return r({},"",{}),r}catch{}})();function Rh(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}var Ih=9007199254740991,Th=/^(?:0|[1-9]\d*)$/;function Oh(r,e){var t=typeof r;return e=e??Ih,!!e&&(t=="number"||t!="symbol"&&Th.test(r))&&r>-1&&r%1==0&&r<e}function Kh(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 Fh=Object.prototype,qh=Fh.hasOwnProperty;function Qh(r,e,t){var s=r[e];(!(qh.call(r,e)&&ln(s,t))||t===void 0&&!(e in r))&&Kh(r,e,t)}var Bh=9007199254740991;function un(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Bh}function Vh(r){return r!=null&&un(r.length)&&!sn(r)}var Gh=Object.prototype;function cn(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Gh;return r===t}function Uh(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var Nh="[object Arguments]";function dn(r){return Fe(r)&&Ke(r)==Nh}var fn=Object.prototype,zh=fn.hasOwnProperty,Lh=fn.propertyIsEnumerable,Wh=dn((function(){return arguments})())?dn:function(r){return Fe(r)&&zh.call(r,"callee")&&!Lh.call(r,"callee")};function Hh(){return!1}var pn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hn=pn&&typeof module=="object"&&module&&!module.nodeType&&module,Jh=hn&&hn.exports===pn,yn=Jh?Y.Buffer:void 0,Zh=yn?yn.isBuffer:void 0,gn=Zh||Hh,Yh="[object Arguments]",Xh="[object Array]",ey="[object Boolean]",ty="[object Date]",ry="[object Error]",sy="[object Function]",oy="[object Map]",ny="[object Number]",iy="[object Object]",ay="[object RegExp]",ly="[object Set]",uy="[object String]",cy="[object WeakMap]",dy="[object ArrayBuffer]",fy="[object DataView]",py="[object Float32Array]",hy="[object Float64Array]",yy="[object Int8Array]",gy="[object Int16Array]",my="[object Int32Array]",vy="[object Uint8Array]",by="[object Uint8ClampedArray]",ky="[object Uint16Array]",wy="[object Uint32Array]",D={};D[py]=D[hy]=D[yy]=D[gy]=D[my]=D[vy]=D[by]=D[ky]=D[wy]=!0,D[Yh]=D[Xh]=D[dy]=D[ey]=D[fy]=D[ty]=D[ry]=D[sy]=D[oy]=D[ny]=D[iy]=D[ay]=D[ly]=D[uy]=D[cy]=!1;function Ay(r){return Fe(r)&&un(r.length)&&!!D[Ke(r)]}function Kr(r){return function(e){return r(e)}}var mn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ct=mn&&typeof module=="object"&&module&&!module.nodeType&&module,$y=ct&&ct.exports===mn,Fr=$y&&Zo.process,Qe=(function(){try{var r=ct&&ct.require&&ct.require("util").types;return r||Fr&&Fr.binding&&Fr.binding("util")}catch{}})(),vn=Qe&&Qe.isTypedArray,Cy=vn?Kr(vn):Ay,Dy=Object.prototype,Py=Dy.hasOwnProperty;function _y(r,e){var t=qe(r),s=!t&&Wh(r),o=!t&&!s&&gn(r),n=!t&&!s&&!o&&Cy(r),i=t||s||o||n,a=i?Uh(r.length,String):[],l=a.length;for(var u in r)Py.call(r,u)&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||n&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Oh(u,l)))&&a.push(u);return a}function bn(r,e){return function(t){return r(e(t))}}var xy=bn(Object.keys,Object),Ey=Object.prototype,jy=Ey.hasOwnProperty;function Sy(r){if(!cn(r))return xy(r);var e=[];for(var t in Object(r))jy.call(r,t)&&t!="constructor"&&e.push(t);return e}function My(r){return Vh(r)?_y(r):Sy(r)}var Ry=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Iy=/^\w*$/;function Ty(r,e){if(qe(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Ir(r)?!0:Iy.test(r)||!Ry.test(r)||e!=null&&r in Object(e)}var dt=$e(Object,"create");function Oy(){this.__data__=dt?dt(null):{},this.size=0}function Ky(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Fy="__lodash_hash_undefined__",qy=Object.prototype,Qy=qy.hasOwnProperty;function By(r){var e=this.__data__;if(dt){var t=e[r];return t===Fy?void 0:t}return Qy.call(e,r)?e[r]:void 0}var Vy=Object.prototype,Gy=Vy.hasOwnProperty;function Uy(r){var e=this.__data__;return dt?e[r]!==void 0:Gy.call(e,r)}var Ny="__lodash_hash_undefined__";function zy(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=dt&&e===void 0?Ny:e,this}function Ce(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}Ce.prototype.clear=Oy,Ce.prototype.delete=Ky,Ce.prototype.get=By,Ce.prototype.has=Uy,Ce.prototype.set=zy;function Ly(){this.__data__=[],this.size=0}function Ft(r,e){for(var t=r.length;t--;)if(ln(r[t][0],e))return t;return-1}var Wy=Array.prototype,Hy=Wy.splice;function Jy(r){var e=this.__data__,t=Ft(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():Hy.call(e,t,1),--this.size,!0}function Zy(r){var e=this.__data__,t=Ft(e,r);return t<0?void 0:e[t][1]}function Yy(r){return Ft(this.__data__,r)>-1}function Xy(r,e){var t=this.__data__,s=Ft(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function ne(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ne.prototype.clear=Ly,ne.prototype.delete=Jy,ne.prototype.get=Zy,ne.prototype.has=Yy,ne.prototype.set=Xy;var ft=$e(Y,"Map");function eg(){this.size=0,this.__data__={hash:new Ce,map:new(ft||ne),string:new Ce}}function tg(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function qt(r,e){var t=r.__data__;return tg(e)?t[typeof e=="string"?"string":"hash"]:t.map}function rg(r){var e=qt(this,r).delete(r);return this.size-=e?1:0,e}function sg(r){return qt(this,r).get(r)}function og(r){return qt(this,r).has(r)}function ng(r,e){var t=qt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function de(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])}}de.prototype.clear=eg,de.prototype.delete=rg,de.prototype.get=sg,de.prototype.has=og,de.prototype.set=ng;var ig="Expected a function";function qr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(ig);var t=function(){var s=arguments,o=e?e.apply(this,s):s[0],n=t.cache;if(n.has(o))return n.get(o);var i=r.apply(this,s);return t.cache=n.set(o,i)||n,i};return t.cache=new(qr.Cache||de),t}qr.Cache=de;var ag=500;function lg(r){var e=qr(r,function(s){return t.size===ag&&t.clear(),s}),t=e.cache;return e}var ug=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,cg=/\\(\\)?/g,dg=lg(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(ug,function(t,s,o,n){e.push(o?n.replace(cg,"$1"):s||t)}),e});function fg(r){return r==null?"":rn(r)}function pg(r,e){return qe(r)?r:Ty(r,e)?[r]:dg(fg(r))}function hg(r){if(typeof r=="string"||Ir(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function yg(r,e){e=pg(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[hg(e[t++])];return t&&t==s?r:void 0}function gg(r,e,t){var s=r==null?void 0:yg(r,e);return s===void 0?t:s}function mg(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var vg=bn(Object.getPrototypeOf,Object);function bg(){this.__data__=new ne,this.size=0}function kg(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function wg(r){return this.__data__.get(r)}function Ag(r){return this.__data__.has(r)}var $g=200;function Cg(r,e){var t=this.__data__;if(t instanceof ne){var s=t.__data__;if(!ft||s.length<$g-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new de(s)}return t.set(r,e),this.size=t.size,this}function Be(r){var e=this.__data__=new ne(r);this.size=e.size}Be.prototype.clear=bg,Be.prototype.delete=kg,Be.prototype.get=wg,Be.prototype.has=Ag,Be.prototype.set=Cg;var kn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,wn=kn&&typeof module=="object"&&module&&!module.nodeType&&module,Dg=wn&&wn.exports===kn,An=Dg?Y.Buffer:void 0;An&&An.allocUnsafe;function Pg(r,e){return r.slice()}function _g(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 xg(){return[]}var Eg=Object.prototype,jg=Eg.propertyIsEnumerable,$n=Object.getOwnPropertySymbols,Sg=$n?function(r){return r==null?[]:(r=Object(r),_g($n(r),function(e){return jg.call(r,e)}))}:xg;function Mg(r,e,t){var s=e(r);return qe(r)?s:mg(s,t(r))}function Rg(r){return Mg(r,My,Sg)}var Qr=$e(Y,"DataView"),Br=$e(Y,"Promise"),Vr=$e(Y,"Set"),Cn="[object Map]",Ig="[object Object]",Dn="[object Promise]",Pn="[object Set]",_n="[object WeakMap]",xn="[object DataView]",Tg=Ae(Qr),Og=Ae(ft),Kg=Ae(Br),Fg=Ae(Vr),qg=Ae(Or),ie=Ke;(Qr&&ie(new Qr(new ArrayBuffer(1)))!=xn||ft&&ie(new ft)!=Cn||Br&&ie(Br.resolve())!=Dn||Vr&&ie(new Vr)!=Pn||Or&&ie(new Or)!=_n)&&(ie=function(r){var e=Ke(r),t=e==Ig?r.constructor:void 0,s=t?Ae(t):"";if(s)switch(s){case Tg:return xn;case Og:return Cn;case Kg:return Dn;case Fg:return Pn;case qg:return _n}return e});var Qg=Object.prototype,Bg=Qg.hasOwnProperty;function Vg(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Bg.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var En=Y.Uint8Array;function Gr(r){var e=new r.constructor(r.byteLength);return new En(e).set(new En(r)),e}function Gg(r,e){var t=Gr(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Ug=/\w*$/;function Ng(r){var e=new r.constructor(r.source,Ug.exec(r));return e.lastIndex=r.lastIndex,e}var jn=ce?ce.prototype:void 0,Sn=jn?jn.valueOf:void 0;function zg(r){return Sn?Object(Sn.call(r)):{}}function Lg(r,e){var t=Gr(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var Wg="[object Boolean]",Hg="[object Date]",Jg="[object Map]",Zg="[object Number]",Yg="[object RegExp]",Xg="[object Set]",em="[object String]",tm="[object Symbol]",rm="[object ArrayBuffer]",sm="[object DataView]",om="[object Float32Array]",nm="[object Float64Array]",im="[object Int8Array]",am="[object Int16Array]",lm="[object Int32Array]",um="[object Uint8Array]",cm="[object Uint8ClampedArray]",dm="[object Uint16Array]",fm="[object Uint32Array]";function pm(r,e,t){var s=r.constructor;switch(e){case rm:return Gr(r);case Wg:case Hg:return new s(+r);case sm:return Gg(r);case om:case nm:case im:case am:case lm:case um:case cm:case dm:case fm:return Lg(r);case Jg:return new s;case Zg:case em:return new s(r);case Yg:return Ng(r);case Xg:return new s;case tm:return zg(r)}}function hm(r){return typeof r.constructor=="function"&&!cn(r)?Mh(vg(r)):{}}var ym="[object Map]";function gm(r){return Fe(r)&&ie(r)==ym}var Mn=Qe&&Qe.isMap,mm=Mn?Kr(Mn):gm,vm="[object Set]";function bm(r){return Fe(r)&&ie(r)==vm}var Rn=Qe&&Qe.isSet,km=Rn?Kr(Rn):bm,In="[object Arguments]",wm="[object Array]",Am="[object Boolean]",$m="[object Date]",Cm="[object Error]",Tn="[object Function]",Dm="[object GeneratorFunction]",Pm="[object Map]",_m="[object Number]",On="[object Object]",xm="[object RegExp]",Em="[object Set]",jm="[object String]",Sm="[object Symbol]",Mm="[object WeakMap]",Rm="[object ArrayBuffer]",Im="[object DataView]",Tm="[object Float32Array]",Om="[object Float64Array]",Km="[object Int8Array]",Fm="[object Int16Array]",qm="[object Int32Array]",Qm="[object Uint8Array]",Bm="[object Uint8ClampedArray]",Vm="[object Uint16Array]",Gm="[object Uint32Array]",A={};A[In]=A[wm]=A[Rm]=A[Im]=A[Am]=A[$m]=A[Tm]=A[Om]=A[Km]=A[Fm]=A[qm]=A[Pm]=A[_m]=A[On]=A[xm]=A[Em]=A[jm]=A[Sm]=A[Qm]=A[Bm]=A[Vm]=A[Gm]=!0,A[Cm]=A[Tn]=A[Mm]=!1;function Qt(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Kt(r))return r;var a=qe(r);if(a)i=Vg(r);else{var l=ie(r),u=l==Tn||l==Dm;if(gn(r))return Pg(r);if(l==On||l==In||u&&!o)i=u?{}:hm(r);else{if(!A[l])return o?r:{};i=pm(r,l)}}n||(n=new Be);var c=n.get(r);if(c)return c;n.set(r,i),km(r)?r.forEach(function(h){i.add(Qt(h,e,t,h,r,n))}):mm(r)&&r.forEach(function(h,p){i.set(p,Qt(h,e,t,p,r,n))});var d=Rg,f=a?void 0:d(r);return Rh(f||r,function(h,p){f&&(p=h,h=r[p]),Qh(i,p,Qt(h,e,t,p,r,n))}),i}var Um=1,Nm=4;function zm(r){return Qt(r,Um|Nm)}function Lm(r){const e=Ur(r);return Wm(e)}function Ur(r){if(typeof r!="object"||r===null)return String(r);if(Array.isArray(r))return"["+r.map(Ur).join(",")+"]";const e=Object.keys(r).sort();let t="{";for(let s=0;s<e.length;s++){const o=e[s];t+=o+":"+Ur(r[o]),s<e.length-1&&(t+=",")}return t+="}",t}function Wm(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 Nr=new S;function zr(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 Hm=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):zm(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=zr();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},Jm="k:",Zm="h:";function Lr(r,e=0){if(r.key)return`${Jm}${r.key}`;const t=Lm({type:r.type,url:r.rawUrl??r.url,model:r.model??"",occurrence:e});return`${Zm}${t}`}function Ym(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=Lr(s,n);for(;t.has(i);)n+=1,i=s.key?`${Lr(s)}#${n}`:Lr(s,n);return e.set(o,n+1),t.add(i),i})}const Bt=(r,e)=>r?(e||(e={}),r.replace(/\$\{(.*?)\}/g,(t,s)=>gg(e,s.trim(),""))):"",Xm=r=>{const e=new Set;return r.replace(/\$\{(.*?)\}/g,(t,s)=>(e.add(s.trim()),"")),{variables:Array.from(e).map(t=>({name:t}))}};let ev=class{log=Nr.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
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
10
  `;)g++;continue}if(m===`
11
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?u.push(this.buildObjectRow(d,h,n,c)):u.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?u.push(this.buildObjectRow(d,h,n,c)):u.push([...h])),u}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(`
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
14
  `)),t=[",",";"," ","|"],s=t.map(o=>{const n=new RegExp(`\\${o}`,"g");return(e.match(n)||[]).length});return t[s.indexOf(Math.max(...s))]||","}dynamicType(r){if(r==="true")return!0;if(r==="false")return!1;if(!isNaN(Number(r)))return Number(r);try{return JSON.parse(r)}catch{return r}}extractJson(r,e,t){const s=[];let o=e,n=!1,i="";for(;o<r.length;){const a=r[o];if(!n&&a===t)break;if(!n&&(a===`
15
- `||a==="\r")){this.log.error("JSON block spans multiple lines",void 0,{startIndex:e,endIndex:o});break}if(a==='"'&&i!=="\\"&&(n=!n),n||(a==="{"||a==="["?s.push(a):(a==="}"&&s[s.length-1]==="{"||a==="]"&&s[s.length-1]==="[")&&s.pop()),o++,i=a,s.length===0&&!n)break}return{value:r.slice(e,o),length:o-e}}};function Vn(r,e=","){return r&&typeof r=="string"?r.split(e).map(t=>t.trim()):[]}class tv{loader;log=Nr.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 c=new Map,u=new Map;if(e.references)for(const p of e.references)c.set(p.key,p),p.origin&&c.set(p.origin,p);if(e.properties)for(const p of e.properties)u.set(p.key,p),p.origin&&u.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=c.get(y);if(g)if(p[0]==="{"||p[0]==="[")try{return JSON.parse(p)}catch(m){a.error("Failed to parse JSON in CSV reference field",m,{header:y,value:p});return}else return g.type==="singleValued"?p:p?.length>0&&g.type==="multiValued"?Vn(p,g?.separator):p;const k=u.get(y);if(!(!e.autoGenerateProperties&&!k))switch(k?.type){case"string":return p;case"int":{const m=parseInt(p,10);if(isNaN(m)){v("int");return}return m}case"float":{const m=parseFloat(p);if(isNaN(m)){v("float");return}return m}case"boolean":if(p==="true")return!0;if(p==="false")return!1;v("boolean");return;case"json":try{return p=p.replace(/[\x00-\x1F\x7F-\x9F]/g,""),JSON.parse(p)}catch(m){a.error("Failed to parse JSON in CSV property field",m,{header:y,value:p}),v("json");return}case"Array<string>":case"Array<int>":case"Array<float>":case"Array<date>":if(p&&typeof p=="string"&&p[0]==="[")try{return JSON.parse(p)}catch{v(k.type);return}if(p&&typeof p=="string")return Vn(p,k?.separator);v(k.type);return;default:return p}}}}getJsonFromCSVString(e,t,s){return this.getJsonFromCSVStringWithMetadata(e,t,s).data}getJsonFromCSVStringWithMetadata(e,t,s){const o=[],n={},i=this.getParserConfig(t,s.options,o,n);return{data:new ev().parse(e,i),sourceColumns:o,coercionFailureSamples:n}}}var Gn=typeof global=="object"&&global&&global.Object===Object&&global,rv=typeof self=="object"&&self&&self.Object===Object&&self,X=Gn||rv||Function("return this")(),fe=X.Symbol,Un=Object.prototype,sv=Un.hasOwnProperty,ov=Un.toString,pt=fe?fe.toStringTag:void 0;function nv(r){var e=sv.call(r,pt),t=r[pt];try{r[pt]=void 0;var s=!0}catch{}var o=ov.call(r);return s&&(e?r[pt]=t:delete r[pt]),o}var iv=Object.prototype,av=iv.toString;function lv(r){return av.call(r)}var cv="[object Null]",uv="[object Undefined]",Nn=fe?fe.toStringTag:void 0;function Ve(r){return r==null?r===void 0?uv:cv:Nn&&Nn in Object(r)?nv(r):lv(r)}function De(r){return r!=null&&typeof r=="object"}var dv="[object Symbol]";function Wr(r){return typeof r=="symbol"||De(r)&&Ve(r)==dv}function zn(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 Ge=Array.isArray,Ln=fe?fe.prototype:void 0,Wn=Ln?Ln.toString:void 0;function Hn(r){if(typeof r=="string")return r;if(Ge(r))return zn(r,Hn)+"";if(Wr(r))return Wn?Wn.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Vt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}function Jn(r){return r}var fv="[object AsyncFunction]",pv="[object Function]",hv="[object GeneratorFunction]",yv="[object Proxy]";function Zn(r){if(!Vt(r))return!1;var e=Ve(r);return e==pv||e==hv||e==fv||e==yv}var Hr=X["__core-js_shared__"],Yn=(function(){var r=/[^.]+$/.exec(Hr&&Hr.keys&&Hr.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function gv(r){return!!Yn&&Yn in r}var mv=Function.prototype,vv=mv.toString;function _e(r){if(r!=null){try{return vv.call(r)}catch{}try{return r+""}catch{}}return""}var bv=/[\\^$.*+?()[\]{}|]/g,kv=/^\[object .+?Constructor\]$/,wv=Function.prototype,Av=Object.prototype,$v=wv.toString,Cv=Av.hasOwnProperty,Dv=RegExp("^"+$v.call(Cv).replace(bv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function _v(r){if(!Vt(r)||gv(r))return!1;var e=Zn(r)?Dv:kv;return e.test(_e(r))}function Pv(r,e){return r?.[e]}function Pe(r,e){var t=Pv(r,e);return _v(t)?t:void 0}var Jr=Pe(X,"WeakMap"),Xn=Object.create,xv=(function(){function r(){}return function(e){if(!Vt(e))return{};if(Xn)return Xn(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function Ev(r,e,t){switch(t.length){case 0:return r.call(e);case 1:return r.call(e,t[0]);case 2:return r.call(e,t[0],t[1]);case 3:return r.call(e,t[0],t[1],t[2])}return r.apply(e,t)}var Sv=800,jv=16,Mv=Date.now;function Rv(r){var e=0,t=0;return function(){var s=Mv(),o=jv-(s-t);if(t=s,o>0){if(++e>=Sv)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function Iv(r){return function(){return r}}var Gt=(function(){try{var r=Pe(Object,"defineProperty");return r({},"",{}),r}catch{}})(),Tv=Gt?function(r,e){return Gt(r,"toString",{configurable:!0,enumerable:!1,value:Iv(e),writable:!0})}:Jn,Ov=Rv(Tv);function Kv(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function Fv(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 qv(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 Bv(r,e,t){return e===e?Qv(r,e,t):Fv(r,qv,t)}function Vv(r,e){var t=r==null?0:r.length;return!!t&&Bv(r,e,0)>-1}var Gv=9007199254740991,Uv=/^(?:0|[1-9]\d*)$/;function Nv(r,e){var t=typeof r;return e=e??Gv,!!e&&(t=="number"||t!="symbol"&&Uv.test(r))&&r>-1&&r%1==0&&r<e}function zv(r,e,t){e=="__proto__"&&Gt?Gt(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function ei(r,e){return r===e||r!==r&&e!==e}var Lv=Object.prototype,Wv=Lv.hasOwnProperty;function Hv(r,e,t){var s=r[e];(!(Wv.call(r,e)&&ei(s,t))||t===void 0&&!(e in r))&&zv(r,e,t)}var ti=Math.max;function Jv(r,e,t){return e=ti(e===void 0?r.length-1:e,0),function(){for(var s=arguments,o=-1,n=ti(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),Ev(r,this,a)}}function Zv(r,e){return Ov(Jv(r,e,Jn),r+"")}var Yv=9007199254740991;function ri(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Yv}function si(r){return r!=null&&ri(r.length)&&!Zn(r)}var Xv=Object.prototype;function oi(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Xv;return r===t}function eb(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var tb="[object Arguments]";function ni(r){return De(r)&&Ve(r)==tb}var ii=Object.prototype,rb=ii.hasOwnProperty,sb=ii.propertyIsEnumerable,ob=ni((function(){return arguments})())?ni:function(r){return De(r)&&rb.call(r,"callee")&&!sb.call(r,"callee")};function nb(){return!1}var ai=typeof exports=="object"&&exports&&!exports.nodeType&&exports,li=ai&&typeof module=="object"&&module&&!module.nodeType&&module,ib=li&&li.exports===ai,ci=ib?X.Buffer:void 0,ab=ci?ci.isBuffer:void 0,ui=ab||nb,lb="[object Arguments]",cb="[object Array]",ub="[object Boolean]",db="[object Date]",fb="[object Error]",pb="[object Function]",hb="[object Map]",yb="[object Number]",gb="[object Object]",mb="[object RegExp]",vb="[object Set]",bb="[object String]",kb="[object WeakMap]",wb="[object ArrayBuffer]",Ab="[object DataView]",$b="[object Float32Array]",Cb="[object Float64Array]",Db="[object Int8Array]",_b="[object Int16Array]",Pb="[object Int32Array]",xb="[object Uint8Array]",Eb="[object Uint8ClampedArray]",Sb="[object Uint16Array]",jb="[object Uint32Array]",_={};_[$b]=_[Cb]=_[Db]=_[_b]=_[Pb]=_[xb]=_[Eb]=_[Sb]=_[jb]=!0,_[lb]=_[cb]=_[wb]=_[ub]=_[Ab]=_[db]=_[fb]=_[pb]=_[hb]=_[yb]=_[gb]=_[mb]=_[vb]=_[bb]=_[kb]=!1;function Mb(r){return De(r)&&ri(r.length)&&!!_[Ve(r)]}function Zr(r){return function(e){return r(e)}}var di=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ht=di&&typeof module=="object"&&module&&!module.nodeType&&module,Rb=ht&&ht.exports===di,Yr=Rb&&Gn.process,Ue=(function(){try{var r=ht&&ht.require&&ht.require("util").types;return r||Yr&&Yr.binding&&Yr.binding("util")}catch{}})(),fi=Ue&&Ue.isTypedArray,Ib=fi?Zr(fi):Mb,Tb=Object.prototype,Ob=Tb.hasOwnProperty;function Kb(r,e){var t=Ge(r),s=!t&&ob(r),o=!t&&!s&&ui(r),n=!t&&!s&&!o&&Ib(r),i=t||s||o||n,a=i?eb(r.length,String):[],l=a.length;for(var c in r)Ob.call(r,c)&&!(i&&(c=="length"||o&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Nv(c,l)))&&a.push(c);return a}function pi(r,e){return function(t){return r(e(t))}}var Fb=pi(Object.keys,Object),qb=Object.prototype,Qb=qb.hasOwnProperty;function Bb(r){if(!oi(r))return Fb(r);var e=[];for(var t in Object(r))Qb.call(r,t)&&t!="constructor"&&e.push(t);return e}function Vb(r){return si(r)?Kb(r):Bb(r)}var Gb=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ub=/^\w*$/;function Nb(r,e){if(Ge(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Wr(r)?!0:Ub.test(r)||!Gb.test(r)||e!=null&&r in Object(e)}var yt=Pe(Object,"create");function zb(){this.__data__=yt?yt(null):{},this.size=0}function Lb(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Wb="__lodash_hash_undefined__",Hb=Object.prototype,Jb=Hb.hasOwnProperty;function Zb(r){var e=this.__data__;if(yt){var t=e[r];return t===Wb?void 0:t}return Jb.call(e,r)?e[r]:void 0}var Yb=Object.prototype,Xb=Yb.hasOwnProperty;function ek(r){var e=this.__data__;return yt?e[r]!==void 0:Xb.call(e,r)}var tk="__lodash_hash_undefined__";function rk(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=yt&&e===void 0?tk:e,this}function xe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}xe.prototype.clear=zb,xe.prototype.delete=Lb,xe.prototype.get=Zb,xe.prototype.has=ek,xe.prototype.set=rk;function sk(){this.__data__=[],this.size=0}function Ut(r,e){for(var t=r.length;t--;)if(ei(r[t][0],e))return t;return-1}var ok=Array.prototype,nk=ok.splice;function ik(r){var e=this.__data__,t=Ut(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():nk.call(e,t,1),--this.size,!0}function ak(r){var e=this.__data__,t=Ut(e,r);return t<0?void 0:e[t][1]}function lk(r){return Ut(this.__data__,r)>-1}function ck(r,e){var t=this.__data__,s=Ut(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function ae(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ae.prototype.clear=sk,ae.prototype.delete=ik,ae.prototype.get=ak,ae.prototype.has=lk,ae.prototype.set=ck;var gt=Pe(X,"Map");function uk(){this.size=0,this.__data__={hash:new xe,map:new(gt||ae),string:new xe}}function dk(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Nt(r,e){var t=r.__data__;return dk(e)?t[typeof e=="string"?"string":"hash"]:t.map}function fk(r){var e=Nt(this,r).delete(r);return this.size-=e?1:0,e}function pk(r){return Nt(this,r).get(r)}function hk(r){return Nt(this,r).has(r)}function yk(r,e){var t=Nt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function le(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}le.prototype.clear=uk,le.prototype.delete=fk,le.prototype.get=pk,le.prototype.has=hk,le.prototype.set=yk;var gk="Expected a function";function Xr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(gk);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(Xr.Cache||le),t}Xr.Cache=le;var mk=500;function vk(r){var e=Xr(r,function(s){return t.size===mk&&t.clear(),s}),t=e.cache;return e}var bk=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,kk=/\\(\\)?/g,wk=vk(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(bk,function(t,s,o,n){e.push(o?n.replace(kk,"$1"):s||t)}),e});function Ak(r){return r==null?"":Hn(r)}function $k(r,e){return Ge(r)?r:Nb(r,e)?[r]:wk(Ak(r))}function Ck(r){if(typeof r=="string"||Wr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Dk(r,e){e=$k(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[Ck(e[t++])];return t&&t==s?r:void 0}function _k(r,e,t){var s=r==null?void 0:Dk(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 xk=pi(Object.getPrototypeOf,Object);function Ek(){this.__data__=new ae,this.size=0}function Sk(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function jk(r){return this.__data__.get(r)}function Mk(r){return this.__data__.has(r)}var Rk=200;function Ik(r,e){var t=this.__data__;if(t instanceof ae){var s=t.__data__;if(!gt||s.length<Rk-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new le(s)}return t.set(r,e),this.size=t.size,this}function Ne(r){var e=this.__data__=new ae(r);this.size=e.size}Ne.prototype.clear=Ek,Ne.prototype.delete=Sk,Ne.prototype.get=jk,Ne.prototype.has=Mk,Ne.prototype.set=Ik;var hi=typeof exports=="object"&&exports&&!exports.nodeType&&exports,yi=hi&&typeof module=="object"&&module&&!module.nodeType&&module,Tk=yi&&yi.exports===hi,gi=Tk?X.Buffer:void 0;gi&&gi.allocUnsafe;function Ok(r,e){return r.slice()}function Kk(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 Fk(){return[]}var qk=Object.prototype,Qk=qk.propertyIsEnumerable,mi=Object.getOwnPropertySymbols,Bk=mi?function(r){return r==null?[]:(r=Object(r),Kk(mi(r),function(e){return Qk.call(r,e)}))}:Fk;function Vk(r,e,t){var s=e(r);return Ge(r)?s:Pk(s,t(r))}function Gk(r){return Vk(r,Vb,Bk)}var es=Pe(X,"DataView"),ts=Pe(X,"Promise"),rs=Pe(X,"Set"),vi="[object Map]",Uk="[object Object]",bi="[object Promise]",ki="[object Set]",wi="[object WeakMap]",Ai="[object DataView]",Nk=_e(es),zk=_e(gt),Lk=_e(ts),Wk=_e(rs),Hk=_e(Jr),ce=Ve;(es&&ce(new es(new ArrayBuffer(1)))!=Ai||gt&&ce(new gt)!=vi||ts&&ce(ts.resolve())!=bi||rs&&ce(new rs)!=ki||Jr&&ce(new Jr)!=wi)&&(ce=function(r){var e=Ve(r),t=e==Uk?r.constructor:void 0,s=t?_e(t):"";if(s)switch(s){case Nk:return Ai;case zk:return vi;case Lk:return bi;case Wk:return ki;case Hk:return wi}return e});var Jk=Object.prototype,Zk=Jk.hasOwnProperty;function Yk(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Zk.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var $i=X.Uint8Array;function ss(r){var e=new r.constructor(r.byteLength);return new $i(e).set(new $i(r)),e}function Xk(r,e){var t=ss(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var ew=/\w*$/;function tw(r){var e=new r.constructor(r.source,ew.exec(r));return e.lastIndex=r.lastIndex,e}var Ci=fe?fe.prototype:void 0,Di=Ci?Ci.valueOf:void 0;function rw(r){return Di?Object(Di.call(r)):{}}function sw(r,e){var t=ss(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var ow="[object Boolean]",nw="[object Date]",iw="[object Map]",aw="[object Number]",lw="[object RegExp]",cw="[object Set]",uw="[object String]",dw="[object Symbol]",fw="[object ArrayBuffer]",pw="[object DataView]",hw="[object Float32Array]",yw="[object Float64Array]",gw="[object Int8Array]",mw="[object Int16Array]",vw="[object Int32Array]",bw="[object Uint8Array]",kw="[object Uint8ClampedArray]",ww="[object Uint16Array]",Aw="[object Uint32Array]";function $w(r,e,t){var s=r.constructor;switch(e){case fw:return ss(r);case ow:case nw:return new s(+r);case pw:return Xk(r);case hw:case yw:case gw:case mw:case vw:case bw:case kw:case ww:case Aw:return sw(r);case iw:return new s;case aw:case uw:return new s(r);case lw:return tw(r);case cw:return new s;case dw:return rw(r)}}function Cw(r){return typeof r.constructor=="function"&&!oi(r)?xv(xk(r)):{}}var Dw="[object Map]";function _w(r){return De(r)&&ce(r)==Dw}var _i=Ue&&Ue.isMap,Pw=_i?Zr(_i):_w,xw="[object Set]";function Ew(r){return De(r)&&ce(r)==xw}var Pi=Ue&&Ue.isSet,Sw=Pi?Zr(Pi):Ew,xi="[object Arguments]",jw="[object Array]",Mw="[object Boolean]",Rw="[object Date]",Iw="[object Error]",Ei="[object Function]",Tw="[object GeneratorFunction]",Ow="[object Map]",Kw="[object Number]",Si="[object Object]",Fw="[object RegExp]",qw="[object Set]",Qw="[object String]",Bw="[object Symbol]",Vw="[object WeakMap]",Gw="[object ArrayBuffer]",Uw="[object DataView]",Nw="[object Float32Array]",zw="[object Float64Array]",Lw="[object Int8Array]",Ww="[object Int16Array]",Hw="[object Int32Array]",Jw="[object Uint8Array]",Zw="[object Uint8ClampedArray]",Yw="[object Uint16Array]",Xw="[object Uint32Array]",$={};$[xi]=$[jw]=$[Gw]=$[Uw]=$[Mw]=$[Rw]=$[Nw]=$[zw]=$[Lw]=$[Ww]=$[Hw]=$[Ow]=$[Kw]=$[Si]=$[Fw]=$[qw]=$[Qw]=$[Bw]=$[Jw]=$[Zw]=$[Yw]=$[Xw]=!0,$[Iw]=$[Ei]=$[Vw]=!1;function zt(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Vt(r))return r;var a=Ge(r);if(a)i=Yk(r);else{var l=ce(r),c=l==Ei||l==Tw;if(ui(r))return Ok(r);if(l==Si||l==xi||c&&!o)i=c?{}:Cw(r);else{if(!$[l])return o?r:{};i=$w(r,l)}}n||(n=new Ne);var u=n.get(r);if(u)return u;n.set(r,i),Sw(r)?r.forEach(function(h){i.add(zt(h,e,t,h,r,n))}):Pw(r)&&r.forEach(function(h,p){i.set(p,zt(h,e,t,p,r,n))});var d=Gk,f=a?void 0:d(r);return Kv(f||r,function(h,p){f&&(p=h,h=r[p]),Hv(i,p,zt(h,e,t,p,r,n))}),i}var eA=1,tA=4;function mt(r){return zt(r,eA|tA)}var rA="__lodash_hash_undefined__";function sA(r){return this.__data__.set(r,rA),this}function oA(r){return this.__data__.has(r)}function Lt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new le;++e<t;)this.add(r[e])}Lt.prototype.add=Lt.prototype.push=sA,Lt.prototype.has=oA;function ji(r,e){return r.has(e)}function nA(r){return De(r)&&si(r)}var iA=Math.min;function aA(r,e,t){for(var s=Vv,o=r[0].length,n=r.length,i=n,a=Array(n),l=1/0,c=[];i--;){var u=r[i];l=iA(u.length,l),a[i]=o>=120&&u.length>=120?new Lt(i&&u):void 0}u=r[0];var d=-1,f=a[0];e:for(;++d<o&&c.length<l;){var h=u[d],p=h;if(h=h!==0?h:0,!(f?ji(f,p):s(c,p))){for(i=n;--i;){var y=a[i];if(!(y?ji(y,p):s(r[i],p)))continue e}f&&f.push(p),c.push(h)}}return c}function lA(r){return nA(r)?r:[]}var Mi=Zv(function(r){var e=zn(r,lA);return e.length&&e[0]===r[0]?aA(e):[]});class Ri{context="";total=0;totalItems=[];processedItems=new Set;downloadedItems=new Set;failedItems=new Set;remainingItems=new Set;skippedItems=[];run;processed=0;remaining=0;progress=0;currentItem;constructor(){}init(e,t){return this.total=e.length,this.totalItems=[...e],this.remaining=e.length,this.remainingItems=new Set(e),this.skippedItems=t?.skipped??[],this.run=t?.run,this.getProgress()}update(e,t,s,o){const n=mt(e);return n.success=t,o&&(n.status=o),t?this.downloadedItems.add(n):this.failedItems.add(n),this.currentItem=n,this.context=s,this.processed++,this.remaining--,this.progress=Math.round(this.processed*100/this.total),this.currentItem=n,this.processedItems.add(n),this.remainingItems.delete(e),this.getProgress()}getProgress(){return{total:this.total,processed:this.processed,remaining:this.remaining,downloadedItems:Array.from(this.downloadedItems.values()),failedItems:Array.from(this.failedItems.values()),progress:this.progress,context:this.context,currentItem:this.currentItem,totalItems:this.totalItems,processedItems:Array.from(this.processedItems.values()),remainingItems:Array.from(this.remainingItems.values()),skippedItems:this.skippedItems,run:this.run}}}function cA(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 Xm(r).variables.map(t=>t.name).filter(t=>_k(e,t)===void 0)}function Ii(r,e,t){const s={applicationKey:t?.applicationKey,resourceTags:t?.resourceTags,environmentKeys:t?.environmentKeys},o=r?.resources??[],n=Ym(o),i=[],a=[],l=Array.isArray(t?.resourceTags)&&t.resourceTags.length>0;return o.forEach((c,u)=>{if(l){if(!Array.isArray(c.tags)||!c.tags.length){a.push({resource:c,reason:"no-tags",id:n[u]});return}if(!cA(c.tags,t.resourceTags)){a.push({resource:c,reason:"tag-mismatch",id:n[u]});return}}const d=c.url??"",f=uA(d,e),h={...c,id:n[u],rawUrl:d,url:Bt(d,{...e})};f.length&&(h.unresolvedVariables=f),i.push(h)}),{scheduled:i,skipped:a,variables:e,run:s}}var dA=Object.defineProperty,fA=Object.getOwnPropertyDescriptor,Ti=(r,e,t,s)=>{for(var o=fA(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&dA(e,t,o),o};const pA={missingModelHandling:{autoGenerateProperties:!0},defaultDataContainerUpdateType:"set",csvParserOptions:{delimiter:"",quoteChar:'"',escapeChar:'"',commentChar:void 0}};let os=class{key;core;cdRef=new Hm;log=Nr.child({prefix:"AppLoader"});registeredTransformers=[];options=pA;csvParser=new tv(this);currentConfig;globalVariables=new Map;defaultVariables=new Map;progressListeners=new Set;currentProcessOptions;currentContext="";progressHandler=new Ri;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 Ii(e,s,t)}};variables={get:(r,e)=>{const t=this.currentConfig?.environments?.filter(s=>s.key===e);return this.evaluateVariables(t,this.currentProcessOptions).find(s=>s.key===r)},getAll:r=>{const e=this.currentConfig?.environments?.filter(t=>t.key===r);return this.evaluateVariables(e,this.currentProcessOptions)},getAllAsObject:r=>{const e=this.currentConfig?.environments?.filter(t=>t.key===r);return this.getEvaluatedVariablesAsRecord(e,this.currentProcessOptions)},default:{get:r=>this.defaultVariables.get(r),getAll:()=>Array.from(this.defaultVariables.values())},environment:{get:(r,e)=>{if(!r)return;const t=this.currentConfig?.environments?.find(s=>s.key===r);if(t)return t.variables?.find(s=>s.key===e)},getAll:r=>this.currentConfig?.environments?.find(e=>e.key===r)?.variables||[]},process:{get:r=>this.currentProcessOptions?.variables?.find(e=>e.key===r),getAll:()=>this.currentProcessOptions?.variables||[]},global:{get:r=>this.globalVariables.get(r),getAll:()=>Array.from(this.globalVariables.values()),set:(r,e)=>{this.globalVariables.set(r,{key:r,value:e})},delete:r=>{this.globalVariables.delete(r)}}};transformers={get:r=>this.registeredTransformers.filter(e=>Mi(e.applyTo,r.appyTo).length>0),getAll:()=>this.registeredTransformers,set:r=>{this.transformers.remove(r.key),this.registeredTransformers.push(r)},remove:r=>{const e=this.registeredTransformers.findIndex(t=>t.key===r);e>-1&&this.registeredTransformers.splice(e,1)}};config={get:()=>mt(this.currentConfig),set:r=>{this.currentConfig=mt(r)},fetch:async r=>this.fetchConfig(r)};async fetchConfig(r){if(!this.core)throw this.log.error("dcupl not connected. Did you add your loader to dcupl? -> dcupl.addRunner(loader)"),new Error;let e;r?.baseUrl&&this.defaultVariables.set("baseUrl",{key:"baseUrl",value:String(r.baseUrl)}),r?.loaderFileName&&this.defaultVariables.set("loaderFileName",{key:"loaderFileName",value:String(r.loaderFileName)});const t=this.variables.get("baseUrl")?.value;if(t&&this.isDcuplCdn(t))await this.setCdnVersion(),e=await this.loadConfigFromApi();else{const s=this.variables.get("loaderFileName")?.value,o=`${t}/${s}`;e=await this.loadConfigFromUrl(o,r?.headers)}if(this.isValidConfig(e))return r?.skipApply||this.config.set(e),e;throw new Error("Invalid Loader Configuration")}isValidConfig(r){return!!r}async loadConfigFromUrl(r,e){try{const t={};e&&(t.headers=e.reduce((o,n)=>(o[n.key]=n.value,o),{}));const s=await fetch(r,t);if(!s.ok)throw new Error(`Failed to fetch loader configuration from ${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=zr();const{config:e,options:t,environments:s,variables:o}=this.resolveRunContext(r),n=this.getHeaderConfigs(s),i=this.getQueryParamConfigs(s),a=Ii(e,o,t),l=this.getLoaderOptions(e,t),c=await this.fetchResources(a,o,l,n,i);return this.currentProcessOptions=t,c}getHeaderConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.headers&&e.push(...t.headers)}),e}getQueryParamConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.queryParams&&e.push(...t.queryParams)}),e}getLoaderOptions(r,e){return e?.options?Object.assign({},this.options,e.options):r?.options?Object.assign({},this.options,r.options):Object.assign({},this.options)}resolveRunContext(r){if(!this.currentConfig)throw new Error("There is no config present. Make sure to call loader.setConfig(..) or loader.fetchConfig(...)");const e=mt(r),t=mt(this.currentConfig);if(e?.applicationKey){const n=this.getAppPreset(t,e);if(!n)throw new Error(`The applicationKey ${e.applicationKey} does not exist`);e.resourceTags=e.resourceTags||n?.resourceTags,e.variables=e.variables||n?.variables}const s=this.getEnvironments(t,e),o=this.getEvaluatedVariablesAsRecord(s,e);return{config:t,options:e,environments:s,variables:o}}evaluateVariables(r,e){const t=new Map;this.defaultVariables&&this.defaultVariables.forEach(n=>{t.set(n.key,n)}),r?.forEach(n=>{n?.variables&&n.variables.forEach(i=>{t.set(i.key,i)})}),e?.variables&&e.variables.forEach(n=>{t.set(n.key,n)}),this.globalVariables&&this.globalVariables.forEach(n=>{t.set(n.key,n)});const s=Array.from(t.values()).map(n=>({...n})),o={};for(const n of s)o[n.key]=n.value||"";for(const n of s)n.value=Bt(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=Bt(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=Bt(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(u=>u.key===n.url);if(i){o.push(i);const u=this.progressHandler.update(n,!0,"transformer");this.updateProgressListeners(u);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 c=this.progressHandler.update(n,!0,"transformer");this.updateProgressListeners(c)}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:c}=this.getRequestOptions(n,e,t,s),u=await fetch(l,{headers:c});if(a=u.status,!u.ok)throw new Error(`Failed to fetch data from ${l}`);const d=F.now(),f=await u.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 c={title:n.url,type:"loader",errorGroup:"ResourceError",errorType:"InvalidResource",meta:n,description:l?.message};this.setError(c);const u=this.progressHandler.update(n,!1,"model",a);return this.updateProgressListeners(u),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=zr(),c={placeholderUid:l,data:[],model:a.model};this.core.registerContainer(c);const u=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 bt=[],Wt=this.core.modelParser.unprocessedModelDescriptions.get(a.model);if(!Wt&&(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}),Wt=this.core.modelParser.unprocessedModelDescriptions.get(a.model)}const gA=F.now();let Oi={sourceColumns:[],coercionFailureSamples:{},origin:a.url};if(a.url.endsWith(".csv")||y?.includes("text/csv")){if(Wt){const q=this.csvParser.getJsonFromCSVStringWithMetadata(M,Wt,a);bt=q.data,Oi={sourceColumns:q.sourceColumns,coercionFailureSamples:q.coercionFailureSamples,origin:a.url}}}else bt=M;const mA=F.now(),vA=F.now();try{bt=this.handleTransformerLogic(bt,a,"parsedFileTransformer",n||[])}catch(q){this.log.error("Transformer error",q,{resource:a.url,model:a.model})}const bA=F.now(),Ki={placeholderUid:l,model:a.model,data:bt,type:a.options?.updateType||t.defaultDataContainerUpdateType,keyProperty:a?.options?.keyProperty,keyPropertySeparator:a?.options?.keyPropertySeparator,autoGenerateKey:a.options?.autoGenerateKey,autoGenerateProperties:a.options?.autoGenerateProperties},ns=F.getEntriesByName(f.toString());if(Array.isArray(ns)&&ns[0]){const q=ns[0],wA={name:a.url,type:"resource",createdAt:new Date().getTime(),value:{model:a.model,type:"data",start:u,startTime:q.startTime,requestStart:q.requestStart,responseEnd:q.responseEnd,responseStart:q.responseStart,duration:q.duration,parseEnd:k,rawTransformStart:m,rawTransformEnd:N,parseStart:v,csvToJsonStart:gA,csvToJsonEnd:mA,parsedTransformStart:vA,parsedTransformEnd:bA,decodedBodySize:q.decodedBodySize,encodedBodySize:q.encodedBodySize,end:k}};this.core.analyticsController.set({value:wA,context:this.currentContext})}this.core.updateRegisteredContainer(Ki,Oi);const kA=this.progressHandler.update(a,!0,"data",d);return this.updateProgressListeners(kA),Promise.resolve(Ki)}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(c);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 Ri,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"),c=await this.handleTransformerResources(l,e,s,o),u=n.filter(f=>f.type==="model");await this.handleModelResources(u,e,s,o);const d=n.filter(f=>f.type==="data");return await this.handleDataResources(d,e,t,s,o,c),!0}catch(i){return this.log.error("Failed to fetch resources",i),!1}}addModelOrView(r,e){try{"model"in e?this.core.views.set(e):this.core.models.set(e)}catch(t){const s={title:r.url,type:"model",errorGroup:"ModelDefinitionError",errorType:"InvalidModelDefinition",model:e.key,meta:r,description:t?.message};this.setError(s)}}handleTransformerLogic(r,e,t,s){for(const o of s)o.type===t&&o.transformer&&(!o.applyTo.length&&!e.tags?.length&&(r=o.transformer(e,r)),Mi(o.applyTo,e.tags||[]).length&&(r=o.transformer(e,r)));return r}updateProgressListeners(r){this.progressListeners.forEach(e=>e(r))}on(r){return this.progressListeners.add(r),()=>{this.progressListeners.delete(r)}}setError(r){this.core.modelParser.qualityController.enabled&&this.core.modelParser.qualityController.setError(r)}};Ti([Bn({scope:"global",origin:"loader",type:"loader_config_fetched",connectMessage:!0,connectMessageResult:!0})],os.prototype,"fetchConfig"),Ti([Bn({scope:"global",origin:"loader",type:"loader_processed",connectMessage:!0})],os.prototype,"process");const hA=os;let vt,ze;async function yA(r){return vt=new oh(r.options),ze=new hA,vt.loaders.add(ze,"default"),r.appLoaderConfig?await ze.config.fetch(r.appLoaderConfig):await ze.config.fetch(),await ze.process(r.processOptions),await vt.init(),globalThis.dcupl=vt,{dcupl:vt,loader:ze}}globalThis.initDcupl=yA})();
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 tv{loader;log=Nr.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 ev().parse(e,i),sourceColumns:o,coercionFailureSamples:n}}}var Vn=typeof global=="object"&&global&&global.Object===Object&&global,rv=typeof self=="object"&&self&&self.Object===Object&&self,X=Vn||rv||Function("return this")(),fe=X.Symbol,Gn=Object.prototype,sv=Gn.hasOwnProperty,ov=Gn.toString,pt=fe?fe.toStringTag:void 0;function nv(r){var e=sv.call(r,pt),t=r[pt];try{r[pt]=void 0;var s=!0}catch{}var o=ov.call(r);return s&&(e?r[pt]=t:delete r[pt]),o}var iv=Object.prototype,av=iv.toString;function lv(r){return av.call(r)}var uv="[object Null]",cv="[object Undefined]",Un=fe?fe.toStringTag:void 0;function Ve(r){return r==null?r===void 0?cv:uv:Un&&Un in Object(r)?nv(r):lv(r)}function De(r){return r!=null&&typeof r=="object"}var dv="[object Symbol]";function Wr(r){return typeof r=="symbol"||De(r)&&Ve(r)==dv}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 Ge=Array.isArray,zn=fe?fe.prototype:void 0,Ln=zn?zn.toString:void 0;function Wn(r){if(typeof r=="string")return r;if(Ge(r))return Nn(r,Wn)+"";if(Wr(r))return Ln?Ln.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Vt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}function Hn(r){return r}var fv="[object AsyncFunction]",pv="[object Function]",hv="[object GeneratorFunction]",yv="[object Proxy]";function Jn(r){if(!Vt(r))return!1;var e=Ve(r);return e==pv||e==hv||e==fv||e==yv}var Hr=X["__core-js_shared__"],Zn=(function(){var r=/[^.]+$/.exec(Hr&&Hr.keys&&Hr.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function gv(r){return!!Zn&&Zn in r}var mv=Function.prototype,vv=mv.toString;function Pe(r){if(r!=null){try{return vv.call(r)}catch{}try{return r+""}catch{}}return""}var bv=/[\\^$.*+?()[\]{}|]/g,kv=/^\[object .+?Constructor\]$/,wv=Function.prototype,Av=Object.prototype,$v=wv.toString,Cv=Av.hasOwnProperty,Dv=RegExp("^"+$v.call(Cv).replace(bv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Pv(r){if(!Vt(r)||gv(r))return!1;var e=Jn(r)?Dv:kv;return e.test(Pe(r))}function _v(r,e){return r?.[e]}function _e(r,e){var t=_v(r,e);return Pv(t)?t:void 0}var Jr=_e(X,"WeakMap"),Yn=Object.create,xv=(function(){function r(){}return function(e){if(!Vt(e))return{};if(Yn)return Yn(e);r.prototype=e;var t=new r;return r.prototype=void 0,t}})();function Ev(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 jv=800,Sv=16,Mv=Date.now;function Rv(r){var e=0,t=0;return function(){var s=Mv(),o=Sv-(s-t);if(t=s,o>0){if(++e>=jv)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}function Iv(r){return function(){return r}}var Gt=(function(){try{var r=_e(Object,"defineProperty");return r({},"",{}),r}catch{}})(),Tv=Gt?function(r,e){return Gt(r,"toString",{configurable:!0,enumerable:!1,value:Iv(e),writable:!0})}:Hn,Ov=Rv(Tv);function Kv(r,e){for(var t=-1,s=r==null?0:r.length;++t<s&&e(r[t],t,r)!==!1;);return r}function Fv(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 qv(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 Bv(r,e,t){return e===e?Qv(r,e,t):Fv(r,qv,t)}function Vv(r,e){var t=r==null?0:r.length;return!!t&&Bv(r,e,0)>-1}var Gv=9007199254740991,Uv=/^(?:0|[1-9]\d*)$/;function Nv(r,e){var t=typeof r;return e=e??Gv,!!e&&(t=="number"||t!="symbol"&&Uv.test(r))&&r>-1&&r%1==0&&r<e}function zv(r,e,t){e=="__proto__"&&Gt?Gt(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 Lv=Object.prototype,Wv=Lv.hasOwnProperty;function Hv(r,e,t){var s=r[e];(!(Wv.call(r,e)&&Xn(s,t))||t===void 0&&!(e in r))&&zv(r,e,t)}var ei=Math.max;function Jv(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),Ev(r,this,a)}}function Zv(r,e){return Ov(Jv(r,e,Hn),r+"")}var Yv=9007199254740991;function ti(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Yv}function ri(r){return r!=null&&ti(r.length)&&!Jn(r)}var Xv=Object.prototype;function si(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Xv;return r===t}function eb(r,e){for(var t=-1,s=Array(r);++t<r;)s[t]=e(t);return s}var tb="[object Arguments]";function oi(r){return De(r)&&Ve(r)==tb}var ni=Object.prototype,rb=ni.hasOwnProperty,sb=ni.propertyIsEnumerable,ob=oi((function(){return arguments})())?oi:function(r){return De(r)&&rb.call(r,"callee")&&!sb.call(r,"callee")};function nb(){return!1}var ii=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ai=ii&&typeof module=="object"&&module&&!module.nodeType&&module,ib=ai&&ai.exports===ii,li=ib?X.Buffer:void 0,ab=li?li.isBuffer:void 0,ui=ab||nb,lb="[object Arguments]",ub="[object Array]",cb="[object Boolean]",db="[object Date]",fb="[object Error]",pb="[object Function]",hb="[object Map]",yb="[object Number]",gb="[object Object]",mb="[object RegExp]",vb="[object Set]",bb="[object String]",kb="[object WeakMap]",wb="[object ArrayBuffer]",Ab="[object DataView]",$b="[object Float32Array]",Cb="[object Float64Array]",Db="[object Int8Array]",Pb="[object Int16Array]",_b="[object Int32Array]",xb="[object Uint8Array]",Eb="[object Uint8ClampedArray]",jb="[object Uint16Array]",Sb="[object Uint32Array]",P={};P[$b]=P[Cb]=P[Db]=P[Pb]=P[_b]=P[xb]=P[Eb]=P[jb]=P[Sb]=!0,P[lb]=P[ub]=P[wb]=P[cb]=P[Ab]=P[db]=P[fb]=P[pb]=P[hb]=P[yb]=P[gb]=P[mb]=P[vb]=P[bb]=P[kb]=!1;function Mb(r){return De(r)&&ti(r.length)&&!!P[Ve(r)]}function Zr(r){return function(e){return r(e)}}var ci=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ht=ci&&typeof module=="object"&&module&&!module.nodeType&&module,Rb=ht&&ht.exports===ci,Yr=Rb&&Vn.process,Ue=(function(){try{var r=ht&&ht.require&&ht.require("util").types;return r||Yr&&Yr.binding&&Yr.binding("util")}catch{}})(),di=Ue&&Ue.isTypedArray,Ib=di?Zr(di):Mb,Tb=Object.prototype,Ob=Tb.hasOwnProperty;function Kb(r,e){var t=Ge(r),s=!t&&ob(r),o=!t&&!s&&ui(r),n=!t&&!s&&!o&&Ib(r),i=t||s||o||n,a=i?eb(r.length,String):[],l=a.length;for(var u in r)Ob.call(r,u)&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||n&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Nv(u,l)))&&a.push(u);return a}function fi(r,e){return function(t){return r(e(t))}}var Fb=fi(Object.keys,Object),qb=Object.prototype,Qb=qb.hasOwnProperty;function Bb(r){if(!si(r))return Fb(r);var e=[];for(var t in Object(r))Qb.call(r,t)&&t!="constructor"&&e.push(t);return e}function Vb(r){return ri(r)?Kb(r):Bb(r)}var Gb=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ub=/^\w*$/;function Nb(r,e){if(Ge(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Wr(r)?!0:Ub.test(r)||!Gb.test(r)||e!=null&&r in Object(e)}var yt=_e(Object,"create");function zb(){this.__data__=yt?yt(null):{},this.size=0}function Lb(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Wb="__lodash_hash_undefined__",Hb=Object.prototype,Jb=Hb.hasOwnProperty;function Zb(r){var e=this.__data__;if(yt){var t=e[r];return t===Wb?void 0:t}return Jb.call(e,r)?e[r]:void 0}var Yb=Object.prototype,Xb=Yb.hasOwnProperty;function ek(r){var e=this.__data__;return yt?e[r]!==void 0:Xb.call(e,r)}var tk="__lodash_hash_undefined__";function rk(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=yt&&e===void 0?tk:e,this}function xe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}xe.prototype.clear=zb,xe.prototype.delete=Lb,xe.prototype.get=Zb,xe.prototype.has=ek,xe.prototype.set=rk;function sk(){this.__data__=[],this.size=0}function Ut(r,e){for(var t=r.length;t--;)if(Xn(r[t][0],e))return t;return-1}var ok=Array.prototype,nk=ok.splice;function ik(r){var e=this.__data__,t=Ut(e,r);if(t<0)return!1;var s=e.length-1;return t==s?e.pop():nk.call(e,t,1),--this.size,!0}function ak(r){var e=this.__data__,t=Ut(e,r);return t<0?void 0:e[t][1]}function lk(r){return Ut(this.__data__,r)>-1}function uk(r,e){var t=this.__data__,s=Ut(t,r);return s<0?(++this.size,t.push([r,e])):t[s][1]=e,this}function ae(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}ae.prototype.clear=sk,ae.prototype.delete=ik,ae.prototype.get=ak,ae.prototype.has=lk,ae.prototype.set=uk;var gt=_e(X,"Map");function ck(){this.size=0,this.__data__={hash:new xe,map:new(gt||ae),string:new xe}}function dk(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Nt(r,e){var t=r.__data__;return dk(e)?t[typeof e=="string"?"string":"hash"]:t.map}function fk(r){var e=Nt(this,r).delete(r);return this.size-=e?1:0,e}function pk(r){return Nt(this,r).get(r)}function hk(r){return Nt(this,r).has(r)}function yk(r,e){var t=Nt(this,r),s=t.size;return t.set(r,e),this.size+=t.size==s?0:1,this}function le(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var s=r[e];this.set(s[0],s[1])}}le.prototype.clear=ck,le.prototype.delete=fk,le.prototype.get=pk,le.prototype.has=hk,le.prototype.set=yk;var gk="Expected a function";function Xr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(gk);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(Xr.Cache||le),t}Xr.Cache=le;var mk=500;function vk(r){var e=Xr(r,function(s){return t.size===mk&&t.clear(),s}),t=e.cache;return e}var bk=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,kk=/\\(\\)?/g,wk=vk(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(bk,function(t,s,o,n){e.push(o?n.replace(kk,"$1"):s||t)}),e});function Ak(r){return r==null?"":Wn(r)}function $k(r,e){return Ge(r)?r:Nb(r,e)?[r]:wk(Ak(r))}function Ck(r){if(typeof r=="string"||Wr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Dk(r,e){e=$k(e,r);for(var t=0,s=e.length;r!=null&&t<s;)r=r[Ck(e[t++])];return t&&t==s?r:void 0}function Pk(r,e,t){var s=r==null?void 0:Dk(r,e);return s===void 0?t:s}function _k(r,e){for(var t=-1,s=e.length,o=r.length;++t<s;)r[o+t]=e[t];return r}var xk=fi(Object.getPrototypeOf,Object);function Ek(){this.__data__=new ae,this.size=0}function jk(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Sk(r){return this.__data__.get(r)}function Mk(r){return this.__data__.has(r)}var Rk=200;function Ik(r,e){var t=this.__data__;if(t instanceof ae){var s=t.__data__;if(!gt||s.length<Rk-1)return s.push([r,e]),this.size=++t.size,this;t=this.__data__=new le(s)}return t.set(r,e),this.size=t.size,this}function Ne(r){var e=this.__data__=new ae(r);this.size=e.size}Ne.prototype.clear=Ek,Ne.prototype.delete=jk,Ne.prototype.get=Sk,Ne.prototype.has=Mk,Ne.prototype.set=Ik;var pi=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hi=pi&&typeof module=="object"&&module&&!module.nodeType&&module,Tk=hi&&hi.exports===pi,yi=Tk?X.Buffer:void 0;yi&&yi.allocUnsafe;function Ok(r,e){return r.slice()}function Kk(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 Fk(){return[]}var qk=Object.prototype,Qk=qk.propertyIsEnumerable,gi=Object.getOwnPropertySymbols,Bk=gi?function(r){return r==null?[]:(r=Object(r),Kk(gi(r),function(e){return Qk.call(r,e)}))}:Fk;function Vk(r,e,t){var s=e(r);return Ge(r)?s:_k(s,t(r))}function Gk(r){return Vk(r,Vb,Bk)}var es=_e(X,"DataView"),ts=_e(X,"Promise"),rs=_e(X,"Set"),mi="[object Map]",Uk="[object Object]",vi="[object Promise]",bi="[object Set]",ki="[object WeakMap]",wi="[object DataView]",Nk=Pe(es),zk=Pe(gt),Lk=Pe(ts),Wk=Pe(rs),Hk=Pe(Jr),ue=Ve;(es&&ue(new es(new ArrayBuffer(1)))!=wi||gt&&ue(new gt)!=mi||ts&&ue(ts.resolve())!=vi||rs&&ue(new rs)!=bi||Jr&&ue(new Jr)!=ki)&&(ue=function(r){var e=Ve(r),t=e==Uk?r.constructor:void 0,s=t?Pe(t):"";if(s)switch(s){case Nk:return wi;case zk:return mi;case Lk:return vi;case Wk:return bi;case Hk:return ki}return e});var Jk=Object.prototype,Zk=Jk.hasOwnProperty;function Yk(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Zk.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var Ai=X.Uint8Array;function ss(r){var e=new r.constructor(r.byteLength);return new Ai(e).set(new Ai(r)),e}function Xk(r,e){var t=ss(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var ew=/\w*$/;function tw(r){var e=new r.constructor(r.source,ew.exec(r));return e.lastIndex=r.lastIndex,e}var $i=fe?fe.prototype:void 0,Ci=$i?$i.valueOf:void 0;function rw(r){return Ci?Object(Ci.call(r)):{}}function sw(r,e){var t=ss(r.buffer);return new r.constructor(t,r.byteOffset,r.length)}var ow="[object Boolean]",nw="[object Date]",iw="[object Map]",aw="[object Number]",lw="[object RegExp]",uw="[object Set]",cw="[object String]",dw="[object Symbol]",fw="[object ArrayBuffer]",pw="[object DataView]",hw="[object Float32Array]",yw="[object Float64Array]",gw="[object Int8Array]",mw="[object Int16Array]",vw="[object Int32Array]",bw="[object Uint8Array]",kw="[object Uint8ClampedArray]",ww="[object Uint16Array]",Aw="[object Uint32Array]";function $w(r,e,t){var s=r.constructor;switch(e){case fw:return ss(r);case ow:case nw:return new s(+r);case pw:return Xk(r);case hw:case yw:case gw:case mw:case vw:case bw:case kw:case ww:case Aw:return sw(r);case iw:return new s;case aw:case cw:return new s(r);case lw:return tw(r);case uw:return new s;case dw:return rw(r)}}function Cw(r){return typeof r.constructor=="function"&&!si(r)?xv(xk(r)):{}}var Dw="[object Map]";function Pw(r){return De(r)&&ue(r)==Dw}var Di=Ue&&Ue.isMap,_w=Di?Zr(Di):Pw,xw="[object Set]";function Ew(r){return De(r)&&ue(r)==xw}var Pi=Ue&&Ue.isSet,jw=Pi?Zr(Pi):Ew,_i="[object Arguments]",Sw="[object Array]",Mw="[object Boolean]",Rw="[object Date]",Iw="[object Error]",xi="[object Function]",Tw="[object GeneratorFunction]",Ow="[object Map]",Kw="[object Number]",Ei="[object Object]",Fw="[object RegExp]",qw="[object Set]",Qw="[object String]",Bw="[object Symbol]",Vw="[object WeakMap]",Gw="[object ArrayBuffer]",Uw="[object DataView]",Nw="[object Float32Array]",zw="[object Float64Array]",Lw="[object Int8Array]",Ww="[object Int16Array]",Hw="[object Int32Array]",Jw="[object Uint8Array]",Zw="[object Uint8ClampedArray]",Yw="[object Uint16Array]",Xw="[object Uint32Array]",$={};$[_i]=$[Sw]=$[Gw]=$[Uw]=$[Mw]=$[Rw]=$[Nw]=$[zw]=$[Lw]=$[Ww]=$[Hw]=$[Ow]=$[Kw]=$[Ei]=$[Fw]=$[qw]=$[Qw]=$[Bw]=$[Jw]=$[Zw]=$[Yw]=$[Xw]=!0,$[Iw]=$[xi]=$[Vw]=!1;function zt(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Vt(r))return r;var a=Ge(r);if(a)i=Yk(r);else{var l=ue(r),u=l==xi||l==Tw;if(ui(r))return Ok(r);if(l==Ei||l==_i||u&&!o)i=u?{}:Cw(r);else{if(!$[l])return o?r:{};i=$w(r,l)}}n||(n=new Ne);var c=n.get(r);if(c)return c;n.set(r,i),jw(r)?r.forEach(function(h){i.add(zt(h,e,t,h,r,n))}):_w(r)&&r.forEach(function(h,p){i.set(p,zt(h,e,t,p,r,n))});var d=Gk,f=a?void 0:d(r);return Kv(f||r,function(h,p){f&&(p=h,h=r[p]),Hv(i,p,zt(h,e,t,p,r,n))}),i}var eA=1,tA=4;function mt(r){return zt(r,eA|tA)}var rA="__lodash_hash_undefined__";function sA(r){return this.__data__.set(r,rA),this}function oA(r){return this.__data__.has(r)}function Lt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new le;++e<t;)this.add(r[e])}Lt.prototype.add=Lt.prototype.push=sA,Lt.prototype.has=oA;function ji(r,e){return r.has(e)}function nA(r){return De(r)&&ri(r)}var iA=Math.min;function aA(r,e,t){for(var s=Vv,o=r[0].length,n=r.length,i=n,a=Array(n),l=1/0,u=[];i--;){var c=r[i];l=iA(c.length,l),a[i]=o>=120&&c.length>=120?new Lt(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 lA(r){return nA(r)?r:[]}var Si=Zv(function(r){var e=Nn(r,lA);return e.length&&e[0]===r[0]?aA(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=mt(e);return n.success=t,o&&(n.status=o),t?this.downloadedItems.add(n):this.failedItems.add(n),this.currentItem=n,this.context=s,this.processed++,this.remaining--,this.progress=Math.round(this.processed*100/this.total),this.currentItem=n,this.processedItems.add(n),this.remainingItems.delete(e),this.getProgress()}getProgress(){return{total:this.total,processed:this.processed,remaining:this.remaining,downloadedItems:Array.from(this.downloadedItems.values()),failedItems:Array.from(this.failedItems.values()),progress:this.progress,context:this.context,currentItem:this.currentItem,totalItems:this.totalItems,processedItems:Array.from(this.processedItems.values()),remainingItems:Array.from(this.remainingItems.values()),skippedItems:this.skippedItems,run:this.run}}}function uA(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 cA(r,e){return Xm(r).variables.map(t=>t.name).filter(t=>Pk(e,t)===void 0)}function Ri(r,e,t){const s={applicationKey:t?.applicationKey,resourceTags:t?.resourceTags,environmentKeys:t?.environmentKeys},o=r?.resources??[],n=Ym(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(!uA(u.tags,t.resourceTags)){a.push({resource:u,reason:"tag-mismatch",id:n[c]});return}}const d=u.url??"",f=cA(d,e),h={...u,id:n[c],rawUrl:d,url:Bt(d,{...e})};f.length&&(h.unresolvedVariables=f),i.push(h)}),{scheduled:i,skipped:a,variables:e,run:s}}var dA=Object.defineProperty,fA=Object.getOwnPropertyDescriptor,Ii=(r,e,t,s)=>{for(var o=fA(e,t),n=r.length-1,i;n>=0;n--)(i=r[n])&&(o=i(e,t,o)||o);return o&&dA(e,t,o),o};const pA={missingModelHandling:{autoGenerateProperties:!0},defaultDataContainerUpdateType:"set",csvParserOptions:{delimiter:"",quoteChar:'"',escapeChar:'"',commentChar:void 0}};let os=class{key;core;cdRef=new Hm;log=Nr.child({prefix:"AppLoader"});registeredTransformers=[];options=pA;csvParser=new tv(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:()=>mt(this.currentConfig),set:r=>{this.currentConfig=mt(r)},fetch:async r=>this.fetchConfig(r)};async fetchConfig(r){if(!this.core)throw this.log.error("dcupl not connected. Did you add your loader to dcupl? -> dcupl.addRunner(loader)"),new Error;let e;r?.baseUrl&&this.defaultVariables.set("baseUrl",{key:"baseUrl",value:String(r.baseUrl)}),r?.loaderFileName&&this.defaultVariables.set("loaderFileName",{key:"loaderFileName",value:String(r.loaderFileName)});const t=this.variables.get("baseUrl")?.value;if(t&&this.isDcuplCdn(t))await this.setCdnVersion(),e=await this.loadConfigFromApi();else{const s=this.variables.get("loaderFileName")?.value,o=`${t}/${s}`;e=await this.loadConfigFromUrl(o,r?.headers)}if(this.isValidConfig(e))return r?.skipApply||this.config.set(e),e;throw new Error("Invalid Loader Configuration")}isValidConfig(r){return!!r}async loadConfigFromUrl(r,e){try{const t={};e&&(t.headers=e.reduce((o,n)=>(o[n.key]=n.value,o),{}));const s=await fetch(r,t);if(!s.ok)throw new Error(`Failed to fetch loader configuration from ${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=zr();const{config:e,options:t,environments:s,variables:o}=this.resolveRunContext(r),n=this.getHeaderConfigs(s),i=this.getQueryParamConfigs(s),a=Ri(e,o,t),l=this.getLoaderOptions(e,t),u=await this.fetchResources(a,o,l,n,i);return this.currentProcessOptions=t,u}getHeaderConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.headers&&e.push(...t.headers)}),e}getQueryParamConfigs(r){if(!r)return[];const e=[];return r.forEach(t=>{t.queryParams&&e.push(...t.queryParams)}),e}getLoaderOptions(r,e){return e?.options?Object.assign({},this.options,e.options):r?.options?Object.assign({},this.options,r.options):Object.assign({},this.options)}resolveRunContext(r){if(!this.currentConfig)throw new Error("There is no config present. Make sure to call loader.setConfig(..) or loader.fetchConfig(...)");const e=mt(r),t=mt(this.currentConfig);if(e?.applicationKey){const n=this.getAppPreset(t,e);if(!n)throw new Error(`The applicationKey ${e.applicationKey} does not exist`);e.resourceTags=e.resourceTags||n?.resourceTags,e.variables=e.variables||n?.variables}const s=this.getEnvironments(t,e),o=this.getEvaluatedVariablesAsRecord(s,e);return{config:t,options:e,environments:s,variables:o}}evaluateVariables(r,e){const t=new Map;this.defaultVariables&&this.defaultVariables.forEach(n=>{t.set(n.key,n)}),r?.forEach(n=>{n?.variables&&n.variables.forEach(i=>{t.set(i.key,i)})}),e?.variables&&e.variables.forEach(n=>{t.set(n.key,n)}),this.globalVariables&&this.globalVariables.forEach(n=>{t.set(n.key,n)});const s=Array.from(t.values()).map(n=>({...n})),o={};for(const n of s)o[n.key]=n.value||"";for(const n of s)n.value=Bt(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=Bt(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=Bt(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=zr(),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 bt=[],Wt=this.core.modelParser.unprocessedModelDescriptions.get(a.model);if(!Wt&&(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}),Wt=this.core.modelParser.unprocessedModelDescriptions.get(a.model)}const gA=F.now();let Ti={sourceColumns:[],coercionFailureSamples:{},origin:a.url};if(a.url.endsWith(".csv")||y?.includes("text/csv")){if(Wt){const q=this.csvParser.getJsonFromCSVStringWithMetadata(M,Wt,a);bt=q.data,Ti={sourceColumns:q.sourceColumns,coercionFailureSamples:q.coercionFailureSamples,origin:a.url}}}else bt=M;const mA=F.now(),vA=F.now();try{bt=this.handleTransformerLogic(bt,a,"parsedFileTransformer",n||[])}catch(q){this.log.error("Transformer error",q,{resource:a.url,model:a.model})}const bA=F.now(),Oi={placeholderUid:l,model:a.model,data:bt,type:a.options?.updateType||t.defaultDataContainerUpdateType,keyProperty:a?.options?.keyProperty,keyPropertySeparator:a?.options?.keyPropertySeparator,autoGenerateKey:a.options?.autoGenerateKey,autoGenerateProperties:a.options?.autoGenerateProperties},ns=F.getEntriesByName(f.toString());if(Array.isArray(ns)&&ns[0]){const q=ns[0],wA={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:gA,csvToJsonEnd:mA,parsedTransformStart:vA,parsedTransformEnd:bA,decodedBodySize:q.decodedBodySize,encodedBodySize:q.encodedBodySize,end:k}};this.core.analyticsController.set({value:wA,context:this.currentContext})}this.core.updateRegisteredContainer(Oi,Ti);const kA=this.progressHandler.update(a,!0,"data",d);return this.updateProgressListeners(kA),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})],os.prototype,"fetchConfig"),Ii([Qn({scope:"global",origin:"loader",type:"loader_processed",connectMessage:!0})],os.prototype,"process");const hA=os;let vt,ze;async function yA(r){return vt=new oh(r.options),ze=new hA,vt.loaders.add(ze,"default"),r.appLoaderConfig?await ze.config.fetch(r.appLoaderConfig):await ze.config.fetch(),await ze.process(r.processOptions),await vt.init(),globalThis.dcupl=vt,{dcupl:vt,loader:ze}}globalThis.initDcupl=yA})();
16
16
  //# sourceMappingURL=dcupl.bundle.min.js.map