@dcupl/bundle 2.0.0-beta.15 → 2.0.0-beta.17

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 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`
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 Gi(r){var e=new FileReader,t=is(e);return e.readAsArrayBuffer(r),t}function Bi(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 Vi(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(Gi);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var r=Zt(this);if(r)return r;if(this._bodyBlob)return Bi(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(Vi(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")(),V=J.Symbol,ds=Object.prototype,Ji=ds.hasOwnProperty,Zi=ds.toString,Le=V?V.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=V?V.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 Se(r){return typeof r=="symbol"||K(r)&&ee(r)==oa}function je(r,e){for(var t=-1,s=r==null?0:r.length,o=Array(s);++t<s;)o[t]=e(r[t],t,r);return o}var E=Array.isArray,ps=V?V.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 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(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=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 Sa(r){if(!z(r)||ka(r))return!1;var e=Yt(r)?Ea:Ca;return e.test(ye(r))}function ja(r,e){return r?.[e]}function ge(r,e){var t=ja(r,e);return Sa(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 Ga(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 Ba(r){return r!==r}function Va(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?Va(r,e,t):bs(r,Ba,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,Sl=Ye&&Ye.exports===xs,nr=Sl&&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,jl=Object.prototype,Ml=jl.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?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 js(r,e){return function(t){return r(e(t))}}var Rl=js(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)?Ss(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||Se(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__",Gl=Object.prototype,Bl=Gl.hasOwnProperty;function Vl(r){var e=this.__data__;if(et){var t=e[r];return t===Ql?void 0:t}return Bl.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=Vl,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"||Se(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=V?V.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=js(Object.getPrototypeOf,Object),yu="\\ud800-\\udfff",gu="\\u0300-\\u036f",mu="\\ufe20-\\ufe2f",vu="\\u20d0-\\u20ff",bu=gu+mu+vu,ku="\\ufe0e\\ufe0f",wu="\\u200d",Au=RegExp("["+wu+yu+bu+ku+"]");function $u(r){return Au.test(r)}function 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,Su=Qs&&Qs.exports===qs,Gs=Su?J.Buffer:void 0,Bs=Gs?Gs.allocUnsafe:void 0;function Vs(r,e){if(e)return r.slice();var t=r.length,s=Bs?Bs(t):new r.constructor(t);return r.copy(s),s}function ju(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),ju(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),Gu=ye(hr),Bu=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 Gu:return Ls;case Bu:return Ws}return e});var Vu=Object.prototype,Uu=Vu.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=V?V.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]",Sc="[object RegExp]",jc="[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]",Gc="[object Int32Array]",Bc="[object Uint8Array]",Vc="[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[Gc]=w[xc]=w[Ec]=w[oo]=w[Sc]=w[jc]=w[Mc]=w[Rc]=w[Bc]=w[Vc]=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 Vs(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 Ga(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=V?V.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]",St="[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?St:l,u=u==lo?St:u;var c=l==St,d=u==St,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,Sd=2;function jd(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|Sd)}}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)?jd(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=je(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 Gd(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 Bd=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=Bd(s+o,0)),bs(r,Re(e),o)}var Vd=Gd(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 jt(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=Se(r),i=e!==void 0,a=e===null,l=e===e,u=Se(e);if(!a&&!u&&!n&&r>e||n&&i&&l&&!a&&!u||s&&i&&l||!t&&l||!o)return 1;if(!s&&!n&&!u&&r<e||u&&t&&o&&!s&&!n||a&&t&&o||!i&&o||!l)return-1}return 0}function Hd(r,e,t){for(var s=-1,o=r.criteria,n=e.criteria,i=o.length,a=t.length;++s<i;){var l=Wd(o[s],n[s]);if(l){if(s>=a)return l;var u=t[s];return l*(u=="desc"?-1:1)}}return r.index-e.index}function Jd(r,e,t){e.length?e=je(e,function(n){return E(n)?function(i){return cr(i,n.length===1?n[0]:n)}:n}):e=[At];var s=-1;e=je(e,Ze(Re));var o=Ud(r,function(n,i,a){var l=je(e,function(u){return u(n)});return{criteria:l,index:++s,value:n}});return Ld(o,function(n,i){return Hd(n,i,t)})}function $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("|")+")",So=RegExp(kr+"(?="+kr+")|"+uf+lf,"g");function cf(r){for(var e=So.lastIndex=0;So.test(r);)++e;return e}function df(r){return $u(r)?cf(r):Zd(r)}var ff="[object Map]",pf="[object Set]";function hf(r){if(r==null)return 0;if(te(r))return jt(r)?df(r):r.length;var e=U(r);return e==ff||e==pf?r.size: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 jo=class Ki{nodes;edges;nodeKinds=new Map;nodeMeta=new Map;edgePolicy;constructor(){this.nodes=new Set,this.edges=new Map}addNode(e,t){this.nodes.has(e)||(this.nodes.add(e),this.edges.set(e,new Set)),t?.kind!==void 0&&this.nodeKinds.set(e,t.kind),t?.meta!==void 0&&this.nodeMeta.set(e,t.meta)}addDependency(e,t){if(!this.nodes.has(e)||!this.nodes.has(t))throw new Error("Both nodes must exist before adding a dependency.");if(this.edgePolicy&&!this.edgePolicy({name:e,kind:this.nodeKinds.get(e)},{name:t,kind:this.nodeKinds.get(t)}))throw new Error(`Edge policy rejected dependency from "${e}" to "${t}".`);this.edges.get(e).add(t)}setEdgePolicy(e){this.edgePolicy=e}setNodeKind(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");t===void 0?this.nodeKinds.delete(e):this.nodeKinds.set(e,t)}getNodeKind(e){return this.nodeKinds.get(e)}setNodeMeta(e,t){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodeMeta.set(e,t)}getNodeMeta(e){return this.nodeMeta.get(e)}removeNode(e){if(!this.nodes.has(e))throw new Error("Node does not exist.");this.nodes.delete(e),this.edges.delete(e);for(let t of this.edges.values())t.delete(e)}removeDependency(e,t){if(!this.edges.has(e))throw new Error("From node does not exist.");this.edges.get(e).delete(t)}hasNode(e){return this.nodes.has(e)}hasDependency(e,t){return this.edges.has(e)?this.edges.get(e).has(t):!1}getDependencies(e){if(!this.edges.has(e))throw new Error("Node does not exist.");return Array.from(this.edges.get(e))}getDependents(e){const t=[];for(let[s,o]of this.edges)o.has(e)&&t.push(s);return t}isCyclic(){const e=new Set,t=new Set,s=o=>{if(e.has(o))return!1;if(t.has(o))return!0;t.add(o);const n=this.edges.get(o);if(n){for(let i of n)if(s(i))return!0}return t.delete(o),e.add(o),!1};for(let o of this.nodes)if(s(o))return!0;return!1}validateNoCycles(){const e=new Set,t=new Set,s=[],o=n=>{if(e.has(n))return null;if(t.has(n)){const a=s.indexOf(n);return s.slice(a).concat([n])}t.add(n),s.push(n);const i=this.edges.get(n);if(i)for(let a of i){const l=o(a);if(l)return l}return s.pop(),t.delete(n),e.add(n),null};for(let n of this.nodes){const i=o(n);if(i)return{hasCycle:!0,path:i}}return{hasCycle:!1}}order(e){const t=new Set,s=new Set,o=[],n=e?.allowCycles??!1,i=a=>{if(t.has(a))return;if(s.has(a)){if(n)return;throw new Error("Graph has a cycle.")}s.add(a);const l=this.edges.get(a);if(l)for(let u of l)i(u);s.delete(a),t.add(a),o.push(a)};for(let a of this.nodes)t.has(a)||i(a);return o}clear(){this.nodes.clear(),this.edges.clear()}getNodes(){return Array.from(this.nodes)}getAllEdges(){const e=[];for(let[t,s]of this.edges)for(let o of s)e.push([t,o]);return e}getNodesWithNoDependants(){if(this.nodes.size===0)return[];const e=new Set;for(const s of this.edges.values())for(const o of s)e.add(o);const t=[];for(const s of this.nodes)e.has(s)||t.push(s);return t}getNodesByKind(e){const t=[];for(const s of this.nodes)this.nodeKinds.get(s)===e&&t.push(s);return t}getRootsByKind(e){const t=new Set(this.getNodesWithNoDependants()),s=Array.from(t);return e?s.filter(o=>this.nodeKinds.get(o)===e):s}getLeavesByKind(e){const t=[];for(const s of this.nodes){const o=this.edges.get(s);(!o||o.size===0)&&(!e||this.nodeKinds.get(s)===e)&&t.push(s)}return t}getDependenciesOfKind(e,t){return this.getDependencies(e).filter(s=>this.nodeKinds.get(s)===t)}getDependentsOfKind(e,t){return this.getDependents(e).filter(s=>this.nodeKinds.get(s)===t)}plan(e){const t=new Map;for(const i of this.nodes)t.set(i,0);for(const i of this.edges.values())for(const a of i)t.set(a,(t.get(a)||0)+1);const s=[];let o=Array.from(this.nodes).filter(i=>(t.get(i)||0)===0);const n=new Set;for(;o.length>0;){const i=o.slice();s.push(i),o=[];for(const a of i){if(n.has(a))continue;n.add(a);const l=this.edges.get(a);if(l)for(const u of l)t.set(u,(t.get(u)||0)-1),(t.get(u)||0)===0&&o.push(u)}}if(n.size!==this.nodes.size)throw new Error("Graph has a cycle.");if(e?.filterKinds&&e.filterKinds.length>0){const i=new Set(e.filterKinds);return{batches:s.map(a=>a.filter(l=>i.has(this.nodeKinds.get(l))))}}return{batches:s}}getImpactedNodes(e,t="downstream",s){const o=new Set(e),n=u=>!s||s.length===0||s.includes(this.nodeKinds.get(u)??void 0),i=()=>{const u=new Set,c=Array.from(o);for(;c.length;){const d=c.shift();for(const[f,h]of this.edges)h.has(d)&&!u.has(f)&&(u.add(f),c.push(f))}return u},a=()=>{const u=new Set,c=Array.from(o);for(;c.length;){const d=c.shift(),f=this.edges.get(d);if(f)for(const h of f)u.has(h)||(u.add(h),c.push(h))}return u};let l;return t==="both"?l=new Set([...i(),...a()]):t==="upstream"?l=a():l=i(),Array.from(l).filter(n)}toJSON(){const e=Array.from(this.nodes).map(s=>({name:s,kind:this.nodeKinds.get(s),meta:this.nodeMeta.get(s)})),t=this.getAllEdges().map(([s,o])=>({from:s,to:o}));return{nodes:e,edges:t}}static fromJSON(e){const t=new Ki;for(const s of e.nodes)t.addNode(s.name,{kind:s.kind,meta:s.meta});for(const s of e.edges)t.addDependency(s.from,s.to);return t}diff(e){const t=new Set(this.getNodes()),s=new Set(e.getNodes()),o=Array.from(s).filter(d=>!t.has(d)),n=Array.from(t).filter(d=>!s.has(d)),i=new Set(this.getAllEdges().map(d=>d.join("→"))),a=new Set(e.getAllEdges().map(d=>d.join("→"))),l=Array.from(a).filter(d=>!i.has(d)).map(d=>d.split("→")),u=Array.from(i).filter(d=>!a.has(d)).map(d=>d.split("→")),c=[];for(const d of new Set([...t,...s])){const f=this.nodeKinds.get(d),h=e.nodeKinds.get(d);f!==h&&c.push({name:d,from:f,to:h})}return{addedNodes:o,removedNodes:n,addedEdges:l,removedEdges:u,kindChanges:c}}};class vf{graph;nodeIndex;constructor(){this.graph=new jo,this.nodeIndex=new Map}getNodeId(e,t){return`${e}.${t}`}parseNodeId(e){const t=e.split(".");return{modelKey:t[0],attributeKey:t.slice(1).join(".")}}addAttribute(e){const t=this.getNodeId(e.modelKey,e.attributeKey);this.nodeIndex.has(t)||(this.graph.addNode(t,{meta:e}),this.nodeIndex.set(t,e))}addAttributeDependency(e,t){this.addAttribute(e),this.addAttribute(t);const s=this.getNodeId(e.modelKey,e.attributeKey),o=this.getNodeId(t.modelKey,t.attributeKey);this.graph.hasDependency(s,o)||this.graph.addDependency(s,o)}getImpactedAttributes(e){const t=e.map(i=>this.getNodeId(i.modelKey,i.attributeKey)),s=this.graph.getImpactedNodes(t,"downstream").map(i=>this.nodeIndex.get(i)).filter(i=>i!==void 0),o=[...e,...s],n=new Set;return o.filter(i=>{const a=this.getNodeId(i.modelKey,i.attributeKey);return n.has(a)?!1:(n.add(a),!0)})}getProcessingOrder(e){const t=new Map,s=[...e].sort((o,n)=>o.processingStep-n.processingStep);for(const o of s){const{modelKey:n,attributeKey:i,processingStep:a}=o;t.has(n)||t.set(n,new Map);const l=t.get(n);l.has(a)||l.set(a,new Set),l.get(a).add(i)}return t}getAttributesForModel(e){const t=[];for(const s of this.nodeIndex.values())s.modelKey===e&&t.push(s);return t}getDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}getDependents(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependents(t).map(s=>this.nodeIndex.get(s)).filter(s=>s!==void 0):[]}hasDependencies(e){const t=this.getNodeId(e.modelKey,e.attributeKey);return this.graph.hasNode(t)?this.graph.getDependencies(t).length>0:!1}hasNode(e){return this.nodeIndex.has(e)}getAllAttributes(){return Array.from(this.nodeIndex.values())}getMaxDepth(){let e=0;const t=(s,o=new Set)=>{if(o.has(s))return 0;o.add(s);const n=this.graph.getDependencies(s);if(n.length===0)return 1;let i=0;for(const a of n){const l=t(a,new Set(o));i=Math.max(i,l)}return i+1};for(const s of this.graph.getNodes()){const o=t(s);e=Math.max(e,o)}return e}validateCompleteness(e){const t=[];for(const[s,o]of e)for(const n of o){const i=this.getNodeId(s,n);this.hasNode(i)||t.push({modelKey:s,attributeKey:n})}return{isComplete:t.length===0,missing:t}}clear(){this.graph.clear(),this.nodeIndex.clear()}getStats(){const e=new Map,t=new Map;for(const s of this.nodeIndex.values())e.set(s.modelKey,(e.get(s.modelKey)||0)+1),t.set(s.processingStep,(t.get(s.processingStep)||0)+1);return{totalAttributes:this.nodeIndex.size,totalDependencies:this.graph.getAllEdges().length,maxDepth:this.getMaxDepth(),attributesByModel:e,attributesByStep:t}}toJSON(){return{nodes:Array.from(this.nodeIndex.values()),edges:this.graph.getAllEdges().map(([e,t])=>{const s=this.parseNodeId(e),o=this.parseNodeId(t);return{from:s,to:o}})}}}const 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 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("."),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 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 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 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=_.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: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||_}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 Gf=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/,Bf=/^-?\d+$/,Vf=/^-?\d+\.\d+$/,Uf=/^\d{1,2}([/.-])\d{1,2}\1\d{2,4}$/,Nf=r=>r==="true"||r==="false"?"boolean":Bf.test(r)?"int":Vf.test(r)?"float":Gf.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,Go=r=>Number(r)===r&&r%1!==0,Jf=r=>{switch(typeof r){case"string":return"string";case"number":return Qo(r)?"int":Go(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)):!!Vd(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(),""))):"",_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}
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)}},Bo=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 S=class{constructor(e,t,s){this.dcuplApi=e,this.cdRef=t,this.indicesController=s,this.itemService=new Bo(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})],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 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 Vo(r){return te(r)?Ss(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,Vo(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=Vs(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)}},Vo)}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 Pp(r){return r===!0||r===!1||K(r)&&ee(r)==Dp}var at=ap(function(r,e,t){No(r,e,t)});const G=(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 G("Invalid Property",r.key,"Property key is missing");if(!r.type||e.indexOf(r.type)===-1)return G("Invalid Property",r.key,"Property type is invalid");if("derive"in r){if(!r.derive?.localReference)return G("Invalid Property",r.key,"Derived Property localReference is missing");if(!r.derive.remoteProperty)return G("Invalid Property",r.key,"Derived Property remoteProperty is missing")}if("expression"in r&&typeof r.expression!="string")return G("Invalid Property",r.key,"Expression is invalid")},xp=r=>{const e=["multiValued","singleValued"];if(!r.key)return G("Invalid Reference",r.key,"Reference key is missing");if(!r.type||e.indexOf(r.type)===-1)return G("Invalid Reference",r.key,"Reference type is invalid");if(!r.model)return G("Invalid Reference",r.key,"Reference model is missing");if("derive"in r){if(!r.derive.localReference)return G("Invalid Reference",r.key,"Derived Reference localReference is missing");if(!r.derive.remoteReference)return G("Invalid Reference",r.key,"Derived Reference remoteReference is missing")}if("resolve"in r){if(!r.resolve.reference)return G("Invalid Reference",r.key,"Resolved Reference reference is missing");if(!r.resolve.model)return G("Invalid Reference",r.key,"Resolved Reference model is missing")}if("groupBy"in r&&!r.groupBy.reference)return G("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 _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 jr(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(!jt(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}}else if(n=String(t),!jt(n)&&n!=t){this.setError(this.getWrongDataTypeError(e,t,s));return}if(!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processIntProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);if(o?.forceStrictDataType){if(!Qo(t)){this.setError(this.getWrongDataTypeError(e,t,s));return}return t}const n=parseInt(t,10);if(isNaN(n)){this.setError(this.getWrongDataTypeError(e,t,s));return}if(this.isLossyNumericCoercion(t,n,!0)&&this.setError(this.getLossyCoercionError(e,t,n,s)),!(!this.handleValidators(n,e,s)&&o?.validatorHandling!=="loose"))return n}processFloatProperty(e,t,s){const o=this.attributeQualityConfigs.get(e.key);if(o?.forceStrictDataType){if(!Go(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=jr(u,c);this.setError({title:"Missing Key",type:"model",errorGroup:"DataContainerError",errorType:"MissingKey",description:`A row in model "${e.model}" has no value for the key attribute "${d}"; the row is dropped.`,attribute:d,model:e.model});continue}let a=this.data.get(String(i.key));if(!a)a={key:String(i.key)};else if(e.type==="set"){const u=e.keyProperty??this.keyProperty,c=e.keyPropertySeparator??this.keyPropertySeparator??we,d=jr(u,c),f=String(i.key);this.setError({title:"Non Unique Key",type:"model",errorGroup:"DataContainerError",errorType:"NonUniqueKey",description:`Row with key "${f}" in model "${e.model}" collides with an existing entry (key attribute "${d}"); the duplicate row is dropped`,itemKey:i.key,attribute:d,model:e.model,meta:{duplicateCount:1,droppedRows:[f]}})}for(const u of t){u.origin&&(i[u.key]=i[u.origin]);const c=this.valueMappings.find(d=>d.attributes.includes(u.key));this.isValidValueMapping(c)&&(i=this.mapRawValueUsingValueMapping(i,u.key,c)),this.processBasicProperty(u,i,a,n)}for(const u of s){const c=this.attributeQualityConfigs.get(u.key);u.origin&&(i[u.key]=i[u.origin]);const d=this.valueMappings.find(h=>h.attributes.includes(u.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,u.key,d));let f=i[u.key];if(typeof f=="number"&&(f=String(f)),!f){this.indicesController.fillInverseIndex(u.key,a.key,[void 0]),c?.required&&this.setError({title:"Undefined Value",type:"model",errorGroup:"ReferenceDataError",errorType:"UndefinedValue",description:`The required ${u.type} reference "${u.key}" in the "${this.key}" model is undefined`,itemKey:i.key,attribute:u.key,model:e.model,meta:{rawValue:f,declaredType:u.type,origin:n}});continue}if(u.type==="singleValued")(typeof f=="object"||typeof f=="string")&&!Array.isArray(f)?this.processSingleValuedReference(u,f,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}});else if(u.type==="multiValued"){const h=this.getValueAsArray(f,u?.separator);Array.isArray(h)?this.processMultiValuedReference(u,h,a):this.setError({title:"Wrong Data Type",type:"model",errorGroup:"ReferenceDataError",errorType:"WrongDataType",description:`Expect ${u.type} but got ${typeof f} with value ${f}`,itemKey:i.key,attribute:u.key,meta:{value:f}})}}const l=String(a.key);a.key=l,this.data.set(l,a)}}addQueryReferences(e){const t=this.getQueryReferences();for(let s of t){const o=JSON.stringify(s.query);for(let n of e.data){let i=this.data.get(String(n.key));const a=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=jr(u,c);this.setError({title:"Missing Key",type:"model",errorGroup:"DataContainerError",errorType:"MissingKey",description:`A row in model "${e.model}" has no value for the key attribute "${d}"; the row is dropped.`,attribute:d,model:e.model});continue}let a=this.data.get(String(i.key));a||(a={key:String(i.key)});for(const u of s){u.origin&&(i[u.key]=i[u.origin]);const c=this.valueMappings.find(d=>d.attributes.includes(u.key));this.isValidValueMapping(c)&&(i=this.mapRawValueUsingValueMapping(i,u.key,c)),this.processBasicProperty(u,i,a,n)}for(const u of o){const c=this.attributeQualityConfigs.get(u.key);u.origin&&(i[u.key]=i[u.origin]);const d=this.valueMappings.find(p=>p.attributes.includes(u.key));this.isValidValueMapping(d)&&(i=this.mapRawValueUsingValueMapping(i,u.key,d));let f=i[u.key];typeof f=="number"&&(f=String(f));const h=a[u.key];if(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 Gp(r){return"query"in r}function Mr(r){return"resolve"in r}function Bp(r){return"derive"in r}function Vp(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}
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 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]===`
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(Gp(s))this.processQueryReference(t,o,s.query);else if(Mr(s))this.processResolvedReference(t,o,s.resolve);else if(Bp(s))this.processDerivedReference(t,o,s.derive);else if(Vp(s))this.processGroupedReference(t,o,s.groupBy);else{const n={modelKey:t,attributeKey:o,type:"reference",processingStep:1};this.attributeDependencyGraph.addAttribute(n)}})})}validateAttributeDependencyGraph(){const e=new Map;this.models.forEach(s=>{const o=[];s.properties.forEach((n,i)=>{o.push(i)}),s.references.forEach((n,i)=>{o.push(i)}),o.length>0&&e.set(s.key,o)});const t=this.attributeDependencyGraph.validateCompleteness(e);if(!t.isComplete){const s=t.missing.length,o=t.missing.map(({modelKey:i,attributeKey:a})=>`${i}.${a}`).slice(0,10).join(", "),n=`Attribute dependency graph incomplete. ${s} attribute(s) missing: ${o}${s>10?` ... and ${s-10} more`:""}`;this.log.warn(`${n}
8
+ These attributes will default to Step 1 processing which may be incorrect. This usually indicates a problem during expression or reference parsing.`)}}processExpressionProperty(e,t,s){const o={modelKey:e,attributeKey:t,type:"property",processingStep:3};this.attributeDependencyGraph.addAttribute(o);const{variables:n}=_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=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 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 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,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};class Jo{constructor(e,t){this.dcuplInstance=e,this.cdRef=t}dcuplInstance;cdRef;lists=[];get(e){if(e)return this.lists.find(t=>t.key===e)}getAll(e){return e?this.lists.filter(t=>t.modelKey===e?.modelKey):this.lists}destroy(e){if(!e)this.lists.forEach(t=>t._destroy()),this.lists=[];else if(e.listKey){const t=this.lists.findIndex(s=>s.key===e.listKey);t>-1&&(this.lists[t]._destroy(),this.lists.splice(t,1))}else e.modelKey&&(this.lists=this.lists.filter(t=>t.modelKey===e.modelKey?(t._destroy(),!1):!0))}create(e){e.listKey=e.listKey||W();const t=new $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}))}getErrorSummary(){const e=new Map;for(const s of this.errors.values()){const o=this.getErrorGroupKey(s);e.set(o,(e.get(o)??0)+1)}const t=[];for(const[s,o]of this.errorCounts){const n=e.get(s)??0;t.push({key:s,model:o.model,attribute:o.attribute,errorGroup:o.errorGroup,errorType:o.errorType,type:o.type,totalCount:o.count,storedCount:n,truncated:o.count>n})}return t}stampGroupTotals(e){const t=new Map(e.map(s=>[s.key,s]));for(const s of this.errors.values()){const o=t.get(this.getErrorGroupKey(s));s.groupTotal=o?.totalCount??1,s.truncated=o?.truncated??!1}}removeError(e){const t=this.errors.get(e);if(t){const s=this.getErrorGroupKey(t),o=this.errorCounts.get(s);o&&(o.count-=1,o.count<=0&&this.errorCounts.delete(s))}this.errors.delete(e)}getError(e){return this.errors.get(e)}getErrors(){return Array.from(this.errors.values())}resetErrors(){this.errors.clear(),this.errorCounts.clear()}resetModelErrors(){this.getErrors().forEach(e=>{e.type==="model"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&this.errorCounts.delete(e)}resetValidationErrors(){this.getErrors().forEach(e=>{e.type==="model"&&e.errorType==="InvalidValidator"&&this.removeError(e.key)});for(const[e,t]of this.errorCounts)t.type==="model"&&t.errorType==="InvalidValidator"&&this.errorCounts.delete(e)}resetDataErrors(){const e=["ReferenceDataError","PropertyDataError","DataContainerError"];this.getErrors().forEach(t=>{t.type==="model"&&e.includes(t.errorGroup)&&this.removeError(t.key)});for(const[t,s]of this.errorCounts)s.type==="model"&&e.includes(s.errorGroup)&&this.errorCounts.delete(t)}cleanUpErrors(e,t){const s=this.dcupl?.getContainerSourceMetadata(t),o=t.model;if(s){const n=s.coercionFailureSamples??{};for(const i of Object.keys(n)){const a=n[i];if(!a||a.count<=0)continue;for(const u of this.getModelErrors(o))u.attribute===i&&u.itemKey!=null&&(u.errorType==="UndefinedValue"||u.errorType==="WrongDataType")&&this.removeError(u.key);const l=e.properties.get(i)?.type??a.expected;this.setError(this.buildColumnCoercionError(o,i,a.rawValue,l,a.count))}for(const[i]of e.properties){if(n[i]||s.sourceColumns.includes(i))continue;const a=this.getGroupCount(o,i,"UndefinedValue");if(a>0&&a===t.data.length){for(const l of this.getModelErrors(o))l.attribute===i&&l.itemKey!=null&&l.errorType==="UndefinedValue"&&this.removeError(l.key);this.setError(this.buildAbsentColumnError(o,i))}}}else{const n=new Set(this.getModelErrors(o).filter(l=>l.errorType==="UndefinedValue"&&l.attribute!=null).map(l=>l.attribute));for(const l of n){const u=this.getGroupCount(o,l,"UndefinedValue");if(u>0&&u===t.data.length){for(const c of this.getModelErrors(o))c.attribute===l&&c.itemKey!=null&&c.errorType==="UndefinedValue"&&this.removeError(c.key);this.setError(this.buildAbsentColumnError(o,l))}}const i=this.getModelErrors(o).filter(l=>l.errorType==="WrongDataType"&&l.errorGroup==="PropertyDataError"&&l.title==="Wrong Data Type"&&l.itemKey!=null),a=Sr(i,"attribute");for(const l in a){const u=a[l];if(!u?.length)continue;const c=u[0].meta,d=e.properties.get(l)?.type??c?.expected??"unknown";for(const f of u)this.removeError(f.key);this.setError(this.buildColumnCoercionError(o,l,String(c?.rawValue??""),d,u.length))}}}buildColumnCoercionError(e,t,s,o,n){return{title:"Wrong Data Type",type:"model",errorGroup:"DataContainerError",errorType:"WrongDataType",model:e,attribute:t,description:`${n} value(s) in column "${t}" of model "${e}" failed to coerce to the declared type "${o}" (e.g. "${s}")`,meta:{rawValue:s,declaredType:o,rowCount:n}}}buildAbsentColumnError(e,t){return{title:"Missing Data",type:"model",errorGroup:"DataContainerError",errorType:"UndefinedAttribute",model:e,attribute:t,description:`The Attribute "${t}" is not present in the dataset for model "${e}"`}}getModelErrors(e){return this.getErrors().filter(t=>t.type==="model"&&t.model===e)}cleanUpErrorsForItems(e,t,s,o){let n,i;typeof s=="string"?i=s:s instanceof Set&&(n=s,i=o);const a=this.getModelErrors(e.key),l=i?a.filter(u=>u.errorType===i):a;for(const u of l)if(u.itemKey&&t.has(u.itemKey)){if(n&&u.attribute&&!n.has(u.attribute))continue;this.removeError(u.key)}}getErrorsForItems(e,t){return this.getModelErrors(e).filter(s=>s.itemKey&&t.has(s.itemKey))}validateItemsPartial(e,t,s){if(!e)return[];const o=[],n=e.getData(),i=e.getAttributes();for(const a of i){if(!s.has(a.key))continue;const l=a.quality?.validators;if(l)for(const u of t){const c=n.get(u);if(!c)continue;const d=c[a.key],f=this.validateAttribute(d,l,a.key);for(const h of f)h.model=e.key,h.itemKey=c.key,o.push(h)}}return o}async initData(){if(!this.modelParser)return;const e=["$DcuplErrorTrackingErrors","$DcuplErrorTrackingSummary"];this.modelParser.unprocessedData=this.modelParser.unprocessedData.filter(o=>!e.includes(o.model));for(const o of e){const n=this.modelParser.models.get(o);n?.resetData(),n?.resetIndexMap()}const t=this.getErrorSummary();this.stampGroupTotals(t),this.modelParser.addData({data:this.getErrors(),model:"$DcuplErrorTrackingErrors",type:"set"}),this.modelParser.addData({data:t,model:"$DcuplErrorTrackingSummary",type:"set"});const s=this.modelParser.unprocessedData.filter(o=>e.includes(o.model));s.length>0&&await this.modelParser.handleDataContainer(s)}initErrorTrackingModels(){this.modelParser?.addModel({key:"$DcuplErrorTrackingErrors",autoGenerateKey:!0,supportsAutoCreation:!0,references:[{key:"model",type:"singleValued",model:"$DcuplErrorTrackingModel",filter:{calculateFacets:!0}},{key:"errorGroup",type:"singleValued",model:"$DcuplErrorTrackingGroup",filter:{calculateFacets:!0}},{key:"errorType",type:"singleValued",model:"$DcuplErrorTrackingType",filter:{calculateFacets:!0}}],properties:[{key:"title",type:"string",filter:!0},{key:"itemKey",type:"string",filter:!0},{key:"attribute",type:"string",filter:!0},{key:"description",type:"string"},{key:"meta",type:"json"},{key:"groupTotal",type:"int"},{key:"truncated",type:"boolean",filter:!0}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingSummary",supportsAutoCreation:!0,references:[{key:"model",type:"singleValued",model:"$DcuplErrorTrackingModel",filter:{calculateFacets:!0}},{key:"errorGroup",type:"singleValued",model:"$DcuplErrorTrackingGroup",filter:{calculateFacets:!0}},{key:"errorType",type:"singleValued",model:"$DcuplErrorTrackingType",filter:{calculateFacets:!0}}],properties:[{key:"attribute",type:"string",filter:!0},{key:"type",type:"string",filter:!0},{key:"totalCount",type:"int",filter:!0},{key:"storedCount",type:"int"},{key:"truncated",type:"boolean",filter:!0}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingType",data:[{key:"UndefinedAttribute"},{key:"InvalidValidator"},{key:"UndefinedValue"},{key:"NullValue"},{key:"WrongDataType"},{key:"MissingModel"},{key:"NonUniqueKey"},{key:"RemoteReferenceKeyNotFound"},{key:"InvalidModelDescription"},{key:"InvalidResource"},{key:"InvalidModelDefinition"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingGroup",data:[{key:"ReferenceDataError"},{key:"PropertyDataError"},{key:"DataContainerError"},{key:"ModelDescriptionError"},{key:"LoaderError"},{key:"ResourceError"},{key:"ModelDefinitionError"}],quality:{enabled:!1}}),this.modelParser?.addModel({key:"$DcuplErrorTrackingModel",supportsAutoCreation:!0,quality:{enabled:!1}})}initAnalyticsValues(){this.calculateTiming(),this.calculateSizes(),this.calculateErrorTrackingFacet(),this.calculateCounts(),this.calculateUnusedAttributes()}calculateUnusedAttributes(){this.values.unusedAttributes=[];const e=this.dcupl.models.keys();for(const t of e){const s=this.getUnusedAttributesFromModel(this.dcupl,t);for(const o of s)this.values.unusedAttributes?.push({model:t,attribute:o})}}calculateCounts(){this.values.counts={},this.values.counts.modelFiles=this.dcupl.modelParser.unprocessedModelDescriptions.size,this.values.counts.dataFiles=this.dcupl.modelParser.unprocessedData.length,this.values.counts.models=this.dcupl.models.keys().length;let e=0,t=0,s=0;this.dcupl.models.keys().forEach(o=>{const n=this.dcupl.modelParser.models.get(o);if(!n)return;const i=n?.getBasicProperties()||[],a=n?.getBasicReferences()||[],l=i.length+a.length;t+=l;const u=n.data?.size||0;e+=u,s+=l*u}),this.values.counts.rows=e,this.values.counts.attributes=t,this.values.counts.dataEntries=s}calculateTiming(){const e=this.dcupl.analyticsController.getByName("loader_processed");e&&e[0]&&(this.values.loading=e[0].value);const t=this.dcupl.analyticsController.getByName("dcupl_initialized");t&&t[0]&&(this.values.processing=t[0].value),this.values.startup=this.values.loading+this.values.processing}calculateSizes(){const e=this.calculateSizesForModels();this.values.sizes={},this.values.sizes.totalEncoded=e.reduce((t,s)=>t+s.encodedBodySize,0),this.values.sizes.totalDecoded=e.reduce((t,s)=>t+s.decodedBodySize,0),this.values.sizes.unusedDecoded=this.calculateUnusedData(),this.values.sizes.models=e.map(t=>({model:t.model,decodedBodySize:t.decodedBodySize,encodedBodySize:t.encodedBodySize})),this.values.sizes.models?.sort((t,s)=>(s.encodedBodySize||0)-(t.encodedBodySize||0))}calculateErrorTrackingFacet(){try{if(!this.enabled)return;const e=new Map;let t=0;for(const s of this.errorCounts.values())e.set(s.errorType,(e.get(s.errorType)??0)+s.count),t+=s.count;this.values.errors={size:t,UndefinedValue:e.get("UndefinedValue")??0,UndefinedAttribute:e.get("UndefinedAttribute")??0,WrongDataType:e.get("WrongDataType")??0,MissingModel:e.get("MissingModel")??0,InvalidModelDescription:e.get("InvalidModelDescription")??0,RemoteReferenceKeyNotFound:e.get("RemoteReferenceKeyNotFound")??0}}catch(e){this.log.error("Error calculating error tracking facet",e)}}calculateSizesForModels(){const e=this.dcupl.analyticsController.getByType("resource").filter(s=>s.value?.type==="data"),t=Sr(e,s=>s.value?.model);return Object.keys(t).map(s=>{const o=t[s]?.reduce((i,a)=>{const l=a.value.encodedBodySize;return i+l},0),n=t[s]?.reduce((i,a)=>{const l=a.value.decodedBodySize;return i+l},0);return{model:s,decodedBodySize:n,encodedBodySize:o}})}calculateUnusedData(){const e=this.dcupl.models.keys();let t=0;return e.forEach(s=>{const o=this.dcupl.modelParser.unprocessedData.find(a=>a.model===s)?.data||[],n=this.getUnusedAttributesFromModel(this.dcupl,s);if(!n.length)return;const i=this.getDataWithAttributes(o,n);t+=JSON.stringify(i).length}),t}getDataWithAttributes(e,t){return e.map(s=>{const o={};return t.forEach(n=>{o[n]=s[n]}),o})}getUnusedAttributesFromModel(e,t){const s=e.modelParser.models.get(t),o=s?.getBasicProperties()||[],n=s?.getBasicReferences()||[],i=s?.keyProperty,a=[...o,...n].map(u=>u.key);typeof i=="string"?a.push(i):Array.isArray(i)?a.push(...i):a.push("key"),a.push("key");const l=e.modelParser.unprocessedData.find(u=>u.model===t)?.data||[];return this.getUnusedAttributes(l,a)}getUnusedAttributes(e,t){const s=new Set;return e.forEach(o=>{Object.keys(o).forEach(n=>{t.includes(n)||s.add(n)})}),Array.from(s.values())}validateAttribute(e,t,s){const o=[];if(t.email){const n=this.validateEmail(e,s);n&&o.push(n)}if(t.endsWith){const n=this.validateEndsWith(e,t.endsWith,s);n&&o.push(n)}if(t.enum){const n=this.validateEnum(e,t.enum,s);n&&o.push(n)}if(t.includes){const n=this.validateIncludes(e,t.includes,s);n&&o.push(n)}if(t.max){const n=this.validateMax(e,t.max,s);n&&o.push(n)}if(t.maxLength){const n=this.validateMaxLength(e,t.maxLength,s);n&&o.push(n)}if(t.min){const n=this.validateMin(e,t.min,s);n&&o.push(n)}if(t.minLength){const n=this.validateMinLength(e,t.minLength,s);n&&o.push(n)}if(t.pattern){const n=this.validatePattern(e,t.pattern,s);n&&o.push(n)}if(t.startsWith){const n=this.validateStartsWith(e,t.startsWith,s);n&&o.push(n)}return o}validateAttributesAfterInitialization(e){if(!e)return[];const t=e.getAttributes(),s=e.getDataAsArray(),o=[];for(const n of t){const i=n.quality?.validators;if(i&&i.unique){const a=this.validateUnique(s,n.key,e);o.push(...a)}}return o}validateUnique(e,t,s){const o=[],n=new Set,i=s.attributeQualityConfigs?.get(t)?.validatorHandling!=="loose";for(const a of e){const l=a[t];if(n.has(l)){const u={title:"Validator Error - Unique",type:"model",errorGroup:"PropertyDataError",model:s.key,errorType:"InvalidValidator",attribute:t,itemKey:a.key,description:`The value "${l}" is not unique`};o.push(u),i&&delete a[t]}else n.add(l)}return o}validateEmail(e,t){if(e!=null&&!/^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,6}$/.test(e))return{title:"Validator Error - Invalid Email",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:t,description:`The value "${e}" is not a valid email address`}}validateMin(e,t,s){if(e<t.value)return{title:"Validator Error - Min Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is smaller than the minimum value of "${t.value}"`}}validateMax(e,t,s){if(e>t.value)return{title:"Validator Error - Max Value",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" is larger than the maximum value of "${t.value}"`}}validateStartsWith(e,t,s){if(e!=null&&!e.startsWith(t.value))return{title:"Validator Error - StartsWith",type:"model",errorGroup:"PropertyDataError",errorType:"InvalidValidator",attribute:s,description:`The value "${e}" does not start with "${t.value}"`}}validateEndsWith(e,t,s){if(e!=null&&!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,B=(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 Bo(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()};quality={errors:{summary:()=>this.qualityController.getErrorSummary()}};views={get:e=>this.modelParser.views.get(e),keys:e=>this.modelParser._getViewKeys(e),set:e=>this.modelParser.addView(e)};data={update:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"update",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},upsert:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"upsert",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},set:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"set",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},remove:(e,t)=>{this.modelParser.addData({data:e,model:t.model,type:"remove",keyProperty:t.keyProperty,keyPropertySeparator:t.keyPropertySeparator,autoGenerateKey:t.autoGenerateKey})},reset:e=>{e.model&&(this.modelParser.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())}}};B([b({scope:"global",type:"fn_pivot",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_pivot"),B([b({scope:"global",type:"fn_aggregate",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_aggregate"),B([b({scope:"global",type:"fn_suggest",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_suggest"),B([b({scope:"global",type:"fn_groupBy",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_groupBy"),B([b({scope:"global",type:"fn_facets",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_facets"),B([b({scope:"global",type:"fn_metadata",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_metadata"),B([b({scope:"global",type:"dcupl_initialized",connectMessage:!0})],Q.prototype,"init"),B([b({scope:"global",type:"dcupl_updated_manually",action:"update",connectMessage:!0})],Q.prototype,"update"),B([b({scope:"global",type:"dcupl_destroyed",connectMessage:!0})],Q.prototype,"destroy"),B([b({scope:"global",type:"query_one",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"getItem"),B([b({scope:"global",type:"query_many",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"_getManyItems"),B([b({scope:"global",type:"query_execute",cloneResult:!0,connectMessage:!0,connectMessageResult:!0})],Q.prototype,"executeQuery"),B([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 Sh(r){if(!Kt(r)||kh(r))return!1;var e=sn(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"),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 Gh=9007199254740991;function un(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Gh}function Bh(r){return r!=null&&un(r.length)&&!sn(r)}var Vh=Object.prototype;function cn(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Vh;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,Sy=Ey.hasOwnProperty;function jy(r){if(!cn(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 Bh(r)?_y(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 Gy(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 By=Object.prototype,Vy=By.hasOwnProperty;function Uy(r){var e=this.__data__;return dt?e[r]!==void 0:Vy.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=Gy,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 Ge(r){var e=this.__data__=new ne(r);this.size=e.size}Ge.prototype.clear=bg,Ge.prototype.delete=kg,Ge.prototype.get=wg,Ge.prototype.has=Ag,Ge.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,Sg=Eg.propertyIsEnumerable,$n=Object.getOwnPropertySymbols,jg=$n?function(r){return r==null?[]:(r=Object(r),_g($n(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"),Gr=$e(Y,"Promise"),Br=$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(Gr),Fg=Ae(Br),qg=Ae(Or),ie=Ke;(Qr&&ie(new Qr(new ArrayBuffer(1)))!=xn||ft&&ie(new ft)!=Cn||Gr&&ie(Gr.resolve())!=Dn||Br&&ie(new Br)!=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,Gg=Qg.hasOwnProperty;function Bg(r){var e=r.length,t=new r.constructor(e);return e&&typeof r[0]=="string"&&Gg.call(r,"index")&&(t.index=r.index,t.input=r.input),t}var En=Y.Uint8Array;function Vr(r){var e=new r.constructor(r.byteLength);return new En(e).set(new En(r)),e}function Vg(r,e){var t=Vr(r.buffer);return new r.constructor(t,r.byteOffset,r.byteLength)}var Ug=/\w*$/;function Ng(r){var e=new r.constructor(r.source,Ug.exec(r));return e.lastIndex=r.lastIndex,e}var Sn=ce?ce.prototype:void 0,jn=Sn?Sn.valueOf:void 0;function zg(r){return jn?Object(jn.call(r)):{}}function Lg(r,e){var t=Vr(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 Vr(r);case Wg:case Hg:return new s(+r);case sm:return Vg(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]",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]",Gm="[object Uint8ClampedArray]",Bm="[object Uint16Array]",Vm="[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[Sm]=A[jm]=A[Qm]=A[Gm]=A[Bm]=A[Vm]=!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=Bg(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 Ge);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 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 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 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 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 Gt=(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
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
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 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})();
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 Gn(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"?Gn(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 Gn(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 Bn=typeof global=="object"&&global&&global.Object===Object&&global,rv=typeof self=="object"&&self&&self.Object===Object&&self,X=Bn||rv||Function("return this")(),fe=X.Symbol,Vn=Object.prototype,sv=Vn.hasOwnProperty,ov=Vn.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 Be(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)&&Be(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 Ve=Array.isArray,zn=fe?fe.prototype:void 0,Ln=zn?zn.toString:void 0;function Wn(r){if(typeof r=="string")return r;if(Ve(r))return Nn(r,Wn)+"";if(Wr(r))return Ln?Ln.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Bt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}function Hn(r){return r}var fv="[object AsyncFunction]",pv="[object Function]",hv="[object GeneratorFunction]",yv="[object Proxy]";function Jn(r){if(!Bt(r))return!1;var e=Be(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(!Bt(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(!Bt(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 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 Vt=(function(){try{var r=_e(Object,"defineProperty");return r({},"",{}),r}catch{}})(),Tv=Vt?function(r,e){return Vt(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 Gv(r,e,t){return e===e?Qv(r,e,t):Fv(r,qv,t)}function Bv(r,e){var t=r==null?0:r.length;return!!t&&Gv(r,e,0)>-1}var Vv=9007199254740991,Uv=/^(?:0|[1-9]\d*)$/;function Nv(r,e){var t=typeof r;return e=e??Vv,!!e&&(t=="number"||t!="symbol"&&Uv.test(r))&&r>-1&&r%1==0&&r<e}function zv(r,e,t){e=="__proto__"&&Vt?Vt(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}function Xn(r,e){return r===e||r!==r&&e!==e}var 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)&&Be(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]",Sb="[object Uint16Array]",jb="[object Uint32Array]",P={};P[$b]=P[Cb]=P[Db]=P[Pb]=P[_b]=P[xb]=P[Eb]=P[Sb]=P[jb]=!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[Be(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&&Bn.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=Ve(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 Gb(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 Bb(r){return ri(r)?Kb(r):Gb(r)}var Vb=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ub=/^\w*$/;function Nb(r,e){if(Ve(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Wr(r)?!0:Ub.test(r)||!Vb.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 Ve(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 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 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,Gk=gi?function(r){return r==null?[]:(r=Object(r),Kk(gi(r),function(e){return Qk.call(r,e)}))}:Fk;function Bk(r,e,t){var s=e(r);return Ve(r)?s:_k(s,t(r))}function Vk(r){return Bk(r,Bb,Gk)}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=Be;(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=Be(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,Sw=Pi?Zr(Pi):Ew,_i="[object Arguments]",jw="[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]",Gw="[object Symbol]",Bw="[object WeakMap]",Vw="[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]=$[jw]=$[Vw]=$[Uw]=$[Mw]=$[Rw]=$[Nw]=$[zw]=$[Lw]=$[Ww]=$[Hw]=$[Ow]=$[Kw]=$[Ei]=$[Fw]=$[qw]=$[Qw]=$[Gw]=$[Jw]=$[Zw]=$[Yw]=$[Xw]=!0,$[Iw]=$[xi]=$[Bw]=!1;function zt(r,e,t,s,o,n){var i;if(i!==void 0)return i;if(!Bt(r))return r;var a=Ve(r);if(a)i=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),Sw(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=Vk,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 Si(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=Bv,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?Si(f,p):s(u,p))){for(i=n;--i;){var y=a[i];if(!(y?Si(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 ji=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:Gt(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=>ji(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=Gt(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=Gt(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=Gt(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)),ji(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