semanticdb-v2 2.0.0-alpha.6 → 2.0.0-alpha.7

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,4 +1,5 @@
1
- "use strict";var Ws=Object.create;var fo=Object.defineProperty;var Ks=Object.getOwnPropertyDescriptor;var Js=Object.getOwnPropertyNames;var Xs=Object.getPrototypeOf,Zs=Object.prototype.hasOwnProperty;var ea=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Js(e))!Zs.call(t,o)&&o!==r&&fo(t,o,{get:()=>e[o],enumerable:!(n=Ks(e,o))||n.enumerable});return t};var Ve=(t,e,r)=>(r=t!=null?Ws(Xs(t)):{},ea(e||!t||!t.__esModule?fo(r,"default",{value:t,enumerable:!0}):r,t));var Mr=require("node:perf_hooks"),se=require("dayjs"),Rt=require("dayjs/plugin/isoWeek.js"),Kt=require("dayjs/plugin/quarterOfYear.js"),mo=require("dayjs/plugin/customParseFormat.js"),yo=require("node:crypto"),ta=require("semanticdb-core"),pe=require("@duckdb/node-api"),ra=require("node:util");const V=t=>typeof t=="string",bt=()=>{let t,e;const r=new Promise((n,o)=>{t=n,e=o});return r.resolve=t,r.reject=e,r},ho=t=>t==null?"":""+t,na=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},oa=/###/g,go=t=>t&&t.indexOf("###")>-1?t.replace(oa,"."):t,$o=t=>!t||V(t),Ot=(t,e,r)=>{const n=V(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if($o(t))return{};const i=go(n[o]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++o}return $o(t)?{}:{obj:t,k:go(n[o])}},wo=(t,e,r)=>{const{obj:n,k:o}=Ot(t,e,Object);if(n!==void 0||e.length===1){n[o]=r;return}let i=e[e.length-1],s=e.slice(0,e.length-1),a=Ot(t,s,Object);for(;a.obj===void 0&&s.length;)i=`${s[s.length-1]}.${i}`,s=s.slice(0,s.length-1),a=Ot(t,s,Object),a?.obj&&typeof a.obj[`${a.k}.${i}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${i}`]=r},ia=(t,e,r,n)=>{const{obj:o,k:i}=Ot(t,e,Object);o[i]=o[i]||[],o[i].push(r)},Jt=(t,e)=>{const{obj:r,k:n}=Ot(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},sa=(t,e,r)=>{const n=Jt(t,r);return n!==void 0?n:Jt(e,r)},Ao=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(n in t?V(t[n])||t[n]instanceof String||V(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):Ao(t[n],e[n],r):t[n]=e[n]);return t},Ge=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var aa={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const ca=t=>V(t)?t.replace(/[&<>"'\/]/g,e=>aa[e]):t;class ua{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const r=this.regExpMap.get(e);if(r!==void 0)return r;const n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}}const da=[" ",",","?","!",";"],pa=new ua(20),la=(t,e,r)=>{e=e||"",r=r||"";const n=da.filter(s=>e.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=pa.getRegExp(`(${n.map(s=>s==="?"?"\\?":s).join("|")})`);let i=!o.test(t);if(!i){const s=t.indexOf(r);s>0&&!o.test(t.substring(0,s))&&(i=!0)}return i},xr=(t,e,r=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const n=e.split(r);let o=t;for(let i=0;i<n.length;){if(!o||typeof o!="object")return;let s,a="";for(let u=i;u<n.length;++u)if(u!==i&&(a+=r),a+=n[u],s=o[a],s!==void 0){if(["string","number","boolean"].indexOf(typeof s)>-1&&u<n.length-1)continue;i+=u-i+1;break}o=s}return o},Nt=t=>t?.replace(/_/g,"-"),fa={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class qr{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||fa,this.options=r,this.debug=r.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,r,n,o){return o&&!this.debug?null:(V(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new qr(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new qr(this.logger,e)}}var Le=new qr;class Xt{constructor(){this.observers={}}on(e,r){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const o=this.observers[n].get(r)||0;this.observers[n].set(r,o+1)}),this}off(e,r){if(this.observers[e]){if(!r){delete this.observers[e];return}this.observers[e].delete(r)}}emit(e,...r){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([o,i])=>{for(let s=0;s<i;s++)o(...r)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([o,i])=>{for(let s=0;s<i;s++)o.apply(o,[e,...r])})}}class Eo extends Xt{constructor(e,r={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const r=this.options.ns.indexOf(e);r>-1&&this.options.ns.splice(r,1)}getResource(e,r,n,o={}){const i=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,s=o.ignoreJSONStructure!==void 0?o.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.indexOf(".")>-1?a=e.split("."):(a=[e,r],n&&(Array.isArray(n)?a.push(...n):V(n)&&i?a.push(...n.split(i)):a.push(n)));const u=Jt(this.data,a);return!u&&!r&&!n&&e.indexOf(".")>-1&&(e=a[0],r=a[1],n=a.slice(2).join(".")),u||!s||!V(n)?u:xr(this.data?.[e]?.[r],n,i)}addResource(e,r,n,o,i={silent:!1}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let a=[e,r];n&&(a=a.concat(s?n.split(s):n)),e.indexOf(".")>-1&&(a=e.split("."),o=r,r=a[1]),this.addNamespaces(r),wo(this.data,a,o),i.silent||this.emit("added",e,r,n,o)}addResources(e,r,n,o={silent:!1}){for(const i in n)(V(n[i])||Array.isArray(n[i]))&&this.addResource(e,r,i,n[i],{silent:!0});o.silent||this.emit("added",e,r,n)}addResourceBundle(e,r,n,o,i,s={silent:!1,skipCopy:!1}){let a=[e,r];e.indexOf(".")>-1&&(a=e.split("."),o=n,n=r,r=a[1]),this.addNamespaces(r);let u=Jt(this.data,a)||{};s.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?Ao(u,n,i):u={...u,...n},wo(this.data,a,u),s.silent||this.emit("added",e,r,n)}removeResourceBundle(e,r){this.hasResourceBundle(e,r)&&delete this.data[e][r],this.removeNamespaces(r),this.emit("removed",e,r)}hasResourceBundle(e,r){return this.getResource(e,r)!==void 0}getResourceBundle(e,r){return r||(r=this.options.defaultNS),this.getResource(e,r)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const r=this.getDataByLanguage(e);return!!(r&&Object.keys(r)||[]).find(o=>r[o]&&Object.keys(r[o]).length>0)}toJSON(){return this.data}}var Io={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,r,n,o){return t.forEach(i=>{e=this.processors[i]?.process(e,r,n,o)??e}),e}};const _o=Symbol("i18next/PATH_KEY");function ma(){const t=[],e=Object.create(null);let r;return e.get=(n,o)=>(r?.revoke?.(),o===_o?t:(t.push(o),r=Proxy.revocable(n,e),r.proxy)),Proxy.revocable(Object.create(null),e).proxy}function it(t,e){const{[_o]:r}=t(ma()),n=e?.keySeparator??".",o=e?.nsSeparator??":";if(r.length>1&&o){const i=e?.ns,s=Array.isArray(i)?i:null;if(s&&s.length>1&&s.slice(1).includes(r[0]))return`${r[0]}${o}${r.slice(1).join(n)}`}return r.join(n)}const So={},Vr=t=>!V(t)&&typeof t!="boolean"&&typeof t!="number";class kr extends Xt{constructor(e,r={}){super(),na(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Le.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,r={interpolation:{}}){const n={...r};if(e==null)return!1;const o=this.resolve(e,n);if(o?.res===void 0)return!1;const i=Vr(o.res);return!(n.returnObjects===!1&&i)}extractFromKey(e,r){let n=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");const o=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator;let i=r.ns||this.options.defaultNS||[];const s=n&&e.indexOf(n)>-1,a=!this.options.userDefinedKeySeparator&&!r.keySeparator&&!this.options.userDefinedNsSeparator&&!r.nsSeparator&&!la(e,n,o);if(s&&!a){const u=e.match(this.interpolator.nestingRegexp);if(u&&u.length>0)return{key:e,namespaces:V(i)?[i]:i};const c=e.split(n);(n!==o||n===o&&this.options.ns.indexOf(c[0])>-1)&&(i=c.shift()),e=c.join(o)}return{key:e,namespaces:V(i)?[i]:i}}translate(e,r,n){let o=typeof r=="object"?{...r}:r;if(typeof o!="object"&&this.options.overloadTranslationOptionHandler&&(o=this.options.overloadTranslationOptionHandler(arguments)),typeof o=="object"&&(o={...o}),o||(o={}),e==null)return"";typeof e=="function"&&(e=it(e,{...this.options,...o})),Array.isArray(e)||(e=[String(e)]),e=e.map(D=>typeof D=="function"?it(D,{...this.options,...o}):String(D));const i=o.returnDetails!==void 0?o.returnDetails:this.options.returnDetails,s=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,{key:a,namespaces:u}=this.extractFromKey(e[e.length-1],o),c=u[u.length-1];let l=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;l===void 0&&(l=":");const d=o.lng||this.language,f=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(d?.toLowerCase()==="cimode")return f?i?{res:`${c}${l}${a}`,usedKey:a,exactUsedKey:a,usedLng:d,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:`${c}${l}${a}`:i?{res:a,usedKey:a,exactUsedKey:a,usedLng:d,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:a;const m=this.resolve(e,o);let y=m?.res;const g=m?.usedKey||a,h=m?.exactUsedKey||a,w=["[object Number]","[object Function]","[object RegExp]"],A=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,_=!this.i18nFormat||this.i18nFormat.handleAsObject,E=o.count!==void 0&&!V(o.count),$=kr.hasDefaultValue(o),b=E?this.pluralResolver.getSuffix(d,o.count,o):"",N=o.ordinal&&E?this.pluralResolver.getSuffix(d,o.count,{ordinal:!1}):"",k=E&&!o.ordinal&&o.count===0,j=k&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${b}`]||o[`defaultValue${N}`]||o.defaultValue;let U=y;_&&!y&&$&&(U=j);const z=Vr(U),B=Object.prototype.toString.apply(U);if(_&&U&&z&&w.indexOf(B)<0&&!(V(A)&&Array.isArray(U))){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const D=this.options.returnedObjectHandler?this.options.returnedObjectHandler(g,U,{...o,ns:u}):`key '${a} (${this.language})' returned an object instead of string.`;return i?(m.res=D,m.usedParams=this.getUsedParamsDetails(o),m):D}if(s){const D=Array.isArray(U),Q=D?[]:{},ce=D?h:g;for(const T in U)if(Object.prototype.hasOwnProperty.call(U,T)){const M=`${ce}${s}${T}`;$&&!y?Q[T]=this.translate(M,{...o,defaultValue:Vr(j)?j[T]:void 0,joinArrays:!1,ns:u}):Q[T]=this.translate(M,{...o,joinArrays:!1,ns:u}),Q[T]===M&&(Q[T]=U[T])}y=Q}}else if(_&&V(A)&&Array.isArray(y))y=y.join(A),y&&(y=this.extendTranslation(y,e,o,n));else{let D=!1,Q=!1;!this.isValidLookup(y)&&$&&(D=!0,y=j),this.isValidLookup(y)||(Q=!0,y=a);const T=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&Q?void 0:y,M=$&&j!==y&&this.options.updateMissing;if(Q||D||M){if(this.logger.log(M?"updateKey":"missingKey",d,c,a,M?j:y),s){const ie=this.resolve(a,{...o,keySeparator:!1});ie&&ie.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let J=[];const H=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&H&&H[0])for(let ie=0;ie<H.length;ie++)J.push(H[ie]);else this.options.saveMissingTo==="all"?J=this.languageUtils.toResolveHierarchy(o.lng||this.language):J.push(o.lng||this.language);const Ae=(ie,de,I)=>{const S=$&&I!==y?I:T;this.options.missingKeyHandler?this.options.missingKeyHandler(ie,c,de,S,M,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(ie,c,de,S,M,o),this.emit("missingKey",ie,c,de,y)};this.options.saveMissing&&(this.options.saveMissingPlurals&&E?J.forEach(ie=>{const de=this.pluralResolver.getSuffixes(ie,o);k&&o[`defaultValue${this.options.pluralSeparator}zero`]&&de.indexOf(`${this.options.pluralSeparator}zero`)<0&&de.push(`${this.options.pluralSeparator}zero`),de.forEach(I=>{Ae([ie],a+I,o[`defaultValue${I}`]||j)})}):Ae(J,a,j))}y=this.extendTranslation(y,e,o,m,n),Q&&y===a&&this.options.appendNamespaceToMissingKey&&(y=`${c}${l}${a}`),(Q||D)&&this.options.parseMissingKeyHandler&&(y=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${l}${a}`:a,D?y:void 0,o))}return i?(m.res=y,m.usedParams=this.getUsedParamsDetails(o),m):y}extendTranslation(e,r,n,o,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||o.usedLng,o.usedNS,o.usedKey,{resolved:o});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const u=V(e)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let c;if(u){const d=e.match(this.interpolator.nestingRegexp);c=d&&d.length}let l=n.replace&&!V(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(l={...this.options.interpolation.defaultVariables,...l}),e=this.interpolator.interpolate(e,l,n.lng||this.language||o.usedLng,n),u){const d=e.match(this.interpolator.nestingRegexp),f=d&&d.length;c<f&&(n.nest=!1)}!n.lng&&o&&o.res&&(n.lng=this.language||o.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...d)=>i?.[0]===d[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${d[0]} in key: ${r[0]}`),null):this.translate(...d,r),n)),n.interpolation&&this.interpolator.reset()}const s=n.postProcess||this.options.postProcess,a=V(s)?[s]:s;return e!=null&&a?.length&&n.applyPostProcessor!==!1&&(e=Io.handle(a,e,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...o,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,r={}){let n,o,i,s,a;return V(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(u=>typeof u=="function"?it(u,{...this.options,...r}):u)),e.forEach(u=>{if(this.isValidLookup(n))return;const c=this.extractFromKey(u,r),l=c.key;o=l;let d=c.namespaces;this.options.fallbackNS&&(d=d.concat(this.options.fallbackNS));const f=r.count!==void 0&&!V(r.count),m=f&&!r.ordinal&&r.count===0,y=r.context!==void 0&&(V(r.context)||typeof r.context=="number")&&r.context!=="",g=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);d.forEach(h=>{this.isValidLookup(n)||(a=h,!So[`${g[0]}-${h}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(So[`${g[0]}-${h}`]=!0,this.logger.warn(`key "${o}" for languages "${g.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),g.forEach(w=>{if(this.isValidLookup(n))return;s=w;const A=[l];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(A,l,w,h,r);else{let E;f&&(E=this.pluralResolver.getSuffix(w,r.count,r));const $=`${this.options.pluralSeparator}zero`,b=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(r.ordinal&&E.indexOf(b)===0&&A.push(l+E.replace(b,this.options.pluralSeparator)),A.push(l+E),m&&A.push(l+$)),y){const N=`${l}${this.options.contextSeparator||"_"}${r.context}`;A.push(N),f&&(r.ordinal&&E.indexOf(b)===0&&A.push(N+E.replace(b,this.options.pluralSeparator)),A.push(N+E),m&&A.push(N+$))}}let _;for(;_=A.pop();)this.isValidLookup(n)||(i=_,n=this.getResource(w,h,_,r))}))})}),{res:n,usedKey:o,exactUsedKey:i,usedLng:s,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,r,n,o={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,r,n,o):this.resourceStore.getResource(e,r,n,o)}getUsedParamsDetails(e={}){const r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!V(e.replace);let o=n?e.replace:e;if(n&&typeof e.count<"u"&&(o.count=e.count),this.options.interpolation.defaultVariables&&(o={...this.options.interpolation.defaultVariables,...o}),!n){o={...o};for(const i of r)delete o[i]}return o}static hasDefaultValue(e){const r="defaultValue";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&r===n.substring(0,r.length)&&e[n]!==void 0)return!0;return!1}}class Ro{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Le.create("languageUtils")}getScriptPartFromCode(e){if(e=Nt(e),!e||e.indexOf("-")<0)return null;const r=e.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}getLanguagePartFromCode(e){if(e=Nt(e),!e||e.indexOf("-")<0)return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(V(e)&&e.indexOf("-")>-1){let r;try{r=Intl.getCanonicalLocales(e)[0]}catch{}return r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let r;return e.forEach(n=>{if(r)return;const o=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(o))&&(r=o)}),!r&&this.options.supportedLngs&&e.forEach(n=>{if(r)return;const o=this.getScriptPartFromCode(n);if(this.isSupportedCode(o))return r=o;const i=this.getLanguagePartFromCode(n);if(this.isSupportedCode(i))return r=i;r=this.options.supportedLngs.find(s=>{if(s===i)return s;if(!(s.indexOf("-")<0&&i.indexOf("-")<0)&&(s.indexOf("-")>0&&i.indexOf("-")<0&&s.substring(0,s.indexOf("-"))===i||s.indexOf(i)===0&&i.length>1))return s})}),r||(r=this.getFallbackCodes(this.options.fallbackLng)[0]),r}getFallbackCodes(e,r){if(!e)return[];if(typeof e=="function"&&(e=e(r)),V(e)&&(e=[e]),Array.isArray(e))return e;if(!r)return e.default||[];let n=e[r];return n||(n=e[this.getScriptPartFromCode(r)]),n||(n=e[this.formatLanguageCode(r)]),n||(n=e[this.getLanguagePartFromCode(r)]),n||(n=e.default),n||[]}toResolveHierarchy(e,r){const n=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],e),o=[],i=s=>{s&&(this.isSupportedCode(s)?o.push(s):this.logger.warn(`rejecting language code not found in supportedLngs: ${s}`))};return V(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&i(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&i(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&i(this.getLanguagePartFromCode(e))):V(e)&&i(this.formatLanguageCode(e)),n.forEach(s=>{o.indexOf(s)<0&&i(this.formatLanguageCode(s))}),o}}const bo={zero:0,one:1,two:2,few:3,many:4,other:5},Oo={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class ya{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=Le.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=Nt(e==="dev"?"en":e),o=r.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:n,type:o});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let s;try{s=new Intl.PluralRules(n,{type:o})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Oo;if(!e.match(/-|_/))return Oo;const u=this.languageUtils.getLanguagePartFromCode(e);s=this.getRule(u,r)}return this.pluralRulesCache[i]=s,s}needsPlural(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,r,n={}){return this.getSuffixes(e,n).map(o=>`${r}${o}`)}getSuffixes(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?n.resolvedOptions().pluralCategories.sort((o,i)=>bo[o]-bo[i]).map(o=>`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${o}`):[]}getSuffix(e,r,n={}){const o=this.getRule(e,n);return o?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${o.select(r)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",r,n))}}const No=(t,e,r,n=".",o=!0)=>{let i=sa(t,e,r);return!i&&o&&V(r)&&(i=xr(t,r,n),i===void 0&&(i=xr(e,r,n))),i},vr=t=>t.replace(/\$/g,"$$$$");class Po{constructor(e={}){this.logger=Le.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(r=>r),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:r,escapeValue:n,useRawValueToEscape:o,prefix:i,prefixEscaped:s,suffix:a,suffixEscaped:u,formatSeparator:c,unescapeSuffix:l,unescapePrefix:d,nestingPrefix:f,nestingPrefixEscaped:m,nestingSuffix:y,nestingSuffixEscaped:g,nestingOptionsSeparator:h,maxReplaces:w,alwaysFormat:A}=e.interpolation;this.escape=r!==void 0?r:ca,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=i?Ge(i):s||"{{",this.suffix=a?Ge(a):u||"}}",this.formatSeparator=c||",",this.unescapePrefix=l?"":d||"-",this.unescapeSuffix=this.unescapePrefix?"":l||"",this.nestingPrefix=f?Ge(f):m||Ge("$t("),this.nestingSuffix=y?Ge(y):g||Ge(")"),this.nestingOptionsSeparator=h||",",this.maxReplaces=w||1e3,this.alwaysFormat=A!==void 0?A:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(r,n)=>r?.source===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,r,n,o){let i,s,a;const u=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=m=>{if(m.indexOf(this.formatSeparator)<0){const w=No(r,u,m,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(w,void 0,n,{...o,...r,interpolationkey:m}):w}const y=m.split(this.formatSeparator),g=y.shift().trim(),h=y.join(this.formatSeparator).trim();return this.format(No(r,u,g,this.options.keySeparator,this.options.ignoreJSONStructure),h,n,{...o,...r,interpolationkey:g})};this.resetRegExp();const l=o?.missingInterpolationHandler||this.options.missingInterpolationHandler,d=o?.interpolation?.skipOnVariables!==void 0?o.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:m=>vr(m)},{regex:this.regexp,safeValue:m=>this.escapeValue?vr(this.escape(m)):vr(m)}].forEach(m=>{for(a=0;i=m.regex.exec(e);){const y=i[1].trim();if(s=c(y),s===void 0)if(typeof l=="function"){const h=l(e,i,o);s=V(h)?h:""}else if(o&&Object.prototype.hasOwnProperty.call(o,y))s="";else if(d){s=i[0];continue}else this.logger.warn(`missed to pass in variable ${y} for interpolating ${e}`),s="";else!V(s)&&!this.useRawValueToEscape&&(s=ho(s));const g=m.safeValue(s);if(e=e.replace(i[0],g),d?(m.regex.lastIndex+=s.length,m.regex.lastIndex-=i[0].length):m.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,r,n={}){let o,i,s;const a=(u,c)=>{const l=this.nestingOptionsSeparator;if(u.indexOf(l)<0)return u;const d=u.split(new RegExp(`${Ge(l)}[ ]*{`));let f=`{${d[1]}`;u=d[0],f=this.interpolate(f,s);const m=f.match(/'/g),y=f.match(/"/g);((m?.length??0)%2===0&&!y||(y?.length??0)%2!==0)&&(f=f.replace(/'/g,'"'));try{s=JSON.parse(f),c&&(s={...c,...s})}catch(g){return this.logger.warn(`failed parsing options string in nesting for key ${u}`,g),`${u}${l}${f}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,u};for(;o=this.nestingRegexp.exec(e);){let u=[];s={...n},s=s.replace&&!V(s.replace)?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;const c=/{.*}/.test(o[1])?o[1].lastIndexOf("}")+1:o[1].indexOf(this.formatSeparator);if(c!==-1&&(u=o[1].slice(c).split(this.formatSeparator).map(l=>l.trim()).filter(Boolean),o[1]=o[1].slice(0,c)),i=r(a.call(this,o[1].trim(),s),s),i&&o[0]===e&&!V(i))return i;V(i)||(i=ho(i)),i||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${e}`),i=""),u.length&&(i=u.reduce((l,d)=>this.format(l,d,n.lng,{...n,interpolationkey:o[1].trim()}),i.trim())),e=e.replace(o[0],i),this.regexp.lastIndex=0}return e}}const ha=t=>{let e=t.toLowerCase().trim();const r={};if(t.indexOf("(")>-1){const n=t.split("(");e=n[0].toLowerCase().trim();const o=n[1].substring(0,n[1].length-1);e==="currency"&&o.indexOf(":")<0?r.currency||(r.currency=o.trim()):e==="relativetime"&&o.indexOf(":")<0?r.range||(r.range=o.trim()):o.split(";").forEach(s=>{if(s){const[a,...u]=s.split(":"),c=u.join(":").trim().replace(/^'+|'+$/g,""),l=a.trim();r[l]||(r[l]=c),c==="false"&&(r[l]=!1),c==="true"&&(r[l]=!0),isNaN(c)||(r[l]=parseInt(c,10))}})}return{formatName:e,formatOptions:r}},To=t=>{const e={};return(r,n,o)=>{let i=o;o&&o.interpolationkey&&o.formatParams&&o.formatParams[o.interpolationkey]&&o[o.interpolationkey]&&(i={...i,[o.interpolationkey]:void 0});const s=n+JSON.stringify(i);let a=e[s];return a||(a=t(Nt(n),o),e[s]=a),a(r)}},ga=t=>(e,r,n)=>t(Nt(r),n)(e);class $a{constructor(e={}){this.logger=Le.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?To:ga;this.formats={number:n((o,i)=>{const s=new Intl.NumberFormat(o,{...i});return a=>s.format(a)}),currency:n((o,i)=>{const s=new Intl.NumberFormat(o,{...i,style:"currency"});return a=>s.format(a)}),datetime:n((o,i)=>{const s=new Intl.DateTimeFormat(o,{...i});return a=>s.format(a)}),relativetime:n((o,i)=>{const s=new Intl.RelativeTimeFormat(o,{...i});return a=>s.format(a,i.range||"day")}),list:n((o,i)=>{const s=new Intl.ListFormat(o,{...i});return a=>s.format(a)})}}add(e,r){this.formats[e.toLowerCase().trim()]=r}addCached(e,r){this.formats[e.toLowerCase().trim()]=To(r)}format(e,r,n,o={}){const i=r.split(this.formatSeparator);if(i.length>1&&i[0].indexOf("(")>1&&i[0].indexOf(")")<0&&i.find(a=>a.indexOf(")")>-1)){const a=i.findIndex(u=>u.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,a)].join(this.formatSeparator)}return i.reduce((a,u)=>{const{formatName:c,formatOptions:l}=ha(u);if(this.formats[c]){let d=a;try{const f=o?.formatParams?.[o.interpolationkey]||{},m=f.locale||f.lng||o.locale||o.lng||n;d=this.formats[c](a,m,{...l,...o,...f})}catch(f){this.logger.warn(f)}return d}else this.logger.warn(`there was no format function for ${c}`);return a},e)}}const wa=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Aa extends Xt{constructor(e,r,n,o={}){super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=Le.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=o.maxParallelReads||10,this.readingCalls=0,this.maxRetries=o.maxRetries>=0?o.maxRetries:5,this.retryTimeout=o.retryTimeout>=1?o.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,o.backend,o)}queueLoad(e,r,n,o){const i={},s={},a={},u={};return e.forEach(c=>{let l=!0;r.forEach(d=>{const f=`${c}|${d}`;!n.reload&&this.store.hasResourceBundle(c,d)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?s[f]===void 0&&(s[f]=!0):(this.state[f]=1,l=!1,s[f]===void 0&&(s[f]=!0),i[f]===void 0&&(i[f]=!0),u[d]===void 0&&(u[d]=!0)))}),l||(a[c]=!0)}),(Object.keys(i).length||Object.keys(s).length)&&this.queue.push({pending:s,pendingCount:Object.keys(s).length,loaded:{},errors:[],callback:o}),{toLoad:Object.keys(i),pending:Object.keys(s),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(u)}}loaded(e,r,n){const o=e.split("|"),i=o[0],s=o[1];r&&this.emit("failedLoading",i,s,r),!r&&n&&this.store.addResourceBundle(i,s,n,void 0,void 0,{skipCopy:!0}),this.state[e]=r?-1:2,r&&n&&(this.state[e]=0);const a={};this.queue.forEach(u=>{ia(u.loaded,[i],s),wa(u,e),r&&u.errors.push(r),u.pendingCount===0&&!u.done&&(Object.keys(u.loaded).forEach(c=>{a[c]||(a[c]={});const l=u.loaded[c];l.length&&l.forEach(d=>{a[c][d]===void 0&&(a[c][d]=!0)})}),u.done=!0,u.errors.length?u.callback(u.errors):u.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(u=>!u.done)}read(e,r,n,o=0,i=this.retryTimeout,s){if(!e.length)return s(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:r,fcName:n,tried:o,wait:i,callback:s});return}this.readingCalls++;const a=(c,l)=>{if(this.readingCalls--,this.waitingReads.length>0){const d=this.waitingReads.shift();this.read(d.lng,d.ns,d.fcName,d.tried,d.wait,d.callback)}if(c&&l&&o<this.maxRetries){setTimeout(()=>{this.read.call(this,e,r,n,o+1,i*2,s)},i);return}s(c,l)},u=this.backend[n].bind(this.backend);if(u.length===2){try{const c=u(e,r);c&&typeof c.then=="function"?c.then(l=>a(null,l)).catch(a):a(null,c)}catch(c){a(c)}return}return u(e,r,a)}prepareLoading(e,r,n={},o){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),o&&o();V(e)&&(e=this.languageUtils.toResolveHierarchy(e)),V(r)&&(r=[r]);const i=this.queueLoad(e,r,n,o);if(!i.toLoad.length)return i.pending.length||o(),null;i.toLoad.forEach(s=>{this.loadOne(s)})}load(e,r,n){this.prepareLoading(e,r,{},n)}reload(e,r,n){this.prepareLoading(e,r,{reload:!0},n)}loadOne(e,r=""){const n=e.split("|"),o=n[0],i=n[1];this.read(o,i,"read",void 0,void 0,(s,a)=>{s&&this.logger.warn(`${r}loading namespace ${i} for language ${o} failed`,s),!s&&a&&this.logger.log(`${r}loaded namespace ${i} for language ${o}`,a),this.loaded(e,s,a)})}saveMissing(e,r,n,o,i,s={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(r)){this.logger.warn(`did not save key "${n}" as the namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if(this.backend?.create){const u={...s,isUpdate:i},c=this.backend.create.bind(this.backend);if(c.length<6)try{let l;c.length===5?l=c(e,r,n,o,u):l=c(e,r,n,o),l&&typeof l.then=="function"?l.then(d=>a(null,d)).catch(a):a(null,l)}catch(l){a(l)}else c(e,r,n,o,a,u)}!e||!e[0]||this.store.addResource(e[0],r,n,o)}}}const Yr=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),V(t[1])&&(e.defaultValue=t[1]),V(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const r=t[3]||t[2];Object.keys(r).forEach(n=>{e[n]=r[n]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),Lo=t=>(V(t.ns)&&(t.ns=[t.ns]),V(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),V(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs?.indexOf?.("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),typeof t.initImmediate=="boolean"&&(t.initAsync=t.initImmediate),t),Zt=()=>{},Ea=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})},Do="__i18next_supportNoticeShown",Ia=()=>!!(typeof globalThis<"u"&&globalThis[Do]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),_a=()=>{typeof globalThis<"u"&&(globalThis[Do]=!0)},Sa=t=>!!(t?.modules?.backend?.name?.indexOf("Locize")>0||t?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||t?.options?.backend?.backends&&t.options.backend.backends.some(e=>e?.name?.indexOf("Locize")>0||e?.constructor?.name?.indexOf("Locize")>0)||t?.options?.backend?.projectId||t?.options?.backend?.backendOptions&&t.options.backend.backendOptions.some(e=>e?.projectId));class Gt extends Xt{constructor(e={},r){if(super(),this.options=Lo(e),this.services={},this.logger=Le,this.modules={external:[]},Ea(this),r&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,r),this;setTimeout(()=>{this.init(e,r)},0)}}init(e={},r){this.isInitializing=!0,typeof e=="function"&&(r=e,e={}),e.defaultNS==null&&e.ns&&(V(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const n=Yr();this.options={...n,...this.options,...Lo(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!Sa(this)&&!Ia()&&(typeof console<"u"&&typeof console.info<"u"&&console.info("\u{1F310} i18next is made possible by our own product, Locize \u2014 consider powering your project with managed localization (AI, CDN, integrations): https://locize.com \u{1F499}"),_a());const o=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?Le.init(o(this.modules.logger),this.options):Le.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=$a;const l=new Ro(this.options);this.store=new Eo(this.options.resources,this.options);const d=this.services;d.logger=Le,d.resourceStore=this.store,d.languageUtils=l,d.pluralResolver=new ya(l,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),c&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(d.formatter=o(c),d.formatter.init&&d.formatter.init(d,this.options),this.options.interpolation.format=d.formatter.format.bind(d.formatter)),d.interpolator=new Po(this.options),d.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},d.backendConnector=new Aa(o(this.modules.backend),d.resourceStore,d,this.options),d.backendConnector.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.languageDetector&&(d.languageDetector=o(this.modules.languageDetector),d.languageDetector.init&&d.languageDetector.init(d,this.options.detection,this.options)),this.modules.i18nFormat&&(d.i18nFormat=o(this.modules.i18nFormat),d.i18nFormat.init&&d.i18nFormat.init(this)),this.translator=new kr(this.services,this.options),this.translator.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.external.forEach(m=>{m.init&&m.init(this)})}if(this.format=this.options.interpolation.format,r||(r=Zt),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...l)=>this.store[c](...l)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...l)=>(this.store[c](...l),this)});const a=bt(),u=()=>{const c=(l,d)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(d),r(l,d)};if(this.languages&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?u():setTimeout(u,0),a}loadResources(e,r=Zt){let n=r;const o=V(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(o?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const i=[],s=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(c=>{c!=="cimode"&&i.indexOf(c)<0&&i.push(c)})};o?s(o):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>s(u)),this.options.preload?.forEach?.(a=>s(a)),this.services.backendConnector.load(i,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(a)})}else n(null)}reloadResources(e,r,n){const o=bt();return typeof e=="function"&&(n=e,e=void 0),typeof r=="function"&&(n=r,r=void 0),e||(e=this.languages),r||(r=this.options.ns),n||(n=Zt),this.services.backendConnector.reload(e,r,i=>{o.resolve(),n(i)}),o}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&Io.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-1)){for(let r=0;r<this.languages.length;r++){const n=this.languages[r];if(!(["cimode","dev"].indexOf(n)>-1)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,r){this.isLanguageChangingTo=e;const n=bt();this.emit("languageChanging",e);const o=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},i=(a,u)=>{u?this.isLanguageChangingTo===e&&(o(u),this.translator.changeLanguage(u),this.isLanguageChangingTo=void 0,this.emit("languageChanged",u),this.logger.log("languageChanged",u)):this.isLanguageChangingTo=void 0,n.resolve((...c)=>this.t(...c)),r&&r(a,(...c)=>this.t(...c))},s=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const u=V(a)?a:a&&a[0],c=this.store.hasLanguageSomeTranslations(u)?u:this.services.languageUtils.getBestMatchFromCodes(V(a)?[a]:a);c&&(this.language||o(c),this.translator.language||this.translator.changeLanguage(c),this.services.languageDetector?.cacheUserLanguage?.(c)),this.loadResources(c,l=>{i(l,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?s(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(s):this.services.languageDetector.detect(s):s(e),n}getFixedT(e,r,n){const o=(i,s,...a)=>{let u;typeof s!="object"?u=this.options.overloadTranslationOptionHandler([i,s].concat(a)):u={...s},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs,u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||n||o.keyPrefix);const c={...this.options,...u};typeof u.keyPrefix=="function"&&(u.keyPrefix=it(u.keyPrefix,c));const l=this.options.keySeparator||".";let d;return u.keyPrefix&&Array.isArray(i)?d=i.map(f=>(typeof f=="function"&&(f=it(f,c)),`${u.keyPrefix}${l}${f}`)):(typeof i=="function"&&(i=it(i,c)),d=u.keyPrefix?`${u.keyPrefix}${l}${i}`:i),this.t(d,u)};return V(e)?o.lng=e:o.lngs=e,o.ns=r,o.keyPrefix=n,o}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,r={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=r.lng||this.resolvedLanguage||this.languages[0],o=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const s=(a,u)=>{const c=this.services.backendConnector.state[`${a}|${u}`];return c===-1||c===0||c===2};if(r.precheck){const a=r.precheck(this,s);if(a!==void 0)return a}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||s(n,e)&&(!o||s(i,e)))}loadNamespaces(e,r){const n=bt();return this.options.ns?(V(e)&&(e=[e]),e.forEach(o=>{this.options.ns.indexOf(o)<0&&this.options.ns.push(o)}),this.loadResources(o=>{n.resolve(),r&&r(o)}),n):(r&&r(),Promise.resolve())}loadLanguages(e,r){const n=bt();V(e)&&(e=[e]);const o=this.options.preload||[],i=e.filter(s=>o.indexOf(s)<0&&this.services.languageUtils.isSupportedCode(s));return i.length?(this.options.preload=o.concat(i),this.loadResources(s=>{n.resolve(),r&&r(s)}),n):(r&&r(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const o=new Intl.Locale(e);if(o&&o.getTextInfo){const i=o.getTextInfo();if(i&&i.direction)return i.direction}}catch{}const r=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=this.services?.languageUtils||new Ro(Yr());return e.toLowerCase().indexOf("-latn")>1?"ltr":r.indexOf(n.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},r){const n=new Gt(e,r);return n.createInstance=Gt.createInstance,n}cloneInstance(e={},r=Zt){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const o={...this.options,...e,isClone:!0},i=new Gt(o);if((e.debug!==void 0||e.prefix!==void 0)&&(i.logger=i.logger.clone(e)),["store","services","language"].forEach(a=>{i[a]=this[a]}),i.services={...this.services},i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},n){const a=Object.keys(this.store.data).reduce((u,c)=>(u[c]={...this.store.data[c]},u[c]=Object.keys(u[c]).reduce((l,d)=>(l[d]={...u[c][d]},l),u[c]),u),{});i.store=new Eo(a,o),i.services.resourceStore=i.store}if(e.interpolation){const u={...Yr().interpolation,...this.options.interpolation,...e.interpolation},c={...o,interpolation:u};i.services.interpolator=new Po(c)}return i.translator=new kr(i.services,o),i.translator.on("*",(a,...u)=>{i.emit(a,...u)}),i.init(o,r),i.translator.options=o,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Ee=Gt.createInstance(),Ra=Ee.createInstance;Ee.dir,Ee.init,Ee.loadResources,Ee.reloadResources,Ee.use,Ee.changeLanguage,Ee.getFixedT,Ee.t,Ee.exists,Ee.setDefaultNamespace,Ee.hasLoadedNamespace,Ee.loadNamespaces,Ee.loadLanguages;const Co={locale:"en-US",messages:{"operator.rows":"rows","operator.$sum":"Total {operandName}","operator.$avg":"Average {operandName}","operator.$min":"Minimum {operandName}","operator.$max":"Maximum {operandName}","operator.$count":"{operandName} count","operator.$count.rows":"Row count","operator.$countDistinct":"Distinct {operandName} count","operator.$add":"{inputNames}","operator.$add.empty":"Sum of {operandName}","operator.$subtract":"{input0} minus {input1}","operator.$subtract.fallback":"{operandName} difference","operator.$multiply":"{inputNames}","operator.$multiply.empty":"Product of {operandName}","operator.$divide":"{input0} divided by {input1}","operator.$divide.fallback":"{operandName} ratio","operator.$concat":"Combined {inputNames}","operator.$concat.empty":"Combined {operandName}","operator.$abs":"Absolute {operandName}","operator.$substring":"{operandName} substring","operator.$case":"{operandName} category","operator.$constant":"Constant","operator.$sql":"Calculated value","operator.$rowNumber":"Row number","operator.$rank":"{operandName} rank","operator.$accumulate":"Cumulative {operandName}","operator.$least":"Least of {inputNames}","operator.$greatest":"Greatest of {inputNames}","operator.$dateBucket":"{operandName} by {granularity}","operator.$periodBoundary.start":"{operandName} at period start","operator.$periodBoundary.end":"{operandName} at period end","operator.$periodValue.start":"{operandName} at period start","operator.$periodValue.end":"{operandName} at period end","operator.$periodShift":"{operandName} {comparison} baseline","operator.$periodGrowth":"{operandName} {comparison} growth","operator.$periodDifference":"{operandName} {comparison} difference","operator.$averagePerPeriod":"Average {operandName} per {granularity}","operator.$newly":"New {operandName}","operator.$shareOfTotal":"{operandName} share of total","component.numerator":"{outputName} numerator","component.denominator":"{outputName} denominator","component.current":"{outputName} current","component.previous":"{outputName} previous","component.start":"{outputName} start","component.end":"{outputName} end","period.comparison":"period-over-period","period.current":"current-period","period.yearOverYear":"year-over-year","period.monthOverMonth":"month-over-month","period.weekOverWeek":"week-over-week","time.granularity.second":"second","time.granularity.minute":"minute","time.granularity.hour":"hour","time.granularity.day":"day","time.granularity.week":"week","time.granularity.month":"month","time.granularity.quarter":"quarter","time.granularity.year":"year","time.granularity.period":"period","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal requires a property","sql.timeWatermark":"Resolve time watermark to keep year-over-year and period-over-period comparison ranges consistent","sql.entityExpansion":"Expand entities to obtain more information","sql.computation":"Numeric computation","sql.total":"Count result rows before pagination","sql.semanticResolution":"Semantic resolution"}},qo={locale:"zh-CN",messages:{"operator.rows":"\u6570\u636E\u884C","operator.$sum":"\u603B{operandName}","operator.$avg":"\u5E73\u5747{operandName}","operator.$min":"{operandName}\u6700\u5C0F\u503C","operator.$max":"{operandName}\u6700\u5927\u503C","operator.$count":"{operandName}\u6570\u91CF","operator.$count.rows":"\u884C\u6570","operator.$countDistinct":"{operandName}\u53BB\u91CD\u8BA1\u6570","operator.$add":"{inputNames}","operator.$add.empty":"{operandName}\u6C42\u548C","operator.$subtract":"{input0}\u51CF\u53BB{input1}","operator.$subtract.fallback":"{operandName}\u5DEE\u503C","operator.$multiply":"{inputNames}","operator.$multiply.empty":"{operandName}\u4E58\u79EF","operator.$divide":"{input0}\u9664\u4EE5{input1}","operator.$divide.fallback":"{operandName}\u6BD4\u503C","operator.$concat":"{inputNames}\u62FC\u63A5\u503C","operator.$concat.empty":"{operandName}\u62FC\u63A5\u503C","operator.$abs":"{operandName}\u7EDD\u5BF9\u503C","operator.$substring":"{operandName}\u5B50\u4E32","operator.$case":"{operandName}\u5206\u7C7B","operator.$constant":"\u5E38\u91CF","operator.$sql":"\u8BA1\u7B97\u503C","operator.$rowNumber":"\u884C\u53F7","operator.$rank":"{operandName}\u6392\u540D","operator.$accumulate":"{operandName}\u7D2F\u8BA1\u503C","operator.$least":"{inputNames}\u4E2D\u7684\u6700\u65E9\u503C","operator.$greatest":"{inputNames}\u4E2D\u7684\u6700\u665A\u503C","operator.$dateBucket":"{operandName}\uFF08\u6309{granularity}\uFF09","operator.$periodBoundary.start":"{operandName}\u671F\u521D","operator.$periodBoundary.end":"{operandName}\u671F\u672B","operator.$periodValue.start":"{operandName}\u671F\u521D\u503C","operator.$periodValue.end":"{operandName}\u671F\u672B\u503C","operator.$periodShift":"{operandName}{comparison}\u57FA\u671F\u503C","operator.$periodGrowth":"{operandName}{comparison}\u589E\u957F\u7387","operator.$periodDifference":"{operandName}{comparison}\u5DEE\u503C","operator.$averagePerPeriod":"{operandName}{granularity}\u5747\u503C","operator.$newly":"\u65B0\u589E{operandName}","operator.$shareOfTotal":"{operandName}\u5360\u6BD4","component.numerator":"{outputName}\u5206\u5B50","component.denominator":"{outputName}\u5206\u6BCD","component.current":"{outputName}\u672C\u671F","component.previous":"{outputName}\u4E0A\u671F","component.start":"{outputName}\u5F00\u59CB","component.end":"{outputName}\u7ED3\u675F","period.comparison":"\u540C\u671F","period.current":"\u672C\u671F","period.yearOverYear":"\u540C\u6BD4","period.monthOverMonth":"\u73AF\u6BD4","period.weekOverWeek":"\u5468\u73AF\u6BD4","time.granularity.second":"\u79D2","time.granularity.minute":"\u5206\u949F","time.granularity.hour":"\u5C0F\u65F6","time.granularity.day":"\u65E5","time.granularity.week":"\u5468","time.granularity.month":"\u6708","time.granularity.quarter":"\u5B63\u5EA6","time.granularity.year":"\u5E74","time.granularity.period":"\u5468\u671F","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal\u9700\u8981pred\u53C2\u6570","sql.timeWatermark":"\u8BA1\u7B97\u6570\u636E\u6700\u540E\u65F6\u95F4\uFF0C\u4ECE\u800C\u4FDD\u8BC1\u540C\u6BD4\u3001\u73AF\u6BD4\u7684\u6BD4\u8F83\u533A\u95F4\u4E00\u81F4","sql.entityExpansion":"\u5B9E\u4F53\u5C55\u5F00\uFF0C\u7528\u4E8E\u83B7\u5F97\u66F4\u591A\u4FE1\u606F","sql.computation":"\u6570\u503C\u8BA1\u7B97","sql.total":"\u8BA1\u7B97\u5206\u9875\u524D\u7684\u7ED3\u679C\u603B\u6570","sql.semanticResolution":"\u8BED\u4E49\u89E3\u6790"}},ba=[qo,Co],Pt=t=>t.trim().toLowerCase(),Oa=t=>t?"locale"in t?[t]:t:[],Na=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=t;return typeof e.locale=="string"&&e.locale.trim().length>0&&typeof e.messages=="object"&&e.messages!==null&&!Array.isArray(e.messages)};class Fr{definitions=new Map;i18n;constructor(e){this.i18n=Ra(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(ba),this.register(e)}register(e){for(const r of Oa(e)){const n=r;if(!Na(n))throw new TypeError("Locale definition must have a non-empty locale");const o=n,i=this.definitions.get(Pt(o.locale)),s={locale:o.locale,messages:Object.freeze({...i?.messages,...o.messages})};this.definitions.set(Pt(o.locale),s),this.i18n.addResourceBundle(o.locale,"translation",s.messages,!0,!0)}return this}resolve(e="zh-CN"){const r=this.definitions.get(Pt(e));if(r)return r;const n=Pt(e).split("-")[0];return[...this.definitions.entries()].find(([i])=>i.split("-")[0]===n)?.[1]??this.definitions.get("zh-cn")}has(e){return this.definitions.has(Pt(e))}translate(e,r,n,o){const i=this.resolve(e);return this.i18n.t(r,{lng:i.locale,defaultValue:n??r,...o??{}})}translator(e="zh-CN"){return(r,n,o)=>this.translate(e,r,n,o)}}const er=t=>new Fr(t),tr=new Fr;class p extends Error{code;details;constructor(e,r,n){super(r),this.code=e,this.details=n,this.name="SemanticDBError"}localizedMessage(e="zh-CN",r=tr){if(this.code==="PRED_PROPERTY_REQUIRED"&&this.message==="$shareOfTotal requires a property")return r.translate(e,"error.PRED_PROPERTY_REQUIRED.$shareOfTotal",this.message,this.details);if(this.code==="PROPERTY_NOT_FOUND"&&e.toLowerCase().startsWith("en")){const n=this.details?.schemaId,o=this.details?.schemaName,i=this.details?.property,s=this.details?.propertyName;if(typeof n=="string"&&typeof o=="string"&&typeof i=="string"&&typeof s=="string")return`Property not found in Schema: ${o}(${n}): ${s}`}return this.message}}se.extend(Rt),se.extend(Kt);const Pa=new Set(["year","quarter","month","week"]),Br=t=>t.format("YYYY-MM-DD HH:mm:ss"),Qr=(t,e)=>t.operator&&e(t.operator).kind==="aggregate"?!0:(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Qr(t.pred,e):!1)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Qr(r,e)),rr=(t,e,r)=>{if(t.kind==="window"||t.kind==="cumulative")throw new p("ACCUMULATE_WINDOW_UNSUPPORTED","$accumulate cannot contain another window expression");if(t.kind==="ordinal-decode")return{...t,input:rr(t.input,e,r)};if(t.kind==="ordinal-encode")return{kind:"cumulative",function:"sum",input:t,...r};if(t.kind!=="operator")return{kind:"cumulative",function:"sum",input:t,...r};const n=e.getOperator(t.operator);if(n.kind==="component")throw new p("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain component operator ${t.operator}`);if(n.kind==="aggregate"){if(t.operator==="$avg"){const s={...t,operator:"$sum"},a={...t,operator:"$count"};return{kind:"operator",operator:"$divide",args:{},inputs:[{kind:"cumulative",function:"sum",input:s,...r},{kind:"cumulative",function:"sum",input:a,...r}]}}const i={$sum:"sum",$count:"sum",$min:"min",$max:"max"}[t.operator];if(!i)throw new p("ACCUMULATE_OPERATOR_UNSUPPORTED",`Aggregate operator ${t.operator} does not declare cumulative semantics`);return{kind:"cumulative",function:i,input:t,...r}}if(n.kind!=="scalar")throw new p("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain ${t.operator}`);return{...t,...t.input?{input:rr(t.input,e,r)}:{},...t.inputs?{inputs:t.inputs.map(o=>rr(o,e,r))}:{}}},Ta=t=>{if(!t.input||t.inputs.length>0||t.pred.query)throw new p("INVALID_ACCUMULATE_INPUT","$accumulate requires exactly one nested pred and does not accept pred.query");if(t.inputProperty?.comparable&&t.input.kind!=="ordinal-decode")throw new p("ACCUMULATE_COMPARABLE_OPERATOR_REQUIRED","$accumulate over a comparable category requires an explicit $min or $max metric");const e=t.args.partitionBy??[],r=t.args.orderBy;if(!Array.isArray(e)||e.some(o=>typeof o!="string"))throw new p("INVALID_ACCUMULATE_ARGS","$accumulate partitionBy must be an array of groupby names");if(!Array.isArray(r)||r.length===0)throw new p("INVALID_ACCUMULATE_ARGS","$accumulate requires a non-empty args.orderBy array");const n=r.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw new p("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require pred and optional direction");const{pred:i,direction:s="asc",...a}=o;if(typeof i!="string"||s!=="asc"&&s!=="desc"||Object.keys(a).length>0)throw new p("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require only a string pred and asc/desc direction");return{expression:t.resolveKey(i),direction:s==="asc"?"ASC":"DESC"}});return rr(t.input,t,{partitionBy:e.map(o=>t.resolveKey(String(o))),orderBy:n})},La=t=>{if(t.groupByNames.length===0)return;if(typeof t.pred.pred!="object"||Array.isArray(t.pred.pred)||!Qr(t.pred.pred,t.getOperator))throw new p("ACCUMULATE_AGGREGATE_REQUIRED","$accumulate over a grouped physical relation requires an aggregate expression");const e=t.pred.args?.partitionBy,r=t.pred.args?.orderBy;if(e!==void 0&&!Array.isArray(e)||!Array.isArray(r)||r.length===0||r.some(i=>typeof i!="object"||i===null||Array.isArray(i)||typeof i.pred!="string"||Object.keys(i).some(s=>s!=="pred"&&s!=="direction")||i.direction!==void 0&&i.direction!=="asc"&&i.direction!=="desc"))return;const n=[...e??[],...r.map(i=>i.pred)];if(n.some(i=>typeof i!="string"))return;const o=n.map(i=>t.resolveGroupName(String(i)));if(o.length!==t.groupByNames.length||new Set(o).size!==t.groupByNames.length||t.groupByNames.some(i=>!o.includes(i)))throw new p("INCOMPLETE_ACCUMULATE_DIMENSIONS","$accumulate partitionBy and orderBy must cover every groupby item exactly once",{expected:t.groupByNames,received:o})},Da=(t,e,r)=>{if(t.from||t.having)throw new p("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period currently requires a physical LogicForm without from or having");if((t.preds?.length??0)!==e.length)throw new p("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period cannot currently be mixed with non-period projections");const n=t.query&&Object.entries(t.query).find(([,E])=>{if(typeof E!="object"||E===null||Array.isArray(E))return!1;const $=E;return typeof $.$gte=="string"&&typeof $.$lte=="string"});if(!n)throw new p("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires one bounded date query identifying the target period");const[o,i]=n,s=i,a=se(String(s.$gte)),u=se(String(s.$lte));if(!a.isValid()||!u.isValid())throw new p("ACCUMULATE_PERIOD_QUERY_REQUIRED","Target date range is invalid");const c=e.map(E=>{if(!E.name)throw new p("MISSING_PRED_NAME","$accumulate args.period requires normalized names");return E.name}),l=r==="week"?a.startOf("isoWeek"):a.startOf(r),d={...t.query,[o]:{...s,$gte:Br(l)}},f=new Set([...(t.groupby??[]).map(({name:E})=>E),...(t.preds??[]).map(({name:E})=>E)]),m=E=>{let $=E;for(;f.has($);)$=`_${$}`;return f.add($),$},y=m("__accumulate_period"),g=e.map((E,$)=>m(`__accumulate_metric_${$}`)),h=(t.groupby??[]).map(({name:E})=>String(E)),w=r==="year"||r==="quarter"?"month":"day",A={version:t.version,...t.schema?{schema:t.schema}:{},query:d,groupby:[...t.groupby??[],{operator:"$dateBucket",pred:o,args:{granularity:w},name:y}],preds:e.map((E,$)=>({...E.pred,name:g[$]??`__accumulate_metric_${$}`}))},_={version:t.version,from:A,preds:[...h.map(E=>({pred:E,name:E})),{pred:y,name:y},...e.map((E,$)=>({operator:"$accumulate",pred:g[$]??`__accumulate_metric_${$}`,args:{partitionBy:h,orderBy:[{pred:y,direction:"asc"}]},name:c[$]??`accumulate_${$}`}))]};return{version:t.version,from:_,query:{[y]:{$gte:Br(a),$lte:Br(u)}},preds:[...h.map(E=>({pred:E,name:E})),...c.map(E=>({pred:E,name:E}))],...t.sort?{sort:t.sort}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.page!==void 0?{page:t.page}:{},...t.output?{output:t.output}:{},...t.representation?{representation:t.representation}:{}}},Ca={name:"$accumulate",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Cumulative ${t}`:`${t}\u7D2F\u8BA1\u503C`,kind:"logical",normalizePred({pred:t}){const e=t.args?.period;if(e!==void 0&&(typeof e!="string"||!Pa.has(e)))throw new p("INVALID_ACCUMULATE_ARGS","$accumulate args.period must be year, quarter, month, or week");if(e!==void 0&&(t.args?.partitionBy!==void 0||t.args?.orderBy!==void 0))throw new p("INVALID_ACCUMULATE_ARGS","$accumulate args.period cannot be combined with partitionBy or orderBy");return t},planExpression:Ta,validatePlan:La,rewriteLogicform({logicform:t,schema:e}){const r=(t.preds??[]).filter(s=>s.operator==="$accumulate"&&s.args?.period!==void 0);if(r.length===0)return;const n=r[0]?.args?.period;if(r.some(s=>s.args?.period!==n))throw new p("ACCUMULATE_PERIOD_UNSUPPORTED","All $accumulate args.period projections in one LogicForm must use the same period");const o=new Set(Object.keys(t.query??{}));if(e.properties.filter(s=>s.primal_type==="date"&&o.has(s.name)).length!==1)throw new p("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires exactly one queried date property");return Da(t,r,n)},getOutputProperty({name:t,inputProperty:e}){return e?{...e,name:t,isArray:!1}:{name:t,type:"number",primal_type:"number",isArray:!1}}},qa={name:"$abs",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Absolute ${t}`:`${t}\u7EDD\u5BF9\u503C`,kind:"scalar",toSQL({expression:t}){if(!t)throw new p("PRED_PROPERTY_REQUIRED","$abs requires a pred");return`ABS(${t})`},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new p("PRED_PROPERTY_REQUIRED","$abs requires a pred");return{...e,name:t,isArray:!1}}},st=(t,e,r,n=r)=>{const o=e.expressions??[];if(o.length<r||o.length>n)throw new p("INVALID_OPERATOR_COMPONENTS",`${t} requires ${r===n?String(r):`${r}-${n}`} pred inputs`);return o},nr=t=>({name:t,type:"number",primal_type:"number",isArray:!1}),ka={name:"$add",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?e.join(" plus "):`Sum of ${t}`:e.length>0?e.join("\u52A0"):`${t}\u6C42\u548C`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$add.empty":"operator.$add",kind:"scalar",requiresProperty:!1,toSQL(t){return`(${st("$add",t,2,Number.POSITIVE_INFINITY).join(" + ")})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:nr(t)}},Z=t=>structuredClone(t),Ua=(t,e)=>{const r=e[t];if(!r)throw new p("SCHEMA_NOT_FOUND",`Schema not found: ${t}`,{schemaId:t});if("_id"in r||"_sid"in r)throw new p("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported",{schemaId:t});if("sid"in r)throw new p("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid",{schemaId:t});if(r.id!==t)throw new p("SCHEMA_ID_MISMATCH",`Schema registry key ${t} does not match schema.id ${r.id}`,{registryKey:t,schemaId:r.id});return r},ja=(t,e)=>{const r=t.properties.find(n=>n.id===e)??t.properties.find(n=>n.name===e);if(!r)throw new p("PROPERTY_NOT_FOUND",`Property not found in ${t.id}: ${e}`,{schemaId:t.id,property:e});return r},Ma=t=>{const e=t.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(e))},ko=(t,e)=>t.properties.some(r=>r!==e&&r.id===e.name)?e.id:e.name,xa=(t,e)=>t.properties.flatMap(r=>[...e.startsWith(`${r.id}_`)?[{property:r,prefix:r.id}]:[],...r.name!==r.id&&e.startsWith(`${r.name}_`)?[{property:r,prefix:r.name}]:[]]).sort((r,n)=>n.prefix.length-r.prefix.length||(n.prefix===n.property.id?1:0)-(r.prefix===r.property.id?1:0)),ae=(t,e,r)=>{const n=t.properties.find(o=>o.id===e)??t.properties.find(o=>o.name===e);if(n)return{canonicalName:ko(t,n),canonicalId:n.id,schema:t,property:n,relations:[]};for(const{property:o,prefix:i}of xa(t,e)){if(o.primal_type!=="entity"&&o.primal_type!=="object"||!o.ref)continue;if(!r)throw new p("SCHEMA_RESOLVER_REQUIRED",`Resolving property path ${e} requires a Schema resolver`);const s=r(o.ref),a=ae(s,e.slice(i.length+1),r);return{canonicalName:`${ko(t,o)}_${a.canonicalName}`,canonicalId:`${o.id}_${a.canonicalId}`,schema:a.schema,property:a.property,relations:[{sourceSchema:t,property:o,targetSchema:s},...a.relations]}}throw new p("PROPERTY_NOT_FOUND",`\u5728 Schema\uFF1A${t.name}(${t.id})\u4E2D\u672A\u627E\u5230\u5C5E\u6027: ${e}`,{schemaId:t.id,schemaName:t.name,property:e,propertyName:e})},Hr=(t,e)=>t.name===e||t.id===e,Va=(t,e,r)=>{const n=new Set,o=[t];for(;o.length>0;){const i=o.shift();if(!i||n.has(i.name))continue;n.add(i.name);const s=[...i.hierarchy?.up?r.properties.filter(a=>Hr(a,i.hierarchy?.up??"")):[],...r.properties.filter(a=>a.hierarchy?.down!==void 0&&Hr(i,a.hierarchy.down))];if(s.some(a=>Hr(e,a.name)))return!0;o.push(...s)}return!1},Uo=(t,e,r,n)=>{if(t.operator||typeof t.pred!="string"||e.length===0)return!1;let o;try{o=ae(r,t.pred,n)}catch{return!1}return o.property.isArray||o.property.primal_type==="entity"||o.property.primal_type==="object"||o.relations.some(({property:i})=>i.isArray)?!1:e.some(i=>{if(i.operator||typeof i.pred!="string")return!1;let s;try{s=ae(r,i.pred,n)}catch{return!1}if(s.property.isArray)return!1;if(s.relations.length===0&&o.relations.length===0)return Va(s.property,o.property,r);if(s.relations.length!==0||o.relations.length===0)return!1;const[a]=o.relations;return s.property.name===a?.property.name})},va=({source:t,properties:e})=>{const r=t.hierarchy;if(!Array.isArray(r))return r===void 0?{}:{hierarchy:r};let n=t.hierarchy_property;if(typeof n!="string"||n.length===0){const s=e.filter(({type:u})=>u==="ID");if(s.length!==1)throw new p("LEGACY_HIERARCHY_ID_PROPERTY_REQUIRED","Legacy Schema hierarchy without hierarchy_property must contain exactly one ID property",{idPropertyCount:s.length});const a=s[0];n=a?.id??a?.name}const o=r.map(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return;const a=s;if(!(typeof a.name!="string"||!Number.isInteger(a.code_length)))return{name:a.name,...Array.isArray(a.syno)?{syno:a.syno}:{},codeLength:a.code_length}});if(o.some(s=>s===void 0))return{};const i=r[0];return{hierarchy:{property:n,storage:i?.use_full_length===!0?"zero-padded":"compact",levels:o}}},Ya=t=>{if(!t.hierarchy)return;const e=t.properties.find(({name:r})=>r===t.hierarchy?.property);if(!e)throw new p("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${t.hierarchy.property}`,{schemaId:t.id,property:t.hierarchy.property});return e},Fa=(t,e,r)=>{const n=ae(t,e,r);if(n.property.primal_type!=="entity"&&n.property.primal_type!=="object")return{schema:n.schema,reference:n.canonicalName,relation:!1};if(n.property.isArray)throw new p("ARRAY_HIERARCHY_RELATION_UNSUPPORTED",`$hierarchyLevel cannot group an array relation: ${n.canonicalName}`);if(!n.property.ref||!r)throw new p("SCHEMA_RESOLVER_REQUIRED",`$hierarchyLevel requires a Schema resolver for relation ${n.canonicalName}`);return{schema:r(n.property.ref),reference:n.canonicalName,relation:!0}},Ba={name:"$hierarchyLevel",defaultName:({operandName:t,args:e,locale:r})=>{const n=typeof e.level=="string"?e.level:"";return r.toLowerCase().startsWith("en")?`${t}${n?` ${n}`:""} level`:`${t}${n}\u5C42\u7EA7`},kind:"scalar",planInput({reference:t,args:e,schema:r,resolveSchema:n}){const o=Object.keys(e).filter(y=>y!=="level");if(o.length>0||e.level!==void 0&&(typeof e.level!="string"||e.level.length===0))throw new p("INVALID_HIERARCHY_LEVEL_ARGS","$hierarchyLevel args may contain only one non-empty level string",{unsupportedArgs:o});const i=Fa(r,t,n),s=i.schema.hierarchy;if(!s)throw new p("SCHEMA_HIERARCHY_REQUIRED",`Schema ${i.schema.id} does not declare hierarchy`,{schemaId:i.schema.id});const a=i.schema.properties.find(({name:y})=>y===s.property);if(!a)throw new p("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${s.property}`);if(!i.relation&&a.name!==ae(r,t,n).property.name)throw new p("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${a.name}`);const u=s.levels.reduce((y,g)=>y+g.codeLength,0),c=i.schema.properties.filter(({type:y})=>y==="ID"),d=i.relation&&c.length===1&&c[0]?.name===a.name?i.reference:i.relation?`${i.reference}_${a.name}`:i.reference;if(e.level===void 0){let y=0;return{reference:d,args:{levels:s.levels.map(({name:g,codeLength:h})=>(y+=h,{name:g,codeLength:y})),totalLength:u,storage:s.storage}}}let f=0;const m=s.levels.find(y=>(f+=y.codeLength,y.name===e.level||y.syno?.includes(e.level)));if(!m)throw new p("HIERARCHY_LEVEL_NOT_FOUND",`Schema ${i.schema.id} does not declare hierarchy level: ${e.level}`,{schemaId:i.schema.id,level:e.level});return{reference:d,args:{level:m.name,codeLength:f,totalLength:u,storage:s.storage}}},toSQL({expression:t,args:e,sql:r}){if(!t)throw new Error("$hierarchyLevel requires a hierarchy pred");if(Array.isArray(e.levels)){const u=e.levels.filter(y=>typeof y=="object"&&y!==null&&!Array.isArray(y)&&typeof y.name=="string"&&Number.isInteger(y.codeLength)),c=e.totalLength,l=e.storage;if(u.length!==e.levels.length||u.length===0||!Number.isInteger(c)||Number(c)<=0||u.some(({name:y,codeLength:g},h)=>y.length===0||g<=0||g>Number(c)||h>0&&g<=Number(u[h-1]?.codeLength))||u.at(-1)?.codeLength!==c||l!=="compact"&&l!=="zero-padded")throw new p("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const d=`WHEN ${t} IS NULL THEN NULL`;if(l==="compact"){const y=r.stringLength(t),g=u.map(h=>`WHEN ${y} = ${h.codeLength} THEN ${r.value(h.name)}`);return`(CASE ${d} ${g.join(" ")} ELSE NULL END)`}const f=u.slice(0,-1).map(y=>{const g=Number(c)-y.codeLength;return`WHEN ${r.substring(t,y.codeLength+1,g)} = ${r.value("0".repeat(g))} THEN ${r.value(y.name)}`}),m=u.at(-1);return`(CASE ${d} ${f.join(" ")} ELSE ${r.value(m?.name)} END)`}const n=e.codeLength,o=e.totalLength,i=e.storage;if(!Number.isInteger(n)||!Number.isInteger(o)||Number(n)<=0||Number(o)<Number(n)||i!=="compact"&&i!=="zero-padded")throw new p("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const s=r.substring(t,1,Number(n)),a=Number(o)-Number(n);return i==="zero-padded"&&a>0?r.concat([s,r.value("0".repeat(a))]):s},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},at=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=t;return Object.keys(e).length===2&&e.kind==="hierarchy"&&typeof e.level=="string"&&e.level.trim().length>0},ct=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),Gr=(t,e,{schema:r,resolveSchema:n})=>{if(typeof e!="string")return;const o=t.primal_type==="entity"||t.primal_type==="object"?t.ref?n?.(t.ref).hierarchy:void 0:r.hierarchy?.property===t.name?r.hierarchy:void 0,i=o?.levels.find(s=>s.name===e||s.syno?.includes(e));if(!(!o||!i))return{name:i.name,index:o.levels.indexOf(i)}},or=(t,{schema:e,mapping:r})=>r.mappings?.find(n=>n.mappingType==="property"&&n.propertyTarget?.some(o=>ct(e,o)?.id===t.id)),jo=(t,e,r)=>{const n=ct(r.schema,t);if(!n)return`hierarchy property is not available: ${t}`;const o=Gr(n,e,r);if(!o)return`hierarchy level is not available: ${String(e)}`;const i=or(n,r);if(!at(i?.granularity))return;const s=Gr(n,i.granularity.level,r);return s&&s.index>=o.index?void 0:`hierarchy dimension ${t} requires ${o.name}, but source has ${s?.name}`},Qa=(t,e)=>{const r=i=>{const s=n(i.query);if(s)return s;if(i.operator==="$hierarchyLevel"&&typeof i.pred=="string")if(i.args?.level!==void 0){const u=jo(i.pred,i.args.level,e);if(u)return u}else{const u=ct(e.schema,i.pred),c=u&&or(u,e);if(at(c?.granularity))return`$hierarchyLevel without args.level is not covered by hierarchy-grained source: ${i.pred}`}const a=Array.isArray(i.pred)?i.pred:i.pred===void 0?[]:[i.pred];for(const u of a){if(typeof u=="string")continue;const c=r(u);if(c)return c}},n=i=>{if(i){for(const[s,a]of Object.entries(i))if(a!==void 0){if(s==="$and"||s==="$or"){if(!Array.isArray(a))continue;for(const u of a){const c=n(u);if(c)return c}}else if(s==="$expr"){if(typeof a!="object"||a===null||Array.isArray(a))continue;const u=a.pred;if(typeof u!="object"||u===null||Array.isArray(u))continue;const c=r(u);if(c)return c}else if(!s.startsWith("$")){const u=ct(e.schema,s),c=u&&or(u,e);if(at(c?.granularity))return`query on hierarchy-grained property requires an explicit $hierarchyLevel: ${s}`}}}},o=n(t.query);if(o)return o;for(const i of t.preds??[]){const s=r(i);if(s)return s}for(const i of t.groupby??[])if(typeof i.pred=="string"){if(i.operator==="$hierarchyLevel"){const s=jo(i.pred,i.args?.level,e);if(s)return s}else if(i.operator===void 0){const s=ct(e.schema,i.pred),a=s&&or(s,e);if(at(a?.granularity))return`raw groupby is not covered by hierarchy-grained source: ${i.pred}`}}},Ha={kind:"hierarchy",isGranularity:at,validateItem(t,e){const r=t.granularity;if(at(r))return t.propertyTarget?.every(n=>{const o=ct(e.schema,n);return o!==void 0&&Gr(o,r.level,e)!==void 0})?void 0:"physical hierarchy granularity requires a mapped hierarchy Property and level"},candidateReason:Qa,supportsGroupby:t=>t.operator==="$hierarchyLevel"},Ga={keys:["hierarchy"],resolve(t,e){for(const f of e)if(f.level!==void 0){if(typeof f.level!="string"||f.level.trim().length===0)throw new p("INVALID_PROPERTY_LEVEL",`Property ${f.name} level must be a non-empty string`,{property:f.name,level:f.level});if(f.primal_type!=="entity"&&f.primal_type!=="object")throw new p("PROPERTY_LEVEL_REQUIRES_ENTITY",`Property ${f.name} level requires an entity relation`,{property:f.name,type:f.type})}if("hierarchy_property"in t)throw new p("LEGACY_HIERARCHY_PROPERTY_NOT_ALLOWED","Schema hierarchy must declare hierarchy.property instead of hierarchy_property");const r=t.hierarchy;if(r===void 0)return{};if(typeof r!="object"||r===null||Array.isArray(r))throw new p("INVALID_HIERARCHY","Schema hierarchy must be an object containing property, levels, and optional storage");const n=r,o=Object.keys(n).filter(f=>f!=="property"&&f!=="storage"&&f!=="levels");if(o.length>0)throw new p("UNSUPPORTED_HIERARCHY_FIELD","Schema hierarchy only supports property, storage, and levels",{unsupportedKeys:o});const i=n.property===void 0?(()=>{const f=e.filter(m=>m.type==="ID");if(f.length!==1)throw new p("HIERARCHY_ID_PROPERTY_REQUIRED","Schema hierarchy.property may be omitted only when the Schema has exactly one ID Property",{idPropertyCount:f.length});return f[0]})():void 0;if(n.property!==void 0&&(typeof n.property!="string"||n.property.length===0))throw new p("HIERARCHY_PROPERTY_REQUIRED","Schema hierarchy.property must be a non-empty property name or id when provided");const s=i??e.find(f=>f.name===n.property||f.id===n.property);if(!s)throw new p("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${n.property}`,{property:n.property});if(s.primal_type!=="string")throw new p("INVALID_HIERARCHY_PROPERTY",`Hierarchy property ${s.name} must have primal_type string`,{property:s.name,primal_type:s.primal_type});const a=n.storage??"compact";if(a!=="compact"&&a!=="zero-padded")throw new p("INVALID_HIERARCHY_STORAGE","Schema hierarchy.storage must be compact or zero-padded");if(!Array.isArray(n.levels)||n.levels.length===0)throw new p("HIERARCHY_LEVELS_REQUIRED","Schema hierarchy.levels must be a non-empty array");const u=new Set,c=new Set,l=n.levels.map((f,m)=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new p("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} must be an object`);const y=f,g=Object.keys(y).filter(w=>w!=="name"&&w!=="syno"&&w!=="codeLength");if(g.length>0)throw new p("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${m} only supports name, syno, and codeLength`,{unsupportedKeys:g});if(typeof y.name!="string"||y.name.length===0)throw new p("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} name must not be empty`);if(u.has(y.name)||c.has(y.name))throw new p("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level name: ${y.name}`);if(!Number.isInteger(y.codeLength)||Number(y.codeLength)<=0)throw new p("INVALID_HIERARCHY_CODE_LENGTH",`Hierarchy level ${y.name} codeLength must be a positive integer`);if(y.syno!==void 0&&(!Array.isArray(y.syno)||y.syno.some(w=>typeof w!="string"||w.length===0)))throw new p("INVALID_HIERARCHY_SYNONYMS",`Hierarchy level ${y.name} syno must contain only non-empty strings`);const h=y.syno??[];for(const w of h){if(w===y.name||u.has(w)||c.has(w))throw new p("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${w}`);c.add(w)}return u.add(y.name),{name:y.name,...h.length>0?{syno:[...h]}:{},codeLength:Number(y.codeLength)}});return{hierarchy:{property:s.name,storage:a,levels:l}}}},za=Object.freeze({name:"hierarchy",schemaMetadata:Ga,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:va,resolveEntityFilterProperty:Ya,operators:[Ba],mappingGranularity:Ha}),Wa=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp"),zr="$periodValue",Ka=(t,e)=>{const r=e?.periodBoundaryPolicy?.({pred:t});if(r)return{operator:zr,...r};if(e?.kind==="aggregate")throw new p("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${zr}; ${e.name} describes a time range`,{operator:e.name});return{operator:zr,boundary:"end",implicit:!0}},Ja={name:"observation",resolveProjection({pred:t,schema:e,sourceProperty:r,outputProperty:n,operator:o}){if(!r||!Wa(r,e))return;const i=Ka(t,o);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:i.boundary,sourceProperty:r.name}}}}},Xa=new Set(["second","minute","hour","day","week","month","quarter","year"]),Mo=t=>typeof t=="string"&&Xa.has(t),Za=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ir=(t,e,r)=>{const n=t instanceof Date?t.getTime():typeof t=="string"||typeof t=="number"?new Date(t).getTime():Number.NaN;if(Number.isNaN(n))throw new p(`${r.codePrefix}_PERIOD_INVALID_BOUND`,`${r.label} period ${e} must be a date`,{owner:e,value:t});return n},ze=(t,e=2)=>String(t).padStart(e,"0"),Wr=t=>`${ze(t.getFullYear(),4)}-${ze(t.getMonth()+1)}-${ze(t.getDate())} ${ze(t.getHours())}:${ze(t.getMinutes())}:${ze(t.getSeconds())}.`+ze(t.getMilliseconds(),3),ec=(t,e)=>{if(!Za(t)){const a=ir(t,"point",e);return{lower:a,upper:a}}const r=t.$eq;if(r!==void 0){const a=ir(r,"$eq",e);return{lower:a,upper:a}}const n=t.$gte??t.$gt,o=t.$lte??t.$lt;if(n===void 0||o===void 0)throw new p(`${e.codePrefix}_PERIOD_BOUNDS_REQUIRED`,`${e.label} period grouping requires both a lower and an upper time bound`);const i=ir(n,t.$gte!==void 0?"$gte":"$gt",e)+(t.$gte===void 0?1:0),s=ir(o,t.$lte!==void 0?"$lte":"$lt",e)-(t.$lte===void 0?1:0);if(i>s)throw new p(`${e.codePrefix}_PERIOD_INVALID_RANGE`,`${e.label} period grouping requires the lower bound to precede the upper bound`,{lower:n,upper:o});return{lower:i,upper:s}},tc=(t,e)=>{const r=new Date(t);switch(e){case"second":r.setMilliseconds(0);break;case"minute":r.setSeconds(0,0);break;case"hour":r.setMinutes(0,0,0);break;case"day":r.setHours(0,0,0,0);break;case"week":{r.setHours(0,0,0,0);const n=(r.getDay()+6)%7;r.setDate(r.getDate()-n);break}case"month":r.setDate(1),r.setHours(0,0,0,0);break;case"quarter":r.setMonth(Math.floor(r.getMonth()/3)*3,1),r.setHours(0,0,0,0);break;case"year":r.setMonth(0,1),r.setHours(0,0,0,0);break}return r},rc=(t,e)=>{const r=new Date(t);switch(e){case"second":r.setSeconds(r.getSeconds()+1);break;case"minute":r.setMinutes(r.getMinutes()+1);break;case"hour":r.setHours(r.getHours()+1);break;case"day":r.setDate(r.getDate()+1);break;case"week":r.setDate(r.getDate()+7);break;case"month":r.setMonth(r.getMonth()+1);break;case"quarter":r.setMonth(r.getMonth()+3);break;case"year":r.setFullYear(r.getFullYear()+1);break}return r},xo=(t,e,r)=>{const{lower:n,upper:o}=ec(t,r),i=[];let s=tc(n,e);for(;s.getTime()<=o;){if(i.length>=1e4)throw new p(`${r.codePrefix}_PERIOD_LIMIT_EXCEEDED`,`${r.label} period grouping cannot generate more than 10000 periods`);const a=rc(s,e),u=new Date(Math.min(a.getTime()-1,o));i.push({label:Wr(s),start:Wr(s),end:Wr(u)}),s=a}return i},nc=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.name),oc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.name)),ic=(t,e)=>{if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:d})=>d==="timestamp");if(!r)return;const n=nc(t,r),o=t.preds??[],i=o.filter(({operator:d})=>d==="$periodValue");if(!n||i.length===0)return;const s=n.args?.granularity;if(n.operator!=="$dateBucket"||!Mo(s))throw new p("OBSERVATION_PERIOD_GRANULARITY_UNSUPPORTED","Grouped observation period values require $dateBucket with a supported time granularity",{property:r.name});if(i.length!==o.length)throw new p("OBSERVATION_PERIOD_METRICS_REQUIRED","A grouped observation query cannot mix $periodValue with ordinary projections");const a=i.map(d=>{const f=d.args?.boundary;if(f!=="start"&&f!=="end")throw new p("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:f});if(!d.pred||typeof d.pred!="object"||Array.isArray(d.pred))throw new p("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");return{pred:d,effectivePred:{...d.pred,...d.name?{name:d.name}:{}}}});if(new Set(i.map(({args:d})=>d?.boundary)).size!==1)throw new p("OBSERVATION_PERIOD_BOUNDARY_MISMATCH","Grouped observation metrics in one query must use the same period boundary");const c=i[0]?.args?.boundary,l=t.query?.[r.name];if(l===void 0)throw new p("OBSERVATION_PERIOD_BOUNDS_REQUIRED",`Grouped observation values on ${r.name} require a bounded query`,{property:r.name});return{group:n,timestamp:r,boundary:c,metrics:a,periods:xo(l,s,{codePrefix:"OBSERVATION",label:"Observation"}).map(d=>({label:d.label,asOf:d[c]}))}},Vo=["second","minute","hour","day","week","month","quarter","year"],sc=Object.freeze({name:"observation",schemaMetadata:{keys:["temporalSemantics"],resolve(t){const e=t.temporalSemantics??"normal";if(e!=="normal"&&e!=="snapshot")throw new p("INVALID_TEMPORAL_SEMANTICS","Schema temporalSemantics must be normal or snapshot",{schemaId:t.id,temporalSemantics:e});return{temporalSemantics:e}}},validateResolvedSchema(t){if(t.temporalSemantics==="snapshot"&&!t.properties.some(({type:e})=>e==="timestamp"))throw new p("SNAPSHOT_TIMESTAMP_REQUIRED","A snapshot Schema must declare exactly one timestamp Property",{schemaId:t.id})},plannerSemantics:[Ja],relationSemantics:{plan({sourceSchema:t,targetSchema:e}){if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:s})=>s==="timestamp");if(!r)throw new p("SNAPSHOT_JOIN_REQUIRES_ID_AND_TIMESTAMP",`Snapshot Schema ${e.id} requires an ID and timestamp Property when joined`,{schemaId:e.id});const n=t.properties.find(({type:s})=>s==="timestamp");if(!n)throw new p("SNAPSHOT_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Snapshot Schema ${e.id} cannot join from a Schema without a timestamp Property`,{schemaId:t.id});const o=n.granularity??"day",i=r.granularity??"day";if(Vo.indexOf(o)>Vo.indexOf(i))throw new p("SNAPSHOT_JOIN_GRANULARITY_TOO_COARSE",`Cannot join ${e.id} snapshot granularity ${i} to coarser source granularity ${o}`,{sourceSchemaId:t.id,targetSchemaId:e.id,sourceGranularity:o,targetGranularity:i});return{kind:"date-bucket-equal",sourceTimestamp:n,targetTimestamp:r}}},plannerPeriod:{resolve(t,e){const r=ic(t,e);if(r)return{group:r.group,property:r.timestamp,periods:r.periods,source:{kind:"latest",timestamp:r.timestamp},rewriteQuery:n=>oc(n,r.timestamp),rewritePred:n=>r.metrics.find(o=>o.pred===n)?.effectivePred??n}}}}),Tt=(t,e)=>typeof e=="string"?t.properties.find(({id:r,name:n})=>r===e||n===e):void 0,ac={name:"$recursive",validateCondition(t){if(Object.keys(t).some(e=>e!=="$recursive"))throw new p("INVALID_RECURSIVE_QUERY","$recursive cannot be combined with other field operators")},async normalize(t,e){const r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{root:t},n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=n===e.schema.id?e.schema:e.resolveSchema?.(n);if(!o)throw new p("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=r.idProperty??r.id_property,s=o.properties.filter(({type:f})=>f==="ID"),a=i===void 0?s.length===1?s[0]:void 0:Tt(o,i);if(!a||i===void 0&&s.length!==1)throw new p("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive Schema ${n} must have exactly one ID property or idProperty`);const u=Array.isArray(r.roots),c=u?r.roots:r.root===void 0?[]:[r.root];if(!u&&c.length===0||c.some(f=>f===void 0))throw new p("RECURSIVE_ROOT_REQUIRED","$recursive requires root or roots");const l=await Promise.all(c.map(f=>e.normalizeValue(f,o,a))),d=r.parentProperty??r.parent_property??o.parentProperty??"pid";if(typeof d!="string"||d.length===0)throw new p("RECURSIVE_PARENT_PROPERTY_REQUIRED","$recursive parentProperty must be a string");if(r.includeSelf!==void 0&&typeof r.includeSelf!="boolean"||r.include_self!==void 0&&typeof r.include_self!="boolean")throw new p("INVALID_RECURSIVE_QUERY","$recursive includeSelf must be boolean");return{schema:n,roots:l,includeSelf:r.includeSelf??r.include_self??!0,idProperty:a.name,parentProperty:d}},authorize(t,e){const r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=e.resolveSchema(n);if(e.assertSchemaAllowed(n),e.hasRowPermissions(n))throw new p("RECURSIVE_ROW_PERMISSION_UNSUPPORTED",`$recursive cannot safely apply row permissions for Schema ${n}`,{schemaId:n});const i=r.idProperty??r.id_property,s=i===void 0?o.properties.find(({type:c})=>c==="ID"):Tt(o,i),a=r.parentProperty??r.parent_property??o.parentProperty??"pid",u=Tt(o,a);s&&e.assertPropertyAllowed(o,s),u&&e.assertPropertyAllowed(o,u)},plan(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw new p("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const r=t,n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=n===e.schema.id?e.schema:e.resolveSchema?.(n);if(!o)throw new p("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=Tt(o,r.idProperty),s=Tt(o,r.parentProperty);if(!i)throw new p("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive ID property not found: ${String(r.idProperty)}`);if(!s)throw new p("RECURSIVE_PARENT_PROPERTY_REQUIRED",`$recursive parent property not found: ${String(r.parentProperty)}`);if(!Array.isArray(r.roots)||typeof r.includeSelf!="boolean")throw new p("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const a=e.resolveMapping(n,e.connectionId);return{value:{schemaId:n,connectionId:a.connectionId,source:a.source,...a.sourceSql?{sourceSql:a.sourceSql}:{},idColumn:i.id,parentColumn:s.id,roots:r.roots,includeSelf:r.includeSelf},sources:[{schemaId:n,source:a.source,...a.connectionId?{connectionId:a.connectionId}:{}}]}},compile(t,{field:e,provider:r,bind:n,renderSource:o}){if(typeof t!="object"||t===null||Array.isArray(t))throw new p("INVALID_RECURSIVE_QUERY","$recursive query was not planned");const i=t;if(typeof i.source!="string"||typeof i.idColumn!="string"||typeof i.parentColumn!="string"||!Array.isArray(i.roots)||typeof i.includeSelf!="boolean")throw new p("INVALID_RECURSIVE_QUERY","$recursive query was not planned");if(!r.supportsRecursiveCte)throw new p("RECURSIVE_QUERY_UNSUPPORTED",`Provider ${r.kind} does not support recursive queries`);const s=Array.isArray(i.roots)?i.roots:[];if(s.length===0)return`${e} IN (SELECT NULL WHERE 1 = 0)`;const a=r.quoteIdentifier("__recursive_tree__"),u=r.quoteIdentifier("__recursive_id__"),c=r.quoteIdentifier("__recursive_node__"),l=r.quoteIdentifier("__recursive_child__"),d=r.quoteIdentifier(i.idColumn),f=r.quoteIdentifier(i.parentColumn),m=o(i.source,typeof i.sourceSql=="string"?i.sourceSql:void 0),y=()=>s.map(E=>n(E)).join(", "),g=(E,$=!1)=>s.length===1?`${E} ${$?"<>":"="} ${y()}`:`${E} ${$?"NOT IN":"IN"} (${y()})`,h=`${c}.${d}`,w=i.includeSelf?g(h):`${g(`${c}.${f}`)} AND ${g(h,!0)}`,A=r.recursiveCteUnion??"UNION",_=`(WITH RECURSIVE ${a}(${u}) AS ( SELECT ${h} FROM ${r.tableAlias(m,"__recursive_node__")} WHERE ${w} ${A} SELECT ${l}.${d} FROM ${r.tableAlias(m,"__recursive_child__")} JOIN ${a} ON ${l}.${f} = ${a}.${u}) SELECT DISTINCT ${u} FROM ${a})`;return`${e} IN ${_}`}},cc=Object.freeze({name:"recursive",schemaMetadata:{keys:["parentProperty"],resolve(t,e){if(t.parentProperty===void 0)return{};const r=e.find(({id:n,name:o})=>n===t.parentProperty||o===t.parentProperty);if(!r)throw new p("RECURSIVE_PARENT_PROPERTY_REQUIRED",`Schema parentProperty does not exist: ${t.parentProperty}`,{schemaId:t.id,property:t.parentProperty});return{parentProperty:r.name}}},queryOperators:[ac]});se.extend(Rt);const Kr=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...Kr(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:Kr(r))]:e},vo=(t,e)=>se(t).endOf(e==="week"?"isoWeek":e).toDate(),Jr=t=>se(t).format("YYYY-MM-DD HH:mm:ss"),uc=(t,e)=>{const r=t??{type:"database_latest"};if(r.type==="database_latest"||Number.isInteger(r.offset))return r;throw new p("INVALID_TIME_WATERMARK",`${e} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:e,timeWatermark:t})},Yo=(t,e)=>{if(t===void 0)return;if(typeof t!="object"||t===null||Array.isArray(t))throw new p("INVALID_TIME_WATERMARK",`${e} timeWatermark must be an object`);const r=t,n=Object.keys(r);if(!(r.type==="database_latest"&&n.length===1)&&!(r.type==="now_offset"&&n.every(o=>o==="type"||o==="offset")&&Number.isInteger(r.offset)))throw new p("INVALID_TIME_WATERMARK",`${e} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:e,timeWatermark:t})},dc=Object.freeze({name:"temporal",schemaMetadata:{keys:["timeWatermark"],resolve(t){return Yo(t.timeWatermark,`Schema ${t.id}`),{...t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}}},propertyMetadata:{keys:["timeWatermark"],resolve(t,e){if(Yo(t.timeWatermark,`Property ${t.name}`),t.timeWatermark&&e.primal_type!=="date")throw new p("TIME_WATERMARK_DATE_PROPERTY_REQUIRED",`Property ${e.name} timeWatermark is only supported by date Properties`,{property:e.name});return t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}},createTimeWatermarkLogicform({logicform:t,rootSchema:e,rootProperty:r,requestedUpperBound:n,now:o,defaultPolicy:i,resolveSchema:s,inferPropertyPath:a}){const u=[...new Set((t.preds??[]).flatMap(Kr).filter(d=>d!==e.id))],c=[{schema:e,property:r}];for(const d of u){const f=s(d),m=t.propertyResolve?.[d],y=m?.[r.id]??m?.[r.name]??a(e,r.name,f);if(!y)throw new p("TIME_WATERMARK_PROPERTY_RESOLVE_REQUIRED",`Cross-Schema timeWatermark requires propertyResolve for ${d}.${r.name}`,{schemaId:d,property:r.name});const g=f.properties.find(({id:h,name:w})=>h===y||w===y);if(!g||g.primal_type!=="date")throw new p("TIME_WATERMARK_PROPERTY_REQUIRED",`timeWatermark Property is not a date Property: ${d}.${y}`,{schemaId:d,property:y});c.push({schema:f,property:g})}const l=c.map(({schema:d,property:f})=>{const m=uc(f.timeWatermark??d.timeWatermark??i,`${d.id}.${f.id}`);if(m.type==="now_offset"){const y=vo(se(o).add(m.offset,"day").toDate(),f.granularity??"day");return{operator:"$constant",args:{value:Jr(y),type:"timestamp"},name:`${d.name}\u6570\u636E\u65F6\u95F4`}}return{operator:"$periodBoundary",args:{boundary:"end"},pred:{operator:"$max",pred:f.name,schema:d.id},name:`${d.name}\u6700\u65B0\u65F6\u95F4`}});return l.some(({operator:d})=>d==="$periodBoundary")&&l.push({operator:"$constant",args:{value:Jr(vo(o,r.granularity??"day")),type:"timestamp"},name:"\u73B0\u5728"}),l.push({operator:"$constant",args:{value:Jr(n),type:"timestamp"},name:"\u63D0\u95EE\u65F6\u95F4\u4E0A\u754C"}),{version:t.version,schema:e.id,preds:[{name:"__timeWatermark__",operator:"$least",pred:l}]}}}),sr=(t,e)=>{const r=t.filter(n=>n.type===e);return r.length===1?r[0]:void 0},Lt=t=>{if(t.type!=="entity"||t.temporalSemantics==="snapshot")return;const e=sr(t.properties,"ID"),r=sr(t.properties,"timestamp"),n=sr(t.properties,"start_date"),o=sr(t.properties,"end_date");return e&&r&&n&&o?{id:e,timestamp:r,start:n,end:o}:void 0},Fo=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.timestamp.name),pc=(t,e)=>Fo(t,e)!==void 0,lc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.timestamp.name)),fc=(t,e)=>{const r=Fo(t,e);if(!r)return;const n=r.args?.granularity;if(r.operator!=="$dateBucket"||!Mo(n))throw new p("VALIDITY_PERIOD_GRANULARITY_UNSUPPORTED","Valid-time period grouping requires $dateBucket with a supported time granularity",{property:e.timestamp.name});const o=t.query?.[e.timestamp.name];if(o===void 0)throw new p("VALIDITY_PERIOD_BOUNDS_REQUIRED",`Valid-time period grouping on ${e.timestamp.name} requires a bounded query`,{property:e.timestamp.name});return{group:r,granularity:n,periods:xo(o,n,{codePrefix:"VALIDITY",label:"Valid-time"}).map(({label:i,end:s})=>({label:i,asOf:s}))}},mc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),yc=t=>mc(t)?t.$lte??t.$lt??t.$eq:t,Bo=(t,e)=>{if(!t)return t;const r=Object.fromEntries(Object.entries(t).map(([a,u])=>[a,(a==="$and"||a==="$or")&&Array.isArray(u)?u.map(c=>Bo(c,e)):u])),n=Object.entries(t).find(([a])=>a===e.timestamp.name);if(!n)return r;const[,o]=n,i=yc(o);if(i===void 0)throw new p("VALIDITY_POINT_IN_TIME_REQUIRED",`Valid-time query on ${e.timestamp.name} requires an upper bound or a point in time`,{property:e.timestamp.name});return{...Object.fromEntries(Object.entries(r).filter(([a])=>a!==e.timestamp.name)),[e.start.name]:t[e.start.name]??{$lte:i},[e.end.name]:t[e.end.name]??{$or:[{$exists:!1},{$gt:i}]}}},Qo=(t,e)=>!!(t&&Object.entries(t).some(([r,n])=>e.has(r)||(r==="$and"||r==="$or")&&Array.isArray(n)&&n.some(o=>typeof o=="object"&&o!==null&&Qo(o,e)))),hc={name:"validity",resolveQuery({logicform:t,schema:e,query:r}){const n=Lt(e);if(!n)return r;if(pc(t,n))return lc(r,n);const i=Qo(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:new Date().toISOString()}};return Bo(i,n)},resolveProjection({schema:t,outputProperty:e}){if(Lt(t))return{outputProperty:{...e,temporal:{kind:"validity"}}}}},gc={name:"start_date",primalType:"date"},$c={name:"end_date",primalType:"date"},wc=Object.freeze({name:"validity",semanticTypes:[gc,$c],prepareSchema(t){const e=t.properties.filter(({type:s})=>s==="ID"),r=t.properties.filter(({type:s})=>s==="start_date"),n=t.properties.filter(({type:s})=>s==="end_date"),o=r[0];if(t.type!=="entity"||t.properties.some(({type:s})=>s==="timestamp")||t.temporalSemantics==="snapshot"||e.length!==1||r.length!==1||n.length!==1||t.properties.some(({name:s})=>s==="\u65E5\u671F")||!o)return t;const i={id:"__chatbi__timestamp__placeholder__",name:"\u65E5\u671F",type:"timestamp",is_supplementary:!0,udf:{sql:o.id??o.name}};return{...t,properties:[...t.properties,i]}},plannerSemantics:[hc],intervalSemantics:{resolve:Lt},relationSemantics:{plan({sourceSchema:t,targetSchema:e}){const r=Lt(e);if(!r)return;const n=t.properties.find(({type:o})=>o==="timestamp");if(!n)throw new p("VALIDITY_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Valid-time Schema ${e.id} cannot join from a Schema without a timestamp Property`,{schemaId:t.id});return{kind:"point-in-interval",point:n,start:r.start,end:r.end}}},plannerPeriod:{resolve(t,e){const r=Lt(e);if(!r)return;const n=fc(t,r);return n?{group:n.group,property:r.timestamp,periods:n.periods,source:{kind:"interval",start:r.start,end:r.end}}:void 0}}}),Ho=(t,e,r,n)=>{if(r===void 0)return;if(typeof r!="string"||r.length===0)throw new p("INVALID_PROPERTY_HIERARCHY",`Property ${e.name} hierarchy.${n} must be a non-empty Property name or id`,{property:e.name,direction:n,reference:r});const o=t.find(i=>i.id===r)??t.find(i=>i.name===r);if(!o)throw new p("PROPERTY_HIERARCHY_TARGET_NOT_FOUND",`Property ${e.name} hierarchy.${n} does not exist: ${r}`,{property:e.name,direction:n,reference:r});if(o===e)throw new p("PROPERTY_HIERARCHY_CYCLE",`Property ${e.name} cannot point to itself in hierarchy.${n}`,{property:e.name,direction:n});return o.name},Ac=Object.freeze({name:"property-hierarchy",propertyMetadata:{keys:["hierarchy"],resolve:()=>({}),resolveAll(t,e){const r=t.map((o,i)=>{const s=e[i]?.hierarchy;if(s===void 0)return o;if(typeof s!="object"||s===null||Array.isArray(s))throw new p("INVALID_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy must be an object containing up and/or down`,{property:o.name,hierarchy:s});const a=s,u=Object.keys(a).filter(d=>d!=="up"&&d!=="down");if(u.length>0)throw new p("UNSUPPORTED_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy only supports up and down`,{property:o.name,unsupported:u});const c=Ho(t,o,a.up,"up"),l=Ho(t,o,a.down,"down");return{...o,hierarchy:{...c?{up:c}:{},...l?{down:l}:{}}}}),n=new Map(r.map(o=>[o.name,o]));for(const o of r)for(const i of["up","down"]){const s=new Set;let a=o;for(;a?.hierarchy?.[i];){if(s.has(a.name))throw new p("PROPERTY_HIERARCHY_CYCLE",`Property hierarchy.${i} contains a cycle at ${a.name}`,{property:o.name,direction:i,cycleAt:a.name});s.add(a.name),a=n.get(a.hierarchy[i])}}return r}}}),Go=Object.freeze([za,cc,dc,sc,wc,Ac]),me=(t=[])=>{const e=[...Go,...t],r=new Set,n=new Set,o=new Set,i=new Set,s=new Set,a=new Set,u=new Set,c=new Set,l=new Set;for(const d of e){if(!d.name)throw new p("INVALID_PLUGIN","Plugin name must not be empty");if(r.has(d.name))throw new p("PLUGIN_ALREADY_REGISTERED",`Plugin is already registered: ${d.name}`,{plugin:d.name});r.add(d.name);for(const m of[...d.schemaMetadata?.keys??[],...d.legacySchemaKeys??[]]){if(!m)throw new p("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(n.has(m))throw new p("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${m}`,{key:m,plugin:d.name});n.add(m)}for(const m of d.propertyMetadata?.keys??[]){if(!m)throw new p("INVALID_PLUGIN_PROPERTY_METADATA_KEY","Plugin Property metadata key must not be empty");if(o.has(m))throw new p("PLUGIN_PROPERTY_METADATA_KEY_ALREADY_REGISTERED",`Plugin Property metadata key is already registered: ${m}`,{key:m,plugin:d.name});o.add(m)}for(const m of d.operators??[]){if(i.has(m.name))throw new p("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${m.name}`,{operator:m.name,plugin:d.name});i.add(m.name)}for(const m of d.semanticTypes??[]){if(s.has(m.name))throw new p("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${m.name}`,{semanticType:m.name,plugin:d.name});s.add(m.name)}for(const m of d.plannerSemantics??[]){if(!m.name||a.has(m.name))throw new p("PLUGIN_SEMANTIC_RULE_ALREADY_REGISTERED",`Plugin Planner semantic rule must be non-empty and unique: ${m.name}`,{rule:m.name,plugin:d.name});a.add(m.name)}for(const m of d.queryOperators??[]){if(!m.name||u.has(m.name))throw new p("PLUGIN_QUERY_OPERATOR_ALREADY_REGISTERED",`Plugin Query Operator must be non-empty and unique: ${m.name}`,{operator:m.name,plugin:d.name});u.add(m.name)}for(const m of d.outputHandlers??[]){if(!m.type||c.has(m.type))throw new p("PLUGIN_OUTPUT_HANDLER_ALREADY_REGISTERED",`Plugin output handler type must be non-empty and unique: ${m.type}`,{type:m.type,plugin:d.name});c.add(m.type)}const f=d.mappingGranularity;if(f){if(!f.kind||l.has(f.kind))throw new p("PLUGIN_GRANULARITY_ALREADY_REGISTERED",`Plugin physical granularity kind must be non-empty and unique: ${f.kind}`);l.add(f.kind)}}return Object.freeze(e)},ut=(t,e=[])=>me(e).flatMap(r=>r.queryOperators??[]).find(r=>r.name===t),zo=(t,e=[])=>me(e).flatMap(r=>r.outputHandlers??[]).find(r=>r.type===t),Xr=(t,e)=>{if(e.length>1)throw new p("PLUGIN_SEMANTIC_CAPABILITY_AMBIGUOUS",`Multiple plugins matched ${t}: ${e.map(({plugin:r})=>r).join(", ")}`,{capability:t,plugins:e.map(({plugin:r})=>r)});return e[0]?.value},Wo=(t,e=[])=>Xr("interval semantics",me(e).flatMap(r=>{const n=r.intervalSemantics?.resolve(t);return n?[{plugin:r.name,value:n}]:[]})),Ec=(t,e,r=[])=>Xr("relation semantics",me(r).flatMap(n=>{const o=n.relationSemantics?.plan({sourceSchema:t,targetSchema:e});return o?[{plugin:n.name,value:o}]:[]})),Ic=(t,e,r=[])=>Xr("planner period semantics",me(r).flatMap(n=>{const o=n.plannerPeriod?.resolve(t,e);return o?[{plugin:n.name,value:o}]:[]})),Zr=t=>typeof t=="string"&&t.length>0&&t!=="placeholder"||typeof t=="number"&&Number.isSafeInteger(t),_c=t=>{const e=t.properties.filter(({type:r})=>r==="ID");if(e.length!==1)throw new p("ENTITY_ID_PROPERTY_REQUIRED",`Schema ${t.id} must contain exactly one ID property to use entity_id`,{schemaId:t.id,idPropertyCount:e.length});return e[0]},en=(t,e=[])=>{for(const r of me(e)){const n=r.resolveEntityFilterProperty?.(t);if(n)return n}return _c(t)},tn=t=>{if(t.name)return t.name;throw new p("MISSING_PRED_NAME","A normalized groupby PredItem must have a name")},rn=t=>typeof t.pred=="string"?t.pred:void 0,Sc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Rc={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},bc={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},nn=(t,e,r)=>{const n=e.toLowerCase().startsWith("en"),o=t.time;if(!Sc(o))return r?.("period.comparison",n?"period-over-period":"\u540C\u671F")??(n?"period-over-period":"\u540C\u671F");if(typeof o.granularity=="string"&&typeof o.offset=="number"){if(o.offset===-1&&o.granularity==="year")return r?.("period.yearOverYear",n?"year-over-year":"\u540C\u6BD4")??(n?"year-over-year":"\u540C\u6BD4");if(o.offset===-1&&o.granularity==="month")return r?.("period.monthOverMonth",n?"month-over-month":"\u73AF\u6BD4")??(n?"month-over-month":"\u73AF\u6BD4");if(o.offset===-1&&o.granularity==="week")return r?.("period.weekOverWeek",n?"week-over-week":"\u5468\u73AF\u6BD4")??(n?"week-over-week":"\u5468\u73AF\u6BD4");if(o.offset===0)return r?.("period.current",n?"current-period":"\u672C\u671F")??(n?"current-period":"\u672C\u671F");const s=Math.abs(o.offset),a=o.offset<0?"before":"after";return n?`${s} ${o.granularity}${s===1?"":"s"} ${a}`:`\u8F83${a==="before"?"\u524D":"\u540E"}${s}${Rc[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${bc[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};se.extend(Rt),se.extend(Kt);const Oc=["second","minute","hour","day","week","month","quarter","year"],Nc=new Set(Oc),on=["year","quarter","month","week","day","hour","minute","second"],Ko=t=>Object.prototype.toString.call(t)==="[object Object]",ve=t=>{throw new p("INVALID_PERIOD_SHIFT_ARGS",t)},Pc=t=>{const e=t.time;Ko(e)||ve("$periodShift requires args.time");const r=e;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!Nc.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&ve("Relative period shift time requires only granularity and an integer offset"),r;const o=Object.entries(r);(o.length===0||o.some(([a,u])=>!on.includes(a)||!Number.isInteger(u)))&&ve("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&ve("Absolute period shift time requires year");const i={quarter:[1,4],month:[1,12],week:[1,53],day:[1,31],hour:[0,23],minute:[0,59],second:[0,59]};for(const[a,[u,c]]of Object.entries(i)){const l=r[a];l!==void 0&&(Number(l)<u||Number(l)>c)&&ve(`Invalid absolute period shift ${a}: ${JSON.stringify(l)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&ve("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&ve("Absolute period shift day requires month"),r},Jo=(t,e,r)=>e==="month"?t.month(r-1):e==="day"?t.date(r):e==="week"?t.isoWeek(r):e==="quarter"?t.quarter(r):t.set(e,r),Tc=(t,e)=>{if("granularity"in e){const n=e.granularity==="week"?"week":e.granularity;return t.add(e.offset,n)}let r=t;for(const n of on){const o=e[n];typeof o=="number"&&(r=Jo(r,n,o))}return r},sn=(t,e)=>t instanceof Date?e.toDate():typeof t!="string"?t:e.format(t.includes(":")?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"),Lc=(t,e,r,n,o)=>(t.groupby??[]).filter(i=>{const s=rn(i);return s?ae(e,s,r).property.primal_type==="date":!1}).map(i=>{const s=i.operator==="$dateBucket"?i.args?.granularity:void 0,a="granularity"in n?n.granularity:s??"day",u="granularity"in n?-n.offset:o.originalAnchor&&o.shiftedAnchor?o.originalAnchor.diff(o.shiftedAnchor,a):0;return{name:tn(i),granularity:a,offset:u}}),an=(t,e,r)=>{if(Array.isArray(t))return t.map(i=>an(i,e,r));if(Ko(t))return Object.fromEntries(Object.entries(t).map(([i,s])=>[i,an(s,e,r)]));if(!(t instanceof Date)&&typeof t!="string")return t;const n=se(t);if(!n.isValid())return t;const o=Tc(n,e);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,sn(t,o)},Dc=(t,e,r,n,o)=>{const i=new Set,s=u=>Object.fromEntries(Object.entries(u).map(([c,l])=>{if((c==="$and"||c==="$or")&&Array.isArray(l))return[c,l.map(f=>s(f))];const d=ae(e,c,r);return d.property.primal_type!=="date"?[c,l]:(i.add(d.canonicalName),[c,an(l,n,o)])})),a=s(t);if(i.size===0||o.shiftedValues===0)throw new p("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a concrete date condition in the LogicForm query");if(i.size>1)throw new p("AMBIGUOUS_PERIOD_SHIFT_TIME","$periodShift query contains more than one date property",{properties:[...i]});return a},We=t=>{const e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?e[0]:{$and:e}},Ye=t=>[...t.query?[t.query]:[],...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Ye(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(r=>typeof r=="string"?[]:Ye(r)):[]],Cc=(t,e,r)=>{if(!(t instanceof Date)&&typeof t!="string")return t;const n=se(t);if(!n.isValid())return t;if("granularity"in e)return sn(t,n.add(-e.offset,e.granularity));if(!r.originalAnchor)return t;let o=n;for(const i of on)if(e[i]!==void 0){const s=i==="month"?r.originalAnchor.month()+1:i==="day"?r.originalAnchor.date():i==="week"?r.originalAnchor.isoWeek():i==="quarter"?r.originalAnchor.quarter():r.originalAnchor.get(i);o=Jo(o,i,s)}return sn(t,o)},cn=({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o})=>{const i=e.pred;(!i||typeof i!="object"||Array.isArray(i))&&ve("$periodShift pred must be a nested metric");const s=Pc(e.args??{}),a={shiftedValues:0},u=We([t.query,...Ye(e)]);if(!u)throw new p("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const c=Dc(u,n,o,s,a),l=Z(i);l.name=r,delete l.query;const d=Z(t);d.query=c,d.preds=[l],delete d.having,delete d.sort,delete d.limit,delete d.page;const f=new Set((t.groupby??[]).filter(m=>{const y=rn(m);return y?ae(n,y,o).property.primal_type==="date":!1}).map(tn));return{kind:"query",logicform:d,groupKeyShifts:Lc(t,n,o,s,a),mapResult:m=>m.map(y=>{const g={...y};for(const h of f)g[h]=Cc(g[h],s,a);return g})}},qc={name:"$periodShift",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=nn(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} baseline`:`${t}${o}\u57FA\u671F\u503C`;return n?.("operator.$periodShift",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:cn,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodShift requires a nested metric");return{...e,name:t,isArray:!1}}},kc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),ar=t=>typeof t=="string"||typeof t=="number"||t instanceof Date,Xo=(t,e)=>{const r=t.properties.find(({type:n})=>n==="timestamp");if(!r)throw new p("TIMESTAMP_PROPERTY_REQUIRED",`${e} requires a timestamp property in the Schema`);return r},Zo=(t,e)=>{if(ar(t)){e.start??=t,e.end??=t;return}if(!kc(t))return;const r=t.$eq;ar(r)&&(e.start??=r,e.end??=r);const n=t.$gte??t.$gt,o=t.$lte??t.$lt;ar(n)&&(e.start??=n),ar(o)&&(e.end??=o);for(const i of["$and","$or"]){const s=t[i];if(Array.isArray(s))for(const a of s)Zo(a,e)}},Uc=(t,e,r,n)=>{const o=Xo(e,n),i=new Set,s={},a=(d,f)=>{for(const[m,y]of Object.entries(d)){if((m==="$and"||m==="$or")&&Array.isArray(y)){for(const h of y)a(h,f||m==="$or");continue}if(m.startsWith("$"))continue;const g=ae(e,m,r);if(g.property.type==="timestamp"){if(f)throw new p("AMBIGUOUS_TIME_QUERY",`${n} does not support timestamp conditions inside $or`);i.add(g.canonicalName),Zo(y,s)}}};if(a(t,!1),i.size!==1)throw new p(i.size===0?"TIME_QUERY_REQUIRED":"AMBIGUOUS_TIME_QUERY",`${n} requires a concrete condition on the Schema timestamp property`);const u=[...i][0];if(!u||u!==o.name)throw new p("AMBIGUOUS_TIME_QUERY",`${n} requires the Schema timestamp property: ${o.name}`);const c=d=>{const f=[];for(const[m,y]of Object.entries(d)){if((m==="$and"||m==="$or")&&Array.isArray(y)){const g=y.map(h=>c(h)).filter(h=>h!==void 0);g.length>0&&f.push([m,g]);continue}!m.startsWith("$")&&ae(e,m,r).property.type==="timestamp"||f.push([m,y])}return f.length>0?Object.fromEntries(f):void 0},l=c(t);return{property:o,propertyName:u,...s.start!==void 0?{start:s.start}:{},...s.end!==void 0?{end:s.end}:{},...l?{queryWithoutTime:l}:{}}},ei=(t,e,r,n,o)=>{const i=We([t,...Ye(e)]);if(!i)throw new p("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return Uc(i,r,n,o)},ti=(t,e,r)=>We([t,{[e]:r}]),jc=new Set(["day","week","month","quarter","year"]),Mc={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},xc=t=>{if(typeof t!="string"||!jc.has(t))throw new p("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return t},ri=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},un=t=>{const e=Z(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=un(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:un(r))),e},Vc={name:"$averagePerPeriod",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${t} per ${typeof e.granularity=="string"?e.granularity:"period"}`:`${t}${Mc[String(e.granularity)]??"\u5468\u671F"}\u5747\u503C`,kind:"component",createComponent({logicform:t,pred:e,schema:r,outputName:n,t:o}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new p("INVALID_AVERAGE_PER_PERIOD_INPUT","$averagePerPeriod pred must be a nested metric");const i=xc(e.args?.granularity),s=Xo(r,"$averagePerPeriod"),a=un(e.pred),u=We([t.query,...Ye(e)]),c=ri(t);c.preds=[{...a,name:"__avg_period_num__"}],u&&(c.query=u);const l=ri(t);l.preds=[{operator:"$countDistinct",pred:{operator:"$dateBucket",pred:s.name,args:{granularity:i},name:"__avg_period_bucket__"},name:"__avg_period_den__"}],u&&(l.query=u);const d=o("component.numerator",`${n}\u5206\u5B50`,{outputName:n}),f=o("component.denominator",`${n}\u5206\u6BCD`,{outputName:n});return{components:[{name:d,logicform:c},{name:f,logicform:l}],expression:`${d} / NULLIF(${f}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$averagePerPeriod requires a nested metric");return{...e,name:t,isArray:!1}}},vc={name:"$avg",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Average ${t}`:`\u5E73\u5747${t}`,kind:"aggregate",toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$avg requires a column");return r.aggregateFunction("avg",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$avg requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1}}},Yc=t=>{if(t.mode!=="auto")return;const e=t.buckets;if(!Number.isInteger(e)||e<2||e>100)throw new p("INVALID_CASE_ARGS","$case auto mode requires args.buckets to be an integer between 2 and 100");if(Object.hasOwn(t,"cases"))throw new p("INVALID_CASE_ARGS","$case auto mode cannot define args.cases");for(const r of["min","max"])if(t[r]!==void 0&&typeof t[r]!="number"||t[r]!==void 0&&!Number.isFinite(t[r]))throw new p("INVALID_CASE_ARGS",`$case auto mode ${r} must be finite number`);if(t.min===void 0!=(t.max===void 0))throw new p("INVALID_CASE_ARGS","$case auto mode requires both min and max");return e},Fc=t=>{if(!Array.isArray(t)||t.length===0)throw new p("INVALID_CASE_ARGS","$case requires a non-empty args.cases array");return t.map(e=>{if(typeof e!="object"||e===null||!("when"in e)||!("then"in e))throw new p("INVALID_CASE_ARGS","Each $case item requires when and then");const r=e;return{when:r.when,then:r.then}})},Bc={name:"$case",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} category`:`${t}\u5206\u7C7B`,kind:"scalar",validateGroupby({pred:t}){if(t.args?.mode==="auto"&&(t.args.min===void 0||t.args.max===void 0))throw new p("AUTO_CASE_GROUPBY_REQUIRES_BOUNDS","$case auto mode in groupby requires explicit args.min and args.max")},toSQL({expression:t,args:e,sql:r}){if(!t)throw new p("PRED_PROPERTY_REQUIRED","$case requires a pred");const n=Yc(e);if(n!==void 0){const s=e.min===void 0?`MIN(${t}) OVER ()`:r.value(e.min),a=e.max===void 0?`MAX(${t}) OVER ()`:r.value(e.max),u=`(${a} - ${s})`,c=Array.from({length:n-1},(l,d)=>{const f=`${s} + ${u} * ${d+1} / ${n}`;return`WHEN ${t} < ${f} THEN ${r.value(d)}`});return`CASE WHEN ${s} = ${a} THEN ${r.value(0)} ${c.join(" ")} ELSE ${r.value(n-1)} END`}const o=Fc(e.cases).map(({when:s,then:a})=>`WHEN ${r.condition(t,s)} THEN ${r.value(a)}`),i=Object.hasOwn(e,"default")?` ELSE ${r.value(e.default)}`:"";return`CASE ${o.join(" ")}${i} END`},getOutputProperty({name:t}){return{name:t,type:"category",primal_type:"string",isArray:!1}}},Qc={name:"$concat",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?`Combined ${e.join(" and ")}`:`Combined ${t}`:e.length>0?`${e.join("\u4E0E")}\u62FC\u63A5\u503C`:`${t}\u62FC\u63A5\u503C`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$concat.empty":"operator.$concat",kind:"scalar",requiresProperty:!1,toSQL(t){return t.sql.concat(st("$concat",t,1,Number.POSITIVE_INFINITY))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},Hc={name:"$count",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?t==="rows"?"Row count":`${t} count`:t==="\u6570\u636E\u884C"?"\u884C\u6570":`${t}\u6570\u91CF`,defaultNameKey:({inputName:t,inputNames:e})=>t||e.length>0?"operator.$count":"operator.$count.rows",kind:"aggregate",requiresProperty:!1,toSQL(t){const{column:e,sql:r}=t;return r.aggregateFunction("count",e)},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},Gc={name:"$countDistinct",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Distinct ${t} count`:`${t}\u53BB\u91CD\u8BA1\u6570`,kind:"aggregate",toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$countDistinct requires a column");return r.aggregateFunction("count",`DISTINCT ${e}`)},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},zc=new Set(["second","minute","hour","day","week","month","quarter","year"]),Wc={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},ni=t=>{if(typeof t!="string"||!zc.has(t))throw new p("INVALID_DATE_BUCKET_ARGS","$dateBucket args.granularity must be second, minute, hour, day, week, month, quarter, or year");return t},Kc={name:"$dateBucket",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} by ${typeof e.granularity=="string"?e.granularity:"time"}`:`${t}\uFF08\u6309${Wc[String(e.granularity)]??"\u65F6\u95F4"}\uFF09`,kind:"scalar",supportsGroupedSourceGroupby:!0,groupedSourceTimeGranularity:({pred:t})=>t.args?.granularity,toSQL({expression:t,args:e,sql:r}){if(!t)throw new Error("$dateBucket requires a date pred");return r.dateBucket(t,ni(e.granularity))},getOutputProperty({name:t,inputProperty:e,args:r}){if(!e||e.primal_type!=="date")throw new p("DATE_BUCKET_DATE_REQUIRED","$dateBucket requires a date-valued pred");const n=ni(r.granularity);return{...e,name:t,type:"date",primal_type:"date",isArray:!1,granularity:n}}},Jc={name:"$divide",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>=2?`${e[0]} divided by ${e[1]}`:`${t} ratio`:e.length>=2?`${e[0]}\u9664\u4EE5${e[1]}`:`${t}\u6BD4\u503C`,defaultNameKey:({inputNames:t})=>t.length<2?"operator.$divide.fallback":"operator.$divide",kind:"scalar",requiresProperty:!1,toSQL(t){const[e,r]=st("$divide",t,2);return`(${e} / NULLIF(${r}, 0))`},getOutputProperty({name:t}){return nr(t)}},Xc=t=>{if(!(!t.inputProperty?.comparable||!t.input))return{kind:"ordinal-decode",comparable:t.inputProperty.comparable,input:{kind:"operator",operator:"$max",args:t.args,...t.pred.query?{query:t.planQuery(t.pred.query)}:{},input:{kind:"ordinal-encode",input:t.input,comparable:t.inputProperty.comparable}}}},Zc={name:"$max",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Maximum ${t}`:`${t}\u6700\u5927\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Xc,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$max requires a column");return r.aggregateFunction("max",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$max requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1,...n.granularity?{granularity:n.granularity}:{},...n.comparable?{comparable:n.comparable}:{}}}},eu=t=>{if(!(!t.inputProperty?.comparable||!t.input))return{kind:"ordinal-decode",comparable:t.inputProperty.comparable,input:{kind:"operator",operator:"$min",args:t.args,...t.pred.query?{query:t.planQuery(t.pred.query)}:{},input:{kind:"ordinal-encode",input:t.input,comparable:t.inputProperty.comparable}}}},tu={name:"$min",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Minimum ${t}`:`${t}\u6700\u5C0F\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:eu,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$min requires a column");return r.aggregateFunction("min",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$min requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1,...n.granularity?{granularity:n.granularity}:{},...n.comparable?{comparable:n.comparable}:{}}}},ru={name:"$multiply",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?e.join(" times "):`Product of ${t}`:e.length>0?e.join("\u4E58\u4EE5"):`${t}\u4E58\u79EF`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$multiply.empty":"operator.$multiply",kind:"scalar",requiresProperty:!1,toSQL(t){return`(${st("$multiply",t,2,Number.POSITIVE_INFINITY).join(" * ")})`},getOutputProperty({name:t}){return nr(t)}},nu=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},dn=t=>{const e=Z(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=dn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:dn(r))),e},ou={name:"$newly",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`New ${t}`:`\u65B0\u589E${t}`,kind:"component",createComponent({logicform:t,pred:e,schema:r,resolveSchema:n,outputName:o,t:i}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new p("INVALID_NEWLY_INPUT","$newly pred must be a nested metric");if((t.groupby??[]).some(d=>{const f=rn(d);return f?ae(r,f,n).property.type==="timestamp":!1}))throw new p("NEWLY_TIME_GROUPBY_UNSUPPORTED","$newly does not support grouping by the timestamp property");const s=ei(t.query,e,r,n,"$newly");if(s.start===void 0||s.end===void 0)throw new p("NEWLY_RANGE_REQUIRED","$newly requires both start and end timestamp bounds");const a=dn(e.pred),u=(d,f)=>{const m=nu(t);return m.query=ti(s.queryWithoutTime,s.propertyName,{$lte:d}),m.preds=[{...a,name:f}],m},c=i("component.end",`${o}\u7ED3\u675F`,{outputName:o}),l=i("component.start",`${o}\u5F00\u59CB`,{outputName:o});return{components:[{name:c,logicform:u(s.end,"__newly_end__")},{name:l,logicform:u(s.start,"__newly_start__")}],expression:`${c} - COALESCE(${l}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$newly requires a nested metric");return{...e,name:t,isArray:!1}}},iu=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},pn=t=>{const e=Z(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=pn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:pn(r))),e},su={name:"$periodValue",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} at period ${e.boundary==="start"?"start":"end"}`:`${t}${e.boundary==="start"?"\u671F\u521D\u503C":"\u671F\u672B\u503C"}`,defaultNameKey:({args:t})=>`operator.$periodValue.${t.boundary==="start"?"start":"end"}`,kind:"component",skipComponentExecution:({plan:t})=>t.periodSource?.match.kind==="latest",periodBoundaryPolicy({pred:t}){const e=t.args?.boundary;if(e!=="start"&&e!=="end")throw new p("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:e});return{boundary:e,implicit:!1}},createComponent({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new p("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");const i=e.args?.boundary;if(i!=="start"&&i!=="end")throw new p("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end");const s=ei(t.query,e,n,o,"$periodValue"),a=i==="start"?s.start:s.end;if(a===void 0)throw new p("PERIOD_BOUNDARY_RANGE_REQUIRED",`$periodValue cannot resolve the ${i} of the timestamp query`);const u={version:t.version,schema:n.id,query:{[s.propertyName]:{$lte:a}},preds:[{operator:"$max",pred:s.propertyName,name:"__period_boundary_date__"}]},c=iu(t);return c.query=ti(s.queryWithoutTime,s.propertyName,u),c.preds=[{...pn(e.pred),name:r}],{kind:"query",logicform:c}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodValue requires a nested metric");return{...e,name:t,isArray:!1}}},au=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},cu=({logicform:t,pred:e,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new Error("$periodDifference pred must be a nested metric");const a=Z(e.pred);a.name="__period_diff_current__";const u=au(t);u.preds=[a];const c=We([t.query,...Ye(e)]);c&&(u.query=c);const l={pred:Z(e.pred),...e.args?{args:e.args}:{}},d=cn({logicform:t,pred:l,outputName:"__period_diff_prev__",schema:i,resolveSchema:s});if(!("logicform"in d))throw new Error("$periodDifference period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:u},{name:m,logicform:d.logicform,...d.groupKeyShifts?{groupKeyShifts:d.groupKeyShifts}:{}}],expression:`${f} - ${m}`}},uu={name:"$periodDifference",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=nn(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} difference`:`${t}${o}\u5DEE\u503C`;return n?.("operator.$periodDifference",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:cu,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodDifference requires a nested metric");return{...e,name:t,isArray:!1}}},du=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},pu=({logicform:t,pred:e,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new Error("$periodGrowth pred must be a nested metric");const a=Z(e.pred);a.name="__period_growth_current__";const u=du(t);u.preds=[a];const c=We([t.query,...Ye(e)]);c&&(u.query=c);const l={pred:Z(e.pred),...e.args?{args:e.args}:{}},d=cn({logicform:t,pred:l,outputName:"__period_growth_prev__",schema:i,resolveSchema:s});if(!("logicform"in d))throw new Error("$periodGrowth period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:u},{name:m,logicform:d.logicform,...d.groupKeyShifts?{groupKeyShifts:d.groupKeyShifts}:{}}],expression:`${f} / NULLIF(ABS(${m}), 0) - 1`}},lu={name:"$periodGrowth",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=nn(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} growth`:`${t}${o}\u589E\u957F\u7387`;return n?.("operator.$periodGrowth",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:pu,getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},fu={name:"$sum",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Total ${t}`:`\u603B${t}`,kind:"aggregate",supportsGroupedSourceRollup:!0,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$sum requires a column");return r.aggregateFunction("sum",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$sum requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1}}},mu={name:"$subtract",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>=2?`${e[0]} minus ${e[1]}`:`${t} difference`:e.length>=2?`${e[0]}\u51CF\u53BB${e[1]}`:`${t}\u5DEE\u503C`,defaultNameKey:({inputNames:t})=>t.length<2?"operator.$subtract.fallback":"operator.$subtract",kind:"scalar",requiresProperty:!1,toSQL(t){const[e,r]=st("$subtract",t,2);return`(${e} - ${r})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:nr(t)}},oi=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},ln=t=>{const e=Z(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=ln(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:ln(r))),e},yu={name:"$shareOfTotal",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} share of total`:`${t}\u5360\u6BD4`,kind:"component",createComponent({logicform:t,pred:e,outputName:r,t:n}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new p("INVALID_SHARE_OF_TOTAL_INPUT","$shareOfTotal pred must be a nested metric");const o=e.args?.dimension;if(o!==void 0&&typeof o!="string")throw new p("INVALID_SHARE_OF_TOTAL_ARGS","$shareOfTotal args.dimension must be a groupby pred or output name");const i=t.groupby??[],s=o===void 0?i.length-1:i.findIndex(y=>typeof y.pred=="string"&&y.pred===o||tn(y)===o);if(o!==void 0&&s<0)throw new p("SHARE_OF_TOTAL_DIMENSION_NOT_FOUND",`$shareOfTotal dimension is not grouped: ${o}`);const a=i.filter((y,g)=>g!==s),u=ln(e.pred),c=oi(t);c.preds=[{...u,name:"__share_numerator__"}];const l=We([t.query,...Ye(e)]);l&&(c.query=l);const d=oi(t);d.groupby=a,d.preds=[{...u,name:"__share_denominator__"}];const f=n("component.numerator",`${r}\u5206\u5B50`,{outputName:r}),m=n("component.denominator",`${r}\u5206\u6BCD`,{outputName:r});return{components:[{name:f,logicform:c},{name:m,logicform:d}],expression:`${f} / NULLIF(${m}, 0)`}},getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},hu={name:"$substring",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} substring`:`${t}\u5B50\u4E32`,kind:"scalar",toSQL({expression:t,args:e,sql:r}){if(!t)throw new p("PRED_PROPERTY_REQUIRED","$substring requires a pred");const{start:n,length:o}=e;if(!Number.isInteger(n)||Number(n)<0||!Number.isInteger(o)||Number(o)<1)throw new p("INVALID_SUBSTRING_ARGS","$substring requires a non-negative integer start and a positive integer length");return r.substring(t,Number(n)+1,Number(o))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},ii=(t,e,r,n="$sql")=>{if(typeof t!="string"||t.trim().length===0)throw new p("INVALID_SQL_ARGS",`${n} requires a non-empty args.sql expression`);let o="",i=0,s;for(let a=0;a<t.length;a+=1){const u=t[a];if(!u)continue;if(s){o+=u,u===s&&(t[a+1]===s?(o+=s,a+=1):s=void 0);continue}if(u==="'"||u==='"'||u==="`"){s=u,o+=u;continue}const c=t.slice(a,a+2);if(u===";"||c==="--"||c==="/*")throw new p("INVALID_SQL_EXPRESSION",`${n} accepts one expression and does not allow statements or SQL comments`);if(u==="?"){if(i>=e.length)throw new p("INVALID_SQL_PARAMETERS",`${n} contains more placeholders than args.parameters values`);o+=r(e[i]),i+=1;continue}o+=u}if(s)throw new p("INVALID_SQL_EXPRESSION",`${n} contains an unterminated quote`);if(i!==e.length)throw new p("INVALID_SQL_PARAMETERS",`${n} args.parameters contains more values than SQL placeholders`);return o},gu=new Set(["boolean","date","number","entity","object","string"]),$u=t=>{if(t===void 0)return[];if(!Array.isArray(t))throw new p("INVALID_SQL_ARGS","$sql args.parameters must be an array");return t},wu=(t,e)=>{const r=e.type,n=e.primal_type;if(typeof r!="string"||r.length===0||!gu.has(n))throw new p("INVALID_SQL_OUTPUT","$sql requires args.type and a valid args.primal_type");if(e.isArray!==void 0&&typeof e.isArray!="boolean")throw new p("INVALID_SQL_OUTPUT","$sql args.isArray must be boolean");if(e.ref!==void 0&&typeof e.ref!="string")throw new p("INVALID_SQL_OUTPUT","$sql args.ref must be a Schema id");return{name:t,type:r,primal_type:n==="object"?"entity":n,isArray:e.isArray===!0,...typeof e.ref=="string"?{ref:e.ref}:{}}},Au={name:"$sql",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Calculated value":"\u8BA1\u7B97\u503C",kind:"scalar",requiresProperty:!1,toSQL({args:t,expression:e,expressions:r,sql:n}){if(e||r&&r.length>0)throw new p("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return ii(t.sql,$u(t.parameters),o=>n.value(o))},getOutputProperty({name:t,args:e,inputProperty:r,inputProperties:n}){if(r||n&&n.length>0)throw new p("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return wu(t,e)}},Eu=t=>{const e=new Set,r=n=>{for(const[o,i]of Object.entries(n)){if(o==="$and"||o==="$or"){for(const s of i)r(s);continue}e.add(o)}};return r(t),[...e]},Iu=t=>typeof t.pred!="string"?t:{...t,pred:{operator:"$sum",pred:t.pred,name:`${t.pred}\u5408\u8BA1`}},_u=(t,e,r)=>{const n=t.preds;if(n.filter(l=>l.operator==="$rank"&&l.query).length!==1)throw new p("AMBIGUOUS_RANK_TARGET","A LogicForm without groupby must contain exactly one $rank pred.query target");const i=Eu(r),[s]=i;if(i.length!==1||!s)throw new p("AMBIGUOUS_RANK_DIMENSION","$rank pred.query must reference exactly one property when groupby is omitted",{properties:i});const a=Z(t);a.groupby=[{pred:s,name:s}],a.preds=n.map(l=>{if(l.name!==e.name)return l;const d={...l};return delete d.query,Iu(d)}),delete a.sort,delete a.limit,delete a.limitBy,delete a.page,delete a.output,delete a.representation;const u=n.map(({name:l})=>l).filter(l=>!!l),c=Z(t);return c.from=a,c.query=r,c.preds=[{pred:s,name:s},...u.map(l=>({pred:l,name:l}))],delete c.groupby,delete c.having,delete c.entity_id,delete c.propertyResolve,c},Su={name:"$rank",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} rank`:`${t}\u6392\u540D`,kind:"window",windowFunction:"rank",rewriteLogicform({logicform:t}){if(t.groupby?.length)return;const e=t.preds?.find(r=>r.operator==="$rank"&&r.query);return e?.query?_u(t,e,e.query):void 0},validatePlan({pred:t,groupByNames:e}){if(!t.pred||Array.isArray(t.pred))throw new p("INVALID_WINDOW_OPERATOR_INPUT","$rank requires exactly one pred");if(e.length===0&&!t.query&&typeof t.pred!="string")throw new p("RANK_GROUPBY_OR_TARGET_REQUIRED","$rank requires groupby or a pred.query target used to infer the ranking dimension")},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},Ru={name:"$rowNumber",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Row number":"\u884C\u53F7",kind:"window",windowFunction:"rowNumber",getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},bu=new Set(["string","number","boolean","date","entity","object"]),fn=t=>{if(t==="timestamp"||t==="date")return{type:t,primal_type:"date"};if(typeof t=="string"&&bu.has(t))return{type:t,primal_type:t};throw new p("INVALID_CONSTANT_TYPE","$constant args.type must be timestamp, date, string, number, boolean, entity, or object")},Ou={name:"$constant",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Constant":"\u5E38\u91CF",kind:"scalar",requiresProperty:!1,normalizePred({pred:t}){if(t.pred!==void 0)throw new p("INVALID_CONSTANT_INPUT","$constant does not accept pred");return fn(t.args?.type),t},toSQL({args:t,sql:e}){return fn(t.type),e.value(t.value,t.type)},getOutputProperty({name:t,args:e}){return{name:t,...fn(e.type),isArray:!1}}},Nu={name:"$periodBoundary",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} at period ${e.boundary==="start"?"start":"end"}`:`${t}${e.boundary==="start"?"\u671F\u521D":"\u671F\u672B"}`,defaultNameKey:({args:t})=>`operator.$periodBoundary.${t.boundary==="start"?"start":"end"}`,kind:"scalar",toSQL({expression:t,args:e,sql:r}){if(!t)throw new p("PRED_PROPERTY_REQUIRED","$periodBoundary requires pred");const n=e.boundary;if(n!=="start"&&n!=="end")throw new p("INVALID_PERIOD_BOUNDARY_ARGS","$periodBoundary args.boundary must be start or end");const o=e.granularity;if(typeof o!="string")throw new p("END_OF_PERIOD_GRANULARITY_REQUIRED","$periodBoundary requires the input Property granularity");const i=r.dateBucket(t,o);return r.datePeriodBoundary?r.datePeriodBoundary(t,o,n):n==="start"?i:r.dateShift(r.dateShift(i,o,1),"second",-1)},planExpression({input:t,inputProperty:e,args:r}){if(!t)return;const n=e?.granularity??r.granularity;return{kind:"operator",operator:"$periodBoundary",input:t,args:{...r,granularity:n}}},normalizePred({pred:t,schema:e}){if(!t.pred||Array.isArray(t.pred))throw new p("INVALID_PERIOD_BOUNDARY_INPUT","$periodBoundary requires one pred");if(typeof t.pred=="string"){const r=e.properties.find(({id:n,name:o})=>n===t.pred||o===t.pred);return{...t,args:{...t.args,granularity:r?.granularity}}}return t},getOutputProperty({name:t,inputProperty:e,args:r}){if(!e||e.primal_type!=="date")throw new p("PERIOD_BOUNDARY_DATE_REQUIRED","$periodBoundary requires a date-valued pred");const n=e.granularity??r.granularity;if(typeof n!="string")throw new p("END_OF_PERIOD_GRANULARITY_REQUIRED","$periodBoundary requires the input Property granularity");return{...e,name:t,granularity:n,isArray:!1}}},si="__scalarExtremumInputs",mn=t=>{if(t.schema)return t.schema;if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred))return mn(t.pred);if(Array.isArray(t.pred)){const e=[...new Set(t.pred.flatMap(r=>typeof r=="string"?[]:mn(r)??[]))];if(e.length===1)return e[0]}},Pu=t=>{const e=Z(t);return delete e.from,delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,delete e.representation,delete e.output,e},Tu=(t,e)=>{if(e.args?.[si]===!0||!Array.isArray(e.pred))return;if(t.preds?.length!==1)throw new p("SCALAR_EXTREMUM_SINGLE_PROJECTION_REQUIRED",`${e.operator} with multiple pred inputs must be the only LogicForm projection`);const r=e.pred.map((o,i)=>{const s=typeof o=="string"?{pred:o}:Z(o),a=s.name??`__scalar_extremum_input_${i}__`,u=s.schema??mn(s);return{...s,name:a,...u?{schema:u}:{}}}),n=Pu(t);return n.preds=r,{version:t.version,from:n,preds:[{operator:e.operator,pred:r.map(({name:o})=>o),...e.name?{name:e.name}:{},args:{...e.args,[si]:!0}}],...t.having?{having:t.having}:{},...t.sort?{sort:t.sort}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.page!==void 0?{page:t.page}:{},...t.output?{output:t.output}:{},...t.representation?{representation:t.representation}:{}}},Lu=(t,e)=>{const r=t==="$least"?"MIN":"MAX",n=e.map(o=>`SELECT ${o} AS value`).join(" UNION ALL ");return`(SELECT ${r}(value) FROM (${n}) AS __scalar_extremum_values)`},Du=(t,e,r)=>{const[n,...o]=r??[];if(!n)throw new p("INVALID_OPERATOR_INPUTS",`${t} requires pred inputs`);if(o.some(({primal_type:i})=>i!==n.primal_type))throw new p("INCOMPATIBLE_OPERATOR_INPUTS",`${t} pred inputs must have the same primal type`);return{...n,name:e,isArray:!1}},ai=t=>({name:t,defaultName:({inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t==="$least"?"Least":"Greatest"} of ${e.join(", ")}`:`${e.join("\u3001")}\u4E2D\u7684${t==="$least"?"\u6700\u65E9\u503C":"\u6700\u665A\u503C"}`,kind:"scalar",requiresProperty:!1,normalizePred({pred:e}){if(!Array.isArray(e.pred)||e.pred.length<2)throw new p("INVALID_OPERATOR_INPUTS",`${t} requires at least two pred inputs`);return e},rewriteLogicform({logicform:e}){const r=e.preds?.[0];return r?.operator===t?Tu(e,r):void 0},toSQL(e){const r=st(t,e,2,Number.POSITIVE_INFINITY);return e.sql.scalarExtremum?.(t==="$least"?"least":"greatest",r)??Lu(t,r)},getOutputProperty({name:e,inputProperties:r}){return Du(t,e,r)}}),Cu=ai("$least"),qu=ai("$greatest"),yn={second:{en:"second",zh:"\u79D2"},minute:{en:"minute",zh:"\u5206\u949F"},hour:{en:"hour",zh:"\u5C0F\u65F6"},weekday:{en:"weekday",zh:"\u661F\u671F"},day:{en:"day",zh:"\u65E5"},week:{en:"week",zh:"\u5468"},month:{en:"month",zh:"\u6708"},quarter:{en:"quarter",zh:"\u5B63\u5EA6"},year:{en:"year",zh:"\u5E74"}},ku={name:"$length",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} length`:`${t}\u957F\u5EA6`,kind:"scalar",toSQL({expression:t,sql:e}){if(!t)throw new p("PRED_PROPERTY_REQUIRED","$length requires a pred");return e.stringLength(t)},getOutputProperty({name:t,inputProperty:e}){if(!e||e.primal_type!=="string"||e.isArray)throw new p("LENGTH_STRING_REQUIRED","$length requires a scalar string-valued pred");return{name:t,type:"int",primal_type:"number",isArray:!1}}},Uu=t=>({name:`$${t}`,defaultName:({operandName:e,locale:r})=>r.toLowerCase().startsWith("en")?`${e} ${yn[t].en}`:`${e}${yn[t].zh}`,kind:"scalar",toSQL({expression:e,sql:r}){if(!e)throw new p("PRED_PROPERTY_REQUIRED",`$${t} requires a pred`);return r.datePart(e,t)},getOutputProperty({name:e,inputProperty:r}){if(!r||r.primal_type!=="date"||r.isArray)throw new p("DATE_PART_DATE_REQUIRED",`$${t} requires a scalar date-valued pred`);return{name:e,type:"int",primal_type:"number",isArray:!1}}}),ju=Object.freeze(Object.keys(yn).map(Uu)),ci=Object.freeze([Ca,fu,Hc,Gc,vc,tu,Zc,qc,lu,uu,Vc,su,ou,ka,mu,ru,Jc,qa,yu,Bc,Qc,hu,Kc,Au,Su,Ru,Ou,Nu,Cu,qu,ku,...ju]),Mu={name:"boolean",primalType:"boolean",hydrateResult(t){return typeof t=="number"?t===1:t}},xu={name:"category",primalType:"string"},Vu={name:"currency",primalType:"number"},vu={name:"date",primalType:"date"},Yu={name:"duration",primalType:"number"},ui=(t,{property:e,requestEntity:r})=>!e.ref||t===void 0||t===null||typeof t=="object"&&!Array.isArray(t)?t:r(e.ref,t),Fu={name:"object",primalType:"object",hydrateResult:ui},Bu={name:"entity",primalType:"entity",hydrateResult:ui},Qu={name:"file",primalType:"string"},Hu={name:"humanName",primalType:"string"},Gu={name:"ID",primalType:"string"},zu={name:"image",primalType:"string"},Wu={name:"int",primalType:"number"},Ku={name:"name",primalType:"string"},Ju={name:"number",primalType:"number"},Xu={name:"order",primalType:"number"},Zu={name:"percentage",primalType:"number"},ed={name:"string",primalType:"string"},td={name:"timestamp",primalType:"date"},hn=Object.freeze([Gu,ed,Ku,Hu,xu,zu,Qu,Ju,Wu,Vu,Zu,Yu,Xu,Mu,td,vu,Bu,Fu]),rd=(t,e,r)=>{if(typeof t=="function")return t;if(typeof t!="string"||t.trim().length===0)return;const n=new Function(`return (${t})`)();if(typeof n!="function")throw new TypeError(`Operator ${r} ${e} must resolve to a function`);return n},di=t=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError("Operator definition must be an object");const e=t,r=e.name,n=typeof r=="string"?r:"",o=e.type,i=new Set(["defaultName","getOutputProperty","planInput","normalizePred","planExpression","periodBoundaryPolicy","validatePlan","rewriteLogicform","requiresPerPeriodEvaluation","toSQL","evaluate","createComponent"]),s=Object.fromEntries(Object.entries(e).filter(([a])=>!i.has(a)));s.name=r;for(const a of i){const u=rd(e[a],a,n);u&&(s[a]=u)}if(!s.getOutputProperty&&typeof o=="string"){const a=hn.find(({name:u})=>u===o);if(!a)throw new TypeError(`Semantic type is not registered: ${o}`);s.getOutputProperty=()=>({name:n,type:o,primal_type:a.primalType,isArray:!1})}return s};class cr{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){const r=di(e);if(!r.name)throw new p("INVALID_OPERATOR","Operator name must not be empty");if(typeof r.defaultName!="function")throw new p("INVALID_OPERATOR",`Operator must implement defaultName: ${r.name}`);if(this.#e.has(r.name))throw new p("OPERATOR_ALREADY_REGISTERED",`Operator is already registered: ${r.name}`,{operator:r.name});const n=r;if(!(n.kind==="scalar"&&(typeof n.toSQL=="function"||typeof n.evaluate=="function")||n.kind==="aggregate"&&typeof n.toSQL=="function"||n.kind==="component"&&typeof n.createComponent=="function"||n.kind==="window"&&typeof n.windowFunction=="string"||n.kind==="logical"&&typeof n.planExpression=="function"))throw new p("INVALID_OPERATOR",`Operator kind and implementation do not match: ${r.name}`);return this.#e.set(r.name,r),this}get(e){const r=this.#e.get(e);if(!r)throw new p("OPERATOR_NOT_FOUND",`Operator is not registered: ${e}`,{operator:e});return r}requiresPerPeriodEvaluation(e,r){return this.get(e).requiresPerPeriodEvaluation?.(r)??!1}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}}const nd=Object.freeze([...ci,...Go.flatMap(({operators:t})=>t??[])]),Ne=(t=[])=>new cr([...ci,...me(t).flatMap(({operators:e})=>e??[])]),dt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="logicform-subquery"&&typeof t.plan=="object"&&t.plan!==null,pi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="query-operator"&&typeof t.operator=="string",od=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="ordinal-query",li=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="expression-query",id=(t,e)=>{const r=ja(t,e);return{schemaId:t.id,propertyId:r.id,propertyName:r.name,physicalColumn:r.udf?.sql??r.id}},fi=(t,e,r)=>{const n=t.fieldReferences?.[r];return n?{schemaId:n.schemaId,propertyId:n.propertyId??n.column,propertyName:n.property,physicalColumn:n.sql??n.column}:id(e,r)},Dt=(t,e,r,n)=>{if(t.kind==="column")return{sources:[{schemaId:t.schemaId??r.id,propertyId:t.propertyId??t.column,propertyName:t.property,physicalColumn:t.column}],transformations:["projection"]};if(t.kind==="property-sql")return{sources:[{schemaId:t.schemaId,propertyId:t.propertyId,propertyName:t.property,physicalColumn:t.sql}],transformations:["property-sql"]};if(t.kind==="array-element")return{sources:[{schemaId:t.schemaId,propertyId:t.property,propertyName:t.property,physicalColumn:t.property}],transformations:["array-expand"]};if(t.kind==="window"){const u=[t.input,...t.partitionBy].map(c=>Dt(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:${t.function}`]}}if(t.kind==="cumulative"){const u=[t.input,...t.partitionBy,...t.orderBy.map(({expression:c})=>c)].map(c=>Dt(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:cumulative:${t.function}`]}}if(t.kind==="ordinal-encode"||t.kind==="ordinal-decode"){const u=Dt(t.input,e,r,n);return{sources:u.sources,transformations:[...u.transformations.filter(c=>c!=="projection"),`ordinal:${t.kind==="ordinal-encode"?"encode":"decode"}`]}}const o=[...t.input?[t.input]:[],...t.inputs??[]].map(u=>Dt(u,e,r,n)),i={sources:o.flatMap(({sources:u})=>u),transformations:o.flatMap(({transformations:u})=>u)},s=n.get(t.operator),a=new Set([...t.property?[t.property]:[],...s.dependencies??[],...ur(t.query)]);return{sources:[...i.sources,...[...a].filter(u=>!i.sources.some(c=>c.propertyName===u)).map(u=>fi(e,r,u))],transformations:[...i.transformations.filter(u=>u!=="projection"),`operator:${t.operator}`]}};function ur(t){if(!t)return[];const e=[];for(const[r,n]of Object.entries(t))if((r==="$and"||r==="$or")&&Array.isArray(n))for(const o of n)typeof o=="object"&&o!==null&&!Array.isArray(o)&&e.push(...ur(o));else r==="$expr"&&li(n)?e.push(...n.properties):r.startsWith("$")||e.push(r);return e}const Ue=t=>t.kind==="window"?[...Ue(t.input),...t.partitionBy.flatMap(Ue)]:t.kind==="cumulative"?[...Ue(t.input),...t.partitionBy.flatMap(Ue),...t.orderBy.flatMap(({expression:e})=>Ue(e))]:t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?Ue(t.input):t.kind==="operator"?[...ur(t.query),...t.input?Ue(t.input):[],...(t.inputs??[]).flatMap(Ue)]:[],mi=(t,e,r,n=Ne(),o)=>{if(t.subplans){const s=t.subplans.map(u=>mi(u,e,r,n,o)),a=new Map;for(const u of s){u.source.connectionId&&a.set(u.source.connectionId,u.source.provider);for(const c of u.source.connections??[])a.set(c.connectionId,c.provider)}return{source:{schemaId:e.id,schemaName:e.name,physicalTable:s.map(({source:u})=>u.physicalTable).join(", "),provider:r.kind,connections:[...a].map(([u,c])=>({connectionId:u,provider:c}))},outputs:t.projections.map(({name:u})=>{const c=s.flatMap(({outputs:l})=>l.filter(d=>d.name===u));return{name:u,sources:c.flatMap(({sources:l})=>l),transformations:[...new Set([...c.flatMap(({transformations:l})=>l),"compose"])]}}),filters:s.flatMap(({filters:u})=>u)}}const i=t.connectionId&&o?o(t.connectionId):r;return{source:{schemaId:e.id,schemaName:e.name,physicalTable:[t.source,...(t.enrichmentJoins??[]).map(({source:s})=>s)].filter(Boolean).join(", "),provider:i.kind,...t.connectionId?{connectionId:t.connectionId}:{}},outputs:t.projections.map(s=>({name:s.name,...Dt(s.expression,t,e,n)})),filters:[...new Set([...ur(t.query),...t.projections.flatMap(({expression:s})=>Ue(s))])].map(s=>fi(t,e,s))}},Ie=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.version=="string"&&(typeof t.schema=="string"||typeof t.from=="object"),sd=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,yi=t=>{const e=sd.exec(t);if(!e)return;const r=Number(e[1]),n=Number(e[2]),o=Number(e[3]??0);if(!(r>23||n>59||o>59))return{hour:r,minute:n,second:o}},hi=t=>{const e=t.freshness;if(e){if(e.mode==="ttl"){if(!Number.isInteger(e.ttlSeconds)||e.ttlSeconds<=0)throw new p("INVALID_SOURCE_FRESHNESS","TTL freshness requires a positive integer ttlSeconds");return}if(e.mode==="daily"){if(!yi(e.expireAt))throw new p("INVALID_SOURCE_FRESHNESS","Daily freshness expireAt must use HH:mm or HH:mm:ss");if(e.timeZone)try{new Intl.DateTimeFormat("en-US",{timeZone:e.timeZone}).format()}catch{throw new p("INVALID_SOURCE_FRESHNESS",`Invalid freshness timeZone: ${e.timeZone}`)}}}},ad=new Set(["second","minute","hour","day","week","month","quarter","year"]),gn=t=>typeof t=="string"&&ad.has(t),$n=(t,e=me())=>gn(t)||typeof t=="object"&&t!==null&&!Array.isArray(t)&&e.some(r=>{const n=r.mappingGranularity;return n!==void 0&&n.kind===t.kind&&n.isGranularity(t)});class wn{#e=new Map;plugins;constructor(e=[],r=[]){this.plugins=me(r);for(const n of e)this.register(n)}register(e){for(const s of this.plugins){const a=s.schemaMapping?.validate?.(e);if(a)throw new p("INVALID_SCHEMA_MAPPING_PLUGIN",`Schema mapping is rejected by plugin ${s.name}: ${a}`,{plugin:s.name,reason:a})}if(!e.schemaId)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping schemaId must not be empty");if(!e.source)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping source must not be empty");if(e.sourceSql!==void 0&&e.sourceSql.trim().length===0)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping sourceSql must not be empty");if(e.id!==void 0&&!e.id)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping id must not be empty");if(e.connectionId.trim().length===0)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping connectionId must not be empty");if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new p("INVALID_SCHEMA_MAPPING","Schema mapping priority must be finite");if("dimensions"in e)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping dimensions is removed; declare time granularity on property mapping items");const r=new Set,n=new Set;for(const s of e.enrichments??[]){if(!s.id||r.has(s.id))throw new p("INVALID_SCHEMA_MAPPING","Schema mapping enrichment ids must be non-empty and unique");if(!s.source||s.source===e.source||n.has(s.source))throw new p("INVALID_SCHEMA_MAPPING","Schema mapping enrichment sources must be non-empty and unique");if(s.sourceSql!==void 0&&s.sourceSql.trim().length===0)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping enrichment sourceSql must not be empty");if(s.on.length===0||s.on.some(({baseColumn:a,targetColumn:u})=>!a||!u))throw new p("INVALID_SCHEMA_MAPPING","Schema mapping enrichments require non-empty baseColumn/targetColumn keys");if(s.temporal?.kind==="point"&&!s.temporal.pointColumn)throw new p("INVALID_SCHEMA_MAPPING","Point-in-time Schema mapping enrichments require pointColumn");hi(s),r.add(s.id),n.add(s.source)}for(const s of e.mappings??[]){if(s.granularity!==void 0&&(s.mappingType!=="property"||!$n(s.granularity,this.plugins)))throw new p("INVALID_SCHEMA_MAPPING","Schema mapping granularity requires a property item and a supported physical granularity");if(s.mappingType==="property"&&(!s.sourceColumn||!s.propertyTarget?.length))throw new p("INVALID_SCHEMA_MAPPING","Schema mapping property items require sourceColumn and propertyTarget");if(s.mappingType==="predItem"&&(!s.sourceColumn||!s.predItem?.operator||typeof s.predItem.pred!="string"))throw new p("INVALID_SCHEMA_MAPPING","Schema mapping PredItem items require sourceColumn and predItem operator/pred");if(s.sourceRef!==void 0&&(s.mappingType!=="property"||!r.has(s.sourceRef)))throw new p("INVALID_SCHEMA_MAPPING","Schema mapping sourceRef requires a property item and a registered enrichment id")}hi(e);const o=this.#e.get(e.schemaId)??[],i=e.id??e.source;if(o.some(s=>s.connectionId===e.connectionId&&((s.id??s.source)===i||s.source===e.source)))throw new p("SCHEMA_MAPPING_ALREADY_REGISTERED",`Schema mapping is already registered: ${e.schemaId}:${e.connectionId}:${i}`,{schemaId:e.schemaId,connectionId:e.connectionId,mappingId:i});return this.#e.set(e.schemaId,[...o,e]),this}get(e,r){const n=this.list(e),o=r===void 0?n:n.filter(s=>s.connectionId===r);if(o.length===0)throw new p("SCHEMA_MAPPING_CONNECTION_NOT_FOUND",`Schema ${e} has no mapping on connection ${r}`,{schemaId:e,connectionId:r});if(o.length===1)return o[0];const i=o.filter(s=>(s.mappings??[]).length===0);if(i.length===1)return i[0];throw new p("SCHEMA_MAPPING_AMBIGUOUS",r===void 0?`Schema ${e} has multiple mappings and requires LogicForm-based selection`:`Schema ${e} has multiple mappings on connection ${r} and requires LogicForm-based selection`,{schemaId:e,...r===void 0?{}:{connectionId:r},mappingIds:o.map(s=>s.id??s.source)})}list(e){const r=this.#e.get(e);if(!r||r.length===0)throw new p("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${e}`,{schemaId:e});return r}findSource(e,r,n){return this.#e.get(e)?.find(o=>o.source===r&&(n===void 0||o.connectionId===n))}}const cd=t=>{if(t.tablePath?.trim())return t.tablePath;const e=[t.physicalDatabase,t.physicalSchema,t.physicalTable].filter(r=>!!r?.trim());if(e.length>0)return e.join(".");if(t.sourceSql?.trim())return t.sourceSql;throw new p("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping ${t.id} has no physical source`)},ud=(t,e=[])=>{const r=me(e);if(!t.schemaSid||!t.datasourceSid)throw new p("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping requires schemaSid and datasourceSid");if(t.enabled===!1)throw new p("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping is disabled: ${t.id}`);if("dimensions"in t)throw new p("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping dimensions is removed; set granularity on property items");const n=[];for(const o of t.mappings){if(o.granularity!==void 0&&(o.mappingType!=="property"||!$n(o.granularity,r)))throw new p("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires a property item and a supported physical granularity");if(o.mappingType==="property"){if(!o.sourceColumn||!o.propertyTarget?.length){if(o.granularity!==void 0)throw new p("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires sourceColumn and propertyTarget");continue}n.push(o);continue}o.mappingType==="predItem"&&(!o.sourceColumn||!o.predItem?.operator||typeof o.predItem.pred!="string"||n.push(o))}return{id:String(t.id),schemaId:t.schemaSid,connectionId:t.datasourceSid,source:cd(t),...t.sourceSql?{sourceSql:t.sourceSql}:{},...t.enrichments?{enrichments:t.enrichments}:{},mappings:n}};class gi{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new p("INVALID_SEMANTIC_RULE","Semantic rule name must not be empty");if(this.#e.has(e.name))throw new p("SEMANTIC_RULE_ALREADY_REGISTERED",`Semantic rule is already registered: ${e.name}`,{rule:e.name});return this.#e.set(e.name,e),this}resolveProjection(e){return[...this.#e.values()].reduce((r,n)=>n.resolveProjection?.({...e,outputProperty:r})?.outputProperty??r,e.outputProperty)}resolveQuery(e){return[...this.#e.values()].reduce((r,n)=>n.resolveQuery?.({...e,...r?{query:r}:{}})??r,e.query)}rules(){return[...this.#e.values()]}}const $i=(t=[])=>new gi([...me(t).flatMap(e=>e.plannerSemantics??[])]);se.extend(mo),se.extend(Rt),se.extend(Kt);const pt=["second","minute","hour","day","week","month","quarter","year"],dd=new Set(["$second","$minute","$hour","$day","$week","$month","$quarter","$year"]),pd="YYYY-MM-DD HH:mm:ss",lt=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),ld=(t,e)=>t==="week"?e==="week":e==="week"?pt.indexOf(t)<=pt.indexOf("day"):pt.indexOf(t)<=pt.indexOf(e),wi=(t,e,r)=>{if(typeof t!="string")return"second";const n=se(t,pd,!0);if(!n.isValid())return"second";for(const o of[...pt].reverse()){const i=o==="week"?n.startOf("isoWeek"):n.startOf(o),s=o==="week"?n.endOf("isoWeek"):n.endOf(o),a=e==="lower"?r?i:s:r?s:i;if(n.isSame(a.millisecond(0),"second"))return o}return"second"},Ai=t=>{if(!t||typeof t!="object"||Array.isArray(t))return["second"];const e=Object.entries(t);return e.length===0?["second"]:e.flatMap(([r,n])=>dd.has(r)?[r.slice(1)]:r==="$weekday"?["day"]:r==="$and"||r==="$or"?Array.isArray(n)?n.flatMap(Ai):["second"]:r==="$gte"||r==="$gt"?[wi(n,"lower",r==="$gte")]:r==="$lte"||r==="$lt"?[wi(n,"upper",r==="$lte")]:["second"])},fd=(t,e,r)=>{if(e.primal_type==="date"){if(t.operator){const n=r.get(t.operator).groupedSourceTimeGranularity?.({pred:t,property:e});if(n&&pt.includes(n))return n}return e.granularity??"day"}},md=(t,e,r,n,o=me(),i=Ne(o))=>{const s=r.mappings??[],a=s.filter(h=>h.granularity!==void 0),u={schema:e,mapping:r,...n?{resolveSchema:n}:{}};if(a.some(h=>!$n(h.granularity,o)))return"physical granularity is not supported by the active plugins";if(a.find(h=>gn(h.granularity)&&!h.propertyTarget?.every(w=>lt(e,w)?.primal_type==="date")))return"physical time granularity requires mapped date Properties";for(const h of a)for(const w of o){const A=w.mappingGranularity;if(!A||!A.isGranularity(h.granularity))continue;const _=A.validateItem?.(h,u);if(_)return _}if(!(a.length>0))return;const d=h=>s.find(w=>w.mappingType==="property"&&w.propertyTarget?.some(A=>lt(e,A)?.id===h.id)),f=(h,w,A="filterOrGroup")=>{const _=lt(e,h);if(!_)return`property is not available: ${h}`;const E=d(_);if(!E&&!(A==="operand"&&s.some($=>$.mappingType==="predItem"&&typeof $.predItem?.pred=="string"&&lt(e,$.predItem.pred)?.id===_.id)))return`property is not available on grouped source: ${h}`;if(A==="filterOrGroup"&&_.primal_type==="number"&&_.type!=="category"&&_.type!=="ID")return`measure cannot be used as a grouped source dimension: ${h}`;if(_.primal_type==="date"&&(!E?.granularity||!gn(E.granularity)||!ld(E.granularity,w??_.granularity??"day")))return`time dimension ${h} is too coarse for ${w}`};function m(h){if(h)for(const[w,A]of Object.entries(h)){if(A===void 0)continue;if(w==="$and"||w==="$or"){if(!Array.isArray(A))return"unsupported dimension query";for(const $ of A){const b=m($);if(b)return b}continue}if(w==="$expr"){if(typeof A!="object"||A===null||Array.isArray(A))return"unsupported expression query";const $=A.pred;if(typeof $!="object"||$===null||Array.isArray($))return"unsupported expression query";const b=y($);if(b)return b;continue}if(w.startsWith("$"))return"unsupported dimension query";const _=lt(e,w);if(!_)return`dimension property is not available: ${w}`;const E=_.primal_type==="date"?Ai(A):[void 0];for(const $ of E){const b=f(w,$);if(b)return b}}}function y(h){const w=m(h.query);if(w)return w;const A=Array.isArray(h.pred)?h.pred:h.pred===void 0?[]:[h.pred];for(const _ of A){const E=typeof _=="string"?f(_,void 0,"operand"):y(_);if(E)return E}}const g=m(t.query);if(g)return g;if(!t.preds?.length)return"grouped source requires an aggregating PredItem";for(const h of t.preds){const w=y(h);if(w)return w;if(typeof h.pred!="string"||!h.operator||!i.get(h.operator).supportsGroupedSourceRollup)return`PredItem ${h.operator??"(projection)"} cannot be rolled up from a grouped source`}for(const h of t.groupby??[]){if(typeof h.pred!="string")return"computed groupby is not covered by the grouped source";const w=lt(e,h.pred);if(!w)return`groupby property is not available: ${h.pred}`;if(h.operator!==void 0&&!i.get(h.operator).supportsGroupedSourceGroupby&&!o.some(_=>_.mappingGranularity?.supportsGroupby?.(h)))return`computed groupby is not covered: ${h.pred}`;const A=f(h.pred,fd(h,w,i));if(A)return A}for(const h of o){const w=h.mappingGranularity?.candidateReason?.(t,u);if(w)return w}};function Ct(t){return[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Ct(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Ct(e)):[]]}const An=t=>t.id??t.source,dr=(t,e)=>{if(t===e)return!0;if(t instanceof Date||e instanceof Date)return t instanceof Date&&e instanceof Date&&t.getTime()===e.getTime();if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((o,i)=>dr(o,e[i]));if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const r=Object.entries(t),n=e;return r.length===Object.keys(n).length&&r.every(([o,i])=>Object.prototype.hasOwnProperty.call(n,o)&&dr(i,n[o]))},ft=t=>{if(!t)return[];const e=[];for(const[r,n]of Object.entries(t))if(n!==void 0){if(r==="$or")return;if(r==="$and"){if(!Array.isArray(n))return;for(const o of n){const i=ft(o);if(!i)return;e.push(...i)}continue}if(r==="$expr"){if(typeof n!="object"||n===null||Array.isArray(n))return;const o=n.pred;if(typeof o!="object"||o===null||Array.isArray(o))return;const i=Ct(o);if(i.length===0)return;e.push(...i.map(s=>({property:s,condition:{$expr:n}})));continue}if(r.startsWith("$"))return;e.push({property:r,condition:n})}return e},En=(t,e,r)=>{if(!t)return;const n={};for(const[o,i]of Object.entries(t))if(i!==void 0){if(o==="$and"&&Array.isArray(i)){const s=i.map(a=>En(a,e,r)).filter(a=>a!==void 0);s.length>0&&(n[o]=s);continue}o!=="$or"&&e.some(s=>pr(r,s.property,o)&&dr(s.condition,i))||(n[o]=i)}return Object.keys(n).length>0?n:void 0},Ke=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),pr=(t,e,r)=>e===r||Ke(t,e)?.id===Ke(t,r)?.id&&Ke(t,e)!==void 0&&Ke(t,r)!==void 0,_e=(t,e,r)=>lr(t,e,r)?.column,lr=(t,e,r)=>{const n=Ke(e,r);if(!n)return;const o=(t.mappings??[]).find(i=>i.mappingType==="property"&&i.propertyTarget?.some(s=>pr(e,s,r)));return o?.sourceColumn?{column:o.sourceColumn,...o.sourceRef?{sourceRef:o.sourceRef}:{}}:(t.mappings??[]).some(i=>i.mappingType==="property")?void 0:{column:n.id}},In=(t,e,r)=>!(t.mappings??[]).some(n=>n.mappingType==="property")||_e(t,e,r)!==void 0,Ei=(t,e,r)=>{if(!t||!(e.mappings??[]).some(i=>i.mappingType==="property"))return;const n=ft(t);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:i})=>!In(e,r,i));return o?`query property is not available: ${o.property}`:void 0},yd=(t,e,r,n,o)=>{if(t.match.schema!==void 0&&t.match.schema!==n)return!1;const i=typeof e.pred=="string"?Ke(r,e.pred):void 0,s=Ke(r,t.match.pred),a=typeof e.pred=="string"&&pr(r,e.pred,t.match.pred)&&!!(i&&s);if(e.operator!==t.match.operator||!a||Array.isArray(e.pred)||e.args&&Object.keys(e.args).length>0)return!1;const u=ft(t.match.query);return u!==void 0&&u.every(c=>o.some(l=>pr(r,l.property,c.property)&&dr(l.condition,c.condition)))},hd=(t,e,r,n,o,i=Ne(o))=>{const s=(r.mappings??[]).flatMap(h=>{if(h.mappingType!=="predItem"||!h.sourceColumn||!h.predItem||!h.predItem.operator||typeof h.predItem.pred!="string")return[];const w=h.predItem,A=w.operator,_=w.pred;return!A||typeof _!="string"?[]:[{match:{operator:A,pred:_,...w.schema?{schema:w.schema}:{},...w.query?{query:w.query}:{}},column:h.sourceColumn}]}),a=(r.mappings??[]).some(h=>h.mappingType==="property");if(s.length===0&&!a){const h={schema:e,mapping:r,...n?{resolveSchema:n}:{}};for(const w of o??[]){const A=w.schemaMapping?.candidateReason?.(t,h);if(A)return A}return{mapping:r,logicform:t,predRewrites:[],priority:r.priority??0,specificity:0}}const u=ft(t.query);if(!u&&s.length>0)return"query contains $or or another unsupported logical expression";const c=Z(t),l=[],d=[];for(const[h,w]of(t.preds??[]).entries()){const A=ft(w.query);if(!A&&s.length>0)return`PredItem ${h} query contains an unsupported logical expression`;if(s.length>0){const E=[...u??[],...A??[]],$=s.filter(j=>yd(j,w,e,w.schema??e.id,E));if($.length===0)return`PredItem ${h} is not mapped`;if($.length>1)return`PredItem ${h} matches multiple mapping rules`;const b=$[0],N=ft(b.match.query)??[];d.push(...N);const k=c.preds?.[h];if(k){const j=En(k.query,N,e);j?k.query=j:delete k.query}l.push({predIndex:h,column:b.column});continue}const _=Ct(w).find(E=>!In(r,e,E));if(_)return`PredItem ${h} property is not available: ${_}`}const f=En(c.query,d,e);f?c.query=f:delete c.query;const m=Ei(c.query,r,e);if(m)return m;for(const[h,w]of(c.preds??[]).entries()){const A=Ei(w.query,r,e);if(A)return`PredItem ${h} ${A}`}for(const h of c.groupby??[]){const A=Ct(h).find(_=>!In(r,e,_));if(A)return`groupby property is not available: ${A}`}const y=md(c,e,r,n,o,i);if(y)return y;const g={schema:e,mapping:r,...n?{resolveSchema:n}:{}};for(const h of o??[]){const w=h.schemaMapping?.candidateReason?.(c,g);if(w)return w}return{mapping:r,logicform:c,predRewrites:l,priority:r.priority??0,specificity:l.length}},gd=(t,e,r,n={})=>{const o=n.plugins?me(n.plugins):r.plugins,i=n.operators??Ne(n.plugins),s=[],a=[];for(const d of r.list(e.id)){const f=hd(t,e,d,n.resolveSchema,o,i);typeof f=="string"?a.push({mappingId:An(d),reason:f}):s.push(f)}if(s.length===0){const d=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id;throw new p("QUERY_NOT_COVERED_BY_DATA_SOURCE",`Schema\u300C${d}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u4E0D\u652F\u6301\u6B64\u95EE\u9898\u3002\u5982\u9700\u652F\u6301\uFF0C\u9700\u8981\u63A5\u5165\u660E\u7EC6\u5C42\u6570\u636E\uFF0C\u8BF7\u8054\u7CFB\u6570\u636E\u7BA1\u7406\u5458\u3002`,{schemaId:e.id,requiredDataLayer:"detail",rejectedMappings:a})}const u=n.preferredConnectionId===void 0?[]:s.filter(({mapping:d})=>d.connectionId===n.preferredConnectionId),l=(u.length>0?u:s).reduce((d,f)=>f.priority>d.priority||f.priority===d.priority&&f.specificity>d.specificity?f:d);for(const d of s){if(d===l)continue;let f;u.length>0&&d.mapping.connectionId!==n.preferredConnectionId?f=`connection ${d.mapping.connectionId} does not match preferred connection ${n.preferredConnectionId}`:d.priority<l.priority?f=`priority ${d.priority} is lower than selected priority ${l.priority}`:d.specificity<l.specificity?f=`specificity ${d.specificity} is lower than selected specificity ${l.specificity}`:f="priority and specificity tie; an earlier registered mapping was selected",a.push({mappingId:An(d.mapping),reason:f})}return{mapping:l.mapping,logicform:l.logicform,predRewrites:l.predRewrites,selection:{schemaId:e.id,selectedMappingId:An(l.mapping),rejectedMappings:a}}},qt=(t,e)=>!!(t.operator&&e.get(t.operator).kind==="component"),kt=(t,e)=>qt(t,e)?!0:t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?kt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&kt(r,e)),Ii=(t,e)=>t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?kt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&kt(r,e)),_i=t=>t.name??(typeof t.pred=="string"?t.pred:void 0),$d=(t,e)=>{const r=t.preds??[];if(!r.some(m=>!qt(m,e)&&Ii(m,e)))return;const n=new Set([...r.map(({name:m})=>m).filter(m=>!!m),...(t.groupby??[]).map(_i).filter(m=>!!m)]);let o=0;const i=()=>{let m;do m=`__nested_component_input_${o}__`,o+=1;while(n.has(m));return n.add(m),m},s=[],a=m=>{const y=i();return s.push(typeof m=="string"?{pred:m,name:y}:{...Z(m),name:y}),y},u=m=>{if(m.query)throw new p("UNSUPPORTED_COMPONENT_NESTING","An operator above a component cannot define pred.query; apply the query inside a materialized input");const y=Z(m);return Array.isArray(m.pred)?y.pred=m.pred.map(g=>typeof g=="string"||!kt(g,e)||qt(g,e)?a(g):u(g)):m.pred&&typeof m.pred=="object"&&(y.pred=qt(m.pred,e)?a(m.pred):u(m.pred)),y},c=r.map(m=>{const y=m.name;if(!y)throw new p("MISSING_PRED_NAME","Nested component rewrite requires every projection to have a name");return!qt(m,e)&&Ii(m,e)?{...u(m),name:y}:(s.push({...Z(m),name:y}),{pred:y,name:y})}),l=Z(t);l.preds=s,delete l.having,delete l.sort,delete l.limit,delete l.limitBy,delete l.page,delete l.output,delete l.representation;const d=(t.groupby??[]).map(m=>{const y=_i(m);if(!y)throw new p("MISSING_PRED_NAME","Nested component rewrite requires every groupby projection to have a name");return{pred:y,name:y}}),f=Z(t);return f.from=l,f.preds=[...d,...c],delete f.query,delete f.groupby,delete f.entity_id,delete f.propertyResolve,f},wd=(t,e)=>`result:${t}:${e.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,Si=(t,e)=>{const r=(t.columnProperties??[]).map(n=>({...n,id:n.name}));return{id:wd(t.schemaId,t.columnProperties??[]),name:`${e.name} result`,type:e.type,temporalSemantics:"normal",properties:r}},Ri=(t,e)=>({...Si(t,e),id:e.id,name:e.name,type:e.type}),_n=t=>{if(!t.name)throw new p("MISSING_PRED_NAME","Planner requires every normalized PredItem to have a name");return t.name},fr=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?fr(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:fr(e)):[]],Sn=(t,e)=>({...t,...typeof t.pred=="string"?{pred:e(t.pred)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Sn(t.pred,e)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(r=>typeof r=="string"?e(r):Sn(r,e))}:{}}),bi=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(o=>bi(o,e))];if(r==="$expr"&&typeof n=="object"&&n!==null&&!Array.isArray(n)){const o=n.pred;if(typeof o=="object"&&o!==null&&!Array.isArray(o))return[r,{...n,pred:Sn(o,e)}]}return[r.startsWith("$")?r:e(r),n]})),Rn=(t,e,r)=>{const n=new Set(r),o=(i,s)=>{if(!(Ie(i)||i===null)){if(Array.isArray(i)){i.forEach(a=>o(a,s));return}if(typeof i=="object"){Object.entries(i).forEach(([a,u])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(a)||o(u,a)});return}if(!(s&&["$exists","$regex","$contains","$startsWith","$length"].includes(s))&&(typeof i!="string"||!n.has(i)))throw new p("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${e} does not contain value: ${JSON.stringify(i)}`,{property:e,value:i})}};o(t)},Oi=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(i=>Oi(i,e))];if(r==="$expr")throw new p("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const o=e.find(({name:i})=>i===r)?.comparable;return o&&Rn(n,r,o.values),[r,o?{kind:"ordinal-query",comparable:o,condition:n}:n]})),Ad=(t,e,r)=>{if(!e.udf)return{};const o=e.udf.sql.includes("$TS")?t.properties.find(({type:i})=>i==="timestamp")?.id:void 0;return{sql:e.udf.sql,...o?{timestampColumn:o}:{},...o&&r?{timestampQualifier:r}:{}}},Ni=t=>t.sql?{kind:"property-sql",schemaId:t.schemaId,property:t.property,propertyId:t.column,sql:t.sql,qualifier:t.qualifier,...t.timestampColumn?{timestampColumn:t.timestampColumn}:{},...t.timestampQualifier?{timestampQualifier:t.timestampQualifier}:{}}:{kind:"column",...t},Pi=(t,e,r={})=>({name:t,type:e.type,primal_type:e.primal_type,isArray:e.isArray,...e.description!==void 0?{description:e.description}:{},...e.ref?{ref:e.ref}:{},...e.comparable?{comparable:e.comparable}:{},...r}),mt=(t,e,r,n,o,i,s,a,u="projection")=>{const c=_n(t);if(u==="groupby"&&t.query)throw new p("GROUPBY_QUERY_NOT_ALLOWED","A groupby expression cannot define pred.query");if(!t.operator){if(typeof t.pred!="string")throw new p("PRED_PROPERTY_REQUIRED","A projection must reference a property");const E=r(t.pred);return{expression:Ni(E.field),outputProperty:Pi(E.reference,E.property),sourceProperty:E.property,sourceField:E.field}}const l=e.get(t.operator);if(u==="groupby"&&l.kind!=="scalar")throw new p("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(u==="groupby"&&!l.toSQL)throw new p("JAVASCRIPT_OPERATOR_NOT_ALLOWED_IN_GROUPBY",`JavaScript-only operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(l.planInput&&typeof t.pred!="string")throw new p("OPERATOR_DIRECT_PROPERTY_REQUIRED",`${t.operator} requires a direct property pred`);const d=l.planInput&&typeof t.pred=="string"?l.planInput({reference:t.pred,args:t.args??{},schema:s,...a?{resolveSchema:a}:{}}):void 0,f=d?.reference??t.pred,m=d?.args??t.args??{},y=f&&typeof f=="object"&&!Array.isArray(f)?mt(f,e,r,n,o,i,s,a,u):typeof f=="string"?mt({pred:f,name:f},e,r,n,o,i,s,a,u):void 0,g=Array.isArray(f)?f.map(E=>mt(typeof E=="string"?{pred:E,name:E}:E,e,r,n,o,i,s,a,u)):[];if(l.requiresProperty!==!1&&!y&&g.length===0)throw new p("PRED_PROPERTY_REQUIRED",`${t.operator} requires a property`);const h=c,w=l.getOutputProperty?.({name:h,...y?.sourceProperty?{property:y.sourceProperty}:{},...y?{inputProperty:{...y.outputProperty,name:h}}:{},...g.length>0?{inputProperties:g.map(({outputProperty:E})=>E)}:{},args:m}),A=w?.description??l.description??y?.outputProperty.description,_={...w??(y?Pi(h,y.outputProperty,{isArray:!1}):{name:h,type:"number",primal_type:"number",isArray:!1}),...A!==void 0?{description:A}:{}};if(l.planExpression){const E=l.planExpression({pred:t,...y?{input:y.expression,inputProperty:y.outputProperty}:{},inputs:g.map(({expression:$})=>$),args:m,resolveKey:o,getOperator:$=>e.get($),planQuery:i});if(E)return{expression:E,outputProperty:_,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}}if(l.kind==="window"){if(!y||g.length>0||t.query)throw new p("INVALID_WINDOW_OPERATOR_INPUT",`${t.operator} requires exactly one nested pred and does not accept pred.query`);const E=t.args?.direction??"desc";if(E!=="asc"&&E!=="desc")throw new p("INVALID_WINDOW_ARGS",`${t.operator} direction must be asc or desc`);const $=t.args?.partitionBy??[];if(!Array.isArray($)||$.some(b=>typeof b!="string"))throw new p("INVALID_WINDOW_ARGS",`${t.operator} partitionBy must be an array of groupby names`);return{expression:{kind:"window",function:l.windowFunction,input:y.expression,partitionBy:$.map(b=>n(String(b))),direction:E==="asc"?"ASC":"DESC"},outputProperty:_}}return{expression:{kind:"operator",operator:t.operator,args:m,...t.query?{query:i(t.query)}:{},...y?{input:y.expression}:{},...g.length>0?{inputs:g.map(({expression:E})=>E)}:{},...y?.sourceProperty?{property:y.sourceProperty.name,column:y.sourceProperty.id}:{},...y?.sourceField?{qualifier:y.sourceField.qualifier,schemaId:y.sourceField.schemaId}:{}},outputProperty:_,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}},Ed=(t,e,r,n,o,i,s,a,u,c,l,d=t)=>{const f=_n(t),m=typeof t.pred=="string"?t.pred:void 0,y=!c||!m?r:A=>{const _=r(A);return A===m?{..._,field:{..._.field,column:c}}:_},g=l?{...t,operator:l}:t,h=mt(g,e,y,n,o,i,s,a),w=u?.resolveProjection({pred:d,schema:s,...h.sourceProperty?{sourceProperty:h.sourceProperty}:{},outputProperty:{...h.outputProperty,name:f},...d.operator?{operator:e.get(d.operator)}:{}})??{...h.outputProperty,name:f};return{name:f,expression:h.expression,outputProperty:w}},Id=t=>{const e=new Set;for(const r of t){if(r.name==="_id")throw new p("RESERVED_OUTPUT_NAME","Output name _id is reserved for executor-owned row identity");if(e.has(r.name))throw new p("DUPLICATE_OUTPUT_NAME",`Duplicate output name: ${r.name}`);e.add(r.name)}},bn=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new p("SCHEMA_RESOLVER_REQUIRED",`Cannot plan nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n},_d=(t,e,r,n,o,i)=>{if(e.length<2)throw new p("COMPOSITION_REQUIRES_MULTIPLE_BRANCHES","A cross-Schema plan requires at least two branches");const s=e.map(g=>Pe(g,bn(g,r,i),n,o,i)),a=s[0]?.groupBy.map(({name:g})=>g)??[];for(const g of s){const h=g.groupBy.map(({name:w})=>w);if(h.length!==a.length||h.some((w,A)=>w!==a[A]))throw new p("INCOMPATIBLE_COMPOSITION_GROUPBY","All composed LogicForm objects must have the same groupby output names in the same order",{expected:a,received:h});if(g.rowIdentity.kind!==(a.length>0?"group":"singleton"))throw new p("UNSTABLE_COMPOSITION_IDENTITY","Composed LogicForm objects must be grouped or aggregate to a singleton row")}const u=[],c=[],l=new Map;s.forEach((g,h)=>{g.projections.forEach((w,A)=>{const _=a.includes(w.name),E=l.get(w.name);if(E!==void 0&&!_)throw new p("DUPLICATE_COMPOSITION_OUTPUT",`Composed LogicForm objects produce the same output: ${w.name}`,{name:w.name,childIndexes:[E,h]});if(E!==void 0)return;l.set(w.name,h),u.push({name:w.name,expression:{kind:"column",property:w.name,column:w.name}});const $=g.columnProperties?.[A];$&&c.push($)})});const d=new Set(u.map(({name:g})=>g)),f=Object.entries(t.sort??{}).map(([g,h])=>{if(!d.has(g))throw new p("INVALID_SORT",`Sort field is not an output: ${g}`);const w=c.find(A=>A.name===g);return{name:g,direction:h===1?"ASC":"DESC",...w?.comparable?{comparable:w.comparable}:{},...w?.comparable?{expression:{kind:"column",property:g,column:g}}:{}}}),m=t.limitBy===void 0||a.length<2?void 0:{count:t.limitBy,partitionBy:a.slice(0,-1),orderBy:f.length>0?f:(()=>{const g=a.at(-1)??"",h=c.find(w=>w.name===g);return[{name:g,direction:"ASC",...h?.comparable?{comparable:h.comparable}:{}}]})()},y=t.limitBy!==void 0&&a.length<2?{kind:"rows",page:1,pageSize:t.limitBy}:t.limit===void 0?void 0:t.limit>0&&t.limit<1?{kind:"ratio",page:t.page??1,ratio:t.limit}:{kind:"rows",page:t.page??1,pageSize:t.limit};return{schemaId:r.id,source:"",subplans:s,fields:Object.fromEntries(u.map(({name:g})=>[g,g])),projections:u,columnProperties:c,groupBy:u.filter(({name:g})=>a.includes(g)),...t.having?{having:Oi(t.having,c)}:{},orderBy:f,rowIdentity:a.length>0?{kind:"group",names:a,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"},...m?{groupLimit:m}:{},...y?{pagination:y}:{}}},Pe=(t,e,r=Ne(),n=new wn,o={})=>{const i=[...new Set((t.preds??[]).map(I=>I.schema).filter(I=>!!(I&&I!==e.id)))];if(i.length>0){const I=t.propertyResolve??{},S=[e.id,...i].map(R=>{const{having:P,sort:C,limit:v,limitBy:W,page:te,...q}=t,ue=re=>{let Y=re;try{Y=ae(e,re,o.resolveSchema).canonicalName}catch{}return I[R]?.[re]??I[R]?.[Y]??re};return{...q,schema:R,preds:(t.preds??[]).filter(re=>(re.schema??e.id)===R).map(({schema:re,...Y})=>Y),...R===e.id||!t.query?{}:{query:bi(t.query,ue)},...R!==e.id&&t.groupby?{groupby:t.groupby.map(re=>({...re,...typeof re.pred=="string"?{pred:ue(re.pred)}:{}}))}:{}}});return _d(t,S,e,r,n,o)}const s=$d(t,r);if(s)return Pe(s,e,r,n,o);for(const I of t.preds??[]){if(!I.operator)continue;const S=r.get(I.operator).rewriteLogicform?.({logicform:t,schema:e,getOperator:R=>r.get(R)});if(S)return Pe(S,e,r,n,o)}const a=o.semanticRegistry??$i(o.plugins);if(t.from){const I=bn(t.from,e,o),S=Pe(t.from,I,r,n,o),R=Ri(S,e),P={...t};delete P.from,P.schema??=R.id;const C=Pe(P,R,r,n,o),v=new Set(C.projections.map(({name:Y})=>Y)),W=S.rowIdentity.kind==="group"&&S.rowIdentity.names.every(Y=>v.has(Y))||S.rowIdentity.kind==="singleton"?S.rowIdentity:{kind:"generated"},te=S.groupBy.map(({name:Y})=>Y).filter(Y=>v.has(Y)),q=te.at(-1),ue=S.columnProperties?.find(Y=>Y.name===q),re=t.limitBy!==void 0&&te.length>0?{count:t.limitBy,partitionBy:te.slice(0,-1),orderBy:C.orderBy.length>0?C.orderBy:te.slice(-1).map(Y=>({name:Y,direction:"ASC",...ue?.comparable?{comparable:ue.comparable}:{}}))}:void 0;return{...C,source:S.source,sourcePlan:S,sourceLogicform:t.from,rowIdentity:W,...re?{groupLimit:re}:{}}}if(!t.schema)throw new p("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const u=gd(t,e,n,{operators:r,...o.plugins?{plugins:o.plugins}:{},...o.preferredConnectionId?{preferredConnectionId:o.preferredConnectionId}:{},...o.resolveSchema?{resolveSchema:o.resolveSchema}:{}});o.onSchemaMappingSelection?.(u.selection),t=u.logicform;const c=new Map(u.predRewrites.map(({predIndex:I,column:S})=>[I,S])),l=Wo(e,o.plugins),d=Ic(t,e,o.plugins),f=a.resolveQuery({logicform:t,schema:e,...t.query?{query:t.query}:{}}),m=d?.rewriteQuery?d.rewriteQuery(f):f,y=e.id,g=new Map,h=new Map,w=new Map,A=new Map,_=I=>{const S=h.get(I);if(S)return S.alias;const R=u.mapping.enrichments?.find(v=>v.id===I);if(!R)throw new p("SCHEMA_MAPPING_ENRICHMENT_NOT_FOUND",`Schema mapping enrichment is not registered: ${I}`,{schemaId:e.id,mappingId:u.mapping.id,enrichmentId:I});const P=`__enrichment_${I}`,C=R.temporal?(()=>{if(!l)throw new p("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${I} requires an entity with interval semantics`,{schemaId:e.id,enrichmentId:I});const v=lr(u.mapping,e,l.start.name),W=lr(u.mapping,e,l.end.name);if(!v||!W)throw new p("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${I} requires mapped interval boundary columns`,{schemaId:e.id,enrichmentId:I});if(v.sourceRef||W.sourceRef)throw new p("POINT_ENRICHMENT_INTERVAL_MUST_USE_BASE_SOURCE",`Point enrichment ${I} requires interval boundaries on the base source`,{schemaId:e.id,enrichmentId:I});return{kind:"point-in-interval",pointSide:"target",pointColumn:R.temporal.pointColumn,intervalSide:"source",startColumn:v.column,endColumn:W.column}})():void 0;return h.set(I,{kind:"enrichment-left",id:I,source:R.source,...R.sourceSql?{sourceSql:R.sourceSql}:{},alias:P,baseAlias:y,keys:R.on,...C?{temporalCondition:C}:{}}),P},E=I=>{const S=ae(e,I,o.resolveSchema);let R=y,P=u.mapping;const C=[];for(const q of S.relations){C.push(q.property.name);const ue=C.join("_"),re=ue,Y=n.get(q.targetSchema.id,u.mapping.connectionId);if(P=Y,!g.has(ue)){const Oe=q.targetSchema.properties.filter(({type:X})=>X==="ID"),[ye]=Oe;if(Oe.length!==1||!ye)throw new p("RELATION_TARGET_ID_REQUIRED",`Relation target ${q.targetSchema.id} must contain exactly one ID property`,{schemaId:q.targetSchema.id,count:Oe.length});const Qe=q.sourceSchema.id===e.id?u.mapping:n.get(q.sourceSchema.id,u.mapping.connectionId),zt=_e(Qe,q.sourceSchema,q.property.name)??q.property.id,nt=_e(Y,q.targetSchema,ye.name)??ye.id,Wt=q.sourceSchema.properties.find(({type:X})=>X==="timestamp"),O=q.targetSchema.properties.find(({type:X})=>X==="timestamp"),L=Ec(q.sourceSchema,q.targetSchema,o.plugins),F=Wt?_e(Qe,q.sourceSchema,Wt.name)??Wt.id:void 0,x=O?_e(Y,q.targetSchema,O.name)??O.id:void 0,G=L?.kind==="date-bucket-equal"?{kind:"date-bucket-equal",sourceColumn:_e(Qe,q.sourceSchema,L.sourceTimestamp.name)??L.sourceTimestamp.id,targetColumn:_e(Y,q.targetSchema,L.targetTimestamp.name)??L.targetTimestamp.id,sourceGranularity:L.sourceTimestamp.granularity??"day",targetGranularity:L.targetTimestamp.granularity??"day"}:L?.kind==="point-in-interval"?{kind:"point-in-interval",pointSide:"source",pointColumn:_e(Qe,q.sourceSchema,L.point.name)??L.point.id,intervalSide:"target",startColumn:_e(Y,q.targetSchema,L.start.name)??L.start.id,endColumn:_e(Y,q.targetSchema,L.end.name)??L.end.id}:void 0,le=q.property.isArray?ue:void 0;le&&!w.has(le)&&w.set(le,{path:le,sourceAlias:R,sourceColumn:zt,...q.property.udf?{sourceSql:q.property.udf.sql,...F?{sourceTimestampColumn:F}:{}}:{},alias:`__array_${ue}`}),g.set(ue,{kind:"left",path:ue,sourceAlias:R,sourceColumn:zt,...q.property.udf?{sourceSql:q.property.udf.sql,...F?{sourceTimestampColumn:F}:{}}:{},targetSchemaId:q.targetSchema.id,targetConnectionId:Y.connectionId,targetSource:Y.source,...Y.sourceSql?{targetSourceSql:Y.sourceSql}:{},targetAlias:re,targetColumn:nt,...le?{sourceArrayExpansionPath:le}:{},...ye.udf?{targetSql:ye.udf.sql,...x?{targetTimestampColumn:x}:{}}:{},...G?{temporalCondition:G}:{}})}R=re}const v=lr(P,S.schema,S.property.name);if(S.relations.length>0&&v?.sourceRef)throw new p("RELATION_MAPPING_ENRICHMENT_UNSUPPORTED",`Related property ${S.canonicalName} cannot be sourced from a mapping enrichment`,{schemaId:S.schema.id,property:S.property.name});const W=v?.sourceRef?_(v.sourceRef):R,te={schemaId:S.schema.id,property:S.property.name,propertyId:S.property.id,column:v?.column??S.property.id,qualifier:W,...S.property.isArray?{isArray:!0}:{},...S.property.comparable?{comparable:S.property.comparable}:{},...Ad(S.relations.length>0?e:S.schema,S.property,y)};return A.set(S.canonicalName,te),{reference:S.canonicalName,schema:S.schema,property:S.property,field:te}},$=I=>{if(I)for(const[S,R]of Object.entries(I))if((S==="$and"||S==="$or")&&Array.isArray(R))for(const P of R)typeof P=="object"&&P!==null&&!Array.isArray(P)&&$(P);else if(S==="$expr"&&typeof R=="object"&&R!==null&&!Array.isArray(R)){const P=R.pred;typeof P=="object"&&P!==null&&!Array.isArray(P)&&fr(P).forEach(E)}else S.startsWith("$")||E(S)},b=I=>{if(Ie(I)){const S=bn(I,e,o),R=Pe(I,S,r,n,o);if(R.projections.length!==1)throw new p("SUBQUERY_SINGLE_COLUMN_REQUIRED",`Query LogicForm must output exactly one column, received ${R.projections.length}`,{schemaId:I.schema,projectionCount:R.projections.length});return{kind:"logicform-subquery",plan:R}}return Array.isArray(I)?I.map(b):typeof I!="object"||I===null||I instanceof Date?I:Object.fromEntries(Object.entries(I).map(([S,R])=>[S,b(R)]))},N=I=>Object.fromEntries(Object.entries(I).map(([S,R])=>{if((S==="$and"||S==="$or")&&Array.isArray(R))return[S,R.map(C=>N(C))];if(S==="$expr"){if(typeof R!="object"||R===null||Array.isArray(R))throw new p("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const C=R;if(typeof C.pred!="object"||C.pred===null||Array.isArray(C.pred)||!Object.prototype.hasOwnProperty.call(C,"condition"))throw new p("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const v=C.pred,W=mt(v,r,E,U,z,N,e,o.resolveSchema,"groupby");if(W.outputProperty.isArray)throw new p("ARRAY_EXPRESSION_QUERY_UNSUPPORTED","$expr must produce a scalar value");const te=b(C.condition);return W.outputProperty.comparable&&Rn(te,v.name??v.operator??"$expr",W.outputProperty.comparable.values),[S,{kind:"expression-query",expression:W.expression,condition:W.outputProperty.comparable?{kind:"ordinal-query",comparable:W.outputProperty.comparable,condition:te}:te,properties:fr(v)}]}if(typeof R=="object"&&R!==null&&!Array.isArray(R)){const v=Object.entries(R).find(([W])=>ut(W,o.plugins));if(v){const[W,te]=v,q=ut(W,o.plugins);if(!q)throw new Error(`Query Operator disappeared: ${W}`);const ue=E(S),re=q.plan(te,{schema:ue.schema,property:ue.property,connectionId:u.mapping.connectionId,...o.resolveSchema?{resolveSchema:o.resolveSchema}:{},resolveMapping:(Y,Oe)=>n.get(Y,Oe)});return[S,{[W]:{kind:"query-operator",operator:W,value:re.value,definition:q,...re.sources?{sources:re.sources}:{}}}]}}const P=S.startsWith("$")?void 0:E(S).property.comparable;return[S,P?{kind:"ordinal-query",comparable:P,condition:b(R)}:b(R)]})),k=I=>{const S=P=>{if(!P||typeof P!="object")return!1;if(Array.isArray(P))return P.some(S);const C=P;return Object.prototype.hasOwnProperty.call(C,"$and")||Object.values(C).some(S)};if(S(I))return I;const R=new Set(Object.keys(I).flatMap(P=>{if(P.startsWith("$"))return[];const C=ae(e,P,o.resolveSchema);return C.relations.length===1&&C.property.type==="ID"?[C.relations[0]?.property.name]:[]}));return Object.fromEntries(Object.entries(I).map(([P,C])=>{if(P==="$and"||P==="$or")return Array.isArray(C)?[P,C.map(ye=>typeof ye=="object"&&ye!==null&&!Array.isArray(ye)?k(ye):ye)]:[P,C];if(P.startsWith("$"))return[P,C];const v=ae(e,P,o.resolveSchema);if(v.relations.length===0)return[P,C];if(v.property.udf?.sql.includes("$TS")===!0||v.relations.some(({property:ye})=>ye.udf?.sql.includes("$TS")===!0))return[P,C];const te=v.relations.map(({property:ye})=>ye.name).join("_");if(g.has(te))return[P,C];const[q]=v.relations;if(!q)return[P,C];if(R.has(q.property.name))return[P,C];const ue=q.property.name,re=v.canonicalName.slice(ue.length+1),Y=q.targetSchema.properties.find(({type:ye})=>ye==="ID");if(!Y)throw new p("RELATION_TARGET_ID_REQUIRED",`Relation target ${q.targetSchema.id} must contain an ID property`,{schemaId:q.targetSchema.id});if(v.relations.length===1&&v.property.id===Y.id)return[q.property.id,C];const Oe={version:t.version,schema:q.targetSchema.id,query:re?{[re]:C}:{},preds:[{pred:Y.name,name:Y.name}]};return[q.property.id,{$in:Oe}]}))},j=(t.groupby??[]).map(I=>{const S=_n(I);I.operator&&r.get(I.operator).validateGroupby?.({pred:I});const R=mt(I,r,E,U,z,N,e,o.resolveSchema,"groupby");let P=R.expression;if(d?.group===I&&(P={kind:"column",schemaId:e.id,property:d.property.name,propertyId:d.property.id,column:"__period_start",qualifier:"__periods"}),R.sourceProperty?.isArray&&R.sourceField){const C=`groupby:${S}`;w.set(C,{path:C,sourceAlias:R.sourceField.qualifier,sourceColumn:R.sourceField.column,...R.sourceField.sql?{sourceSql:R.sourceField.sql,...R.sourceField.timestampColumn?{sourceTimestampColumn:R.sourceField.timestampColumn}:{}}:{},alias:`__array_group_${w.size}`}),P={kind:"array-element",schemaId:R.sourceField.schemaId,property:R.sourceProperty.name,expansionPath:C}}return{name:S,expression:P,outputProperty:{...R.outputProperty,name:S,isArray:!1}}});function U(I){const S=(t.groupby??[]).findIndex(P=>typeof P.pred=="string"&&P.pred===I||P.name===I),R=S>=0?j[S]:void 0;if(!R)throw new p("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${I}`);return R.expression}function z(I){const S=(t.groupby??[]).findIndex(P=>typeof P.pred=="string"&&P.pred===I||P.name===I),R=S>=0?j[S]:void 0;return R?R.expression:Ni(E(I).field)}const B=I=>{I.operator&&r.get(I.operator).validatePlan?.({pred:I,groupByNames:j.map(({name:S})=>S),resolveGroupName:S=>{const R=(t.groupby??[]).findIndex(P=>P.name===S||typeof P.pred=="string"&&P.pred===S);return R>=0?j[R]?.name:void 0},getOperator:S=>r.get(S)}),I.pred&&typeof I.pred=="object"&&!Array.isArray(I.pred)&&B(I.pred);for(const S of Array.isArray(I.pred)?I.pred:[])B(typeof S=="string"?{pred:S}:S)};for(const I of t.preds??[])B(I);const D=[...j,...(t.preds??[]).map((I,S)=>{const R=d?.rewritePred?.(I)??I;return Ed(R,r,E,U,z,N,e,o.resolveSchema,a,c.get(S),Uo(R,t.groupby??[],e,o.resolveSchema)?"$min":void 0,I)})],Q=I=>Object.fromEntries(Object.entries(I).map(([S,R])=>{if((S==="$and"||S==="$or")&&Array.isArray(R))return[S,R.map(C=>Q(C))];if(S==="$expr")throw new p("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const P=D.find(({name:C})=>C===S)?.outputProperty.comparable;return P&&Rn(R,S,P.values),[S,P?{kind:"ordinal-query",comparable:P,condition:b(R)}:b(R)]})),ce=m?k(m):void 0;$(ce);const T=I=>{$(I.query),I.pred&&typeof I.pred=="object"&&!Array.isArray(I.pred)&&T(I.pred);for(const S of Array.isArray(I.pred)?I.pred:[])T(typeof S=="string"?{pred:S}:S)};for(const I of t.preds??[])T(I);if(D.length===0)throw new p("EMPTY_PROJECTION","LogicForm must contain preds or groupby");Id(D);const M=new Set(D.map(({name:I})=>I)),J=j.length>0?{kind:"group",names:j.map(({name:I})=>I),separator:"_",nullLabel:"\u7A7A\u503C"}:D.every(({expression:I})=>I.kind==="column"||I.kind==="property-sql")||D.some(({expression:I})=>I.kind==="property-sql"&&e.properties.some(({id:S,type:R})=>R==="ID"&&S===I.propertyId))?(()=>{const I=e.properties.find(({type:S})=>S==="ID");return I&&(o.canUsePropertyRowIdentity?.(e,I)??!0)?{kind:"property",column:I.id,internalName:"_id"}:{kind:"generated"}})():{kind:"singleton"},H=Object.entries(t.sort??{}).map(([I,S])=>{if(!M.has(I))throw new p("INVALID_SORT",`Sort field is not an output: ${I}`);const R=D.find(P=>P.name===I);return{name:I,direction:S===1?"ASC":"DESC",...R?.outputProperty.comparable?{comparable:R.outputProperty.comparable,expression:R.expression}:{}}}),Ae=t.limit===void 0?void 0:t.limit>0&&t.limit<1?{kind:"ratio",page:t.page??1,ratio:t.limit}:{kind:"rows",page:t.page??1,pageSize:t.limit},ie=t.limitBy===void 0?void 0:{count:t.limitBy,partitionBy:j.slice(0,-1).map(({name:I})=>I),orderBy:H.length>0?H:(()=>{const I=j.at(-1);return[{name:I?.name??"",direction:"ASC",...I?.outputProperty.comparable?{comparable:I.outputProperty.comparable,expression:I.expression}:{}}]})()},de=A.size===0&&g.size===0&&h.size===0&&w.size===0&&!ce&&j.length===0&&D.length>0&&D.every(({expression:I})=>I.kind==="operator"&&I.operator==="$constant");return{schemaId:e.id,source:de?"":u.mapping.source,...de?{}:{connectionId:u.mapping.connectionId},...!de&&u.mapping.sourceSql?{sourceSql:u.mapping.sourceSql}:{},mappingId:u.mapping.id??u.mapping.source,sourceAlias:y,fields:{...Ma(e),...Object.fromEntries(e.properties.flatMap(I=>{const S=_e(u.mapping,e,I.name);return S?[[I.name,S],[I.id,S]]:[]}))},fieldReferences:Object.fromEntries(A),joins:[...g.values()],enrichmentJoins:[...h.values()],arrayExpansions:[...w.values()],...d?{periodSource:{alias:"__periods",labelColumn:"__period_start",asOfColumn:"__as_of",sourceAlias:y,periods:d.periods,match:d.source.kind==="interval"?{kind:"interval",startColumn:_e(u.mapping,e,d.source.start.name)??d.source.start.id,endColumn:_e(u.mapping,e,d.source.end.name)??d.source.end.id}:{kind:"latest",lookupAlias:"__period_lookup",timestampColumn:_e(u.mapping,e,d.source.timestamp.name)??d.source.timestamp.id}}}:{},projections:D.map(({name:I,expression:S})=>({name:I,expression:S})),columnProperties:D.map(({outputProperty:I})=>I),groupBy:j.map(({name:I,expression:S})=>({name:I,expression:S})),...ce?{query:N(ce)}:{},...t.having?{having:Q(t.having)}:{},orderBy:H,rowIdentity:de?{kind:"singleton"}:J,...Ae?{pagination:Ae}:{},...ie?{groupLimit:ie}:{}}};class Sd{provider;parameterOffset;values=[];constructor(e,r=0){this.provider=e,this.parameterOffset=r}add(e){const r=this.parameterOffset+this.values.length;return this.values.push(e),this.provider.parameter(r,e)}get nextParameterOffset(){return this.parameterOffset+this.values.length}append(e){this.values.push(...e)}}const Rd=(t,e)=>{const r=e.split(".");if(r.some(n=>n.length===0))throw new p("INVALID_SOURCE",`Invalid physical source: ${e}`);return r.map(n=>t.quoteIdentifier(n)).join(".")},mr=(t,e,r)=>r===void 0?Rd(t,e):`(${r.trim().replace(/;+\s*$/,"")})`,Ut=(t,e,r,n,o)=>{const i=ii(t,[],String,`Property ${e} udf.sql`);if(!i.includes("$TS"))return i;if(!n)throw new p("PROPERTY_UDF_TIMESTAMP_REQUIRED",`Property ${e} udf.sql uses $TS but its evaluation context has no timestamp Property`,{property:e});const s=(o?`${r.quoteIdentifier(o)}.`:"")+r.quoteIdentifier(n);return i.replace(/\$TS/g,s)},De=(t,e,r,n=!1,o,i,s,a)=>{const u=(c,l)=>n&&l?`${e.quoteIdentifier(l)}.${e.quoteIdentifier(c)}`:e.quoteIdentifier(c);switch(t.kind){case"array-element":if(!a)throw new p("ARRAY_EXPANSION_UNAVAILABLE","Array expansion compiler is unavailable");return a(t.expansionPath);case"column":return u(t.column,t.qualifier);case"property-sql":return Ut(t.sql,t.property,e,t.timestampColumn,n?t.timestampQualifier??t.qualifier:void 0);case"window":{if(Se(t.input,r))throw new p("UNSUPPORTED_MIXED_OPERATOR","Window operators cannot consume a JavaScript operator");const c=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>De(f,e,r,n,o,i,s,a)).join(", ")} `:"",l=De(t.input,e,r,n,o,i,s,a);return`${t.function==="rank"?"RANK":"ROW_NUMBER"}() OVER (${c}ORDER BY ${l} ${t.direction})`}case"cumulative":{if(Se(t.input,r))throw new p("UNSUPPORTED_MIXED_OPERATOR","Cumulative expressions cannot consume a JavaScript operator");const c=De(t.input,e,r,n,o,i,s,a),l=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>De(f,e,r,n,o,i,s,a)).join(", ")} `:"",d=t.orderBy.map(f=>`${De(f.expression,e,r,n,o,i,s,a)} ${f.direction}`).join(", ");return`${e.aggregateFunction(t.function,c)} OVER (${l}ORDER BY ${d} ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`}case"ordinal-encode":{if(!i)throw new p("SQL_BINDER_UNAVAILABLE","Ordinal encoding requires a value binder");return`CASE ${t.comparable.values.map((l,d)=>`WHEN ${De(t.input,e,r,n,o,i,s,a)} = ${i(l)} THEN ${t.comparable.direction*d}`).join(" ")} END`}case"ordinal-decode":{if(!i)throw new p("SQL_BINDER_UNAVAILABLE","Ordinal decoding requires a value binder");return`CASE ${t.comparable.values.map((l,d)=>`WHEN ${De(t.input,e,r,n,o,i,s,a)} = ${t.comparable.direction*d} THEN ${i(l)}`).join(" ")} END`}case"operator":{const c=r.get(t.operator);if(c.kind==="component")throw new p("COMPONENT_OPERATOR_REQUIRES_EXECUTOR",`${t.operator} must be compiled through the executor component pipeline`);if(c.toSQL&&(t.input&&Se(t.input,r)||t.inputs?.some(f=>Se(f,r))))throw new p("UNSUPPORTED_MIXED_OPERATOR",`${t.operator} cannot consume a JavaScript operator in SQL`);let l=t.input?De(t.input,e,r,n,o,i,s,a):t.column?u(t.column,t.qualifier):void 0;const d=t.inputs?.map(f=>De(f,e,r,n,o,i,s,a));if(t.query&&Object.keys(t.query).length>0){if(c.kind!=="aggregate")throw new p("OPERATOR_QUERY_REQUIRES_AGGREGATION",`Pred query is only supported by aggregation operators: ${t.operator}`);if(!o)throw new p("INVALID_OPERATOR_QUERY","Operator query compiler is unavailable");l=`CASE WHEN ${o(t.query)} THEN ${l??"1"} END`}if(c.requiresProperty!==!1&&!l)throw new p("PRED_PROPERTY_REQUIRED",`${t.operator} requires a column`);return c.toSQL?c.toSQL({sql:{aggregateFunction:e.aggregateFunction.bind(e),quoteIdentifier:e.quoteIdentifier.bind(e),concat:e.concat.bind(e),substring:e.substring.bind(e),stringLength:e.stringLength.bind(e),datePart:e.datePart.bind(e),dateBucket:e.dateBucket.bind(e),dateShift:e.dateShift.bind(e),...e.datePeriodBoundary?{datePeriodBoundary:e.datePeriodBoundary.bind(e)}:{},...e.scalarExtremum?{scalarExtremum:e.scalarExtremum.bind(e)}:{},value:(f,m)=>{if(!i)throw new p("SQL_BINDER_UNAVAILABLE","SQL value binder is unavailable");const y=i(f);return m&&e.castValue?e.castValue(y,m):y},condition:(f,m)=>{if(!s)throw new p("SQL_CONDITION_UNAVAILABLE","SQL condition compiler is unavailable");return s(f,m)}},...l?{expression:l,column:l}:{},...d?{expressions:d}:{},args:t.args}):l??"NULL"}}},Se=(t,e)=>t.kind==="window"?Se(t.input,e)||t.partitionBy.some(r=>Se(r,e)):t.kind==="cumulative"?Se(t.input,e)||t.partitionBy.some(r=>Se(r,e))||t.orderBy.some(r=>Se(r.expression,e)):t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?Se(t.input,e):t.kind==="operator"&&(!e.get(t.operator).toSQL&&!!e.get(t.operator).evaluate||(t.input?Se(t.input,e):!1)||(t.inputs?.some(r=>Se(r,e))??!1)),bd=(t,e)=>t.sourceSql?Ut(t.sourceSql,t.sourceColumn,e,t.sourceTimestampColumn,t.sourceAlias):`${e.quoteIdentifier(t.sourceAlias)}.${e.quoteIdentifier(t.sourceColumn)}`,Ti=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).some(e=>e.startsWith("$")),Li={$second:"second",$minute:"minute",$hour:"hour",$weekday:"weekday",$day:"day",$week:"week",$month:"month",$quarter:"quarter",$year:"year"},jt=(t,e,r,n,o,i,s,a)=>{if(pi(r)){if(r.operator!==e)throw new p("INVALID_PLUGIN_QUERY",`Query Operator plan does not match ${e}`);const d=r.definition??s(e);if(!d)throw new p("UNSUPPORTED_QUERY_OPERATOR",`Query Operator is not registered: ${e}`);return d.compile(r.value,{field:t,provider:o,bind:f=>n.add(f),renderSource:(f,m)=>mr(o,f,m)})}if(s(e))throw new p("INVALID_PLUGIN_QUERY",`${e} query was not planned`,{operator:e});if(e==="$eq"&&r===null)return`${t} IS NULL`;if(e==="$ne"&&r===null)return`${t} IS NOT NULL`;const l={$eq:"=",$ne:"<>",$gt:">",$gte:">=",$lt:"<",$lte:"<="}[e];if(l){const d=dt(r)?`(${i(r)})`:n.add(r);return`${t} ${l} ${d}`}if(e==="$in"||e==="$nin"){const d=e==="$in"?"IN":"NOT IN";if(dt(r))return`${t} ${d} (${i(r)})`;if(!Array.isArray(r))throw new p("INVALID_QUERY_VALUE",`${e} requires an array or query LogicForm`);if(r.length===0)return e==="$in"?"0 = 1":"1 = 1";const f=r.filter(dt);if(f.length>0){if(f.length!==r.length)throw new p("MIXED_SUBQUERY_VALUES",`${e} cannot mix query LogicForm objects and literal values`);return`${t} ${d} (${f.map(i).join(" UNION ALL ")})`}const m=r.map(y=>n.add(y)).join(", ");return`${t} ${d} (${m})`}if(dt(r))throw new p("UNSUPPORTED_SUBQUERY_OPERATOR",`Query LogicForm is not supported by ${e}`);if(e==="$exists")return`${t} IS ${r?"NOT ":""}NULL`;if(e==="$contains")return`${t} LIKE ${n.add(`%${String(r)}%`)}`;if(e==="$startsWith"){if(typeof r!="string")throw new p("INVALID_QUERY_VALUE","$startsWith requires a string");return`${t} LIKE ${n.add(`${r}%`)}`}if(e==="$regex"){if(typeof r!="string"||a!==void 0&&typeof a!="string")throw new p("INVALID_QUERY_VALUE","$regex requires a string pattern and args.options must be a string");return o.regex(t,n.add(r),a)}throw new p("UNSUPPORTED_QUERY_OPERATOR",`Unsupported query operator: ${e}`)},On=(t,e)=>{if(!(typeof t=="number"&&Number.isFinite(t))){if(Array.isArray(t)){if(t.every(r=>typeof r=="number"&&Number.isFinite(r)))return;throw new p("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}if(typeof t=="object"&&t!==null&&!dt(t)){for(const[r,n]of Object.entries(t)){if(!r.startsWith("$"))throw new p("INVALID_QUERY_VALUE",`${e} requires numeric conditions`);if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new p("INVALID_QUERY_VALUE",`${r} requires an array`);n.forEach(o=>On(o,e))}else if(r==="$in"||r==="$nin"){if(!Array.isArray(n)||n.some(o=>typeof o!="number"||!Number.isFinite(o)))throw new p("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}else if(typeof n!="number"||!Number.isFinite(n))throw new p("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}return}throw new p("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}},Je=(t,e,r,n,o,i)=>{if(od(e)){const c=()=>`CASE ${e.comparable.values.map((m,y)=>`WHEN ${t} = ${r.add(m)} THEN ${e.comparable.direction*y}`).join(" ")} END`,l=new Set(["$gt","$gte","$lt","$lte"]),d=f=>typeof f!="object"||f===null||Array.isArray(f)?Je(t,f,r,n,o,i):Object.entries(f).filter(([m])=>m!=="args").map(([m,y])=>(m==="$and"||m==="$or")&&Array.isArray(y)?`(${y.map(d).join(m==="$and"?" AND ":" OR ")})`:l.has(m)?jt(c(),m,e.comparable.direction*e.comparable.values.indexOf(String(y)),r,n,o,i):jt(t,m,y,r,n,o,i)).join(" AND ");return d(e.condition)}if(Array.isArray(e))return jt(t,"$in",e,r,n,o,i);if(!Ti(e))return jt(t,"$eq",e,r,n,o,i);const s=[],a=e.args;if(a!==void 0){if(typeof a!="object"||a===null||Array.isArray(a))throw new p("INVALID_QUERY_VALUE","Query args.options must be a string");const c=a.options;if(c!==void 0&&typeof c!="string")throw new p("INVALID_QUERY_VALUE","Query args.options must be a string")}const u=a?.options;for(const[c,l]of Object.entries(e))if(c==="$and"||c==="$or"){if(!Array.isArray(l))throw new p("INVALID_QUERY_VALUE",`${c} requires an array`);const d=l.map(f=>Je(t,f,r,n,o,i));s.push(`(${d.join(c==="$and"?" AND ":" OR ")})`)}else Li[c]?(On(l,c),s.push(Je(n.datePart(t,Li[c]),l,r,n,o,i))):c==="$length"?(On(l,"$length"),s.push(Je(n.stringLength(t),l,r,n,o,i))):c!=="args"&&s.push(jt(t,c,l,r,n,o,i,c==="$regex"?u:void 0));if(s.length===0)throw new p("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},Di=(t,e,r,n)=>{if(!n.arrayContains)throw new p("ARRAY_CONDITION_UNSUPPORTED",`Provider ${n.kind} does not support array conditions`);const o=n.arrayContains.bind(n),i=a=>o(t,r.add(a));if(Array.isArray(e))return`(${e.map(i).join(" OR ")})`;if(!Ti(e))return i(e);const s=[];for(const[a,u]of Object.entries(e))if(a==="$and"||a==="$or"){if(!Array.isArray(u))throw new p("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(l=>Di(t,l,r,n));s.push(`(${c.join(a==="$and"?" AND ":" OR ")})`)}else if(a==="$eq")s.push(i(u));else if(a==="$ne")s.push(`NOT (${i(u)})`);else if(a==="$in"||a==="$nin"){if(!Array.isArray(u))throw new p("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(i),l=c.length===0?a==="$in"?"0 = 1":"1 = 1":c.join(a==="$in"?" OR ":" AND NOT ");s.push(a==="$nin"&&c.length>0?`NOT (${c.join(" OR ")})`:`(${l})`)}else if(a==="$exists")s.push(`${t} IS ${u?"NOT ":""}NULL`);else if(a!=="args")throw new p("UNSUPPORTED_ARRAY_QUERY_OPERATOR",`Unsupported array query operator: ${a}`);if(s.length===0)throw new p("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},yt=(t,e,r,n,o,i,s,a)=>{const u=[];for(const[c,l]of Object.entries(t)){if(c==="$and"||c==="$or"){if(!Array.isArray(l))throw new p("INVALID_QUERY_VALUE",`${c} requires an array`);const f=l.map(m=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new p("INVALID_QUERY_VALUE",`${c} items must be query objects`);return yt(m,e,r,n,o,i,s,a)});u.push(`(${f.join(c==="$and"?" AND ":" OR ")})`);continue}if(c==="$expr"){if(!li(l))throw new p("INVALID_EXPRESSION_QUERY","$expr query was not planned");u.push(Je(s(l.expression),l.condition,n,o,i,a));continue}const d=e(c);u.push(r(c)?Di(d,l,n,o):Je(d,l,n,o,i,a))}return u.join(" AND ")},yr=(t,e,r,n,o)=>t.orderBy.map(i=>{const s=e.quoteIdentifier(i.name),a=`${n?`${n}.`:""}${s}`,u=i.comparable,c=!n&&o&&i.expression?o(i.expression):a;return`${u?`CASE ${u.values.map((d,f)=>`WHEN ${c} = ${r.add(d)} THEN ${u.direction*f}`).join(" ")} END`:a} ${i.direction}`}).join(", "),Nn=(t,e)=>{let r=t;for(;e.has(r);)r=`_${r}`;return r},Ci=(t,e,r,n)=>e.concat(t.flatMap((o,i)=>[...i>0?[`'${r.replaceAll("'","''")}'`]:[],`CASE WHEN ${o} IS NULL THEN '${n.replaceAll("'","''")}' ELSE ${e.stringify(o)} END`])),qi=(t,e,r,n,o)=>{const i=new Set(e.projections.map(({name:k})=>k)),s="__sdb_page_source",a="__sdb_page",u=n.quoteIdentifier(s),c=n.quoteIdentifier(a),l=Nn("__sdb_row_number",i),d=Nn("__sdb_total_rows",i),f=n.quoteIdentifier(l),m=n.quoteIdentifier(d),y=yr(e,n,o,u),g=y?`ORDER BY ${y}`:"",h=`CEIL(${m} * ${r.ratio})`,w=r.page-1,A=r.page,E=[...e.projections.map(({name:k})=>k),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(k=>`${c}.${n.quoteIdentifier(k)}`).join(", "),$=yr(e,n,o,c),b=`SELECT ${u}.*, ROW_NUMBER() OVER (${g}) AS ${f}, COUNT(*) OVER () AS ${m} FROM ${n.tableAlias(`(${t})`,s)}`;let N=`SELECT ${E} FROM ${n.tableAlias(`(${b})`,a)} WHERE ${c}.${f} > ${w} * ${h} AND ${c}.${f} <= ${A} * ${h}`;return $&&(N+=` ORDER BY ${$}`),N},ki=(t,e,r,n)=>{const o=e.groupLimit;if(!o)return t;const i="__sdb_limit_by_source",s="__sdb_limit_by_ranked",a=r.quoteIdentifier(i),u=r.quoteIdentifier(s),c=new Set(e.projections.map(({name:A})=>A)),l=Nn("__sdb_limit_by_row_number",c),d=r.quoteIdentifier(l),f=o.partitionBy.map(A=>`${a}.${r.quoteIdentifier(A)}`).join(", "),m=o.orderBy.map(({name:A,direction:_,comparable:E})=>{const $=`${a}.${r.quoteIdentifier(A)}`;return`${E?`CASE ${E.values.map((N,k)=>`WHEN ${$} = ${n.add(N)} THEN ${E.direction*k}`).join(" ")} END`:$} ${_}`}).join(", "),g=[...e.projections.map(({name:A})=>A),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(A=>`${u}.${r.quoteIdentifier(A)}`).join(", "),h=`PARTITION BY ${f} ORDER BY ${m}`,w=`SELECT ${a}.*, ROW_NUMBER() OVER (${h}) AS ${d} FROM ${r.tableAlias(`(${t})`,i)}`;return`SELECT ${g} FROM ${r.tableAlias(`(${w})`,s)} WHERE ${u}.${d} <= ${o.count}`},he=(t,e,r=Ne(),n=0)=>{const o=new Sd(e,n),i=$=>ut($);if(t.subplans){const $=t.projections.map(({name:B})=>B),b=new Set(t.groupBy.map(({name:B})=>B)),N=t.subplans.map((B,D)=>{const Q=he(B,e,r,o.nextParameterOffset);o.append(Q.parameters);const ce=`__composition_child_${D}`,T=e.quoteIdentifier(ce),M=new Set(B.projections.map(({name:J})=>J));return{aliasName:ce,alias:T,available:M,sql:Q.sql}}),k=N[0];if(!k)throw new p("INVALID_COMPOSITION","Composition has no children");const j=$.map(B=>{const D=N.filter(T=>T.available.has(B)),Q=D[0]??k;return`${b.has(B)&&D.length>1?`COALESCE(${D.map(T=>`${T.alias}.${e.quoteIdentifier(B)}`).join(", ")})`:`${Q.alias}.${e.quoteIdentifier(B)}`} AS ${e.quoteIdentifier(B)}`}),U=N.map(B=>`${B.alias} AS (${B.sql})`);let z;if(t.rowIdentity.kind==="group"){const D=e.quoteIdentifier("__composition_keys"),Q=e.quoteIdentifier("_id");U.push(`${D} AS (${N.map(ce=>`SELECT ${Q} FROM ${ce.alias}`).join(" UNION ")})`),j.push(`${D}.${Q} AS ${Q}`),z=`WITH ${U.join(", ")} SELECT ${j.join(", ")} FROM ${D}`;for(const ce of N)z+=` LEFT JOIN ${ce.alias} ON ${D}.${Q} = ${ce.alias}.${Q}`}else{z=`WITH ${U.join(", ")} SELECT ${j.join(", ")} FROM ${k.alias}`;for(const B of N.slice(1))z+=` LEFT JOIN ${B.alias} ON 1 = 1`}if(t.having&&Object.keys(t.having).length>0){const B="__composition_having",D=e.quoteIdentifier(B),Q=new Set($),ce=yt(t.having,T=>{if(!Q.has(T))throw new p("INVALID_HAVING",`Having field is not an output: ${T}`);return`${D}.${e.quoteIdentifier(T)}`},()=>!1,o,e,()=>{throw new p("SUBQUERY_IN_COMPOSITION_HAVING_UNSUPPORTED","A composed result having condition cannot contain a LogicForm subquery")},()=>{throw new p("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names")},i);z=`SELECT ${D}.* FROM ${e.tableAlias(`(${z})`,B)} WHERE ${ce}`}if(t.groupLimit&&(z=ki(z,t,e,o)),t.pagination?.kind==="ratio")z=qi(z,t,t.pagination,e,o);else if(t.orderBy.length>0&&(z+=` ORDER BY ${yr(t,e,o)}`),t.pagination?.kind==="rows"){const B=(t.pagination.page-1)*t.pagination.pageSize;z=e.paginate(z,t.pagination.pageSize,B)}return{sql:z,parameters:o.values}}const s=$=>{if($.plan.projections.some(({expression:N})=>Se(N,r)))throw new p("JAVASCRIPT_OPERATOR_IN_SUBQUERY","A query LogicForm cannot use a JavaScript-only operator");const b=he($.plan.rowIdentity.kind==="property"||$.plan.rowIdentity.kind==="group"?{...$.plan,rowIdentity:{kind:"generated"}}:$.plan,e,r,o.nextParameterOffset);return o.append(b.parameters),b.sql},a=(t.joins?.length??0)>0||(t.enrichmentJoins?.length??0)>0,u=(t.arrayExpansions?.length??0)>0,c=a||u||t.sourcePlan!==void 0||t.sourceSql!==void 0||t.periodSource!==void 0,l=new Map,d=(t.arrayExpansions??[]).map($=>{if(!e.expandArray)throw new p("ARRAY_EXPANSION_UNSUPPORTED",`Provider ${e.kind} does not support array expansion`);const b=e.expandArray(bd($,e),$.alias,"value");return l.set($.path,b.valueExpression),b}),f=$=>{const b=t.fieldReferences?.[$];if(b?.sql)return Ut(b.sql,b.property,e,b.timestampColumn,c?b.timestampQualifier??b.qualifier:void 0);if(b&&c)return`${e.quoteIdentifier(b.qualifier)}.${e.quoteIdentifier(b.column)}`;const N=t.fields[$];if(!N)throw new p("PROPERTY_NOT_FOUND",`Query property not found: ${$}`);return e.quoteIdentifier(N)},m=$=>De($,e,r,c,b=>yt(b,f,N=>t.fieldReferences?.[N]?.isArray===!0,o,e,s,m,i),b=>o.add(b),(b,N)=>Je(b,N,o,e,s,i),b=>{const N=l.get(b);if(!N)throw new p("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${b}`);return N}),y=t.projections.map($=>`${m($.expression)} AS ${e.quoteIdentifier($.name)}`),g=t.rowIdentity.kind==="property"?`${c&&t.sourceAlias?`${e.quoteIdentifier(t.sourceAlias)}.`:""}${e.quoteIdentifier(t.rowIdentity.column)} AS ${e.quoteIdentifier(t.rowIdentity.internalName)}`:t.rowIdentity.kind==="group"?(()=>{const $=t.rowIdentity.names.map(b=>{const N=t.groupBy.find(k=>k.name===b)??t.projections.find(k=>k.name===b);if(!N)throw new p("GROUP_IDENTITY_OUTPUT_NOT_FOUND",`Group identity output not found: ${b}`);return m(N.expression)});return`${Ci($,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`})():void 0,h=[...y,...g?[g]:[]].join(", "),w=t.sourcePlan?(()=>{const $=he(t.sourcePlan,e,r,o.nextParameterOffset);return o.append($.parameters),`(${$.sql})`})():t.source?mr(e,t.source,t.sourceSql):"",A=c&&t.sourceAlias?e.tableAlias(w,t.sourceAlias):w;let _=`SELECT ${h}`;if(t.periodSource){const $=t.periodSource,b=$.periods.map(({label:D,asOf:Q},ce)=>{const T=o.add(D),M=o.add(Q);return ce===0?`SELECT ${T} AS ${e.quoteIdentifier($.labelColumn)}, ${M} AS ${e.quoteIdentifier($.asOfColumn)}`:`SELECT ${T}, ${M}`}).join(" UNION ALL "),N=e.tableAlias(`(${b})`,$.alias),k=e.tableAlias(w,$.sourceAlias),j=e.quoteIdentifier($.alias),U=e.quoteIdentifier($.sourceAlias),z=`${j}.${e.quoteIdentifier($.asOfColumn)}`,B=$.match.kind==="interval"?(()=>{const D=`${U}.${e.quoteIdentifier($.match.startColumn)}`,Q=`${U}.${e.quoteIdentifier($.match.endColumn)}`;return`${D} <= ${z} AND (${Q} > ${z} OR ${Q} IS NULL)`})():(()=>{const D=e.tableAlias(w,$.match.lookupAlias),Q=e.quoteIdentifier($.match.lookupAlias),ce=`${U}.${e.quoteIdentifier($.match.timestampColumn)}`,T=`${Q}.${e.quoteIdentifier($.match.timestampColumn)}`,M=`SELECT ${e.aggregateFunction("max",T)} FROM ${D} WHERE ${T} <= ${z}`;return`${ce} = (${M})`})();_+=` FROM ${N} LEFT JOIN ${k} ON ${B}`,t.query&&Object.keys(t.query).length>0&&(_+=` AND ${yt(t.query,f,D=>t.fieldReferences?.[D]?.isArray===!0,o,e,s,m,i)}`)}else A&&(_+=` FROM ${A}`);for(const $ of d)_+=` ${$.joinSql}`;for(const $ of t.enrichmentJoins??[]){const b=e.quoteIdentifier($.alias),N=e.quoteIdentifier($.baseAlias);_+=` LEFT JOIN ${e.tableAlias(mr(e,$.source,$.sourceSql),$.alias)}`;const k=$.keys.map(({baseColumn:j,targetColumn:U})=>`${N}.${e.quoteIdentifier(j)} = ${b}.${e.quoteIdentifier(U)}`);if($.temporalCondition?.kind==="point-in-interval"){const j=Q=>Q==="source"?N:b,U=`${j($.temporalCondition.pointSide)}.${e.quoteIdentifier($.temporalCondition.pointColumn)}`,z=j($.temporalCondition.intervalSide),B=`${z}.${e.quoteIdentifier($.temporalCondition.startColumn)}`,D=`${z}.${e.quoteIdentifier($.temporalCondition.endColumn)}`;k.push(`${B} <= ${U}`),k.push(`(${D} > ${U} OR ${D} IS NULL)`)}_+=` ON ${k.join(" AND ")}`}for(const $ of t.joins??[]){_+=` LEFT JOIN ${e.tableAlias(mr(e,$.targetSource,$.targetSourceSql),$.targetAlias)}`;const b=$.sourceArrayExpansionPath?l.get($.sourceArrayExpansionPath):$.sourceSql?Ut($.sourceSql,$.sourceColumn,e,$.sourceTimestampColumn,$.sourceAlias):`${e.quoteIdentifier($.sourceAlias)}.${e.quoteIdentifier($.sourceColumn)}`,N=$.targetSql?Ut($.targetSql,$.targetColumn,e,$.targetTimestampColumn,$.targetAlias):`${e.quoteIdentifier($.targetAlias)}.${e.quoteIdentifier($.targetColumn)}`;if(!b)throw new p("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${$.path}`);if(_+=` ON ${b} = ${N}`,$.temporalCondition?.kind==="date-bucket-equal"){const k=`${e.quoteIdentifier($.sourceAlias)}.${e.quoteIdentifier($.temporalCondition.sourceColumn)}`,j=`${e.quoteIdentifier($.targetAlias)}.${e.quoteIdentifier($.temporalCondition.targetColumn)}`;_+=` AND ${e.dateBucket(k,$.temporalCondition.sourceGranularity)} = ${e.dateBucket(j,$.temporalCondition.targetGranularity)}`}else if($.temporalCondition?.kind==="point-in-interval"){const k=D=>D==="source"?e.quoteIdentifier($.sourceAlias):e.quoteIdentifier($.targetAlias),j=`${k($.temporalCondition.pointSide)}.${e.quoteIdentifier($.temporalCondition.pointColumn)}`,U=k($.temporalCondition.intervalSide),z=`${U}.${e.quoteIdentifier($.temporalCondition.startColumn)}`,B=`${U}.${e.quoteIdentifier($.temporalCondition.endColumn)}`;_+=` AND ${z} <= ${j} AND (${B} > ${j} OR ${B} IS NULL)`}}const E=[];if(!t.periodSource&&t.query&&Object.keys(t.query).length>0&&E.push(yt(t.query,f,$=>t.fieldReferences?.[$]?.isArray===!0,o,e,s,m,i)),E.length>0&&(_+=` WHERE ${E.join(" AND ")}`),t.groupBy.length>0){const $=t.groupBy.map(N=>m(N.expression)),b=t.rowIdentity.kind==="group"?[Ci($,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)]:[];_+=` GROUP BY ${[...$,...b].join(", ")}`}if(t.having&&Object.keys(t.having).length>0){const $=b=>{const N=t.projections.find(k=>k.name===b);if(!N)throw new p("INVALID_HAVING",`Having field is not an output: ${b}`);return e.supportsHavingAlias===!1?m(N.expression):e.quoteIdentifier(b)};_+=` HAVING ${yt(t.having,$,()=>!1,o,e,s,m,i)}`}if(t.groupLimit&&(_=ki(_,t,e,o)),t.pagination?.kind==="ratio")_=qi(_,t,t.pagination,e,o);else if(t.orderBy.length>0&&(_+=` ORDER BY ${yr(t,e,o,void 0,m)}`),t.pagination?.kind==="rows"){const $=(t.pagination.page-1)*t.pagination.pageSize;_=e.paginate(_,t.pagination.pageSize,$)}return{sql:_,parameters:o.values}},Od=(t,e)=>{const r=Object.keys(e).sort((f,m)=>m.length-f.length),n=[];let o=0;for(;o<t.length;){const f=t[o];if(f&&/\s/.test(f)){o+=1;continue}if(f&&/[()+\-*/,]/.test(f)){n.push(f),o+=1;continue}const m=t.slice(o).match(/^\d+(?:\.\d+)?/);if(m?.[0]){n.push(m[0]),o+=m[0].length;continue}const y=r.find(h=>t.startsWith(h,o));if(y){n.push(y),o+=y.length;continue}const g=t.slice(o).match(/^[A-Za-z_$][\w$]*/);if(g?.[0]){n.push(g[0]),o+=g[0].length;continue}n.push(f??""),o+=1}let i=0;const s=()=>n[i],a=()=>n[i++],u=()=>{const f=a();if(!f)throw new Error("Component expression is incomplete");if(f==="("){const y=l();if(a()!==")")throw new Error("Component expression has an unclosed parenthesis");return`(${y})`}if(/^\d/.test(f))return f;if(!e[f]&&!/^[A-Za-z_$][\w$]*$/.test(f))throw new Error(`Invalid component expression token: ${f}`);if(s()==="("){a();const y=[];if(s()!==")")for(;y.push(l()),s()===",";)a();if(a()!==")")throw new Error("Component expression has an unclosed function call");if(!["ABS","NULLIF","COALESCE"].includes(f.toUpperCase()))throw new Error(`Unsupported component expression function: ${f}`);return`${f.toUpperCase()}(${y.join(", ")})`}const m=e[f];if(!m)throw new Error(`Unknown component in expression: ${f}`);return m},c=()=>{let f=u();for(;s()==="*"||s()==="/";)f=`${f} ${a()} ${u()}`;return f},l=()=>{let f=c();for(;s()==="+"||s()==="-";)f=`${f} ${a()} ${c()}`;return f},d=l();if(i!==n.length)throw new Error(`Unexpected component expression token: ${s()}`);return d},Nd=t=>`__sdb_cte_${t}`,Ui=t=>{const e=t.projections[t.groupBy.length];if(!e)throw new Error("CTE component must produce one metric projection");return e.name},Pd=(t,e)=>t?.find(r=>r.name===e),Td=(t,e,r)=>r===0?t:e.kind==="postgresql"?t.replace(/\$(\d+)/g,(n,o)=>`$${Number(o)+r}`):e.kind==="oracle"?t.replace(/:(\d+)/g,(n,o)=>`:${Number(o)+r}`):e.kind==="clickhouse"?t.replace(/\{p(\d+):([^}]+)\}/g,(n,o,i)=>`{p${Number(o)+r}:${i}}`):t,Pn=(t,e,r,n=Ne())=>{if(t.length===0)throw new Error("CTE query combination requires at least one unit");let o=0;const i=t.map((A,_)=>{const E={...A.compiled,sql:Td(A.compiled.sql,r,o)};return o+=A.compiled.parameters.length,{...A,compiled:E,alias:`__sdb_exec_${_}`}}),s=i.map(({alias:A,compiled:_})=>`${r.quoteIdentifier(A)} AS (${_.sql})`),a=i[0],u=r.quoteIdentifier(a.alias),c=e.groupBy.map(({name:A})=>A),l=e.orderBy??[],d=e.rowIdentity.kind==="group",f=r.quoteIdentifier("__sdb_exec_keys");if(d){const A=_=>[...c.map(E=>`${_}.${r.quoteIdentifier(E)}`),`${_}.${r.quoteIdentifier("_id")}`].join(", ");s.push(`${f} AS (${i.map(({alias:_})=>`SELECT ${A(r.quoteIdentifier(_))} FROM ${r.quoteIdentifier(_)}`).join(" UNION ")})`)}const m=d?f:u,y=[...c,...t.flatMap(({outputs:A})=>A)],g=y.filter((A,_,E)=>E.indexOf(A)===_).map(A=>{if(c.includes(A))return`${m}.${r.quoteIdentifier(A)} AS ${r.quoteIdentifier(A)}`;const _=i.find(({outputs:$})=>$.includes(A));if(!_)throw new Error(`CTE execution unit does not expose output projection: ${A}`);return`${r.quoteIdentifier(_.alias)}.${r.quoteIdentifier(A)} AS ${r.quoteIdentifier(A)}`});d&&g.push(`${m}.${r.quoteIdentifier("_id")} AS ${r.quoteIdentifier("_id")}`);let h=`SELECT ${g.join(", ")} FROM ${m}`;for(const A of d?i:i.slice(1)){const _=r.quoteIdentifier(A.alias);h+=` LEFT JOIN ${_}`,h+=d?` ON ${m}.${r.quoteIdentifier("_id")} = ${_}.${r.quoteIdentifier("_id")}`:" ON 1 = 1"}if(!!(e.having&&Object.keys(e.having).length>0||l.length>0||e.pagination||e.groupLimit)){const A={schemaId:e.schemaId,source:"__sdb_cte_result_source",sourceSql:h,sourceAlias:"__sdb_cte_result",fields:Object.fromEntries(y.map(E=>[E,E])),projections:y.map(E=>({name:E,expression:{kind:"column",property:E,column:E}})),groupBy:[],...e.having&&Object.keys(e.having).length>0?{query:e.having}:{},orderBy:l.map(({name:E,direction:$,comparable:b})=>({name:E,direction:$,...b?{comparable:b}:{}})),...e.pagination?{pagination:e.pagination}:{},...e.groupLimit?{groupLimit:e.groupLimit}:{},rowIdentity:{kind:"generated"}},_=he(A,r,n,o);return{sql:`WITH ${s.join(", ")} ${_.sql}`,parameters:[...i.flatMap(({compiled:E})=>E.parameters),..._.parameters]}}return{sql:`WITH ${s.join(", ")} ${h}`,parameters:i.flatMap(({compiled:A})=>A.parameters)}},hr=(t,e,r,n,o,i)=>{const s=[];let a=0;for(const A of e){const _=he(A.plan,o,i,a);a+=_.parameters.length,s.push({input:A,sql:_,alias:Nd(A.name)})}const u=s.map(({sql:A,alias:_})=>`${o.quoteIdentifier(_)} AS (${A.sql})`).join(", "),c=s[0];if(!c)throw new Error("CTE calculation requires a current component");const l=o.quoteIdentifier(c.alias),d=r.groupBy.map(({name:A})=>A),f=d.map(A=>`${l}.${o.quoteIdentifier(A)} AS ${o.quoteIdentifier(A)}`);let m="";for(const A of s.slice(1)){const _=o.quoteIdentifier(A.alias),E=A.input.plan.groupBy.map(({name:N})=>N),b=(A.input.joinKeys??d.filter(N=>E.includes(N))).map(N=>{const k=Pd(A.input.groupKeyShifts,N),j=k?o.dateShift(`${_}.${o.quoteIdentifier(N)}`,k.granularity,k.offset):`${_}.${o.quoteIdentifier(N)}`;return`${l}.${o.quoteIdentifier(N)} = ${j}`});m+=` LEFT JOIN ${_} ON ${b.length>0?b.join(" AND "):"1 = 1"}`}const y=Object.fromEntries(s.map(({input:A,alias:_})=>[A.name,`${o.quoteIdentifier(_)}.${o.quoteIdentifier(Ui(A.plan))}`])),g=Od(t.expression,y),h=[...f,...r.rowIdentity.kind==="group"?[`${l}.${o.quoteIdentifier("_id")} AS ${o.quoteIdentifier("_id")}`]:[],...s.map(({input:A,alias:_})=>`${`${o.quoteIdentifier(_)}.${o.quoteIdentifier(Ui(A.plan))}`} AS ${o.quoteIdentifier(A.name)}`),`${g} AS ${o.quoteIdentifier(n)}`].join(", ");let w=`WITH ${u} SELECT ${h} FROM ${l}`;return w+=m,{sql:w,parameters:s.flatMap(({sql:A})=>A.parameters)}},Ld=t=>{if(typeof t!="string"||!/\bSELECT\b/i.test(t))return t;try{let e=t;const r=Mi(t).length*2+2;for(let n=0;n<r;n+=1){const o=Dd(e);if(o===e)return e;e=o}return e}catch{return t}},Dd=t=>{const e=Mi(t),r=Cd(t,e);if(r!==t)return r;const n=[];for(const i of e){const s=xi(t,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?zd(t.slice(i.fromStart+4,i.close)):null;if(a){n.push({start:i.open,end:i.close+1,value:a});continue}if(!s||s.some(g=>g.trim()==="*"))continue;const u=Hd(qd(t.slice(i.fromStart,i.close),i,e)),c=kd(t,i),l=Ud(t,i);if(l&&jd(c,l))continue;let d=s.filter(g=>{const h=Vi(g);if(!h||h==="_id")return!0;const w=new RegExp(`(^|[^\\w$])${Tn(h)}([^\\w$]|$)`,"i");return w.test(u)||w.test(c)}),f=!0;for(;f;){f=!1;const g=Fi(d.join(" ")),h=s.filter(w=>{if(d.includes(w))return!1;const A=Vi(w);return A?new RegExp(`(^|[^\\w$])${Tn(A)}([^\\w$]|$)`,"i").test(g):!1});h.length>0&&(d=s.filter(w=>d.includes(w)||h.includes(w)),f=!0)}if(d.length===s.length)continue;const m=t.slice(i.selectEnd,i.fromStart),y=d.length===0&&Gd(t,i)&&!/(^|[^\w$])\*([^\w$]|$)/.test(c)&&!/^\s*(?:DISTINCT|ALL|TOP|SQL_)\b/i.test(m)&&!/\b(?:UNION|INTERSECT|EXCEPT)\b/i.test(u);d.length===0&&!y||n.push({start:i.selectEnd,end:i.fromStart,value:m.match(/^\s*/)[0]+(y?"1":d.map(g=>g.trim()).join(", "))+m.match(/\s*$/)[0]})}n.sort((i,s)=>s.start-i.start);let o=t;for(const i of n)o=o.slice(0,i.start)+i.value+o.slice(i.end);return o},Cd=(t,e)=>{const r=/^\s*SELECT\b/i.exec(t);if(!r)return t;const n=r.index+r[0].length,o=ji(t,"FROM",n);if(o===-1||!xi(t,n,o)?.every(Qd))return t;const s=e.find(f=>f.open>o&&t.slice(o+4,f.open).trim().length===0);if(!s||!/^\s*1\s*$/.test(t.slice(s.selectEnd,s.fromStart)))return t;const a=e.filter(f=>f.open>s.fromStart&&f.close<s.close).sort((f,m)=>m.close-m.open-(f.close-f.open))[0];if(!a||t.slice(s.fromStart+4,a.open).trim().length>0)return t;const u=t.slice(a.close+1,s.close);if(/\b(?:GROUP|HAVING|ORDER|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT)\b/i.test(u))return t;const c=Fd.exec(u)?.[1],l=Bd.exec(t.slice(s.close+1));if(!c||!l||vi(c)!==vi(l[1]))return t;const d=/;(\s*)$/.exec(t)?.[0]??"";return t.slice(0,s.open)+t.slice(a.open,s.close)+d},qd=(t,e,r)=>Md(t,r.filter(n=>n.open>e.open&&n.close<e.close).map(n=>({start:n.open-e.fromStart,end:n.close-e.fromStart+1}))),kd=(t,e)=>{const r=t.slice(0,e.open)+" ".repeat(e.close-e.open+1)+t.slice(e.close+1);return Fi(r)},Ud=(t,e)=>t.slice(e.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${je})(?=\\s|$)`,"i"))?.[1]??null,jd=(t,e)=>new RegExp(`(^|[^\\w$])${Tn(e)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(t),Md=(t,e)=>{if(!e.length)return t;const r=t.split("");for(const n of e)for(let o=Math.max(0,n.start);o<Math.min(r.length,n.end);o+=1)r[o]=" ";return r.join("")},ji=(t,e,r)=>{let n=0,o=0,i="",s="";for(let a=r;a<t.length;a+=1){const u=t[a],c=t[a+1];if(s==="--"){u===`
2
- `&&(s="");continue}if(s==="/*"){u==="*"&&c==="/"&&(s="",a+=1);continue}if(i){u===i&&t[a-1]!=="\\"&&(i="");continue}if(u==="-"&&c==="-"){s="--",a+=1;continue}if(u==="/"&&c==="*"){s="/*",a+=1;continue}if(u==="`"||u==='"'||u==="'"){i=u;continue}if(u==="("){n+=1;continue}if(u===")"){n-=1;continue}if(u==="["){o+=1;continue}if(u==="]"){o-=1;continue}if(n===0&&o===0&&new RegExp(`^${e}\\b`,"i").test(t.slice(a)))return a}return-1},Mi=t=>{const e=[],r=[];let n="",o="";for(let i=0;i<t.length;i+=1){const s=t[i],a=t[i+1];if(o==="--"){s===`
3
- `&&(o="");continue}if(o==="/*"){s==="*"&&a==="/"&&(o="",i+=1);continue}if(n){s===n&&t[i-1]!=="\\"&&(n="");continue}if(s==="-"&&a==="-"){o="--",i+=1;continue}if(s==="/"&&a==="*"){o="/*",i+=1;continue}if(s==="`"||s==='"'||s==="'"){n=s;continue}if(s==="("){r.push({open:i});continue}if(s!==")")continue;const u=r.pop();if(!u)continue;const c=t.slice(u.open+1,i),l=/^\s*SELECT\b/i.exec(c);if(!l)continue;const d=u.open+1+l.index,f=ji(t,"FROM",d+6);f===-1||f>=i||e.push({open:u.open,close:i,selectEnd:d+6,fromStart:f})}return e},xi=(t,e,r)=>{const n=t.slice(e,r),o=[];let i=0,s=0,a=0,u="";for(let c=0;c<n.length;c+=1){const l=n[c];if(u){l===u&&n[c-1]!=="\\"&&(u="");continue}if(l==="`"||l==='"'||l==="'"){u=l;continue}l==="("?s+=1:l===")"?s-=1:l==="["?a+=1:l==="]"?a-=1:l===","&&s===0&&a===0&&(o.push(n.slice(i,c)),i=c+1)}return u||s!==0||a!==0?null:(o.push(n.slice(i)),o)},Vi=t=>t.trim().match(/\bAS\s+(`[^`]+`|"[^"]+"|[A-Za-z_][\w$]*)\s*$/i)?.[1]?.replace(/^`|`$/g,"").replace(/^"|"$/g,"")??null,je='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',xd=new RegExp(`\\s+AS\\s+${je}\\s*$`,"i"),Vd=new RegExp(`\\bAS\\s+${je}`,"gi"),vd=new RegExp(`(?:${je}\\s*\\.\\s*)+${je}`,"g"),Yd=new RegExp(`^${je}(?:\\s*\\.\\s*${je})*$`),Fd=new RegExp(`^\\s*(?:AS\\s+)?(${je})\\s+WHERE\\b`,"i"),Bd=new RegExp(`^\\s*(?:AS\\s+)?(${je})\\s*;?\\s*$`,"i"),vi=t=>t.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),Qd=t=>{const e=t.replace(xd,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(e)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(e)},Yi=(t,e)=>t.replace(e,r=>" ".repeat(r.length)),Fi=t=>Yi(t,Vd),Hd=t=>Yi(t,vd),Gd=(t,e)=>/\b(?:FROM|JOIN)\s*$/i.test(t.slice(0,e.open)),zd=t=>{const e=t.trim();return Yd.test(e)?e:null},Tn=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ln=(t,e)=>{if(t.kind!=="operator")return!1;const r=e.get(t.operator);return!r.toSQL&&!!r.evaluate||(t.input?Ln(t.input,e):!1)||(t.inputs?.some(n=>Ln(n,e))??!1)},Bi=(t,e,r,n)=>{if(t.kind!=="operator")return e[r];const o=n.get(t.operator),i=t.input?Bi(t.input,e,r,n):e[r];return o.evaluate?Promise.resolve(i).then(s=>o.evaluate?.({input:s,args:t.args})):i},Xe=async(t,e,r)=>{const n=e.filter(({expression:o})=>Ln(o,r));return n.length===0?[...t]:Promise.all(t.map(async o=>{const i={...o};for(const s of n)i[s.name]=await Bi(s.expression,i,s.name,r);return i}))},gr=t=>t==null?"\u7A7A\u503C":typeof t=="object"?"_id"in t?String(t._id):"id"in t?String(t.id):JSON.stringify(t):String(t),Dn=(t,e,r="_",n="\u7A7A\u503C")=>e.map(o=>t[o]===null||t[o]===void 0?n:gr(t[o])).join(r),Cn=(t,e)=>t.map(r=>{if(e.kind==="property"){const{[e.internalName]:n,...o}=r;return{...o,_id:String(n)}}return e.kind==="group"?{...r,_id:r._id===void 0?Dn(r,e.names,e.separator,e.nullLabel):gr(r._id)}:{...r,_id:e.kind==="singleton"?"0":yo.randomUUID()}}),Wd=t=>{const e=Z(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Mt=(t,e)=>t.operator&&e.get(t.operator).kind==="component"?!0:!!t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&Mt(t.pred,e)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Mt(r,e)),$r=(t,e,r,n,o,i,s="zh-CN",a=tr.translator(s))=>{const u=t.preds??[],c=u.map((m,y)=>({pred:m,index:y,definition:m.operator?n.get(m.operator):void 0})).filter(({definition:m})=>m?.kind==="component"&&!m.skipComponentExecution?.({plan:e}));if(c.length===0&&e.sourcePlan||c.length===0)return;for(const m of u)if((!m.operator||n.get(m.operator).kind!=="component")&&(m.pred&&typeof m.pred=="object"&&!Array.isArray(m.pred)&&Mt(m.pred,n)||Array.isArray(m.pred)&&m.pred.some(y=>typeof y!="string"&&Mt(y,n))))throw new p("UNSUPPORTED_COMPONENT_NESTING","A component operator must currently be the top-level projection operator");const l=[],d=u.filter((m,y)=>!c.some(g=>g.index===y));if(d.length>0){const m=Wd(t);m.preds=d,l.push({kind:"query",logicform:m})}const f=t.groupby?.length??0;for(const{pred:m,index:y,definition:g}of c){const h=g?.createComponent;if(!h)continue;const w=e.projections[f+y]?.name;if(!w)throw new p("INVALID_COMPONENT_PLAN","Component output projection is missing");const A=i?.preds?.[y],_=h({logicform:t,pred:A??m,outputName:w,locale:s,t:a,schema:r,resolveSchema:o,...i?{sourceLogicform:i}:{}});if("logicform"in _&&(_.logicform.preds??[]).some(E=>Mt(E,n)))throw new p("UNSUPPORTED_COMPONENT_NESTING","Nested component operators are not supported yet");l.push("components"in _?{..._,outputName:w}:_)}return l},Ce=t=>t instanceof Date?t.getTime():t,Kd=(t,e,r,n)=>{const o=Ce(t),i=Ce(r);switch(e){case"$eq":return o===i;case"$ne":return o!==i;case"$gt":return o!=null&&i!==void 0&&i!==null&&o>i;case"$gte":return o!=null&&i!==void 0&&i!==null&&o>=i;case"$lt":return o!=null&&i!==void 0&&i!==null&&o<i;case"$lte":return o!=null&&i!==void 0&&i!==null&&o<=i;case"$in":return Array.isArray(r)&&r.some(s=>Ce(s)===o);case"$nin":return Array.isArray(r)&&r.every(s=>Ce(s)!==o);case"$exists":return r?t!=null:t==null;case"$contains":return String(t).includes(String(r));case"$startsWith":return typeof t=="string"&&typeof r=="string"&&t.startsWith(r);case"$regex":return typeof r=="string"&&new RegExp(r,n).test(String(t));default:throw new p("UNSUPPORTED_QUERY_OPERATOR",`Unsupported having operator: ${e}`)}},qn=(t,e)=>{if(!e||typeof e!="object"||Array.isArray(e))return Ce(t)===Ce(e);const r=Object.entries(e),n=e.args,o=n&&typeof n=="object"&&!Array.isArray(n)?n.options:void 0;return r.every(([i,s])=>{if(i==="args")return!0;if(i==="$and"||i==="$or"){if(!Array.isArray(s))return!1;const a=s.map(u=>qn(t,u));return i==="$and"?a.every(Boolean):a.some(Boolean)}return i==="$length"?typeof t=="string"&&qn(t.length,s):Kd(t,i,s,typeof o=="string"?o:void 0)})},Qi=(t,e)=>Object.entries(e).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>Qi(t,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return qn(t[r],n)}),Hi=(t,e)=>e.length===0?"0":t._id===void 0?Dn(t,e):gr(t._id),kn=(t,e)=>{const r=new Map;for(const n of t)for(const o of n){const i=Hi(o,e);r.set(i,{...r.get(i)??{},...o})}return[...r.values()]},Un=(t,e)=>{const r=e.groupBy.map(({name:o})=>o);let n=kn(t,r);if(e.having&&(n=n.filter(o=>Qi(o,e.having))),e.groupLimit){const o=e.groupLimit,i=new Map;for(const s of n){const a=Hi(s,o.partitionBy);i.set(a,[...i.get(a)??[],s])}n=[...i.values()].flatMap(s=>s.sort((a,u)=>{for(const c of o.orderBy){const l=Ce(a[c.name]),d=Ce(u[c.name]);if(l!==d)return l==null?c.direction==="ASC"?-1:1:d==null?c.direction==="ASC"?1:-1:(l<d?-1:1)*(c.direction==="ASC"?1:-1)}return 0}).slice(0,o.count))}if(e.orderBy.length>0&&n.sort((o,i)=>{for(const s of e.orderBy){const a=Ce(o[s.name]),u=Ce(i[s.name]);if(a!==u)return a==null?s.direction==="ASC"?-1:1:u==null?s.direction==="ASC"?1:-1:(a<u?-1:1)*(s.direction==="ASC"?1:-1)}return 0}),e.pagination?.kind==="rows"){const o=(e.pagination.page-1)*e.pagination.pageSize;n=n.slice(o,o+e.pagination.pageSize)}else if(e.pagination?.kind==="ratio"){const o=Math.ceil(n.length*e.pagination.ratio),i=(e.pagination.page-1)*o;n=n.slice(i,i+o)}return n},Gi=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new p("SCHEMA_RESOLVER_REQUIRED",`Cannot normalize nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n};class jn{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new p("INVALID_SEMANTIC_TYPE","Semantic type name must not be empty");if(this.#e.has(e.name))throw new p("SEMANTIC_TYPE_ALREADY_REGISTERED",`Semantic type is already registered: ${e.name}`,{type:e.name});return this.#e.set(e.name,e),this}get(e){const r=this.#e.get(e);if(!r)throw new p("SEMANTIC_TYPE_NOT_FOUND",`Semantic type is not registered: ${e}`,{type:e});return r}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}requiresPerPeriodEvaluation(e){return e.property?this.get(e.property.type).requiresPerPeriodEvaluation?.({...e,property:e.property})??!1:!1}}const Jd=t=>{const e=new Set,r=new Set;for(const n of t){if(!n.name)throw new p("INVALID_PROPERTY_NAME","Property name must not be empty");if(!n.id)throw new p("INVALID_PROPERTY_ID",`Property ${n.name} physical id must not be empty`);if(e.has(n.name))throw new p("DUPLICATE_PROPERTY_NAME",`Duplicate property name: ${n.name}`,{property:n.name});if(r.has(n.id))throw new p("DUPLICATE_PROPERTY_ID",`Duplicate property physical id: ${n.id}`,{propertyId:n.id});e.add(n.name),r.add(n.id)}},zi=t=>{Jd(t);const e=t.filter(({type:r})=>r==="timestamp");if(e.length>1)throw new p("MULTIPLE_TIMESTAMP_PROPERTIES","A Schema can declare at most one timestamp Property",{properties:e.map(({name:r})=>r)})},Xd=new Set(["second","minute","hour","day","week","month","quarter","year"]),Zd=(t,e)=>{if("_id"in t||"_sid"in t)throw new p("LEGACY_PROPERTY_ID_NOT_ALLOWED",`Property ${t.name} must use id instead of _id; _sid is not supported`,{property:t.name});if("sid"in t)throw new p("PROPERTY_SID_NOT_ALLOWED",`Property ${t.name} must not declare sid`,{property:t.name});const r=t;if(r.is_comparable!==void 0||r.comparable_order!==void 0)throw new p("LEGACY_COMPARABLE_NOT_ALLOWED",`Property ${t.name} must use comparable instead of is_comparable/comparable_order`,{property:t.name});if(t.udf!==void 0){const a=t.udf;if(typeof a!="object"||a===null||Array.isArray(a))throw new p("INVALID_PROPERTY_UDF",`Property ${t.name} udf must be an object containing only sql`,{property:t.name});const u=a,c=Object.keys(u).filter(l=>l!=="sql");if(c.length>0)throw new p("UNSUPPORTED_PROPERTY_UDF",`Property ${t.name} udf only supports sql`,{property:t.name,unsupportedKeys:c});if(typeof u.sql!="string"||u.sql.trim().length===0)throw new p("INVALID_PROPERTY_UDF",`Property ${t.name} udf.sql must be a non-empty string`,{property:t.name})}const n=e.get(t.type),o=t.primal_type==="object"?"entity":t.primal_type;if(o!==void 0&&o!==n.primalType)throw new p("PRIMAL_TYPE_MISMATCH",`Property ${t.name} declares primal_type ${t.primal_type}, but ${t.type} requires ${n.primalType}`,{property:t.name,type:t.type,declared:t.primal_type,expected:n.primalType});if(t.isArray!==void 0&&typeof t.isArray!="boolean")throw new p("INVALID_IS_ARRAY",`Property ${t.name} isArray must be a boolean`,{property:t.name,isArray:t.isArray});if("is_observation"in t)throw new p("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED",`Property ${t.name} must use Schema temporalSemantics; is_observation is not supported`,{property:t.name});if(t.comparable!==void 0){const a=t.comparable;if(typeof a!="object"||a===null||Array.isArray(a))throw new p("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable must contain values and direction`);const u=a;if(Object.keys(u).some(c=>c!=="values"&&c!=="direction")||!Array.isArray(u.values)||u.values.length===0||u.values.some(c=>typeof c!="string")||new Set(u.values).size!==u.values.length||u.direction!==1&&u.direction!==-1)throw new p("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable requires unique string values and direction 1 or -1`,{property:t.name,comparable:a});if(t.type!=="category"||t.isArray===!0)throw new p("COMPARABLE_CATEGORY_REQUIRED",`Property ${t.name} comparable is only supported by scalar category properties`,{property:t.name,type:t.type})}const i={...t,id:t.id??t.name,primal_type:n.primalType,isArray:t.isArray??!1,is_dynamic:t.udf?.sql!==void 0,...n.primalType==="date"?{granularity:t.granularity??"day"}:{}};if(n.primalType==="entity"||n.primalType==="object"){if(typeof i.ref!="string"||i.ref.length===0)throw new p("PROPERTY_REF_REQUIRED",`Entity property ${i.name} must declare ref`,{property:i.name,type:i.type})}else if(i.ref!==void 0)throw new p("PROPERTY_REF_NOT_ALLOWED",`Property ${i.name} cannot declare ref unless its primal_type is entity`,{property:i.name,type:i.type});if(n.primalType==="date"||t.type==="duration"){if(i.granularity!==void 0&&!Xd.has(i.granularity))throw new p("INVALID_GRANULARITY",`Property ${i.name} has unsupported granularity: ${i.granularity}`,{property:i.name,granularity:i.granularity})}else if(i.granularity!==void 0)throw new p("GRANULARITY_NOT_ALLOWED",`Property ${i.name} cannot declare granularity unless its type supports it`,{property:i.name,type:i.type});return n.validateProperty?.(i),i},Wi=(t,e,r=[])=>{const n=me(r),o=n.reduce((m,y)=>y.prepareSchema?.(m)??m,t);if("_id"in o||"_sid"in o)throw new p("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported");if("sid"in o)throw new p("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid");if("is_snapshot"in o||"is_observation"in o)throw new p("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED","Schema must use temporalSemantics instead of is_snapshot/is_observation",{schemaId:o.id});if(!o.id)throw new p("INVALID_SCHEMA_ID","Schema id must not be empty");const i=n.flatMap(m=>m.propertyMetadata?[m.propertyMetadata]:[]),s=new Set(i.flatMap(({keys:m})=>m));let a=o.properties.map(m=>{const y=Object.fromEntries(Object.entries(m).filter(([h])=>!s.has(h))),g=Zd(y,e);return i.reduce((h,w)=>({...h,...w.resolve(m,h,o)}),g)});for(const m of i)a=[...m.resolveAll?.(a,o.properties,o)??a];zi(a);const u=n.flatMap(m=>m.schemaMetadata?[m.schemaMetadata]:[]);let c={};for(const m of u)c={...c,...m.resolve(o,a)};const l=new Set(n.flatMap(m=>[...m.schemaMetadata?.keys??[],...m.legacySchemaKeys??[]])),f={...Object.fromEntries(Object.entries(o).filter(([m])=>!l.has(m))),properties:a,...c};for(const m of n)m.validateResolvedSchema?.(f);return f};se.extend(mo),se.extend(Rt),se.extend(Kt);const ep="YYYY-MM-DD HH:mm:ss",tp=new Set(["YTD","QTD","MTD","WTD","DTD"]),Ki=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),rp=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),wr=["second","minute","hour","day","week","month","quarter","year"],Ze=t=>Object.prototype.toString.call(t)==="[object Object]",Ji=(t,e)=>{const r=n=>{if(typeof n!="number"||!Number.isSafeInteger(n))throw new p("INVALID_DATE_PART_QUERY",`${e} requires integer values`)};if(typeof t=="number"){r(t);return}if(Array.isArray(t)){t.forEach(r);return}if(Ze(t)){const n=Object.entries(t);if(n.length===0||n.some(([o])=>!Ki.has(o)))throw new p("INVALID_DATE_PART_QUERY",`${e} requires numeric comparison operators`);for(const[o,i]of n)if(o==="$and"||o==="$or"){if(!Array.isArray(i)||i.length===0)throw new p("INVALID_DATE_PART_QUERY",`${e}.${o} requires a non-empty array`);i.forEach(s=>Ji(s,e))}else if(o==="$in"||o==="$nin"){if(!Array.isArray(i))throw new p("INVALID_DATE_PART_QUERY",`${e}.${o} requires an array`);i.forEach(r)}else r(i);return}throw new p("INVALID_DATE_PART_QUERY",`${e} requires integer values`)},Mn=t=>!Ze(t)||"$gte"in t||"$gt"in t||"$lte"in t||"$lt"in t||"$or"in t||"$ne"in t?!1:typeof t.granularity=="string"&&wr.includes(t.granularity)&&typeof t.offset=="number"||wr.some(e=>e in t),ht=t=>se(t).format(ep),np=(t,e)=>wr.find(r=>r in t||e!==void 0),op=(t,e,r)=>e==="month"?t.month(r-1):e==="day"?t.date(r):e==="week"?t.isoWeek(r):e==="quarter"?t.quarter(r):t.set(e,r),Xi=(t,e)=>{const r=typeof t.granularity=="string"?t.granularity:void 0,n=r?{[r]:t.offset}:void 0,o=r??np(t,void 0)??"day";let i=se(e).millisecond(0);for(const a of[...wr].reverse()){const u=t[a];typeof u=="number"&&(i=op(i,a,u));const c=n?.[a];typeof c=="number"&&c!==0&&(i=i.add(c,a))}const s=o==="week"?"isoWeek":o;return{$gte:ht(i.startOf(s)),$lte:ht(i.endOf(s))}},ip=(t,e)=>{const r=se(e),o={DTD:()=>r.startOf("day"),WTD:()=>r.startOf("isoWeek"),MTD:()=>r.startOf("month"),QTD:()=>r.startOf("quarter"),YTD:()=>r.startOf("year")}[t];return{$gte:ht(o()),$lte:ht(r.endOf("day"))}},xn=async(t,e)=>{const r=se(String(t.$lte)),n=await e.requestTimeWatermark(r.toDate());if(!n)return t;const o=e.property.granularity??"day",i=o==="week"?"isoWeek":o,s=se(n).endOf(i),a=se(String(t.$gte));if(a.isValid()&&s.isBefore(a))return t;const u=s.isBefore(r)?s:r;return{...t,$lte:ht(u)}},Vn=async(t,e)=>Ie(t)?t:t instanceof Date||typeof t=="string"&&se(t).isValid()?ht(t):typeof t=="string"&&tp.has(t)?xn(ip(t,e.now),e):Mn(t)?xn(Xi(t,e.now),e):t,Zi=async(t,e,r)=>{if(t==="$and"||t==="$or")return Array.isArray(e)?Promise.all(e.map(o=>Ar(o,r))):e;if(Array.isArray(e))return Promise.all(e.map(o=>Vn(o,r)));const n=await Vn(e,r);return t==="$eq"&&Ze(n)&&"$gte"in n&&"$lte"in n?n:t==="$gte"||t==="$gt"?Ze(n)&&"$gte"in n?n.$gte:n:(t==="$lte"||t==="$lt")&&Ze(n)&&"$lte"in n?n.$lte:n},Ar=async(t,e)=>{if(Ie(t))return t;if(Array.isArray(t))return Promise.all(t.map(o=>Ar(o,e)));if(!Ze(t))return Vn(t,e);if("$options"in t)throw new p("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");if("$offset"in t)throw new p("UNSUPPORTED_DATE_VALUE","The legacy {$offset: ...} date form is not supported; use { granularity, offset }");if(("granularity"in t||"offset"in t)&&(!Mn(t)||!Number.isInteger(t.offset)))throw new p("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(Mn(t))return xn(Xi(t,e.now),e);const r=Object.entries(t);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await Zi("$eq",r[0][1],e);if(Ze(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)rp.has(o)&&Ji(i,o),n[o]=Ki.has(o)?await Zi(o,i,e):await Ar(i,e);return n},sp=(t,e)=>e.property.primal_type==="date"?Ar(t,e):t,vn=(t=[])=>new jn([...hn,...me(t).flatMap(({semanticTypes:e})=>e??[])]),es=(t,e)=>{const r=new jn(t.definitions());for(const n of me(e))for(const o of n.semanticTypes??[])if(!r.has(o.name))r.register(o);else if(r.get(o.name)!==o)throw new p("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${o.name}`,{semanticType:o.name,plugin:n.name});return r},ap=/^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,cp=t=>{if(typeof t!="string")return!1;const e=ap.exec(t);if(!e)return!1;const r=Number(e[1]),n=Number(e[2]),o=Number(e[3]??0);return r!==2?r>2:n>0||o>0?!0:e[4]===void 0},Yn=t=>{if(!cp(t.version))throw new p("UNSUPPORTED_LOGICFORM_VERSION",`This library only supports LogicForm version 2.0 or later; received ${JSON.stringify(t.version)}`,{minimumVersion:"2.0",receivedVersion:t.version})},ts=(t,e)=>Object.entries(t).some(([r,n])=>e.has(r)?!0:r!=="$and"&&r!=="$or"||!Array.isArray(n)?!1:n.some(o=>typeof o=="object"&&o!==null&&!Array.isArray(o)&&ts(o,e))),rs=(t,e,r,n=[])=>{if(e===void 0||e==="placeholder")return t;if(!Zr(e))throw new p("INVALID_ENTITY_ID","entity_id must be a non-empty string or a safe integer");const o=en(r,n);return t&&ts(t,new Set([o.name,o.id]))?t:{[o.name]:e,...t??{}}},gt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),up={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},ns={$second:{zh:"\u79D2",en:"second"},$minute:{zh:"\u5206\u949F",en:"minute"},$hour:{zh:"\u5C0F\u65F6",en:"hour"},$weekday:{zh:"\u661F\u671F",en:"weekday"},$day:{zh:"\u65E5",en:"day of month"},$week:{zh:"\u5468",en:"week"},$month:{zh:"\u6708",en:"month"},$quarter:{zh:"\u5B63\u5EA6",en:"quarter"},$year:{zh:"\u5E74",en:"year"}},$t=(t,e)=>{if(t===null)return e?"null":"\u7A7A\u503C";if(typeof t=="string"||typeof t=="number")return String(t);if(typeof t=="boolean")return e?String(t):t?"\u662F":"\u5426";if(Array.isArray(t))return t.map(n=>$t(n,e)).join(e?", ":"\u3001");if(!gt(t))return e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6";if(Array.isArray(t.roots))return t.roots.map(n=>$t(n,e)).join(e?", ":"\u3001");if(t.root!==void 0)return $t(t.root,e);const r=["year","quarter","month","week","day","hour","minute","second"].filter(n=>t[n]!==void 0).map(n=>e?`${n} ${String(t[n])}`:`${String(t[n])}${up[n]??""}`);return r.length>0?r.join(e?", ":""):e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6"},Er=(t,e,r)=>t.filter(Boolean).join(r?e==="$and"?" and ":" or ":e==="$and"?"\u4E14":"\u6216"),os=(t,e,r,n)=>{const s=(n?{$eq:"is",$ne:"is not",$gt:"is greater than",$gte:"is at least",$lt:"is less than",$lte:"is at most",$in:"is one of",$nin:"is none of",$contains:"contains",$startsWith:"starts with",$regex:"matches",$recursive:"is"}:{$eq:"\u4E3A",$ne:"\u4E0D\u4E3A",$gt:"\u5927\u4E8E",$gte:"\u5927\u4E8E\u7B49\u4E8E",$lt:"\u5C0F\u4E8E",$lte:"\u5C0F\u4E8E\u7B49\u4E8E",$in:"\u4E3A",$nin:"\u4E0D\u4E3A",$contains:"\u5305\u542B",$startsWith:"\u4EE5",$regex:"\u5339\u914D",$recursive:"\u5C5E\u4E8E"})[t];if(!s)return;const a=t==="$startsWith"?n?"":"\u5F00\u5934":t==="$in"?n?"":"\u4E4B\u4E00":t==="$nin"?n?"":"\u4E2D\u7684\u4EFB\u4E00\u9879":t==="$recursive"?n?" or a descendant":"\u53CA\u5176\u4E0B\u7EA7":"";return n?`${e} ${s} ${r}${a}`:`${e}${s}${r}${a}`},xt=(t,e,r)=>{if(!gt(e)||Object.keys(e).every(o=>!o.startsWith("$")))return os("$eq",t,$t(e,r),r)??"";const n=[];for(const[o,i]of Object.entries(e))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Er(i.map(s=>xt(t,s,r)),o,r));else if(o==="$exists")n.push(r?`${t} ${i?"exists":"does not exist"}`:`${i?"\u6709":"\u65E0"}${t}`);else if(ns[o]){const s=ns[o];n.push(xt(r?`${t} ${s.en}`:`${t}\u7684${s.zh}`,i,r))}else if(o==="$length")n.push(xt(r?`${t} length`:`${t}\u957F\u5EA6`,i,r));else if(o!=="args"){const s=o==="$regex"&&gt(i)?$t(i.pattern,r):$t(i,r),a=os(o,t,s,r);a&&n.push(a)}return Er(n,"$and",r)},is=(t,e="zh-CN")=>{const r=e.toLowerCase().startsWith("en"),n=[];for(const[o,i]of Object.entries(t))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Er(i.map(s=>gt(s)?is(s,e):""),o,r));else if(o==="$expr"&&gt(i)){const s=i.pred,a=gt(s)&&typeof s.name=="string"?s.name:r?"expression":"\u8868\u8FBE\u5F0F";i.condition!==void 0&&n.push(xt(a,i.condition,r))}else i!==void 0&&n.push(xt(o,i,r));return Er(n,"$and",r)},wt=(t,e,r={})=>{if(t.name!==void 0){if(typeof t.name!="string"||t.name.length===0)throw new p("INVALID_PRED_NAME","PredItem name must be a non-empty string");return t.name}const n=r.locale??"zh-CN",o=r.localeRegistry??tr,i=o.resolve(n).locale.toLowerCase().startsWith("en"),s=o.translator(n),a=Array.isArray(t.pred)?t.pred.map(m=>typeof m=="string"?m:wt(m,e,r)):[],u=typeof t.pred=="string"?t.pred:t.pred&&!Array.isArray(t.pred)?wt(t.pred,e,r):void 0,c=u??(a.length>0?a.join(i?", ":"\u3001"):s("operator.rows",i?"rows":"\u6570\u636E\u884C")),l=t.args??{},d=t.operator?(()=>{const m=e.get(t.operator),y={operandName:c,...u?{inputName:u}:{},inputNames:a,args:l,locale:n,t:s},g=m.defaultName(y);if(typeof g!="string"||g.length===0)throw new p("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});const h=typeof l.granularity=="string"?s(`time.granularity.${l.granularity}`,l.granularity):s("time.granularity.period","\u5468\u671F"),w=i?t.operator==="$concat"?" and ":t.operator==="$multiply"?" times ":" plus ":t.operator==="$concat"?"\u4E0E":t.operator==="$multiply"?"\u4E58\u4EE5":"\u52A0";if(m.defaultNameIsLocalized)return g;const A=typeof m.defaultNameKey=="function"?m.defaultNameKey(y):m.defaultNameKey??`operator.${t.operator}`;return s(A,g,{...l,operandName:c,inputName:u??"",inputNames:a.join(w),input0:a[0]??"",input1:a[1]??"",granularity:h})})():c;if(typeof d!="string"||d.length===0)throw new p("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});if(!t.query)return d;const f=is(t.query,n);return f?i?`${d} where ${f}`:`${f}\u7684${d}`:d},dp=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},pp=t=>{if(t.args===void 0||Object.keys(t.args).length>0)return t;const{args:e,...r}=t;return r},Vt=async(t,e,r,n)=>{if("components"in t)throw new p("PRED_COMPONENTS_NOT_ALLOWED","PredItem components is not supported; use a pred array for multiple inputs");const o=r.operators,i={...r.locale?{locale:r.locale}:{},...r.localeRegistry?{localeRegistry:r.localeRegistry}:{}};if(!o)throw new Error("Normalizer operator registry is not initialized");if(t.name!==void 0&&(typeof t.name!="string"||t.name.length===0))throw new p("INVALID_PRED_NAME","PredItem name must be a non-empty string");if(t.name==="_id")throw new p("RESERVED_OUTPUT_NAME","PredItem name _id is reserved for executor-owned row identity");if(t.args!==void 0&&!dp(t.args))throw new p("INVALID_OPERATOR_ARGS","Pred args must be a plain object");const s=t.schema===void 0||t.schema===e.id?e:r.resolveSchema?.(t.schema);if(!s)throw new p("SCHEMA_RESOLVER_REQUIRED",`Cross-Schema pred requires Schema ${t.schema}`);const a=await n(t.query,s,r),u=Array.isArray(t.pred)?await Promise.all(t.pred.map(m=>Vt(typeof m=="string"?{pred:m}:m,s,r,n))):void 0,{query:c,...l}=t,d={...l,...a?{query:a}:{},...u?{pred:u}:{}},f=m=>{const y=m.operator?o.get(m.operator).normalizePred?.({pred:m,schema:s})??m:m;return pp(y)};if(typeof t.pred=="string"){const m=ae(s,t.pred,r.resolveSchema),y={...d,pred:m.canonicalName};return f({...y,name:y.name??wt(y,o,i)})}if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)){const m={...d,pred:await Vt(t.pred,s,r,n)};return f({...m,name:m.name??wt(m,o,i)})}if(u)return f({...d,name:d.name??wt(d,o,i)});if(t.pred!==void 0)throw new p("UNSUPPORTED_PRED","A pred must be a property name or nested pred");return f({...d,name:d.name??wt(d,o,i)})},lp=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),fp=t=>{if(!Ie(t))return!1;const e=t;return e.groupby!==void 0||e.preds!==void 0||e.from!==void 0||e.having!==void 0||e.sort!==void 0||e.limit!==void 0||e.limitBy!==void 0||e.page!==void 0},Ir=async(t,e)=>{if(Ie(t)){if(!e.normalizeNestedLogicform)throw new p("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");return e.normalizeNestedLogicform(t)}return Array.isArray(t)?Promise.all(t.map(r=>Ir(r,e))):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(await Promise.all(Object.entries(t).map(async([r,n])=>[r,await Ir(n,e)])))},ss=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>ss(o,e))]:[`${e}_${r}`,n])),Fn=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const e=Object.entries(t),[r]=e;return e.length===1&&r?.[0]==="$eq"?r[1]:t},as=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),Bn=new Set([...as,"$length"]),_r=t=>Array.isArray(t)?t.some(_r):typeof t!="object"||t===null||Ie(t)?!1:Object.entries(t).some(([e,r])=>Bn.has(e)||_r(r)),cs=(t,e)=>{if(!(typeof t=="number"&&Number.isFinite(t))){if(Array.isArray(t)){if(t.every(r=>typeof r=="number"&&Number.isFinite(r)))return;throw new p("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}if(typeof t=="object"&&t!==null&&!Ie(t)){for(const[r,n]of Object.entries(t)){if(!r.startsWith("$"))throw new p("INVALID_QUERY_VALUE",`${e} requires numeric conditions`);if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new p("INVALID_QUERY_VALUE",`${r} requires an array`);n.forEach(o=>cs(o,e))}else if(r==="$in"||r==="$nin"){if(!Array.isArray(n)||n.some(o=>typeof o!="number"||!Number.isFinite(o)))throw new p("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}else if(typeof n!="number"||!Number.isFinite(n))throw new p("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}return}throw new p("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}},Sr=(t,e)=>{if(t.schema!==void 0)throw new p("EXPRESSION_QUERY_SCHEMA_NOT_ALLOWED","$expr.pred is scoped to the query Schema and cannot define schema");if(t.query)throw new p("EXPRESSION_QUERY_PRED_QUERY_NOT_ALLOWED","$expr.pred cannot define pred.query");if(t.operator){if(!e.operators)throw new Error("Normalizer operator registry is not initialized");const r=e.operators.get(t.operator);if(r.kind!=="scalar"||!r.toSQL)throw new p("OPERATOR_NOT_ALLOWED_IN_EXPRESSION_QUERY",`Operator ${t.operator} cannot be used in $expr`,{operator:t.operator})}t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&Sr(t.pred,e);for(const r of Array.isArray(t.pred)?t.pred:[])typeof r!="string"&&Sr(r,e)},us=async(t,e,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new p("INVALID_EXPRESSION_QUERY","$expr must be an object");const n=t,o=Object.keys(n).filter(u=>u!=="pred"&&u!=="condition");if(o.length>0||!Object.prototype.hasOwnProperty.call(n,"condition"))throw new p("INVALID_EXPRESSION_QUERY","$expr must contain exactly pred and condition",{unsupported:o});if(typeof n.pred!="object"||n.pred===null||Array.isArray(n.pred))throw new p("INVALID_EXPRESSION_QUERY","$expr.pred must be a pred expression");const i=n.pred;if(!i.operator)throw new p("EXPRESSION_QUERY_OPERATOR_REQUIRED","$expr.pred must define a scalar operator");if(!r.operators)throw new Error("Normalizer operator registry is not initialized");Sr(i,r);const s=await Vt(i,e,r,()=>Promise.resolve(void 0));Sr(s,r);const a=Fn(await Ir(n.condition,r));return Bn.has(s.operator)&&cs(a,s.operator),{pred:s,condition:a}},ds=async(t,e,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||Ie(e))return{[t]:e};const o={},i=[];for(const[s,a]of Object.entries(e))Bn.has(s)?i.push({$expr:await us({pred:{operator:s,pred:t},condition:a},r,n)}):(s==="$and"||s==="$or")&&Array.isArray(a)&&a.some(_r)?i.push({[s]:await Promise.all(a.map(u=>ds(t,u,r,n)))}):o[s]=a;return Object.keys(o).length>0&&i.unshift({[t]:Fn(o)}),i.length===1?i[0]??{}:{$and:i}},Qn=t=>Array.isArray(t)?t.some(Qn):typeof t!="object"||t===null||Ie(t)?!1:Object.entries(t).some(([e,r])=>as.has(e)||Qn(r)),ps=async(t,e,r,n)=>{const o=c=>{if(Array.isArray(c)){c.forEach(o);return}if(typeof c!="object"||c===null||Ie(c))return;const l=c;if("$options"in l)throw new p("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");Object.values(l).forEach(o)};if(o(t),r.primal_type!=="date"&&Qn(t))throw new p("INVALID_DATE_PART_QUERY",`Date-part query Operators require a date Property: ${r.name}`,{property:r.name});const i=n.semanticTypes.get(r.type),s={schema:e,property:r,now:n.now??new Date,requestTimeWatermark:c=>n.requestTimeWatermark?.(e,r,c)??Promise.resolve(void 0)},a=await sp(Z(t),s),u=i.normalizeQuery?i.normalizeQuery(a,s):a;if(r.comparable){const c=new Set(r.comparable.values),l=(d,f)=>{if(!(Ie(d)||d===null)){if(Array.isArray(d)){d.forEach(m=>l(m,f));return}if(typeof d=="object"){Object.entries(d).forEach(([m,y])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(m)||l(y,m)});return}if(!(f&&["$exists","$regex","$contains","$startsWith","$length"].includes(f))&&(typeof d!="string"||!c.has(d)))throw new p("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${r.name} does not contain value: ${JSON.stringify(d)}`,{property:r.name,value:d})}};l(u)}return u},Hn=async(t,e,r)=>{const n={},o=[],i=[],s=a=>{const u=Object.entries(a);if(u.length===1&&u[0]?.[0]==="$and"&&Array.isArray(u[0][1]))for(const c of u[0][1])s(c);else u.length===1&&u[0]?.[0]==="$expr"?o.push(a):u.every(([c])=>!c.startsWith("$"))?Object.assign(n,a):i.push(a)};for(const[a,u]of Object.entries(t)){if(a==="$and"||a==="$or"){if(!Array.isArray(u))throw new p("INVALID_QUERY_VALUE",`${a} requires an array`);n[a]=await Promise.all(u.map(async m=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new p("INVALID_QUERY_VALUE",`${a} items must be query objects`);return Hn(m,e,r)}));continue}if(a==="$expr"){o.push({$expr:await us(u,e,r)});continue}const c=ae(e,a,r.resolveSchema);if(fp(u)&&(c.property.primal_type==="entity"||c.property.primal_type==="object")&&c.property.ref){if(u.schema!==c.property.ref)throw new p("RELATION_SCHEMA_MISMATCH",`Relation ${c.canonicalName} references ${c.property.ref}, not ${u.schema??"undefined"}`);if(!r.normalizeNestedLogicform)throw new p("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");const m=await r.normalizeNestedLogicform(u);n[c.canonicalName]={$in:m};continue}if(lp(u)){if(u.version!==void 0&&Yn(u),c.property.primal_type!=="entity"&&c.property.primal_type!=="object")throw new p("INVALID_RELATION_QUERY",`Relation query ${a} must resolve to an entity property`);if(!c.property.ref)throw new p("INVALID_RELATION_QUERY",`Nested LogicForm query requires an object property: ${c.canonicalName}`);if(u.schema!==c.property.ref)throw new p("RELATION_SCHEMA_MISMATCH",`Relation ${c.canonicalName} references ${c.property.ref}, not ${u.schema}`);const m=r.resolveSchema?.(u.schema);if(!m)throw new p("SCHEMA_RESOLVER_REQUIRED",`Nested relation query requires Schema ${u.schema}`);const y=rs(u.query,u.entity_id,m,r.plugins),g=await Hn(y,m,r);Object.assign(n,ss(g,c.canonicalName));continue}if(typeof u=="object"&&u!==null&&!Array.isArray(u)){const m=u,y=Object.entries(m).filter(([g])=>ut(g,r.plugins));if(y.length>0){const[g]=y,h=g?ut(g[0],r.plugins):void 0;if(h?.validateCondition?.(m),!g||y.length!==1||Object.keys(m).length!==1)throw new p("INVALID_PLUGIN_QUERY","A plugin Query Operator cannot be combined with other field operators");const[w,A]=g;if(!h)throw new Error(`Query Operator disappeared: ${w}`);n[c.canonicalName]={[w]:await h.normalize(A,{schema:c.schema,property:c.property,...r.resolveSchema?{resolveSchema:r.resolveSchema}:{},normalizeValue:(_,E,$)=>ps(_,E,$,r)})};continue}}const l=await Ir(u,r),d=await ps(l,c.schema,c.property,r),f=Fn(d);if(_r(f)){s(await ds(c.canonicalName,f,e,r));continue}n[c.canonicalName]=f}if(i.length>0){const a=Array.isArray(n.$and)?n.$and:[];n.$and=[...a,...i]}if(o.length===1)n.$expr=o[0]?.$expr;else if(o.length>1){const a=Array.isArray(n.$and)?n.$and:[];n.$and=[...a,...o]}return n},ls=async(t,e,r)=>{if(!t)return;const n=await Hn(t,e,r);return Object.keys(n).length===0?void 0:n},fs=(t,e,r)=>Promise.all((t??[]).map(n=>Vt(n,e,r,ls))),mp=(t,e,r)=>fs(t??[],e,r),At=(t,e)=>{throw new p("INVALID_PAGINATION",t,e)},yp=t=>{"skip"in t&&At("skip has been removed; use the 1-based page field",{skip:t.skip});const e=t.groupby?.length??0;t.limitBy!==void 0&&((!Number.isInteger(t.limitBy)||t.limitBy<=0)&&At("limitBy must be a positive integer",{limitBy:t.limitBy}),e<2&&(t.limit=t.limitBy,delete t.limitBy));const{limit:r,page:n}=t;if(r===void 0){n!==void 0&&At("page requires limit",{page:n});return}if((!Number.isFinite(r)||r<0&&r!==-1||r>1&&!Number.isInteger(r))&&At("limit must be -1, a non-negative integer, or a ratio between 0 and 1",{limit:r}),r===-1){n!==void 0&&At("page cannot be used with unlimited results",{limit:r,page:n}),delete t.limit;return}n!==void 0&&(!Number.isInteger(n)||n<1)&&At("page must be a positive integer starting from 1",{page:n}),t.page=n??1},hp=t=>t.property.name,ms=(t,e,r,n,o=new Set)=>{if(o.has(t.id))return;const i=new Set(o).add(t.id),s=t.properties.find(a=>a.id===e||a.name===e);if(s)return s.name;if(n==="timestamp"){const a=t.properties.find(u=>u.type==="timestamp");if(a)return a.name}for(const a of t.properties){if(!a.ref||a.primal_type!=="entity"&&a.primal_type!=="object")continue;const u=r?.(a.ref);if(!u)continue;const c=ms(u,e,r,n,i);if(c)return`${a.name}_${c}`}},ys=(t,e,r,n)=>{try{const o=ae(t,e,n);return ms(r,hp(o),n,o.property.type)}catch{return}},Gn=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Gn(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Gn(e)):[]],hs=t=>t?Object.entries(t).flatMap(([e,r])=>{if((e==="$and"||e==="$or")&&Array.isArray(r))return r.flatMap(n=>hs(n));if(e==="$expr"&&typeof r=="object"&&r!==null&&!Array.isArray(r)){const n=r.pred;return typeof n=="object"&&n!==null&&!Array.isArray(n)?Gn(n):[]}return e.startsWith("$")?[]:[e]}):[],gp=(t,e,r)=>{const n=[...new Set((t.preds??[]).map(s=>s.schema).filter(s=>!!(s&&s!==e.id)))];if(n.length===0)return t;const o={};for(const[s,a]of Object.entries(t.propertyResolve??{})){const u=r.resolveSchema?.(s),c={};for(const[l,d]of Object.entries(a))try{const f=ae(e,l,r.resolveSchema),m=u?ae(u,d,r.resolveSchema):void 0;c[f.canonicalName]=m?.canonicalName??d}catch{c[l]=d}o[s]=c}const i=[...(t.groupby??[]).map(s=>s.pred),...hs(t.query)];for(const s of i){if(typeof s!="string")continue;let a;try{a=ae(e,s,r.resolveSchema)}catch{continue}for(const u of n){const c=r.resolveSchema?.(u),l=c&&ys(e,s,c,r.resolveSchema);l&&l!==a.canonicalName&&(o[u]={...o[u]??{},[a.canonicalName]:l})}}return Object.keys(o).length>0?{...t,propertyResolve:o}:t},$p=t=>{if(t!==void 0){if(typeof t!="object"||t===null||Array.isArray(t))throw new p("INVALID_PROPERTY_RESOLVE","propertyResolve must be an object");for(const[e,r]of Object.entries(t)){if(typeof r!="object"||r===null||Array.isArray(r))throw new p("INVALID_PROPERTY_RESOLVE",`propertyResolve.${e} must be an object`);for(const[n,o]of Object.entries(r))if(typeof o!="string"||o.length===0)throw new p("INVALID_PROPERTY_RESOLVE",`propertyResolve.${e}.${n} must be a non-empty string`)}}},wp=async(t,e,r)=>{if(!t)return;const n=Gi(t,e,r);return Et(t,n,r)},Et=async(t,e,r)=>{if(r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:er([...me(r.plugins).flatMap(y=>y.locales??[]),...r.locales===void 0?[]:"locale"in r.locales?[r.locales]:r.locales])},...r.operators?{}:{operators:Ne(r.plugins)}},Yn(t),$p(t.propertyResolve),t.output&&t.output.type!=="data"&&t.output.type!=="sql"&&!zo(t.output.type,r.plugins))throw new p("UNSUPPORTED_OUTPUT",`Output type is not supported: ${t.output.type}`);const o=Z(t),i={...r,normalizeNestedLogicform:async y=>{const g=Gi(y,e,r);return Et(y,g,r)}};yp(o);const s=await wp(o.from,e,i),a=s&&r.resolveFromSchema?r.resolveFromSchema(s,e):e,u=await ls(rs(o.query,o.entity_id,a,r.plugins),a,i),c=o.preds===void 0&&o.groupby===void 0?a.properties.filter(y=>r.canProjectProperty?.(a,y)??!0).map(y=>({pred:y.name,name:y.name})):o.preds;let l=await fs(c,a,i),d=await mp(o.groupby,a,i);const f=d.filter(y=>Uo(y,d,a,r.resolveSchema));if(f.length>0){const y=new Set(f.map(({name:g})=>g));d=d.filter(({name:g})=>!y.has(g)),l=[...l,...f]}return o.preds=l,d.length>0?o.groupby=d:delete o.groupby,s?o.from=s:delete o.from,u?o.query=u:delete o.query,gp(o,a,i)},gs=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Me=(t,e)=>{if(t){if(!gs(t,e))throw new p("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},et=(t,e,r)=>{const n=Me(t,e)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},vt=(t,e,r)=>{if(!et(t,e.id,r))throw new p("COLUMN_PERMISSION_DENIED",`Property is not included in the column permissions: ${e.id}.${r.name}`,{schemaId:e.id,property:r.name,propertyId:r.id})},zn=(t,e,r,n)=>{const o=ae(e,t,n);for(const i of o.relations)Me(r,i.targetSchema.id),vt(r,i.sourceSchema,i.property);vt(r,o.schema,o.property)},$s=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),Rr=(t,e,r,n)=>{if(Ie(t)){Or(t,e,r,n);return}if(Array.isArray(t)){for(const o of t)Rr(o,e,r,n);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const o of Object.values(t))Rr(o,e,r,n)};function Yt(t,e,r,n,o){const i=t.schema?n(t.schema):e;t.schema&&Me(r,t.schema),typeof t.pred=="string"?zn(t.pred,i,r,n):t.pred&&!Array.isArray(t.pred)&&Yt(t.pred,i,r,n,o);for(const s of Array.isArray(t.pred)?t.pred:[])typeof s=="string"?zn(s,i,r,n):Yt(s,i,r,n,o);br(t.query,i,r,n,o)}const br=(t,e,r,n,o)=>{if(t)for(const[i,s]of Object.entries(t)){if(i==="$and"||i==="$or"){if(Array.isArray(s))for(const u of s)br(u,e,r,n,o);continue}if(i==="$expr"){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const u=s.pred;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Yt(u,e,r,n,o),Rr(s.condition,r,n,o)}continue}const a=ae(e,i,n);if(zn(i,e,r,n),typeof s=="object"&&s!==null&&!Array.isArray(s))for(const[u,c]of Object.entries(s))ut(u,o)?.authorize?.(c,{schema:a.schema,property:a.property,resolveSchema:n,assertSchemaAllowed:l=>{Me(r,l)},assertPropertyAllowed:(l,d)=>vt(r,l,d),hasRowPermissions:l=>Me(r,l)?.rowPermissions!==void 0});if($s(s)){if(a.property.ref!==s.schema)continue;const u=n(s.schema);Me(r,u.id),Zr(s.entity_id)&&vt(r,u,en(u,o)),br(s.query,u,r,n,o);continue}Rr(s,r,n,o)}},Or=(t,e,r,n=[])=>{if(!t.schema){if(t.from){Or(t.from,e,r,n);return}throw new p("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const o=r(t.schema);if(Me(e,o.id),Zr(t.entity_id)&&vt(e,o,en(o,n)),t.from){Or(t.from,e,r,n);return}br(t.query,o,e,r,n);for(const i of t.preds??[])Yt(i,o,e,r,n);for(const i of t.groupby??[])Yt(i,o,e,r,n)},Nr=(t,e)=>{if(Array.isArray(t))return t.map(o=>Nr(o,e));if(typeof t!="object"||t===null||t instanceof Date)return t;const r=Object.entries(t).map(([o,i])=>[o,Nr(i,e)]),n=Object.fromEntries(r);return $s(t)&&!gs(t,"version")&&(n.version=e),n},Ap=(t,e,r)=>{const n=[],o=(s,a)=>{if(s)for(const[u,c]of Object.entries(s))if((u==="$and"||u==="$or")&&Array.isArray(c))for(const l of c)o(l,a);else if(u==="$expr"&&typeof c=="object"&&c!==null&&!Array.isArray(c)){const l=c.pred;typeof l=="object"&&l!==null&&!Array.isArray(l)&&i(l,a)}else u.startsWith("$")||n.push(ae(a,u,r))},i=(s,a)=>{const u=s.schema?r(s.schema):a;typeof s.pred=="string"?n.push(ae(u,s.pred,r)):s.pred&&!Array.isArray(s.pred)&&i(s.pred,u);for(const c of Array.isArray(s.pred)?s.pred:[])typeof c=="string"?n.push(ae(u,c,r)):i(c,u);o(s.query,u)};o(t.query,e);for(const s of t.preds??[])i(s,e);for(const s of t.groupby??[])i(s,e);return n},Ep=(t,e,r)=>{if(!t.schema)return[];const n=r(t.schema),o=new Set,i=[];for(const s of Ap(t,n,r)){if(s.relations.length===0)continue;let a=-1;if(s.relations.forEach(({targetSchema:d},f)=>{e[d.id]?.rowPermissions!==void 0&&(a=f)}),a<0)continue;const u=s.relations.slice(0,a+1),c=u.map(({property:d})=>d.name).join("_");if(o.has(c))continue;o.add(c);let l={};for(const d of[...u].reverse())l={[d.property.name]:{schema:d.targetSchema.id,query:l}};i.push(l)}return i},It=(t,e,r,n,o,i)=>Ie(t)?tt(t,e,r,n,o,i):Array.isArray(t)?t.map(s=>It(s,e,r,n,o,i)):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(Object.entries(t).map(([s,a])=>[s,It(a,e,r,n,o,i)])),Wn=(t,e,r,n,o,i)=>({...t,...t.query?{query:It(t.query,e,r,n,o,i)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Wn(t.pred,e,r,n,o,i)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(s=>typeof s=="string"?s:Wn(s,e,r,n,o,i))}:{}}),tt=(t,e,r,n=!0,o=new Set,i=[])=>{if(!e)return Z(t);if(!t.schema){const m=Z(t);return m.from&&(m.from=tt(m.from,e,r,n,new Set,i)),m}n&&Or(t,e,r,i);const s=Me(e,t.schema),a=o.has(t.schema),u=new Set(o).add(t.schema),c=Z(t);c.query&&(c.query=It(c.query,e,r,n,new Set,i)),c.preds&&(c.preds=c.preds.map(m=>Wn(m,e,r,n,new Set,i))),c.from&&(c.from=tt(c.from,e,r,n,new Set,i));const l=a||t.from?void 0:s?.rowPermissions,d=(t.from?[]:Ep(t,e,r)).map(m=>It(Nr(m,t.version),e,r,!1,u,i));l&&d.push(It(Nr(Z(l),t.version),e,r,!1,u,i));const f=[c.query,...d].filter(m=>m!==void 0&&Object.keys(m).length>0);return f.length===1?c.query=f[0]:f.length>1?c.query={$and:f}:delete c.query,c},Ip=(t,e)=>{if(t)for(const[r,n]of Object.entries(t)){const o=e(r),i=n.columnPermissions?.whitelist;if(i&&(!Array.isArray(i)||i.some(s=>typeof s!="string")))throw new p("INVALID_COLUMN_PERMISSIONS",`Column permissions whitelist must be an array of strings: ${r}`,{schemaId:r});for(const s of i??[])if(!o.properties.some(({id:a,name:u})=>a===s||u===s))throw new p("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${r}.${s}`,{schemaId:r,property:s})}},ws=(t,e)=>{const r=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(t),n=o=>Number(r.find(i=>i.type===o)?.value);return{year:n("year"),month:n("month"),day:n("day"),hour:n("hour"),minute:n("minute"),second:n("second")}},As=(t,e)=>{const r=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second);let n=r;for(let o=0;o<3;o+=1){const i=ws(new Date(n),e),s=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second);n+=r-s}return new Date(n)},_p=(t,e)=>{const r=yi(t.expireAt);if(!r)throw new Error(`Invalid daily expiration time: ${t.expireAt}`);if(!t.timeZone){const i=new Date(e);return i.setHours(r.hour,r.minute,r.second,0),i.getTime()<=e.getTime()&&i.setDate(i.getDate()+1),i}const n=ws(e,t.timeZone);let o=As({...n,...r},t.timeZone);if(o.getTime()<=e.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=As({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},t.timeZone)}return o},Sp=(t,e)=>{const r=t.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(e.getTime()+n.ttlSeconds*1e3)]:[_p(n,e)]);return r.length===0?void 0:new Date(Math.min(...r.map(n=>n.getTime())))},Kn=(t,e)=>e.findSource(t.schemaId,t.mappingSource??t.source,t.connectionId),Ft=(t,e,r)=>{if(dt(t)){e.push(t.plan);return}if(pi(t)){for(const n of t.sources??[])r.set(`${n.schemaId}:${n.connectionId??""}:${n.source}`,n);return}if(Array.isArray(t)){for(const n of t)Ft(n,e,r);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const n of Object.values(t))Ft(n,e,r)},Bt=(t,e,r)=>{if(t.kind==="window"){Bt(t.input,e,r);for(const n of t.partitionBy)Bt(n,e,r);return}if(t.kind==="operator"){Ft(t.query,e,r),t.input&&Bt(t.input,e,r);for(const n of t.inputs??[])Bt(n,e,r)}},we=t=>{const e=new Map,r=o=>{e.set(`${o.schemaId}:${o.connectionId??""}:${o.mappingSource??""}:${o.source}`,o)};if(t.subplans)for(const o of t.subplans)for(const i of we(o))r(i);else if(t.sourcePlan)for(const o of we(t.sourcePlan))r(o);else t.source&&r({schemaId:t.schemaId,source:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});for(const o of t.joins??[])r({schemaId:o.targetSchemaId,source:o.targetSource,...o.targetConnectionId?{connectionId:o.targetConnectionId}:{}});for(const o of t.enrichmentJoins??[])r({schemaId:t.schemaId,source:o.source,mappingSource:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});const n=[];Ft(t.query,n,e),Ft(t.having,n,e);for(const o of t.projections)Bt(o.expression,n,e);for(const o of n)for(const i of we(o))r(i);return[...e.values()]},Qt=t=>{const e=new Map;for(const r of t.flat())e.set(`${r.schemaId}:${r.connectionId??""}:${r.mappingSource??""}:${r.source}`,r);return[...e.values()]},Es=async(t,e)=>{try{return await t.execute(e)}catch(r){const n=r instanceof Error?r.message:String(r),o=`${t.kind} provider \u6267\u884C SQL \u4EA7\u751F\u9519\u8BEF\uFF1A`;throw r instanceof Error?(r.message.startsWith(o)||(r.message=`${o}${n}`),r):new Error(`${o}${n}`,{cause:r})}},Rp=(t,e)=>{const r=[];for(const n of t){const o=Kn(n,e),i=n.mappingSource?o?.enrichments?.find(({source:s})=>s===n.source)?.freshness:o?.freshness;if(!i)return;r.push(i)}return r},Re=async(t,e,r)=>{t=Is(t),r.signal?.throwIfAborted();const n=r.cache?Rp(e,r.schemaMappings):void 0;if(!r.cache||!n)return Es(r.provider,{...t,...r.signal?{signal:r.signal}:{}});const o={namespace:r.cache.namespace,provider:r.provider.kind,...r.connectionId?{connectionId:r.connectionId}:{},sql:t.sql,parameters:t.parameters};try{const s=await r.cache.store.get(o);if(r.signal?.throwIfAborted(),s)return[...s]}catch{r.signal?.throwIfAborted()}const i=await Es(r.provider,{...t,...r.signal?{signal:r.signal}:{}});try{const s=Sp(n,new Date);await r.cache.store.set(o,i,{sources:[...new Set(e.map(({source:a})=>a))],...s?{expiresAt:s}:{}})}catch{}return i},Is=t=>({...t,sql:Ld(t.sql)}),bp=t=>{if(t.every(e=>typeof e=="string"))return[...t];if(t.every(e=>typeof e=="number"))return[...t];if(t.every(e=>typeof e=="boolean"))return[...t];throw new TypeError("Entity IDs must have one scalar type")},Op=(t,e,r)=>{const n=bp(e);if(!r||n.length<=r)return{[t]:{$in:n}};const o=[];for(let i=0;i<n.length;i+=r)o.push({[t]:{$in:n.slice(i,i+r)}});return{$or:o}},_s=async(t,e)=>{if(!et(e.permissions,t.schema.id,t.idProperty))throw new p("COLUMN_PERMISSION_DENIED",`Entity hydration requires the ID property in the column permissions: ${t.schema.id}.${t.idProperty.name}`,{schemaId:t.schema.id,property:t.idProperty.name});const r=t.schema.properties.filter(g=>et(e.permissions,t.schema.id,g)),n=e.schemaMappings.list(t.schema.id),o=n.find(({connectionId:g})=>g===e.preferredConnectionId)?.connectionId??n[0]?.connectionId,i=o&&e.providerForConnection?e.providerForConnection(o):e.provider,s={version:e.version,schema:t.schema.id,query:Op(t.idProperty.name,t.ids,i.maxInListItems),preds:r.map(g=>({pred:g.name,name:g.name}))},a=tt(s,e.permissions,e.resolveSchema,!0,new Set,e.plugins),u=await Et(a,t.schema,{semanticTypes:e.semanticTypes,operators:e.operators,...e.plugins?{plugins:e.plugins}:{},...e.locale?{locale:e.locale}:{},...e.localeRegistry?{localeRegistry:e.localeRegistry}:{},resolveSchema:e.resolveSchema}),c=Pe(u,t.schema,e.operators,e.schemaMappings,{resolveSchema:e.resolveSchema,...o?{preferredConnectionId:o}:{},canUsePropertyRowIdentity:(g,h)=>et(e.permissions,g.id,h)}),l=new Set(we(c).map(g=>e.schemaMappings.findSource(g.schemaId,g.source,g.connectionId)?.connectionId).filter(g=>!!g));if(l.size>1)throw new p("CROSS_CONNECTION_ENTITY_HYDRATION_UNSUPPORTED",`Entity hydration cannot span connections: ${[...l].join(", ")}`);const d=[...l][0]??o,f=d&&e.providerForConnection?e.providerForConnection(d):i,m=he(c,f,e.operators);e.onCompiled?.(m,u,f,d);const y=await Re(m,we(c),{provider:f,...d?{connectionId:d}:{},schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}});return Cn(y,c.rowIdentity)},Ss=t=>String(t),Np=(t,e,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${Ss(r)}\u300D\u7684\u5B9E\u4F53`,o={};for(const i of t.properties)i.id===e.id?o[i.name]=r:i.isArray?o[i.name]=[]:o[i.name]=i.primal_type==="string"?n:null;return o._id=Ss(r),o},Rs=(t,e)=>`${t}:${String(e)}`,Pp=t=>{const e=t.properties.filter(({type:n})=>n==="ID"),r=e[0];if(e.length!==1||!r)throw new p("RELATION_TARGET_ID_REQUIRED",`Relation target ${t.id} must contain exactly one ID property`,{schemaId:t.id,count:e.length});return r};class Tp{#e;#t=new Map;#r=new Map;#n=new Map;#o=!1;constructor(e){this.#e=e}load=(e,r)=>{const n=Rs(e,r),o=this.#t.get(n);if(o)return Promise.resolve(o);const i=this.#r.get(n);if(i)return i;const s=this.#e.resolveSchema(e);if(Wo(s,this.#e.plugins))throw new p("INTERVAL_ENTITY_HYDRATION_REQUIRES_POINT",`Cannot hydrate interval-versioned entity ${e} by ID without a selection point; use a relation path to select its point-in-time properties`,{schemaId:e});const a=Pp(s);let u,c;const l=new Promise((f,m)=>{u=f,c=m}),d=this.#n.get(e)??{schema:s,idProperty:a,loads:new Map};return d.loads.set(n,{id:r,resolve:f=>u?.(f),reject:f=>c?.(f)}),this.#n.set(e,d),this.#r.set(n,l),this.#i(),l};#i(){this.#o||(this.#o=!0,queueMicrotask(()=>{this.#s()}))}async#s(){this.#o=!1;const e=this.#n;this.#n=new Map,await Promise.all([...e.values()].map(r=>this.#a(r)))}async#a(e){const r={schema:e.schema,idProperty:e.idProperty,ids:[...e.loads.values()].map(({id:n})=>n)};try{const n=await this.#e.fetchEntities(r),o=new Map;for(const i of n){const s=i[e.idProperty.name]??i._id;if(s!=null){const a=typeof s=="string"?s:typeof s=="number"||typeof s=="boolean"||typeof s=="bigint"?String(s):JSON.stringify(s),u=i._id===a?i:{...i,_id:a};o.set(Rs(e.schema.id,s),u)}}for(const[i,s]of e.loads){const a=o.get(i)??Np(e.schema,e.idProperty,s.id);this.#t.set(i,a),this.#r.delete(i),s.resolve(a)}}catch(n){for(const[o,i]of e.loads)this.#r.delete(o),i.reject(n)}}}const Lp=(t,e)=>{if(!e.isArray||typeof t!="string")return t;const r=t.trim();if(!r.startsWith("[")||!r.endsWith("]"))return t;try{const n=JSON.parse(r);if(!Array.isArray(n))throw new Error("JSON result is not an array");return n}catch(n){throw new p("INVALID_ARRAY_RESULT",`Result column ${e.name} contains invalid array JSON`,{property:e.name,cause:n})}},Dp=async(t,e,r,n)=>{await Promise.all(t.map(async o=>{await Promise.all(e.map(async i=>{if(!(i.name in o))return;const s=Lp(o[i.name],i),a=r.get(i.type).hydrateResult;if(!a){o[i.name]=s;return}o[i.name]=i.isArray&&Array.isArray(s)?await Promise.all(s.map(u=>a(u,{property:i,requestEntity:n}))):await a(s,{property:i,requestEntity:n})}))}))},bs=5,Cp=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),qp=(t,e)=>{const r=e.properties.find(({type:n})=>n==="ID");return r?t[r.name]:void 0},kp=(t,e)=>{const r=ta.getNameProperty(e);t._title=t[r.name]??t._id},Up=(t,e)=>{const r=structuredClone(t);if(!("_id"in r)){const n=qp(r,e);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},jp=(t,e,r,n)=>{const o=`${e.id}:${n?"recursive":"leaf"}`,i=t.get(o);if(i){i.rows.push(r);return}t.set(o,{rows:[r],properties:e.properties,schema:e,expandEntities:n})},Mp=async(t,e,r)=>{const n=new Tp(r);let o=[{rows:t,properties:e,expandEntities:!0}];for(let i=0;o.length>0;i+=1){await Promise.all(o.map(a=>{const u=a.expandEntities&&i<bs;return Dp(a.rows,a.properties,r.semanticTypes,u?n.load:(c,l)=>Promise.resolve(l))}));for(const a of o)if(a.schema)for(const u of a.rows)kp(u,a.schema);if(i>=bs)return;const s=new Map;for(const a of o)if(a.expandEntities)for(const u of a.properties){if(u.primal_type!=="entity"&&u.primal_type!=="object"||!u.ref)continue;const c=r.resolveSchema(u.ref);for(const l of a.rows){if(!(u.name in l))continue;const d=l[u.name],f=u.isArray?Array.isArray(d)?d:[d]:[d];for(const[m,y]of f.entries()){if(!Cp(y))continue;const g=Up(y,c);u.isArray?f[m]=g:l[u.name]=g,jp(s,c,g,!u.isArray)}u.isArray&&(l[u.name]=f)}}o=[...s.values()]}},Os=async(t,e,r)=>{const n=t.map(o=>({...o}));return await Mp(n,e,r),n},Jn=t=>`'${t.replaceAll("'","''")}'`,Ns=t=>{const e=[["\\","\\\\"],["\0","\\0"],["\b","\\b"],[" ","\\t"],[`
4
- `,"\\n"],["\r","\\r"],["","\\Z"],['"','\\"'],["'","\\'"]];let r=t;for(const[n,o]of e)r=r.replaceAll(n,o);return`'${r}'`},Ht=(t,e)=>{if(t==null)return"NULL";if(typeof t=="boolean")return e==="mysql"?t?"true":"false":e==="sqlserver"?t?"1":"0":t?"TRUE":"FALSE";if(typeof t=="number")return String(t);if(typeof t=="bigint")return e==="mysql"||e==="sqlserver"?t.toString():Jn(t.toString());if(typeof t=="string")return e==="mysql"?Ns(t):Jn(t);if(t instanceof Date){const r=e==="clickhouse"||e==="mysql"?t.toISOString().replace("T"," ").replace("Z",""):t.toISOString();return e==="mysql"?Ns(r):Jn(r)}if(Buffer.isBuffer(t)){const r=t.toString("hex");return e==="mysql"?`X'${r}'`:e==="dameng"||e==="oracle"?`HEXTORAW('${r}')`:e==="postgresql"?`decode('${r}', 'hex')`:e==="snowflake"?`TO_BINARY('${r}', 'HEX')`:e==="sqlserver"?`0x${r}`:`unhex('${r}')`}throw new TypeError(`Unsupported ${e} display parameter type: ${typeof t}`)},xp=(t,e)=>t.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in e?Ht(e[o],"clickhouse"):r}),Vp=(t,e)=>t.replace(/:([1-9]\d*)\b/g,(r,n)=>{const o=Number(n)-1;return o in e?Ht(e[o],"oracle"):r}),vp=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="$"){const s=/^\$(\d+)/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a)-1;if(u in e){r+=Ht(e[u],"postgresql"),o+=s[0].length-1;continue}}}r+=i}}return r},Xn=(t,e,r)=>{let n="",o=0,i;for(let s=0;s<t.length;s+=1){const a=t[s];if(a){if(i){n+=a,a===i&&(t[s+1]===i?(n+=i,s+=1):i=void 0);continue}if(a==="'"||a==='"'||a==="`"){i=a,n+=a;continue}if(a==="?"&&o<e.length){n+=Ht(e[o],r),o+=1;continue}n+=a}}return n},Yp=(t,e)=>Xn(t,e,"mysql"),Zn=(t,e)=>Xn(t,e,"snowflake"),Fp=(t,e)=>Xn(t,e,"dameng"),Bp=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="["){n="]",r+=i;continue}if(i==="@"){const s=/^@p(\d+)\b/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a);if(u in e){r+=Ht(e[u],"sqlserver"),o+=s[0].length-1;continue}}}r+=i}}return r},Fe=(t,e)=>new Error(`Database driver "${t}" is not installed or could not be loaded. Install it with: npm install ${t}`,{cause:e}),Qp=t=>{if(t.url!==void 0)return t.url;const e=t.host??"localhost";if(/^[a-z][a-z\d+.-]*:\/\//iu.test(e)){if(t.port===void 0)return e;const n=new URL(e);return n.port=String(t.port),n.toString()}return`http://${e}:${t.port??8123}`},Hp=t=>t===null?"Nullable(String)":typeof t=="boolean"?"Bool":typeof t=="number"?"Float64":t instanceof Date?"DateTime64(3)":"String",Gp=t=>t instanceof Date?t.toISOString().replace("T"," ").replace("Z",""):t;class zp{kind="clickhouse";supportsRecursiveCte=!0;recursiveCteUnion="UNION ALL";#e;#t;constructor(e={}){this.#e=e,this.#t=e.client?Promise.resolve(e.client):void 0}async#r(){this.#t??=(async()=>{const{createClient:e}=await import("@clickhouse/client").catch(r=>{throw Fe("@clickhouse/client",r)});return e({url:Qp(this.#e),username:this.#e.username??this.#e.user??"default",password:this.#e.password??"",database:this.#e.database??"default"})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`\`${e.replaceAll("`","``")}\``}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return`{p${e}:${Hp(r)}}`}displayQuery(e,r){return xp(e,r)}dateBucket(e,r){if(r==="second")return`toDateTime64(${e}, 0)`;const o={minute:"toStartOfMinute",hour:"toStartOfHour",day:"toStartOfDay",week:"toStartOfWeek",month:"toStartOfMonth",quarter:"toStartOfQuarter",year:"toStartOfYear"}[r];if(!o)throw new Error(`Unsupported ClickHouse date level: ${r}`);return`${o}(${e})`}datePart(e,r){return`${{second:"toSecond",minute:"toMinute",hour:"toHour",weekday:"toDayOfWeek",day:"toDayOfMonth",week:"toISOWeek",month:"toMonth",quarter:"toQuarter",year:"toYear"}[r]}(${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported ClickHouse date shift: ${r}/${n}`);return`dateAdd(${r}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`toDateTime(${e})`:r==="date"?`toDate(${e})`:e}scalarExtremum(e,r){const n=`[${r.map(s=>`toNullable(${s})`).join(", ")}]`,o=`arrayFilter(value -> isNotNull(value), ${n})`;return`if(arrayExists(value -> isNotNull(value), ${n}), ${e==="least"?"arrayMin":"arrayMax"}(${o}), NULL)`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported ClickHouse aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`toString(${e})`}concat(e){return`concat(${e.join(", ")})`}substring(e,r,n){return`substring(${e}, ${r}, ${n})`}stringLength(e){return`lengthUTF8(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported ClickHouse regex options: ${n}`);const o=n==="i"?`concat('(?i)', ${r})`:r;return`match(${e}, ${o})`}arrayContains(e,r){return`has(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`ARRAY JOIN ${e} AS ${o}`,valueExpression:o}}async execute(e){e.signal?.throwIfAborted();const r=await this.#r();e.signal?.throwIfAborted();const n=Object.fromEntries(e.parameters.map((i,s)=>[`p${s}`,Gp(i)]));return(await r.query({query:e.sql,format:"JSONEachRow",query_params:n,...e.signal?{abort_signal:e.signal}:{}})).json()}async close(){const e=this.#t;if(!e)return;await(await e).close(),this.#t=void 0}}const Wp=t=>[".azuredatabricks.net",".databricks.azure.cn",".databricks.azure.us"].some(e=>t.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]?.endsWith(e)),Kp=t=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Databricks connection options must be an object");const e=t,{host:r,path:n,authType:o}=e;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0)throw new Error("Databricks connection requires host and path");if(o==="databricks-oauth"){const{oauthClientId:i,oauthClientSecret:s}=e;if(typeof i!="string"||i.length===0||typeof s!="string"||s.length===0)throw new Error("Databricks OAuth requires oauthClientId and oauthClientSecret");if("token"in e)throw new Error("Databricks OAuth connection must not define token");if("azureTenantId"in e&&typeof e.azureTenantId!="string")throw new Error("Databricks OAuth azureTenantId must be a string");if("oauthScopes"in e&&(!Array.isArray(e.oauthScopes)||e.oauthScopes.some(a=>typeof a!="string")))throw new Error("Databricks OAuth oauthScopes must be a string array");if("useDatabricksOAuthInAzure"in e&&typeof e.useDatabricksOAuthInAzure!="boolean")throw new Error("Databricks OAuth useDatabricksOAuthInAzure must be boolean");return{host:r,path:n,authType:o,oauthClientId:i,oauthClientSecret:s,...typeof e.azureTenantId=="string"?{azureTenantId:e.azureTenantId}:{},...Array.isArray(e.oauthScopes)?{oauthScopes:e.oauthScopes}:{},useDatabricksOAuthInAzure:e.useDatabricksOAuthInAzure??(Wp(r)&&!e.azureTenantId)}}if(o==="access-token"){if(typeof e.token!="string"||e.token.length===0)throw new Error("Databricks access-token connection requires token");if(["oauthClientId","oauthClientSecret","azureTenantId","oauthScopes","useDatabricksOAuthInAzure"].some(i=>i in e))throw new Error("Databricks access-token connection must not define OAuth fields");return{host:r,path:n,authType:o,token:e.token}}throw new Error(`Unsupported Databricks authType: ${String(o)}`)},Jp=t=>{if(t==null)return null;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||t instanceof Date)return t;throw new TypeError(`Unsupported Databricks parameter type: ${typeof t}`)};class Xp{kind="databricks";supportsHavingAlias=!1;supportsRecursiveCte=!0;#e;#t;#r;constructor(e={}){this.#e=e.connection,this.#t=e.client}async#n(){this.#r??=(async()=>{const e=this.#t??new(await import("@databricks/sql").catch(r=>{throw Fe("@databricks/sql",r)})).DBSQLClient;if(this.#e)try{await e.connect(Kp(this.#e))}catch(r){throw await e.close().catch(()=>{}),r}return e})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`\`${e.replaceAll("`","``")}\``}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return Zn(e,r)}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Databricks date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${e})`}datePart(e,r){const n={second:"SECOND",minute:"MINUTE",hour:"HOUR",day:"DAYOFMONTH",week:"WEEKOFYEAR",month:"MONTH",quarter:"QUARTER",year:"YEAR"};return r==="weekday"?`(WEEKDAY(${e}) + 1)`:`${n[r]}(${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported Databricks date shift: ${r}/${n}`);return`TIMESTAMPADD(${r.toUpperCase()}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`CAST(${e} AS TIMESTAMP)`:r==="date"?`CAST(${e} AS DATE)`:e}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Databricks aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS STRING)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Databricks regex options: ${n}`);return`${e} RLIKE ${n==="i"?`CONCAT('(?i)', ${r})`:r}`}arrayContains(e,r){return`ARRAY_CONTAINS(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`LATERAL VIEW EXPLODE(${e}) ${o} AS ${i}`,valueExpression:`${o}.${i}`}}async execute(e){e.signal?.throwIfAborted();const r=await this.#n();e.signal?.throwIfAborted();const n=this.#e?.schema??this.#e?.database,o=await r.openSession({...this.#e?.catalog?{initialCatalog:this.#e.catalog}:{},...n?{initialSchema:n}:{}});let i;const s=()=>{i&&i.cancel().catch(()=>{})};e.signal?.addEventListener("abort",s,{once:!0});try{e.signal?.throwIfAborted(),i=await o.executeStatement(e.sql,{ordinalParameters:e.parameters.map(Jp)}),e.signal?.aborted&&s(),e.signal?.throwIfAborted();const a=await i.fetchAll();if(e.signal?.throwIfAborted(),!Array.isArray(a))throw new Error("Databricks provider expected an array result");return a}finally{e.signal?.removeEventListener("abort",s);try{i&&await i.close()}finally{await o.close()}}}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}const Ps=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="boolean")return t?1:0;if(typeof t=="string"||typeof t=="number"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported Dameng parameter type: ${typeof t}`)},Zp=t=>{const{host:e,port:r,...n}=t;return{...n,connectString:t.connectString??`${e??"localhost"}:${r??5236}`}};class el{kind="dameng";supportsHavingAlias=!1;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}async#n(){this.#r??=(async()=>{const e={...Zp(this.#e),poolAlias:typeof this.#e.poolAlias=="string"?this.#e.poolAlias:`semanticdb-${yo.randomUUID()}`};if(this.#t)return this.#t.createPool(e);const{default:r}=await import("dmdb").catch(n=>{throw Fe("dmdb",n)});return r.createPool(e)})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} ${this.quoteIdentifier(r)}`}paginate(e,r,n){return n>0?`${e} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`:`${e} FETCH FIRST ${r} ROWS ONLY`}parameter(e,r){return"?"}displayQuery(e,r){return Fp(e,r.map(Ps))}dateBucket(e,r){const n={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(r in n))throw new Error(`Unsupported Dameng date level: ${r}`);const o=n[r];return o?`TRUNC(${e}, '${o}')`:`TRUNC(${e})`}datePart(e,r){return r==="weekday"?`(TRUNC(${e}) - TRUNC(${e}, 'IW') + 1)`:`TO_NUMBER(TO_CHAR(${e}, '${{second:"SS",minute:"MI",hour:"HH24",day:"DD",week:"IW",month:"MM",quarter:"Q",year:"YYYY"}[r]}'))`}dateShift(e,r,n){if(!Number.isInteger(n))throw new Error(`Unsupported Dameng date shift: ${r}/${n}`);const i={month:1,quarter:3,year:12}[r];if(i)return`ADD_MONTHS(${e}, ${n*i})`;const a={second:{unit:"SECOND",multiplier:1},minute:{unit:"MINUTE",multiplier:1},hour:{unit:"HOUR",multiplier:1},day:{unit:"DAY",multiplier:1},week:{unit:"DAY",multiplier:7}}[r];if(!a)throw new Error(`Unsupported Dameng date shift: ${r}/${n}`);return`(${e} + NUMTODSINTERVAL(${n*a.multiplier}, '${a.unit}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Dameng aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_CHAR(${e})`}concat(e){return`(${e.join(" || ")})`}substring(e,r,n){return`SUBSTR(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Dameng regex options: ${n}`);return`REGEXP_LIKE(${e}, ${r}${n?", 'i'":""})`}async execute(e){e.signal?.throwIfAborted();const r=await this.#n();e.signal?.throwIfAborted();const n=await r.getConnection();try{e.signal?.throwIfAborted();const o=await n.execute(e.sql,e.parameters.map(Ps),{outFormat:4002});if(e.signal?.throwIfAborted(),!Array.isArray(o.rows))throw new Error("Dameng provider expected an array result");return o.rows}finally{await n.close()}}async close(){const e=this.#r;if(!e)return;await(await e).close(0),this.#r=void 0}}const K={quoteIdentifier(t){return`\`${t.replaceAll("`","``")}\``},tableAlias(t,e){return`${t} AS ${this.quoteIdentifier(e)}`},paginate(t,e,r){return`${t} LIMIT ${e}${r>0?` OFFSET ${r}`:""}`},parameter(t,e){return"?"},displayQuery(t,e){return Yp(t,e)},dateBucket(t,e){const r={hour:"%Y-%m-%d %H:00:00",day:"%Y-%m-%d",month:"%Y-%m-01",year:"%Y-01-01"};if(e==="week")return`DATE_SUB(DATE(${t}), INTERVAL WEEKDAY(${t}) DAY)`;if(e==="quarter")return`MAKEDATE(YEAR(${t}), 1) + INTERVAL (QUARTER(${t}) - 1) QUARTER`;const n=r[e];if(!n)throw new Error(`Unsupported MySQL-compatible date level: ${e}`);return`DATE_FORMAT(${t}, '${n}')`},datePart(t,e){const r={second:"SECOND",minute:"MINUTE",hour:"HOUR",day:"DAYOFMONTH",month:"MONTH",quarter:"QUARTER",year:"YEAR"};if(e==="weekday")return`(WEEKDAY(${t}) + 1)`;if(e==="week")return`WEEK(${t}, 3)`;const n=r[e];if(!n)throw new Error(`Unsupported MySQL-compatible date part: ${e}`);return`${n}(${t})`},dateShift(t,e,r){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(e)||!Number.isInteger(r))throw new Error(`Unsupported MySQL-compatible date shift: ${e}/${r}`);return`DATE_ADD(${t}, INTERVAL ${r} ${e.toUpperCase()})`},datePeriodBoundary(t,e,r){if(r==="start")return this.dateBucket(t,e);switch(e){case"hour":return`DATE_FORMAT(${t}, '%Y-%m-%d %H:59:59')`;case"day":return`TIMESTAMP(DATE(${t}), '23:59:59')`;case"month":return`TIMESTAMP(LAST_DAY(${t}), '23:59:59')`;case"year":return`CONCAT(YEAR(${t}), '-12-31 23:59:59')`;default:return this.dateShift(this.dateShift(this.dateBucket(t,e),e,1),"second",-1)}},aggregateFunction(t,e="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(t))throw new Error(`Unsupported MySQL-compatible aggregate function: ${t}`);return`${t.toUpperCase()}(${e})`},stringify(t){return`CAST(${t} AS CHAR)`},concat(t){return`CONCAT(${t.join(", ")})`},substring(t,e,r){return`SUBSTRING(${t}, ${e}, ${r})`},stringLength(t){return`CHAR_LENGTH(${t})`},regex(t,e,r){if(r&&r!=="i")throw new Error(`Unsupported MySQL-compatible regex options: ${r}`);return r==="i"?`LOWER(${t}) REGEXP LOWER(${e})`:`${t} REGEXP ${e}`},arrayContains(t,e){return`JSON_OVERLAPS(${t}, JSON_ARRAY(${e}))`},expandArray(t,e,r){const n=this.quoteIdentifier(e),o=this.quoteIdentifier(r);return{joinSql:`CROSS JOIN JSON_TABLE(CASE WHEN JSON_TYPE(${t}) = 'ARRAY' THEN ${t} ELSE JSON_ARRAY() END, '$[*]' COLUMNS (${o} JSON PATH '$')) AS ${n}`,valueExpression:`${n}.${o}`}}},tl={connectionLimit:30,maxIdle:10,idleTimeout:6e4,enableKeepAlive:!0,keepAliveInitialDelay:0};class Pr{supportsRecursiveCte=!0;#e;#t;constructor(e={}){this.#e=e.connection??{},this.#t=e.pool?Promise.resolve(e.pool):void 0}async#r(){this.#t??=(async()=>{const{createPool:e}=await import("mysql2/promise").catch(r=>{throw Fe("mysql2",r)});return e({...tl,decimalNumbers:!0,...this.#e})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return K.quoteIdentifier(e)}tableAlias(e,r){return K.tableAlias(e,r)}paginate(e,r,n){return K.paginate(e,r,n)}parameter(e,r){return K.parameter(e,r)}displayQuery(e,r){return K.displayQuery(e,r)}dateBucket(e,r){return K.dateBucket(e,r)}datePart(e,r){return K.datePart(e,r)}dateShift(e,r,n){return K.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=K.datePeriodBoundary?.bind(K);if(!o)throw new Error("MySQL date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return K.aggregateFunction(e,r)}stringify(e){return K.stringify(e)}concat(e){return K.concat(e)}substring(e,r,n){return K.substring(e,r,n)}stringLength(e){return K.stringLength(e)}regex(e,r,n){return K.regex(e,r,n)}arrayContains(e,r){const n=K.arrayContains?.bind(K);if(!n)throw new Error("MySQL-compatible array conditions are unavailable");return n(e,r)}expandArray(e,r,n){const o=K.expandArray?.bind(K);if(!o)throw new Error("MySQL-compatible array expansion is unavailable");return o(e,r,n)}async execute(e){e.signal?.throwIfAborted();const r=await this.#r();e.signal?.throwIfAborted();const[n]=await r.execute(e.sql,e.parameters);if(!Array.isArray(n))throw new Error(`${this.kind} provider expected an array result`);return n}async close(){const e=this.#t;if(!e)return;await(await e).end(),this.#t=void 0}}class rl extends Pr{kind="doris";constructor(e={}){super(e)}}class nl extends Pr{kind="gbase";supportsRecursiveCte=!1;constructor(e={}){super({...e,connection:{port:5258,...e.connection}})}}class ol{kind="maxcompute";supportsRecursiveCte=!1;#e;#t=!1;constructor(e){this.#e=e.client}quoteIdentifier(e){return K.quoteIdentifier(e)}tableAlias(e,r){return K.tableAlias(e,r)}paginate(e,r,n){return K.paginate(e,r,n)}parameter(e,r){return K.parameter(e,r)}displayQuery(e,r){return K.displayQuery(e,r)}dateBucket(e,r){return K.dateBucket(e,r)}datePart(e,r){return K.datePart(e,r)}dateShift(e,r,n){return K.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=K.datePeriodBoundary?.bind(K);if(!o)throw new Error("MaxCompute date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return K.aggregateFunction(e,r)}stringify(e){return K.stringify(e)}concat(e){return K.concat(e)}substring(e,r,n){return K.substring(e,r,n)}stringLength(e){return K.stringLength(e)}regex(e,r,n){return K.regex(e,r,n)}async execute(e){e.signal?.throwIfAborted();const r=await this.#e.execute(e);if(e.signal?.throwIfAborted(),!Array.isArray(r))throw new Error("MaxCompute provider expected an array result");return r}async close(){this.#t||(await this.#e.close(),this.#t=!0)}}class il extends Pr{kind="mysql";constructor(e={}){super(e)}}const Ts=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported Oracle parameter type: ${typeof t}`)},sl=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class al{kind="oracle";supportsHavingAlias=!1;maxInListItems=1e3;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} ${this.quoteIdentifier(r)}`}paginate(e,r,n){return n>0?`${e} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`:`${e} FETCH FIRST ${r} ROWS ONLY`}parameter(e,r){return`:${e+1}`}displayQuery(e,r){return Vp(e,r.map(Ts))}dateBucket(e,r){const n={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(r in n))throw new Error(`Unsupported Oracle date level: ${r}`);const o=n[r];return o?`TRUNC(${e}, '${o}')`:`TRUNC(${e})`}datePart(e,r){return r==="weekday"?`(TRUNC(${e}) - TRUNC(${e}, 'IW') + 1)`:`TO_NUMBER(TO_CHAR(${e}, '${{second:"SS",minute:"MI",hour:"HH24",day:"DD",week:"IW",month:"MM",quarter:"Q",year:"YYYY"}[r]}'))`}dateShift(e,r,n){if(!Number.isInteger(n))throw new Error(`Unsupported Oracle date shift: ${r}/${n}`);const i={month:1,quarter:3,year:12}[r];if(i)return`ADD_MONTHS(${e}, ${n*i})`;const a={second:{unit:"SECOND",multiplier:1},minute:{unit:"MINUTE",multiplier:1},hour:{unit:"HOUR",multiplier:1},day:{unit:"DAY",multiplier:1},week:{unit:"DAY",multiplier:7}}[r];if(!a)throw new Error(`Unsupported Oracle date shift: ${r}/${n}`);return`(${e} + NUMTODSINTERVAL(${n*a.multiplier}, '${a.unit}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Oracle aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_CHAR(${e})`}concat(e){return`(${e.join(" || ")})`}substring(e,r,n){return`SUBSTR(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Oracle regex options: ${n}`);return`REGEXP_LIKE(${e}, ${r}${n?", 'i'":""})`}arrayContains(e,r){return`JSON_EXISTS(${e}, '$?(@ == $value)' PASSING ${r} AS "value")`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS APPLY JSON_TABLE(${e}, '$[*]' COLUMNS (${i} VARCHAR2(4000) PATH '$')) ${o}`,valueExpression:`${o}.${i}`}}async#n(){this.#r??=(async()=>{if(this.#t)return this.#t.createPool(this.#e);const{default:e}=await import("oracledb").catch(r=>{throw Fe("oracledb",r)});return e.createPool(this.#e)})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}async execute(e){e.signal?.throwIfAborted();const r=await this.#n();e.signal?.throwIfAborted();const n=await r.getConnection(),o=e.signal,i=()=>{n.break().catch(()=>{})};o?.addEventListener("abort",i,{once:!0});try{const s=await n.execute(e.sql,e.parameters.map(Ts),{outFormat:4002});if(o?.throwIfAborted(),!Array.isArray(s.rows))throw new Error("Oracle provider expected an array result");return s.rows}catch(s){throw o?.aborted?sl(o):s}finally{o?.removeEventListener("abort",i),await n.close()}}async close(){const e=this.#r;if(!e)return;await(await e).close(0),this.#r=void 0}}class cl{kind="postgresql";supportsHavingAlias=!1;supportsRecursiveCte=!0;#e;#t;constructor(e={}){this.#e=e.connection??{},this.#t=e.pool?Promise.resolve(e.pool):void 0}async#r(){this.#t??=(async()=>{const{Pool:e}=await import("pg").catch(r=>{throw Fe("pg",r)});return new e(this.#e)})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return`$${e+1}`}displayQuery(e,r){return vp(e,r)}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported PostgreSQL date level: ${r}`);return`DATE_TRUNC('${r}', ${e})`}datePart(e,r){return`EXTRACT(${r==="weekday"?"ISODOW":r.toUpperCase()} FROM ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported PostgreSQL date shift: ${r}/${n}`);return`(${e} + (${n} * INTERVAL '1 ${r}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported PostgreSQL aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS TEXT)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e} FROM ${r} FOR ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported PostgreSQL regex options: ${n}`);return`${e} ${n==="i"?"~*":"~"} ${r}`}arrayContains(e,r){return`${r} = ANY(${e})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS JOIN LATERAL unnest(${e}) AS ${o}(${i})`,valueExpression:`${o}.${i}`}}async execute(e){e.signal?.throwIfAborted();const r=await this.#r();e.signal?.throwIfAborted();const n=await r.query(e.sql,[...e.parameters]);if(e.signal?.throwIfAborted(),!Array.isArray(n.rows))throw new Error("PostgreSQL provider expected an array result");return n.rows}async close(){const e=this.#t;if(!e)return;await(await e).end(),this.#t=void 0}}const Ls=t=>{if(t==null)return null;if(t instanceof Date)return t.toISOString();if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;throw new TypeError(`Unsupported Snowflake parameter type: ${typeof t}`)},ul=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class dl{kind="snowflake";#e;#t;#r=!1;#n;constructor(e={}){this.#e=e.connection??{},this.#t=e.client?Promise.resolve(e.client):void 0}async#o(){this.#t??=(async()=>{const{default:e}=await import("snowflake-sdk").catch(r=>{throw Fe("snowflake-sdk",r)});return e.createConnection(this.#e)})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return Zn(e,r.map(Ls))}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Snowflake date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${e})`}datePart(e,r){return`DATE_PART(${r==="weekday"?"DAYOFWEEKISO":r==="week"?"WEEKISO":r.toUpperCase()}, ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported Snowflake date shift: ${r}/${n}`);return`DATEADD(${r.toUpperCase()}, ${n}, ${e})`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Snowflake aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_VARCHAR(${e})`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Snowflake regex options: ${n}`);return n?`REGEXP_INSTR(${e}, ${r}, 1, 1, 0, '${n}') > 0`:`REGEXP_INSTR(${e}, ${r}) > 0`}arrayContains(e,r){return`ARRAY_CONTAINS(${r}::VARIANT, ${e})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`, LATERAL FLATTEN(INPUT => ${e}) ${o}`,valueExpression:`${o}.VALUE`}}async#i(){if(this.#r)return;const e=await this.#o();this.#n??=new Promise((r,n)=>{e.connect(o=>{if(o){n(o);return}this.#r=!0,r()})});try{await this.#n}catch(r){throw this.#n=void 0,r}}async execute(e){e.signal?.throwIfAborted(),await this.#i(),e.signal?.throwIfAborted();const r=await this.#o(),n=e.parameters.map(Ls);return new Promise((o,i)=>{const s=e.signal,a={};let u=!1;const c=d=>{u||(u=!0,s?.removeEventListener("abort",l),d())},l=()=>{a.current?.cancel(),s&&c(()=>i(ul(s)))};s?.addEventListener("abort",l,{once:!0}),a.current=r.execute({sqlText:e.sql,binds:n,complete:(d,f,m)=>{if(d){c(()=>i(d));return}if(!Array.isArray(m)){c(()=>i(new Error("Snowflake provider expected an array result")));return}c(()=>o(m))}}),s?.aborted&&l()})}async close(){if(!this.#r)return;const e=await this.#o();await new Promise((r,n)=>{e.destroy(o=>{if(o){n(o);return}this.#r=!1,this.#n=void 0,this.#t=void 0,r()})})}}const pl=t=>{const{host:e,server:r,options:n,pool:o,...i}=t;return{...i,server:r??e??"localhost",port:t.port??1433,requestTimeout:t.requestTimeout??6e4,connectionTimeout:t.connectionTimeout??3e4,options:{encrypt:!1,trustServerCertificate:!0,enableArithAbort:!0,...n},pool:{max:10,min:0,idleTimeoutMillis:3e4,...o}}},ll=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported SQL Server parameter type: ${typeof t}`)},fl=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError"),ml=t=>t instanceof Error?t:new Error("SQL Server query failed",{cause:t}),yl=t=>{let e=0,r;for(let n=0;n<t.length;n+=1){const o=t[n];if(o){if(r){o===r&&(t[n+1]===r?n+=1:r=void 0);continue}if(o==="'"||o==='"')r=o;else if(o==="[")r="]";else if(o==="(")e+=1;else if(o===")")e=Math.max(0,e-1);else if(e===0&&/^ORDER\s+BY\b/i.test(t.slice(n)))return!0}}return!1};class hl{kind="sqlserver";supportsHavingAlias=!1;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}async#n(){this.#r??=(async()=>{const e=this.#t??await import("mssql").then(n=>n.default,n=>{throw Fe("mssql",n)}),r=new e.ConnectionPool(pl(this.#e));return await r.connect(),r})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`[${e.replaceAll("]","]]")}]`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${yl(e)?e:`${e} ORDER BY (SELECT NULL)`} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`}parameter(e,r){return`@p${e}`}displayQuery(e,r){return Bp(e,r)}dateBucket(e,r){const n=new Set(["second","minute","hour","day","month","quarter","year"]);if(r==="week")return`DATEADD(DAY, -(((DATEDIFF(DAY, '19000101', ${e}) % 7) + 7) % 7), CAST(${e} AS DATE))`;if(!n.has(r))throw new Error(`Unsupported SQL Server date level: ${r}`);const o=r==="second"||r==="minute"?"'20000101'":"0";return`DATEADD(${r.toUpperCase()}, DATEDIFF(${r.toUpperCase()}, ${o}, ${e}), ${o})`}datePart(e,r){return r==="weekday"?`((((DATEDIFF(DAY, '19000101', ${e}) % 7) + 7) % 7) + 1)`:`DATEPART(${r==="week"?"ISO_WEEK":r.toUpperCase()}, ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported SQL Server date shift: ${r}/${n}`);return`DATEADD(${r.toUpperCase()}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`CAST(${e} AS DATETIME2)`:r==="date"?`CAST(${e} AS DATE)`:r==="string"?`CAST(${e} AS NVARCHAR(MAX))`:e}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported SQL Server aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS NVARCHAR(MAX))`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`LEN(${e})`}regex(e,r,n){throw new Error("SQL Server does not provide a native regular-expression predicate")}arrayContains(e,r){return`EXISTS (SELECT 1 FROM OPENJSON(${e}) AS [semanticdb_array] WHERE [semanticdb_array].[value] = ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`CROSS APPLY OPENJSON(${e}) AS ${o}`,valueExpression:`${o}.[value]`}}async execute(e){e.signal?.throwIfAborted();const r=await this.#n();e.signal?.throwIfAborted();const n=r.request();return e.parameters.forEach((o,i)=>n.input(`p${i}`,ll(o))),new Promise((o,i)=>{const s=e.signal;let a=!1;const u=l=>{a||(a=!0,s?.removeEventListener("abort",c),l())},c=()=>{n.cancel(),s&&u(()=>i(fl(s)))};s?.addEventListener("abort",c,{once:!0}),n.query(e.sql).then(l=>{if(!Array.isArray(l.recordset)){u(()=>i(new Error("SQL Server provider expected an array result")));return}u(()=>o(l.recordset))},l=>u(()=>i(ml(l)))),s?.aborted&&c()})}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}class gl extends Pr{kind="starrocks";constructor(e={}){super(e)}}const be=t=>{const{id:e,kind:r,...n}=t;return n},$l=Object.freeze([{kind:"mysql",create:t=>new il({connection:be(t)})},{kind:"doris",create:t=>new rl({connection:be(t)})},{kind:"gbase",create:t=>new nl({connection:be(t)})},{kind:"starrocks",create:t=>new gl({connection:be(t)})},{kind:"maxcompute",create:t=>new ol(be(t))},{kind:"postgresql",create:t=>new cl({connection:be(t)})},{kind:"clickhouse",create:t=>new zp(be(t))},{kind:"databricks",create:t=>new Xp({connection:be(t)})},{kind:"dameng",create:t=>new el({connection:be(t)})},{kind:"snowflake",create:t=>new dl({connection:be(t)})},{kind:"sqlserver",create:t=>new hl({connection:be(t)})},{kind:"oracle",create:t=>new al({connection:be(t)})}]);class Ds{#e=new Map;constructor(e=$l){e.forEach(r=>this.register(r))}register(e){if(!e.kind)throw new p("INVALID_PROVIDER","Provider kind must not be empty");if(this.#e.has(e.kind))throw new p("PROVIDER_ALREADY_REGISTERED",`Provider is already registered: ${e.kind}`,{provider:e.kind});return this.#e.set(e.kind,e),this}create(e){const r=this.#e.get(e.kind);if(!r)throw new p("PROVIDER_NOT_FOUND",`Provider is not registered: ${e.kind}`,{provider:e.kind});return r.create(e)}has(e){return this.#e.has(e)}}const Cs=new Ds,qs=(t,e=Cs)=>e.create(t),wl=t=>{const{name:e,kind:r}=t;switch(r){case"boolean":return{name:e,kind:r,type:pe.BOOLEAN,sqlType:"BOOLEAN"};case"date":return{name:e,kind:r,type:pe.TIMESTAMP,sqlType:"TIMESTAMP"};case"number":return{name:e,kind:r,type:pe.DOUBLE,sqlType:"DOUBLE"};case"string":return{name:e,kind:r,type:pe.VARCHAR,sqlType:"VARCHAR"}}},Al=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="true"?!0:t===0||t==="0"||t==="false"?!1:!!t,El=(t,e)=>{if(t==null)return null;switch(e.kind){case"boolean":return pe.jsToDuckDBValue(Al(t),pe.BOOLEAN);case"date":{const r=t instanceof Date?t:new Date(typeof t=="number"||typeof t=="string"?t:Number.NaN);return Number.isNaN(r.getTime())?null:pe.jsToDuckDBValue(r,pe.TIMESTAMP)}case"number":{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?pe.jsToDuckDBValue(r,pe.DOUBLE):null}case"string":return typeof t=="string"?pe.jsToDuckDBValue(t,pe.VARCHAR):typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?pe.jsToDuckDBValue(t.toString(),pe.VARCHAR):typeof t=="symbol"?pe.jsToDuckDBValue(t.description??"",pe.VARCHAR):typeof t=="function"?pe.jsToDuckDBValue(t.name,pe.VARCHAR):pe.jsToDuckDBValue(JSON.stringify(t),pe.VARCHAR)}},Il=t=>{if(t==null)return null;if(t instanceof Date)return pe.jsToDuckDBValue(t,pe.TIMESTAMP);if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"||typeof t=="string")return t;if(Buffer.isBuffer(t))return pe.blobValue(t);throw new TypeError(`Unsupported DuckDB coordinator parameter: ${typeof t}`)};class Ur{instance;connection;kind="duckdb";supportsHavingAlias=!0;supportsRecursiveCte=!0;static async create(){const e=await pe.DuckDBInstance.create(":memory:"),r=await e.connect();return new Ur(e,r)}constructor(e,r){this.instance=e,this.connection=r}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return Zn(e,r)}dateBucket(e,r){return`DATE_TRUNC('${r.replaceAll("'","''")}', ${e})`}datePart(e,r){return`EXTRACT(${r==="weekday"?"ISODOW":r.toUpperCase()} FROM ${e})`}dateShift(e,r,n){return`(${e} + INTERVAL '${n} ${r.replaceAll("'","''")}')`}datePeriodBoundary(e,r,n){const o=this.dateBucket(e,r);return n==="start"?o:`(${o} + INTERVAL '1 ${r.replaceAll("'","''")}' - INTERVAL '1 microsecond')`}castValue(e,r){return`CAST(${e} AS ${r==="timestamp"?"TIMESTAMP":r==="date"?"DATE":"VARCHAR"})`}scalarExtremum(e,r){return`${e.toUpperCase()}(${r.join(", ")})`}aggregateFunction(e,r){const n={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"};if(e==="countDistinct")return`COUNT(DISTINCT ${r??"*"})`;const o=n[e];if(!o)throw new Error(`Unsupported DuckDB aggregate: ${e}`);return`${o}(${r??"*"})`}stringify(e){return`CAST(${e} AS VARCHAR)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){return n?`REGEXP_MATCHES(${e}, ${r}, '${n.replaceAll("'","''")}')`:`REGEXP_MATCHES(${e}, ${r})`}arrayContains(e,r){return`LIST_CONTAINS(${e}, ${r})`}async materialize(e,r,n){const o=r.map(wl),i=o.map(a=>`${this.quoteIdentifier(a.name)} ${a.sqlType}`).join(", ");await this.connection.run(`CREATE TABLE ${this.quoteIdentifier(e)} (${i})`);const s=await this.connection.createAppender(e);try{for(const a of n){for(const u of o){const c=El(a[u.name],u);c===null?s.appendNull():s.appendValue(c,u.type)}s.endRow()}s.flushSync()}finally{s.closeSync()}}async execute(e){e.signal?.throwIfAborted();const r=await this.connection.runAndReadAll(e.sql,e.parameters.map(Il));return e.signal?.throwIfAborted(),r.getRowObjectsJS()}close(){return this.connection.closeSync(),this.instance.closeSync(),Promise.resolve()}}const eo="__sdb_total__",_l="__sdb_total_source__",to=t=>{const e={...t,orderBy:[]};return delete e.pagination,e},Sl=t=>{const e={...t};return delete e.limit,delete e.page,e},ro=(t,e)=>({sql:`SELECT ${e.aggregateFunction("count")} AS ${e.quoteIdentifier(eo)} FROM ${e.tableAlias(`(${t.sql})`,_l)}`,parameters:t.parameters}),Tr=t=>{if(t.length===0)return 0;const e=t[0]??{},r=e[eo]??e[eo.toUpperCase()]??Object.values(e)[0],n=typeof r=="number"?r:Number(r);if(!Number.isSafeInteger(n)||n<0)throw new p("INVALID_TOTAL_RESULT","The total query must return a non-negative safe integer",{total:r});return n},_t="__semanticdb_coordinator__",ks=(t,e)=>{const r=new Set;for(const n of we(t)){const o=e.findSource(n.schemaId,n.source,n.connectionId);if(!o)throw new p("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${n.schemaId}:${n.source}`,{schemaId:n.schemaId,source:n.source});r.add(o.connectionId)}return[...r]},Lr=(t,e)=>!!t.subplans&&new Set(t.subplans?.flatMap(r=>ks(r,e))).size>1||!!(t.sourcePlan&&Lr(t.sourcePlan,e)),Rl=(t,e)=>({name:t,expression:{kind:"column",property:t,column:t,qualifier:e}}),bl=(t,e)=>{const r=t.map(n=>n[e]).find(n=>n!=null);return typeof r=="number"||typeof r=="bigint"?"number":typeof r=="boolean"?"boolean":r instanceof Date?"date":"string"},Us=(t,e)=>{const r=new Map((t.columnProperties??[]).map(n=>[n.name,n]));return[...t.projections.map(({name:n})=>n),"_id"].map(n=>{const o=r.get(n),i=n==="_id"?"string":o?.primal_type==="number"?"number":o?.primal_type==="boolean"?"boolean":o?.primal_type==="date"?"date":o?.primal_type==="entity"||o?.primal_type==="object"?bl(e,n):"string";return{name:n,kind:i}})},Ol=(t,e)=>{const r=t.projections.map(({name:n})=>n);return{schemaId:t.schemaId,source:e,sourceAlias:e,fields:Object.fromEntries([...r,"_id"].map(n=>[n,n])),projections:[...r,"_id"].map(n=>Rl(n,e)),...t.columnProperties?{columnProperties:t.columnProperties}:{},groupBy:[],orderBy:[],rowIdentity:{kind:"generated"}}},Nl=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:JSON.stringify(r.names.map(o=>{const i=n[o];return i==null?["null"]:i instanceof Date?["date",i.toISOString()]:typeof i=="bigint"?["bigint",i.toString()]:typeof i=="object"?"_id"in i||"id"in i?["entity",gr(i)]:["object",JSON.stringify(i)]:[typeof i,i]}))}))}if(e.rowIdentity.kind==="singleton")return t.map(r=>({...r,_id:"0"}));throw new p("UNSTABLE_FEDERATED_IDENTITY","A federated composition branch must be grouped or aggregate to a singleton row")},js=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:Dn(n,r.names,r.separator,r.nullLabel)}))}return e.rowIdentity.kind==="singleton"?t.map(r=>({...r,_id:"0"})):[...t]},no=async(t,e)=>{if(!Number.isSafeInteger(e.maxMaterializedRows)||e.maxMaterializedRows<1)throw new p("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:e.maxMaterializedRows});if(t.sourcePlan&&Lr(t.sourcePlan,e.schemaMappings)){const s=await no(t.sourcePlan,e),a=await Ur.create();try{const u="__federated_source";await a.materialize(u,Us(t.sourcePlan,s.rows),s.rows);const c={...t,source:u};delete c.sourcePlan,delete c.sourceLogicform,delete c.connectionId;const l=he(c,a,e.operators),d=ro(he(to(c),a,e.operators),a);e.onCompiled({compiled:l,connectionId:_t,provider:a,type:"computation",logicform:e.logicform}),e.onCompiled({compiled:d,connectionId:_t,provider:a,type:"total",logicform:e.logicform});const f=await a.execute({...d,...e.signal?{signal:e.signal}:{}}),m=await a.execute({...l,...e.signal?{signal:e.signal}:{}});return{rows:js(m,t),total:Tr(f),connections:s.connections}}finally{await a.close()}}if(!t.subplans||t.subplans.length<2)throw new p("INVALID_FEDERATED_PLAN","A federated composition requires at least two child plans");const r=new Map,n=await Promise.all(t.subplans.map(async s=>{const a=ks(s,e.schemaMappings);if(a.length!==1)throw new p("CROSS_CONNECTION_FRAGMENT_UNSUPPORTED","A federated branch must compile completely on one physical connection",{schemaId:s.schemaId,connectionIds:a});const u=a[0],c=e.providerForConnection(u);r.set(u,c.kind);const l=he(s,c,e.operators);e.onCompiled({compiled:l,connectionId:u,provider:c,type:"computation",logicform:e.logicform});const d=await Re(l,we(s),{provider:c,connectionId:u,schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}}),f=await Xe(d,s.projections,e.operators);return{child:s,rows:Nl(f,s)}})),o=n.reduce((s,a)=>s+a.rows.length,0);if(o>e.maxMaterializedRows)throw new p("FEDERATED_RESULT_LIMIT_EXCEEDED",`Federated execution materialized ${o} rows; maximum is ${e.maxMaterializedRows}`,{materializedRowCount:o,maxMaterializedRows:e.maxMaterializedRows});const i=await Ur.create();try{const s=n.flatMap(({rows:m})=>m),a=[];for(const[m,{child:y,rows:g}]of n.entries()){const h=`__federated_branch_${m}`;await i.materialize(h,Us(y,s),g),a.push(Ol(y,h))}const u={...t,subplans:a},c=he(u,i,e.operators),l=ro(he(to(u),i,e.operators),i);e.onCompiled({compiled:c,connectionId:_t,provider:i,type:"computation",logicform:e.logicform}),e.onCompiled({compiled:l,connectionId:_t,provider:i,type:"total",logicform:e.logicform});const d=await i.execute({...l,...e.signal?{signal:e.signal}:{}}),f=await i.execute({...c,...e.signal?{signal:e.signal}:{}});return{rows:js(f,t),total:Tr(d),connections:[...r].map(([m,y])=>({connectionId:m,provider:y}))}}finally{await i.close()}};class Pl{create;#e=new Map;constructor(e=qs){this.create=e}get(e){const r=this.#e.get(e.id);if(r){if(!ra.isDeepStrictEqual(r.connection,e))throw new p("DATABASE_CONNECTION_CONFIGURATION_MISMATCH",`Database connection configuration changed for id: ${e.id}`,{connectionId:e.id});return r.provider}const n=this.create(e);return this.#e.set(e.id,{connection:e,provider:n}),n}async close(){const e=[...this.#e.values()].map(({provider:o})=>o);this.#e.clear();const r=await Promise.allSettled(e.map(async o=>o.close())),n=[];for(const o of r)o.status==="rejected"&&n.push(o.reason);if(n.length>0)throw new AggregateError(n,"Failed to close one or more database connections")}}const Dr=new Map,Tl=t=>{const e=Dr.get(t);if(e)return e;const r=new Pl(n=>qs(n,t));return Dr.set(t,r),r},Ll=(t,e=Cs)=>Tl(e).get(t),Dl=async()=>{const t=[...Dr.values()];Dr.clear();const r=(await Promise.allSettled(t.map(async n=>n.close()))).flatMap(n=>n.status==="rejected"?[n.reason]:[]);if(r.length>0)throw new AggregateError(r,"Failed to close one or more connection registries")},Cl=new Set(["$sply","$splm","$splq","$splw","$yoy","$mom","$qoq","$wow","$yoyd","$momd","$qoqd","$wowd","$percentage"]),Ms=t=>!oe(t)||!Array.isArray(t.properties)?[]:t.properties.filter(oe),St=(t,e,r)=>{const n=(o,i,s)=>{const c=Ms(r[o]).map(y=>{const g=typeof y.id=="string"?y.id:void 0,h=typeof y.name=="string"?y.name:void 0,A=[g,h].filter(_=>!!_&&(i===_||i.startsWith(`${_}_`))).sort((_,E)=>E.length-_.length)[0];return A?{property:y,key:A}:void 0}).filter(y=>!!y).sort((y,g)=>g.key.length-y.key.length)[0];if(!c)return;const l=String(c.property.id??c.property.name),d=i===c.key?"":i.slice(c.key.length+1);if(!d)return l;const f=typeof c.property.ref=="string"?c.property.ref:void 0;if(!f||s.has(f))return;const m=n(f,d,new Set(s).add(f));return m?`${l}_${m}`:void 0};return n(t,e,new Set([t]))},oo=(t,e,r)=>{const n=Ms(r[t]).filter(o=>typeof o.id=="string").sort((o,i)=>String(i.id).length-String(o.id).length).find(o=>e===o.id||e.startsWith(`${String(o.id)}_`));if(!(!n||typeof n.id!="string")){if(e===n.id)return n.id;if(typeof n.ref=="string")return oo(n.ref,e.slice(n.id.length+1),r)}},xs=t=>Object.keys(t).filter(e=>e!=="$and"&&e!=="$or"),oe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Vs=t=>typeof t=="string"&&/^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?$/.test(t),vs=t=>{if(!oe(t))return t;if(oe(t.$offset)){const e=Object.entries(t.$offset),r=e[0];if(e.length===1&&r&&Number.isInteger(r[1]))return{granularity:r[0],offset:r[1]}}return t},ql=t=>typeof t=="string"&&t.length>0||typeof t=="number"&&Number.isSafeInteger(t),kl=(t,e)=>{if(!e)return;const r=e[t]??Object.values(e).find(u=>oe(u)&&(u.id===t||u._id===t));if(!oe(r))return;const n=r.hierarchy,o=Array.isArray(n)?n:oe(n)&&Array.isArray(n.levels)?n.levels:void 0;if(!o)return;const i=o.map(u=>{if(!oe(u)||typeof u.name!="string")return;const c=u.codeLength??u.code_length;return Number.isInteger(c)&&Number(c)>0?{name:u.name,codeLength:Number(c)}:void 0});if(i.length===0||i.some(u=>u===void 0))return;const s=o[0],a=Array.isArray(n)?oe(s)&&s.use_full_length===!0?"zero-padded":"compact":oe(n)&&n.storage==="zero-padded"?"zero-padded":"compact";return{levels:i.filter(u=>u!==void 0),storage:a}},Ul=(t,e,r)=>{const n=kl(t,r);if(!n)return;const o=String(e),i=n.levels.reduce((a,u)=>a+u.codeLength,0);let s=0;for(const a of n.levels)if(s+=a.codeLength,o.length===s||n.storage==="zero-padded"&&o.length===i&&o.slice(s)==="0".repeat(i-s))return a.name;throw new p("LEGACY_HIERARCHY_LEVEL_INFERENCE_FAILED",`Cannot infer hierarchy level from entity_id ${o} in Schema ${t}`,{schemaId:t,entityId:e})},jl=(t,e)=>e.length===0?t:e.length===1&&t.$expr===void 0?{...t,$expr:e[0]}:{$and:[...Object.keys(t).length>0?[t]:[],...e.map(n=>({$expr:n}))]},io=(t,e)=>{const r={},n=[];for(const[o,i]of Object.entries(t)){if((o==="$and"||o==="$or")&&Array.isArray(i)){r[o]=i.map(y=>oe(y)?io(y,e):y);continue}if(!oe(i)){r[o]=i;continue}const s=i.entity_id;if(typeof i.schema!="string"||!oe(i.query)||!ql(s)){r[o]=i;continue}const a=i.entity_level,u=typeof a=="string"&&a.length>0?a:Ul(i.schema,s,e);if(!u){r[o]=i;continue}const{entity_id:c,entity_level:l,...d}=i,f=io(i.query,e),m=Object.keys(d).filter(y=>y!=="schema"&&y!=="version"&&y!=="query");(Object.keys(f).length>0||m.length>0)&&(r[o]={...d,query:f}),n.push({pred:{operator:"$hierarchyLevel",pred:o,args:{level:u}},condition:s})}return jl(r,n)},Ml=(t,e)=>{const n=t&&({$sply:"$periodShift",$splm:"$periodShift",$splq:"$periodShift",$splw:"$periodShift",$yoy:"$periodGrowth",$mom:"$periodGrowth",$qoq:"$periodGrowth",$wow:"$periodGrowth",$yoyd:"$periodDifference",$momd:"$periodDifference",$qoqd:"$periodDifference",$wowd:"$periodDifference",$dailyavg:"$averagePerPeriod",$weeklyavg:"$averagePerPeriod",$monthlyavg:"$averagePerPeriod",$startOfPeriod:"$periodValue",$endOfPeriod:"$periodValue",$dateLevel:"$dateBucket",$uniq:"$countDistinct",$percentage:"$shareOfTotal"}[t]??t),o={...e};return t==="$sply"||t==="$yoy"||t==="$yoyd"?o.time??={granularity:"year",offset:-1}:t==="$splm"||t==="$mom"||t==="$momd"?o.time??={granularity:"month",offset:-1}:t==="$splq"||t==="$qoq"||t==="$qoqd"?o.time??={granularity:"quarter",offset:-1}:t==="$splw"||t==="$wow"||t==="$wowd"?o.time??={granularity:"week",offset:-1}:t==="$dailyavg"?o.granularity??="day":t==="$weeklyavg"?o.granularity??="week":t==="$monthlyavg"?o.granularity??="month":t==="$startOfPeriod"?o.boundary??="start":t==="$endOfPeriod"&&(o.boundary??="end"),{...n?{operator:n}:{},args:o}},Be=(t,e)=>{if(Array.isArray(t))return t.map(s=>Be(s,e));if(!oe(t))return t;const r=vs(t);if(r!==t)return r;const n=t,o={};for(const[s,a]of Object.entries(n))s==="skip"||s==="_snapshot"||s==="_snapshots"||(o[s]=Be(a,e));if(typeof n.version=="string"&&/^1\./.test(n.version)&&(o.version="2.0"),Array.isArray(n.groupby)){const s=n.groupby;o.groupby=s.map(a=>{if(!oe(a))return a;const{_id:u,level:c,...l}=a,d={...l,...l.pred===void 0&&typeof u=="string"?{pred:u}:{}};return typeof c=="string"&&(d.operator="$dateBucket",d.args={...oe(d.args)?d.args:{},granularity:c}),d})}const i=n.skip;if(typeof i=="number"&&Number.isInteger(i)&&i>=0){const s=n.limit;i===0?delete o.skip:typeof s=="number"&&Number.isInteger(s)&&s>0&&i%s===0?o.page=i/s+1:o.skip=i}else i!==void 0&&(o.skip=Be(i));if(n.operator&&typeof n.operator=="string"){const s=Ml(n.operator,oe(o.args)?o.args:{});s.operator&&(o.operator=s.operator),o.args=s.args,Cl.has(n.operator)&&typeof o.pred=="string"&&(o.pred={operator:"$sum",pred:o.pred})}return n.params!==void 0&&o.args===void 0&&(o.args=Array.isArray(n.params)?{values:Be(n.params,e)}:Be(n.params,e)),n.inputs!==void 0&&o.pred===void 0&&Array.isArray(n.inputs)&&(o.pred=n.inputs.map(s=>Be(s,e)),oe(o.args)&&delete o.args.inputs),n.pred===void 0&&typeof n.operator=="string"&&n.operator==="$sql"&&typeof n.sql=="string"&&(o.args={...oe(o.args)?o.args:{},sql:n.sql},delete o.sql),n.$options!==void 0&&o.$regex!==void 0?(o.args={...oe(o.args)?o.args:{},options:n.$options},delete o.$options):"$options"in n&&Vs(n.$gte)&&Vs(n.$lte)&&delete o.$options,n.query&&oe(n.query)&&(o.query=xl(n.query,e)),o},xl=(t,e)=>{const r=Be(t,e);for(const[n,o]of Object.entries(r))r[n]=vs(o);return io(r,e)},Ys=(t,e)=>{const r=oe(t)?t:void 0,n=Be(t,e);if(!oe(n))return n;if(r&&typeof r.operator=="string"&&r.preds===void 0){const o={};for(const a of["version","schema","query","groupby","having","sort","limit","page","skip","output","representation","currency"])n[a]!==void 0&&(o[a]=n[a]);const i=new Set(["version","schema","query","groupby","having","sort","limit","page","skip","output","representation","currency"]),s=Object.fromEntries(Object.entries(n).filter(([a])=>!i.has(a)));return o.preds=[s],Ys(o,e)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),e?Vl(n,e):n},Vl=(t,e)=>{const r=t;if(!Array.isArray(r.preds))return t;const n=r.preds,o=typeof r.schema=="string"?r.schema:void 0;if(!o)return t;const i=new Set([o]);for(const u of n)oe(u)&&typeof u.schema=="string"&&i.add(u.schema);if(i.size<2)return t;if(!e)throw new Error("Cannot migrate cross-Schema LogicForm without Schema metadata for field alignment");const s=Array.isArray(r.groupby)?r.groupby.map(u=>oe(u)&&typeof u.pred=="string"?St(o,u.pred,e):void 0):[];for(const u of i)if(Array.isArray(r.groupby)&&r.groupby.map((c,l)=>{if(!oe(c)||typeof c.pred!="string")return c;const d=u===o?St(u,c.pred,e):St(u,oo(o,s[l]??"",e)??c.pred,e);if(!d)return c;const f=d.split("_").at(-1)??c.pred;return{...c,pred:d,name:f}}),oe(r.query))for(const c of xs(r.query)){const l=St(o,c,e);if(!(u===o?l:St(u,(l&&oo(o,l,e))??c,e))&&u===o)throw new Error(`Cannot align legacy query field ${c} in Schema ${u}`)}const a={...r};if(Array.isArray(r.groupby)&&(a.groupby=r.groupby.map((u,c)=>{if(!oe(u)||typeof u.pred!="string")return u;const l=s[c];return l?{...u,pred:l}:u})),oe(r.query)){const u=r.query,c=xs(u).map(l=>[St(o,l,e)??l,u[l]]);a.query=Object.fromEntries(c)}return a},vl=t=>{const e=(r,n)=>{if(Array.isArray(r)){r.forEach((o,i)=>e(o,`${n}[${i}]`));return}if(oe(r))for(const[o,i]of Object.entries(r)){if(["is_snapshot","is_observation","_snapshot","_snapshots","$options","params","inputs","entity_level","entity_codelength"].includes(o))throw new p("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);if(o==="_id"&&(n.endsWith(".groupby")||n.includes(".groupby[")))throw new p("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);e(i,`${n}.${o}`)}};e(t,"$")},so=t=>{if(Array.isArray(t))return t.map(so).filter(n=>n!==void 0);if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return t;const e=Object.entries(t),r=e.filter(([,n])=>n!==null).map(([n,o])=>[n,so(o)]).filter(([,n])=>n!==void 0);if(!(e.length>0&&r.length===0))return Object.fromEntries(r)},Yl=t=>{if(t.comparable!=null)return t.comparable;if(t.is_comparable!==!0||t.isArray===!0||t.type!=="string"&&t.type!=="category"||!Array.isArray(t.constraints?.enum))return;const r=t.constraints.enum.map(n=>Array.isArray(n)?n[0]:n);if(!(r.length===0||r.some(n=>typeof n!="string")))return{values:[...new Set(r)],direction:t.comparable_order===-1?-1:1}},Fl=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const e=t;if(e.sql!=null)return Object.keys(e).every(r=>r==="sql")?t:{sql:e.sql}},Bl=(t,e=[],r=!0)=>{const n=me(e),o={},i=new Set(n.flatMap(s=>[...s.schemaMetadata?.keys??[],...s.legacySchemaKeys??[]]));for(const[s,a]of Object.entries(t)){const u=so(a),c=u,d=(Array.isArray(c.properties)?c.properties:[]).some(_=>_.is_observation===!0)||c.is_observation===!0,f=c.is_snapshot===!0,m=typeof u.id=="string"&&u.id.length>0?u.id:r&&typeof u._id=="string"&&u._id.length>0?u._id:u.id,{properties:y}=u,g=Object.fromEntries(Object.entries(u).filter(([_])=>(r?!["_id","_sid","sid","is_observation","is_snapshot"].includes(_):_!=="properties")&&_!=="properties"&&!i.has(_))),h=y.map(_=>{const E=_,$=typeof E.id=="string"&&E.id.length>0?E.id:r&&typeof E._id=="string"&&E._id.length>0?E._id:E.id,{udf:b,...N}=E,k=Yl(E),j=Fl(b),U=k!==void 0&&E.comparable==null?"category":E.type==="object"?"entity":E.type;return{...r?Object.fromEntries(Object.entries(N).filter(([B])=>!["_id","_sid","sid","is_observation","is_comparable","comparable_order"].includes(B))):N,type:U,...E.primal_type==="object"?{primal_type:"entity"}:{},...$!==void 0?{id:$}:{},...j!==void 0?{udf:j}:{},...k!==void 0?{comparable:k}:{}}});let w={};for(const _ of n)for(const E of _.schemaMetadata?.keys??[])u[E]!==void 0&&(w={...w,[E]:u[E]});for(const _ of n)w={...w,..._.normalizeLegacySchema?.({source:u,properties:h})};const A={...g,...m!==void 0?{id:m}:{},properties:h,...r&&(f||d)?{temporalSemantics:"snapshot"}:{},...w};o[s]=A}return o},Fs=(t,e)=>[...me(t).flatMap(r=>r.locales??[]),...e===void 0?[]:"locale"in e?[e]:e],Cr=t=>({kind:"query",logicform:t.logicform,...t.prepare!==void 0?{prepare:t.prepare}:{},...t.mapResult?{mapResult:t.mapResult}:{},...t.groupKeyShifts?{groupKeyShifts:t.groupKeyShifts}:{}}),Bs=t=>t instanceof Error?t:new Error(String(t)),Ql=(t,e="zh-CN",r)=>t instanceof p?t.localizedMessage(e,r):t.message,Hl=(t,e,r={},n="zh-CN",o)=>{const i=Bs(t);return{errorCode:"100",error:Ql(i,n,o),result:[],...r.schema?{schema:r.schema}:{},normedLogicform:r.normedLogicform??e,sqls:r.sqls??[],...r.provider?{provider:r.provider}:{},...r.lineage?{lineage:r.lineage}:{}}},Gl=(t,e,r)=>{const n=e.projections.map(({name:c})=>c),o=new Map((e.columnProperties??[]).map(c=>[c.name,c])),i=[],s=(c,l)=>{const d=r.parameter(i.length,l);i.push(l);const f=o.get(c)?.type;return f&&(f==="date"||f==="timestamp")&&r.castValue?r.castValue(d,f):d},a=c=>`SELECT ${n.map(l=>`${s(l,c[l])} AS ${r.quoteIdentifier(l)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""}`;return{sql:t.length>0?t.map(a).join(" UNION ALL "):`SELECT ${n.map(c=>`NULL AS ${r.quoteIdentifier(c)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""} WHERE 1 = 0`,parameters:i}},zl=(t,e,r)=>{if(t.length<2||t.some(i=>i.kind==="js"||i.kind==="query"&&i.unit.mapResult))return!1;const n=new Set,o=[...t.flatMap(({sources:i})=>i),...we(r)];for(const i of o){const s=Kn(i,e);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},Wl=async(t,e,r)=>{await t?.({...e,partialResult:r})},Kl=(t,e,r,n,o,i,s=r,a)=>({type:r,...a?{connectionId:a}:{},provider:e.kind,explain:i.translate(o,s==="time-watermark"?"sql.timeWatermark":s==="entity-expansion"?"sql.entityExpansion":s==="total"?"sql.total":s==="computation"?"sql.computation":"sql.semanticResolution"),logicform:n,sql:t.sql,parameters:[...t.parameters],displaySql:e.displayQuery(t.sql,t.parameters)}),Qs=(t,e)=>{if(e.connectionId)for(const r of we(t)){const n=Kn(r,e.schemaMappings);if(!n)throw new p("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${r.schemaId}:${r.source}`,{schemaId:r.schemaId,source:r.source});if(n.connectionId!==e.connectionId)throw new p("CROSS_CONNECTION_QUERY_UNSUPPORTED",`One physical query cannot use multiple database connections: ${e.connectionId}, ${n.connectionId}`,{schemaId:r.schemaId,source:r.source,connectionId:n.connectionId})}},Jl=t=>{const e=new Set,r=n=>{n.from&&r(n.from),n.schema&&e.add(n.schema);for(const o of n.preds??[])for(const i of ao(o))e.add(i)};return r(t),[...e]},ao=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...ao(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:ao(r))]:e},Xl=async(t,e)=>{const r=e.locale??"zh-CN",n=e.localeRegistry??er(Fs(e.plugins,e.locales)),o=e.plugins??[],i=t.version,s=typeof i=="string"&&(/^2\./.test(i)||/^[3-9]\d*\./.test(i)),a=i===void 0||typeof i=="string"&&/^1\./.test(i);s&&vl(t);const u=a?Ys(t,e.schemas):t,c={...e,locale:r,localeRegistry:n,schemas:Bl(e.schemas,o,a)},l=Mr.performance.now(),d=c.semanticTypes===void 0?vn(o):c.semanticTypesResolved?c.semanticTypes:es(c.semanticTypes,o),f=c.operators??Ne(o);if(c.operators&&!c.operatorsResolved)for(const T of o)for(const M of T.operators??[])if(f.has(M.name)){if(f.get(M.name)!==M)throw new p("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${M.name}`,{operator:M.name,plugin:T.name})}else f.register(M);const m=c.schemaMappings,y=new Date,g=new Map,h=[],w=new Set,A=T=>{const M=JSON.stringify(T);w.has(M)||(w.add(M),h.push(T),_={..._,schemaMappingSelections:[...h]})};let _={provider:c.provider.kind};const E=[],$=new Map;c.connectionId&&$.set(c.connectionId,c.provider.kind);const b=(T,M,J,H=M,Ae=c.provider,ie=c.connectionId)=>{ie&&ie!==_t&&$.set(ie,Ae.kind),E.push(Kl(Is(T),Ae,M,J,c.locale??"zh-CN",n,H,ie)),_={..._,sqls:[...E],providers:[...$].map(([de,I])=>({connectionId:de,provider:I}))}},N=async(T,M={})=>{_={..._,...M},await Wl(c.onProgress,T,_)},k=T=>Wi(Ua(T,c.schemas),d,o),j=new Map,U=T=>{const M=j.get(T);return M||(Me(c.permissions,T),k(T))},z=T=>{if(T.schema)return U(T.schema);if(T.from)return z(T.from);throw new p("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},B=T=>{if(T.schema)return k(T.schema);if(T.from)return B(T.from);throw new p("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},D={plugins:o,resolveSchema:U,onSchemaMappingSelection:A,...c.connectionId?{preferredConnectionId:c.connectionId}:{},canUsePropertyRowIdentity:(T,M)=>et(c.permissions,T.id,M)},Q=(T,M)=>{const J=Ri(Pe(T,z(T),f,m,D),M);return j.set(J.id,J),J},ce=async(T,M,J)=>{const H=`${T.id}:${M.id}:${J.toISOString()}`,Ae=g.get(H);if(Ae)return Ae;const ie=(async()=>{const de=me(o).find(te=>te.createTimeWatermarkLogicform)?.createTimeWatermarkLogicform;if(!de)return;const I=de({logicform:u,rootSchema:T,rootProperty:M,requestedUpperBound:J,now:y,...c.timeWatermark?{defaultPolicy:c.timeWatermark}:{},resolveSchema:U,inferPropertyPath:(te,q,ue)=>ys(te,q,ue,U)}),S=tt(I,c.permissions,U,!1,new Set,o),R=await Et(S,T,{semanticTypes:d,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:U,resolveFromSchema:Q}),P=Pe(R,T,f,m,D);let C;if(Lr(P,m)){const te=c.providerForConnection;if(!te)throw new p("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated timeWatermark resolution requires a provider resolver");C=(await no(P,{logicform:R,operators:f,schemaMappings:m,providerForConnection:te,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:ue,logicform:re,provider:Y,connectionId:Oe})=>b(ue,"semantic-resolution",re,"time-watermark",Y,Oe)})).rows}else{Qs(P,c);const te=he(P,c.provider,f);b(te,"semantic-resolution",R,"time-watermark"),C=await Re(te,we(P),c)}const v=C[0]?.__timeWatermark__??Object.values(C[0]??{})[0];if(v==null||!(v instanceof Date)&&typeof v!="string"&&typeof v!="number")return;const W=v instanceof Date?v:new Date(v);return Number.isNaN(W.getTime())?void 0:W})();return g.set(H,ie),ie};try{c.signal?.throwIfAborted(),Yn(u),await N({stage:"started",logicform:u}),Ip(c.permissions,k);const T=z(u);await N({stage:"validated",schema:T});const M=tt(u,c.permissions,U,!0,new Set,o),J=await Et(M,T,{semanticTypes:d,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:U,resolveFromSchema:Q,canProjectProperty:(O,L)=>et(c.permissions,O.id,L),requestTimeWatermark:ce});await N({stage:"normalized",normedLogicform:J},{normedLogicform:J});const H=Pe(J,T,f,m,D),Ae=Lr(H,m);Ae||Qs(H,c);const ie=H.columnProperties??[],de=Si(H,T);j.set(de.id,de),await N({stage:"planned",plan:H},{schema:de});const I=mi(H,T,c.provider,f,c.providerForConnection);if(await N({stage:"lineage",lineage:I},{lineage:I}),Ae){const O=c.providerForConnection;if(!O)throw new p("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated execution requires a provider resolver for every physical connection");const L=await no(H,{logicform:J,operators:f,schemaMappings:m,providerForConnection:O,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:le,type:X,logicform:ee,provider:$e,connectionId:fe})=>b(le,X,ee,X,$e,fe)});await N({stage:"compiled",sqls:[...E]},{sqls:[...E]}),await N({stage:"executing",provider:"duckdb",connectionId:_t}),await N({stage:"hydrating"});const F=L.connections.length===1?L.connections[0]?.connectionId:void 0,x=await Os(L.rows,ie,{semanticTypes:d,plugins:o,resolveSchema:U,fetchEntities:le=>_s(le,{version:J.version,operators:f,schemaMappings:m,semanticTypes:d,plugins:o,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:U,...c.permissions?{permissions:c.permissions}:{},provider:c.provider,providerForConnection:O,...F?{preferredConnectionId:F}:{},...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:(X,ee,$e,fe)=>b(X,"semantic-resolution",ee,"entity-expansion",$e,fe)})}),G=Cn(x,H.rowIdentity);return await N({stage:"result",result:G},{result:G,total:L.total,sqls:[...E],providers:L.connections}),await N({stage:"completed",durationMs:Mr.performance.now()-l}),{result:G,total:L.total,schema:de,normedLogicform:J,sqls:[...E],lineage:I,provider:"duckdb",providers:L.connections,schemaMappingSelections:[...h]}}const S=$r(J,H,T,f,U,void 0,r,n.translator(r)),R=async(O,L)=>{const F=L&&O.logicform.schema===L.id?L:z(O.logicform),x=O.prepare?await Et(tt(O.logicform,c.permissions,U,!0,new Set,o),F,{semanticTypes:d,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:U,resolveFromSchema:Q,canProjectProperty:(X,ee)=>et(c.permissions,X.id,ee),requestTimeWatermark:ce}):O.logicform,G=Pe(x,F,f,m,D),le=$r(x,G,F,f,U,O.logicform,r,n.translator(r));if(le){if(le.length!==1)throw new Error("A generated component must produce exactly one execution unit");const X=le[0];if("logicform"in X){const fe=await R(X,F),ot=fe.component.mapResult,qe=O.mapResult;return{...fe,component:{...O,logicform:fe.component.logicform,...ot||qe?{mapResult:ke=>{const He=ot?.(ke)??[...ke];return qe?.(He)??[...He]}}:{}}}}if("mergeRow"in X)throw new p("UNSUPPORTED_NESTED_JS_COMPONENT","A JavaScript composite metric cannot currently be nested as a generated component");const ee=await Promise.all(X.components.map(async fe=>({name:fe.name,prepared:await R(Cr(fe)),...fe.groupKeyShifts?{groupKeyShifts:fe.groupKeyShifts}:{},...fe.joinKeys?{joinKeys:fe.joinKeys}:{}}))),$e=hr(X,ee.map(({name:fe,prepared:ot,...qe})=>({name:fe,plan:ot.plan,...qe})),G,X.outputName,c.provider,f);return{component:{...O,logicform:x},plan:G,compiled:$e,sources:Qt(ee.map(({prepared:fe})=>fe.sources))}}return{component:{...O,logicform:x},plan:G,compiled:he(G,c.provider,f),sources:we(G)}},P=async(O,L)=>{const F=$r(O,L,z(O),f,U,void 0,r,n.translator(r));if(!F)return{compiled:he(L,c.provider,f),sources:we(L)};const x=await Promise.all(F.map(async G=>{if("logicform"in G){const ee=await R(G);return{plan:ee.plan,compiled:ee.compiled,outputs:ee.plan.projections.map(({name:$e})=>$e).filter($e=>!L.groupBy.some(fe=>fe.name===$e))}}if("mergeRow"in G)throw new p("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const le=await Promise.all(G.components.map(async ee=>{const $e=await R(Cr(ee));return{name:ee.name,plan:$e.plan,...ee.joinKeys?{joinKeys:ee.joinKeys}:{},...ee.groupKeyShifts?{groupKeyShifts:ee.groupKeyShifts}:{}}})),X=hr(G,le,L,G.outputName,c.provider,f);return{plan:L,compiled:X,outputs:[G.outputName,...G.components.map(ee=>ee.name)]}}));return{compiled:Pn(x,L,c.provider,f),sources:Qt(x.map(({plan:G})=>we(G)))}},C=new WeakMap,v=async O=>{if(!O.sourcePlan||!O.sourceLogicform)return he(O,c.provider,f);const L=B(O.sourceLogicform),F=$r(O.sourceLogicform,O.sourcePlan,L,f,U,void 0,r,n.translator(r));if(F?.some(ee=>"mergeRow"in ee)){const ee=C.get(O.sourcePlan);if(ee){const ne={...O};delete ne.sourcePlan,delete ne.sourceLogicform;const xe=he({...ne,sourceSql:ee.sql,source:O.source},c.provider,f,ee.parameters.length);return{sql:xe.sql,parameters:[...ee.parameters,...xe.parameters]}}const $e=await Promise.all(F.map(async ne=>{if("logicform"in ne)return{kind:"query",unit:ne,prepared:await R(ne,L)};const xe=await Promise.all(ne.components.map(async ge=>({input:ge,prepared:await R(Cr(ge),L)})));return"mergeRow"in ne?{kind:"js",unit:ne,components:xe}:{kind:"component",unit:ne,components:xe,compiled:hr(ne,xe.map(({input:ge,prepared:Te})=>({name:ge.name,plan:Te.plan,...ge.joinKeys?{joinKeys:ge.joinKeys}:{},...ge.groupKeyShifts?{groupKeyShifts:ge.groupKeyShifts}:{}})),O.sourcePlan,ne.outputName,c.provider,f)}})),fe=O.sourcePlan.groupBy.map(({name:ne})=>ne),ot=await Promise.all($e.map(async ne=>{if(ne.kind==="query"){b(ne.prepared.compiled,"computation",ne.prepared.component.logicform);const ge=await Re(ne.prepared.compiled,ne.prepared.sources,c),Te=await Xe(ge,ne.prepared.plan.projections,f);return ne.unit.mapResult?.(Te)??Te}if(ne.kind==="component")return b(ne.compiled,"computation",O.sourceLogicform),Re(ne.compiled,Qt(ne.components.map(({prepared:ge})=>ge.sources)),c);const xe=await Promise.all(ne.components.map(async({input:ge,prepared:Te})=>{b(Te.compiled,"computation",Te.component.logicform);const zs=await Re(Te.compiled,Te.sources,c),lo=await Xe(zs,Te.plan.projections,f);return ge.mapResult?.(lo)??lo}));return Promise.all(kn(xe,fe).map(async ge=>({...ge,[ne.unit.outputName]:await ne.unit.mergeRow(ge)})))})),qe=Un(ot,O.sourcePlan),ke=c.federation?.maxMaterializedRows??1e5;if(!Number.isSafeInteger(ke)||ke<1)throw new p("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:ke});if(qe.length>ke)throw new p("MATERIALIZED_RESULT_LIMIT_EXCEEDED",`Nested component materialized ${qe.length} rows; maximum is ${ke}`,{materializedRowCount:qe.length,maxMaterializedRows:ke});const He=Gl(qe,O.sourcePlan,c.provider);C.set(O.sourcePlan,He);const jr={...O};delete jr.sourcePlan,delete jr.sourceLogicform;const po=he({...jr,sourceSql:He.sql,source:O.source},c.provider,f,He.parameters.length);return{sql:po.sql,parameters:[...He.parameters,...po.parameters]}}const x=await P(O.sourceLogicform,O.sourcePlan),G={...O};delete G.sourcePlan,delete G.sourceLogicform;const le={...G,sourceSql:x.compiled.sql,source:O.source},X=he(le,c.provider,f,x.compiled.parameters.length);return{sql:X.sql,parameters:[...x.compiled.parameters,...X.parameters]}},W=S?await Promise.all(S.map(async O=>{if("logicform"in O)return{kind:"query",unit:O,...await R(O)};const L=await Promise.all(O.components.map(async x=>({name:x.name,prepared:await R(Cr(x)),...x.groupKeyShifts?{groupKeyShifts:x.groupKeyShifts}:{},...x.joinKeys?{joinKeys:x.joinKeys}:{}})));if("mergeRow"in O)return{kind:"js",unit:O,components:L.map(({prepared:x})=>x)};const F=L.map(({name:x,prepared:G,...le})=>({name:x,plan:G.plan,...le}));return{kind:"component",unit:O,plan:H,compiled:hr(O,F,H,O.outputName,c.provider,f),sources:Qt(L.map(({prepared:x})=>x.sources))}})):void 0,te=W&&zl(W,m,H)?W.map(O=>{const L=new Set(H.groupBy.map(({name:x})=>x));if(O.kind==="query")return{plan:O.plan,compiled:O.compiled,outputs:O.plan.projections.map(({name:x})=>x).filter(x=>!L.has(x))};const F=O.unit.outputName;if(!F)throw new p("INVALID_COMPONENT_PLAN","Component output projection is missing");return{plan:O.plan,compiled:O.compiled,outputs:[F,...O.unit.components.map(x=>x.name)]}}):void 0,q=te?Pn(te,H,c.provider,f):void 0,ue=W?void 0:await v(H),re=to(H),Y=H.pagination&&(q||ue)?ro(te?Pn(te,re,c.provider,f):await v(re),c.provider):void 0;if(q)b(q,"computation",J);else if(W)for(const O of W)if(O.kind==="js")for(const L of O.components)b(L.compiled,"computation",L.component.logicform);else b(O.compiled,"computation",J);else b(ue,"computation",J);Y&&b(Y,"total",Sl(J)),await N({stage:"compiled",sqls:[...E]},{sqls:[...E]}),await N({stage:"executing",provider:c.provider.kind});const Oe=q?await(async()=>{const O=Qt([...W.map(G=>G.sources),we(H)]),[L,F]=await Promise.all([Re(q,O,c),Y?Re(Y,O,c):Promise.resolve(void 0)]),x=await Xe(L,H.projections,f);return{rows:x,total:F?Tr(F):x.length}})():W?await(async()=>{const O=await Promise.all(W.map(async F=>{if(F.kind==="js"){const le=await Promise.all(F.components.map(async X=>{const ee=await Re(X.compiled,X.sources,c),$e=await Xe(ee,X.plan.projections,f);return X.component.mapResult?.($e)??$e}));return Promise.all(kn(le,H.groupBy.map(({name:X})=>X)).map(async X=>{const ee=await F.unit.mergeRow(X);return{...X,[F.unit.outputName]:ee}}))}const x=await Re(F.compiled,F.sources,c),G=F.kind==="query"?await Xe(x,F.plan.projections,f):x;return F.kind==="query"?F.unit.mapResult?.(G)??G:G})),L=Un(O,re);return{rows:H.pagination?Un(O,H):L,total:L.length}})():await(async()=>{const O=we(H),[L,F]=await Promise.all([Re(ue,O,c),Y?Re(Y,O,c):Promise.resolve(void 0)]),x=await Xe(L,H.projections,f);return{rows:x,total:F?Tr(F):x.length}})(),{rows:ye,total:Qe}=Oe;await N({stage:"hydrating"});const zt=await Os(ye,ie,{semanticTypes:d,plugins:o,resolveSchema:U,fetchEntities:O=>_s(O,{version:J.version,operators:f,schemaMappings:m,semanticTypes:d,plugins:o,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:U,...c.permissions?{permissions:c.permissions}:{},provider:c.provider,...c.connectionId?{preferredConnectionId:c.connectionId}:{},...c.providerForConnection?{providerForConnection:c.providerForConnection}:{},...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:(L,F,x,G)=>b(L,"semantic-resolution",F,"entity-expansion",x,G)})}),nt=Cn(zt,H.rowIdentity);return await N({stage:"result",result:nt},{result:nt,total:Qe,sqls:[...E]}),await N({stage:"completed",durationMs:Mr.performance.now()-l}),{result:nt,total:Qe,schema:de,normedLogicform:J,sqls:[...E],lineage:I,provider:c.provider.kind,providers:[...$].map(([O,L])=>({connectionId:O,provider:L})),schemaMappingSelections:[...h],...J.output?await(async()=>{const O=zo(J.output?.type??"",o);return O?{output:await O.handle({rows:nt,logicform:J,schema:de})}:{}})():{}}}catch(T){const M=Bs(T);try{await N({stage:"failed",error:M})}catch{}throw M}},Zl=async(t,e)=>{let r={};const n=e.locale??"zh-CN",o=er(Fs(e.plugins,e.locales));try{if(e.connections.length===0)throw new p("DATABASE_CONNECTION_REQUIRED","At least one database connection is required");const i=new Map;for(const w of e.connections){if(w.id.trim().length===0)throw new p("INVALID_DATABASE_CONNECTION","Database connection id must not be empty");if(i.has(w.id))throw new p("DATABASE_CONNECTION_ALREADY_REGISTERED",`Database connection id is duplicated: ${w.id}`,{connectionId:w.id});i.set(w.id,w)}const s=new wn(e.schemaMappings,e.plugins),u=Jl(t).flatMap(w=>s.list(w)).map(({connectionId:w})=>w)[0];if(!u)throw new p("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain at least one physical Schema leaf");const c=w=>{const A=i.get(w);if(!A)throw new p("DATABASE_CONNECTION_NOT_FOUND",`Database connection is not registered: ${w}`,{connectionId:w});return Ll(A,e.providerRegistry)},l=c(u);r={provider:l.kind};const d=Ne(e.plugins),f=e.operators===void 0?[]:Array.isArray(e.operators)?e.operators:[e.operators],m=new cr(f),y=new Set(m.definitions().map(({name:w})=>w)),g=f.length===0?d:new cr([...d.definitions().filter(({name:w})=>!y.has(w)),...m.definitions()]),h=e.semanticTypes===void 0?vn(e.plugins):es(e.semanticTypes,e.plugins??[]);return await Xl(t,{...e,schemaMappings:s,locale:n,localeRegistry:o,provider:l,providerForConnection:c,operators:g,operatorsResolved:!0,semanticTypes:h,semanticTypesResolved:!0,connectionId:u,onProgress:async w=>{r=w.partialResult,await e.onProgress?.(w)}})}catch(i){return Hl(i,t,r,n,o)}},Hs="semanticdb_calendar_dates",co="semanticdb_calendar_relations",rt={dates:"__sdb_calendar_dates",relations:"__sdb_calendar_relations"},uo=t=>`${typeof t}:${String(t)}`,ef=(t,e)=>{const r=typeof t=="number"?t:Number(t),n=typeof e=="number"?e:Number(e);return Number.isFinite(r)&&Number.isFinite(n)?r-n:String(t).localeCompare(String(e))},Gs=(t,e,r)=>{const n=r.filter(u=>u.calendar===e.calendar&&u.grain===e.grain&&u.relation===e.relation&&(e.key===void 0||u.key===e.key)),o=new Map(n.map(u=>[uo(u.sourceDateId),u])),i=t.flatMap(u=>{const c=o.get(uo(u))?.targetDateId;return c==null?[]:[c]}),s=[...new Map(i.map(u=>[uo(u),u])).values()].sort(ef),a=[];for(const u of s){const c=a[a.length-1];if(c&&typeof c.end=="number"&&typeof u=="number"&&u===c.end+1)c.end=u;else if(c&&String(c.end).match(/^\d{8}$/)&&String(u).match(/^\d{8}$/)){const l=Number(c.end),d=Number(u),f=new Date(Date.UTC(Math.floor(l/1e4),Math.floor(l/100)%100-1,l%100));f.setUTCDate(f.getUTCDate()+1);const m=new Date(Date.UTC(Math.floor(d/1e4),Math.floor(d/100)%100-1,d%100));if(f.getTime()===m.getTime()){c.end=u;continue}a.push({start:u,end:u})}else a.push({start:u,end:u})}return{dateIds:s,ranges:a}},tf=async(t,e,r)=>Gs(t,e,await r.loadRelations(t,e)),rf=(t,e)=>t.filter(r=>Object.entries(e).every(([n,o])=>r[n]===o)).map(r=>r.dateId),nf=["source_date_id","target_date_id","calendar","grain","relation","relation_key"];class of{provider;constructor(e){this.provider=e}async loadRelations(e,r){if(e.length===0)return[];const n=[...e,r.calendar,r.grain,r.relation];r.key!==void 0&&n.push(r.key);const o=e.map((c,l)=>this.provider.parameter(l,c)),i=c=>this.provider.parameter(c,n[c]),s=c=>this.provider.quoteIdentifier(c),a=[`${s("source_date_id")} IN (${o.join(", ")})`,`${s("calendar")} = ${i(e.length)}`,`${s("grain")} = ${i(e.length+1)}`,`${s("relation")} = ${i(e.length+2)}`];return r.key!==void 0&&a.push(`${s("relation_key")} = ${i(e.length+3)}`),(await this.provider.execute({sql:`SELECT ${nf.map(s).join(", ")} FROM ${s(co)} WHERE ${a.join(" AND ")}`,parameters:n})).map(c=>({sourceDateId:c.source_date_id,targetDateId:c.target_date_id,calendar:String(c.calendar),grain:String(c.grain),relation:String(c.relation),...typeof c.relation_key=="string"||typeof c.relation_key=="number"?{key:String(c.relation_key)}:{}}))}}const sf={[rt.dates]:{id:rt.dates,name:rt.dates,type:"entity",source:Hs,properties:[{id:"date_id",name:"date_id",type:"id",primal_type:"string"},{id:"calendar",name:"calendar",type:"string",primal_type:"string"},{id:"grain",name:"grain",type:"string",primal_type:"string"},{id:"period_key",name:"period_key",type:"string",primal_type:"string"},{id:"relative_day",name:"relative_day",type:"int",primal_type:"number"}]},[rt.relations]:{id:rt.relations,name:rt.relations,type:"entity",source:co,properties:[{id:"source_date_id",name:"source_date_id",type:"string",primal_type:"string"},{id:"target_date_id",name:"target_date_id",type:"string",primal_type:"string"},{id:"calendar",name:"calendar",type:"string",primal_type:"string"},{id:"grain",name:"grain",type:"string",primal_type:"string"},{id:"relation",name:"relation",type:"string",primal_type:"string"},{id:"relation_key",name:"relation_key",type:"string",primal_type:"string"}]}},af=Object.freeze({execute:Zl,close:Dl});exports.CALENDAR_DATES_TABLE=Hs,exports.CALENDAR_RELATIONS_TABLE=co,exports.CALENDAR_SYSTEM_SCHEMA_IDS=rt,exports.LocaleRegistry=Fr,exports.Logicform=af,exports.OperatorRegistry=cr,exports.PlannerSemanticRegistry=gi,exports.ProviderCalendarRelationStore=of,exports.ProviderRegistry=Ds,exports.SchemaMappingRegistry=wn,exports.SemanticDBError=p,exports.SemanticTypeRegistry=jn,exports.builtinOperators=nd,exports.builtinSemanticTypes=hn,exports.calendarSystemSchemas=sf,exports.createLocaleRegistry=er,exports.createOperatorRegistry=Ne,exports.createPlannerSemanticRegistry=$i,exports.createSemanticTypeRegistry=vn,exports.defaultLocaleRegistry=tr,exports.enUS=Co,exports.fromYiAskSchemaMapping=ud,exports.resolveCalendarPeriod=Gs,exports.resolveCalendarPeriodFromStore=tf,exports.resolveOperator=di,exports.resolveSchema=Wi,exports.selectCalendarDates=rf,exports.validateResolvedSchema=zi,exports.zhCN=qo;
1
+ "use strict";var Aa=Object.create;var Lo=Object.defineProperty;var $a=Object.getOwnPropertyDescriptor;var wa=Object.getOwnPropertyNames;var Ea=Object.getPrototypeOf,_a=Object.prototype.hasOwnProperty;var Sa=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wa(e))!_a.call(t,o)&&o!==r&&Lo(t,o,{get:()=>e[o],enumerable:!(n=$a(e,o))||n.enumerable});return t};var We=(t,e,r)=>(r=t!=null?Aa(Ea(t)):{},Sa(e||!t||!t.__esModule?Lo(r,"default",{value:t,enumerable:!0}):r,t));var Xr=require("node:perf_hooks"),ue=require("dayjs"),Mt=require("dayjs/plugin/isoWeek.js"),ar=require("dayjs/plugin/quarterOfYear.js"),Do=require("dayjs/plugin/customParseFormat.js"),Co=require("node:crypto"),Ia=require("semanticdb-core"),ba=require("node:util"),pe=require("@duckdb/node-api");const V=t=>typeof t=="string",qt=()=>{let t,e;const r=new Promise((n,o)=>{t=n,e=o});return r.resolve=t,r.reject=e,r},ko=t=>t==null?"":""+t,Ra=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},Na=/###/g,Uo=t=>t&&t.indexOf("###")>-1?t.replace(Na,"."):t,Mo=t=>!t||V(t),jt=(t,e,r)=>{const n=V(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if(Mo(t))return{};const i=Uo(n[o]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++o}return Mo(t)?{}:{obj:t,k:Uo(n[o])}},qo=(t,e,r)=>{const{obj:n,k:o}=jt(t,e,Object);if(n!==void 0||e.length===1){n[o]=r;return}let i=e[e.length-1],s=e.slice(0,e.length-1),a=jt(t,s,Object);for(;a.obj===void 0&&s.length;)i=`${s[s.length-1]}.${i}`,s=s.slice(0,s.length-1),a=jt(t,s,Object),a?.obj&&typeof a.obj[`${a.k}.${i}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${i}`]=r},Oa=(t,e,r,n)=>{const{obj:o,k:i}=jt(t,e,Object);o[i]=o[i]||[],o[i].push(r)},cr=(t,e)=>{const{obj:r,k:n}=jt(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},Ta=(t,e,r)=>{const n=cr(t,r);return n!==void 0?n:cr(e,r)},jo=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(n in t?V(t[n])||t[n]instanceof String||V(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):jo(t[n],e[n],r):t[n]=e[n]);return t},et=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Pa={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const La=t=>V(t)?t.replace(/[&<>"'\/]/g,e=>Pa[e]):t;class Da{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const r=this.regExpMap.get(e);if(r!==void 0)return r;const n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}}const Ca=[" ",",","?","!",";"],ka=new Da(20),Ua=(t,e,r)=>{e=e||"",r=r||"";const n=Ca.filter(s=>e.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=ka.getRegExp(`(${n.map(s=>s==="?"?"\\?":s).join("|")})`);let i=!o.test(t);if(!i){const s=t.indexOf(r);s>0&&!o.test(t.substring(0,s))&&(i=!0)}return i},Zr=(t,e,r=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const n=e.split(r);let o=t;for(let i=0;i<n.length;){if(!o||typeof o!="object")return;let s,a="";for(let u=i;u<n.length;++u)if(u!==i&&(a+=r),a+=n[u],s=o[a],s!==void 0){if(["string","number","boolean"].indexOf(typeof s)>-1&&u<n.length-1)continue;i+=u-i+1;break}o=s}return o},xt=t=>t?.replace(/_/g,"-"),Ma={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class Wr{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||Ma,this.options=r,this.debug=r.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,r,n,o){return o&&!this.debug?null:(V(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new Wr(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Wr(this.logger,e)}}var Ue=new Wr;class ur{constructor(){this.observers={}}on(e,r){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const o=this.observers[n].get(r)||0;this.observers[n].set(r,o+1)}),this}off(e,r){if(this.observers[e]){if(!r){delete this.observers[e];return}this.observers[e].delete(r)}}emit(e,...r){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([o,i])=>{for(let s=0;s<i;s++)o(...r)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([o,i])=>{for(let s=0;s<i;s++)o.apply(o,[e,...r])})}}class xo extends ur{constructor(e,r={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const r=this.options.ns.indexOf(e);r>-1&&this.options.ns.splice(r,1)}getResource(e,r,n,o={}){const i=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,s=o.ignoreJSONStructure!==void 0?o.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.indexOf(".")>-1?a=e.split("."):(a=[e,r],n&&(Array.isArray(n)?a.push(...n):V(n)&&i?a.push(...n.split(i)):a.push(n)));const u=cr(this.data,a);return!u&&!r&&!n&&e.indexOf(".")>-1&&(e=a[0],r=a[1],n=a.slice(2).join(".")),u||!s||!V(n)?u:Zr(this.data?.[e]?.[r],n,i)}addResource(e,r,n,o,i={silent:!1}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let a=[e,r];n&&(a=a.concat(s?n.split(s):n)),e.indexOf(".")>-1&&(a=e.split("."),o=r,r=a[1]),this.addNamespaces(r),qo(this.data,a,o),i.silent||this.emit("added",e,r,n,o)}addResources(e,r,n,o={silent:!1}){for(const i in n)(V(n[i])||Array.isArray(n[i]))&&this.addResource(e,r,i,n[i],{silent:!0});o.silent||this.emit("added",e,r,n)}addResourceBundle(e,r,n,o,i,s={silent:!1,skipCopy:!1}){let a=[e,r];e.indexOf(".")>-1&&(a=e.split("."),o=n,n=r,r=a[1]),this.addNamespaces(r);let u=cr(this.data,a)||{};s.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?jo(u,n,i):u={...u,...n},qo(this.data,a,u),s.silent||this.emit("added",e,r,n)}removeResourceBundle(e,r){this.hasResourceBundle(e,r)&&delete this.data[e][r],this.removeNamespaces(r),this.emit("removed",e,r)}hasResourceBundle(e,r){return this.getResource(e,r)!==void 0}getResourceBundle(e,r){return r||(r=this.options.defaultNS),this.getResource(e,r)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const r=this.getDataByLanguage(e);return!!(r&&Object.keys(r)||[]).find(o=>r[o]&&Object.keys(r[o]).length>0)}toJSON(){return this.data}}var Bo={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,r,n,o){return t.forEach(i=>{e=this.processors[i]?.process(e,r,n,o)??e}),e}};const Vo=Symbol("i18next/PATH_KEY");function qa(){const t=[],e=Object.create(null);let r;return e.get=(n,o)=>(r?.revoke?.(),o===Vo?t:(t.push(o),r=Proxy.revocable(n,e),r.proxy)),Proxy.revocable(Object.create(null),e).proxy}function yt(t,e){const{[Vo]:r}=t(qa()),n=e?.keySeparator??".",o=e?.nsSeparator??":";if(r.length>1&&o){const i=e?.ns,s=Array.isArray(i)?i:null;if(s&&s.length>1&&s.slice(1).includes(r[0]))return`${r[0]}${o}${r.slice(1).join(n)}`}return r.join(n)}const vo={},en=t=>!V(t)&&typeof t!="boolean"&&typeof t!="number";class zr extends ur{constructor(e,r={}){super(),Ra(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Ue.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,r={interpolation:{}}){const n={...r};if(e==null)return!1;const o=this.resolve(e,n);if(o?.res===void 0)return!1;const i=en(o.res);return!(n.returnObjects===!1&&i)}extractFromKey(e,r){let n=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");const o=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator;let i=r.ns||this.options.defaultNS||[];const s=n&&e.indexOf(n)>-1,a=!this.options.userDefinedKeySeparator&&!r.keySeparator&&!this.options.userDefinedNsSeparator&&!r.nsSeparator&&!Ua(e,n,o);if(s&&!a){const u=e.match(this.interpolator.nestingRegexp);if(u&&u.length>0)return{key:e,namespaces:V(i)?[i]:i};const c=e.split(n);(n!==o||n===o&&this.options.ns.indexOf(c[0])>-1)&&(i=c.shift()),e=c.join(o)}return{key:e,namespaces:V(i)?[i]:i}}translate(e,r,n){let o=typeof r=="object"?{...r}:r;if(typeof o!="object"&&this.options.overloadTranslationOptionHandler&&(o=this.options.overloadTranslationOptionHandler(arguments)),typeof o=="object"&&(o={...o}),o||(o={}),e==null)return"";typeof e=="function"&&(e=yt(e,{...this.options,...o})),Array.isArray(e)||(e=[String(e)]),e=e.map(k=>typeof k=="function"?yt(k,{...this.options,...o}):String(k));const i=o.returnDetails!==void 0?o.returnDetails:this.options.returnDetails,s=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,{key:a,namespaces:u}=this.extractFromKey(e[e.length-1],o),c=u[u.length-1];let p=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;p===void 0&&(p=":");const l=o.lng||this.language,f=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l?.toLowerCase()==="cimode")return f?i?{res:`${c}${p}${a}`,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:`${c}${p}${a}`:i?{res:a,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:a;const m=this.resolve(e,o);let y=m?.res;const h=m?.usedKey||a,g=m?.exactUsedKey||a,$=["[object Number]","[object Function]","[object RegExp]"],w=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,E=o.count!==void 0&&!V(o.count),A=zr.hasDefaultValue(o),R=E?this.pluralResolver.getSuffix(l,o.count,o):"",O=o.ordinal&&E?this.pluralResolver.getSuffix(l,o.count,{ordinal:!1}):"",D=E&&!o.ordinal&&o.count===0,M=D&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${R}`]||o[`defaultValue${O}`]||o.defaultValue;let z=y;S&&!y&&A&&(z=M);const q=en(z),v=Object.prototype.toString.apply(z);if(S&&z&&q&&$.indexOf(v)<0&&!(V(w)&&Array.isArray(z))){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const k=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,z,{...o,ns:u}):`key '${a} (${this.language})' returned an object instead of string.`;return i?(m.res=k,m.usedParams=this.getUsedParamsDetails(o),m):k}if(s){const k=Array.isArray(z),H=k?[]:{},ae=k?g:h;for(const te in z)if(Object.prototype.hasOwnProperty.call(z,te)){const me=`${ae}${s}${te}`;A&&!y?H[te]=this.translate(me,{...o,defaultValue:en(M)?M[te]:void 0,joinArrays:!1,ns:u}):H[te]=this.translate(me,{...o,joinArrays:!1,ns:u}),H[te]===me&&(H[te]=z[te])}y=H}}else if(S&&V(w)&&Array.isArray(y))y=y.join(w),y&&(y=this.extendTranslation(y,e,o,n));else{let k=!1,H=!1;!this.isValidLookup(y)&&A&&(k=!0,y=M),this.isValidLookup(y)||(H=!0,y=a);const te=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&H?void 0:y,me=A&&M!==y&&this.options.updateMissing;if(H||k||me){if(this.logger.log(me?"updateKey":"missingKey",l,c,a,me?M:y),s){const j=this.resolve(a,{...o,keySeparator:!1});j&&j.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let C=[];const F=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&F&&F[0])for(let j=0;j<F.length;j++)C.push(F[j]);else this.options.saveMissingTo==="all"?C=this.languageUtils.toResolveHierarchy(o.lng||this.language):C.push(o.lng||this.language);const Z=(j,le,_)=>{const I=A&&_!==y?_:te;this.options.missingKeyHandler?this.options.missingKeyHandler(j,c,le,I,me,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(j,c,le,I,me,o),this.emit("missingKey",j,c,le,y)};this.options.saveMissing&&(this.options.saveMissingPlurals&&E?C.forEach(j=>{const le=this.pluralResolver.getSuffixes(j,o);D&&o[`defaultValue${this.options.pluralSeparator}zero`]&&le.indexOf(`${this.options.pluralSeparator}zero`)<0&&le.push(`${this.options.pluralSeparator}zero`),le.forEach(_=>{Z([j],a+_,o[`defaultValue${_}`]||M)})}):Z(C,a,M))}y=this.extendTranslation(y,e,o,m,n),H&&y===a&&this.options.appendNamespaceToMissingKey&&(y=`${c}${p}${a}`),(H||k)&&this.options.parseMissingKeyHandler&&(y=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${p}${a}`:a,k?y:void 0,o))}return i?(m.res=y,m.usedParams=this.getUsedParamsDetails(o),m):y}extendTranslation(e,r,n,o,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||o.usedLng,o.usedNS,o.usedKey,{resolved:o});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const u=V(e)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let c;if(u){const l=e.match(this.interpolator.nestingRegexp);c=l&&l.length}let p=n.replace&&!V(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),e=this.interpolator.interpolate(e,p,n.lng||this.language||o.usedLng,n),u){const l=e.match(this.interpolator.nestingRegexp),f=l&&l.length;c<f&&(n.nest=!1)}!n.lng&&o&&o.res&&(n.lng=this.language||o.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...l)=>i?.[0]===l[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${l[0]} in key: ${r[0]}`),null):this.translate(...l,r),n)),n.interpolation&&this.interpolator.reset()}const s=n.postProcess||this.options.postProcess,a=V(s)?[s]:s;return e!=null&&a?.length&&n.applyPostProcessor!==!1&&(e=Bo.handle(a,e,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...o,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,r={}){let n,o,i,s,a;return V(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(u=>typeof u=="function"?yt(u,{...this.options,...r}):u)),e.forEach(u=>{if(this.isValidLookup(n))return;const c=this.extractFromKey(u,r),p=c.key;o=p;let l=c.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));const f=r.count!==void 0&&!V(r.count),m=f&&!r.ordinal&&r.count===0,y=r.context!==void 0&&(V(r.context)||typeof r.context=="number")&&r.context!=="",h=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);l.forEach(g=>{this.isValidLookup(n)||(a=g,!vo[`${h[0]}-${g}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(vo[`${h[0]}-${g}`]=!0,this.logger.warn(`key "${o}" for languages "${h.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),h.forEach($=>{if(this.isValidLookup(n))return;s=$;const w=[p];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(w,p,$,g,r);else{let E;f&&(E=this.pluralResolver.getSuffix($,r.count,r));const A=`${this.options.pluralSeparator}zero`,R=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(r.ordinal&&E.indexOf(R)===0&&w.push(p+E.replace(R,this.options.pluralSeparator)),w.push(p+E),m&&w.push(p+A)),y){const O=`${p}${this.options.contextSeparator||"_"}${r.context}`;w.push(O),f&&(r.ordinal&&E.indexOf(R)===0&&w.push(O+E.replace(R,this.options.pluralSeparator)),w.push(O+E),m&&w.push(O+A))}}let S;for(;S=w.pop();)this.isValidLookup(n)||(i=S,n=this.getResource($,g,S,r))}))})}),{res:n,usedKey:o,exactUsedKey:i,usedLng:s,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,r,n,o={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,r,n,o):this.resourceStore.getResource(e,r,n,o)}getUsedParamsDetails(e={}){const r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!V(e.replace);let o=n?e.replace:e;if(n&&typeof e.count<"u"&&(o.count=e.count),this.options.interpolation.defaultVariables&&(o={...this.options.interpolation.defaultVariables,...o}),!n){o={...o};for(const i of r)delete o[i]}return o}static hasDefaultValue(e){const r="defaultValue";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&r===n.substring(0,r.length)&&e[n]!==void 0)return!0;return!1}}class Fo{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Ue.create("languageUtils")}getScriptPartFromCode(e){if(e=xt(e),!e||e.indexOf("-")<0)return null;const r=e.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}getLanguagePartFromCode(e){if(e=xt(e),!e||e.indexOf("-")<0)return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(V(e)&&e.indexOf("-")>-1){let r;try{r=Intl.getCanonicalLocales(e)[0]}catch{}return r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let r;return e.forEach(n=>{if(r)return;const o=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(o))&&(r=o)}),!r&&this.options.supportedLngs&&e.forEach(n=>{if(r)return;const o=this.getScriptPartFromCode(n);if(this.isSupportedCode(o))return r=o;const i=this.getLanguagePartFromCode(n);if(this.isSupportedCode(i))return r=i;r=this.options.supportedLngs.find(s=>{if(s===i)return s;if(!(s.indexOf("-")<0&&i.indexOf("-")<0)&&(s.indexOf("-")>0&&i.indexOf("-")<0&&s.substring(0,s.indexOf("-"))===i||s.indexOf(i)===0&&i.length>1))return s})}),r||(r=this.getFallbackCodes(this.options.fallbackLng)[0]),r}getFallbackCodes(e,r){if(!e)return[];if(typeof e=="function"&&(e=e(r)),V(e)&&(e=[e]),Array.isArray(e))return e;if(!r)return e.default||[];let n=e[r];return n||(n=e[this.getScriptPartFromCode(r)]),n||(n=e[this.formatLanguageCode(r)]),n||(n=e[this.getLanguagePartFromCode(r)]),n||(n=e.default),n||[]}toResolveHierarchy(e,r){const n=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],e),o=[],i=s=>{s&&(this.isSupportedCode(s)?o.push(s):this.logger.warn(`rejecting language code not found in supportedLngs: ${s}`))};return V(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&i(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&i(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&i(this.getLanguagePartFromCode(e))):V(e)&&i(this.formatLanguageCode(e)),n.forEach(s=>{o.indexOf(s)<0&&i(this.formatLanguageCode(s))}),o}}const Yo={zero:0,one:1,two:2,few:3,many:4,other:5},Ho={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class ja{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=Ue.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=xt(e==="dev"?"en":e),o=r.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:n,type:o});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let s;try{s=new Intl.PluralRules(n,{type:o})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Ho;if(!e.match(/-|_/))return Ho;const u=this.languageUtils.getLanguagePartFromCode(e);s=this.getRule(u,r)}return this.pluralRulesCache[i]=s,s}needsPlural(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,r,n={}){return this.getSuffixes(e,n).map(o=>`${r}${o}`)}getSuffixes(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?n.resolvedOptions().pluralCategories.sort((o,i)=>Yo[o]-Yo[i]).map(o=>`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${o}`):[]}getSuffix(e,r,n={}){const o=this.getRule(e,n);return o?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${o.select(r)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",r,n))}}const Qo=(t,e,r,n=".",o=!0)=>{let i=Ta(t,e,r);return!i&&o&&V(r)&&(i=Zr(t,r,n),i===void 0&&(i=Zr(e,r,n))),i},tn=t=>t.replace(/\$/g,"$$$$");class Go{constructor(e={}){this.logger=Ue.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(r=>r),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:r,escapeValue:n,useRawValueToEscape:o,prefix:i,prefixEscaped:s,suffix:a,suffixEscaped:u,formatSeparator:c,unescapeSuffix:p,unescapePrefix:l,nestingPrefix:f,nestingPrefixEscaped:m,nestingSuffix:y,nestingSuffixEscaped:h,nestingOptionsSeparator:g,maxReplaces:$,alwaysFormat:w}=e.interpolation;this.escape=r!==void 0?r:La,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=i?et(i):s||"{{",this.suffix=a?et(a):u||"}}",this.formatSeparator=c||",",this.unescapePrefix=p?"":l||"-",this.unescapeSuffix=this.unescapePrefix?"":p||"",this.nestingPrefix=f?et(f):m||et("$t("),this.nestingSuffix=y?et(y):h||et(")"),this.nestingOptionsSeparator=g||",",this.maxReplaces=$||1e3,this.alwaysFormat=w!==void 0?w:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(r,n)=>r?.source===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,r,n,o){let i,s,a;const u=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=m=>{if(m.indexOf(this.formatSeparator)<0){const $=Qo(r,u,m,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format($,void 0,n,{...o,...r,interpolationkey:m}):$}const y=m.split(this.formatSeparator),h=y.shift().trim(),g=y.join(this.formatSeparator).trim();return this.format(Qo(r,u,h,this.options.keySeparator,this.options.ignoreJSONStructure),g,n,{...o,...r,interpolationkey:h})};this.resetRegExp();const p=o?.missingInterpolationHandler||this.options.missingInterpolationHandler,l=o?.interpolation?.skipOnVariables!==void 0?o.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:m=>tn(m)},{regex:this.regexp,safeValue:m=>this.escapeValue?tn(this.escape(m)):tn(m)}].forEach(m=>{for(a=0;i=m.regex.exec(e);){const y=i[1].trim();if(s=c(y),s===void 0)if(typeof p=="function"){const g=p(e,i,o);s=V(g)?g:""}else if(o&&Object.prototype.hasOwnProperty.call(o,y))s="";else if(l){s=i[0];continue}else this.logger.warn(`missed to pass in variable ${y} for interpolating ${e}`),s="";else!V(s)&&!this.useRawValueToEscape&&(s=ko(s));const h=m.safeValue(s);if(e=e.replace(i[0],h),l?(m.regex.lastIndex+=s.length,m.regex.lastIndex-=i[0].length):m.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,r,n={}){let o,i,s;const a=(u,c)=>{const p=this.nestingOptionsSeparator;if(u.indexOf(p)<0)return u;const l=u.split(new RegExp(`${et(p)}[ ]*{`));let f=`{${l[1]}`;u=l[0],f=this.interpolate(f,s);const m=f.match(/'/g),y=f.match(/"/g);((m?.length??0)%2===0&&!y||(y?.length??0)%2!==0)&&(f=f.replace(/'/g,'"'));try{s=JSON.parse(f),c&&(s={...c,...s})}catch(h){return this.logger.warn(`failed parsing options string in nesting for key ${u}`,h),`${u}${p}${f}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,u};for(;o=this.nestingRegexp.exec(e);){let u=[];s={...n},s=s.replace&&!V(s.replace)?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;const c=/{.*}/.test(o[1])?o[1].lastIndexOf("}")+1:o[1].indexOf(this.formatSeparator);if(c!==-1&&(u=o[1].slice(c).split(this.formatSeparator).map(p=>p.trim()).filter(Boolean),o[1]=o[1].slice(0,c)),i=r(a.call(this,o[1].trim(),s),s),i&&o[0]===e&&!V(i))return i;V(i)||(i=ko(i)),i||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${e}`),i=""),u.length&&(i=u.reduce((p,l)=>this.format(p,l,n.lng,{...n,interpolationkey:o[1].trim()}),i.trim())),e=e.replace(o[0],i),this.regexp.lastIndex=0}return e}}const xa=t=>{let e=t.toLowerCase().trim();const r={};if(t.indexOf("(")>-1){const n=t.split("(");e=n[0].toLowerCase().trim();const o=n[1].substring(0,n[1].length-1);e==="currency"&&o.indexOf(":")<0?r.currency||(r.currency=o.trim()):e==="relativetime"&&o.indexOf(":")<0?r.range||(r.range=o.trim()):o.split(";").forEach(s=>{if(s){const[a,...u]=s.split(":"),c=u.join(":").trim().replace(/^'+|'+$/g,""),p=a.trim();r[p]||(r[p]=c),c==="false"&&(r[p]=!1),c==="true"&&(r[p]=!0),isNaN(c)||(r[p]=parseInt(c,10))}})}return{formatName:e,formatOptions:r}},Wo=t=>{const e={};return(r,n,o)=>{let i=o;o&&o.interpolationkey&&o.formatParams&&o.formatParams[o.interpolationkey]&&o[o.interpolationkey]&&(i={...i,[o.interpolationkey]:void 0});const s=n+JSON.stringify(i);let a=e[s];return a||(a=t(xt(n),o),e[s]=a),a(r)}},Ba=t=>(e,r,n)=>t(xt(r),n)(e);class Va{constructor(e={}){this.logger=Ue.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?Wo:Ba;this.formats={number:n((o,i)=>{const s=new Intl.NumberFormat(o,{...i});return a=>s.format(a)}),currency:n((o,i)=>{const s=new Intl.NumberFormat(o,{...i,style:"currency"});return a=>s.format(a)}),datetime:n((o,i)=>{const s=new Intl.DateTimeFormat(o,{...i});return a=>s.format(a)}),relativetime:n((o,i)=>{const s=new Intl.RelativeTimeFormat(o,{...i});return a=>s.format(a,i.range||"day")}),list:n((o,i)=>{const s=new Intl.ListFormat(o,{...i});return a=>s.format(a)})}}add(e,r){this.formats[e.toLowerCase().trim()]=r}addCached(e,r){this.formats[e.toLowerCase().trim()]=Wo(r)}format(e,r,n,o={}){const i=r.split(this.formatSeparator);if(i.length>1&&i[0].indexOf("(")>1&&i[0].indexOf(")")<0&&i.find(a=>a.indexOf(")")>-1)){const a=i.findIndex(u=>u.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,a)].join(this.formatSeparator)}return i.reduce((a,u)=>{const{formatName:c,formatOptions:p}=xa(u);if(this.formats[c]){let l=a;try{const f=o?.formatParams?.[o.interpolationkey]||{},m=f.locale||f.lng||o.locale||o.lng||n;l=this.formats[c](a,m,{...p,...o,...f})}catch(f){this.logger.warn(f)}return l}else this.logger.warn(`there was no format function for ${c}`);return a},e)}}const va=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Fa extends ur{constructor(e,r,n,o={}){super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=Ue.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=o.maxParallelReads||10,this.readingCalls=0,this.maxRetries=o.maxRetries>=0?o.maxRetries:5,this.retryTimeout=o.retryTimeout>=1?o.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,o.backend,o)}queueLoad(e,r,n,o){const i={},s={},a={},u={};return e.forEach(c=>{let p=!0;r.forEach(l=>{const f=`${c}|${l}`;!n.reload&&this.store.hasResourceBundle(c,l)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?s[f]===void 0&&(s[f]=!0):(this.state[f]=1,p=!1,s[f]===void 0&&(s[f]=!0),i[f]===void 0&&(i[f]=!0),u[l]===void 0&&(u[l]=!0)))}),p||(a[c]=!0)}),(Object.keys(i).length||Object.keys(s).length)&&this.queue.push({pending:s,pendingCount:Object.keys(s).length,loaded:{},errors:[],callback:o}),{toLoad:Object.keys(i),pending:Object.keys(s),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(u)}}loaded(e,r,n){const o=e.split("|"),i=o[0],s=o[1];r&&this.emit("failedLoading",i,s,r),!r&&n&&this.store.addResourceBundle(i,s,n,void 0,void 0,{skipCopy:!0}),this.state[e]=r?-1:2,r&&n&&(this.state[e]=0);const a={};this.queue.forEach(u=>{Oa(u.loaded,[i],s),va(u,e),r&&u.errors.push(r),u.pendingCount===0&&!u.done&&(Object.keys(u.loaded).forEach(c=>{a[c]||(a[c]={});const p=u.loaded[c];p.length&&p.forEach(l=>{a[c][l]===void 0&&(a[c][l]=!0)})}),u.done=!0,u.errors.length?u.callback(u.errors):u.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(u=>!u.done)}read(e,r,n,o=0,i=this.retryTimeout,s){if(!e.length)return s(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:r,fcName:n,tried:o,wait:i,callback:s});return}this.readingCalls++;const a=(c,p)=>{if(this.readingCalls--,this.waitingReads.length>0){const l=this.waitingReads.shift();this.read(l.lng,l.ns,l.fcName,l.tried,l.wait,l.callback)}if(c&&p&&o<this.maxRetries){setTimeout(()=>{this.read.call(this,e,r,n,o+1,i*2,s)},i);return}s(c,p)},u=this.backend[n].bind(this.backend);if(u.length===2){try{const c=u(e,r);c&&typeof c.then=="function"?c.then(p=>a(null,p)).catch(a):a(null,c)}catch(c){a(c)}return}return u(e,r,a)}prepareLoading(e,r,n={},o){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),o&&o();V(e)&&(e=this.languageUtils.toResolveHierarchy(e)),V(r)&&(r=[r]);const i=this.queueLoad(e,r,n,o);if(!i.toLoad.length)return i.pending.length||o(),null;i.toLoad.forEach(s=>{this.loadOne(s)})}load(e,r,n){this.prepareLoading(e,r,{},n)}reload(e,r,n){this.prepareLoading(e,r,{reload:!0},n)}loadOne(e,r=""){const n=e.split("|"),o=n[0],i=n[1];this.read(o,i,"read",void 0,void 0,(s,a)=>{s&&this.logger.warn(`${r}loading namespace ${i} for language ${o} failed`,s),!s&&a&&this.logger.log(`${r}loaded namespace ${i} for language ${o}`,a),this.loaded(e,s,a)})}saveMissing(e,r,n,o,i,s={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(r)){this.logger.warn(`did not save key "${n}" as the namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if(this.backend?.create){const u={...s,isUpdate:i},c=this.backend.create.bind(this.backend);if(c.length<6)try{let p;c.length===5?p=c(e,r,n,o,u):p=c(e,r,n,o),p&&typeof p.then=="function"?p.then(l=>a(null,l)).catch(a):a(null,p)}catch(p){a(p)}else c(e,r,n,o,a,u)}!e||!e[0]||this.store.addResource(e[0],r,n,o)}}}const rn=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),V(t[1])&&(e.defaultValue=t[1]),V(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const r=t[3]||t[2];Object.keys(r).forEach(n=>{e[n]=r[n]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),zo=t=>(V(t.ns)&&(t.ns=[t.ns]),V(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),V(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs?.indexOf?.("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),typeof t.initImmediate=="boolean"&&(t.initAsync=t.initImmediate),t),dr=()=>{},Ya=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})},Ko="__i18next_supportNoticeShown",Ha=()=>!!(typeof globalThis<"u"&&globalThis[Ko]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),Qa=()=>{typeof globalThis<"u"&&(globalThis[Ko]=!0)},Ga=t=>!!(t?.modules?.backend?.name?.indexOf("Locize")>0||t?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||t?.options?.backend?.backends&&t.options.backend.backends.some(e=>e?.name?.indexOf("Locize")>0||e?.constructor?.name?.indexOf("Locize")>0)||t?.options?.backend?.projectId||t?.options?.backend?.backendOptions&&t.options.backend.backendOptions.some(e=>e?.projectId));class sr extends ur{constructor(e={},r){if(super(),this.options=zo(e),this.services={},this.logger=Ue,this.modules={external:[]},Ya(this),r&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,r),this;setTimeout(()=>{this.init(e,r)},0)}}init(e={},r){this.isInitializing=!0,typeof e=="function"&&(r=e,e={}),e.defaultNS==null&&e.ns&&(V(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const n=rn();this.options={...n,...this.options,...zo(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!Ga(this)&&!Ha()&&(typeof console<"u"&&typeof console.info<"u"&&console.info("\u{1F310} i18next is made possible by our own product, Locize \u2014 consider powering your project with managed localization (AI, CDN, integrations): https://locize.com \u{1F499}"),Qa());const o=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?Ue.init(o(this.modules.logger),this.options):Ue.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=Va;const p=new Fo(this.options);this.store=new xo(this.options.resources,this.options);const l=this.services;l.logger=Ue,l.resourceStore=this.store,l.languageUtils=p,l.pluralResolver=new ja(p,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),c&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(l.formatter=o(c),l.formatter.init&&l.formatter.init(l,this.options),this.options.interpolation.format=l.formatter.format.bind(l.formatter)),l.interpolator=new Go(this.options),l.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},l.backendConnector=new Fa(o(this.modules.backend),l.resourceStore,l,this.options),l.backendConnector.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.languageDetector&&(l.languageDetector=o(this.modules.languageDetector),l.languageDetector.init&&l.languageDetector.init(l,this.options.detection,this.options)),this.modules.i18nFormat&&(l.i18nFormat=o(this.modules.i18nFormat),l.i18nFormat.init&&l.i18nFormat.init(this)),this.translator=new zr(this.services,this.options),this.translator.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.external.forEach(m=>{m.init&&m.init(this)})}if(this.format=this.options.interpolation.format,r||(r=dr),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...p)=>this.store[c](...p)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...p)=>(this.store[c](...p),this)});const a=qt(),u=()=>{const c=(p,l)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(l),r(p,l)};if(this.languages&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?u():setTimeout(u,0),a}loadResources(e,r=dr){let n=r;const o=V(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(o?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const i=[],s=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(c=>{c!=="cimode"&&i.indexOf(c)<0&&i.push(c)})};o?s(o):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>s(u)),this.options.preload?.forEach?.(a=>s(a)),this.services.backendConnector.load(i,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(a)})}else n(null)}reloadResources(e,r,n){const o=qt();return typeof e=="function"&&(n=e,e=void 0),typeof r=="function"&&(n=r,r=void 0),e||(e=this.languages),r||(r=this.options.ns),n||(n=dr),this.services.backendConnector.reload(e,r,i=>{o.resolve(),n(i)}),o}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&Bo.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-1)){for(let r=0;r<this.languages.length;r++){const n=this.languages[r];if(!(["cimode","dev"].indexOf(n)>-1)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,r){this.isLanguageChangingTo=e;const n=qt();this.emit("languageChanging",e);const o=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},i=(a,u)=>{u?this.isLanguageChangingTo===e&&(o(u),this.translator.changeLanguage(u),this.isLanguageChangingTo=void 0,this.emit("languageChanged",u),this.logger.log("languageChanged",u)):this.isLanguageChangingTo=void 0,n.resolve((...c)=>this.t(...c)),r&&r(a,(...c)=>this.t(...c))},s=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const u=V(a)?a:a&&a[0],c=this.store.hasLanguageSomeTranslations(u)?u:this.services.languageUtils.getBestMatchFromCodes(V(a)?[a]:a);c&&(this.language||o(c),this.translator.language||this.translator.changeLanguage(c),this.services.languageDetector?.cacheUserLanguage?.(c)),this.loadResources(c,p=>{i(p,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?s(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(s):this.services.languageDetector.detect(s):s(e),n}getFixedT(e,r,n){const o=(i,s,...a)=>{let u;typeof s!="object"?u=this.options.overloadTranslationOptionHandler([i,s].concat(a)):u={...s},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs,u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||n||o.keyPrefix);const c={...this.options,...u};typeof u.keyPrefix=="function"&&(u.keyPrefix=yt(u.keyPrefix,c));const p=this.options.keySeparator||".";let l;return u.keyPrefix&&Array.isArray(i)?l=i.map(f=>(typeof f=="function"&&(f=yt(f,c)),`${u.keyPrefix}${p}${f}`)):(typeof i=="function"&&(i=yt(i,c)),l=u.keyPrefix?`${u.keyPrefix}${p}${i}`:i),this.t(l,u)};return V(e)?o.lng=e:o.lngs=e,o.ns=r,o.keyPrefix=n,o}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,r={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=r.lng||this.resolvedLanguage||this.languages[0],o=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const s=(a,u)=>{const c=this.services.backendConnector.state[`${a}|${u}`];return c===-1||c===0||c===2};if(r.precheck){const a=r.precheck(this,s);if(a!==void 0)return a}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||s(n,e)&&(!o||s(i,e)))}loadNamespaces(e,r){const n=qt();return this.options.ns?(V(e)&&(e=[e]),e.forEach(o=>{this.options.ns.indexOf(o)<0&&this.options.ns.push(o)}),this.loadResources(o=>{n.resolve(),r&&r(o)}),n):(r&&r(),Promise.resolve())}loadLanguages(e,r){const n=qt();V(e)&&(e=[e]);const o=this.options.preload||[],i=e.filter(s=>o.indexOf(s)<0&&this.services.languageUtils.isSupportedCode(s));return i.length?(this.options.preload=o.concat(i),this.loadResources(s=>{n.resolve(),r&&r(s)}),n):(r&&r(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const o=new Intl.Locale(e);if(o&&o.getTextInfo){const i=o.getTextInfo();if(i&&i.direction)return i.direction}}catch{}const r=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=this.services?.languageUtils||new Fo(rn());return e.toLowerCase().indexOf("-latn")>1?"ltr":r.indexOf(n.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},r){const n=new sr(e,r);return n.createInstance=sr.createInstance,n}cloneInstance(e={},r=dr){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const o={...this.options,...e,isClone:!0},i=new sr(o);if((e.debug!==void 0||e.prefix!==void 0)&&(i.logger=i.logger.clone(e)),["store","services","language"].forEach(a=>{i[a]=this[a]}),i.services={...this.services},i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},n){const a=Object.keys(this.store.data).reduce((u,c)=>(u[c]={...this.store.data[c]},u[c]=Object.keys(u[c]).reduce((p,l)=>(p[l]={...u[c][l]},p),u[c]),u),{});i.store=new xo(a,o),i.services.resourceStore=i.store}if(e.interpolation){const u={...rn().interpolation,...this.options.interpolation,...e.interpolation},c={...o,interpolation:u};i.services.interpolator=new Go(c)}return i.translator=new zr(i.services,o),i.translator.on("*",(a,...u)=>{i.emit(a,...u)}),i.init(o,r),i.translator.options=o,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Se=sr.createInstance(),Wa=Se.createInstance;Se.dir,Se.init,Se.loadResources,Se.reloadResources,Se.use,Se.changeLanguage,Se.getFixedT,Se.t,Se.exists,Se.setDefaultNamespace,Se.hasLoadedNamespace,Se.loadNamespaces,Se.loadLanguages;const Jo={locale:"en-US",messages:{"operator.rows":"rows","operator.$sum":"Total {operandName}","operator.$avg":"Average {operandName}","operator.$min":"Minimum {operandName}","operator.$max":"Maximum {operandName}","operator.$count":"{operandName} count","operator.$count.rows":"Row count","operator.$countDistinct":"Distinct {operandName} count","operator.$add":"{inputNames}","operator.$add.empty":"Sum of {operandName}","operator.$subtract":"{input0} minus {input1}","operator.$subtract.fallback":"{operandName} difference","operator.$multiply":"{inputNames}","operator.$multiply.empty":"Product of {operandName}","operator.$divide":"{input0} divided by {input1}","operator.$divide.fallback":"{operandName} ratio","operator.$concat":"Combined {inputNames}","operator.$concat.empty":"Combined {operandName}","operator.$abs":"Absolute {operandName}","operator.$substring":"{operandName} substring","operator.$case":"{operandName} category","operator.$constant":"Constant","operator.$sql":"Calculated value","operator.$rowNumber":"Row number","operator.$rank":"{operandName} rank","operator.$accumulate":"Cumulative {operandName}","operator.$least":"Least of {inputNames}","operator.$greatest":"Greatest of {inputNames}","operator.$dateBucket":"{operandName} by {granularity}","operator.$periodBoundary.start":"{operandName} at period start","operator.$periodBoundary.end":"{operandName} at period end","operator.$periodValue.start":"{operandName} at period start","operator.$periodValue.end":"{operandName} at period end","operator.$periodShift":"{operandName} {comparison} baseline","operator.$periodGrowth":"{operandName} {comparison} growth","operator.$periodDifference":"{operandName} {comparison} difference","operator.$averagePerPeriod":"Average {operandName} per {granularity}","operator.$newly":"New {operandName}","operator.$shareOfTotal":"{operandName} share of total","component.numerator":"{outputName} numerator","component.denominator":"{outputName} denominator","component.current":"{outputName} current","component.previous":"{outputName} previous","component.start":"{outputName} start","component.end":"{outputName} end","period.comparison":"period-over-period","period.current":"current-period","period.yearOverYear":"year-over-year","period.monthOverMonth":"month-over-month","period.weekOverWeek":"week-over-week","time.granularity.second":"second","time.granularity.minute":"minute","time.granularity.hour":"hour","time.granularity.day":"day","time.granularity.week":"week","time.granularity.month":"month","time.granularity.quarter":"quarter","time.granularity.year":"year","time.granularity.period":"period","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal requires a property","sql.timeWatermark":"Resolve time watermark to keep year-over-year and period-over-period comparison ranges consistent","sql.autoCase":"Resolve automatic bucket boundaries","sql.entityExpansion":"Expand entities to obtain more information","sql.computation":"Numeric computation","sql.total":"Count result rows before pagination","sql.semanticResolution":"Semantic resolution"}},Xo={locale:"zh-CN",messages:{"operator.rows":"\u6570\u636E\u884C","operator.$sum":"\u603B{operandName}","operator.$avg":"\u5E73\u5747{operandName}","operator.$min":"{operandName}\u6700\u5C0F\u503C","operator.$max":"{operandName}\u6700\u5927\u503C","operator.$count":"{operandName}\u6570\u91CF","operator.$count.rows":"\u884C\u6570","operator.$countDistinct":"{operandName}\u53BB\u91CD\u8BA1\u6570","operator.$add":"{inputNames}","operator.$add.empty":"{operandName}\u6C42\u548C","operator.$subtract":"{input0}\u51CF\u53BB{input1}","operator.$subtract.fallback":"{operandName}\u5DEE\u503C","operator.$multiply":"{inputNames}","operator.$multiply.empty":"{operandName}\u4E58\u79EF","operator.$divide":"{input0}\u9664\u4EE5{input1}","operator.$divide.fallback":"{operandName}\u6BD4\u503C","operator.$concat":"{inputNames}\u62FC\u63A5\u503C","operator.$concat.empty":"{operandName}\u62FC\u63A5\u503C","operator.$abs":"{operandName}\u7EDD\u5BF9\u503C","operator.$substring":"{operandName}\u5B50\u4E32","operator.$case":"{operandName}\u5206\u7C7B","operator.$constant":"\u5E38\u91CF","operator.$sql":"\u8BA1\u7B97\u503C","operator.$rowNumber":"\u884C\u53F7","operator.$rank":"{operandName}\u6392\u540D","operator.$accumulate":"{operandName}\u7D2F\u8BA1\u503C","operator.$least":"{inputNames}\u4E2D\u7684\u6700\u65E9\u503C","operator.$greatest":"{inputNames}\u4E2D\u7684\u6700\u665A\u503C","operator.$dateBucket":"{operandName}\uFF08\u6309{granularity}\uFF09","operator.$periodBoundary.start":"{operandName}\u671F\u521D","operator.$periodBoundary.end":"{operandName}\u671F\u672B","operator.$periodValue.start":"{operandName}\u671F\u521D\u503C","operator.$periodValue.end":"{operandName}\u671F\u672B\u503C","operator.$periodShift":"{operandName}{comparison}\u57FA\u671F\u503C","operator.$periodGrowth":"{operandName}{comparison}\u589E\u957F\u7387","operator.$periodDifference":"{operandName}{comparison}\u5DEE\u503C","operator.$averagePerPeriod":"{operandName}{granularity}\u5747\u503C","operator.$newly":"\u65B0\u589E{operandName}","operator.$shareOfTotal":"{operandName}\u5360\u6BD4","component.numerator":"{outputName}\u5206\u5B50","component.denominator":"{outputName}\u5206\u6BCD","component.current":"{outputName}\u672C\u671F","component.previous":"{outputName}\u4E0A\u671F","component.start":"{outputName}\u5F00\u59CB","component.end":"{outputName}\u7ED3\u675F","period.comparison":"\u540C\u671F","period.current":"\u672C\u671F","period.yearOverYear":"\u540C\u6BD4","period.monthOverMonth":"\u73AF\u6BD4","period.weekOverWeek":"\u5468\u73AF\u6BD4","time.granularity.second":"\u79D2","time.granularity.minute":"\u5206\u949F","time.granularity.hour":"\u5C0F\u65F6","time.granularity.day":"\u65E5","time.granularity.week":"\u5468","time.granularity.month":"\u6708","time.granularity.quarter":"\u5B63\u5EA6","time.granularity.year":"\u5E74","time.granularity.period":"\u5468\u671F","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal\u9700\u8981pred\u53C2\u6570","sql.timeWatermark":"\u8BA1\u7B97\u6570\u636E\u6700\u540E\u65F6\u95F4\uFF0C\u4ECE\u800C\u4FDD\u8BC1\u540C\u6BD4\u3001\u73AF\u6BD4\u7684\u6BD4\u8F83\u533A\u95F4\u4E00\u81F4","sql.autoCase":"\u8BA1\u7B97\u81EA\u52A8\u5206\u6BB5\u8FB9\u754C","sql.entityExpansion":"\u5B9E\u4F53\u5C55\u5F00\uFF0C\u7528\u4E8E\u83B7\u5F97\u66F4\u591A\u4FE1\u606F","sql.computation":"\u6570\u503C\u8BA1\u7B97","sql.total":"\u8BA1\u7B97\u5206\u9875\u524D\u7684\u7ED3\u679C\u603B\u6570","sql.semanticResolution":"\u8BED\u4E49\u89E3\u6790"}},za=[Xo,Jo],Bt=t=>t.trim().toLowerCase(),Ka=t=>t?"locale"in t?[t]:t:[],Ja=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=t;return typeof e.locale=="string"&&e.locale.trim().length>0&&typeof e.messages=="object"&&e.messages!==null&&!Array.isArray(e.messages)};class nn{definitions=new Map;i18n;constructor(e){this.i18n=Wa(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(za),this.register(e)}register(e){for(const r of Ka(e)){const n=r;if(!Ja(n))throw new TypeError("Locale definition must have a non-empty locale");const o=n,i=this.definitions.get(Bt(o.locale)),s={locale:o.locale,messages:Object.freeze({...i?.messages,...o.messages})};this.definitions.set(Bt(o.locale),s),this.i18n.addResourceBundle(o.locale,"translation",s.messages,!0,!0)}return this}resolve(e="zh-CN"){const r=this.definitions.get(Bt(e));if(r)return r;const n=Bt(e).split("-")[0];return[...this.definitions.entries()].find(([i])=>i.split("-")[0]===n)?.[1]??this.definitions.get("zh-cn")}has(e){return this.definitions.has(Bt(e))}translate(e,r,n,o){const i=this.resolve(e);return this.i18n.t(r,{lng:i.locale,defaultValue:n??r,...o??{}})}translator(e="zh-CN"){return(r,n,o)=>this.translate(e,r,n,o)}}const lr=t=>new nn(t),pr=new nn;class d extends Error{code;details;constructor(e,r,n){super(r),this.code=e,this.details=n,this.name="SemanticDBError"}localizedMessage(e="zh-CN",r=pr){if(this.code==="PRED_PROPERTY_REQUIRED"&&this.message==="$shareOfTotal requires a property")return r.translate(e,"error.PRED_PROPERTY_REQUIRED.$shareOfTotal",this.message,this.details);if(this.code==="PROPERTY_NOT_FOUND"&&e.toLowerCase().startsWith("en")){const n=this.details?.schemaId,o=this.details?.schemaName,i=this.details?.property,s=this.details?.propertyName;if(typeof n=="string"&&typeof o=="string"&&typeof i=="string"&&typeof s=="string")return`Property not found in Schema: ${o}(${n}): ${s}`}return this.message}}ue.extend(Mt),ue.extend(ar);const Xa=new Set(["year","quarter","month","week"]),on=t=>t.format("YYYY-MM-DD HH:mm:ss"),sn=(t,e)=>t.operator&&e(t.operator).kind==="aggregate"?!0:(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?sn(t.pred,e):!1)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&sn(r,e)),fr=(t,e,r)=>{if(t.kind==="window"||t.kind==="cumulative")throw new d("ACCUMULATE_WINDOW_UNSUPPORTED","$accumulate cannot contain another window expression");if(t.kind==="ordinal-decode")return{...t,input:fr(t.input,e,r)};if(t.kind==="ordinal-encode")return{kind:"cumulative",function:"sum",input:t,...r};if(t.kind!=="operator")return{kind:"cumulative",function:"sum",input:t,...r};const n=e.getOperator(t.operator);if(n.kind==="component")throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain component operator ${t.operator}`);if(n.kind==="aggregate"){if(t.operator==="$avg"){const s={...t,operator:"$sum"},a={...t,operator:"$count"};return{kind:"operator",operator:"$divide",args:{},inputs:[{kind:"cumulative",function:"sum",input:s,...r},{kind:"cumulative",function:"sum",input:a,...r}]}}const i={$sum:"sum",$count:"sum",$min:"min",$max:"max"}[t.operator];if(!i)throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`Aggregate operator ${t.operator} does not declare cumulative semantics`);return{kind:"cumulative",function:i,input:t,...r}}if(n.kind!=="scalar")throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain ${t.operator}`);return{...t,...t.input?{input:fr(t.input,e,r)}:{},...t.inputs?{inputs:t.inputs.map(o=>fr(o,e,r))}:{}}},Za=t=>{if(!t.input||t.inputs.length>0||t.pred.query)throw new d("INVALID_ACCUMULATE_INPUT","$accumulate requires exactly one nested pred and does not accept pred.query");if(t.inputProperty?.comparable&&t.input.kind!=="ordinal-decode")throw new d("ACCUMULATE_COMPARABLE_OPERATOR_REQUIRED","$accumulate over a comparable category requires an explicit $min or $max metric");const e=t.args.partitionBy??[],r=t.args.orderBy;if(!Array.isArray(e)||e.some(o=>typeof o!="string"))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate partitionBy must be an array of groupby names");if(!Array.isArray(r)||r.length===0)throw new d("INVALID_ACCUMULATE_ARGS","$accumulate requires a non-empty args.orderBy array");const n=r.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require pred and optional direction");const{pred:i,direction:s="asc",...a}=o;if(typeof i!="string"||s!=="asc"&&s!=="desc"||Object.keys(a).length>0)throw new d("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require only a string pred and asc/desc direction");return{expression:t.resolveKey(i),direction:s==="asc"?"ASC":"DESC"}});return fr(t.input,t,{partitionBy:e.map(o=>t.resolveKey(String(o))),orderBy:n})},ec=t=>{if(t.groupByNames.length===0)return;if(typeof t.pred.pred!="object"||Array.isArray(t.pred.pred)||!sn(t.pred.pred,t.getOperator))throw new d("ACCUMULATE_AGGREGATE_REQUIRED","$accumulate over a grouped physical relation requires an aggregate expression");const e=t.pred.args?.partitionBy,r=t.pred.args?.orderBy;if(e!==void 0&&!Array.isArray(e)||!Array.isArray(r)||r.length===0||r.some(i=>typeof i!="object"||i===null||Array.isArray(i)||typeof i.pred!="string"||Object.keys(i).some(s=>s!=="pred"&&s!=="direction")||i.direction!==void 0&&i.direction!=="asc"&&i.direction!=="desc"))return;const n=[...e??[],...r.map(i=>i.pred)];if(n.some(i=>typeof i!="string"))return;const o=n.map(i=>t.resolveGroupName(String(i)));if(o.length!==t.groupByNames.length||new Set(o).size!==t.groupByNames.length||t.groupByNames.some(i=>!o.includes(i)))throw new d("INCOMPLETE_ACCUMULATE_DIMENSIONS","$accumulate partitionBy and orderBy must cover every groupby item exactly once",{expected:t.groupByNames,received:o})},tc=(t,e,r)=>{if(t.from||t.having)throw new d("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period currently requires a physical LogicForm without from or having");if((t.preds?.length??0)!==e.length)throw new d("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period cannot currently be mixed with non-period projections");const n=t.query&&Object.entries(t.query).find(([,E])=>{if(typeof E!="object"||E===null||Array.isArray(E))return!1;const A=E;return typeof A.$gte=="string"&&typeof A.$lte=="string"});if(!n)throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires one bounded date query identifying the target period");const[o,i]=n,s=i,a=ue(String(s.$gte)),u=ue(String(s.$lte));if(!a.isValid()||!u.isValid())throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","Target date range is invalid");const c=e.map(E=>{if(!E.name)throw new d("MISSING_PRED_NAME","$accumulate args.period requires normalized names");return E.name}),p=r==="week"?a.startOf("isoWeek"):a.startOf(r),l={...t.query,[o]:{...s,$gte:on(p)}},f=new Set([...(t.groupby??[]).map(({name:E})=>E),...(t.preds??[]).map(({name:E})=>E)]),m=E=>{let A=E;for(;f.has(A);)A=`_${A}`;return f.add(A),A},y=m("__accumulate_period"),h=e.map((E,A)=>m(`__accumulate_metric_${A}`)),g=(t.groupby??[]).map(({name:E})=>String(E)),$=r==="year"||r==="quarter"?"month":"day",w={version:t.version,...t.schema?{schema:t.schema}:{},query:l,groupby:[...t.groupby??[],{operator:"$dateBucket",pred:o,args:{granularity:$},name:y}],preds:e.map((E,A)=>({...E.pred,name:h[A]??`__accumulate_metric_${A}`}))},S={version:t.version,from:w,preds:[...g.map(E=>({pred:E,name:E})),{pred:y,name:y},...e.map((E,A)=>({operator:"$accumulate",pred:h[A]??`__accumulate_metric_${A}`,args:{partitionBy:g,orderBy:[{pred:y,direction:"asc"}]},name:c[A]??`accumulate_${A}`}))]};return{version:t.version,from:S,query:{[y]:{$gte:on(a),$lte:on(u)}},preds:[...g.map(E=>({pred:E,name:E})),...c.map(E=>({pred:E,name:E}))],...t.sort?{sort:t.sort}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.page!==void 0?{page:t.page}:{},...t.output?{output:t.output}:{},...t.representation?{representation:t.representation}:{}}},rc={name:"$accumulate",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Cumulative ${t}`:`${t}\u7D2F\u8BA1\u503C`,kind:"logical",normalizePred({pred:t}){const e=t.args?.period;if(e!==void 0&&(typeof e!="string"||!Xa.has(e)))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate args.period must be year, quarter, month, or week");if(e!==void 0&&(t.args?.partitionBy!==void 0||t.args?.orderBy!==void 0))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate args.period cannot be combined with partitionBy or orderBy");return t},planExpression:Za,validatePlan:ec,rewriteLogicform({logicform:t,schema:e}){const r=(t.preds??[]).filter(s=>s.operator==="$accumulate"&&s.args?.period!==void 0);if(r.length===0)return;const n=r[0]?.args?.period;if(r.some(s=>s.args?.period!==n))throw new d("ACCUMULATE_PERIOD_UNSUPPORTED","All $accumulate args.period projections in one LogicForm must use the same period");const o=new Set(Object.keys(t.query??{}));if(e.properties.filter(s=>s.primal_type==="date"&&o.has(s.name)).length!==1)throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires exactly one queried date property");return tc(t,r,n)},getOutputProperty({name:t,inputProperty:e}){return e?{...e,name:t,isArray:!1}:{name:t,type:"number",primal_type:"number",isArray:!1}}},nc={name:"$abs",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Absolute ${t}`:`${t}\u7EDD\u5BF9\u503C`,kind:"scalar",toSQL({expression:t}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$abs requires a pred");return`ABS(${t})`},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new d("PRED_PROPERTY_REQUIRED","$abs requires a pred");return{...e,name:t,isArray:!1}}},ht=(t,e,r,n=r)=>{const o=e.expressions??[];if(o.length<r||o.length>n)throw new d("INVALID_OPERATOR_COMPONENTS",`${t} requires ${r===n?String(r):`${r}-${n}`} pred inputs`);return o},mr=t=>({name:t,type:"number",primal_type:"number",isArray:!1}),oc={name:"$add",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?e.join(" plus "):`Sum of ${t}`:e.length>0?e.join("\u52A0"):`${t}\u6C42\u548C`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$add.empty":"operator.$add",kind:"scalar",requiresProperty:!1,toSQL(t){return`(${ht("$add",t,2,Number.POSITIVE_INFINITY).join(" + ")})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:mr(t)}},ne=t=>structuredClone(t),ic=(t,e)=>{const r=e[t];if(!r)throw new d("SCHEMA_NOT_FOUND",`Schema not found: ${t}`,{schemaId:t});if("_id"in r||"_sid"in r)throw new d("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported",{schemaId:t});if("sid"in r)throw new d("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid",{schemaId:t});if(r.id!==t)throw new d("SCHEMA_ID_MISMATCH",`Schema registry key ${t} does not match schema.id ${r.id}`,{registryKey:t,schemaId:r.id});return r},sc=(t,e)=>{const r=t.properties.find(n=>n.id===e)??t.properties.find(n=>n.name===e);if(!r)throw new d("PROPERTY_NOT_FOUND",`Property not found in ${t.id}: ${e}`,{schemaId:t.id,property:e});return r},ac=t=>{const e=t.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(e))},Zo=(t,e)=>t.properties.some(r=>r!==e&&r.id===e.name)?e.id:e.name,cc=(t,e)=>t.properties.flatMap(r=>[...e.startsWith(`${r.id}_`)?[{property:r,prefix:r.id}]:[],...r.name!==r.id&&e.startsWith(`${r.name}_`)?[{property:r,prefix:r.name}]:[]]).sort((r,n)=>n.prefix.length-r.prefix.length||(n.prefix===n.property.id?1:0)-(r.prefix===r.property.id?1:0)),de=(t,e,r)=>{const n=t.properties.find(o=>o.id===e)??t.properties.find(o=>o.name===e);if(n)return{canonicalName:Zo(t,n),canonicalId:n.id,schema:t,property:n,relations:[]};for(const{property:o,prefix:i}of cc(t,e)){if(o.primal_type!=="entity"&&o.primal_type!=="object"||!o.ref)continue;if(!r)throw new d("SCHEMA_RESOLVER_REQUIRED",`Resolving property path ${e} requires a Schema resolver`);const s=r(o.ref),a=de(s,e.slice(i.length+1),r);return{canonicalName:`${Zo(t,o)}_${a.canonicalName}`,canonicalId:`${o.id}_${a.canonicalId}`,schema:a.schema,property:a.property,relations:[{sourceSchema:t,property:o,targetSchema:s},...a.relations]}}throw new d("PROPERTY_NOT_FOUND",`\u5728 Schema\uFF1A${t.name}(${t.id})\u4E2D\u672A\u627E\u5230\u5C5E\u6027: ${e}`,{schemaId:t.id,schemaName:t.name,property:e,propertyName:e})},an=(t,e)=>t.name===e||t.id===e,uc=(t,e,r)=>{const n=new Set,o=[t];for(;o.length>0;){const i=o.shift();if(!i||n.has(i.name))continue;n.add(i.name);const s=[...i.hierarchy?.up?r.properties.filter(a=>an(a,i.hierarchy?.up??"")):[],...r.properties.filter(a=>a.hierarchy?.down!==void 0&&an(i,a.hierarchy.down))];if(s.some(a=>an(e,a.name)))return!0;o.push(...s)}return!1},ei=(t,e,r,n)=>{if(t.operator||typeof t.pred!="string"||e.length===0)return!1;let o;try{o=de(r,t.pred,n)}catch{return!1}return o.property.isArray||o.property.primal_type==="entity"||o.property.primal_type==="object"||o.relations.some(({property:i})=>i.isArray)?!1:e.some(i=>{if(i.operator||typeof i.pred!="string")return!1;let s;try{s=de(r,i.pred,n)}catch{return!1}if(s.property.isArray)return!1;if(s.relations.length===0&&o.relations.length===0)return uc(s.property,o.property,r);if(s.relations.length!==0||o.relations.length===0)return!1;const[a]=o.relations;return s.property.name===a?.property.name})},dc=({source:t,properties:e})=>{const r=t.hierarchy;if(!Array.isArray(r))return r===void 0?{}:{hierarchy:r};let n=t.hierarchy_property;if(typeof n!="string"||n.length===0){const s=e.filter(({type:u})=>u==="ID");if(s.length!==1)throw new d("LEGACY_HIERARCHY_ID_PROPERTY_REQUIRED","Legacy Schema hierarchy without hierarchy_property must contain exactly one ID property",{idPropertyCount:s.length});const a=s[0];n=a?.id??a?.name}const o=r.map(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return;const a=s;if(!(typeof a.name!="string"||!Number.isInteger(a.code_length)))return{name:a.name,...Array.isArray(a.syno)?{syno:a.syno}:{},codeLength:a.code_length}});if(o.some(s=>s===void 0))return{};const i=r[0];return{hierarchy:{property:n,storage:i?.use_full_length===!0?"zero-padded":"compact",levels:o}}},lc=t=>{if(!t.hierarchy)return;const e=t.properties.find(({name:r})=>r===t.hierarchy?.property);if(!e)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${t.hierarchy.property}`,{schemaId:t.id,property:t.hierarchy.property});return e},pc=(t,e,r)=>{const n=de(t,e,r);if(n.property.primal_type!=="entity"&&n.property.primal_type!=="object")return{schema:n.schema,reference:n.canonicalName,relation:!1};if(n.property.isArray)throw new d("ARRAY_HIERARCHY_RELATION_UNSUPPORTED",`$hierarchyLevel cannot group an array relation: ${n.canonicalName}`);if(!n.property.ref||!r)throw new d("SCHEMA_RESOLVER_REQUIRED",`$hierarchyLevel requires a Schema resolver for relation ${n.canonicalName}`);return{schema:r(n.property.ref),reference:n.canonicalName,relation:!0}},fc={name:"$hierarchyLevel",defaultName:({operandName:t,args:e,locale:r})=>{const n=typeof e.level=="string"?e.level:"";return r.toLowerCase().startsWith("en")?`${t}${n?` ${n}`:""} level`:`${t}${n}\u5C42\u7EA7`},kind:"scalar",planInput({reference:t,args:e,schema:r,resolveSchema:n}){const o=Object.keys(e).filter(y=>y!=="level");if(o.length>0||e.level!==void 0&&(typeof e.level!="string"||e.level.length===0))throw new d("INVALID_HIERARCHY_LEVEL_ARGS","$hierarchyLevel args may contain only one non-empty level string",{unsupportedArgs:o});const i=pc(r,t,n),s=i.schema.hierarchy;if(!s)throw new d("SCHEMA_HIERARCHY_REQUIRED",`Schema ${i.schema.id} does not declare hierarchy`,{schemaId:i.schema.id});const a=i.schema.properties.find(({name:y})=>y===s.property);if(!a)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${s.property}`);if(!i.relation&&a.name!==de(r,t,n).property.name)throw new d("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${a.name}`);const u=s.levels.reduce((y,h)=>y+h.codeLength,0),c=i.schema.properties.filter(({type:y})=>y==="ID"),l=i.relation&&c.length===1&&c[0]?.name===a.name?i.reference:i.relation?`${i.reference}_${a.name}`:i.reference;if(e.level===void 0){let y=0;return{reference:l,args:{levels:s.levels.map(({name:h,codeLength:g})=>(y+=g,{name:h,codeLength:y})),totalLength:u,storage:s.storage}}}let f=0;const m=s.levels.find(y=>(f+=y.codeLength,y.name===e.level||y.syno?.includes(e.level)));if(!m)throw new d("HIERARCHY_LEVEL_NOT_FOUND",`Schema ${i.schema.id} does not declare hierarchy level: ${e.level}`,{schemaId:i.schema.id,level:e.level});return{reference:l,args:{level:m.name,codeLength:f,totalLength:u,storage:s.storage}}},toSQL({expression:t,args:e,sql:r}){if(!t)throw new Error("$hierarchyLevel requires a hierarchy pred");if(Array.isArray(e.levels)){const u=e.levels.filter(y=>typeof y=="object"&&y!==null&&!Array.isArray(y)&&typeof y.name=="string"&&Number.isInteger(y.codeLength)),c=e.totalLength,p=e.storage;if(u.length!==e.levels.length||u.length===0||!Number.isInteger(c)||Number(c)<=0||u.some(({name:y,codeLength:h},g)=>y.length===0||h<=0||h>Number(c)||g>0&&h<=Number(u[g-1]?.codeLength))||u.at(-1)?.codeLength!==c||p!=="compact"&&p!=="zero-padded")throw new d("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const l=`WHEN ${t} IS NULL THEN NULL`;if(p==="compact"){const y=r.stringLength(t),h=u.map(g=>`WHEN ${y} = ${g.codeLength} THEN ${r.value(g.name)}`);return`(CASE ${l} ${h.join(" ")} ELSE NULL END)`}const f=u.slice(0,-1).map(y=>{const h=Number(c)-y.codeLength;return`WHEN ${r.substring(t,y.codeLength+1,h)} = ${r.value("0".repeat(h))} THEN ${r.value(y.name)}`}),m=u.at(-1);return`(CASE ${l} ${f.join(" ")} ELSE ${r.value(m?.name)} END)`}const n=e.codeLength,o=e.totalLength,i=e.storage;if(!Number.isInteger(n)||!Number.isInteger(o)||Number(n)<=0||Number(o)<Number(n)||i!=="compact"&&i!=="zero-padded")throw new d("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const s=r.substring(t,1,Number(n)),a=Number(o)-Number(n);return i==="zero-padded"&&a>0?r.concat([s,r.value("0".repeat(a))]):s},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},gt=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=t;return Object.keys(e).length===2&&e.kind==="hierarchy"&&typeof e.level=="string"&&e.level.trim().length>0},At=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),cn=(t,e,{schema:r,resolveSchema:n})=>{if(typeof e!="string")return;const o=t.primal_type==="entity"||t.primal_type==="object"?t.ref?n?.(t.ref).hierarchy:void 0:r.hierarchy?.property===t.name?r.hierarchy:void 0,i=o?.levels.find(s=>s.name===e||s.syno?.includes(e));if(!(!o||!i))return{name:i.name,index:o.levels.indexOf(i)}},yr=(t,{schema:e,mapping:r})=>r.mappings?.find(n=>n.mappingType==="property"&&n.propertyTarget?.some(o=>At(e,o)?.id===t.id)),ti=(t,e,r)=>{const n=At(r.schema,t);if(!n)return`hierarchy property is not available: ${t}`;const o=cn(n,e,r);if(!o)return`hierarchy level is not available: ${String(e)}`;const i=yr(n,r);if(!gt(i?.granularity))return;const s=cn(n,i.granularity.level,r);return s&&s.index>=o.index?void 0:`hierarchy dimension ${t} requires ${o.name}, but source has ${s?.name}`},mc=(t,e)=>{const r=i=>{const s=n(i.query);if(s)return s;if(i.operator==="$hierarchyLevel"&&typeof i.pred=="string")if(i.args?.level!==void 0){const u=ti(i.pred,i.args.level,e);if(u)return u}else{const u=At(e.schema,i.pred),c=u&&yr(u,e);if(gt(c?.granularity))return`$hierarchyLevel without args.level is not covered by hierarchy-grained source: ${i.pred}`}const a=Array.isArray(i.pred)?i.pred:i.pred===void 0?[]:[i.pred];for(const u of a){if(typeof u=="string")continue;const c=r(u);if(c)return c}},n=i=>{if(i){for(const[s,a]of Object.entries(i))if(a!==void 0){if(s==="$and"||s==="$or"){if(!Array.isArray(a))continue;for(const u of a){const c=n(u);if(c)return c}}else if(s==="$expr"){if(typeof a!="object"||a===null||Array.isArray(a))continue;const u=a.pred;if(typeof u!="object"||u===null||Array.isArray(u))continue;const c=r(u);if(c)return c}else if(!s.startsWith("$")){const u=At(e.schema,s),c=u&&yr(u,e);if(gt(c?.granularity))return`query on hierarchy-grained property requires an explicit $hierarchyLevel: ${s}`}}}},o=n(t.query);if(o)return o;for(const i of t.preds??[]){const s=r(i);if(s)return s}for(const i of t.groupby??[])if(typeof i.pred=="string"){if(i.operator==="$hierarchyLevel"){const s=ti(i.pred,i.args?.level,e);if(s)return s}else if(i.operator===void 0){const s=At(e.schema,i.pred),a=s&&yr(s,e);if(gt(a?.granularity))return`raw groupby is not covered by hierarchy-grained source: ${i.pred}`}}},yc={kind:"hierarchy",isGranularity:gt,validateItem(t,e){const r=t.granularity;if(gt(r))return t.propertyTarget?.every(n=>{const o=At(e.schema,n);return o!==void 0&&cn(o,r.level,e)!==void 0})?void 0:"physical hierarchy granularity requires a mapped hierarchy Property and level"},candidateReason:mc,supportsGroupby:t=>t.operator==="$hierarchyLevel"},hc={keys:["hierarchy"],resolve(t,e){for(const f of e)if(f.level!==void 0){if(typeof f.level!="string"||f.level.trim().length===0)throw new d("INVALID_PROPERTY_LEVEL",`Property ${f.name} level must be a non-empty string`,{property:f.name,level:f.level});if(f.primal_type!=="entity"&&f.primal_type!=="object")throw new d("PROPERTY_LEVEL_REQUIRES_ENTITY",`Property ${f.name} level requires an entity relation`,{property:f.name,type:f.type})}if("hierarchy_property"in t)throw new d("LEGACY_HIERARCHY_PROPERTY_NOT_ALLOWED","Schema hierarchy must declare hierarchy.property instead of hierarchy_property");const r=t.hierarchy;if(r===void 0)return{};if(typeof r!="object"||r===null||Array.isArray(r))throw new d("INVALID_HIERARCHY","Schema hierarchy must be an object containing property, levels, and optional storage");const n=r,o=Object.keys(n).filter(f=>f!=="property"&&f!=="storage"&&f!=="levels");if(o.length>0)throw new d("UNSUPPORTED_HIERARCHY_FIELD","Schema hierarchy only supports property, storage, and levels",{unsupportedKeys:o});const i=n.property===void 0?(()=>{const f=e.filter(m=>m.type==="ID");if(f.length!==1)throw new d("HIERARCHY_ID_PROPERTY_REQUIRED","Schema hierarchy.property may be omitted only when the Schema has exactly one ID Property",{idPropertyCount:f.length});return f[0]})():void 0;if(n.property!==void 0&&(typeof n.property!="string"||n.property.length===0))throw new d("HIERARCHY_PROPERTY_REQUIRED","Schema hierarchy.property must be a non-empty property name or id when provided");const s=i??e.find(f=>f.name===n.property||f.id===n.property);if(!s)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${n.property}`,{property:n.property});if(s.primal_type!=="string")throw new d("INVALID_HIERARCHY_PROPERTY",`Hierarchy property ${s.name} must have primal_type string`,{property:s.name,primal_type:s.primal_type});const a=n.storage??"compact";if(a!=="compact"&&a!=="zero-padded")throw new d("INVALID_HIERARCHY_STORAGE","Schema hierarchy.storage must be compact or zero-padded");if(!Array.isArray(n.levels)||n.levels.length===0)throw new d("HIERARCHY_LEVELS_REQUIRED","Schema hierarchy.levels must be a non-empty array");const u=new Set,c=new Set,p=n.levels.map((f,m)=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} must be an object`);const y=f,h=Object.keys(y).filter($=>$!=="name"&&$!=="syno"&&$!=="codeLength");if(h.length>0)throw new d("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${m} only supports name, syno, and codeLength`,{unsupportedKeys:h});if(typeof y.name!="string"||y.name.length===0)throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} name must not be empty`);if(u.has(y.name)||c.has(y.name))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level name: ${y.name}`);if(!Number.isInteger(y.codeLength)||Number(y.codeLength)<=0)throw new d("INVALID_HIERARCHY_CODE_LENGTH",`Hierarchy level ${y.name} codeLength must be a positive integer`);if(y.syno!==void 0&&(!Array.isArray(y.syno)||y.syno.some($=>typeof $!="string"||$.length===0)))throw new d("INVALID_HIERARCHY_SYNONYMS",`Hierarchy level ${y.name} syno must contain only non-empty strings`);const g=y.syno??[];for(const $ of g){if($===y.name||u.has($)||c.has($))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${$}`);c.add($)}return u.add(y.name),{name:y.name,...g.length>0?{syno:[...g]}:{},codeLength:Number(y.codeLength)}});return{hierarchy:{property:s.name,storage:a,levels:p}}}},gc=Object.freeze({name:"hierarchy",schemaMetadata:hc,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:dc,resolveEntityFilterProperty:lc,operators:[fc],mappingGranularity:yc}),Ac=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp"),un="$periodValue",$c=(t,e)=>{const r=e?.periodBoundaryPolicy?.({pred:t});if(r)return{operator:un,...r};if(e?.kind==="aggregate")throw new d("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${un}; ${e.name} describes a time range`,{operator:e.name});return{operator:un,boundary:"end",implicit:!0}},wc={name:"observation",resolveProjection({pred:t,schema:e,sourceProperty:r,outputProperty:n,operator:o}){if(!r||!Ac(r,e))return;const i=$c(t,o);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:i.boundary,sourceProperty:r.name}}}}},Ec=new Set(["second","minute","hour","day","week","month","quarter","year"]),ri=t=>typeof t=="string"&&Ec.has(t),_c=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),hr=(t,e,r)=>{const n=t instanceof Date?t.getTime():typeof t=="string"||typeof t=="number"?new Date(t).getTime():Number.NaN;if(Number.isNaN(n))throw new d(`${r.codePrefix}_PERIOD_INVALID_BOUND`,`${r.label} period ${e} must be a date`,{owner:e,value:t});return n},tt=(t,e=2)=>String(t).padStart(e,"0"),dn=t=>`${tt(t.getFullYear(),4)}-${tt(t.getMonth()+1)}-${tt(t.getDate())} ${tt(t.getHours())}:${tt(t.getMinutes())}:${tt(t.getSeconds())}.`+tt(t.getMilliseconds(),3),Sc=(t,e)=>{if(!_c(t)){const a=hr(t,"point",e);return{lower:a,upper:a}}const r=t.$eq;if(r!==void 0){const a=hr(r,"$eq",e);return{lower:a,upper:a}}const n=t.$gte??t.$gt,o=t.$lte??t.$lt;if(n===void 0||o===void 0)throw new d(`${e.codePrefix}_PERIOD_BOUNDS_REQUIRED`,`${e.label} period grouping requires both a lower and an upper time bound`);const i=hr(n,t.$gte!==void 0?"$gte":"$gt",e)+(t.$gte===void 0?1:0),s=hr(o,t.$lte!==void 0?"$lte":"$lt",e)-(t.$lte===void 0?1:0);if(i>s)throw new d(`${e.codePrefix}_PERIOD_INVALID_RANGE`,`${e.label} period grouping requires the lower bound to precede the upper bound`,{lower:n,upper:o});return{lower:i,upper:s}},Ic=(t,e)=>{const r=new Date(t);switch(e){case"second":r.setMilliseconds(0);break;case"minute":r.setSeconds(0,0);break;case"hour":r.setMinutes(0,0,0);break;case"day":r.setHours(0,0,0,0);break;case"week":{r.setHours(0,0,0,0);const n=(r.getDay()+6)%7;r.setDate(r.getDate()-n);break}case"month":r.setDate(1),r.setHours(0,0,0,0);break;case"quarter":r.setMonth(Math.floor(r.getMonth()/3)*3,1),r.setHours(0,0,0,0);break;case"year":r.setMonth(0,1),r.setHours(0,0,0,0);break}return r},bc=(t,e)=>{const r=new Date(t);switch(e){case"second":r.setSeconds(r.getSeconds()+1);break;case"minute":r.setMinutes(r.getMinutes()+1);break;case"hour":r.setHours(r.getHours()+1);break;case"day":r.setDate(r.getDate()+1);break;case"week":r.setDate(r.getDate()+7);break;case"month":r.setMonth(r.getMonth()+1);break;case"quarter":r.setMonth(r.getMonth()+3);break;case"year":r.setFullYear(r.getFullYear()+1);break}return r},ni=(t,e,r)=>{const{lower:n,upper:o}=Sc(t,r),i=[];let s=Ic(n,e);for(;s.getTime()<=o;){if(i.length>=1e4)throw new d(`${r.codePrefix}_PERIOD_LIMIT_EXCEEDED`,`${r.label} period grouping cannot generate more than 10000 periods`);const a=bc(s,e),u=new Date(Math.min(a.getTime()-1,o));i.push({label:dn(s),start:dn(s),end:dn(u)}),s=a}return i},Rc=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.name),Nc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.name)),Oc=(t,e)=>{if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:l})=>l==="timestamp");if(!r)return;const n=Rc(t,r),o=t.preds??[],i=o.filter(({operator:l})=>l==="$periodValue");if(!n||i.length===0)return;const s=n.args?.granularity;if(n.operator!=="$dateBucket"||!ri(s))throw new d("OBSERVATION_PERIOD_GRANULARITY_UNSUPPORTED","Grouped observation period values require $dateBucket with a supported time granularity",{property:r.name});if(i.length!==o.length)throw new d("OBSERVATION_PERIOD_METRICS_REQUIRED","A grouped observation query cannot mix $periodValue with ordinary projections");const a=i.map(l=>{const f=l.args?.boundary;if(f!=="start"&&f!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:f});if(!l.pred||typeof l.pred!="object"||Array.isArray(l.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");return{pred:l,effectivePred:{...l.pred,...l.name?{name:l.name}:{}}}});if(new Set(i.map(({args:l})=>l?.boundary)).size!==1)throw new d("OBSERVATION_PERIOD_BOUNDARY_MISMATCH","Grouped observation metrics in one query must use the same period boundary");const c=i[0]?.args?.boundary,p=t.query?.[r.name];if(p===void 0)throw new d("OBSERVATION_PERIOD_BOUNDS_REQUIRED",`Grouped observation values on ${r.name} require a bounded query`,{property:r.name});return{group:n,timestamp:r,boundary:c,metrics:a,periods:ni(p,s,{codePrefix:"OBSERVATION",label:"Observation"}).map(l=>({label:l.label,asOf:l[c]}))}},oi=["second","minute","hour","day","week","month","quarter","year"],Tc=Object.freeze({name:"observation",schemaMetadata:{keys:["temporalSemantics"],resolve(t){const e=t.temporalSemantics??"normal";if(e!=="normal"&&e!=="snapshot")throw new d("INVALID_TEMPORAL_SEMANTICS","Schema temporalSemantics must be normal or snapshot",{schemaId:t.id,temporalSemantics:e});return{temporalSemantics:e}}},validateResolvedSchema(t){if(t.temporalSemantics==="snapshot"&&!t.properties.some(({type:e})=>e==="timestamp"))throw new d("SNAPSHOT_TIMESTAMP_REQUIRED","A snapshot Schema must declare exactly one timestamp Property",{schemaId:t.id})},plannerSemantics:[wc],relationSemantics:{plan({sourceSchema:t,targetSchema:e}){if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:s})=>s==="timestamp");if(!r)throw new d("SNAPSHOT_JOIN_REQUIRES_ID_AND_TIMESTAMP",`Snapshot Schema ${e.id} requires an ID and timestamp Property when joined`,{schemaId:e.id});const n=t.properties.find(({type:s})=>s==="timestamp");if(!n)throw new d("SNAPSHOT_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Snapshot Schema ${e.id} cannot join from a Schema without a timestamp Property`,{schemaId:t.id});const o=n.granularity??"day",i=r.granularity??"day";if(oi.indexOf(o)>oi.indexOf(i))throw new d("SNAPSHOT_JOIN_GRANULARITY_TOO_COARSE",`Cannot join ${e.id} snapshot granularity ${i} to coarser source granularity ${o}`,{sourceSchemaId:t.id,targetSchemaId:e.id,sourceGranularity:o,targetGranularity:i});return{kind:"date-bucket-equal",sourceTimestamp:n,targetTimestamp:r}}},plannerPeriod:{resolve(t,e){const r=Oc(t,e);if(r)return{group:r.group,property:r.timestamp,periods:r.periods,source:{kind:"latest",timestamp:r.timestamp},rewriteQuery:n=>Nc(n,r.timestamp),rewritePred:n=>r.metrics.find(o=>o.pred===n)?.effectivePred??n}}}}),Vt=(t,e)=>typeof e=="string"?t.properties.find(({id:r,name:n})=>r===e||n===e):void 0,Pc={name:"$recursive",validateCondition(t){if(Object.keys(t).some(e=>e!=="$recursive"))throw new d("INVALID_RECURSIVE_QUERY","$recursive cannot be combined with other field operators")},async normalize(t,e){const r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{root:t},n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=n===e.schema.id?e.schema:e.resolveSchema?.(n);if(!o)throw new d("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=r.idProperty??r.id_property,s=o.properties.filter(({type:f})=>f==="ID"),a=i===void 0?s.length===1?s[0]:void 0:Vt(o,i);if(!a||i===void 0&&s.length!==1)throw new d("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive Schema ${n} must have exactly one ID property or idProperty`);const u=Array.isArray(r.roots),c=u?r.roots:r.root===void 0?[]:[r.root];if(!u&&c.length===0||c.some(f=>f===void 0))throw new d("RECURSIVE_ROOT_REQUIRED","$recursive requires root or roots");const p=await Promise.all(c.map(f=>e.normalizeValue(f,o,a))),l=r.parentProperty??r.parent_property??o.parentProperty??"pid";if(typeof l!="string"||l.length===0)throw new d("RECURSIVE_PARENT_PROPERTY_REQUIRED","$recursive parentProperty must be a string");if(r.includeSelf!==void 0&&typeof r.includeSelf!="boolean"||r.include_self!==void 0&&typeof r.include_self!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive includeSelf must be boolean");return{schema:n,roots:p,includeSelf:r.includeSelf??r.include_self??!0,idProperty:a.name,parentProperty:l}},authorize(t,e){const r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=e.resolveSchema(n);if(e.assertSchemaAllowed(n),e.hasRowPermissions(n))throw new d("RECURSIVE_ROW_PERMISSION_UNSUPPORTED",`$recursive cannot safely apply row permissions for Schema ${n}`,{schemaId:n});const i=r.idProperty??r.id_property,s=i===void 0?o.properties.find(({type:c})=>c==="ID"):Vt(o,i),a=r.parentProperty??r.parent_property??o.parentProperty??"pid",u=Vt(o,a);s&&e.assertPropertyAllowed(o,s),u&&e.assertPropertyAllowed(o,u)},plan(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const r=t,n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=n===e.schema.id?e.schema:e.resolveSchema?.(n);if(!o)throw new d("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=Vt(o,r.idProperty),s=Vt(o,r.parentProperty);if(!i)throw new d("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive ID property not found: ${String(r.idProperty)}`);if(!s)throw new d("RECURSIVE_PARENT_PROPERTY_REQUIRED",`$recursive parent property not found: ${String(r.parentProperty)}`);if(!Array.isArray(r.roots)||typeof r.includeSelf!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const a=e.resolveMapping(n,e.connectionId);return{value:{schemaId:n,connectionId:a.connectionId,source:a.source,...a.sourceSql?{sourceSql:a.sourceSql}:{},idColumn:i.id,parentColumn:s.id,roots:r.roots,includeSelf:r.includeSelf},sources:[{schemaId:n,source:a.source,...a.connectionId?{connectionId:a.connectionId}:{}}]}},compile(t,{field:e,provider:r,bind:n,renderSource:o}){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_RECURSIVE_QUERY","$recursive query was not planned");const i=t;if(typeof i.source!="string"||typeof i.idColumn!="string"||typeof i.parentColumn!="string"||!Array.isArray(i.roots)||typeof i.includeSelf!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive query was not planned");if(!r.supportsRecursiveCte)throw new d("RECURSIVE_QUERY_UNSUPPORTED",`Provider ${r.kind} does not support recursive queries`);const s=Array.isArray(i.roots)?i.roots:[];if(s.length===0)return`${e} IN (SELECT NULL WHERE 1 = 0)`;const a=r.quoteIdentifier("__recursive_tree__"),u=r.quoteIdentifier("__recursive_id__"),c=r.quoteIdentifier("__recursive_node__"),p=r.quoteIdentifier("__recursive_child__"),l=r.quoteIdentifier(i.idColumn),f=r.quoteIdentifier(i.parentColumn),m=o(i.source,typeof i.sourceSql=="string"?i.sourceSql:void 0),y=()=>s.map(E=>n(E)).join(", "),h=(E,A=!1)=>s.length===1?`${E} ${A?"<>":"="} ${y()}`:`${E} ${A?"NOT IN":"IN"} (${y()})`,g=`${c}.${l}`,$=i.includeSelf?h(g):`${h(`${c}.${f}`)} AND ${h(g,!0)}`,w=r.recursiveCteUnion??"UNION",S=`(WITH RECURSIVE ${a}(${u}) AS ( SELECT ${g} FROM ${r.tableAlias(m,"__recursive_node__")} WHERE ${$} ${w} SELECT ${p}.${l} FROM ${r.tableAlias(m,"__recursive_child__")} JOIN ${a} ON ${p}.${f} = ${a}.${u}) SELECT DISTINCT ${u} FROM ${a})`;return`${e} IN ${S}`}},Lc=Object.freeze({name:"recursive",schemaMetadata:{keys:["parentProperty"],resolve(t,e){if(t.parentProperty===void 0)return{};const r=e.find(({id:n,name:o})=>n===t.parentProperty||o===t.parentProperty);if(!r)throw new d("RECURSIVE_PARENT_PROPERTY_REQUIRED",`Schema parentProperty does not exist: ${t.parentProperty}`,{schemaId:t.id,property:t.parentProperty});return{parentProperty:r.name}}},queryOperators:[Pc]});ue.extend(Mt);const ln=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...ln(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:ln(r))]:e},ii=(t,e)=>ue(t).endOf(e==="week"?"isoWeek":e).toDate(),pn=t=>ue(t).format("YYYY-MM-DD HH:mm:ss"),Dc=(t,e)=>{const r=t??{type:"database_latest"};if(r.type==="database_latest"||Number.isInteger(r.offset))return r;throw new d("INVALID_TIME_WATERMARK",`${e} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:e,timeWatermark:t})},si=(t,e)=>{if(t===void 0)return;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_TIME_WATERMARK",`${e} timeWatermark must be an object`);const r=t,n=Object.keys(r);if(!(r.type==="database_latest"&&n.length===1)&&!(r.type==="now_offset"&&n.every(o=>o==="type"||o==="offset")&&Number.isInteger(r.offset)))throw new d("INVALID_TIME_WATERMARK",`${e} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:e,timeWatermark:t})},Cc=Object.freeze({name:"temporal",schemaMetadata:{keys:["timeWatermark"],resolve(t){return si(t.timeWatermark,`Schema ${t.id}`),{...t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}}},propertyMetadata:{keys:["timeWatermark"],resolve(t,e){if(si(t.timeWatermark,`Property ${t.name}`),t.timeWatermark&&e.primal_type!=="date")throw new d("TIME_WATERMARK_DATE_PROPERTY_REQUIRED",`Property ${e.name} timeWatermark is only supported by date Properties`,{property:e.name});return t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}},createTimeWatermarkLogicform({logicform:t,rootSchema:e,rootProperty:r,requestedUpperBound:n,now:o,defaultPolicy:i,resolveSchema:s,inferPropertyPath:a}){const u=[...new Set((t.preds??[]).flatMap(ln).filter(l=>l!==e.id))],c=[{schema:e,property:r}];for(const l of u){const f=s(l),m=t.propertyResolve?.[l],y=m?.[r.id]??m?.[r.name]??a(e,r.name,f);if(!y)throw new d("TIME_WATERMARK_PROPERTY_RESOLVE_REQUIRED",`Cross-Schema timeWatermark requires propertyResolve for ${l}.${r.name}`,{schemaId:l,property:r.name});const h=f.properties.find(({id:g,name:$})=>g===y||$===y);if(!h||h.primal_type!=="date")throw new d("TIME_WATERMARK_PROPERTY_REQUIRED",`timeWatermark Property is not a date Property: ${l}.${y}`,{schemaId:l,property:y});c.push({schema:f,property:h})}const p=c.map(({schema:l,property:f})=>{const m=Dc(f.timeWatermark??l.timeWatermark??i,`${l.id}.${f.id}`);if(m.type==="now_offset"){const y=ii(ue(o).add(m.offset,"day").toDate(),f.granularity??"day");return{operator:"$constant",args:{value:pn(y),type:"timestamp"},name:`${l.name}\u6570\u636E\u65F6\u95F4`}}return{operator:"$periodBoundary",args:{boundary:"end"},pred:{operator:"$max",pred:f.name,schema:l.id},name:`${l.name}\u6700\u65B0\u65F6\u95F4`}});return p.some(({operator:l})=>l==="$periodBoundary")&&p.push({operator:"$constant",args:{value:pn(ii(o,r.granularity??"day")),type:"timestamp"},name:"\u73B0\u5728"}),p.push({operator:"$constant",args:{value:pn(n),type:"timestamp"},name:"\u63D0\u95EE\u65F6\u95F4\u4E0A\u754C"}),{version:t.version,schema:e.id,preds:[{name:"__timeWatermark__",operator:"$least",pred:p}]}}}),gr=(t,e)=>{const r=t.filter(n=>n.type===e);return r.length===1?r[0]:void 0},vt=t=>{if(t.type!=="entity"||t.temporalSemantics==="snapshot")return;const e=gr(t.properties,"ID"),r=gr(t.properties,"timestamp"),n=gr(t.properties,"start_date"),o=gr(t.properties,"end_date");return e&&r&&n&&o?{id:e,timestamp:r,start:n,end:o}:void 0},ai=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.timestamp.name),kc=(t,e)=>ai(t,e)!==void 0,Uc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.timestamp.name)),Mc=(t,e)=>{const r=ai(t,e);if(!r)return;const n=r.args?.granularity;if(r.operator!=="$dateBucket"||!ri(n))throw new d("VALIDITY_PERIOD_GRANULARITY_UNSUPPORTED","Valid-time period grouping requires $dateBucket with a supported time granularity",{property:e.timestamp.name});const o=t.query?.[e.timestamp.name];if(o===void 0)throw new d("VALIDITY_PERIOD_BOUNDS_REQUIRED",`Valid-time period grouping on ${e.timestamp.name} requires a bounded query`,{property:e.timestamp.name});return{group:r,granularity:n,periods:ni(o,n,{codePrefix:"VALIDITY",label:"Valid-time"}).map(({label:i,end:s})=>({label:i,asOf:s}))}},qc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),jc=t=>qc(t)?t.$lte??t.$lt??t.$eq:t,ci=(t,e)=>{if(!t)return t;const r=Object.fromEntries(Object.entries(t).map(([a,u])=>[a,(a==="$and"||a==="$or")&&Array.isArray(u)?u.map(c=>ci(c,e)):u])),n=Object.entries(t).find(([a])=>a===e.timestamp.name);if(!n)return r;const[,o]=n,i=jc(o);if(i===void 0)throw new d("VALIDITY_POINT_IN_TIME_REQUIRED",`Valid-time query on ${e.timestamp.name} requires an upper bound or a point in time`,{property:e.timestamp.name});return{...Object.fromEntries(Object.entries(r).filter(([a])=>a!==e.timestamp.name)),[e.start.name]:t[e.start.name]??{$lte:i},[e.end.name]:t[e.end.name]??{$or:[{$exists:!1},{$gt:i}]}}},ui=(t,e)=>!!(t&&Object.entries(t).some(([r,n])=>e.has(r)||(r==="$and"||r==="$or")&&Array.isArray(n)&&n.some(o=>typeof o=="object"&&o!==null&&ui(o,e)))),xc={name:"validity",resolveQuery({logicform:t,schema:e,query:r}){const n=vt(e);if(!n)return r;if(kc(t,n))return Uc(r,n);const i=ui(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:new Date().toISOString()}};return ci(i,n)},resolveProjection({schema:t,outputProperty:e}){if(vt(t))return{outputProperty:{...e,temporal:{kind:"validity"}}}}},Bc={name:"start_date",primalType:"date"},Vc={name:"end_date",primalType:"date"},vc=Object.freeze({name:"validity",semanticTypes:[Bc,Vc],prepareSchema(t){const e=t.properties.filter(({type:s})=>s==="ID"),r=t.properties.filter(({type:s})=>s==="start_date"),n=t.properties.filter(({type:s})=>s==="end_date"),o=r[0];if(t.type!=="entity"||t.properties.some(({type:s})=>s==="timestamp")||t.temporalSemantics==="snapshot"||e.length!==1||r.length!==1||n.length!==1||t.properties.some(({name:s})=>s==="\u65E5\u671F")||!o)return t;const i={id:"__chatbi__timestamp__placeholder__",name:"\u65E5\u671F",type:"timestamp",is_supplementary:!0,udf:{sql:o.id??o.name}};return{...t,properties:[...t.properties,i]}},plannerSemantics:[xc],intervalSemantics:{resolve:vt},relationSemantics:{plan({sourceSchema:t,targetSchema:e}){const r=vt(e);if(!r)return;const n=t.properties.find(({type:o})=>o==="timestamp");if(!n)throw new d("VALIDITY_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Valid-time Schema ${e.id} cannot join from a Schema without a timestamp Property`,{schemaId:t.id});return{kind:"point-in-interval",point:n,start:r.start,end:r.end}}},plannerPeriod:{resolve(t,e){const r=vt(e);if(!r)return;const n=Mc(t,r);return n?{group:n.group,property:r.timestamp,periods:n.periods,source:{kind:"interval",start:r.start,end:r.end}}:void 0}}}),di=(t,e,r,n)=>{if(r===void 0)return;if(typeof r!="string"||r.length===0)throw new d("INVALID_PROPERTY_HIERARCHY",`Property ${e.name} hierarchy.${n} must be a non-empty Property name or id`,{property:e.name,direction:n,reference:r});const o=t.find(i=>i.id===r)??t.find(i=>i.name===r);if(!o)throw new d("PROPERTY_HIERARCHY_TARGET_NOT_FOUND",`Property ${e.name} hierarchy.${n} does not exist: ${r}`,{property:e.name,direction:n,reference:r});if(o===e)throw new d("PROPERTY_HIERARCHY_CYCLE",`Property ${e.name} cannot point to itself in hierarchy.${n}`,{property:e.name,direction:n});return o.name},Fc=Object.freeze({name:"property-hierarchy",propertyMetadata:{keys:["hierarchy"],resolve:()=>({}),resolveAll(t,e){const r=t.map((o,i)=>{const s=e[i]?.hierarchy;if(s===void 0)return o;if(typeof s!="object"||s===null||Array.isArray(s))throw new d("INVALID_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy must be an object containing up and/or down`,{property:o.name,hierarchy:s});const a=s,u=Object.keys(a).filter(l=>l!=="up"&&l!=="down");if(u.length>0)throw new d("UNSUPPORTED_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy only supports up and down`,{property:o.name,unsupported:u});const c=di(t,o,a.up,"up"),p=di(t,o,a.down,"down");return{...o,hierarchy:{...c?{up:c}:{},...p?{down:p}:{}}}}),n=new Map(r.map(o=>[o.name,o]));for(const o of r)for(const i of["up","down"]){const s=new Set;let a=o;for(;a?.hierarchy?.[i];){if(s.has(a.name))throw new d("PROPERTY_HIERARCHY_CYCLE",`Property hierarchy.${i} contains a cycle at ${a.name}`,{property:o.name,direction:i,cycleAt:a.name});s.add(a.name),a=n.get(a.hierarchy[i])}}return r}}}),li=Object.freeze([gc,Lc,Cc,Tc,vc,Fc]),ye=(t=[])=>{const e=[...li,...t],r=new Set,n=new Set,o=new Set,i=new Set,s=new Set,a=new Set,u=new Set,c=new Set,p=new Set;for(const l of e){if(!l.name)throw new d("INVALID_PLUGIN","Plugin name must not be empty");if(r.has(l.name))throw new d("PLUGIN_ALREADY_REGISTERED",`Plugin is already registered: ${l.name}`,{plugin:l.name});r.add(l.name);for(const m of[...l.schemaMetadata?.keys??[],...l.legacySchemaKeys??[]]){if(!m)throw new d("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(n.has(m))throw new d("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${m}`,{key:m,plugin:l.name});n.add(m)}for(const m of l.propertyMetadata?.keys??[]){if(!m)throw new d("INVALID_PLUGIN_PROPERTY_METADATA_KEY","Plugin Property metadata key must not be empty");if(o.has(m))throw new d("PLUGIN_PROPERTY_METADATA_KEY_ALREADY_REGISTERED",`Plugin Property metadata key is already registered: ${m}`,{key:m,plugin:l.name});o.add(m)}for(const m of l.operators??[]){if(i.has(m.name))throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${m.name}`,{operator:m.name,plugin:l.name});i.add(m.name)}for(const m of l.semanticTypes??[]){if(s.has(m.name))throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${m.name}`,{semanticType:m.name,plugin:l.name});s.add(m.name)}for(const m of l.plannerSemantics??[]){if(!m.name||a.has(m.name))throw new d("PLUGIN_SEMANTIC_RULE_ALREADY_REGISTERED",`Plugin Planner semantic rule must be non-empty and unique: ${m.name}`,{rule:m.name,plugin:l.name});a.add(m.name)}for(const m of l.queryOperators??[]){if(!m.name||u.has(m.name))throw new d("PLUGIN_QUERY_OPERATOR_ALREADY_REGISTERED",`Plugin Query Operator must be non-empty and unique: ${m.name}`,{operator:m.name,plugin:l.name});u.add(m.name)}for(const m of l.outputHandlers??[]){if(!m.type||c.has(m.type))throw new d("PLUGIN_OUTPUT_HANDLER_ALREADY_REGISTERED",`Plugin output handler type must be non-empty and unique: ${m.type}`,{type:m.type,plugin:l.name});c.add(m.type)}const f=l.mappingGranularity;if(f){if(!f.kind||p.has(f.kind))throw new d("PLUGIN_GRANULARITY_ALREADY_REGISTERED",`Plugin physical granularity kind must be non-empty and unique: ${f.kind}`);p.add(f.kind)}}return Object.freeze(e)},$t=(t,e=[])=>ye(e).flatMap(r=>r.queryOperators??[]).find(r=>r.name===t),pi=(t,e=[])=>ye(e).flatMap(r=>r.outputHandlers??[]).find(r=>r.type===t),fn=(t,e)=>{if(e.length>1)throw new d("PLUGIN_SEMANTIC_CAPABILITY_AMBIGUOUS",`Multiple plugins matched ${t}: ${e.map(({plugin:r})=>r).join(", ")}`,{capability:t,plugins:e.map(({plugin:r})=>r)});return e[0]?.value},fi=(t,e=[])=>fn("interval semantics",ye(e).flatMap(r=>{const n=r.intervalSemantics?.resolve(t);return n?[{plugin:r.name,value:n}]:[]})),Yc=(t,e,r=[])=>fn("relation semantics",ye(r).flatMap(n=>{const o=n.relationSemantics?.plan({sourceSchema:t,targetSchema:e});return o?[{plugin:n.name,value:o}]:[]})),Hc=(t,e,r=[])=>fn("planner period semantics",ye(r).flatMap(n=>{const o=n.plannerPeriod?.resolve(t,e);return o?[{plugin:n.name,value:o}]:[]})),mn=t=>typeof t=="string"&&t.length>0&&t!=="placeholder"||typeof t=="number"&&Number.isSafeInteger(t),Qc=t=>{const e=t.properties.filter(({type:r})=>r==="ID");if(e.length!==1)throw new d("ENTITY_ID_PROPERTY_REQUIRED",`Schema ${t.id} must contain exactly one ID property to use entity_id`,{schemaId:t.id,idPropertyCount:e.length});return e[0]},yn=(t,e=[])=>{for(const r of ye(e)){const n=r.resolveEntityFilterProperty?.(t);if(n)return n}return Qc(t)},hn=t=>{if(t.name)return t.name;throw new d("MISSING_PRED_NAME","A normalized groupby PredItem must have a name")},gn=t=>typeof t.pred=="string"?t.pred:void 0,Gc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Wc={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},zc={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},An=(t,e,r)=>{const n=e.toLowerCase().startsWith("en"),o=t.time;if(!Gc(o))return r?.("period.comparison",n?"period-over-period":"\u540C\u671F")??(n?"period-over-period":"\u540C\u671F");if(typeof o.granularity=="string"&&typeof o.offset=="number"){if(o.offset===-1&&o.granularity==="year")return r?.("period.yearOverYear",n?"year-over-year":"\u540C\u6BD4")??(n?"year-over-year":"\u540C\u6BD4");if(o.offset===-1&&o.granularity==="month")return r?.("period.monthOverMonth",n?"month-over-month":"\u73AF\u6BD4")??(n?"month-over-month":"\u73AF\u6BD4");if(o.offset===-1&&o.granularity==="week")return r?.("period.weekOverWeek",n?"week-over-week":"\u5468\u73AF\u6BD4")??(n?"week-over-week":"\u5468\u73AF\u6BD4");if(o.offset===0)return r?.("period.current",n?"current-period":"\u672C\u671F")??(n?"current-period":"\u672C\u671F");const s=Math.abs(o.offset),a=o.offset<0?"before":"after";return n?`${s} ${o.granularity}${s===1?"":"s"} ${a}`:`\u8F83${a==="before"?"\u524D":"\u540E"}${s}${Wc[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${zc[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};ue.extend(Mt),ue.extend(ar);const Kc=["second","minute","hour","day","week","month","quarter","year"],Jc=new Set(Kc),$n=["year","quarter","month","week","day","hour","minute","second"],mi=t=>Object.prototype.toString.call(t)==="[object Object]",ze=t=>{throw new d("INVALID_PERIOD_SHIFT_ARGS",t)},Xc=t=>{const e=t.time;mi(e)||ze("$periodShift requires args.time");const r=e;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!Jc.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&ze("Relative period shift time requires only granularity and an integer offset"),r;const o=Object.entries(r);(o.length===0||o.some(([a,u])=>!$n.includes(a)||!Number.isInteger(u)))&&ze("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&ze("Absolute period shift time requires year");const i={quarter:[1,4],month:[1,12],week:[1,53],day:[1,31],hour:[0,23],minute:[0,59],second:[0,59]};for(const[a,[u,c]]of Object.entries(i)){const p=r[a];p!==void 0&&(Number(p)<u||Number(p)>c)&&ze(`Invalid absolute period shift ${a}: ${JSON.stringify(p)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&ze("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&ze("Absolute period shift day requires month"),r},yi=(t,e,r)=>e==="month"?t.month(r-1):e==="day"?t.date(r):e==="week"?t.isoWeek(r):e==="quarter"?t.quarter(r):t.set(e,r),Zc=(t,e)=>{if("granularity"in e){const n=e.granularity==="week"?"week":e.granularity;return t.add(e.offset,n)}let r=t;for(const n of $n){const o=e[n];typeof o=="number"&&(r=yi(r,n,o))}return r},wn=(t,e)=>t instanceof Date?e.toDate():typeof t!="string"?t:e.format(t.includes(":")?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"),eu=(t,e,r,n,o)=>(t.groupby??[]).filter(i=>{const s=gn(i);return s?de(e,s,r).property.primal_type==="date":!1}).map(i=>{const s=i.operator==="$dateBucket"?i.args?.granularity:void 0,a="granularity"in n?n.granularity:s??"day",u="granularity"in n?-n.offset:o.originalAnchor&&o.shiftedAnchor?o.originalAnchor.diff(o.shiftedAnchor,a):0;return{name:hn(i),granularity:a,offset:u}}),En=(t,e,r)=>{if(Array.isArray(t))return t.map(i=>En(i,e,r));if(mi(t))return Object.fromEntries(Object.entries(t).map(([i,s])=>[i,En(s,e,r)]));if(!(t instanceof Date)&&typeof t!="string")return t;const n=ue(t);if(!n.isValid())return t;const o=Zc(n,e);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,wn(t,o)},tu=(t,e,r,n,o)=>{const i=new Set,s=u=>Object.fromEntries(Object.entries(u).map(([c,p])=>{if((c==="$and"||c==="$or")&&Array.isArray(p))return[c,p.map(f=>s(f))];const l=de(e,c,r);return l.property.primal_type!=="date"?[c,p]:(i.add(l.canonicalName),[c,En(p,n,o)])})),a=s(t);if(i.size===0||o.shiftedValues===0)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a concrete date condition in the LogicForm query");if(i.size>1)throw new d("AMBIGUOUS_PERIOD_SHIFT_TIME","$periodShift query contains more than one date property",{properties:[...i]});return a},rt=t=>{const e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?e[0]:{$and:e}},Ke=t=>[...t.query?[t.query]:[],...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Ke(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(r=>typeof r=="string"?[]:Ke(r)):[]],ru=(t,e,r)=>{if(!(t instanceof Date)&&typeof t!="string")return t;const n=ue(t);if(!n.isValid())return t;if("granularity"in e)return wn(t,n.add(-e.offset,e.granularity));if(!r.originalAnchor)return t;let o=n;for(const i of $n)if(e[i]!==void 0){const s=i==="month"?r.originalAnchor.month()+1:i==="day"?r.originalAnchor.date():i==="week"?r.originalAnchor.isoWeek():i==="quarter"?r.originalAnchor.quarter():r.originalAnchor.get(i);o=yi(o,i,s)}return wn(t,o)},_n=({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o})=>{const i=e.pred;(!i||typeof i!="object"||Array.isArray(i))&&ze("$periodShift pred must be a nested metric");const s=Xc(e.args??{}),a={shiftedValues:0},u=rt([t.query,...Ke(e)]);if(!u)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const c=tu(u,n,o,s,a),p=ne(i);p.name=r,delete p.query;const l=ne(t);l.query=c,l.preds=[p],delete l.having,delete l.sort,delete l.limit,delete l.page;const f=new Set((t.groupby??[]).filter(m=>{const y=gn(m);return y?de(n,y,o).property.primal_type==="date":!1}).map(hn));return{kind:"query",logicform:l,groupKeyShifts:eu(t,n,o,s,a),mapResult:m=>m.map(y=>{const h={...y};for(const g of f)h[g]=ru(h[g],s,a);return h})}},nu={name:"$periodShift",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=An(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} baseline`:`${t}${o}\u57FA\u671F\u503C`;return n?.("operator.$periodShift",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:_n,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodShift requires a nested metric");return{...e,name:t,isArray:!1}}},ou=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Ar=t=>typeof t=="string"||typeof t=="number"||t instanceof Date,hi=(t,e)=>{const r=t.properties.find(({type:n})=>n==="timestamp");if(!r)throw new d("TIMESTAMP_PROPERTY_REQUIRED",`${e} requires a timestamp property in the Schema`);return r},gi=(t,e)=>{if(Ar(t)){e.start??=t,e.end??=t;return}if(!ou(t))return;const r=t.$eq;Ar(r)&&(e.start??=r,e.end??=r);const n=t.$gte??t.$gt,o=t.$lte??t.$lt;Ar(n)&&(e.start??=n),Ar(o)&&(e.end??=o);for(const i of["$and","$or"]){const s=t[i];if(Array.isArray(s))for(const a of s)gi(a,e)}},iu=(t,e,r,n)=>{const o=hi(e,n),i=new Set,s={},a=(l,f)=>{for(const[m,y]of Object.entries(l)){if((m==="$and"||m==="$or")&&Array.isArray(y)){for(const g of y)a(g,f||m==="$or");continue}if(m.startsWith("$"))continue;const h=de(e,m,r);if(h.property.type==="timestamp"){if(f)throw new d("AMBIGUOUS_TIME_QUERY",`${n} does not support timestamp conditions inside $or`);i.add(h.canonicalName),gi(y,s)}}};if(a(t,!1),i.size!==1)throw new d(i.size===0?"TIME_QUERY_REQUIRED":"AMBIGUOUS_TIME_QUERY",`${n} requires a concrete condition on the Schema timestamp property`);const u=[...i][0];if(!u||u!==o.name)throw new d("AMBIGUOUS_TIME_QUERY",`${n} requires the Schema timestamp property: ${o.name}`);const c=l=>{const f=[];for(const[m,y]of Object.entries(l)){if((m==="$and"||m==="$or")&&Array.isArray(y)){const h=y.map(g=>c(g)).filter(g=>g!==void 0);h.length>0&&f.push([m,h]);continue}!m.startsWith("$")&&de(e,m,r).property.type==="timestamp"||f.push([m,y])}return f.length>0?Object.fromEntries(f):void 0},p=c(t);return{property:o,propertyName:u,...s.start!==void 0?{start:s.start}:{},...s.end!==void 0?{end:s.end}:{},...p?{queryWithoutTime:p}:{}}},Ai=(t,e,r,n,o)=>{const i=rt([t,...Ke(e)]);if(!i)throw new d("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return iu(i,r,n,o)},$i=(t,e,r)=>rt([t,{[e]:r}]),su=new Set(["day","week","month","quarter","year"]),au={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},cu=t=>{if(typeof t!="string"||!su.has(t))throw new d("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return t},wi=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Sn=t=>{const e=ne(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Sn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Sn(r))),e},uu={name:"$averagePerPeriod",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${t} per ${typeof e.granularity=="string"?e.granularity:"period"}`:`${t}${au[String(e.granularity)]??"\u5468\u671F"}\u5747\u503C`,kind:"component",createComponent({logicform:t,pred:e,schema:r,outputName:n,t:o}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_AVERAGE_PER_PERIOD_INPUT","$averagePerPeriod pred must be a nested metric");const i=cu(e.args?.granularity),s=hi(r,"$averagePerPeriod"),a=Sn(e.pred),u=rt([t.query,...Ke(e)]),c=wi(t);c.preds=[{...a,name:"__avg_period_num__"}],u&&(c.query=u);const p=wi(t);p.preds=[{operator:"$countDistinct",pred:{operator:"$dateBucket",pred:s.name,args:{granularity:i},name:"__avg_period_bucket__"},name:"__avg_period_den__"}],u&&(p.query=u);const l=o("component.numerator",`${n}\u5206\u5B50`,{outputName:n}),f=o("component.denominator",`${n}\u5206\u6BCD`,{outputName:n});return{components:[{name:l,logicform:c},{name:f,logicform:p}],expression:`${l} / NULLIF(${f}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$averagePerPeriod requires a nested metric");return{...e,name:t,isArray:!1}}},du={name:"$avg",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Average ${t}`:`\u5E73\u5747${t}`,kind:"aggregate",toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$avg requires a column");return r.aggregateFunction("avg",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$avg requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1}}},wt=t=>{throw new d("INVALID_CASE_ARGS",t)},lu=t=>{if(t.mode!=="auto")return;Object.hasOwn(t,"cases")&&wt("$case auto mode cannot define args.cases"),t.empty!==void 0&&typeof t.empty!="boolean"&&wt("$case auto mode args.empty must be boolean");const e=t.buckets;e!==void 0&&(!Number.isInteger(e)||e<2||e>100)&&wt("$case auto mode args.buckets must be an integer between 2 and 100");const r=t.count;if(r!==void 0&&(!Number.isSafeInteger(r)||r<0)&&wt("$case auto mode args.count must be a non-negative safe integer"),t.empty===!0)return{empty:!0};for(const o of["min","max"])(typeof t[o]!="number"||!Number.isFinite(t[o]))&&wt(`$case auto mode requires resolved finite args.${o}`);t.min>t.max&&wt("$case auto mode args.min cannot be greater than args.max");const n=e===void 0?r===void 0?10:Math.min(12,Math.max(5,Math.ceil(Math.log2(Math.max(r,1))+1))):e;return{empty:!1,minimum:t.min,maximum:t.max,targetBuckets:n}},pu=t=>{const r=10**Math.floor(Math.log10(t)),n=t/r;return(n<=1?1:n<=2?2:n<=2.5?2.5:n<=5?5:10)*r},$r=t=>{const e=Number(t.toPrecision(15));return Object.is(e,-0)?0:e},In=t=>String($r(t)),fu=(t,e,r)=>{if(t===e)return[t,e];const n=pu((e-t)/r),o=$r(Math.floor(t/n)*n),i=$r(Math.ceil(e/n)*n),s=Math.max(1,Math.round((i-o)/n));return Array.from({length:s+1},(a,u)=>u===s?i:$r(o+n*u))},mu=t=>{if(!Array.isArray(t)||t.length===0)throw new d("INVALID_CASE_ARGS","$case requires a non-empty args.cases array");return t.map(e=>{if(typeof e!="object"||e===null||!("when"in e)||!("then"in e))throw new d("INVALID_CASE_ARGS","Each $case item requires when and then");const r=e;return{when:r.when,then:r.then}})},yu={name:"$case",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} category`:`${t}\u5206\u7C7B`,kind:"scalar",validateGroupby({pred:t}){if(t.args?.mode==="auto"&&t.args.empty!==!0&&(t.args.min===void 0||t.args.max===void 0))throw new d("AUTO_CASE_GROUPBY_REQUIRES_BOUNDS","$case auto mode in groupby requires resolved args.min and args.max")},toSQL({expression:t,args:e,sql:r}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$case requires a pred");const n=lu(e);if(n){const s=r.value("\u672A\u77E5");if(n.empty)return s;const a=n.minimum,u=n.maximum;if(a===u)return`CASE WHEN ${t} IS NULL THEN ${s} ELSE ${r.value(In(a))} END`;const c=fu(a,u,n.targetBuckets),p=c.slice(0,-1).map((f,m)=>{const y=c[m+1],h=m===c.length-2?"]":")";return`[${In(f)}, ${In(y)}${h}`}),l=p.slice(0,-1).map((f,m)=>`WHEN ${t} < ${r.value(c[m+1])} THEN ${r.value(f)}`);return`CASE WHEN ${t} IS NULL THEN ${s} ${l.join(" ")} ELSE ${r.value(p.at(-1))} END`}const o=mu(e.cases).map(({when:s,then:a})=>`WHEN ${r.condition(t,s)} THEN ${r.value(a)}`),i=Object.hasOwn(e,"default")?` ELSE ${r.value(e.default)}`:"";return`CASE ${o.join(" ")}${i} END`},getOutputProperty({name:t}){return{name:t,type:"category",primal_type:"string",isArray:!1}}},hu={name:"$concat",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?`Combined ${e.join(" and ")}`:`Combined ${t}`:e.length>0?`${e.join("\u4E0E")}\u62FC\u63A5\u503C`:`${t}\u62FC\u63A5\u503C`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$concat.empty":"operator.$concat",kind:"scalar",requiresProperty:!1,toSQL(t){return t.sql.concat(ht("$concat",t,1,Number.POSITIVE_INFINITY))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},gu={name:"$count",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?t==="rows"?"Row count":`${t} count`:t==="\u6570\u636E\u884C"?"\u884C\u6570":`${t}\u6570\u91CF`,defaultNameKey:({inputName:t,inputNames:e})=>t||e.length>0?"operator.$count":"operator.$count.rows",kind:"aggregate",requiresProperty:!1,toSQL(t){const{column:e,sql:r}=t;return r.aggregateFunction("count",e)},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},Au={name:"$countDistinct",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Distinct ${t} count`:`${t}\u53BB\u91CD\u8BA1\u6570`,kind:"aggregate",toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$countDistinct requires a column");return r.aggregateFunction("count",`DISTINCT ${e}`)},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},$u=new Set(["second","minute","hour","day","week","month","quarter","year"]),wu={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Ei=t=>{if(typeof t!="string"||!$u.has(t))throw new d("INVALID_DATE_BUCKET_ARGS","$dateBucket args.granularity must be second, minute, hour, day, week, month, quarter, or year");return t},Eu={name:"$dateBucket",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} by ${typeof e.granularity=="string"?e.granularity:"time"}`:`${t}\uFF08\u6309${wu[String(e.granularity)]??"\u65F6\u95F4"}\uFF09`,kind:"scalar",supportsGroupedSourceGroupby:!0,groupedSourceTimeGranularity:({pred:t})=>t.args?.granularity,toSQL({expression:t,args:e,sql:r}){if(!t)throw new Error("$dateBucket requires a date pred");return r.dateBucket(t,Ei(e.granularity))},getOutputProperty({name:t,inputProperty:e,args:r}){if(!e||e.primal_type!=="date")throw new d("DATE_BUCKET_DATE_REQUIRED","$dateBucket requires a date-valued pred");const n=Ei(r.granularity);return{...e,name:t,type:"date",primal_type:"date",isArray:!1,granularity:n}}},_u={name:"$divide",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>=2?`${e[0]} divided by ${e[1]}`:`${t} ratio`:e.length>=2?`${e[0]}\u9664\u4EE5${e[1]}`:`${t}\u6BD4\u503C`,defaultNameKey:({inputNames:t})=>t.length<2?"operator.$divide.fallback":"operator.$divide",kind:"scalar",requiresProperty:!1,toSQL(t){const[e,r]=ht("$divide",t,2);return`(${e} / NULLIF(${r}, 0))`},getOutputProperty({name:t}){return mr(t)}},Su=t=>{if(!(!t.inputProperty?.comparable||!t.input))return{kind:"ordinal-decode",comparable:t.inputProperty.comparable,input:{kind:"operator",operator:"$max",args:t.args,...t.pred.query?{query:t.planQuery(t.pred.query)}:{},input:{kind:"ordinal-encode",input:t.input,comparable:t.inputProperty.comparable}}}},Iu={name:"$max",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Maximum ${t}`:`${t}\u6700\u5927\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Su,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$max requires a column");return r.aggregateFunction("max",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$max requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1,...n.granularity?{granularity:n.granularity}:{},...n.comparable?{comparable:n.comparable}:{}}}},bu=t=>{if(!(!t.inputProperty?.comparable||!t.input))return{kind:"ordinal-decode",comparable:t.inputProperty.comparable,input:{kind:"operator",operator:"$min",args:t.args,...t.pred.query?{query:t.planQuery(t.pred.query)}:{},input:{kind:"ordinal-encode",input:t.input,comparable:t.inputProperty.comparable}}}},Ru={name:"$min",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Minimum ${t}`:`${t}\u6700\u5C0F\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:bu,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$min requires a column");return r.aggregateFunction("min",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$min requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1,...n.granularity?{granularity:n.granularity}:{},...n.comparable?{comparable:n.comparable}:{}}}},Nu={name:"$multiply",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?e.join(" times "):`Product of ${t}`:e.length>0?e.join("\u4E58\u4EE5"):`${t}\u4E58\u79EF`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$multiply.empty":"operator.$multiply",kind:"scalar",requiresProperty:!1,toSQL(t){return`(${ht("$multiply",t,2,Number.POSITIVE_INFINITY).join(" * ")})`},getOutputProperty({name:t}){return mr(t)}},Ou=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},bn=t=>{const e=ne(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=bn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:bn(r))),e},Tu={name:"$newly",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`New ${t}`:`\u65B0\u589E${t}`,kind:"component",createComponent({logicform:t,pred:e,schema:r,resolveSchema:n,outputName:o,t:i}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_NEWLY_INPUT","$newly pred must be a nested metric");if((t.groupby??[]).some(l=>{const f=gn(l);return f?de(r,f,n).property.type==="timestamp":!1}))throw new d("NEWLY_TIME_GROUPBY_UNSUPPORTED","$newly does not support grouping by the timestamp property");const s=Ai(t.query,e,r,n,"$newly");if(s.start===void 0||s.end===void 0)throw new d("NEWLY_RANGE_REQUIRED","$newly requires both start and end timestamp bounds");const a=bn(e.pred),u=(l,f)=>{const m=Ou(t);return m.query=$i(s.queryWithoutTime,s.propertyName,{$lte:l}),m.preds=[{...a,name:f}],m},c=i("component.end",`${o}\u7ED3\u675F`,{outputName:o}),p=i("component.start",`${o}\u5F00\u59CB`,{outputName:o});return{components:[{name:c,logicform:u(s.end,"__newly_end__")},{name:p,logicform:u(s.start,"__newly_start__")}],expression:`${c} - COALESCE(${p}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$newly requires a nested metric");return{...e,name:t,isArray:!1}}},Pu=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Rn=t=>{const e=ne(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Rn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Rn(r))),e},Lu={name:"$periodValue",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} at period ${e.boundary==="start"?"start":"end"}`:`${t}${e.boundary==="start"?"\u671F\u521D\u503C":"\u671F\u672B\u503C"}`,defaultNameKey:({args:t})=>`operator.$periodValue.${t.boundary==="start"?"start":"end"}`,kind:"component",skipComponentExecution:({plan:t})=>t.periodSource?.match.kind==="latest",periodBoundaryPolicy({pred:t}){const e=t.args?.boundary;if(e!=="start"&&e!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:e});return{boundary:e,implicit:!1}},createComponent({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");const i=e.args?.boundary;if(i!=="start"&&i!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end");const s=Ai(t.query,e,n,o,"$periodValue"),a=i==="start"?s.start:s.end;if(a===void 0)throw new d("PERIOD_BOUNDARY_RANGE_REQUIRED",`$periodValue cannot resolve the ${i} of the timestamp query`);const u={version:t.version,schema:n.id,query:{[s.propertyName]:{$lte:a}},preds:[{operator:"$max",pred:s.propertyName,name:"__period_boundary_date__"}]},c=Pu(t);return c.query=$i(s.queryWithoutTime,s.propertyName,u),c.preds=[{...Rn(e.pred),name:r}],{kind:"query",logicform:c}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodValue requires a nested metric");return{...e,name:t,isArray:!1}}},Du=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Cu=({logicform:t,pred:e,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new Error("$periodDifference pred must be a nested metric");const a=ne(e.pred);a.name="__period_diff_current__";const u=Du(t);u.preds=[a];const c=rt([t.query,...Ke(e)]);c&&(u.query=c);const p={pred:ne(e.pred),...e.args?{args:e.args}:{}},l=_n({logicform:t,pred:p,outputName:"__period_diff_prev__",schema:i,resolveSchema:s});if(!("logicform"in l))throw new Error("$periodDifference period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:u},{name:m,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${f} - ${m}`}},ku={name:"$periodDifference",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=An(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} difference`:`${t}${o}\u5DEE\u503C`;return n?.("operator.$periodDifference",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:Cu,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodDifference requires a nested metric");return{...e,name:t,isArray:!1}}},Uu=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Mu=({logicform:t,pred:e,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new Error("$periodGrowth pred must be a nested metric");const a=ne(e.pred);a.name="__period_growth_current__";const u=Uu(t);u.preds=[a];const c=rt([t.query,...Ke(e)]);c&&(u.query=c);const p={pred:ne(e.pred),...e.args?{args:e.args}:{}},l=_n({logicform:t,pred:p,outputName:"__period_growth_prev__",schema:i,resolveSchema:s});if(!("logicform"in l))throw new Error("$periodGrowth period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:u},{name:m,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${f} / NULLIF(ABS(${m}), 0) - 1`}},qu={name:"$periodGrowth",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=An(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} growth`:`${t}${o}\u589E\u957F\u7387`;return n?.("operator.$periodGrowth",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:Mu,getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},ju={name:"$sum",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Total ${t}`:`\u603B${t}`,kind:"aggregate",supportsGroupedSourceRollup:!0,toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$sum requires a column");return r.aggregateFunction("sum",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$sum requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1}}},xu={name:"$subtract",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>=2?`${e[0]} minus ${e[1]}`:`${t} difference`:e.length>=2?`${e[0]}\u51CF\u53BB${e[1]}`:`${t}\u5DEE\u503C`,defaultNameKey:({inputNames:t})=>t.length<2?"operator.$subtract.fallback":"operator.$subtract",kind:"scalar",requiresProperty:!1,toSQL(t){const[e,r]=ht("$subtract",t,2);if(t.args.nullAsZero!==void 0&&typeof t.args.nullAsZero!="boolean")throw new d("INVALID_SUBTRACT_ARGS","$subtract args.nullAsZero must be boolean");return t.args.nullAsZero===!0?`(COALESCE(${e}, 0) - COALESCE(${r}, 0))`:`(${e} - ${r})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:mr(t)}},_i=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Nn=t=>{const e=ne(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Nn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Nn(r))),e},Bu={name:"$shareOfTotal",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} share of total`:`${t}\u5360\u6BD4`,kind:"component",createComponent({logicform:t,pred:e,outputName:r,t:n}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_SHARE_OF_TOTAL_INPUT","$shareOfTotal pred must be a nested metric");const o=e.args?.dimension;if(o!==void 0&&typeof o!="string")throw new d("INVALID_SHARE_OF_TOTAL_ARGS","$shareOfTotal args.dimension must be a groupby pred or output name");const i=t.groupby??[],s=o===void 0?i.length-1:i.findIndex(y=>typeof y.pred=="string"&&y.pred===o||hn(y)===o);if(o!==void 0&&s<0)throw new d("SHARE_OF_TOTAL_DIMENSION_NOT_FOUND",`$shareOfTotal dimension is not grouped: ${o}`);const a=i.filter((y,h)=>h!==s),u=Nn(e.pred),c=_i(t);c.preds=[{...u,name:"__share_numerator__"}];const p=rt([t.query,...Ke(e)]);p&&(c.query=p);const l=_i(t);l.groupby=a,l.preds=[{...u,name:"__share_denominator__"}];const f=n("component.numerator",`${r}\u5206\u5B50`,{outputName:r}),m=n("component.denominator",`${r}\u5206\u6BCD`,{outputName:r});return{components:[{name:f,logicform:c},{name:m,logicform:l}],expression:`${f} / NULLIF(${m}, 0)`}},getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},Vu={name:"$substring",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} substring`:`${t}\u5B50\u4E32`,kind:"scalar",toSQL({expression:t,args:e,sql:r}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$substring requires a pred");const{start:n,length:o}=e;if(!Number.isInteger(n)||Number(n)<0||!Number.isInteger(o)||Number(o)<1)throw new d("INVALID_SUBSTRING_ARGS","$substring requires a non-negative integer start and a positive integer length");return r.substring(t,Number(n)+1,Number(o))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},Si=(t,e,r,n="$sql")=>{if(typeof t!="string"||t.trim().length===0)throw new d("INVALID_SQL_ARGS",`${n} requires a non-empty args.sql expression`);let o="",i=0,s;for(let a=0;a<t.length;a+=1){const u=t[a];if(!u)continue;if(s){o+=u,u===s&&(t[a+1]===s?(o+=s,a+=1):s=void 0);continue}if(u==="'"||u==='"'||u==="`"){s=u,o+=u;continue}const c=t.slice(a,a+2);if(u===";"||c==="--"||c==="/*")throw new d("INVALID_SQL_EXPRESSION",`${n} accepts one expression and does not allow statements or SQL comments`);if(u==="?"){if(i>=e.length)throw new d("INVALID_SQL_PARAMETERS",`${n} contains more placeholders than args.parameters values`);o+=r(e[i]),i+=1;continue}o+=u}if(s)throw new d("INVALID_SQL_EXPRESSION",`${n} contains an unterminated quote`);if(i!==e.length)throw new d("INVALID_SQL_PARAMETERS",`${n} args.parameters contains more values than SQL placeholders`);return o},vu=new Set(["boolean","date","number","entity","object","string"]),Fu=t=>{if(t===void 0)return[];if(!Array.isArray(t))throw new d("INVALID_SQL_ARGS","$sql args.parameters must be an array");return t},Yu=(t,e)=>{const r=e.type,n=e.primal_type;if(typeof r!="string"||r.length===0||!vu.has(n))throw new d("INVALID_SQL_OUTPUT","$sql requires args.type and a valid args.primal_type");if(e.isArray!==void 0&&typeof e.isArray!="boolean")throw new d("INVALID_SQL_OUTPUT","$sql args.isArray must be boolean");if(e.ref!==void 0&&typeof e.ref!="string")throw new d("INVALID_SQL_OUTPUT","$sql args.ref must be a Schema id");return{name:t,type:r,primal_type:n==="object"?"entity":n,isArray:e.isArray===!0,...typeof e.ref=="string"?{ref:e.ref}:{}}},Hu={name:"$sql",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Calculated value":"\u8BA1\u7B97\u503C",kind:"scalar",requiresProperty:!1,toSQL({args:t,expression:e,expressions:r,sql:n}){if(e||r&&r.length>0)throw new d("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return Si(t.sql,Fu(t.parameters),o=>n.value(o))},getOutputProperty({name:t,args:e,inputProperty:r,inputProperties:n}){if(r||n&&n.length>0)throw new d("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return Yu(t,e)}},Qu=t=>{const e=new Set,r=n=>{for(const[o,i]of Object.entries(n)){if(o==="$and"||o==="$or"){for(const s of i)r(s);continue}e.add(o)}};return r(t),[...e]},Gu=t=>typeof t.pred!="string"?t:{...t,pred:{operator:"$sum",pred:t.pred,name:`${t.pred}\u5408\u8BA1`}},Wu=(t,e,r)=>{const n=t.preds;if(n.filter(p=>p.operator==="$rank"&&p.query).length!==1)throw new d("AMBIGUOUS_RANK_TARGET","A LogicForm without groupby must contain exactly one $rank pred.query target");const i=Qu(r),[s]=i;if(i.length!==1||!s)throw new d("AMBIGUOUS_RANK_DIMENSION","$rank pred.query must reference exactly one property when groupby is omitted",{properties:i});const a=ne(t);a.groupby=[{pred:s,name:s}],a.preds=n.map(p=>{if(p.name!==e.name)return p;const l={...p};return delete l.query,Gu(l)}),delete a.sort,delete a.limit,delete a.limitBy,delete a.page,delete a.output,delete a.representation;const u=n.map(({name:p})=>p).filter(p=>!!p),c=ne(t);return c.from=a,c.query=r,c.preds=[{pred:s,name:s},...u.map(p=>({pred:p,name:p}))],delete c.groupby,delete c.having,delete c.entity_id,delete c.propertyResolve,c},zu={name:"$rank",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} rank`:`${t}\u6392\u540D`,kind:"window",windowFunction:"rank",rewriteLogicform({logicform:t}){if(t.groupby?.length)return;const e=t.preds?.find(r=>r.operator==="$rank"&&r.query);return e?.query?Wu(t,e,e.query):void 0},validatePlan({pred:t,groupByNames:e}){if(!t.pred||Array.isArray(t.pred))throw new d("INVALID_WINDOW_OPERATOR_INPUT","$rank requires exactly one pred");if(e.length===0&&!t.query&&typeof t.pred!="string")throw new d("RANK_GROUPBY_OR_TARGET_REQUIRED","$rank requires groupby or a pred.query target used to infer the ranking dimension")},getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},Ku={name:"$rowNumber",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Row number":"\u884C\u53F7",kind:"window",windowFunction:"rowNumber",getOutputProperty({name:t}){return{name:t,type:"int",primal_type:"number",isArray:!1}}},Ju=new Set(["string","number","boolean","date","entity","object"]),On=t=>{if(t==="timestamp"||t==="date")return{type:t,primal_type:"date"};if(typeof t=="string"&&Ju.has(t))return{type:t,primal_type:t};throw new d("INVALID_CONSTANT_TYPE","$constant args.type must be timestamp, date, string, number, boolean, entity, or object")},Xu={name:"$constant",defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Constant":"\u5E38\u91CF",kind:"scalar",requiresProperty:!1,normalizePred({pred:t}){if(t.pred!==void 0)throw new d("INVALID_CONSTANT_INPUT","$constant does not accept pred");return On(t.args?.type),t},toSQL({args:t,sql:e}){return On(t.type),e.value(t.value,t.type)},getOutputProperty({name:t,args:e}){return{name:t,...On(e.type),isArray:!1}}},Zu={name:"$periodBoundary",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} at period ${e.boundary==="start"?"start":"end"}`:`${t}${e.boundary==="start"?"\u671F\u521D":"\u671F\u672B"}`,defaultNameKey:({args:t})=>`operator.$periodBoundary.${t.boundary==="start"?"start":"end"}`,kind:"scalar",toSQL({expression:t,args:e,sql:r}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$periodBoundary requires pred");const n=e.boundary;if(n!=="start"&&n!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodBoundary args.boundary must be start or end");const o=e.granularity;if(typeof o!="string")throw new d("END_OF_PERIOD_GRANULARITY_REQUIRED","$periodBoundary requires the input Property granularity");const i=r.dateBucket(t,o);return r.datePeriodBoundary?r.datePeriodBoundary(t,o,n):n==="start"?i:r.dateShift(r.dateShift(i,o,1),"second",-1)},planExpression({input:t,inputProperty:e,args:r}){if(!t)return;const n=e?.granularity??r.granularity;return{kind:"operator",operator:"$periodBoundary",input:t,args:{...r,granularity:n}}},normalizePred({pred:t,schema:e}){if(!t.pred||Array.isArray(t.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodBoundary requires one pred");if(typeof t.pred=="string"){const r=e.properties.find(({id:n,name:o})=>n===t.pred||o===t.pred);return{...t,args:{...t.args,granularity:r?.granularity}}}return t},getOutputProperty({name:t,inputProperty:e,args:r}){if(!e||e.primal_type!=="date")throw new d("PERIOD_BOUNDARY_DATE_REQUIRED","$periodBoundary requires a date-valued pred");const n=e.granularity??r.granularity;if(typeof n!="string")throw new d("END_OF_PERIOD_GRANULARITY_REQUIRED","$periodBoundary requires the input Property granularity");return{...e,name:t,granularity:n,isArray:!1}}},Ii="__scalarExtremumInputs",Tn=t=>{if(t.schema)return t.schema;if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred))return Tn(t.pred);if(Array.isArray(t.pred)){const e=[...new Set(t.pred.flatMap(r=>typeof r=="string"?[]:Tn(r)??[]))];if(e.length===1)return e[0]}},ed=t=>{const e=ne(t);return delete e.from,delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,delete e.representation,delete e.output,e},td=(t,e)=>{if(e.args?.[Ii]===!0||!Array.isArray(e.pred))return;if(t.preds?.length!==1)throw new d("SCALAR_EXTREMUM_SINGLE_PROJECTION_REQUIRED",`${e.operator} with multiple pred inputs must be the only LogicForm projection`);const r=e.pred.map((o,i)=>{const s=typeof o=="string"?{pred:o}:ne(o),a=s.name??`__scalar_extremum_input_${i}__`,u=s.schema??Tn(s);return{...s,name:a,...u?{schema:u}:{}}}),n=ed(t);return n.preds=r,{version:t.version,from:n,preds:[{operator:e.operator,pred:r.map(({name:o})=>o),...e.name?{name:e.name}:{},args:{...e.args,[Ii]:!0}}],...t.having?{having:t.having}:{},...t.sort?{sort:t.sort}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.page!==void 0?{page:t.page}:{},...t.output?{output:t.output}:{},...t.representation?{representation:t.representation}:{}}},rd=(t,e)=>{const r=t==="$least"?"MIN":"MAX",n=e.map(o=>`SELECT ${o} AS value`).join(" UNION ALL ");return`(SELECT ${r}(value) FROM (${n}) AS __scalar_extremum_values)`},nd=(t,e,r)=>{const[n,...o]=r??[];if(!n)throw new d("INVALID_OPERATOR_INPUTS",`${t} requires pred inputs`);if(o.some(({primal_type:i})=>i!==n.primal_type))throw new d("INCOMPATIBLE_OPERATOR_INPUTS",`${t} pred inputs must have the same primal type`);return{...n,name:e,isArray:!1}},bi=t=>({name:t,defaultName:({inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t==="$least"?"Least":"Greatest"} of ${e.join(", ")}`:`${e.join("\u3001")}\u4E2D\u7684${t==="$least"?"\u6700\u65E9\u503C":"\u6700\u665A\u503C"}`,kind:"scalar",requiresProperty:!1,normalizePred({pred:e}){if(!Array.isArray(e.pred)||e.pred.length<2)throw new d("INVALID_OPERATOR_INPUTS",`${t} requires at least two pred inputs`);return e},rewriteLogicform({logicform:e}){const r=e.preds?.[0];return r?.operator===t?td(e,r):void 0},toSQL(e){const r=ht(t,e,2,Number.POSITIVE_INFINITY);return e.sql.scalarExtremum?.(t==="$least"?"least":"greatest",r)??rd(t,r)},getOutputProperty({name:e,inputProperties:r}){return nd(t,e,r)}}),od=bi("$least"),id=bi("$greatest"),Pn={second:{en:"second",zh:"\u79D2"},minute:{en:"minute",zh:"\u5206\u949F"},hour:{en:"hour",zh:"\u5C0F\u65F6"},weekday:{en:"weekday",zh:"\u661F\u671F"},day:{en:"day",zh:"\u65E5"},week:{en:"week",zh:"\u5468"},month:{en:"month",zh:"\u6708"},quarter:{en:"quarter",zh:"\u5B63\u5EA6"},year:{en:"year",zh:"\u5E74"}},sd={name:"$length",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} length`:`${t}\u957F\u5EA6`,kind:"scalar",toSQL({expression:t,sql:e}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$length requires a pred");return e.stringLength(t)},getOutputProperty({name:t,inputProperty:e}){if(!e||e.primal_type!=="string"||e.isArray)throw new d("LENGTH_STRING_REQUIRED","$length requires a scalar string-valued pred");return{name:t,type:"int",primal_type:"number",isArray:!1}}},ad=t=>({name:`$${t}`,defaultName:({operandName:e,locale:r})=>r.toLowerCase().startsWith("en")?`${e} ${Pn[t].en}`:`${e}${Pn[t].zh}`,kind:"scalar",toSQL({expression:e,sql:r}){if(!e)throw new d("PRED_PROPERTY_REQUIRED",`$${t} requires a pred`);return r.datePart(e,t)},getOutputProperty({name:e,inputProperty:r}){if(!r||r.primal_type!=="date"||r.isArray)throw new d("DATE_PART_DATE_REQUIRED",`$${t} requires a scalar date-valued pred`);return{name:e,type:"int",primal_type:"number",isArray:!1}}}),cd=Object.freeze(Object.keys(Pn).map(ad)),Ri=Object.freeze([rc,ju,gu,Au,du,Ru,Iu,nu,qu,ku,uu,Lu,Tu,oc,xu,Nu,_u,nc,Bu,yu,hu,Vu,Eu,Hu,zu,Ku,Xu,Zu,od,id,sd,...cd]),ud={name:"boolean",primalType:"boolean",hydrateResult(t){return typeof t=="number"?t===1:t}},dd={name:"category",primalType:"string"},ld={name:"currency",primalType:"number"},pd={name:"date",primalType:"date"},fd={name:"duration",primalType:"number"},Ni=(t,{property:e,requestEntity:r})=>!e.ref||t===void 0||t===null||typeof t=="object"&&!Array.isArray(t)?t:r(e.ref,t),md={name:"object",primalType:"object",hydrateResult:Ni},yd={name:"entity",primalType:"entity",hydrateResult:Ni},hd={name:"file",primalType:"string"},gd={name:"humanName",primalType:"string"},Ad={name:"ID",primalType:"string"},$d={name:"image",primalType:"string"},wd={name:"int",primalType:"number"},Ed={name:"name",primalType:"string"},_d={name:"number",primalType:"number"},Sd={name:"order",primalType:"number"},Id={name:"percentage",primalType:"number"},bd={name:"string",primalType:"string"},Rd={name:"timestamp",primalType:"date"},Ln=Object.freeze([Ad,bd,Ed,gd,dd,$d,hd,_d,wd,ld,Id,fd,Sd,ud,Rd,pd,yd,md]),Nd=(t,e,r)=>{if(typeof t=="function")return t;if(typeof t!="string"||t.trim().length===0)return;const n=new Function(`return (${t})`)();if(typeof n!="function")throw new TypeError(`Operator ${r} ${e} must resolve to a function`);return n},Oi=t=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError("Operator definition must be an object");const e=t,r=e.name,n=typeof r=="string"?r:"",o=e.type,i=new Set(["defaultName","getOutputProperty","planInput","normalizePred","planExpression","periodBoundaryPolicy","validatePlan","rewriteLogicform","requiresPerPeriodEvaluation","toSQL","evaluate","createComponent"]),s=Object.fromEntries(Object.entries(e).filter(([a])=>!i.has(a)));s.name=r;for(const a of i){const u=Nd(e[a],a,n);u&&(s[a]=u)}if(!s.getOutputProperty&&typeof o=="string"){const a=Ln.find(({name:u})=>u===o);if(!a)throw new TypeError(`Semantic type is not registered: ${o}`);s.getOutputProperty=()=>({name:n,type:o,primal_type:a.primalType,isArray:!1})}return s};class wr{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){const r=Oi(e);if(!r.name)throw new d("INVALID_OPERATOR","Operator name must not be empty");if(typeof r.defaultName!="function")throw new d("INVALID_OPERATOR",`Operator must implement defaultName: ${r.name}`);if(this.#e.has(r.name))throw new d("OPERATOR_ALREADY_REGISTERED",`Operator is already registered: ${r.name}`,{operator:r.name});const n=r;if(!(n.kind==="scalar"&&(typeof n.toSQL=="function"||typeof n.evaluate=="function")||n.kind==="aggregate"&&typeof n.toSQL=="function"||n.kind==="component"&&typeof n.createComponent=="function"||n.kind==="window"&&typeof n.windowFunction=="string"||n.kind==="logical"&&typeof n.planExpression=="function"))throw new d("INVALID_OPERATOR",`Operator kind and implementation do not match: ${r.name}`);return this.#e.set(r.name,r),this}get(e){const r=this.#e.get(e);if(!r)throw new d("OPERATOR_NOT_FOUND",`Operator is not registered: ${e}`,{operator:e});return r}requiresPerPeriodEvaluation(e,r){return this.get(e).requiresPerPeriodEvaluation?.(r)??!1}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}}const Od=Object.freeze([...Ri,...li.flatMap(({operators:t})=>t??[])]),De=(t=[])=>new wr([...Ri,...ye(t).flatMap(({operators:e})=>e??[])]),Et=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="logicform-subquery"&&typeof t.plan=="object"&&t.plan!==null,Ti=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="query-operator"&&typeof t.operator=="string",Td=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="ordinal-query",Pi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="expression-query",Pd=(t,e)=>{const r=sc(t,e);return{schemaId:t.id,propertyId:r.id,propertyName:r.name,physicalColumn:r.udf?.sql??r.id}},Li=(t,e,r)=>{const n=t.fieldReferences?.[r];return n?{schemaId:n.schemaId,propertyId:n.propertyId??n.column,propertyName:n.property,physicalColumn:n.sql??n.column}:Pd(e,r)},Ft=(t,e,r,n)=>{if(t.kind==="column")return{sources:[{schemaId:t.schemaId??r.id,propertyId:t.propertyId??t.column,propertyName:t.property,physicalColumn:t.column}],transformations:["projection"]};if(t.kind==="property-sql")return{sources:[{schemaId:t.schemaId,propertyId:t.propertyId,propertyName:t.property,physicalColumn:t.sql}],transformations:["property-sql"]};if(t.kind==="array-element")return{sources:[{schemaId:t.schemaId,propertyId:t.property,propertyName:t.property,physicalColumn:t.property}],transformations:["array-expand"]};if(t.kind==="window"){const u=[t.input,...t.partitionBy].map(c=>Ft(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:${t.function}`]}}if(t.kind==="cumulative"){const u=[t.input,...t.partitionBy,...t.orderBy.map(({expression:c})=>c)].map(c=>Ft(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:cumulative:${t.function}`]}}if(t.kind==="ordinal-encode"||t.kind==="ordinal-decode"){const u=Ft(t.input,e,r,n);return{sources:u.sources,transformations:[...u.transformations.filter(c=>c!=="projection"),`ordinal:${t.kind==="ordinal-encode"?"encode":"decode"}`]}}const o=[...t.input?[t.input]:[],...t.inputs??[]].map(u=>Ft(u,e,r,n)),i={sources:o.flatMap(({sources:u})=>u),transformations:o.flatMap(({transformations:u})=>u)},s=n.get(t.operator),a=new Set([...t.property?[t.property]:[],...s.dependencies??[],...Er(t.query)]);return{sources:[...i.sources,...[...a].filter(u=>!i.sources.some(c=>c.propertyName===u)).map(u=>Li(e,r,u))],transformations:[...i.transformations.filter(u=>u!=="projection"),`operator:${t.operator}`]}};function Er(t){if(!t)return[];const e=[];for(const[r,n]of Object.entries(t))if((r==="$and"||r==="$or")&&Array.isArray(n))for(const o of n)typeof o=="object"&&o!==null&&!Array.isArray(o)&&e.push(...Er(o));else r==="$expr"&&Pi(n)?e.push(...n.properties):r.startsWith("$")||e.push(r);return e}const Ve=t=>t.kind==="window"?[...Ve(t.input),...t.partitionBy.flatMap(Ve)]:t.kind==="cumulative"?[...Ve(t.input),...t.partitionBy.flatMap(Ve),...t.orderBy.flatMap(({expression:e})=>Ve(e))]:t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?Ve(t.input):t.kind==="operator"?[...Er(t.query),...t.input?Ve(t.input):[],...(t.inputs??[]).flatMap(Ve)]:[],Di=(t,e,r,n=De(),o)=>{if(t.subplans){const s=t.subplans.map(u=>Di(u,e,r,n,o)),a=new Map;for(const u of s){u.source.connectionId&&a.set(u.source.connectionId,u.source.provider);for(const c of u.source.connections??[])a.set(c.connectionId,c.provider)}return{source:{schemaId:e.id,schemaName:e.name,physicalTable:s.map(({source:u})=>u.physicalTable).join(", "),provider:r.kind,connections:[...a].map(([u,c])=>({connectionId:u,provider:c}))},outputs:t.projections.map(({name:u})=>{const c=s.flatMap(({outputs:p})=>p.filter(l=>l.name===u));return{name:u,sources:c.flatMap(({sources:p})=>p),transformations:[...new Set([...c.flatMap(({transformations:p})=>p),"compose"])]}}),filters:s.flatMap(({filters:u})=>u)}}const i=t.connectionId&&o?o(t.connectionId):r;return{source:{schemaId:e.id,schemaName:e.name,physicalTable:[t.source,...(t.enrichmentJoins??[]).map(({source:s})=>s)].filter(Boolean).join(", "),provider:i.kind,...t.connectionId?{connectionId:t.connectionId}:{}},outputs:t.projections.map(s=>({name:s.name,...Ft(s.expression,t,e,n)})),filters:[...new Set([...Er(t.query),...t.projections.flatMap(({expression:s})=>Ve(s))])].map(s=>Li(t,e,s))}},Ie=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.version=="string"&&(typeof t.schema=="string"||typeof t.from=="object"),Ld=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,Ci=t=>{const e=Ld.exec(t);if(!e)return;const r=Number(e[1]),n=Number(e[2]),o=Number(e[3]??0);if(!(r>23||n>59||o>59))return{hour:r,minute:n,second:o}},ki=t=>{const e=t.freshness;if(e){if(e.mode==="ttl"){if(!Number.isInteger(e.ttlSeconds)||e.ttlSeconds<=0)throw new d("INVALID_SOURCE_FRESHNESS","TTL freshness requires a positive integer ttlSeconds");return}if(e.mode==="daily"){if(!Ci(e.expireAt))throw new d("INVALID_SOURCE_FRESHNESS","Daily freshness expireAt must use HH:mm or HH:mm:ss");if(e.timeZone)try{new Intl.DateTimeFormat("en-US",{timeZone:e.timeZone}).format()}catch{throw new d("INVALID_SOURCE_FRESHNESS",`Invalid freshness timeZone: ${e.timeZone}`)}}}},Dd=new Set(["second","minute","hour","day","week","month","quarter","year"]),Dn=t=>typeof t=="string"&&Dd.has(t),Cn=(t,e=ye())=>Dn(t)||typeof t=="object"&&t!==null&&!Array.isArray(t)&&e.some(r=>{const n=r.mappingGranularity;return n!==void 0&&n.kind===t.kind&&n.isGranularity(t)});class kn{#e=new Map;plugins;constructor(e=[],r=[]){this.plugins=ye(r);for(const n of e)this.register(n)}register(e){for(const s of this.plugins){const a=s.schemaMapping?.validate?.(e);if(a)throw new d("INVALID_SCHEMA_MAPPING_PLUGIN",`Schema mapping is rejected by plugin ${s.name}: ${a}`,{plugin:s.name,reason:a})}if(!e.schemaId)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping schemaId must not be empty");if(!e.source)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping source must not be empty");if(e.sourceSql!==void 0&&e.sourceSql.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping sourceSql must not be empty");if(e.id!==void 0&&!e.id)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping id must not be empty");if(e.connectionId.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping connectionId must not be empty");if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping priority must be finite");if("dimensions"in e)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping dimensions is removed; declare time granularity on property mapping items");const r=new Set,n=new Set;for(const s of e.enrichments??[]){if(!s.id||r.has(s.id))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment ids must be non-empty and unique");if(!s.source||s.source===e.source||n.has(s.source))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment sources must be non-empty and unique");if(s.sourceSql!==void 0&&s.sourceSql.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment sourceSql must not be empty");if(s.on.length===0||s.on.some(({baseColumn:a,targetColumn:u})=>!a||!u))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichments require non-empty baseColumn/targetColumn keys");if(s.temporal?.kind==="point"&&!s.temporal.pointColumn)throw new d("INVALID_SCHEMA_MAPPING","Point-in-time Schema mapping enrichments require pointColumn");ki(s),r.add(s.id),n.add(s.source)}for(const s of e.mappings??[]){if(s.granularity!==void 0&&(s.mappingType!=="property"||!Cn(s.granularity,this.plugins)))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping granularity requires a property item and a supported physical granularity");if(s.mappingType==="property"&&(!s.sourceColumn||!s.propertyTarget?.length))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping property items require sourceColumn and propertyTarget");if(s.mappingType==="predItem"&&(!s.sourceColumn||!s.predItem?.operator||typeof s.predItem.pred!="string"))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping PredItem items require sourceColumn and predItem operator/pred");if(s.sourceRef!==void 0&&(s.mappingType!=="property"||!r.has(s.sourceRef)))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping sourceRef requires a property item and a registered enrichment id")}ki(e);const o=this.#e.get(e.schemaId)??[],i=e.id??e.source;if(o.some(s=>s.connectionId===e.connectionId&&((s.id??s.source)===i||s.source===e.source)))throw new d("SCHEMA_MAPPING_ALREADY_REGISTERED",`Schema mapping is already registered: ${e.schemaId}:${e.connectionId}:${i}`,{schemaId:e.schemaId,connectionId:e.connectionId,mappingId:i});return this.#e.set(e.schemaId,[...o,e]),this}get(e,r){const n=this.list(e),o=r===void 0?n:n.filter(s=>s.connectionId===r);if(o.length===0)throw new d("SCHEMA_MAPPING_CONNECTION_NOT_FOUND",`Schema ${e} has no mapping on connection ${r}`,{schemaId:e,connectionId:r});if(o.length===1)return o[0];const i=o.filter(s=>(s.mappings??[]).length===0);if(i.length===1)return i[0];throw new d("SCHEMA_MAPPING_AMBIGUOUS",r===void 0?`Schema ${e} has multiple mappings and requires LogicForm-based selection`:`Schema ${e} has multiple mappings on connection ${r} and requires LogicForm-based selection`,{schemaId:e,...r===void 0?{}:{connectionId:r},mappingIds:o.map(s=>s.id??s.source)})}list(e){const r=this.#e.get(e);if(!r||r.length===0)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${e}`,{schemaId:e});return r}findSource(e,r,n){return this.#e.get(e)?.find(o=>o.source===r&&(n===void 0||o.connectionId===n))}}const Cd=t=>{if(t.tablePath?.trim())return t.tablePath;const e=[t.physicalDatabase,t.physicalSchema,t.physicalTable].filter(r=>!!r?.trim());if(e.length>0)return e.join(".");if(t.sourceSql?.trim())return t.sourceSql;throw new d("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping ${t.id} has no physical source`)},kd=(t,e=[])=>{const r=ye(e);if(!t.schemaSid||!t.datasourceSid)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping requires schemaSid and datasourceSid");if(t.enabled===!1)throw new d("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping is disabled: ${t.id}`);if("dimensions"in t)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping dimensions is removed; set granularity on property items");const n=[];for(const o of t.mappings){if(o.granularity!==void 0&&(o.mappingType!=="property"||!Cn(o.granularity,r)))throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires a property item and a supported physical granularity");if(o.mappingType==="property"){if(!o.sourceColumn||!o.propertyTarget?.length){if(o.granularity!==void 0)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires sourceColumn and propertyTarget");continue}n.push(o);continue}o.mappingType==="predItem"&&(!o.sourceColumn||!o.predItem?.operator||typeof o.predItem.pred!="string"||n.push(o))}return{id:String(t.id),schemaId:t.schemaSid,connectionId:t.datasourceSid,source:Cd(t),...t.sourceSql?{sourceSql:t.sourceSql}:{},...t.enrichments?{enrichments:t.enrichments}:{},mappings:n}};class Ui{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new d("INVALID_SEMANTIC_RULE","Semantic rule name must not be empty");if(this.#e.has(e.name))throw new d("SEMANTIC_RULE_ALREADY_REGISTERED",`Semantic rule is already registered: ${e.name}`,{rule:e.name});return this.#e.set(e.name,e),this}resolveProjection(e){return[...this.#e.values()].reduce((r,n)=>n.resolveProjection?.({...e,outputProperty:r})?.outputProperty??r,e.outputProperty)}resolveQuery(e){return[...this.#e.values()].reduce((r,n)=>n.resolveQuery?.({...e,...r?{query:r}:{}})??r,e.query)}rules(){return[...this.#e.values()]}}const Mi=(t=[])=>new Ui([...ye(t).flatMap(e=>e.plannerSemantics??[])]);ue.extend(Do),ue.extend(Mt),ue.extend(ar);const _t=["second","minute","hour","day","week","month","quarter","year"],Ud=new Set(["$second","$minute","$hour","$day","$week","$month","$quarter","$year"]),Md="YYYY-MM-DD HH:mm:ss",St=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),qd=(t,e)=>t==="week"?e==="week":e==="week"?_t.indexOf(t)<=_t.indexOf("day"):_t.indexOf(t)<=_t.indexOf(e),qi=(t,e,r)=>{if(typeof t!="string")return"second";const n=ue(t,Md,!0);if(!n.isValid())return"second";for(const o of[..._t].reverse()){const i=o==="week"?n.startOf("isoWeek"):n.startOf(o),s=o==="week"?n.endOf("isoWeek"):n.endOf(o),a=e==="lower"?r?i:s:r?s:i;if(n.isSame(a.millisecond(0),"second"))return o}return"second"},ji=t=>{if(!t||typeof t!="object"||Array.isArray(t))return["second"];const e=Object.entries(t);return e.length===0?["second"]:e.flatMap(([r,n])=>Ud.has(r)?[r.slice(1)]:r==="$weekday"?["day"]:r==="$and"||r==="$or"?Array.isArray(n)?n.flatMap(ji):["second"]:r==="$gte"||r==="$gt"?[qi(n,"lower",r==="$gte")]:r==="$lte"||r==="$lt"?[qi(n,"upper",r==="$lte")]:["second"])},jd=(t,e,r)=>{if(e.primal_type==="date"){if(t.operator){const n=r.get(t.operator).groupedSourceTimeGranularity?.({pred:t,property:e});if(n&&_t.includes(n))return n}return e.granularity??"day"}},xd=(t,e,r,n,o=ye(),i=De(o))=>{const s=r.mappings??[],a=s.filter(g=>g.granularity!==void 0),u={schema:e,mapping:r,...n?{resolveSchema:n}:{}};if(a.some(g=>!Cn(g.granularity,o)))return"physical granularity is not supported by the active plugins";if(a.find(g=>Dn(g.granularity)&&!g.propertyTarget?.every($=>St(e,$)?.primal_type==="date")))return"physical time granularity requires mapped date Properties";for(const g of a)for(const $ of o){const w=$.mappingGranularity;if(!w||!w.isGranularity(g.granularity))continue;const S=w.validateItem?.(g,u);if(S)return S}if(!(a.length>0))return;const l=g=>s.find($=>$.mappingType==="property"&&$.propertyTarget?.some(w=>St(e,w)?.id===g.id)),f=(g,$,w="filterOrGroup")=>{const S=St(e,g);if(!S)return`property is not available: ${g}`;const E=l(S);if(!E&&!(w==="operand"&&s.some(A=>A.mappingType==="predItem"&&typeof A.predItem?.pred=="string"&&St(e,A.predItem.pred)?.id===S.id)))return`property is not available on grouped source: ${g}`;if(w==="filterOrGroup"&&S.primal_type==="number"&&S.type!=="category"&&S.type!=="ID")return`measure cannot be used as a grouped source dimension: ${g}`;if(S.primal_type==="date"&&(!E?.granularity||!Dn(E.granularity)||!qd(E.granularity,$??S.granularity??"day")))return`time dimension ${g} is too coarse for ${$}`};function m(g){if(g)for(const[$,w]of Object.entries(g)){if(w===void 0)continue;if($==="$and"||$==="$or"){if(!Array.isArray(w))return"unsupported dimension query";for(const A of w){const R=m(A);if(R)return R}continue}if($==="$expr"){if(typeof w!="object"||w===null||Array.isArray(w))return"unsupported expression query";const A=w.pred;if(typeof A!="object"||A===null||Array.isArray(A))return"unsupported expression query";const R=y(A);if(R)return R;continue}if($.startsWith("$"))return"unsupported dimension query";const S=St(e,$);if(!S)return`dimension property is not available: ${$}`;const E=S.primal_type==="date"?ji(w):[void 0];for(const A of E){const R=f($,A);if(R)return R}}}function y(g){const $=m(g.query);if($)return $;const w=Array.isArray(g.pred)?g.pred:g.pred===void 0?[]:[g.pred];for(const S of w){const E=typeof S=="string"?f(S,void 0,"operand"):y(S);if(E)return E}}const h=m(t.query);if(h)return h;if(!t.preds?.length)return"grouped source requires an aggregating PredItem";for(const g of t.preds){const $=y(g);if($)return $;if(typeof g.pred!="string"||!g.operator||!i.get(g.operator).supportsGroupedSourceRollup)return`PredItem ${g.operator??"(projection)"} cannot be rolled up from a grouped source`}for(const g of t.groupby??[]){if(typeof g.pred!="string")return"computed groupby is not covered by the grouped source";const $=St(e,g.pred);if(!$)return`groupby property is not available: ${g.pred}`;if(g.operator!==void 0&&!i.get(g.operator).supportsGroupedSourceGroupby&&!o.some(S=>S.mappingGranularity?.supportsGroupby?.(g)))return`computed groupby is not covered: ${g.pred}`;const w=f(g.pred,jd(g,$,i));if(w)return w}for(const g of o){const $=g.mappingGranularity?.candidateReason?.(t,u);if($)return $}};function Yt(t){return[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Yt(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Yt(e)):[]]}const Un=t=>t.id??t.source,_r=(t,e)=>{if(t===e)return!0;if(t instanceof Date||e instanceof Date)return t instanceof Date&&e instanceof Date&&t.getTime()===e.getTime();if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((o,i)=>_r(o,e[i]));if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const r=Object.entries(t),n=e;return r.length===Object.keys(n).length&&r.every(([o,i])=>Object.prototype.hasOwnProperty.call(n,o)&&_r(i,n[o]))},It=t=>{if(!t)return[];const e=[];for(const[r,n]of Object.entries(t))if(n!==void 0){if(r==="$or")return;if(r==="$and"){if(!Array.isArray(n))return;for(const o of n){const i=It(o);if(!i)return;e.push(...i)}continue}if(r==="$expr"){if(typeof n!="object"||n===null||Array.isArray(n))return;const o=n.pred;if(typeof o!="object"||o===null||Array.isArray(o))return;const i=Yt(o);if(i.length===0)return;e.push(...i.map(s=>({property:s,condition:{$expr:n}})));continue}if(r.startsWith("$"))return;e.push({property:r,condition:n})}return e},Mn=(t,e,r)=>{if(!t)return;const n={};for(const[o,i]of Object.entries(t))if(i!==void 0){if(o==="$and"&&Array.isArray(i)){const s=i.map(a=>Mn(a,e,r)).filter(a=>a!==void 0);s.length>0&&(n[o]=s);continue}o!=="$or"&&e.some(s=>Sr(r,s.property,o)&&_r(s.condition,i))||(n[o]=i)}return Object.keys(n).length>0?n:void 0},nt=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),Sr=(t,e,r)=>e===r||nt(t,e)?.id===nt(t,r)?.id&&nt(t,e)!==void 0&&nt(t,r)!==void 0,be=(t,e,r)=>Ir(t,e,r)?.column,Ir=(t,e,r)=>{const n=nt(e,r);if(!n)return;const o=(t.mappings??[]).find(i=>i.mappingType==="property"&&i.propertyTarget?.some(s=>Sr(e,s,r)));return o?.sourceColumn?{column:o.sourceColumn,...o.sourceRef?{sourceRef:o.sourceRef}:{}}:(t.mappings??[]).some(i=>i.mappingType==="property")?void 0:{column:n.id}},qn=(t,e,r)=>!(t.mappings??[]).some(n=>n.mappingType==="property")||be(t,e,r)!==void 0,xi=(t,e,r)=>{if(!t||!(e.mappings??[]).some(i=>i.mappingType==="property"))return;const n=It(t);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:i})=>!qn(e,r,i));return o?`query property is not available: ${o.property}`:void 0},Bd=(t,e,r,n,o)=>{if(t.match.schema!==void 0&&t.match.schema!==n)return!1;const i=typeof e.pred=="string"?nt(r,e.pred):void 0,s=nt(r,t.match.pred),a=typeof e.pred=="string"&&Sr(r,e.pred,t.match.pred)&&!!(i&&s);if(e.operator!==t.match.operator||!a||Array.isArray(e.pred)||e.args&&Object.keys(e.args).length>0)return!1;const u=It(t.match.query);return u!==void 0&&u.every(c=>o.some(p=>Sr(r,p.property,c.property)&&_r(p.condition,c.condition)))},Vd=(t,e,r,n,o,i=De(o))=>{const s=(r.mappings??[]).flatMap(g=>{if(g.mappingType!=="predItem"||!g.sourceColumn||!g.predItem||!g.predItem.operator||typeof g.predItem.pred!="string")return[];const $=g.predItem,w=$.operator,S=$.pred;return!w||typeof S!="string"?[]:[{match:{operator:w,pred:S,...$.schema?{schema:$.schema}:{},...$.query?{query:$.query}:{}},column:g.sourceColumn}]}),a=(r.mappings??[]).some(g=>g.mappingType==="property");if(s.length===0&&!a){const g={schema:e,mapping:r,...n?{resolveSchema:n}:{}};for(const $ of o??[]){const w=$.schemaMapping?.candidateReason?.(t,g);if(w)return w}return{mapping:r,logicform:t,predRewrites:[],priority:r.priority??0,specificity:0}}const u=It(t.query);if(!u&&s.length>0)return"query contains $or or another unsupported logical expression";const c=ne(t),p=[],l=[];for(const[g,$]of(t.preds??[]).entries()){const w=It($.query);if(!w&&s.length>0)return`PredItem ${g} query contains an unsupported logical expression`;if(s.length>0){const E=[...u??[],...w??[]],A=s.filter(M=>Bd(M,$,e,$.schema??e.id,E));if(A.length===0)return`PredItem ${g} is not mapped`;if(A.length>1)return`PredItem ${g} matches multiple mapping rules`;const R=A[0],O=It(R.match.query)??[];l.push(...O);const D=c.preds?.[g];if(D){const M=Mn(D.query,O,e);M?D.query=M:delete D.query}p.push({predIndex:g,column:R.column});continue}const S=Yt($).find(E=>!qn(r,e,E));if(S)return`PredItem ${g} property is not available: ${S}`}const f=Mn(c.query,l,e);f?c.query=f:delete c.query;const m=xi(c.query,r,e);if(m)return m;for(const[g,$]of(c.preds??[]).entries()){const w=xi($.query,r,e);if(w)return`PredItem ${g} ${w}`}for(const g of c.groupby??[]){const w=Yt(g).find(S=>!qn(r,e,S));if(w)return`groupby property is not available: ${w}`}const y=xd(c,e,r,n,o,i);if(y)return y;const h={schema:e,mapping:r,...n?{resolveSchema:n}:{}};for(const g of o??[]){const $=g.schemaMapping?.candidateReason?.(c,h);if($)return $}return{mapping:r,logicform:c,predRewrites:p,priority:r.priority??0,specificity:p.length}},vd=(t,e,r,n={})=>{const o=n.plugins?ye(n.plugins):r.plugins,i=n.operators??De(n.plugins),s=[],a=[];for(const l of r.list(e.id)){const f=Vd(t,e,l,n.resolveSchema,o,i);typeof f=="string"?a.push({mappingId:Un(l),reason:f}):s.push(f)}if(s.length===0){const l=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id;throw new d("QUERY_NOT_COVERED_BY_DATA_SOURCE",`Schema\u300C${l}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u4E0D\u652F\u6301\u6B64\u95EE\u9898\u3002\u5982\u9700\u652F\u6301\uFF0C\u9700\u8981\u63A5\u5165\u660E\u7EC6\u5C42\u6570\u636E\uFF0C\u8BF7\u8054\u7CFB\u6570\u636E\u7BA1\u7406\u5458\u3002`,{schemaId:e.id,requiredDataLayer:"detail",rejectedMappings:a})}const u=n.preferredConnectionId===void 0?[]:s.filter(({mapping:l})=>l.connectionId===n.preferredConnectionId),p=(u.length>0?u:s).reduce((l,f)=>f.priority>l.priority||f.priority===l.priority&&f.specificity>l.specificity?f:l);for(const l of s){if(l===p)continue;let f;u.length>0&&l.mapping.connectionId!==n.preferredConnectionId?f=`connection ${l.mapping.connectionId} does not match preferred connection ${n.preferredConnectionId}`:l.priority<p.priority?f=`priority ${l.priority} is lower than selected priority ${p.priority}`:l.specificity<p.specificity?f=`specificity ${l.specificity} is lower than selected specificity ${p.specificity}`:f="priority and specificity tie; an earlier registered mapping was selected",a.push({mappingId:Un(l.mapping),reason:f})}return{mapping:p.mapping,logicform:p.logicform,predRewrites:p.predRewrites,selection:{schemaId:e.id,selectedMappingId:Un(p.mapping),rejectedMappings:a}}},Ht=(t,e)=>!!(t.operator&&e.get(t.operator).kind==="component"),Qt=(t,e)=>Ht(t,e)?!0:t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Qt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Qt(r,e)),Bi=(t,e)=>t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Qt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Qt(r,e)),Vi=t=>t.name??(typeof t.pred=="string"?t.pred:void 0),Fd=(t,e)=>{const r=t.preds??[];if(!r.some(m=>!Ht(m,e)&&Bi(m,e)))return;const n=new Set([...r.map(({name:m})=>m).filter(m=>!!m),...(t.groupby??[]).map(Vi).filter(m=>!!m)]);let o=0;const i=()=>{let m;do m=`__nested_component_input_${o}__`,o+=1;while(n.has(m));return n.add(m),m},s=[],a=m=>{const y=i();return s.push(typeof m=="string"?{pred:m,name:y}:{...ne(m),name:y}),y},u=m=>{if(m.query)throw new d("UNSUPPORTED_COMPONENT_NESTING","An operator above a component cannot define pred.query; apply the query inside a materialized input");const y=ne(m);return Array.isArray(m.pred)?y.pred=m.pred.map(h=>typeof h=="string"||!Qt(h,e)||Ht(h,e)?a(h):u(h)):m.pred&&typeof m.pred=="object"&&(y.pred=Ht(m.pred,e)?a(m.pred):u(m.pred)),y},c=r.map(m=>{const y=m.name;if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every projection to have a name");return!Ht(m,e)&&Bi(m,e)?{...u(m),name:y}:(s.push({...ne(m),name:y}),{pred:y,name:y})}),p=ne(t);p.preds=s,delete p.having,delete p.sort,delete p.limit,delete p.limitBy,delete p.page,delete p.output,delete p.representation;const l=(t.groupby??[]).map(m=>{const y=Vi(m);if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every groupby projection to have a name");return{pred:y,name:y}}),f=ne(t);return f.from=p,f.preds=[...l,...c],delete f.query,delete f.groupby,delete f.entity_id,delete f.propertyResolve,f},Yd=(t,e)=>`result:${t}:${e.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,vi=(t,e)=>{const r=(t.columnProperties??[]).map(n=>({...n,id:n.name}));return{id:Yd(t.schemaId,t.columnProperties??[]),name:`${e.name} result`,type:e.type,temporalSemantics:"normal",properties:r}},Fi=(t,e)=>({...vi(t,e),id:e.id,name:e.name,type:e.type}),jn=t=>{if(!t.name)throw new d("MISSING_PRED_NAME","Planner requires every normalized PredItem to have a name");return t.name},br=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?br(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:br(e)):[]],xn=(t,e)=>({...t,...typeof t.pred=="string"?{pred:e(t.pred)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:xn(t.pred,e)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(r=>typeof r=="string"?e(r):xn(r,e))}:{}}),Yi=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(o=>Yi(o,e))];if(r==="$expr"&&typeof n=="object"&&n!==null&&!Array.isArray(n)){const o=n.pred;if(typeof o=="object"&&o!==null&&!Array.isArray(o))return[r,{...n,pred:xn(o,e)}]}return[r.startsWith("$")?r:e(r),n]})),Bn=(t,e,r)=>{const n=new Set(r),o=(i,s)=>{if(!(Ie(i)||i===null)){if(Array.isArray(i)){i.forEach(a=>o(a,s));return}if(typeof i=="object"){Object.entries(i).forEach(([a,u])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(a)||o(u,a)});return}if(!(s&&["$exists","$regex","$contains","$startsWith","$length"].includes(s))&&(typeof i!="string"||!n.has(i)))throw new d("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${e} does not contain value: ${JSON.stringify(i)}`,{property:e,value:i})}};o(t)},Hi=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(i=>Hi(i,e))];if(r==="$expr")throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const o=e.find(({name:i})=>i===r)?.comparable;return o&&Bn(n,r,o.values),[r,o?{kind:"ordinal-query",comparable:o,condition:n}:n]})),Hd=(t,e,r)=>{if(!e.udf)return{};const o=e.udf.sql.includes("$TS")?t.properties.find(({type:i})=>i==="timestamp")?.id:void 0;return{sql:e.udf.sql,...o?{timestampColumn:o}:{},...o&&r?{timestampQualifier:r}:{}}},Qi=t=>t.sql?{kind:"property-sql",schemaId:t.schemaId,property:t.property,propertyId:t.column,sql:t.sql,qualifier:t.qualifier,...t.timestampColumn?{timestampColumn:t.timestampColumn}:{},...t.timestampQualifier?{timestampQualifier:t.timestampQualifier}:{}}:{kind:"column",...t},Gi=(t,e,r={})=>({name:t,type:e.type,primal_type:e.primal_type,isArray:e.isArray,...e.description!==void 0?{description:e.description}:{},...e.ref?{ref:e.ref}:{},...e.comparable?{comparable:e.comparable}:{},...r}),bt=(t,e,r,n,o,i,s,a,u="projection")=>{const c=jn(t);if(u==="groupby"&&t.query)throw new d("GROUPBY_QUERY_NOT_ALLOWED","A groupby expression cannot define pred.query");if(!t.operator){if(typeof t.pred!="string")throw new d("PRED_PROPERTY_REQUIRED","A projection must reference a property");const E=r(t.pred);return{expression:Qi(E.field),outputProperty:Gi(E.reference,E.property),sourceProperty:E.property,sourceField:E.field}}const p=e.get(t.operator);if(u==="groupby"&&p.kind!=="scalar")throw new d("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(u==="groupby"&&!p.toSQL)throw new d("JAVASCRIPT_OPERATOR_NOT_ALLOWED_IN_GROUPBY",`JavaScript-only operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(p.planInput&&typeof t.pred!="string")throw new d("OPERATOR_DIRECT_PROPERTY_REQUIRED",`${t.operator} requires a direct property pred`);const l=p.planInput&&typeof t.pred=="string"?p.planInput({reference:t.pred,args:t.args??{},schema:s,...a?{resolveSchema:a}:{}}):void 0,f=l?.reference??t.pred,m=l?.args??t.args??{},y=f&&typeof f=="object"&&!Array.isArray(f)?bt(f,e,r,n,o,i,s,a,u):typeof f=="string"?bt({pred:f,name:f},e,r,n,o,i,s,a,u):void 0,h=Array.isArray(f)?f.map(E=>bt(typeof E=="string"?{pred:E,name:E}:E,e,r,n,o,i,s,a,u)):[];if(p.requiresProperty!==!1&&!y&&h.length===0)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a property`);const g=c,$=p.getOutputProperty?.({name:g,...y?.sourceProperty?{property:y.sourceProperty}:{},...y?{inputProperty:{...y.outputProperty,name:g}}:{},...h.length>0?{inputProperties:h.map(({outputProperty:E})=>E)}:{},args:m}),w=$?.description??p.description??y?.outputProperty.description,S={...$??(y?Gi(g,y.outputProperty,{isArray:!1}):{name:g,type:"number",primal_type:"number",isArray:!1}),...w!==void 0?{description:w}:{}};if(p.planExpression){const E=p.planExpression({pred:t,...y?{input:y.expression,inputProperty:y.outputProperty}:{},inputs:h.map(({expression:A})=>A),args:m,resolveKey:o,getOperator:A=>e.get(A),planQuery:i});if(E)return{expression:E,outputProperty:S,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}}if(p.kind==="window"){if(!y||h.length>0||t.query)throw new d("INVALID_WINDOW_OPERATOR_INPUT",`${t.operator} requires exactly one nested pred and does not accept pred.query`);const E=t.args?.direction??"desc";if(E!=="asc"&&E!=="desc")throw new d("INVALID_WINDOW_ARGS",`${t.operator} direction must be asc or desc`);const A=t.args?.partitionBy??[];if(!Array.isArray(A)||A.some(R=>typeof R!="string"))throw new d("INVALID_WINDOW_ARGS",`${t.operator} partitionBy must be an array of groupby names`);return{expression:{kind:"window",function:p.windowFunction,input:y.expression,partitionBy:A.map(R=>n(String(R))),direction:E==="asc"?"ASC":"DESC"},outputProperty:S}}return{expression:{kind:"operator",operator:t.operator,args:m,...t.query?{query:i(t.query)}:{},...y?{input:y.expression}:{},...h.length>0?{inputs:h.map(({expression:E})=>E)}:{},...y?.sourceProperty?{property:y.sourceProperty.name,column:y.sourceProperty.id}:{},...y?.sourceField?{qualifier:y.sourceField.qualifier,schemaId:y.sourceField.schemaId}:{}},outputProperty:S,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}},Qd=(t,e,r,n,o,i,s,a,u,c,p,l=t)=>{const f=jn(t),m=typeof t.pred=="string"?t.pred:void 0,y=!c||!m?r:w=>{const S=r(w);return w===m?{...S,field:{...S.field,column:c}}:S},h=p?{...t,operator:p}:t,g=bt(h,e,y,n,o,i,s,a),$=u?.resolveProjection({pred:l,schema:s,...g.sourceProperty?{sourceProperty:g.sourceProperty}:{},outputProperty:{...g.outputProperty,name:f},...l.operator?{operator:e.get(l.operator)}:{}})??{...g.outputProperty,name:f};return{name:f,expression:g.expression,outputProperty:$}},Gd=t=>{const e=new Set;for(const r of t){if(r.name==="_id")throw new d("RESERVED_OUTPUT_NAME","Output name _id is reserved for executor-owned row identity");if(e.has(r.name))throw new d("DUPLICATE_OUTPUT_NAME",`Duplicate output name: ${r.name}`);e.add(r.name)}},Vn=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cannot plan nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n},Wd=(t,e,r,n,o,i)=>{if(e.length<2)throw new d("COMPOSITION_REQUIRES_MULTIPLE_BRANCHES","A cross-Schema plan requires at least two branches");const s=e.map(h=>Te(h,Vn(h,r,i),n,o,i)),a=s[0]?.groupBy.map(({name:h})=>h)??[];for(const h of s){const g=h.groupBy.map(({name:$})=>$);if(g.length!==a.length||g.some(($,w)=>$!==a[w]))throw new d("INCOMPATIBLE_COMPOSITION_GROUPBY","All composed LogicForm objects must have the same groupby output names in the same order",{expected:a,received:g});if(h.rowIdentity.kind!==(a.length>0?"group":"singleton"))throw new d("UNSTABLE_COMPOSITION_IDENTITY","Composed LogicForm objects must be grouped or aggregate to a singleton row")}const u=[],c=[],p=new Map;s.forEach((h,g)=>{h.projections.forEach(($,w)=>{const S=a.includes($.name),E=p.get($.name);if(E!==void 0&&!S)throw new d("DUPLICATE_COMPOSITION_OUTPUT",`Composed LogicForm objects produce the same output: ${$.name}`,{name:$.name,childIndexes:[E,g]});if(E!==void 0)return;p.set($.name,g),u.push({name:$.name,expression:{kind:"column",property:$.name,column:$.name}});const A=h.columnProperties?.[w];A&&c.push(A)})});const l=new Set(u.map(({name:h})=>h)),f=Object.entries(t.sort??{}).map(([h,g])=>{if(!l.has(h))throw new d("INVALID_SORT",`Sort field is not an output: ${h}`);const $=c.find(w=>w.name===h);return{name:h,direction:g===1?"ASC":"DESC",...$?.comparable?{comparable:$.comparable}:{},...$?.comparable?{expression:{kind:"column",property:h,column:h}}:{}}}),m=t.limitBy===void 0||a.length<2?void 0:{count:t.limitBy,partitionBy:a.slice(0,-1),orderBy:f.length>0?f:(()=>{const h=a.at(-1)??"",g=c.find($=>$.name===h);return[{name:h,direction:"ASC",...g?.comparable?{comparable:g.comparable}:{}}]})()},y=t.limitBy!==void 0&&a.length<2?{kind:"rows",page:1,pageSize:t.limitBy}:t.limit===void 0?void 0:t.limit>0&&t.limit<1?{kind:"ratio",page:t.page??1,ratio:t.limit}:{kind:"rows",page:t.page??1,pageSize:t.limit};return{schemaId:r.id,source:"",subplans:s,fields:Object.fromEntries(u.map(({name:h})=>[h,h])),projections:u,columnProperties:c,groupBy:u.filter(({name:h})=>a.includes(h)),...t.having?{having:Hi(t.having,c)}:{},orderBy:f,rowIdentity:a.length>0?{kind:"group",names:a,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"},...m?{groupLimit:m}:{},...y?{pagination:y}:{}}},Te=(t,e,r=De(),n=new kn,o={})=>{const i=[...new Set((t.preds??[]).map(_=>_.schema).filter(_=>!!(_&&_!==e.id)))];if(i.length>0){const _=t.propertyResolve??{},I=[e.id,...i].map(b=>{const{having:T,sort:P,limit:Y,limitBy:K,page:re,...L}=t,ee=J=>{let B=J;try{B=de(e,J,o.resolveSchema).canonicalName}catch{}return _[b]?.[J]??_[b]?.[B]??J};return{...L,schema:b,preds:(t.preds??[]).filter(J=>(J.schema??e.id)===b).map(({schema:J,...B})=>B),...b===e.id||!t.query?{}:{query:Yi(t.query,ee)},...b!==e.id&&t.groupby?{groupby:t.groupby.map(J=>({...J,...typeof J.pred=="string"?{pred:ee(J.pred)}:{}}))}:{}}});return Wd(t,I,e,r,n,o)}const s=Fd(t,r);if(s)return Te(s,e,r,n,o);for(const _ of t.preds??[]){if(!_.operator)continue;const I=r.get(_.operator).rewriteLogicform?.({logicform:t,schema:e,getOperator:b=>r.get(b)});if(I)return Te(I,e,r,n,o)}const a=o.semanticRegistry??Mi(o.plugins);if(t.from){const _=Vn(t.from,e,o),I=Te(t.from,_,r,n,o),b=Fi(I,e),T={...t};delete T.from,T.schema??=b.id;const P=Te(T,b,r,n,o),Y=new Set(P.projections.map(({name:B})=>B)),K=I.rowIdentity.kind==="group"&&I.rowIdentity.names.every(B=>Y.has(B))||I.rowIdentity.kind==="singleton"?I.rowIdentity:{kind:"generated"},re=I.groupBy.map(({name:B})=>B).filter(B=>Y.has(B)),L=re.at(-1),ee=I.columnProperties?.find(B=>B.name===L),J=t.limitBy!==void 0&&re.length>0?{count:t.limitBy,partitionBy:re.slice(0,-1),orderBy:P.orderBy.length>0?P.orderBy:re.slice(-1).map(B=>({name:B,direction:"ASC",...ee?.comparable?{comparable:ee.comparable}:{}}))}:void 0;return{...P,source:I.source,sourcePlan:I,sourceLogicform:t.from,rowIdentity:K,...J?{groupLimit:J}:{}}}if(!t.schema)throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const u=vd(t,e,n,{operators:r,...o.plugins?{plugins:o.plugins}:{},...o.preferredConnectionId?{preferredConnectionId:o.preferredConnectionId}:{},...o.resolveSchema?{resolveSchema:o.resolveSchema}:{}});o.onSchemaMappingSelection?.(u.selection),t=u.logicform;const c=new Map(u.predRewrites.map(({predIndex:_,column:I})=>[_,I])),p=fi(e,o.plugins),l=Hc(t,e,o.plugins),f=a.resolveQuery({logicform:t,schema:e,...t.query?{query:t.query}:{}}),m=l?.rewriteQuery?l.rewriteQuery(f):f,y=e.id,h=new Map,g=new Map,$=new Map,w=new Map,S=_=>{const I=g.get(_);if(I)return I.alias;const b=u.mapping.enrichments?.find(Y=>Y.id===_);if(!b)throw new d("SCHEMA_MAPPING_ENRICHMENT_NOT_FOUND",`Schema mapping enrichment is not registered: ${_}`,{schemaId:e.id,mappingId:u.mapping.id,enrichmentId:_});const T=`__enrichment_${_}`,P=b.temporal?(()=>{if(!p)throw new d("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${_} requires an entity with interval semantics`,{schemaId:e.id,enrichmentId:_});const Y=Ir(u.mapping,e,p.start.name),K=Ir(u.mapping,e,p.end.name);if(!Y||!K)throw new d("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${_} requires mapped interval boundary columns`,{schemaId:e.id,enrichmentId:_});if(Y.sourceRef||K.sourceRef)throw new d("POINT_ENRICHMENT_INTERVAL_MUST_USE_BASE_SOURCE",`Point enrichment ${_} requires interval boundaries on the base source`,{schemaId:e.id,enrichmentId:_});return{kind:"point-in-interval",pointSide:"target",pointColumn:b.temporal.pointColumn,intervalSide:"source",startColumn:Y.column,endColumn:K.column}})():void 0;return g.set(_,{kind:"enrichment-left",id:_,source:b.source,...b.sourceSql?{sourceSql:b.sourceSql}:{},alias:T,baseAlias:y,keys:b.on,...P?{temporalCondition:P}:{}}),T},E=_=>{const I=de(e,_,o.resolveSchema);let b=y,T=u.mapping;const P=[];for(const L of I.relations){P.push(L.property.name);const ee=P.join("_"),J=ee,B=n.get(L.targetSchema.id,u.mapping.connectionId);if(T=B,!h.has(ee)){const he=L.targetSchema.properties.filter(({type:Q})=>Q==="ID"),[ce]=he;if(he.length!==1||!ce)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${L.targetSchema.id} must contain exactly one ID property`,{schemaId:L.targetSchema.id,count:he.length});const Ce=L.sourceSchema.id===e.id?u.mapping:n.get(L.sourceSchema.id,u.mapping.connectionId),pt=be(Ce,L.sourceSchema,L.property.name)??L.property.id,ft=be(B,L.targetSchema,ce.name)??ce.id,Xe=L.sourceSchema.properties.find(({type:Q})=>Q==="timestamp"),Qe=L.targetSchema.properties.find(({type:Q})=>Q==="timestamp"),Ee=Yc(L.sourceSchema,L.targetSchema,o.plugins),N=Xe?be(Ce,L.sourceSchema,Xe.name)??Xe.id:void 0,x=Qe?be(B,L.targetSchema,Qe.name)??Qe.id:void 0,G=Ee?.kind==="date-bucket-equal"?{kind:"date-bucket-equal",sourceColumn:be(Ce,L.sourceSchema,Ee.sourceTimestamp.name)??Ee.sourceTimestamp.id,targetColumn:be(B,L.targetSchema,Ee.targetTimestamp.name)??Ee.targetTimestamp.id,sourceGranularity:Ee.sourceTimestamp.granularity??"day",targetGranularity:Ee.targetTimestamp.granularity??"day"}:Ee?.kind==="point-in-interval"?{kind:"point-in-interval",pointSide:"source",pointColumn:be(Ce,L.sourceSchema,Ee.point.name)??Ee.point.id,intervalSide:"target",startColumn:be(B,L.targetSchema,Ee.start.name)??Ee.start.id,endColumn:be(B,L.targetSchema,Ee.end.name)??Ee.end.id}:void 0,U=L.property.isArray?ee:void 0;U&&!$.has(U)&&$.set(U,{path:U,sourceAlias:b,sourceColumn:pt,...L.property.udf?{sourceSql:L.property.udf.sql,...N?{sourceTimestampColumn:N}:{}}:{},alias:`__array_${ee}`}),h.set(ee,{kind:"left",path:ee,sourceAlias:b,sourceColumn:pt,...L.property.udf?{sourceSql:L.property.udf.sql,...N?{sourceTimestampColumn:N}:{}}:{},targetSchemaId:L.targetSchema.id,targetConnectionId:B.connectionId,targetSource:B.source,...B.sourceSql?{targetSourceSql:B.sourceSql}:{},targetAlias:J,targetColumn:ft,...U?{sourceArrayExpansionPath:U}:{},...ce.udf?{targetSql:ce.udf.sql,...x?{targetTimestampColumn:x}:{}}:{},...G?{temporalCondition:G}:{}})}b=J}const Y=Ir(T,I.schema,I.property.name);if(I.relations.length>0&&Y?.sourceRef)throw new d("RELATION_MAPPING_ENRICHMENT_UNSUPPORTED",`Related property ${I.canonicalName} cannot be sourced from a mapping enrichment`,{schemaId:I.schema.id,property:I.property.name});const K=Y?.sourceRef?S(Y.sourceRef):b,re={schemaId:I.schema.id,property:I.property.name,propertyId:I.property.id,column:Y?.column??I.property.id,qualifier:K,...I.property.isArray?{isArray:!0}:{},...I.property.comparable?{comparable:I.property.comparable}:{},...Hd(I.relations.length>0?e:I.schema,I.property,y)};return w.set(I.canonicalName,re),{reference:I.canonicalName,schema:I.schema,property:I.property,field:re}},A=_=>{if(_)for(const[I,b]of Object.entries(_))if((I==="$and"||I==="$or")&&Array.isArray(b))for(const T of b)typeof T=="object"&&T!==null&&!Array.isArray(T)&&A(T);else if(I==="$expr"&&typeof b=="object"&&b!==null&&!Array.isArray(b)){const T=b.pred;typeof T=="object"&&T!==null&&!Array.isArray(T)&&br(T).forEach(E)}else I.startsWith("$")||E(I)},R=_=>{if(Ie(_)){const I=Vn(_,e,o),b=Te(_,I,r,n,o);if(b.projections.length!==1)throw new d("SUBQUERY_SINGLE_COLUMN_REQUIRED",`Query LogicForm must output exactly one column, received ${b.projections.length}`,{schemaId:_.schema,projectionCount:b.projections.length});return{kind:"logicform-subquery",plan:b}}return Array.isArray(_)?_.map(R):typeof _!="object"||_===null||_ instanceof Date?_:Object.fromEntries(Object.entries(_).map(([I,b])=>[I,R(b)]))},O=_=>Object.fromEntries(Object.entries(_).map(([I,b])=>{if((I==="$and"||I==="$or")&&Array.isArray(b))return[I,b.map(P=>O(P))];if(I==="$expr"){if(typeof b!="object"||b===null||Array.isArray(b))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const P=b;if(typeof P.pred!="object"||P.pred===null||Array.isArray(P.pred)||!Object.prototype.hasOwnProperty.call(P,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const Y=P.pred,K=bt(Y,r,E,z,q,O,e,o.resolveSchema,"groupby");if(K.outputProperty.isArray)throw new d("ARRAY_EXPRESSION_QUERY_UNSUPPORTED","$expr must produce a scalar value");const re=R(P.condition);return K.outputProperty.comparable&&Bn(re,Y.name??Y.operator??"$expr",K.outputProperty.comparable.values),[I,{kind:"expression-query",expression:K.expression,condition:K.outputProperty.comparable?{kind:"ordinal-query",comparable:K.outputProperty.comparable,condition:re}:re,properties:br(Y)}]}if(typeof b=="object"&&b!==null&&!Array.isArray(b)){const Y=Object.entries(b).find(([K])=>$t(K,o.plugins));if(Y){const[K,re]=Y,L=$t(K,o.plugins);if(!L)throw new Error(`Query Operator disappeared: ${K}`);const ee=E(I),J=L.plan(re,{schema:ee.schema,property:ee.property,connectionId:u.mapping.connectionId,...o.resolveSchema?{resolveSchema:o.resolveSchema}:{},resolveMapping:(B,he)=>n.get(B,he)});return[I,{[K]:{kind:"query-operator",operator:K,value:J.value,definition:L,...J.sources?{sources:J.sources}:{}}}]}}const T=I.startsWith("$")?void 0:E(I).property.comparable;return[I,T?{kind:"ordinal-query",comparable:T,condition:R(b)}:R(b)]})),D=_=>{const I=T=>{if(!T||typeof T!="object")return!1;if(Array.isArray(T))return T.some(I);const P=T;return Object.prototype.hasOwnProperty.call(P,"$and")||Object.values(P).some(I)};if(I(_))return _;const b=new Set(Object.keys(_).flatMap(T=>{if(T.startsWith("$"))return[];const P=de(e,T,o.resolveSchema);return P.relations.length===1&&P.property.type==="ID"?[P.relations[0]?.property.name]:[]}));return Object.fromEntries(Object.entries(_).map(([T,P])=>{if(T==="$and"||T==="$or")return Array.isArray(P)?[T,P.map(ce=>typeof ce=="object"&&ce!==null&&!Array.isArray(ce)?D(ce):ce)]:[T,P];if(T.startsWith("$"))return[T,P];const Y=de(e,T,o.resolveSchema);if(Y.relations.length===0)return[T,P];if(Y.property.udf?.sql.includes("$TS")===!0||Y.relations.some(({property:ce})=>ce.udf?.sql.includes("$TS")===!0))return[T,P];const re=Y.relations.map(({property:ce})=>ce.name).join("_");if(h.has(re))return[T,P];const[L]=Y.relations;if(!L)return[T,P];if(b.has(L.property.name))return[T,P];const ee=L.property.name,J=Y.canonicalName.slice(ee.length+1),B=L.targetSchema.properties.find(({type:ce})=>ce==="ID");if(!B)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${L.targetSchema.id} must contain an ID property`,{schemaId:L.targetSchema.id});if(Y.relations.length===1&&Y.property.id===B.id)return[L.property.id,P];const he={version:t.version,schema:L.targetSchema.id,query:J?{[J]:P}:{},preds:[{pred:B.name,name:B.name}]};return[L.property.id,{$in:he}]}))},M=(t.groupby??[]).map(_=>{const I=jn(_);_.operator&&r.get(_.operator).validateGroupby?.({pred:_});const b=bt(_,r,E,z,q,O,e,o.resolveSchema,"groupby");let T=b.expression;if(l?.group===_&&(T={kind:"column",schemaId:e.id,property:l.property.name,propertyId:l.property.id,column:"__period_start",qualifier:"__periods"}),b.sourceProperty?.isArray&&b.sourceField){const P=`groupby:${I}`;$.set(P,{path:P,sourceAlias:b.sourceField.qualifier,sourceColumn:b.sourceField.column,...b.sourceField.sql?{sourceSql:b.sourceField.sql,...b.sourceField.timestampColumn?{sourceTimestampColumn:b.sourceField.timestampColumn}:{}}:{},alias:`__array_group_${$.size}`}),T={kind:"array-element",schemaId:b.sourceField.schemaId,property:b.sourceProperty.name,expansionPath:P}}return{name:I,expression:T,outputProperty:{...b.outputProperty,name:I,isArray:!1}}});function z(_){const I=(t.groupby??[]).findIndex(T=>typeof T.pred=="string"&&T.pred===_||T.name===_),b=I>=0?M[I]:void 0;if(!b)throw new d("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${_}`);return b.expression}function q(_){const I=(t.groupby??[]).findIndex(T=>typeof T.pred=="string"&&T.pred===_||T.name===_),b=I>=0?M[I]:void 0;return b?b.expression:Qi(E(_).field)}const v=_=>{_.operator&&r.get(_.operator).validatePlan?.({pred:_,groupByNames:M.map(({name:I})=>I),resolveGroupName:I=>{const b=(t.groupby??[]).findIndex(T=>T.name===I||typeof T.pred=="string"&&T.pred===I);return b>=0?M[b]?.name:void 0},getOperator:I=>r.get(I)}),_.pred&&typeof _.pred=="object"&&!Array.isArray(_.pred)&&v(_.pred);for(const I of Array.isArray(_.pred)?_.pred:[])v(typeof I=="string"?{pred:I}:I)};for(const _ of t.preds??[])v(_);const k=[...M,...(t.preds??[]).map((_,I)=>{const b=l?.rewritePred?.(_)??_;return Qd(b,r,E,z,q,O,e,o.resolveSchema,a,c.get(I),ei(b,t.groupby??[],e,o.resolveSchema)?"$min":void 0,_)})],H=_=>Object.fromEntries(Object.entries(_).map(([I,b])=>{if((I==="$and"||I==="$or")&&Array.isArray(b))return[I,b.map(P=>H(P))];if(I==="$expr")throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const T=k.find(({name:P})=>P===I)?.outputProperty.comparable;return T&&Bn(b,I,T.values),[I,T?{kind:"ordinal-query",comparable:T,condition:R(b)}:R(b)]})),ae=m?D(m):void 0;A(ae);const te=_=>{A(_.query),_.pred&&typeof _.pred=="object"&&!Array.isArray(_.pred)&&te(_.pred);for(const I of Array.isArray(_.pred)?_.pred:[])te(typeof I=="string"?{pred:I}:I)};for(const _ of t.preds??[])te(_);if(k.length===0)throw new d("EMPTY_PROJECTION","LogicForm must contain preds or groupby");Gd(k);const me=new Set(k.map(({name:_})=>_)),C=M.length>0?{kind:"group",names:M.map(({name:_})=>_),separator:"_",nullLabel:"\u7A7A\u503C"}:k.every(({expression:_})=>_.kind==="column"||_.kind==="property-sql")||k.some(({expression:_})=>_.kind==="property-sql"&&e.properties.some(({id:I,type:b})=>b==="ID"&&I===_.propertyId))?(()=>{const _=e.properties.find(({type:I})=>I==="ID");return _&&(o.canUsePropertyRowIdentity?.(e,_)??!0)?{kind:"property",column:_.id,internalName:"_id"}:{kind:"generated"}})():{kind:"singleton"},F=Object.entries(t.sort??{}).map(([_,I])=>{if(!me.has(_))throw new d("INVALID_SORT",`Sort field is not an output: ${_}`);const b=k.find(T=>T.name===_);return{name:_,direction:I===1?"ASC":"DESC",...b?.outputProperty.comparable?{comparable:b.outputProperty.comparable,expression:b.expression}:{}}}),Z=t.limit===void 0?void 0:t.limit>0&&t.limit<1?{kind:"ratio",page:t.page??1,ratio:t.limit}:{kind:"rows",page:t.page??1,pageSize:t.limit},j=t.limitBy===void 0?void 0:{count:t.limitBy,partitionBy:M.slice(0,-1).map(({name:_})=>_),orderBy:F.length>0?F:(()=>{const _=M.at(-1);return[{name:_?.name??"",direction:"ASC",..._?.outputProperty.comparable?{comparable:_.outputProperty.comparable,expression:_.expression}:{}}]})()},le=w.size===0&&h.size===0&&g.size===0&&$.size===0&&!ae&&M.length===0&&k.length>0&&k.every(({expression:_})=>_.kind==="operator"&&_.operator==="$constant");return{schemaId:e.id,source:le?"":u.mapping.source,...le?{}:{connectionId:u.mapping.connectionId},...!le&&u.mapping.sourceSql?{sourceSql:u.mapping.sourceSql}:{},mappingId:u.mapping.id??u.mapping.source,sourceAlias:y,fields:{...ac(e),...Object.fromEntries(e.properties.flatMap(_=>{const I=be(u.mapping,e,_.name);return I?[[_.name,I],[_.id,I]]:[]}))},fieldReferences:Object.fromEntries(w),joins:[...h.values()],enrichmentJoins:[...g.values()],arrayExpansions:[...$.values()],...l?{periodSource:{alias:"__periods",labelColumn:"__period_start",asOfColumn:"__as_of",sourceAlias:y,periods:l.periods,match:l.source.kind==="interval"?{kind:"interval",startColumn:be(u.mapping,e,l.source.start.name)??l.source.start.id,endColumn:be(u.mapping,e,l.source.end.name)??l.source.end.id}:{kind:"latest",lookupAlias:"__period_lookup",timestampColumn:be(u.mapping,e,l.source.timestamp.name)??l.source.timestamp.id}}}:{},projections:k.map(({name:_,expression:I})=>({name:_,expression:I})),columnProperties:k.map(({outputProperty:_})=>_),groupBy:M.map(({name:_,expression:I})=>({name:_,expression:I})),...ae?{query:O(ae)}:{},...t.having?{having:H(t.having)}:{},orderBy:F,rowIdentity:le?{kind:"singleton"}:C,...Z?{pagination:Z}:{},...j?{groupLimit:j}:{}}};class zd{provider;parameterOffset;values=[];constructor(e,r=0){this.provider=e,this.parameterOffset=r}add(e){const r=this.parameterOffset+this.values.length;return this.values.push(e),this.provider.parameter(r,e)}get nextParameterOffset(){return this.parameterOffset+this.values.length}append(e){this.values.push(...e)}}const Kd=(t,e)=>{const r=e.split(".");if(r.some(n=>n.length===0))throw new d("INVALID_SOURCE",`Invalid physical source: ${e}`);return r.map(n=>t.quoteIdentifier(n)).join(".")},Rr=(t,e,r)=>r===void 0?Kd(t,e):`(${r.trim().replace(/;+\s*$/,"")})`,Gt=(t,e,r,n,o)=>{const i=Si(t,[],String,`Property ${e} udf.sql`);if(!i.includes("$TS"))return i;if(!n)throw new d("PROPERTY_UDF_TIMESTAMP_REQUIRED",`Property ${e} udf.sql uses $TS but its evaluation context has no timestamp Property`,{property:e});const s=(o?`${r.quoteIdentifier(o)}.`:"")+r.quoteIdentifier(n);return i.replace(/\$TS/g,s)},Me=(t,e,r,n=!1,o,i,s,a)=>{const u=(c,p)=>n&&p?`${e.quoteIdentifier(p)}.${e.quoteIdentifier(c)}`:e.quoteIdentifier(c);switch(t.kind){case"array-element":if(!a)throw new d("ARRAY_EXPANSION_UNAVAILABLE","Array expansion compiler is unavailable");return a(t.expansionPath);case"column":return u(t.column,t.qualifier);case"property-sql":return Gt(t.sql,t.property,e,t.timestampColumn,n?t.timestampQualifier??t.qualifier:void 0);case"window":{if(Re(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Window operators cannot consume a JavaScript operator");const c=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>Me(f,e,r,n,o,i,s,a)).join(", ")} `:"",p=Me(t.input,e,r,n,o,i,s,a);return`${t.function==="rank"?"RANK":"ROW_NUMBER"}() OVER (${c}ORDER BY ${p} ${t.direction})`}case"cumulative":{if(Re(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Cumulative expressions cannot consume a JavaScript operator");const c=Me(t.input,e,r,n,o,i,s,a),p=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>Me(f,e,r,n,o,i,s,a)).join(", ")} `:"",l=t.orderBy.map(f=>`${Me(f.expression,e,r,n,o,i,s,a)} ${f.direction}`).join(", ");return`${e.aggregateFunction(t.function,c)} OVER (${p}ORDER BY ${l} ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`}case"ordinal-encode":{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","Ordinal encoding requires a value binder");return`CASE ${t.comparable.values.map((p,l)=>`WHEN ${Me(t.input,e,r,n,o,i,s,a)} = ${i(p)} THEN ${t.comparable.direction*l}`).join(" ")} END`}case"ordinal-decode":{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","Ordinal decoding requires a value binder");return`CASE ${t.comparable.values.map((p,l)=>`WHEN ${Me(t.input,e,r,n,o,i,s,a)} = ${t.comparable.direction*l} THEN ${i(p)}`).join(" ")} END`}case"operator":{const c=r.get(t.operator);if(c.kind==="component")throw new d("COMPONENT_OPERATOR_REQUIRES_EXECUTOR",`${t.operator} must be compiled through the executor component pipeline`);if(c.toSQL&&(t.input&&Re(t.input,r)||t.inputs?.some(f=>Re(f,r))))throw new d("UNSUPPORTED_MIXED_OPERATOR",`${t.operator} cannot consume a JavaScript operator in SQL`);let p=t.input?Me(t.input,e,r,n,o,i,s,a):t.column?u(t.column,t.qualifier):void 0;const l=t.inputs?.map(f=>Me(f,e,r,n,o,i,s,a));if(t.query&&Object.keys(t.query).length>0){if(c.kind!=="aggregate")throw new d("OPERATOR_QUERY_REQUIRES_AGGREGATION",`Pred query is only supported by aggregation operators: ${t.operator}`);if(!o)throw new d("INVALID_OPERATOR_QUERY","Operator query compiler is unavailable");p=`CASE WHEN ${o(t.query)} THEN ${p??"1"} END`}if(c.requiresProperty!==!1&&!p)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a column`);return c.toSQL?c.toSQL({sql:{aggregateFunction:e.aggregateFunction.bind(e),quoteIdentifier:e.quoteIdentifier.bind(e),concat:e.concat.bind(e),substring:e.substring.bind(e),stringLength:e.stringLength.bind(e),datePart:e.datePart.bind(e),dateBucket:e.dateBucket.bind(e),dateShift:e.dateShift.bind(e),...e.datePeriodBoundary?{datePeriodBoundary:e.datePeriodBoundary.bind(e)}:{},...e.scalarExtremum?{scalarExtremum:e.scalarExtremum.bind(e)}:{},value:(f,m)=>{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","SQL value binder is unavailable");const y=i(f);return m&&e.castValue?e.castValue(y,m):y},condition:(f,m)=>{if(!s)throw new d("SQL_CONDITION_UNAVAILABLE","SQL condition compiler is unavailable");return s(f,m)}},...p?{expression:p,column:p}:{},...l?{expressions:l}:{},args:t.args}):p??"NULL"}}},Re=(t,e)=>t.kind==="window"?Re(t.input,e)||t.partitionBy.some(r=>Re(r,e)):t.kind==="cumulative"?Re(t.input,e)||t.partitionBy.some(r=>Re(r,e))||t.orderBy.some(r=>Re(r.expression,e)):t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?Re(t.input,e):t.kind==="operator"&&(!e.get(t.operator).toSQL&&!!e.get(t.operator).evaluate||(t.input?Re(t.input,e):!1)||(t.inputs?.some(r=>Re(r,e))??!1)),Jd=(t,e)=>t.sourceSql?Gt(t.sourceSql,t.sourceColumn,e,t.sourceTimestampColumn,t.sourceAlias):`${e.quoteIdentifier(t.sourceAlias)}.${e.quoteIdentifier(t.sourceColumn)}`,Wi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).some(e=>e.startsWith("$")),zi={$second:"second",$minute:"minute",$hour:"hour",$weekday:"weekday",$day:"day",$week:"week",$month:"month",$quarter:"quarter",$year:"year"},Wt=(t,e,r,n,o,i,s,a)=>{if(Ti(r)){if(r.operator!==e)throw new d("INVALID_PLUGIN_QUERY",`Query Operator plan does not match ${e}`);const l=r.definition??s(e);if(!l)throw new d("UNSUPPORTED_QUERY_OPERATOR",`Query Operator is not registered: ${e}`);return l.compile(r.value,{field:t,provider:o,bind:f=>n.add(f),renderSource:(f,m)=>Rr(o,f,m)})}if(s(e))throw new d("INVALID_PLUGIN_QUERY",`${e} query was not planned`,{operator:e});if(e==="$eq"&&r===null)return`${t} IS NULL`;if(e==="$ne"&&r===null)return`${t} IS NOT NULL`;const p={$eq:"=",$ne:"<>",$gt:">",$gte:">=",$lt:"<",$lte:"<="}[e];if(p){const l=Et(r)?`(${i(r)})`:n.add(r);return`${t} ${p} ${l}`}if(e==="$in"||e==="$nin"){const l=e==="$in"?"IN":"NOT IN";if(Et(r))return`${t} ${l} (${i(r)})`;if(!Array.isArray(r))throw new d("INVALID_QUERY_VALUE",`${e} requires an array or query LogicForm`);if(r.length===0)return e==="$in"?"0 = 1":"1 = 1";const f=r.filter(Et);if(f.length>0){if(f.length!==r.length)throw new d("MIXED_SUBQUERY_VALUES",`${e} cannot mix query LogicForm objects and literal values`);return`${t} ${l} (${f.map(i).join(" UNION ALL ")})`}const m=r.map(y=>n.add(y)).join(", ");return`${t} ${l} (${m})`}if(Et(r))throw new d("UNSUPPORTED_SUBQUERY_OPERATOR",`Query LogicForm is not supported by ${e}`);if(e==="$exists")return`${t} IS ${r?"NOT ":""}NULL`;if(e==="$contains")return`${t} LIKE ${n.add(`%${String(r)}%`)}`;if(e==="$startsWith"){if(typeof r!="string")throw new d("INVALID_QUERY_VALUE","$startsWith requires a string");return`${t} LIKE ${n.add(`${r}%`)}`}if(e==="$regex"){if(typeof r!="string"||a!==void 0&&typeof a!="string")throw new d("INVALID_QUERY_VALUE","$regex requires a string pattern and args.options must be a string");return o.regex(t,n.add(r),a)}throw new d("UNSUPPORTED_QUERY_OPERATOR",`Unsupported query operator: ${e}`)},vn=(t,e)=>{if(!(typeof t=="number"&&Number.isFinite(t))){if(Array.isArray(t)){if(t.every(r=>typeof r=="number"&&Number.isFinite(r)))return;throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}if(typeof t=="object"&&t!==null&&!Et(t)){for(const[r,n]of Object.entries(t)){if(!r.startsWith("$"))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`);if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new d("INVALID_QUERY_VALUE",`${r} requires an array`);n.forEach(o=>vn(o,e))}else if(r==="$in"||r==="$nin"){if(!Array.isArray(n)||n.some(o=>typeof o!="number"||!Number.isFinite(o)))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}else if(typeof n!="number"||!Number.isFinite(n))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}return}throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}},ot=(t,e,r,n,o,i)=>{if(Td(e)){const c=()=>`CASE ${e.comparable.values.map((m,y)=>`WHEN ${t} = ${r.add(m)} THEN ${e.comparable.direction*y}`).join(" ")} END`,p=new Set(["$gt","$gte","$lt","$lte"]),l=f=>typeof f!="object"||f===null||Array.isArray(f)?ot(t,f,r,n,o,i):Object.entries(f).filter(([m])=>m!=="args").map(([m,y])=>(m==="$and"||m==="$or")&&Array.isArray(y)?`(${y.map(l).join(m==="$and"?" AND ":" OR ")})`:p.has(m)?Wt(c(),m,e.comparable.direction*e.comparable.values.indexOf(String(y)),r,n,o,i):Wt(t,m,y,r,n,o,i)).join(" AND ");return l(e.condition)}if(Array.isArray(e))return Wt(t,"$in",e,r,n,o,i);if(!Wi(e))return Wt(t,"$eq",e,r,n,o,i);const s=[],a=e.args;if(a!==void 0){if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_QUERY_VALUE","Query args.options must be a string");const c=a.options;if(c!==void 0&&typeof c!="string")throw new d("INVALID_QUERY_VALUE","Query args.options must be a string")}const u=a?.options;for(const[c,p]of Object.entries(e))if(c==="$and"||c==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${c} requires an array`);const l=p.map(f=>ot(t,f,r,n,o,i));s.push(`(${l.join(c==="$and"?" AND ":" OR ")})`)}else zi[c]?(vn(p,c),s.push(ot(n.datePart(t,zi[c]),p,r,n,o,i))):c==="$length"?(vn(p,"$length"),s.push(ot(n.stringLength(t),p,r,n,o,i))):c!=="args"&&s.push(Wt(t,c,p,r,n,o,i,c==="$regex"?u:void 0));if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},Ki=(t,e,r,n)=>{if(!n.arrayContains)throw new d("ARRAY_CONDITION_UNSUPPORTED",`Provider ${n.kind} does not support array conditions`);const o=n.arrayContains.bind(n),i=a=>o(t,r.add(a));if(Array.isArray(e))return`(${e.map(i).join(" OR ")})`;if(!Wi(e))return i(e);const s=[];for(const[a,u]of Object.entries(e))if(a==="$and"||a==="$or"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(p=>Ki(t,p,r,n));s.push(`(${c.join(a==="$and"?" AND ":" OR ")})`)}else if(a==="$eq")s.push(i(u));else if(a==="$ne")s.push(`NOT (${i(u)})`);else if(a==="$in"||a==="$nin"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(i),p=c.length===0?a==="$in"?"0 = 1":"1 = 1":c.join(a==="$in"?" OR ":" AND NOT ");s.push(a==="$nin"&&c.length>0?`NOT (${c.join(" OR ")})`:`(${p})`)}else if(a==="$exists")s.push(`${t} IS ${u?"NOT ":""}NULL`);else if(a!=="args")throw new d("UNSUPPORTED_ARRAY_QUERY_OPERATOR",`Unsupported array query operator: ${a}`);if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},Rt=(t,e,r,n,o,i,s,a)=>{const u=[];for(const[c,p]of Object.entries(t)){if(c==="$and"||c==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${c} requires an array`);const f=p.map(m=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_QUERY_VALUE",`${c} items must be query objects`);return Rt(m,e,r,n,o,i,s,a)});u.push(`(${f.join(c==="$and"?" AND ":" OR ")})`);continue}if(c==="$expr"){if(!Pi(p))throw new d("INVALID_EXPRESSION_QUERY","$expr query was not planned");u.push(ot(s(p.expression),p.condition,n,o,i,a));continue}const l=e(c);u.push(r(c)?Ki(l,p,n,o):ot(l,p,n,o,i,a))}return u.join(" AND ")},Nr=(t,e,r,n,o)=>t.orderBy.map(i=>{const s=e.quoteIdentifier(i.name),a=`${n?`${n}.`:""}${s}`,u=i.comparable,c=!n&&o&&i.expression?o(i.expression):a;return`${u?`CASE ${u.values.map((l,f)=>`WHEN ${c} = ${r.add(l)} THEN ${u.direction*f}`).join(" ")} END`:a} ${i.direction}`}).join(", "),Fn=(t,e)=>{let r=t;for(;e.has(r);)r=`_${r}`;return r},Ji=(t,e,r,n)=>e.concat(t.flatMap((o,i)=>[...i>0?[`'${r.replaceAll("'","''")}'`]:[],`CASE WHEN ${o} IS NULL THEN '${n.replaceAll("'","''")}' ELSE ${e.stringify(o)} END`])),Xi=(t,e,r,n,o)=>{const i=new Set(e.projections.map(({name:D})=>D)),s="__sdb_page_source",a="__sdb_page",u=n.quoteIdentifier(s),c=n.quoteIdentifier(a),p=Fn("__sdb_row_number",i),l=Fn("__sdb_total_rows",i),f=n.quoteIdentifier(p),m=n.quoteIdentifier(l),y=Nr(e,n,o,u),h=y?`ORDER BY ${y}`:"",g=`CEIL(${m} * ${r.ratio})`,$=r.page-1,w=r.page,E=[...e.projections.map(({name:D})=>D),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(D=>`${c}.${n.quoteIdentifier(D)}`).join(", "),A=Nr(e,n,o,c),R=`SELECT ${u}.*, ROW_NUMBER() OVER (${h}) AS ${f}, COUNT(*) OVER () AS ${m} FROM ${n.tableAlias(`(${t})`,s)}`;let O=`SELECT ${E} FROM ${n.tableAlias(`(${R})`,a)} WHERE ${c}.${f} > ${$} * ${g} AND ${c}.${f} <= ${w} * ${g}`;return A&&(O+=` ORDER BY ${A}`),O},Zi=(t,e,r,n)=>{const o=e.groupLimit;if(!o)return t;const i="__sdb_limit_by_source",s="__sdb_limit_by_ranked",a=r.quoteIdentifier(i),u=r.quoteIdentifier(s),c=new Set(e.projections.map(({name:w})=>w)),p=Fn("__sdb_limit_by_row_number",c),l=r.quoteIdentifier(p),f=o.partitionBy.map(w=>`${a}.${r.quoteIdentifier(w)}`).join(", "),m=o.orderBy.map(({name:w,direction:S,comparable:E})=>{const A=`${a}.${r.quoteIdentifier(w)}`;return`${E?`CASE ${E.values.map((O,D)=>`WHEN ${A} = ${n.add(O)} THEN ${E.direction*D}`).join(" ")} END`:A} ${S}`}).join(", "),h=[...e.projections.map(({name:w})=>w),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(w=>`${u}.${r.quoteIdentifier(w)}`).join(", "),g=`PARTITION BY ${f} ORDER BY ${m}`,$=`SELECT ${a}.*, ROW_NUMBER() OVER (${g}) AS ${l} FROM ${r.tableAlias(`(${t})`,i)}`;return`SELECT ${h} FROM ${r.tableAlias(`(${$})`,s)} WHERE ${u}.${l} <= ${o.count}`},ge=(t,e,r=De(),n=0)=>{const o=new zd(e,n),i=A=>$t(A);if(t.subplans){const A=t.projections.map(({name:v})=>v),R=new Set(t.groupBy.map(({name:v})=>v)),O=t.subplans.map((v,k)=>{const H=ge(v,e,r,o.nextParameterOffset);o.append(H.parameters);const ae=`__composition_child_${k}`,te=e.quoteIdentifier(ae),me=new Set(v.projections.map(({name:C})=>C));return{aliasName:ae,alias:te,available:me,sql:H.sql}}),D=O[0];if(!D)throw new d("INVALID_COMPOSITION","Composition has no children");const M=A.map(v=>{const k=O.filter(te=>te.available.has(v)),H=k[0]??D;return`${R.has(v)&&k.length>1?`COALESCE(${k.map(te=>`${te.alias}.${e.quoteIdentifier(v)}`).join(", ")})`:`${H.alias}.${e.quoteIdentifier(v)}`} AS ${e.quoteIdentifier(v)}`}),z=O.map(v=>`${v.alias} AS (${v.sql})`);let q;if(t.rowIdentity.kind==="group"){const k=e.quoteIdentifier("__composition_keys"),H=e.quoteIdentifier("_id");z.push(`${k} AS (${O.map(ae=>`SELECT ${H} FROM ${ae.alias}`).join(" UNION ")})`),M.push(`${k}.${H} AS ${H}`),q=`WITH ${z.join(", ")} SELECT ${M.join(", ")} FROM ${k}`;for(const ae of O)q+=` LEFT JOIN ${ae.alias} ON ${k}.${H} = ${ae.alias}.${H}`}else{q=`WITH ${z.join(", ")} SELECT ${M.join(", ")} FROM ${D.alias}`;for(const v of O.slice(1))q+=` LEFT JOIN ${v.alias} ON 1 = 1`}if(t.having&&Object.keys(t.having).length>0){const v="__composition_having",k=e.quoteIdentifier(v),H=new Set(A),ae=Rt(t.having,te=>{if(!H.has(te))throw new d("INVALID_HAVING",`Having field is not an output: ${te}`);return`${k}.${e.quoteIdentifier(te)}`},()=>!1,o,e,()=>{throw new d("SUBQUERY_IN_COMPOSITION_HAVING_UNSUPPORTED","A composed result having condition cannot contain a LogicForm subquery")},()=>{throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names")},i);q=`SELECT ${k}.* FROM ${e.tableAlias(`(${q})`,v)} WHERE ${ae}`}if(t.groupLimit&&(q=Zi(q,t,e,o)),t.pagination?.kind==="ratio")q=Xi(q,t,t.pagination,e,o);else if(t.orderBy.length>0&&(q+=` ORDER BY ${Nr(t,e,o)}`),t.pagination?.kind==="rows"){const v=(t.pagination.page-1)*t.pagination.pageSize;q=e.paginate(q,t.pagination.pageSize,v)}return{sql:q,parameters:o.values}}const s=A=>{if(A.plan.projections.some(({expression:O})=>Re(O,r)))throw new d("JAVASCRIPT_OPERATOR_IN_SUBQUERY","A query LogicForm cannot use a JavaScript-only operator");const R=ge(A.plan.rowIdentity.kind==="property"||A.plan.rowIdentity.kind==="group"?{...A.plan,rowIdentity:{kind:"generated"}}:A.plan,e,r,o.nextParameterOffset);return o.append(R.parameters),R.sql},a=(t.joins?.length??0)>0||(t.enrichmentJoins?.length??0)>0,u=(t.arrayExpansions?.length??0)>0,c=a||u||t.sourcePlan!==void 0||t.sourceSql!==void 0||t.periodSource!==void 0,p=new Map,l=(t.arrayExpansions??[]).map(A=>{if(!e.expandArray)throw new d("ARRAY_EXPANSION_UNSUPPORTED",`Provider ${e.kind} does not support array expansion`);const R=e.expandArray(Jd(A,e),A.alias,"value");return p.set(A.path,R.valueExpression),R}),f=A=>{const R=t.fieldReferences?.[A];if(R?.sql)return Gt(R.sql,R.property,e,R.timestampColumn,c?R.timestampQualifier??R.qualifier:void 0);if(R&&c)return`${e.quoteIdentifier(R.qualifier)}.${e.quoteIdentifier(R.column)}`;const O=t.fields[A];if(!O)throw new d("PROPERTY_NOT_FOUND",`Query property not found: ${A}`);return e.quoteIdentifier(O)},m=A=>Me(A,e,r,c,R=>Rt(R,f,O=>t.fieldReferences?.[O]?.isArray===!0,o,e,s,m,i),R=>o.add(R),(R,O)=>ot(R,O,o,e,s,i),R=>{const O=p.get(R);if(!O)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${R}`);return O}),y=t.projections.map(A=>`${m(A.expression)} AS ${e.quoteIdentifier(A.name)}`),h=t.rowIdentity.kind==="property"?`${c&&t.sourceAlias?`${e.quoteIdentifier(t.sourceAlias)}.`:""}${e.quoteIdentifier(t.rowIdentity.column)} AS ${e.quoteIdentifier(t.rowIdentity.internalName)}`:t.rowIdentity.kind==="group"?(()=>{const A=t.rowIdentity.names.map(R=>{const O=t.groupBy.find(D=>D.name===R)??t.projections.find(D=>D.name===R);if(!O)throw new d("GROUP_IDENTITY_OUTPUT_NOT_FOUND",`Group identity output not found: ${R}`);return m(O.expression)});return`${Ji(A,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`})():void 0,g=[...y,...h?[h]:[]].join(", "),$=t.sourcePlan?(()=>{const A=ge(t.sourcePlan,e,r,o.nextParameterOffset);return o.append(A.parameters),`(${A.sql})`})():t.source?Rr(e,t.source,t.sourceSql):"",w=c&&t.sourceAlias?e.tableAlias($,t.sourceAlias):$;let S=`SELECT ${g}`;if(t.periodSource){const A=t.periodSource,R=A.periods.map(({label:k,asOf:H},ae)=>{const te=o.add(k),me=o.add(H);return ae===0?`SELECT ${te} AS ${e.quoteIdentifier(A.labelColumn)}, ${me} AS ${e.quoteIdentifier(A.asOfColumn)}`:`SELECT ${te}, ${me}`}).join(" UNION ALL "),O=e.tableAlias(`(${R})`,A.alias),D=e.tableAlias($,A.sourceAlias),M=e.quoteIdentifier(A.alias),z=e.quoteIdentifier(A.sourceAlias),q=`${M}.${e.quoteIdentifier(A.asOfColumn)}`,v=A.match.kind==="interval"?(()=>{const k=`${z}.${e.quoteIdentifier(A.match.startColumn)}`,H=`${z}.${e.quoteIdentifier(A.match.endColumn)}`;return`${k} <= ${q} AND (${H} > ${q} OR ${H} IS NULL)`})():(()=>{const k=e.tableAlias($,A.match.lookupAlias),H=e.quoteIdentifier(A.match.lookupAlias),ae=`${z}.${e.quoteIdentifier(A.match.timestampColumn)}`,te=`${H}.${e.quoteIdentifier(A.match.timestampColumn)}`,me=`SELECT ${e.aggregateFunction("max",te)} FROM ${k} WHERE ${te} <= ${q}`;return`${ae} = (${me})`})();S+=` FROM ${O} LEFT JOIN ${D} ON ${v}`,t.query&&Object.keys(t.query).length>0&&(S+=` AND ${Rt(t.query,f,k=>t.fieldReferences?.[k]?.isArray===!0,o,e,s,m,i)}`)}else w&&(S+=` FROM ${w}`);for(const A of l)S+=` ${A.joinSql}`;for(const A of t.enrichmentJoins??[]){const R=e.quoteIdentifier(A.alias),O=e.quoteIdentifier(A.baseAlias);S+=` LEFT JOIN ${e.tableAlias(Rr(e,A.source,A.sourceSql),A.alias)}`;const D=A.keys.map(({baseColumn:M,targetColumn:z})=>`${O}.${e.quoteIdentifier(M)} = ${R}.${e.quoteIdentifier(z)}`);if(A.temporalCondition?.kind==="point-in-interval"){const M=H=>H==="source"?O:R,z=`${M(A.temporalCondition.pointSide)}.${e.quoteIdentifier(A.temporalCondition.pointColumn)}`,q=M(A.temporalCondition.intervalSide),v=`${q}.${e.quoteIdentifier(A.temporalCondition.startColumn)}`,k=`${q}.${e.quoteIdentifier(A.temporalCondition.endColumn)}`;D.push(`${v} <= ${z}`),D.push(`(${k} > ${z} OR ${k} IS NULL)`)}S+=` ON ${D.join(" AND ")}`}for(const A of t.joins??[]){S+=` LEFT JOIN ${e.tableAlias(Rr(e,A.targetSource,A.targetSourceSql),A.targetAlias)}`;const R=A.sourceArrayExpansionPath?p.get(A.sourceArrayExpansionPath):A.sourceSql?Gt(A.sourceSql,A.sourceColumn,e,A.sourceTimestampColumn,A.sourceAlias):`${e.quoteIdentifier(A.sourceAlias)}.${e.quoteIdentifier(A.sourceColumn)}`,O=A.targetSql?Gt(A.targetSql,A.targetColumn,e,A.targetTimestampColumn,A.targetAlias):`${e.quoteIdentifier(A.targetAlias)}.${e.quoteIdentifier(A.targetColumn)}`;if(!R)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${A.path}`);if(S+=` ON ${R} = ${O}`,A.temporalCondition?.kind==="date-bucket-equal"){const D=`${e.quoteIdentifier(A.sourceAlias)}.${e.quoteIdentifier(A.temporalCondition.sourceColumn)}`,M=`${e.quoteIdentifier(A.targetAlias)}.${e.quoteIdentifier(A.temporalCondition.targetColumn)}`;S+=` AND ${e.dateBucket(D,A.temporalCondition.sourceGranularity)} = ${e.dateBucket(M,A.temporalCondition.targetGranularity)}`}else if(A.temporalCondition?.kind==="point-in-interval"){const D=k=>k==="source"?e.quoteIdentifier(A.sourceAlias):e.quoteIdentifier(A.targetAlias),M=`${D(A.temporalCondition.pointSide)}.${e.quoteIdentifier(A.temporalCondition.pointColumn)}`,z=D(A.temporalCondition.intervalSide),q=`${z}.${e.quoteIdentifier(A.temporalCondition.startColumn)}`,v=`${z}.${e.quoteIdentifier(A.temporalCondition.endColumn)}`;S+=` AND ${q} <= ${M} AND (${v} > ${M} OR ${v} IS NULL)`}}const E=[];if(!t.periodSource&&t.query&&Object.keys(t.query).length>0&&E.push(Rt(t.query,f,A=>t.fieldReferences?.[A]?.isArray===!0,o,e,s,m,i)),E.length>0&&(S+=` WHERE ${E.join(" AND ")}`),t.groupBy.length>0){const A=t.groupBy.map(O=>m(O.expression)),R=t.rowIdentity.kind==="group"?[Ji(A,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)]:[];S+=` GROUP BY ${[...A,...R].join(", ")}`}if(t.having&&Object.keys(t.having).length>0){const A=R=>{const O=t.projections.find(D=>D.name===R);if(!O)throw new d("INVALID_HAVING",`Having field is not an output: ${R}`);return e.supportsHavingAlias===!1?m(O.expression):e.quoteIdentifier(R)};S+=` HAVING ${Rt(t.having,A,()=>!1,o,e,s,m,i)}`}if(t.groupLimit&&(S=Zi(S,t,e,o)),t.pagination?.kind==="ratio")S=Xi(S,t,t.pagination,e,o);else if(t.orderBy.length>0&&(S+=` ORDER BY ${Nr(t,e,o,void 0,m)}`),t.pagination?.kind==="rows"){const A=(t.pagination.page-1)*t.pagination.pageSize;S=e.paginate(S,t.pagination.pageSize,A)}return{sql:S,parameters:o.values}},Xd=(t,e)=>{const r=Object.keys(e).sort((f,m)=>m.length-f.length),n=[];let o=0;for(;o<t.length;){const f=t[o];if(f&&/\s/.test(f)){o+=1;continue}if(f&&/[()+\-*/,]/.test(f)){n.push(f),o+=1;continue}const m=t.slice(o).match(/^\d+(?:\.\d+)?/);if(m?.[0]){n.push(m[0]),o+=m[0].length;continue}const y=r.find(g=>t.startsWith(g,o));if(y){n.push(y),o+=y.length;continue}const h=t.slice(o).match(/^[A-Za-z_$][\w$]*/);if(h?.[0]){n.push(h[0]),o+=h[0].length;continue}n.push(f??""),o+=1}let i=0;const s=()=>n[i],a=()=>n[i++],u=()=>{const f=a();if(!f)throw new Error("Component expression is incomplete");if(f==="("){const y=p();if(a()!==")")throw new Error("Component expression has an unclosed parenthesis");return`(${y})`}if(/^\d/.test(f))return f;if(!e[f]&&!/^[A-Za-z_$][\w$]*$/.test(f))throw new Error(`Invalid component expression token: ${f}`);if(s()==="("){a();const y=[];if(s()!==")")for(;y.push(p()),s()===",";)a();if(a()!==")")throw new Error("Component expression has an unclosed function call");if(!["ABS","NULLIF","COALESCE"].includes(f.toUpperCase()))throw new Error(`Unsupported component expression function: ${f}`);return`${f.toUpperCase()}(${y.join(", ")})`}const m=e[f];if(!m)throw new Error(`Unknown component in expression: ${f}`);return m},c=()=>{let f=u();for(;s()==="*"||s()==="/";)f=`${f} ${a()} ${u()}`;return f},p=()=>{let f=c();for(;s()==="+"||s()==="-";)f=`${f} ${a()} ${c()}`;return f},l=p();if(i!==n.length)throw new Error(`Unexpected component expression token: ${s()}`);return l},Zd=t=>`__sdb_cte_${t}`,es=t=>{const e=t.projections[t.groupBy.length];if(!e)throw new Error("CTE component must produce one metric projection");return e.name},el=(t,e)=>t?.find(r=>r.name===e),tl=(t,e,r)=>r===0?t:e.kind==="postgresql"?t.replace(/\$(\d+)/g,(n,o)=>`$${Number(o)+r}`):e.kind==="oracle"?t.replace(/:(\d+)/g,(n,o)=>`:${Number(o)+r}`):e.kind==="clickhouse"?t.replace(/\{p(\d+):([^}]+)\}/g,(n,o,i)=>`{p${Number(o)+r}:${i}}`):t,Yn=(t,e,r,n=De())=>{if(t.length===0)throw new Error("CTE query combination requires at least one unit");let o=0;const i=t.map((w,S)=>{const E={...w.compiled,sql:tl(w.compiled.sql,r,o)};return o+=w.compiled.parameters.length,{...w,compiled:E,alias:`__sdb_exec_${S}`}}),s=i.map(({alias:w,compiled:S})=>`${r.quoteIdentifier(w)} AS (${S.sql})`),a=i[0],u=r.quoteIdentifier(a.alias),c=e.groupBy.map(({name:w})=>w),p=e.orderBy??[],l=e.rowIdentity.kind==="group",f=r.quoteIdentifier("__sdb_exec_keys");if(l){const w=S=>[...c.map(E=>`${S}.${r.quoteIdentifier(E)}`),`${S}.${r.quoteIdentifier("_id")}`].join(", ");s.push(`${f} AS (${i.map(({alias:S})=>`SELECT ${w(r.quoteIdentifier(S))} FROM ${r.quoteIdentifier(S)}`).join(" UNION ")})`)}const m=l?f:u,y=[...c,...t.flatMap(({outputs:w})=>w)],h=y.filter((w,S,E)=>E.indexOf(w)===S).map(w=>{if(c.includes(w))return`${m}.${r.quoteIdentifier(w)} AS ${r.quoteIdentifier(w)}`;const S=i.find(({outputs:A})=>A.includes(w));if(!S)throw new Error(`CTE execution unit does not expose output projection: ${w}`);return`${r.quoteIdentifier(S.alias)}.${r.quoteIdentifier(w)} AS ${r.quoteIdentifier(w)}`});l&&h.push(`${m}.${r.quoteIdentifier("_id")} AS ${r.quoteIdentifier("_id")}`);let g=`SELECT ${h.join(", ")} FROM ${m}`;for(const w of l?i:i.slice(1)){const S=r.quoteIdentifier(w.alias);g+=` LEFT JOIN ${S}`,g+=l?` ON ${m}.${r.quoteIdentifier("_id")} = ${S}.${r.quoteIdentifier("_id")}`:" ON 1 = 1"}if(!!(e.having&&Object.keys(e.having).length>0||p.length>0||e.pagination||e.groupLimit)){const w={schemaId:e.schemaId,source:"__sdb_cte_result_source",sourceSql:g,sourceAlias:"__sdb_cte_result",fields:Object.fromEntries(y.map(E=>[E,E])),projections:y.map(E=>({name:E,expression:{kind:"column",property:E,column:E}})),groupBy:[],...e.having&&Object.keys(e.having).length>0?{query:e.having}:{},orderBy:p.map(({name:E,direction:A,comparable:R})=>({name:E,direction:A,...R?{comparable:R}:{}})),...e.pagination?{pagination:e.pagination}:{},...e.groupLimit?{groupLimit:e.groupLimit}:{},rowIdentity:{kind:"generated"}},S=ge(w,r,n,o);return{sql:`WITH ${s.join(", ")} ${S.sql}`,parameters:[...i.flatMap(({compiled:E})=>E.parameters),...S.parameters]}}return{sql:`WITH ${s.join(", ")} ${g}`,parameters:i.flatMap(({compiled:w})=>w.parameters)}},Or=(t,e,r,n,o,i)=>{const s=[];let a=0;for(const w of e){const S=ge(w.plan,o,i,a);a+=S.parameters.length,s.push({input:w,sql:S,alias:Zd(w.name)})}const u=s.map(({sql:w,alias:S})=>`${o.quoteIdentifier(S)} AS (${w.sql})`).join(", "),c=s[0];if(!c)throw new Error("CTE calculation requires a current component");const p=o.quoteIdentifier(c.alias),l=r.groupBy.map(({name:w})=>w),f=l.map(w=>`${p}.${o.quoteIdentifier(w)} AS ${o.quoteIdentifier(w)}`);let m="";for(const w of s.slice(1)){const S=o.quoteIdentifier(w.alias),E=w.input.plan.groupBy.map(({name:O})=>O),R=(w.input.joinKeys??l.filter(O=>E.includes(O))).map(O=>{const D=el(w.input.groupKeyShifts,O),M=D?o.dateShift(`${S}.${o.quoteIdentifier(O)}`,D.granularity,D.offset):`${S}.${o.quoteIdentifier(O)}`;return`${p}.${o.quoteIdentifier(O)} = ${M}`});m+=` LEFT JOIN ${S} ON ${R.length>0?R.join(" AND "):"1 = 1"}`}const y=Object.fromEntries(s.map(({input:w,alias:S})=>[w.name,`${o.quoteIdentifier(S)}.${o.quoteIdentifier(es(w.plan))}`])),h=Xd(t.expression,y),g=[...f,...r.rowIdentity.kind==="group"?[`${p}.${o.quoteIdentifier("_id")} AS ${o.quoteIdentifier("_id")}`]:[],...s.map(({input:w,alias:S})=>`${`${o.quoteIdentifier(S)}.${o.quoteIdentifier(es(w.plan))}`} AS ${o.quoteIdentifier(w.name)}`),`${h} AS ${o.quoteIdentifier(n)}`].join(", ");let $=`WITH ${u} SELECT ${g} FROM ${p}`;return $+=m,{sql:$,parameters:s.flatMap(({sql:w})=>w.parameters)}},rl=t=>{if(typeof t!="string"||!/\bSELECT\b/i.test(t))return t;try{let e=t;const r=rs(t).length*2+2;for(let n=0;n<r;n+=1){const o=nl(e);if(o===e)return e;e=o}return e}catch{return t}},nl=t=>{const e=rs(t),r=ol(t,e);if(r!==t)return r;const n=[];for(const i of e){const s=ns(t,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?$l(t.slice(i.fromStart+4,i.close)):null;if(a){n.push({start:i.open,end:i.close+1,value:a});continue}if(!s||s.some(h=>h.trim()==="*"))continue;const u=gl(il(t.slice(i.fromStart,i.close),i,e)),c=sl(t,i),p=al(t,i);if(p&&cl(c,p))continue;let l=s.filter(h=>{const g=os(h);if(!g||g==="_id")return!0;const $=new RegExp(`(^|[^\\w$])${Hn(g)}([^\\w$]|$)`,"i");return $.test(u)||$.test(c)}),f=!0;for(;f;){f=!1;const h=as(l.join(" ")),g=s.filter($=>{if(l.includes($))return!1;const w=os($);return w?new RegExp(`(^|[^\\w$])${Hn(w)}([^\\w$]|$)`,"i").test(h):!1});g.length>0&&(l=s.filter($=>l.includes($)||g.includes($)),f=!0)}if(l.length===s.length)continue;const m=t.slice(i.selectEnd,i.fromStart),y=l.length===0&&Al(t,i)&&!/(^|[^\w$])\*([^\w$]|$)/.test(c)&&!/^\s*(?:DISTINCT|ALL|TOP|SQL_)\b/i.test(m)&&!/\b(?:UNION|INTERSECT|EXCEPT)\b/i.test(u);l.length===0&&!y||n.push({start:i.selectEnd,end:i.fromStart,value:m.match(/^\s*/)[0]+(y?"1":l.map(h=>h.trim()).join(", "))+m.match(/\s*$/)[0]})}n.sort((i,s)=>s.start-i.start);let o=t;for(const i of n)o=o.slice(0,i.start)+i.value+o.slice(i.end);return o},ol=(t,e)=>{const r=/^\s*SELECT\b/i.exec(t);if(!r)return t;const n=r.index+r[0].length,o=ts(t,"FROM",n);if(o===-1||!ns(t,n,o)?.every(hl))return t;const s=e.find(f=>f.open>o&&t.slice(o+4,f.open).trim().length===0);if(!s||!/^\s*1\s*$/.test(t.slice(s.selectEnd,s.fromStart)))return t;const a=e.filter(f=>f.open>s.fromStart&&f.close<s.close).sort((f,m)=>m.close-m.open-(f.close-f.open))[0];if(!a||t.slice(s.fromStart+4,a.open).trim().length>0)return t;const u=t.slice(a.close+1,s.close);if(/\b(?:GROUP|HAVING|ORDER|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT)\b/i.test(u))return t;const c=ml.exec(u)?.[1],p=yl.exec(t.slice(s.close+1));if(!c||!p||is(c)!==is(p[1]))return t;const l=/;(\s*)$/.exec(t)?.[0]??"";return t.slice(0,s.open)+t.slice(a.open,s.close)+l},il=(t,e,r)=>ul(t,r.filter(n=>n.open>e.open&&n.close<e.close).map(n=>({start:n.open-e.fromStart,end:n.close-e.fromStart+1}))),sl=(t,e)=>{const r=t.slice(0,e.open)+" ".repeat(e.close-e.open+1)+t.slice(e.close+1);return as(r)},al=(t,e)=>t.slice(e.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${ve})(?=\\s|$)`,"i"))?.[1]??null,cl=(t,e)=>new RegExp(`(^|[^\\w$])${Hn(e)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(t),ul=(t,e)=>{if(!e.length)return t;const r=t.split("");for(const n of e)for(let o=Math.max(0,n.start);o<Math.min(r.length,n.end);o+=1)r[o]=" ";return r.join("")},ts=(t,e,r)=>{let n=0,o=0,i="",s="";for(let a=r;a<t.length;a+=1){const u=t[a],c=t[a+1];if(s==="--"){u===`
2
+ `&&(s="");continue}if(s==="/*"){u==="*"&&c==="/"&&(s="",a+=1);continue}if(i){u===i&&t[a-1]!=="\\"&&(i="");continue}if(u==="-"&&c==="-"){s="--",a+=1;continue}if(u==="/"&&c==="*"){s="/*",a+=1;continue}if(u==="`"||u==='"'||u==="'"){i=u;continue}if(u==="("){n+=1;continue}if(u===")"){n-=1;continue}if(u==="["){o+=1;continue}if(u==="]"){o-=1;continue}if(n===0&&o===0&&new RegExp(`^${e}\\b`,"i").test(t.slice(a)))return a}return-1},rs=t=>{const e=[],r=[];let n="",o="";for(let i=0;i<t.length;i+=1){const s=t[i],a=t[i+1];if(o==="--"){s===`
3
+ `&&(o="");continue}if(o==="/*"){s==="*"&&a==="/"&&(o="",i+=1);continue}if(n){s===n&&t[i-1]!=="\\"&&(n="");continue}if(s==="-"&&a==="-"){o="--",i+=1;continue}if(s==="/"&&a==="*"){o="/*",i+=1;continue}if(s==="`"||s==='"'||s==="'"){n=s;continue}if(s==="("){r.push({open:i});continue}if(s!==")")continue;const u=r.pop();if(!u)continue;const c=t.slice(u.open+1,i),p=/^\s*SELECT\b/i.exec(c);if(!p)continue;const l=u.open+1+p.index,f=ts(t,"FROM",l+6);f===-1||f>=i||e.push({open:u.open,close:i,selectEnd:l+6,fromStart:f})}return e},ns=(t,e,r)=>{const n=t.slice(e,r),o=[];let i=0,s=0,a=0,u="";for(let c=0;c<n.length;c+=1){const p=n[c];if(u){p===u&&n[c-1]!=="\\"&&(u="");continue}if(p==="`"||p==='"'||p==="'"){u=p;continue}p==="("?s+=1:p===")"?s-=1:p==="["?a+=1:p==="]"?a-=1:p===","&&s===0&&a===0&&(o.push(n.slice(i,c)),i=c+1)}return u||s!==0||a!==0?null:(o.push(n.slice(i)),o)},os=t=>t.trim().match(/\bAS\s+(`[^`]+`|"[^"]+"|[A-Za-z_][\w$]*)\s*$/i)?.[1]?.replace(/^`|`$/g,"").replace(/^"|"$/g,"")??null,ve='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',dl=new RegExp(`\\s+AS\\s+${ve}\\s*$`,"i"),ll=new RegExp(`\\bAS\\s+${ve}`,"gi"),pl=new RegExp(`(?:${ve}\\s*\\.\\s*)+${ve}`,"g"),fl=new RegExp(`^${ve}(?:\\s*\\.\\s*${ve})*$`),ml=new RegExp(`^\\s*(?:AS\\s+)?(${ve})\\s+WHERE\\b`,"i"),yl=new RegExp(`^\\s*(?:AS\\s+)?(${ve})\\s*;?\\s*$`,"i"),is=t=>t.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),hl=t=>{const e=t.replace(dl,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(e)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(e)},ss=(t,e)=>t.replace(e,r=>" ".repeat(r.length)),as=t=>ss(t,ll),gl=t=>ss(t,pl),Al=(t,e)=>/\b(?:FROM|JOIN)\s*$/i.test(t.slice(0,e.open)),$l=t=>{const e=t.trim();return fl.test(e)?e:null},Hn=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Qn=(t,e)=>{if(t.kind!=="operator")return!1;const r=e.get(t.operator);return!r.toSQL&&!!r.evaluate||(t.input?Qn(t.input,e):!1)||(t.inputs?.some(n=>Qn(n,e))??!1)},cs=(t,e,r,n)=>{if(t.kind!=="operator")return e[r];const o=n.get(t.operator),i=t.input?cs(t.input,e,r,n):e[r];return o.evaluate?Promise.resolve(i).then(s=>o.evaluate?.({input:s,args:t.args})):i},it=async(t,e,r)=>{const n=e.filter(({expression:o})=>Qn(o,r));return n.length===0?[...t]:Promise.all(t.map(async o=>{const i={...o};for(const s of n)i[s.name]=await cs(s.expression,i,s.name,r);return i}))},Tr=t=>t==null?"\u7A7A\u503C":typeof t=="object"?"_id"in t?String(t._id):"id"in t?String(t.id):JSON.stringify(t):String(t),Gn=(t,e,r="_",n="\u7A7A\u503C")=>e.map(o=>t[o]===null||t[o]===void 0?n:Tr(t[o])).join(r),Wn=(t,e)=>t.map(r=>{if(e.kind==="property"){const{[e.internalName]:n,...o}=r;return{...o,_id:String(n)}}return e.kind==="group"?{...r,_id:r._id===void 0?Gn(r,e.names,e.separator,e.nullLabel):Tr(r._id)}:{...r,_id:e.kind==="singleton"?"0":Co.randomUUID()}}),wl=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},zt=(t,e)=>t.operator&&e.get(t.operator).kind==="component"?!0:!!t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&zt(t.pred,e)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&zt(r,e)),Pr=(t,e,r,n,o,i,s="zh-CN",a=pr.translator(s))=>{const u=t.preds??[],c=u.map((m,y)=>({pred:m,index:y,definition:m.operator?n.get(m.operator):void 0})).filter(({definition:m})=>m?.kind==="component"&&!m.skipComponentExecution?.({plan:e}));if(c.length===0&&e.sourcePlan||c.length===0)return;for(const m of u)if((!m.operator||n.get(m.operator).kind!=="component")&&(m.pred&&typeof m.pred=="object"&&!Array.isArray(m.pred)&&zt(m.pred,n)||Array.isArray(m.pred)&&m.pred.some(y=>typeof y!="string"&&zt(y,n))))throw new d("UNSUPPORTED_COMPONENT_NESTING","A component operator must currently be the top-level projection operator");const p=[],l=u.filter((m,y)=>!c.some(h=>h.index===y));if(l.length>0){const m=wl(t);m.preds=l,p.push({kind:"query",logicform:m})}const f=t.groupby?.length??0;for(const{pred:m,index:y,definition:h}of c){const g=h?.createComponent;if(!g)continue;const $=e.projections[f+y]?.name;if(!$)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");const w=i?.preds?.[y],S=g({logicform:t,pred:w??m,outputName:$,locale:s,t:a,schema:r,resolveSchema:o,...i?{sourceLogicform:i}:{}});if("logicform"in S&&(S.logicform.preds??[]).some(E=>zt(E,n)))throw new d("UNSUPPORTED_COMPONENT_NESTING","Nested component operators are not supported yet");p.push("components"in S?{...S,outputName:$}:S)}return p},qe=t=>t instanceof Date?t.getTime():t,El=(t,e,r,n)=>{const o=qe(t),i=qe(r);switch(e){case"$eq":return o===i;case"$ne":return o!==i;case"$gt":return o!=null&&i!==void 0&&i!==null&&o>i;case"$gte":return o!=null&&i!==void 0&&i!==null&&o>=i;case"$lt":return o!=null&&i!==void 0&&i!==null&&o<i;case"$lte":return o!=null&&i!==void 0&&i!==null&&o<=i;case"$in":return Array.isArray(r)&&r.some(s=>qe(s)===o);case"$nin":return Array.isArray(r)&&r.every(s=>qe(s)!==o);case"$exists":return r?t!=null:t==null;case"$contains":return String(t).includes(String(r));case"$startsWith":return typeof t=="string"&&typeof r=="string"&&t.startsWith(r);case"$regex":return typeof r=="string"&&new RegExp(r,n).test(String(t));default:throw new d("UNSUPPORTED_QUERY_OPERATOR",`Unsupported having operator: ${e}`)}},zn=(t,e)=>{if(!e||typeof e!="object"||Array.isArray(e))return qe(t)===qe(e);const r=Object.entries(e),n=e.args,o=n&&typeof n=="object"&&!Array.isArray(n)?n.options:void 0;return r.every(([i,s])=>{if(i==="args")return!0;if(i==="$and"||i==="$or"){if(!Array.isArray(s))return!1;const a=s.map(u=>zn(t,u));return i==="$and"?a.every(Boolean):a.some(Boolean)}return i==="$length"?typeof t=="string"&&zn(t.length,s):El(t,i,s,typeof o=="string"?o:void 0)})},us=(t,e)=>Object.entries(e).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>us(t,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return zn(t[r],n)}),ds=(t,e)=>e.length===0?"0":t._id===void 0?Gn(t,e):Tr(t._id),Kn=(t,e)=>{const r=new Map;for(const n of t)for(const o of n){const i=ds(o,e);r.set(i,{...r.get(i)??{},...o})}return[...r.values()]},Jn=(t,e)=>{const r=e.groupBy.map(({name:o})=>o);let n=Kn(t,r);if(e.having&&(n=n.filter(o=>us(o,e.having))),e.groupLimit){const o=e.groupLimit,i=new Map;for(const s of n){const a=ds(s,o.partitionBy);i.set(a,[...i.get(a)??[],s])}n=[...i.values()].flatMap(s=>s.sort((a,u)=>{for(const c of o.orderBy){const p=qe(a[c.name]),l=qe(u[c.name]);if(p!==l)return p==null?c.direction==="ASC"?-1:1:l==null?c.direction==="ASC"?1:-1:(p<l?-1:1)*(c.direction==="ASC"?1:-1)}return 0}).slice(0,o.count))}if(e.orderBy.length>0&&n.sort((o,i)=>{for(const s of e.orderBy){const a=qe(o[s.name]),u=qe(i[s.name]);if(a!==u)return a==null?s.direction==="ASC"?-1:1:u==null?s.direction==="ASC"?1:-1:(a<u?-1:1)*(s.direction==="ASC"?1:-1)}return 0}),e.pagination?.kind==="rows"){const o=(e.pagination.page-1)*e.pagination.pageSize;n=n.slice(o,o+e.pagination.pageSize)}else if(e.pagination?.kind==="ratio"){const o=Math.ceil(n.length*e.pagination.ratio),i=(e.pagination.page-1)*o;n=n.slice(i,i+o)}return n},ls=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cannot normalize nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n};class Xn{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new d("INVALID_SEMANTIC_TYPE","Semantic type name must not be empty");if(this.#e.has(e.name))throw new d("SEMANTIC_TYPE_ALREADY_REGISTERED",`Semantic type is already registered: ${e.name}`,{type:e.name});return this.#e.set(e.name,e),this}get(e){const r=this.#e.get(e);if(!r)throw new d("SEMANTIC_TYPE_NOT_FOUND",`Semantic type is not registered: ${e}`,{type:e});return r}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}requiresPerPeriodEvaluation(e){return e.property?this.get(e.property.type).requiresPerPeriodEvaluation?.({...e,property:e.property})??!1:!1}}const _l=t=>{const e=new Set,r=new Set;for(const n of t){if(!n.name)throw new d("INVALID_PROPERTY_NAME","Property name must not be empty");if(!n.id)throw new d("INVALID_PROPERTY_ID",`Property ${n.name} physical id must not be empty`);if(e.has(n.name))throw new d("DUPLICATE_PROPERTY_NAME",`Duplicate property name: ${n.name}`,{property:n.name});if(r.has(n.id))throw new d("DUPLICATE_PROPERTY_ID",`Duplicate property physical id: ${n.id}`,{propertyId:n.id});e.add(n.name),r.add(n.id)}},ps=t=>{_l(t);const e=t.filter(({type:r})=>r==="timestamp");if(e.length>1)throw new d("MULTIPLE_TIMESTAMP_PROPERTIES","A Schema can declare at most one timestamp Property",{properties:e.map(({name:r})=>r)})},Sl=new Set(["second","minute","hour","day","week","month","quarter","year"]),Il=(t,e)=>{if("_id"in t||"_sid"in t)throw new d("LEGACY_PROPERTY_ID_NOT_ALLOWED",`Property ${t.name} must use id instead of _id; _sid is not supported`,{property:t.name});if("sid"in t)throw new d("PROPERTY_SID_NOT_ALLOWED",`Property ${t.name} must not declare sid`,{property:t.name});const r=t;if(r.is_comparable!==void 0||r.comparable_order!==void 0)throw new d("LEGACY_COMPARABLE_NOT_ALLOWED",`Property ${t.name} must use comparable instead of is_comparable/comparable_order`,{property:t.name});if(t.udf!==void 0){const a=t.udf;if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_PROPERTY_UDF",`Property ${t.name} udf must be an object containing only sql`,{property:t.name});const u=a,c=Object.keys(u).filter(p=>p!=="sql");if(c.length>0)throw new d("UNSUPPORTED_PROPERTY_UDF",`Property ${t.name} udf only supports sql`,{property:t.name,unsupportedKeys:c});if(typeof u.sql!="string"||u.sql.trim().length===0)throw new d("INVALID_PROPERTY_UDF",`Property ${t.name} udf.sql must be a non-empty string`,{property:t.name})}const n=e.get(t.type),o=t.primal_type==="object"?"entity":t.primal_type;if(o!==void 0&&o!==n.primalType)throw new d("PRIMAL_TYPE_MISMATCH",`Property ${t.name} declares primal_type ${t.primal_type}, but ${t.type} requires ${n.primalType}`,{property:t.name,type:t.type,declared:t.primal_type,expected:n.primalType});if(t.isArray!==void 0&&typeof t.isArray!="boolean")throw new d("INVALID_IS_ARRAY",`Property ${t.name} isArray must be a boolean`,{property:t.name,isArray:t.isArray});if("is_observation"in t)throw new d("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED",`Property ${t.name} must use Schema temporalSemantics; is_observation is not supported`,{property:t.name});if(t.comparable!==void 0){const a=t.comparable;if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable must contain values and direction`);const u=a;if(Object.keys(u).some(c=>c!=="values"&&c!=="direction")||!Array.isArray(u.values)||u.values.length===0||u.values.some(c=>typeof c!="string")||new Set(u.values).size!==u.values.length||u.direction!==1&&u.direction!==-1)throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable requires unique string values and direction 1 or -1`,{property:t.name,comparable:a});if(t.type!=="category"||t.isArray===!0)throw new d("COMPARABLE_CATEGORY_REQUIRED",`Property ${t.name} comparable is only supported by scalar category properties`,{property:t.name,type:t.type})}const i={...t,id:t.id??t.name,primal_type:n.primalType,isArray:t.isArray??!1,is_dynamic:t.udf?.sql!==void 0,...n.primalType==="date"?{granularity:t.granularity??"day"}:{}};if(n.primalType==="entity"||n.primalType==="object"){if(typeof i.ref!="string"||i.ref.length===0)throw new d("PROPERTY_REF_REQUIRED",`Entity property ${i.name} must declare ref`,{property:i.name,type:i.type})}else if(i.ref!==void 0)throw new d("PROPERTY_REF_NOT_ALLOWED",`Property ${i.name} cannot declare ref unless its primal_type is entity`,{property:i.name,type:i.type});if(n.primalType==="date"||t.type==="duration"){if(i.granularity!==void 0&&!Sl.has(i.granularity))throw new d("INVALID_GRANULARITY",`Property ${i.name} has unsupported granularity: ${i.granularity}`,{property:i.name,granularity:i.granularity})}else if(i.granularity!==void 0)throw new d("GRANULARITY_NOT_ALLOWED",`Property ${i.name} cannot declare granularity unless its type supports it`,{property:i.name,type:i.type});return n.validateProperty?.(i),i},fs=(t,e,r=[])=>{const n=ye(r),o=n.reduce((m,y)=>y.prepareSchema?.(m)??m,t);if("_id"in o||"_sid"in o)throw new d("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported");if("sid"in o)throw new d("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid");if("is_snapshot"in o||"is_observation"in o)throw new d("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED","Schema must use temporalSemantics instead of is_snapshot/is_observation",{schemaId:o.id});if(!o.id)throw new d("INVALID_SCHEMA_ID","Schema id must not be empty");const i=n.flatMap(m=>m.propertyMetadata?[m.propertyMetadata]:[]),s=new Set(i.flatMap(({keys:m})=>m));let a=o.properties.map(m=>{const y=Object.fromEntries(Object.entries(m).filter(([g])=>!s.has(g))),h=Il(y,e);return i.reduce((g,$)=>({...g,...$.resolve(m,g,o)}),h)});for(const m of i)a=[...m.resolveAll?.(a,o.properties,o)??a];ps(a);const u=n.flatMap(m=>m.schemaMetadata?[m.schemaMetadata]:[]);let c={};for(const m of u)c={...c,...m.resolve(o,a)};const p=new Set(n.flatMap(m=>[...m.schemaMetadata?.keys??[],...m.legacySchemaKeys??[]])),f={...Object.fromEntries(Object.entries(o).filter(([m])=>!p.has(m))),properties:a,...c};for(const m of n)m.validateResolvedSchema?.(f);return f};ue.extend(Do),ue.extend(Mt),ue.extend(ar);const bl="YYYY-MM-DD HH:mm:ss",Rl=new Set(["YTD","QTD","MTD","WTD","DTD"]),ms=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),Nl=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),Lr=["second","minute","hour","day","week","month","quarter","year"],st=t=>Object.prototype.toString.call(t)==="[object Object]",ys=(t,e)=>{const r=n=>{if(typeof n!="number"||!Number.isSafeInteger(n))throw new d("INVALID_DATE_PART_QUERY",`${e} requires integer values`)};if(typeof t=="number"){r(t);return}if(Array.isArray(t)){t.forEach(r);return}if(st(t)){const n=Object.entries(t);if(n.length===0||n.some(([o])=>!ms.has(o)))throw new d("INVALID_DATE_PART_QUERY",`${e} requires numeric comparison operators`);for(const[o,i]of n)if(o==="$and"||o==="$or"){if(!Array.isArray(i)||i.length===0)throw new d("INVALID_DATE_PART_QUERY",`${e}.${o} requires a non-empty array`);i.forEach(s=>ys(s,e))}else if(o==="$in"||o==="$nin"){if(!Array.isArray(i))throw new d("INVALID_DATE_PART_QUERY",`${e}.${o} requires an array`);i.forEach(r)}else r(i);return}throw new d("INVALID_DATE_PART_QUERY",`${e} requires integer values`)},Zn=t=>!st(t)||"$gte"in t||"$gt"in t||"$lte"in t||"$lt"in t||"$or"in t||"$ne"in t?!1:typeof t.granularity=="string"&&Lr.includes(t.granularity)&&typeof t.offset=="number"||Lr.some(e=>e in t),Nt=t=>ue(t).format(bl),Ol=(t,e)=>Lr.find(r=>r in t||e!==void 0),Tl=(t,e,r)=>e==="month"?t.month(r-1):e==="day"?t.date(r):e==="week"?t.isoWeek(r):e==="quarter"?t.quarter(r):t.set(e,r),hs=(t,e)=>{const r=typeof t.granularity=="string"?t.granularity:void 0,n=r?{[r]:t.offset}:void 0,o=r??Ol(t,void 0)??"day";let i=ue(e).millisecond(0);for(const a of[...Lr].reverse()){const u=t[a];typeof u=="number"&&(i=Tl(i,a,u));const c=n?.[a];typeof c=="number"&&c!==0&&(i=i.add(c,a))}const s=o==="week"?"isoWeek":o;return{$gte:Nt(i.startOf(s)),$lte:Nt(i.endOf(s))}},Pl=(t,e)=>{const r=ue(e),o={DTD:()=>r.startOf("day"),WTD:()=>r.startOf("isoWeek"),MTD:()=>r.startOf("month"),QTD:()=>r.startOf("quarter"),YTD:()=>r.startOf("year")}[t];return{$gte:Nt(o()),$lte:Nt(r.endOf("day"))}},eo=async(t,e)=>{const r=ue(String(t.$lte)),n=await e.requestTimeWatermark(r.toDate());if(!n)return t;const o=e.property.granularity??"day",i=o==="week"?"isoWeek":o,s=ue(n).endOf(i),a=ue(String(t.$gte));if(a.isValid()&&s.isBefore(a))return t;const u=s.isBefore(r)?s:r;return{...t,$lte:Nt(u)}},to=async(t,e)=>Ie(t)?t:t instanceof Date||typeof t=="string"&&ue(t).isValid()?Nt(t):typeof t=="string"&&Rl.has(t)?eo(Pl(t,e.now),e):Zn(t)?eo(hs(t,e.now),e):t,gs=async(t,e,r)=>{if(t==="$and"||t==="$or")return Array.isArray(e)?Promise.all(e.map(o=>Dr(o,r))):e;if(Array.isArray(e))return Promise.all(e.map(o=>to(o,r)));const n=await to(e,r);return t==="$eq"&&st(n)&&"$gte"in n&&"$lte"in n?n:t==="$gte"||t==="$gt"?st(n)&&"$gte"in n?n.$gte:n:(t==="$lte"||t==="$lt")&&st(n)&&"$lte"in n?n.$lte:n},Dr=async(t,e)=>{if(Ie(t))return t;if(Array.isArray(t))return Promise.all(t.map(o=>Dr(o,e)));if(!st(t))return to(t,e);if("$options"in t)throw new d("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");if("$offset"in t)throw new d("UNSUPPORTED_DATE_VALUE","The legacy {$offset: ...} date form is not supported; use { granularity, offset }");if(("granularity"in t||"offset"in t)&&(!Zn(t)||!Number.isInteger(t.offset)))throw new d("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(Zn(t))return eo(hs(t,e.now),e);const r=Object.entries(t);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await gs("$eq",r[0][1],e);if(st(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)Nl.has(o)&&ys(i,o),n[o]=ms.has(o)?await gs(o,i,e):await Dr(i,e);return n},Ll=(t,e)=>e.property.primal_type==="date"?Dr(t,e):t,ro=(t=[])=>new Xn([...Ln,...ye(t).flatMap(({semanticTypes:e})=>e??[])]),As=(t,e)=>{const r=new Xn(t.definitions());for(const n of ye(e))for(const o of n.semanticTypes??[])if(!r.has(o.name))r.register(o);else if(r.get(o.name)!==o)throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${o.name}`,{semanticType:o.name,plugin:n.name});return r},Dl=/^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Cl=t=>{if(typeof t!="string")return!1;const e=Dl.exec(t);if(!e)return!1;const r=Number(e[1]),n=Number(e[2]),o=Number(e[3]??0);return r!==2?r>2:n>0||o>0?!0:e[4]===void 0},no=t=>{if(!Cl(t.version))throw new d("UNSUPPORTED_LOGICFORM_VERSION",`This library only supports LogicForm version 2.0 or later; received ${JSON.stringify(t.version)}`,{minimumVersion:"2.0",receivedVersion:t.version})},$s=(t,e)=>Object.entries(t).some(([r,n])=>e.has(r)?!0:r!=="$and"&&r!=="$or"||!Array.isArray(n)?!1:n.some(o=>typeof o=="object"&&o!==null&&!Array.isArray(o)&&$s(o,e))),ws=(t,e,r,n=[])=>{if(e===void 0||e==="placeholder")return t;if(!mn(e))throw new d("INVALID_ENTITY_ID","entity_id must be a non-empty string or a safe integer");const o=yn(r,n);return t&&$s(t,new Set([o.name,o.id]))?t:{[o.name]:e,...t??{}}},Ot=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),kl={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},Es={$second:{zh:"\u79D2",en:"second"},$minute:{zh:"\u5206\u949F",en:"minute"},$hour:{zh:"\u5C0F\u65F6",en:"hour"},$weekday:{zh:"\u661F\u671F",en:"weekday"},$day:{zh:"\u65E5",en:"day of month"},$week:{zh:"\u5468",en:"week"},$month:{zh:"\u6708",en:"month"},$quarter:{zh:"\u5B63\u5EA6",en:"quarter"},$year:{zh:"\u5E74",en:"year"}},Tt=(t,e)=>{if(t===null)return e?"null":"\u7A7A\u503C";if(typeof t=="string"||typeof t=="number")return String(t);if(typeof t=="boolean")return e?String(t):t?"\u662F":"\u5426";if(Array.isArray(t))return t.map(n=>Tt(n,e)).join(e?", ":"\u3001");if(!Ot(t))return e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6";if(Array.isArray(t.roots))return t.roots.map(n=>Tt(n,e)).join(e?", ":"\u3001");if(t.root!==void 0)return Tt(t.root,e);const r=["year","quarter","month","week","day","hour","minute","second"].filter(n=>t[n]!==void 0).map(n=>e?`${n} ${String(t[n])}`:`${String(t[n])}${kl[n]??""}`);return r.length>0?r.join(e?", ":""):e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6"},Cr=(t,e,r)=>t.filter(Boolean).join(r?e==="$and"?" and ":" or ":e==="$and"?"\u4E14":"\u6216"),_s=(t,e,r,n)=>{const s=(n?{$eq:"is",$ne:"is not",$gt:"is greater than",$gte:"is at least",$lt:"is less than",$lte:"is at most",$in:"is one of",$nin:"is none of",$contains:"contains",$startsWith:"starts with",$regex:"matches",$recursive:"is"}:{$eq:"\u4E3A",$ne:"\u4E0D\u4E3A",$gt:"\u5927\u4E8E",$gte:"\u5927\u4E8E\u7B49\u4E8E",$lt:"\u5C0F\u4E8E",$lte:"\u5C0F\u4E8E\u7B49\u4E8E",$in:"\u4E3A",$nin:"\u4E0D\u4E3A",$contains:"\u5305\u542B",$startsWith:"\u4EE5",$regex:"\u5339\u914D",$recursive:"\u5C5E\u4E8E"})[t];if(!s)return;const a=t==="$startsWith"?n?"":"\u5F00\u5934":t==="$in"?n?"":"\u4E4B\u4E00":t==="$nin"?n?"":"\u4E2D\u7684\u4EFB\u4E00\u9879":t==="$recursive"?n?" or a descendant":"\u53CA\u5176\u4E0B\u7EA7":"";return n?`${e} ${s} ${r}${a}`:`${e}${s}${r}${a}`},Kt=(t,e,r)=>{if(!Ot(e)||Object.keys(e).every(o=>!o.startsWith("$")))return _s("$eq",t,Tt(e,r),r)??"";const n=[];for(const[o,i]of Object.entries(e))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Cr(i.map(s=>Kt(t,s,r)),o,r));else if(o==="$exists")n.push(r?`${t} ${i?"exists":"does not exist"}`:`${i?"\u6709":"\u65E0"}${t}`);else if(Es[o]){const s=Es[o];n.push(Kt(r?`${t} ${s.en}`:`${t}\u7684${s.zh}`,i,r))}else if(o==="$length")n.push(Kt(r?`${t} length`:`${t}\u957F\u5EA6`,i,r));else if(o!=="args"){const s=o==="$regex"&&Ot(i)?Tt(i.pattern,r):Tt(i,r),a=_s(o,t,s,r);a&&n.push(a)}return Cr(n,"$and",r)},Ss=(t,e="zh-CN")=>{const r=e.toLowerCase().startsWith("en"),n=[];for(const[o,i]of Object.entries(t))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Cr(i.map(s=>Ot(s)?Ss(s,e):""),o,r));else if(o==="$expr"&&Ot(i)){const s=i.pred,a=Ot(s)&&typeof s.name=="string"?s.name:r?"expression":"\u8868\u8FBE\u5F0F";i.condition!==void 0&&n.push(Kt(a,i.condition,r))}else i!==void 0&&n.push(Kt(o,i,r));return Cr(n,"$and",r)},Pt=(t,e,r={})=>{if(t.name!==void 0){if(typeof t.name!="string"||t.name.length===0)throw new d("INVALID_PRED_NAME","PredItem name must be a non-empty string");return t.name}const n=r.locale??"zh-CN",o=r.localeRegistry??pr,i=o.resolve(n).locale.toLowerCase().startsWith("en"),s=o.translator(n),a=Array.isArray(t.pred)?t.pred.map(m=>typeof m=="string"?m:Pt(m,e,r)):[],u=typeof t.pred=="string"?t.pred:t.pred&&!Array.isArray(t.pred)?Pt(t.pred,e,r):void 0,c=u??(a.length>0?a.join(i?", ":"\u3001"):s("operator.rows",i?"rows":"\u6570\u636E\u884C")),p=t.args??{},l=t.operator?(()=>{const m=e.get(t.operator),y={operandName:c,...u?{inputName:u}:{},inputNames:a,args:p,locale:n,t:s},h=m.defaultName(y);if(typeof h!="string"||h.length===0)throw new d("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});const g=typeof p.granularity=="string"?s(`time.granularity.${p.granularity}`,p.granularity):s("time.granularity.period","\u5468\u671F"),$=i?t.operator==="$concat"?" and ":t.operator==="$multiply"?" times ":" plus ":t.operator==="$concat"?"\u4E0E":t.operator==="$multiply"?"\u4E58\u4EE5":"\u52A0";if(m.defaultNameIsLocalized)return h;const w=typeof m.defaultNameKey=="function"?m.defaultNameKey(y):m.defaultNameKey??`operator.${t.operator}`;return s(w,h,{...p,operandName:c,inputName:u??"",inputNames:a.join($),input0:a[0]??"",input1:a[1]??"",granularity:g})})():c;if(typeof l!="string"||l.length===0)throw new d("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});if(!t.query)return l;const f=Ss(t.query,n);return f?i?`${l} where ${f}`:`${f}\u7684${l}`:l},Ul=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},Ml=t=>{if(t.args===void 0||Object.keys(t.args).length>0)return t;const{args:e,...r}=t;return r},ql=async(t,e,r)=>{if(t.operator!=="$case"||t.args?.mode!=="auto"||t.args.min!==void 0||t.args.max!==void 0||t.args.empty===!0)return t;if(typeof t.pred!="string")throw new d("AUTO_CASE_PROPERTY_REQUIRED","$case auto mode requires a direct property pred when bounds are not explicit");if(!r.requestAutoCaseBounds)return t;const n=await r.requestAutoCaseBounds(e,t.pred,r.autoCaseQuery);return{...t,args:{...t.args,...n}}},Jt=async(t,e,r,n)=>{if("components"in t)throw new d("PRED_COMPONENTS_NOT_ALLOWED","PredItem components is not supported; use a pred array for multiple inputs");const o=r.operators,i={...r.locale?{locale:r.locale}:{},...r.localeRegistry?{localeRegistry:r.localeRegistry}:{}};if(!o)throw new Error("Normalizer operator registry is not initialized");if(t.name!==void 0&&(typeof t.name!="string"||t.name.length===0))throw new d("INVALID_PRED_NAME","PredItem name must be a non-empty string");if(t.name==="_id")throw new d("RESERVED_OUTPUT_NAME","PredItem name _id is reserved for executor-owned row identity");if(t.args!==void 0&&!Ul(t.args))throw new d("INVALID_OPERATOR_ARGS","Pred args must be a plain object");const s=t.schema===void 0||t.schema===e.id?e:r.resolveSchema?.(t.schema);if(!s)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cross-Schema pred requires Schema ${t.schema}`);const a=await n(t.query,s,r),u=Array.isArray(t.pred)?await Promise.all(t.pred.map(m=>Jt(typeof m=="string"?{pred:m}:m,s,r,n))):void 0,{query:c,...p}=t,l={...p,...a?{query:a}:{},...u?{pred:u}:{}},f=async m=>{const y=await ql(m,s,r),h=y.operator?o.get(y.operator).normalizePred?.({pred:y,schema:s})??y:y;return Ml(h)};if(typeof t.pred=="string"){const m=de(s,t.pred,r.resolveSchema),y={...l,pred:m.canonicalName};return f({...y,name:y.name??Pt(y,o,i)})}if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)){const m={...l,pred:await Jt(t.pred,s,r,n)};return f({...m,name:m.name??Pt(m,o,i)})}if(u)return f({...l,name:l.name??Pt(l,o,i)});if(t.pred!==void 0)throw new d("UNSUPPORTED_PRED","A pred must be a property name or nested pred");return f({...l,name:l.name??Pt(l,o,i)})},jl=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),xl=t=>{if(!Ie(t))return!1;const e=t;return e.groupby!==void 0||e.preds!==void 0||e.from!==void 0||e.having!==void 0||e.sort!==void 0||e.limit!==void 0||e.limitBy!==void 0||e.page!==void 0},kr=async(t,e)=>{if(Ie(t)){if(!e.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");return e.normalizeNestedLogicform(t)}return Array.isArray(t)?Promise.all(t.map(r=>kr(r,e))):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(await Promise.all(Object.entries(t).map(async([r,n])=>[r,await kr(n,e)])))},Is=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>Is(o,e))]:[`${e}_${r}`,n])),oo=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const e=Object.entries(t),[r]=e;return e.length===1&&r?.[0]==="$eq"?r[1]:t},bs=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),io=new Set([...bs,"$length"]),Ur=t=>Array.isArray(t)?t.some(Ur):typeof t!="object"||t===null||Ie(t)?!1:Object.entries(t).some(([e,r])=>io.has(e)||Ur(r)),Rs=(t,e)=>{if(!(typeof t=="number"&&Number.isFinite(t))){if(Array.isArray(t)){if(t.every(r=>typeof r=="number"&&Number.isFinite(r)))return;throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}if(typeof t=="object"&&t!==null&&!Ie(t)){for(const[r,n]of Object.entries(t)){if(!r.startsWith("$"))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`);if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new d("INVALID_QUERY_VALUE",`${r} requires an array`);n.forEach(o=>Rs(o,e))}else if(r==="$in"||r==="$nin"){if(!Array.isArray(n)||n.some(o=>typeof o!="number"||!Number.isFinite(o)))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}else if(typeof n!="number"||!Number.isFinite(n))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}return}throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}},Mr=(t,e)=>{if(t.schema!==void 0)throw new d("EXPRESSION_QUERY_SCHEMA_NOT_ALLOWED","$expr.pred is scoped to the query Schema and cannot define schema");if(t.query)throw new d("EXPRESSION_QUERY_PRED_QUERY_NOT_ALLOWED","$expr.pred cannot define pred.query");if(t.operator){if(!e.operators)throw new Error("Normalizer operator registry is not initialized");const r=e.operators.get(t.operator);if(r.kind!=="scalar"||!r.toSQL)throw new d("OPERATOR_NOT_ALLOWED_IN_EXPRESSION_QUERY",`Operator ${t.operator} cannot be used in $expr`,{operator:t.operator})}t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&Mr(t.pred,e);for(const r of Array.isArray(t.pred)?t.pred:[])typeof r!="string"&&Mr(r,e)},Ns=async(t,e,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_EXPRESSION_QUERY","$expr must be an object");const n=t,o=Object.keys(n).filter(u=>u!=="pred"&&u!=="condition");if(o.length>0||!Object.prototype.hasOwnProperty.call(n,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must contain exactly pred and condition",{unsupported:o});if(typeof n.pred!="object"||n.pred===null||Array.isArray(n.pred))throw new d("INVALID_EXPRESSION_QUERY","$expr.pred must be a pred expression");const i=n.pred;if(!i.operator)throw new d("EXPRESSION_QUERY_OPERATOR_REQUIRED","$expr.pred must define a scalar operator");if(!r.operators)throw new Error("Normalizer operator registry is not initialized");Mr(i,r);const s=await Jt(i,e,r,()=>Promise.resolve(void 0));Mr(s,r);const a=oo(await kr(n.condition,r));return io.has(s.operator)&&Rs(a,s.operator),{pred:s,condition:a}},Os=async(t,e,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||Ie(e))return{[t]:e};const o={},i=[];for(const[s,a]of Object.entries(e))io.has(s)?i.push({$expr:await Ns({pred:{operator:s,pred:t},condition:a},r,n)}):(s==="$and"||s==="$or")&&Array.isArray(a)&&a.some(Ur)?i.push({[s]:await Promise.all(a.map(u=>Os(t,u,r,n)))}):o[s]=a;return Object.keys(o).length>0&&i.unshift({[t]:oo(o)}),i.length===1?i[0]??{}:{$and:i}},so=t=>Array.isArray(t)?t.some(so):typeof t!="object"||t===null||Ie(t)?!1:Object.entries(t).some(([e,r])=>bs.has(e)||so(r)),Ts=async(t,e,r,n)=>{const o=c=>{if(Array.isArray(c)){c.forEach(o);return}if(typeof c!="object"||c===null||Ie(c))return;const p=c;if("$options"in p)throw new d("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");Object.values(p).forEach(o)};if(o(t),r.primal_type!=="date"&&so(t))throw new d("INVALID_DATE_PART_QUERY",`Date-part query Operators require a date Property: ${r.name}`,{property:r.name});const i=n.semanticTypes.get(r.type),s={schema:e,property:r,now:n.now??new Date,requestTimeWatermark:c=>n.requestTimeWatermark?.(e,r,c)??Promise.resolve(void 0)},a=await Ll(ne(t),s),u=i.normalizeQuery?i.normalizeQuery(a,s):a;if(r.comparable){const c=new Set(r.comparable.values),p=(l,f)=>{if(!(Ie(l)||l===null)){if(Array.isArray(l)){l.forEach(m=>p(m,f));return}if(typeof l=="object"){Object.entries(l).forEach(([m,y])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(m)||p(y,m)});return}if(!(f&&["$exists","$regex","$contains","$startsWith","$length"].includes(f))&&(typeof l!="string"||!c.has(l)))throw new d("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${r.name} does not contain value: ${JSON.stringify(l)}`,{property:r.name,value:l})}};p(u)}return u},ao=async(t,e,r)=>{const n={},o=[],i=[],s=a=>{const u=Object.entries(a);if(u.length===1&&u[0]?.[0]==="$and"&&Array.isArray(u[0][1]))for(const c of u[0][1])s(c);else u.length===1&&u[0]?.[0]==="$expr"?o.push(a):u.every(([c])=>!c.startsWith("$"))?Object.assign(n,a):i.push(a)};for(const[a,u]of Object.entries(t)){if(a==="$and"||a==="$or"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);n[a]=await Promise.all(u.map(async m=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_QUERY_VALUE",`${a} items must be query objects`);return ao(m,e,r)}));continue}if(a==="$expr"){o.push({$expr:await Ns(u,e,r)});continue}const c=de(e,a,r.resolveSchema);if(xl(u)&&(c.property.primal_type==="entity"||c.property.primal_type==="object")&&c.property.ref){if(u.schema!==c.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${c.canonicalName} references ${c.property.ref}, not ${u.schema??"undefined"}`);if(!r.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");const m=await r.normalizeNestedLogicform(u);n[c.canonicalName]={$in:m};continue}if(jl(u)){if(u.version!==void 0&&no(u),c.property.primal_type!=="entity"&&c.property.primal_type!=="object")throw new d("INVALID_RELATION_QUERY",`Relation query ${a} must resolve to an entity property`);if(!c.property.ref)throw new d("INVALID_RELATION_QUERY",`Nested LogicForm query requires an object property: ${c.canonicalName}`);if(u.schema!==c.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${c.canonicalName} references ${c.property.ref}, not ${u.schema}`);const m=r.resolveSchema?.(u.schema);if(!m)throw new d("SCHEMA_RESOLVER_REQUIRED",`Nested relation query requires Schema ${u.schema}`);const y=ws(u.query,u.entity_id,m,r.plugins),h=await ao(y,m,r);Object.assign(n,Is(h,c.canonicalName));continue}if(typeof u=="object"&&u!==null&&!Array.isArray(u)){const m=u,y=Object.entries(m).filter(([h])=>$t(h,r.plugins));if(y.length>0){const[h]=y,g=h?$t(h[0],r.plugins):void 0;if(g?.validateCondition?.(m),!h||y.length!==1||Object.keys(m).length!==1)throw new d("INVALID_PLUGIN_QUERY","A plugin Query Operator cannot be combined with other field operators");const[$,w]=h;if(!g)throw new Error(`Query Operator disappeared: ${$}`);n[c.canonicalName]={[$]:await g.normalize(w,{schema:c.schema,property:c.property,...r.resolveSchema?{resolveSchema:r.resolveSchema}:{},normalizeValue:(S,E,A)=>Ts(S,E,A,r)})};continue}}const p=await kr(u,r),l=await Ts(p,c.schema,c.property,r),f=oo(l);if(Ur(f)){s(await Os(c.canonicalName,f,e,r));continue}n[c.canonicalName]=f}if(i.length>0){const a=Array.isArray(n.$and)?n.$and:[];n.$and=[...a,...i]}if(o.length===1)n.$expr=o[0]?.$expr;else if(o.length>1){const a=Array.isArray(n.$and)?n.$and:[];n.$and=[...a,...o]}return n},Ps=async(t,e,r)=>{if(!t)return;const n=await ao(t,e,r);return Object.keys(n).length===0?void 0:n},Ls=(t,e,r)=>Promise.all((t??[]).map(n=>Jt(n,e,r,Ps))),Bl=(t,e,r)=>Ls(t??[],e,r),Lt=(t,e)=>{throw new d("INVALID_PAGINATION",t,e)},Vl=t=>{"skip"in t&&Lt("skip has been removed; use the 1-based page field",{skip:t.skip});const e=t.groupby?.length??0;t.limitBy!==void 0&&((!Number.isInteger(t.limitBy)||t.limitBy<=0)&&Lt("limitBy must be a positive integer",{limitBy:t.limitBy}),e<2&&(t.limit=t.limitBy,delete t.limitBy));const{limit:r,page:n}=t;if(r===void 0){n!==void 0&&Lt("page requires limit",{page:n});return}if((!Number.isFinite(r)||r<0&&r!==-1||r>1&&!Number.isInteger(r))&&Lt("limit must be -1, a non-negative integer, or a ratio between 0 and 1",{limit:r}),r===-1){n!==void 0&&Lt("page cannot be used with unlimited results",{limit:r,page:n}),delete t.limit;return}n!==void 0&&(!Number.isInteger(n)||n<1)&&Lt("page must be a positive integer starting from 1",{page:n}),t.page=n??1},vl=t=>t.property.name,Ds=(t,e,r,n,o=new Set)=>{if(o.has(t.id))return;const i=new Set(o).add(t.id),s=t.properties.find(a=>a.id===e||a.name===e);if(s)return s.name;if(n==="timestamp"){const a=t.properties.find(u=>u.type==="timestamp");if(a)return a.name}for(const a of t.properties){if(!a.ref||a.primal_type!=="entity"&&a.primal_type!=="object")continue;const u=r?.(a.ref);if(!u)continue;const c=Ds(u,e,r,n,i);if(c)return`${a.name}_${c}`}},Cs=(t,e,r,n)=>{try{const o=de(t,e,n);return Ds(r,vl(o),n,o.property.type)}catch{return}},co=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?co(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:co(e)):[]],ks=t=>t?Object.entries(t).flatMap(([e,r])=>{if((e==="$and"||e==="$or")&&Array.isArray(r))return r.flatMap(n=>ks(n));if(e==="$expr"&&typeof r=="object"&&r!==null&&!Array.isArray(r)){const n=r.pred;return typeof n=="object"&&n!==null&&!Array.isArray(n)?co(n):[]}return e.startsWith("$")?[]:[e]}):[],Fl=(t,e,r)=>{const n=[...new Set((t.preds??[]).map(s=>s.schema).filter(s=>!!(s&&s!==e.id)))];if(n.length===0)return t;const o={};for(const[s,a]of Object.entries(t.propertyResolve??{})){const u=r.resolveSchema?.(s),c={};for(const[p,l]of Object.entries(a))try{const f=de(e,p,r.resolveSchema),m=u?de(u,l,r.resolveSchema):void 0;c[f.canonicalName]=m?.canonicalName??l}catch{c[p]=l}o[s]=c}const i=[...(t.groupby??[]).map(s=>s.pred),...ks(t.query)];for(const s of i){if(typeof s!="string")continue;let a;try{a=de(e,s,r.resolveSchema)}catch{continue}for(const u of n){const c=r.resolveSchema?.(u),p=c&&Cs(e,s,c,r.resolveSchema);p&&p!==a.canonicalName&&(o[u]={...o[u]??{},[a.canonicalName]:p})}}return Object.keys(o).length>0?{...t,propertyResolve:o}:t},Yl=t=>{if(t!==void 0){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_PROPERTY_RESOLVE","propertyResolve must be an object");for(const[e,r]of Object.entries(t)){if(typeof r!="object"||r===null||Array.isArray(r))throw new d("INVALID_PROPERTY_RESOLVE",`propertyResolve.${e} must be an object`);for(const[n,o]of Object.entries(r))if(typeof o!="string"||o.length===0)throw new d("INVALID_PROPERTY_RESOLVE",`propertyResolve.${e}.${n} must be a non-empty string`)}}},Hl=async(t,e,r)=>{if(!t)return;const n=ls(t,e,r);return at(t,n,r)},at=async(t,e,r)=>{if(r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:lr([...ye(r.plugins).flatMap(h=>h.locales??[]),...r.locales===void 0?[]:"locale"in r.locales?[r.locales]:r.locales])},...r.operators?{}:{operators:De(r.plugins)}},no(t),Yl(t.propertyResolve),t.output&&t.output.type!=="data"&&t.output.type!=="sql"&&!pi(t.output.type,r.plugins))throw new d("UNSUPPORTED_OUTPUT",`Output type is not supported: ${t.output.type}`);const o=ne(t),i={...r,normalizeNestedLogicform:async h=>{const g=ls(h,e,r);return at(h,g,r)}};Vl(o);const s=await Hl(o.from,e,i),a=s&&r.resolveFromSchema?r.resolveFromSchema(s,e):e,u=await Ps(ws(o.query,o.entity_id,a,r.plugins),a,i),c=o.preds===void 0&&o.groupby===void 0?a.properties.filter(h=>r.canProjectProperty?.(a,h)??!0).map(h=>({pred:h.name,name:h.name})):o.preds,p={...i,...u?{autoCaseQuery:u}:{}};let l=await Ls(c,a,p),f=await Bl(o.groupby,a,p);const m=f.filter(h=>ei(h,f,a,r.resolveSchema));if(m.length>0){const h=new Set(m.map(({name:g})=>g));f=f.filter(({name:g})=>!h.has(g)),l=[...l,...m]}return o.preds=l,f.length>0?o.groupby=f:delete o.groupby,s?o.from=s:delete o.from,u?o.query=u:delete o.query,Fl(o,a,i)},Us=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Fe=(t,e)=>{if(t){if(!Us(t,e))throw new d("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},ct=(t,e,r)=>{const n=Fe(t,e)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},Xt=(t,e,r)=>{if(!ct(t,e.id,r))throw new d("COLUMN_PERMISSION_DENIED",`Property is not included in the column permissions: ${e.id}.${r.name}`,{schemaId:e.id,property:r.name,propertyId:r.id})},uo=(t,e,r,n)=>{const o=de(e,t,n);for(const i of o.relations)Fe(r,i.targetSchema.id),Xt(r,i.sourceSchema,i.property);Xt(r,o.schema,o.property)},Ms=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),qr=(t,e,r,n)=>{if(Ie(t)){xr(t,e,r,n);return}if(Array.isArray(t)){for(const o of t)qr(o,e,r,n);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const o of Object.values(t))qr(o,e,r,n)};function Zt(t,e,r,n,o){const i=t.schema?n(t.schema):e;t.schema&&Fe(r,t.schema),typeof t.pred=="string"?uo(t.pred,i,r,n):t.pred&&!Array.isArray(t.pred)&&Zt(t.pred,i,r,n,o);for(const s of Array.isArray(t.pred)?t.pred:[])typeof s=="string"?uo(s,i,r,n):Zt(s,i,r,n,o);jr(t.query,i,r,n,o)}const jr=(t,e,r,n,o)=>{if(t)for(const[i,s]of Object.entries(t)){if(i==="$and"||i==="$or"){if(Array.isArray(s))for(const u of s)jr(u,e,r,n,o);continue}if(i==="$expr"){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const u=s.pred;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Zt(u,e,r,n,o),qr(s.condition,r,n,o)}continue}const a=de(e,i,n);if(uo(i,e,r,n),typeof s=="object"&&s!==null&&!Array.isArray(s))for(const[u,c]of Object.entries(s))$t(u,o)?.authorize?.(c,{schema:a.schema,property:a.property,resolveSchema:n,assertSchemaAllowed:p=>{Fe(r,p)},assertPropertyAllowed:(p,l)=>Xt(r,p,l),hasRowPermissions:p=>Fe(r,p)?.rowPermissions!==void 0});if(Ms(s)){if(a.property.ref!==s.schema)continue;const u=n(s.schema);Fe(r,u.id),mn(s.entity_id)&&Xt(r,u,yn(u,o)),jr(s.query,u,r,n,o);continue}qr(s,r,n,o)}},xr=(t,e,r,n=[])=>{if(!t.schema){if(t.from){xr(t.from,e,r,n);return}throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const o=r(t.schema);if(Fe(e,o.id),mn(t.entity_id)&&Xt(e,o,yn(o,n)),t.from){xr(t.from,e,r,n);return}jr(t.query,o,e,r,n);for(const i of t.preds??[])Zt(i,o,e,r,n);for(const i of t.groupby??[])Zt(i,o,e,r,n)},Br=(t,e)=>{if(Array.isArray(t))return t.map(o=>Br(o,e));if(typeof t!="object"||t===null||t instanceof Date)return t;const r=Object.entries(t).map(([o,i])=>[o,Br(i,e)]),n=Object.fromEntries(r);return Ms(t)&&!Us(t,"version")&&(n.version=e),n},Ql=(t,e,r)=>{const n=[],o=(s,a)=>{if(s)for(const[u,c]of Object.entries(s))if((u==="$and"||u==="$or")&&Array.isArray(c))for(const p of c)o(p,a);else if(u==="$expr"&&typeof c=="object"&&c!==null&&!Array.isArray(c)){const p=c.pred;typeof p=="object"&&p!==null&&!Array.isArray(p)&&i(p,a)}else u.startsWith("$")||n.push(de(a,u,r))},i=(s,a)=>{const u=s.schema?r(s.schema):a;typeof s.pred=="string"?n.push(de(u,s.pred,r)):s.pred&&!Array.isArray(s.pred)&&i(s.pred,u);for(const c of Array.isArray(s.pred)?s.pred:[])typeof c=="string"?n.push(de(u,c,r)):i(c,u);o(s.query,u)};o(t.query,e);for(const s of t.preds??[])i(s,e);for(const s of t.groupby??[])i(s,e);return n},Gl=(t,e,r)=>{if(!t.schema)return[];const n=r(t.schema),o=new Set,i=[];for(const s of Ql(t,n,r)){if(s.relations.length===0)continue;let a=-1;if(s.relations.forEach(({targetSchema:l},f)=>{e[l.id]?.rowPermissions!==void 0&&(a=f)}),a<0)continue;const u=s.relations.slice(0,a+1),c=u.map(({property:l})=>l.name).join("_");if(o.has(c))continue;o.add(c);let p={};for(const l of[...u].reverse())p={[l.property.name]:{schema:l.targetSchema.id,query:p}};i.push(p)}return i},Dt=(t,e,r,n,o,i)=>Ie(t)?ut(t,e,r,n,o,i):Array.isArray(t)?t.map(s=>Dt(s,e,r,n,o,i)):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(Object.entries(t).map(([s,a])=>[s,Dt(a,e,r,n,o,i)])),lo=(t,e,r,n,o,i)=>({...t,...t.query?{query:Dt(t.query,e,r,n,o,i)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:lo(t.pred,e,r,n,o,i)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(s=>typeof s=="string"?s:lo(s,e,r,n,o,i))}:{}}),ut=(t,e,r,n=!0,o=new Set,i=[])=>{if(!e)return ne(t);if(!t.schema){const m=ne(t);return m.from&&(m.from=ut(m.from,e,r,n,new Set,i)),m}n&&xr(t,e,r,i);const s=Fe(e,t.schema),a=o.has(t.schema),u=new Set(o).add(t.schema),c=ne(t);c.query&&(c.query=Dt(c.query,e,r,n,new Set,i)),c.preds&&(c.preds=c.preds.map(m=>lo(m,e,r,n,new Set,i))),c.from&&(c.from=ut(c.from,e,r,n,new Set,i));const p=a||t.from?void 0:s?.rowPermissions,l=(t.from?[]:Gl(t,e,r)).map(m=>Dt(Br(m,t.version),e,r,!1,u,i));p&&l.push(Dt(Br(ne(p),t.version),e,r,!1,u,i));const f=[c.query,...l].filter(m=>m!==void 0&&Object.keys(m).length>0);return f.length===1?c.query=f[0]:f.length>1?c.query={$and:f}:delete c.query,c},Wl=(t,e)=>{if(t)for(const[r,n]of Object.entries(t)){const o=e(r),i=n.columnPermissions?.whitelist;if(i&&(!Array.isArray(i)||i.some(s=>typeof s!="string")))throw new d("INVALID_COLUMN_PERMISSIONS",`Column permissions whitelist must be an array of strings: ${r}`,{schemaId:r});for(const s of i??[])if(!o.properties.some(({id:a,name:u})=>a===s||u===s))throw new d("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${r}.${s}`,{schemaId:r,property:s})}},qs=(t,e)=>{const r=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(t),n=o=>Number(r.find(i=>i.type===o)?.value);return{year:n("year"),month:n("month"),day:n("day"),hour:n("hour"),minute:n("minute"),second:n("second")}},js=(t,e)=>{const r=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second);let n=r;for(let o=0;o<3;o+=1){const i=qs(new Date(n),e),s=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second);n+=r-s}return new Date(n)},zl=(t,e)=>{const r=Ci(t.expireAt);if(!r)throw new Error(`Invalid daily expiration time: ${t.expireAt}`);if(!t.timeZone){const i=new Date(e);return i.setHours(r.hour,r.minute,r.second,0),i.getTime()<=e.getTime()&&i.setDate(i.getDate()+1),i}const n=qs(e,t.timeZone);let o=js({...n,...r},t.timeZone);if(o.getTime()<=e.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=js({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},t.timeZone)}return o},Kl=(t,e)=>{const r=t.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(e.getTime()+n.ttlSeconds*1e3)]:[zl(n,e)]);return r.length===0?void 0:new Date(Math.min(...r.map(n=>n.getTime())))},po=(t,e)=>e.findSource(t.schemaId,t.mappingSource??t.source,t.connectionId),er=(t,e,r)=>{if(Et(t)){e.push(t.plan);return}if(Ti(t)){for(const n of t.sources??[])r.set(`${n.schemaId}:${n.connectionId??""}:${n.source}`,n);return}if(Array.isArray(t)){for(const n of t)er(n,e,r);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const n of Object.values(t))er(n,e,r)},tr=(t,e,r)=>{if(t.kind==="window"){tr(t.input,e,r);for(const n of t.partitionBy)tr(n,e,r);return}if(t.kind==="operator"){er(t.query,e,r),t.input&&tr(t.input,e,r);for(const n of t.inputs??[])tr(n,e,r)}},we=t=>{const e=new Map,r=o=>{e.set(`${o.schemaId}:${o.connectionId??""}:${o.mappingSource??""}:${o.source}`,o)};if(t.subplans)for(const o of t.subplans)for(const i of we(o))r(i);else if(t.sourcePlan)for(const o of we(t.sourcePlan))r(o);else t.source&&r({schemaId:t.schemaId,source:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});for(const o of t.joins??[])r({schemaId:o.targetSchemaId,source:o.targetSource,...o.targetConnectionId?{connectionId:o.targetConnectionId}:{}});for(const o of t.enrichmentJoins??[])r({schemaId:t.schemaId,source:o.source,mappingSource:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});const n=[];er(t.query,n,e),er(t.having,n,e);for(const o of t.projections)tr(o.expression,n,e);for(const o of n)for(const i of we(o))r(i);return[...e.values()]},rr=t=>{const e=new Map;for(const r of t.flat())e.set(`${r.schemaId}:${r.connectionId??""}:${r.mappingSource??""}:${r.source}`,r);return[...e.values()]},xs=async(t,e)=>{try{return await t.execute(e)}catch(r){const n=r instanceof Error?r.message:String(r),o=`${t.kind} provider \u6267\u884C SQL \u4EA7\u751F\u9519\u8BEF\uFF1A`;throw r instanceof Error?(r.message.startsWith(o)||(r.message=`${o}${n}`),r):new Error(`${o}${n}`,{cause:r})}},Jl=(t,e)=>{const r=[];for(const n of t){const o=po(n,e),i=n.mappingSource?o?.enrichments?.find(({source:s})=>s===n.source)?.freshness:o?.freshness;if(!i)return;r.push(i)}return r},Ne=async(t,e,r)=>{t=Bs(t),r.signal?.throwIfAborted();const n=r.cache?Jl(e,r.schemaMappings):void 0;if(!r.cache||!n)return xs(r.provider,{...t,...r.signal?{signal:r.signal}:{}});const o={namespace:r.cache.namespace,provider:r.provider.kind,...r.connectionId?{connectionId:r.connectionId}:{},sql:t.sql,parameters:t.parameters};try{const s=await r.cache.store.get(o);if(r.signal?.throwIfAborted(),s)return[...s]}catch{r.signal?.throwIfAborted()}const i=await xs(r.provider,{...t,...r.signal?{signal:r.signal}:{}});try{const s=Kl(n,new Date);await r.cache.store.set(o,i,{sources:[...new Set(e.map(({source:a})=>a))],...s?{expiresAt:s}:{}})}catch{}return i},Bs=t=>({...t,sql:rl(t.sql)}),Xl=t=>{if(t.every(e=>typeof e=="string"))return[...t];if(t.every(e=>typeof e=="number"))return[...t];if(t.every(e=>typeof e=="boolean"))return[...t];throw new TypeError("Entity IDs must have one scalar type")},Zl=(t,e,r)=>{const n=Xl(e);if(!r||n.length<=r)return{[t]:{$in:n}};const o=[];for(let i=0;i<n.length;i+=r)o.push({[t]:{$in:n.slice(i,i+r)}});return{$or:o}},Vs=async(t,e)=>{if(!ct(e.permissions,t.schema.id,t.idProperty))throw new d("COLUMN_PERMISSION_DENIED",`Entity hydration requires the ID property in the column permissions: ${t.schema.id}.${t.idProperty.name}`,{schemaId:t.schema.id,property:t.idProperty.name});const r=t.schema.properties.filter(h=>ct(e.permissions,t.schema.id,h)),n=e.schemaMappings.list(t.schema.id),o=n.find(({connectionId:h})=>h===e.preferredConnectionId)?.connectionId??n[0]?.connectionId,i=o&&e.providerForConnection?e.providerForConnection(o):e.provider,s={version:e.version,schema:t.schema.id,query:Zl(t.idProperty.name,t.ids,i.maxInListItems),preds:r.map(h=>({pred:h.name,name:h.name}))},a=ut(s,e.permissions,e.resolveSchema,!0,new Set,e.plugins),u=await at(a,t.schema,{semanticTypes:e.semanticTypes,operators:e.operators,...e.plugins?{plugins:e.plugins}:{},...e.locale?{locale:e.locale}:{},...e.localeRegistry?{localeRegistry:e.localeRegistry}:{},resolveSchema:e.resolveSchema}),c=Te(u,t.schema,e.operators,e.schemaMappings,{resolveSchema:e.resolveSchema,...o?{preferredConnectionId:o}:{},canUsePropertyRowIdentity:(h,g)=>ct(e.permissions,h.id,g)}),p=new Set(we(c).map(h=>e.schemaMappings.findSource(h.schemaId,h.source,h.connectionId)?.connectionId).filter(h=>!!h));if(p.size>1)throw new d("CROSS_CONNECTION_ENTITY_HYDRATION_UNSUPPORTED",`Entity hydration cannot span connections: ${[...p].join(", ")}`);const l=[...p][0]??o,f=l&&e.providerForConnection?e.providerForConnection(l):i,m=ge(c,f,e.operators);e.onCompiled?.(m,u,f,l);const y=await Ne(m,we(c),{provider:f,...l?{connectionId:l}:{},schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}});return Wn(y,c.rowIdentity)},vs=t=>String(t),ep=(t,e,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${vs(r)}\u300D\u7684\u5B9E\u4F53`,o={};for(const i of t.properties)i.id===e.id?o[i.name]=r:i.isArray?o[i.name]=[]:o[i.name]=i.primal_type==="string"?n:null;return o._id=vs(r),o},Fs=(t,e)=>`${t}:${String(e)}`,tp=t=>{const e=t.properties.filter(({type:n})=>n==="ID"),r=e[0];if(e.length!==1||!r)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${t.id} must contain exactly one ID property`,{schemaId:t.id,count:e.length});return r};class rp{#e;#t=new Map;#r=new Map;#n=new Map;#o=!1;constructor(e){this.#e=e}load=(e,r)=>{const n=Fs(e,r),o=this.#t.get(n);if(o)return Promise.resolve(o);const i=this.#r.get(n);if(i)return i;const s=this.#e.resolveSchema(e);if(fi(s,this.#e.plugins))throw new d("INTERVAL_ENTITY_HYDRATION_REQUIRES_POINT",`Cannot hydrate interval-versioned entity ${e} by ID without a selection point; use a relation path to select its point-in-time properties`,{schemaId:e});const a=tp(s);let u,c;const p=new Promise((f,m)=>{u=f,c=m}),l=this.#n.get(e)??{schema:s,idProperty:a,loads:new Map};return l.loads.set(n,{id:r,resolve:f=>u?.(f),reject:f=>c?.(f)}),this.#n.set(e,l),this.#r.set(n,p),this.#s(),p};#s(){this.#o||(this.#o=!0,queueMicrotask(()=>{this.#i()}))}async#i(){this.#o=!1;const e=this.#n;this.#n=new Map,await Promise.all([...e.values()].map(r=>this.#a(r)))}async#a(e){const r={schema:e.schema,idProperty:e.idProperty,ids:[...e.loads.values()].map(({id:n})=>n)};try{const n=await this.#e.fetchEntities(r),o=new Map;for(const i of n){const s=i[e.idProperty.name]??i._id;if(s!=null){const a=typeof s=="string"?s:typeof s=="number"||typeof s=="boolean"||typeof s=="bigint"?String(s):JSON.stringify(s),u=i._id===a?i:{...i,_id:a};o.set(Fs(e.schema.id,s),u)}}for(const[i,s]of e.loads){const a=o.get(i)??ep(e.schema,e.idProperty,s.id);this.#t.set(i,a),this.#r.delete(i),s.resolve(a)}}catch(n){for(const[o,i]of e.loads)this.#r.delete(o),i.reject(n)}}}const np=(t,e)=>{if(!e.isArray||typeof t!="string")return t;const r=t.trim();if(!r.startsWith("[")||!r.endsWith("]"))return t;try{const n=JSON.parse(r);if(!Array.isArray(n))throw new Error("JSON result is not an array");return n}catch(n){throw new d("INVALID_ARRAY_RESULT",`Result column ${e.name} contains invalid array JSON`,{property:e.name,cause:n})}},op=async(t,e,r,n)=>{await Promise.all(t.map(async o=>{await Promise.all(e.map(async i=>{if(!(i.name in o))return;const s=np(o[i.name],i),a=r.get(i.type).hydrateResult;if(!a){o[i.name]=s;return}o[i.name]=i.isArray&&Array.isArray(s)?await Promise.all(s.map(u=>a(u,{property:i,requestEntity:n}))):await a(s,{property:i,requestEntity:n})}))}))},Ys=5,ip=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),sp=(t,e)=>{const r=e.properties.find(({type:n})=>n==="ID");return r?t[r.name]:void 0},ap=(t,e)=>{const r=Ia.getNameProperty(e);t._title=t[r.name]??t._id},cp=(t,e)=>{const r=structuredClone(t);if(!("_id"in r)){const n=sp(r,e);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},up=(t,e,r,n)=>{const o=`${e.id}:${n?"recursive":"leaf"}`,i=t.get(o);if(i){i.rows.push(r);return}t.set(o,{rows:[r],properties:e.properties,schema:e,expandEntities:n})},dp=async(t,e,r)=>{const n=new rp(r);let o=[{rows:t,properties:e,expandEntities:!0}];for(let i=0;o.length>0;i+=1){await Promise.all(o.map(a=>{const u=a.expandEntities&&i<Ys;return op(a.rows,a.properties,r.semanticTypes,u?n.load:(c,p)=>Promise.resolve(p))}));for(const a of o)if(a.schema)for(const u of a.rows)ap(u,a.schema);if(i>=Ys)return;const s=new Map;for(const a of o)if(a.expandEntities)for(const u of a.properties){if(u.primal_type!=="entity"&&u.primal_type!=="object"||!u.ref)continue;const c=r.resolveSchema(u.ref);for(const p of a.rows){if(!(u.name in p))continue;const l=p[u.name],f=u.isArray?Array.isArray(l)?l:[l]:[l];for(const[m,y]of f.entries()){if(!ip(y))continue;const h=cp(y,c);u.isArray?f[m]=h:p[u.name]=h,up(s,c,h,!u.isArray)}u.isArray&&(p[u.name]=f)}}o=[...s.values()]}},Hs=async(t,e,r)=>{const n=t.map(o=>({...o}));return await dp(n,e,r),n},fo=t=>`'${t.replaceAll("'","''")}'`,Qs=t=>{const e=[["\\","\\\\"],["\0","\\0"],["\b","\\b"],[" ","\\t"],[`
4
+ `,"\\n"],["\r","\\r"],["","\\Z"],['"','\\"'],["'","\\'"]];let r=t;for(const[n,o]of e)r=r.replaceAll(n,o);return`'${r}'`},nr=(t,e)=>{if(t==null)return"NULL";if(typeof t=="boolean")return e==="mysql"?t?"true":"false":e==="sqlserver"?t?"1":"0":t?"TRUE":"FALSE";if(typeof t=="number")return String(t);if(typeof t=="bigint")return e==="mysql"||e==="sqlserver"?t.toString():fo(t.toString());if(typeof t=="string")return e==="mysql"?Qs(t):fo(t);if(t instanceof Date){const r=e==="clickhouse"||e==="mysql"?t.toISOString().replace("T"," ").replace("Z",""):t.toISOString();return e==="mysql"?Qs(r):fo(r)}if(Buffer.isBuffer(t)){const r=t.toString("hex");return e==="mysql"?`X'${r}'`:e==="dameng"||e==="oracle"?`HEXTORAW('${r}')`:e==="postgresql"?`decode('${r}', 'hex')`:e==="snowflake"?`TO_BINARY('${r}', 'HEX')`:e==="sqlserver"?`0x${r}`:`unhex('${r}')`}throw new TypeError(`Unsupported ${e} display parameter type: ${typeof t}`)},lp=(t,e)=>t.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in e?nr(e[o],"clickhouse"):r}),pp=(t,e)=>t.replace(/:([1-9]\d*)\b/g,(r,n)=>{const o=Number(n)-1;return o in e?nr(e[o],"oracle"):r}),fp=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="$"){const s=/^\$(\d+)/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a)-1;if(u in e){r+=nr(e[u],"postgresql"),o+=s[0].length-1;continue}}}r+=i}}return r},mo=(t,e,r)=>{let n="",o=0,i;for(let s=0;s<t.length;s+=1){const a=t[s];if(a){if(i){n+=a,a===i&&(t[s+1]===i?(n+=i,s+=1):i=void 0);continue}if(a==="'"||a==='"'||a==="`"){i=a,n+=a;continue}if(a==="?"&&o<e.length){n+=nr(e[o],r),o+=1;continue}n+=a}}return n},mp=(t,e)=>mo(t,e,"mysql"),yo=(t,e)=>mo(t,e,"snowflake"),yp=(t,e)=>mo(t,e,"dameng"),hp=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="["){n="]",r+=i;continue}if(i==="@"){const s=/^@p(\d+)\b/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a);if(u in e){r+=nr(e[u],"sqlserver"),o+=s[0].length-1;continue}}}r+=i}}return r},Je=(t,e)=>new Error(`Database driver "${t}" is not installed or could not be loaded. Install it with: npm install ${t}`,{cause:e}),or=t=>{for(const[e,r]of Object.entries({database:t.database,schema:t.schema}))if(r!==void 0&&!r.trim())throw new d("INVALID_TABLE_SCOPE",`Table discovery ${e} must not be empty`)},Pe=(t,e)=>{throw new d("UNSUPPORTED_TABLE_SCOPE",`${t.kind} table discovery does not support a ${e} override`)},je=(t,e)=>Object.entries(t).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1],Oe=(t,e)=>{const r=je(t,e);if(typeof r!="string"||!r)throw new d("INVALID_TABLE_METADATA",`Expected a non-empty metadata field: ${e}`);return r},Gs=t=>{const e=Oe(t,"table_name"),r=je(t,"table_database"),n=je(t,"table_schema"),o=Oe(t,"table_type").toUpperCase();if(!["BASE TABLE","TABLE","FOREIGN TABLE","EXTERNAL TABLE","EVENT TABLE","VIEW","SYSTEM VIEW","MATERIALIZED VIEW"].includes(o))throw new d("INVALID_TABLE_METADATA",`Unsupported metadata table type: ${o}`);return{name:e,...typeof r=="string"?{database:r}:{},...typeof n=="string"?{schema:n}:{},type:o.includes("VIEW")?"view":"table"}},gp=t=>t.map(Gs),dt=async(t,e)=>{e.signal?.throwIfAborted(),or(e);const r=[],n=u=>{const c=t.parameter(r.length,u);return r.push(u),c},o=e.database,i=e.schema;let s;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":i!==void 0&&Pe(t,"schema"),s="SELECT TABLE_NAME AS table_name, TABLE_SCHEMA AS table_database, TABLE_TYPE AS table_type FROM information_schema.tables WHERE TABLE_SCHEMA = "+(o!==void 0?n(o):"DATABASE()");break;case"postgresql":o!==void 0&&Pe(t,"database"),s="SELECT table_name, table_catalog AS table_database, table_schema, table_type FROM information_schema.tables WHERE table_schema = "+(i!==void 0?n(i):"current_schema()");break;case"sqlserver":case"snowflake":{s=`SELECT TABLE_NAME AS table_name, TABLE_CATALOG AS table_database, TABLE_SCHEMA AS table_schema, TABLE_TYPE AS table_type FROM ${`${o!==void 0?`${t.quoteIdentifier(o)}.`:""}INFORMATION_SCHEMA.TABLES`}`,i!==void 0?s+=` WHERE TABLE_SCHEMA = ${n(i)}`:t.kind==="snowflake"&&(s+=" WHERE TABLE_SCHEMA = CURRENT_SCHEMA()");break}case"oracle":case"dameng":o!==void 0&&Pe(t,"database"),s="SELECT OBJECT_NAME AS table_name, OWNER AS table_schema, OBJECT_TYPE AS table_type FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TABLE', 'VIEW') AND OWNER = "+(i!==void 0?n(i):"SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')");break;case"clickhouse":i!==void 0&&Pe(t,"schema"),s="SELECT name AS table_name, database AS table_database, if(engine IN ('View', 'MaterializedView', 'LiveView', 'WindowView'), 'VIEW', 'TABLE') AS table_type FROM system.tables WHERE database = "+(o!==void 0?n(o):"currentDatabase()");break;default:throw new d("UNSUPPORTED_TABLE_DISCOVERY",`No metadata SQL for provider: ${t.kind}`)}s+=" ORDER BY table_name";const a=await t.execute({sql:s,parameters:r,...e.signal?{signal:e.signal}:{}});return e.signal?.throwIfAborted(),gp(a)},ho=t=>{if(or(t),!t.table.trim())throw new d("INVALID_TABLE_NAME","Table name must not be empty")},Vr=(t,e)=>{const r=je(t,e);return typeof r=="string"?r:""},Ap=t=>{const e=Oe(t,"column_type"),r=je(t,"type_length"),n=je(t,"type_precision"),o=je(t,"type_scale");return/^(?:n?varchar2?|n?char|n?varbinary|binary|raw)$/i.test(e)&&typeof r=="number"?`${e}(${r===-1?"max":r})`:/^(?:number|numeric|decimal)$/i.test(e)&&typeof n=="number"?`${e}(${n}${typeof o=="number"?`,${o}`:""})`:e},Ws=t=>{const e=je(t,"is_primary_key");let r;if(e!=null)if([!0,1,"1","true","TRUE","YES","Y"].includes(e))r=!0;else if([!1,0,"0","false","FALSE","NO","N"].includes(e))r=!1;else throw new d("INVALID_TABLE_METADATA","Invalid primary-key metadata");return{name:Oe(t,"column_name"),type:Ap(t),comment:Vr(t,"column_comment"),...r!==void 0?{primaryKey:r}:{}}},$p=(t,e)=>{const r=[],n=c=>{const p=t.parameter(r.length,c);return r.push(c),p},o=n(e.table),{database:i,schema:s}=e;let a,u;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":{s!==void 0&&Pe(t,"schema");const c=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${i!==void 0?n(i):"DATABASE()"}`;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_SCHEMA AS table_database, c.TABLE_TYPE AS table_type, c.TABLE_COMMENT AS table_comment FROM information_schema.tables c WHERE ${c}`,u=`SELECT c.COLUMN_NAME AS column_name, c.COLUMN_TYPE AS column_type, c.COLUMN_COMMENT AS column_comment, (c.COLUMN_KEY = 'PRI') AS is_primary_key FROM information_schema.columns c WHERE ${c} ORDER BY c.ORDINAL_POSITION`;break}case"postgresql":{i!==void 0&&Pe(t,"database");const c=`c.relname = ${o} AND n.nspname = ${s!==void 0?n(s):"current_schema()"}`;a=`SELECT c.relname AS table_name, current_database() AS table_database, n.nspname AS table_schema, CASE WHEN c.relkind IN ('v', 'm') THEN 'VIEW' ELSE 'TABLE' END AS table_type, obj_description(c.oid, 'pg_class') AS table_comment FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE ${c} AND c.relkind IN ('r', 'v', 'm', 'p', 'f')`,u=`SELECT a.attname AS column_name, format_type(a.atttypid, a.atttypmod) AS column_type, col_description(c.oid, a.attnum) AS column_comment, EXISTS (SELECT 1 FROM pg_catalog.pg_index i WHERE i.indrelid = c.oid AND i.indisprimary AND a.attnum = ANY(i.indkey)) AS is_primary_key FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE ${c} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`;break}case"sqlserver":{const c=i!==void 0?`${t.quoteIdentifier(i)}.`:"",p=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"SCHEMA_NAME()"}`,l=`JOIN ${c}sys.schemas s ON s.name = c.TABLE_SCHEMA JOIN ${c}sys.objects o ON o.schema_id = s.schema_id AND o.name = c.TABLE_NAME `;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_CATALOG AS table_database, c.TABLE_SCHEMA AS table_schema, c.TABLE_TYPE AS table_type, CAST(ep.value AS nvarchar(max)) AS table_comment FROM ${c}INFORMATION_SCHEMA.TABLES c ${l}LEFT JOIN ${c}sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id AND ep.minor_id = 0 AND ep.name = 'MS_Description' WHERE ${p}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, c.CHARACTER_MAXIMUM_LENGTH AS type_length, c.NUMERIC_PRECISION AS type_precision, c.NUMERIC_SCALE AS type_scale, CAST(ep.value AS nvarchar(max)) AS column_comment, CASE WHEN EXISTS (SELECT 1 FROM ${c}sys.indexes i JOIN ${c}sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id WHERE i.object_id = o.object_id AND i.is_primary_key = 1 AND ic.key_ordinal > 0 AND ic.column_id = sc.column_id) THEN 1 ELSE 0 END AS is_primary_key FROM ${c}INFORMATION_SCHEMA.COLUMNS c ${l}JOIN ${c}sys.columns sc ON sc.object_id = o.object_id AND sc.name = c.COLUMN_NAME LEFT JOIN ${c}sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id AND ep.minor_id = sc.column_id AND ep.name = 'MS_Description' WHERE ${p} ORDER BY c.ORDINAL_POSITION`;break}case"snowflake":{const c=`${i!==void 0?`${t.quoteIdentifier(i)}.`:""}INFORMATION_SCHEMA`,p=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"CURRENT_SCHEMA()"}`;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_CATALOG AS table_database, c.TABLE_SCHEMA AS table_schema, c.TABLE_TYPE AS table_type, c.COMMENT AS table_comment FROM ${c}.TABLES c WHERE ${p}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, c.COMMENT AS column_comment, c.CHARACTER_MAXIMUM_LENGTH AS type_length, c.NUMERIC_PRECISION AS type_precision, c.NUMERIC_SCALE AS type_scale FROM ${c}.COLUMNS c WHERE ${p} ORDER BY c.ORDINAL_POSITION`;break}case"oracle":case"dameng":{i!==void 0&&Pe(t,"database");const c=`c.TABLE_NAME = ${o} AND c.OWNER = ${s!==void 0?n(s):"SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')"}`;a=`SELECT c.TABLE_NAME AS table_name, c.OWNER AS table_schema, c.TABLE_TYPE AS table_type, c.COMMENTS AS table_comment FROM ALL_TAB_COMMENTS c WHERE ${c}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, CASE WHEN c.DATA_TYPE = 'RAW' THEN c.DATA_LENGTH ELSE c.CHAR_LENGTH END AS type_length, c.DATA_PRECISION AS type_precision, c.DATA_SCALE AS type_scale, cm.COMMENTS AS column_comment, CASE WHEN EXISTS (SELECT 1 FROM ALL_CONS_COLUMNS k JOIN ALL_CONSTRAINTS t ON t.OWNER = k.OWNER AND t.CONSTRAINT_NAME = k.CONSTRAINT_NAME WHERE t.CONSTRAINT_TYPE = 'P' AND k.OWNER = c.OWNER AND k.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END AS is_primary_key FROM ALL_TAB_COLUMNS c LEFT JOIN ALL_COL_COMMENTS cm ON cm.OWNER = c.OWNER AND cm.TABLE_NAME = c.TABLE_NAME AND cm.COLUMN_NAME = c.COLUMN_NAME WHERE ${c} ORDER BY c.COLUMN_ID`;break}case"clickhouse":{s!==void 0&&Pe(t,"schema");const c=i!==void 0?n(i):"currentDatabase()";a=`SELECT c.name AS table_name, c.database AS table_database, c.comment AS table_comment, if(c.engine IN ('View', 'MaterializedView', 'LiveView', 'WindowView'), 'VIEW', 'TABLE') AS table_type FROM system.tables c WHERE c.name = ${o} AND c.database = ${c}`,u=`SELECT c.name AS column_name, c.type AS column_type, c.comment AS column_comment, c.is_in_primary_key AS is_primary_key FROM system.columns c WHERE c.table = ${o} AND c.database = ${c} ORDER BY c.position`;break}default:throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`No table description SQL for provider: ${t.kind}`)}return{tableSql:a,columnSql:u,parameters:r}},zs=(t,e)=>{const r=[];return!["postgresql","oracle","dameng"].includes(t.kind)&&e.database!==void 0&&r.push(e.database),e.schema!==void 0&&r.push(e.schema),r.push(e.name),r.map(n=>t.quoteIdentifier(n)).join(".")},Ct=async(t,e,r,n=[])=>{e.signal?.throwIfAborted();const o=await t.execute({sql:r,parameters:n,...e.signal?{signal:e.signal}:{}});return e.signal?.throwIfAborted(),o},go=async(t,e,r)=>{if(e.includeSample===!1)return r;const n=zs(t,r.tableInfo),o=t.kind==="sqlserver"?`SELECT TOP (1) * FROM ${n}`:["oracle","dameng"].includes(t.kind)?`SELECT * FROM ${n} FETCH FIRST 1 ROWS ONLY`:`SELECT * FROM ${n} LIMIT 1`;let i;try{[i]=await Ct(t,e,o)}catch{return e.signal?.throwIfAborted(),r}return i?{...r,columns:r.columns.map(s=>({...s,...Object.hasOwn(i,s.name)?{exampleValue:i[s.name]}:{}}))}:r},wp=async(t,e)=>{let{database:r,schema:n}=e;if(r===void 0||n===void 0){const[l]=await Ct(t,e,"SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!l)throw new d("INVALID_TABLE_METADATA","Databricks current namespace was not returned");r??=Oe(l,"table_database"),n??=Oe(l,"table_schema")}const o=zs(t,{name:e.table,database:r,schema:n}),i=await Ct(t,e,`DESCRIBE TABLE EXTENDED ${o}`),s=[];let a=!0,u=!1,c="",p="table";for(const l of i){const f=je(l,"col_name"),m=je(l,"data_type"),y=(f==="# Partition Information"||f==="# Detailed Table Information")&&!m;(f===""||y)&&(a=!1),y&&f==="# Detailed Table Information"&&(u=!0),a?s.push({name:Oe(l,"col_name"),type:Oe(l,"data_type"),comment:Vr(l,"comment")}):u&&f==="Comment"?c=Vr(l,"data_type"):u&&f==="Type"&&m==="VIEW"&&(p="view")}if(!s.length)throw new d("INVALID_TABLE_METADATA","Databricks description did not contain columns");return go(t,e,{columns:s,tableInfo:{name:e.table,database:r,schema:n,type:p,comment:c}})},Ep=async(t,e)=>{e.database!==void 0&&Pe(t,"database"),e.schema!==void 0&&Pe(t,"schema");const n=(await Ct(t,e,`DESC ${t.quoteIdentifier(e.table)}`)).map(Ws);if(!n.length)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);return go(t,e,{columns:n,tableInfo:{name:e.table,type:"table",comment:""}})},Ye=async(t,e)=>{if(e.signal?.throwIfAborted(),ho(e),t.kind==="databricks")return wp(t,e);if(t.kind==="maxcompute")return Ep(t,e);const{tableSql:r,columnSql:n,parameters:o}=$p(t,e),i=await Ct(t,e,r,o),[s]=i;if(!s)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);if(i.length!==1)throw new d("AMBIGUOUS_TABLE",`More than one table matched: ${e.table}`);const a={...Gs(s),comment:Vr(s,"table_comment")},u=(await Ct(t,e,n,o)).map(Ws);return go(t,e,{columns:u,tableInfo:a})},_p=t=>{if(t.url!==void 0)return t.url;const e=t.host??"localhost";if(/^[a-z][a-z\d+.-]*:\/\//iu.test(e)){if(t.port===void 0)return e;const n=new URL(e);return n.port=String(t.port),n.toString()}return`http://${e}:${t.port??8123}`},Sp=t=>t===null?"Nullable(String)":typeof t=="boolean"?"Bool":typeof t=="number"?"Float64":t instanceof Date?"DateTime64(3)":"String",Ks=t=>t instanceof Date?t.toISOString().replace("T"," ").replace("Z",""):t;class Ip{kind="clickhouse";supportsRecursiveCte=!0;recursiveCteUnion="UNION ALL";#e;#t;constructor(e={}){this.#e=e,this.#t=e.client?Promise.resolve(e.client):void 0}async#r(){this.#t??=(async()=>{const{createClient:e}=await import("@clickhouse/client").catch(r=>{throw Je("@clickhouse/client",r)});return e({url:_p(this.#e),username:this.#e.username??this.#e.user??"default",password:this.#e.password??"",database:this.#e.database??"default"})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`\`${e.replaceAll("`","``")}\``}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return`{p${e}:${Sp(r)}}`}displayQuery(e,r){return lp(e,r)}dateBucket(e,r){if(r==="second")return`toDateTime64(${e}, 0)`;const o={minute:"toStartOfMinute",hour:"toStartOfHour",day:"toStartOfDay",week:"toStartOfWeek",month:"toStartOfMonth",quarter:"toStartOfQuarter",year:"toStartOfYear"}[r];if(!o)throw new Error(`Unsupported ClickHouse date level: ${r}`);return`${o}(${e})`}datePart(e,r){return`${{second:"toSecond",minute:"toMinute",hour:"toHour",weekday:"toDayOfWeek",day:"toDayOfMonth",week:"toISOWeek",month:"toMonth",quarter:"toQuarter",year:"toYear"}[r]}(${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported ClickHouse date shift: ${r}/${n}`);return`dateAdd(${r}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`toDateTime(${e})`:r==="date"?`toDate(${e})`:e}scalarExtremum(e,r){const n=`[${r.map(s=>`toNullable(${s})`).join(", ")}]`,o=`arrayFilter(value -> isNotNull(value), ${n})`;return`if(arrayExists(value -> isNotNull(value), ${n}), ${e==="least"?"arrayMin":"arrayMax"}(${o}), NULL)`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported ClickHouse aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`toString(${e})`}concat(e){return`concat(${e.join(", ")})`}substring(e,r,n){return`substring(${e}, ${r}, ${n})`}stringLength(e){return`lengthUTF8(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported ClickHouse regex options: ${n}`);const o=n==="i"?`concat('(?i)', ${r})`:r;return`match(${e}, ${o})`}arrayContains(e,r){return`has(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`ARRAY JOIN ${e} AS ${o}`,valueExpression:o}}async execute(e){e.signal?.throwIfAborted();const r=await this.#r();e.signal?.throwIfAborted();const n=Object.fromEntries(e.parameters.map((i,s)=>[`p${s}`,Ks(i)]));return(await r.query({query:e.sql,format:"JSONEachRow",query_params:n,...e.signal?{abort_signal:e.signal}:{}})).json()}getTableList(e){return dt(this,e)}describeTable(e){return Ye(this,e)}async runSQL(e){e.signal?.throwIfAborted();const r=await this.#r();if(e.signal?.throwIfAborted(),!r.exec)throw new d("UNSUPPORTED_RAW_SQL","ClickHouse native SQL requires client.exec");const n=await r.exec({query:e.sql,query_params:Object.fromEntries(e.parameters.map((a,u)=>[`p${u}`,Ks(a)])),clickhouse_settings:{default_format:"JSONEachRow"},...e.signal?{abort_signal:e.signal}:{}}),o=[];for await(const a of n.stream)e.signal?.throwIfAborted(),o.push(Buffer.isBuffer(a)?a:Buffer.from(a));e.signal?.throwIfAborted();const i=Buffer.concat(o).toString("utf8").trim();return{rows:i?i.split(`
5
+ `).map(a=>{const u=JSON.parse(a);if(typeof u!="object"||u===null||Array.isArray(u))throw new Error("ClickHouse provider expected object rows");return u}):[]}}async close(){const e=this.#t;if(!e)return;await(await e).close(),this.#t=void 0}}const bp=t=>[".azuredatabricks.net",".databricks.azure.cn",".databricks.azure.us"].some(e=>t.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]?.endsWith(e)),Rp=t=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Databricks connection options must be an object");const e=t,{host:r,path:n,authType:o}=e;if(typeof r!="string"||r.length===0||typeof n!="string"||n.length===0)throw new Error("Databricks connection requires host and path");if(o==="databricks-oauth"){const{oauthClientId:i,oauthClientSecret:s}=e;if(typeof i!="string"||i.length===0||typeof s!="string"||s.length===0)throw new Error("Databricks OAuth requires oauthClientId and oauthClientSecret");if("token"in e)throw new Error("Databricks OAuth connection must not define token");if("azureTenantId"in e&&typeof e.azureTenantId!="string")throw new Error("Databricks OAuth azureTenantId must be a string");if("oauthScopes"in e&&(!Array.isArray(e.oauthScopes)||e.oauthScopes.some(a=>typeof a!="string")))throw new Error("Databricks OAuth oauthScopes must be a string array");if("useDatabricksOAuthInAzure"in e&&typeof e.useDatabricksOAuthInAzure!="boolean")throw new Error("Databricks OAuth useDatabricksOAuthInAzure must be boolean");return{host:r,path:n,authType:o,oauthClientId:i,oauthClientSecret:s,...typeof e.azureTenantId=="string"?{azureTenantId:e.azureTenantId}:{},...Array.isArray(e.oauthScopes)?{oauthScopes:e.oauthScopes}:{},useDatabricksOAuthInAzure:e.useDatabricksOAuthInAzure??(bp(r)&&!e.azureTenantId)}}if(o==="access-token"){if(typeof e.token!="string"||e.token.length===0)throw new Error("Databricks access-token connection requires token");if(["oauthClientId","oauthClientSecret","azureTenantId","oauthScopes","useDatabricksOAuthInAzure"].some(i=>i in e))throw new Error("Databricks access-token connection must not define OAuth fields");return{host:r,path:n,authType:o,token:e.token}}throw new Error(`Unsupported Databricks authType: ${String(o)}`)},Np=t=>{if(t==null)return null;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"||t instanceof Date)return t;throw new TypeError(`Unsupported Databricks parameter type: ${typeof t}`)};class Op{kind="databricks";supportsHavingAlias=!1;supportsRecursiveCte=!0;#e;#t;#r;constructor(e={}){this.#e=e.connection,this.#t=e.client}async#n(){this.#r??=(async()=>{const e=this.#t??new(await import("@databricks/sql").catch(r=>{throw Je("@databricks/sql",r)})).DBSQLClient;if(this.#e)try{await e.connect(Rp(this.#e))}catch(r){throw await e.close().catch(()=>{}),r}return e})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`\`${e.replaceAll("`","``")}\``}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return yo(e,r)}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Databricks date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${e})`}datePart(e,r){const n={second:"SECOND",minute:"MINUTE",hour:"HOUR",day:"DAYOFMONTH",week:"WEEKOFYEAR",month:"MONTH",quarter:"QUARTER",year:"YEAR"};return r==="weekday"?`(WEEKDAY(${e}) + 1)`:`${n[r]}(${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported Databricks date shift: ${r}/${n}`);return`TIMESTAMPADD(${r.toUpperCase()}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`CAST(${e} AS TIMESTAMP)`:r==="date"?`CAST(${e} AS DATE)`:e}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Databricks aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS STRING)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Databricks regex options: ${n}`);return`${e} RLIKE ${n==="i"?`CONCAT('(?i)', ${r})`:r}`}arrayContains(e,r){return`ARRAY_CONTAINS(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`LATERAL VIEW EXPLODE(${e}) ${o} AS ${i}`,valueExpression:`${o}.${i}`}}async execute(e){e.signal?.throwIfAborted();const r=await this.#n();e.signal?.throwIfAborted();const n=this.#e?.schema??this.#e?.database,o=await r.openSession({...this.#e?.catalog?{initialCatalog:this.#e.catalog}:{},...n?{initialSchema:n}:{}});let i;const s=()=>{i&&i.cancel().catch(()=>{})};e.signal?.addEventListener("abort",s,{once:!0});try{e.signal?.throwIfAborted(),i=await o.executeStatement(e.sql,{ordinalParameters:e.parameters.map(Np)}),e.signal?.aborted&&s(),e.signal?.throwIfAborted(),await i.finished?.(),e.signal?.throwIfAborted();const a=await i.fetchAll();if(e.signal?.throwIfAborted(),!Array.isArray(a))throw new Error("Databricks provider expected an array result");return a}finally{e.signal?.removeEventListener("abort",s);try{i&&await i.close()}finally{await o.close()}}}async runSQL(e){return{rows:await this.execute(e)}}describeTable(e){const r=e.database??this.#e?.catalog,n=e.schema??this.#e?.schema??this.#e?.database;return Ye(this,{...e,...r!==void 0?{database:r}:{},...n!==void 0?{schema:n}:{}})}async getTableList(e){e.signal?.throwIfAborted(),or(e);const r=c=>this.execute({sql:c,parameters:[],...e.signal?{signal:e.signal}:{}});let n=e.database??this.#e?.catalog,o=e.schema??this.#e?.schema??this.#e?.database;if(n===void 0||o===void 0){const[c]=await r("SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!c)throw new Error("Databricks current namespace was not returned");n??=Oe(c,"table_database"),o??=Oe(c,"table_schema")}const i=`${this.quoteIdentifier(n)}.${this.quoteIdentifier(o)}`,s=await r(`SHOW TABLES IN ${i}`),a=await r(`SHOW VIEWS IN ${i}`),u=new Map;for(const c of s){const p=Oe(c,"tableName");u.set(p,{name:p,database:n,schema:o,type:"table"})}for(const c of a){const p=Oe(c,"viewName");u.set(p,{name:p,database:n,schema:o,type:"view"})}return[...u.values()].sort((c,p)=>c.name.localeCompare(p.name))}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}const Js=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="boolean")return t?1:0;if(typeof t=="string"||typeof t=="number"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported Dameng parameter type: ${typeof t}`)},Tp=t=>{const{host:e,port:r,...n}=t;return{...n,connectString:t.connectString??`${e??"localhost"}:${r??5236}`}};class Pp{kind="dameng";supportsHavingAlias=!1;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}async#n(){this.#r??=(async()=>{const e={...Tp(this.#e),poolAlias:typeof this.#e.poolAlias=="string"?this.#e.poolAlias:`semanticdb-${Co.randomUUID()}`};if(this.#t)return this.#t.createPool(e);const{default:r}=await import("dmdb").catch(n=>{throw Je("dmdb",n)});return r.createPool(e)})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} ${this.quoteIdentifier(r)}`}paginate(e,r,n){return n>0?`${e} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`:`${e} FETCH FIRST ${r} ROWS ONLY`}parameter(e,r){return"?"}displayQuery(e,r){return yp(e,r.map(Js))}dateBucket(e,r){const n={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(r in n))throw new Error(`Unsupported Dameng date level: ${r}`);const o=n[r];return o?`TRUNC(${e}, '${o}')`:`TRUNC(${e})`}datePart(e,r){return r==="weekday"?`(TRUNC(${e}) - TRUNC(${e}, 'IW') + 1)`:`TO_NUMBER(TO_CHAR(${e}, '${{second:"SS",minute:"MI",hour:"HH24",day:"DD",week:"IW",month:"MM",quarter:"Q",year:"YYYY"}[r]}'))`}dateShift(e,r,n){if(!Number.isInteger(n))throw new Error(`Unsupported Dameng date shift: ${r}/${n}`);const i={month:1,quarter:3,year:12}[r];if(i)return`ADD_MONTHS(${e}, ${n*i})`;const a={second:{unit:"SECOND",multiplier:1},minute:{unit:"MINUTE",multiplier:1},hour:{unit:"HOUR",multiplier:1},day:{unit:"DAY",multiplier:1},week:{unit:"DAY",multiplier:7}}[r];if(!a)throw new Error(`Unsupported Dameng date shift: ${r}/${n}`);return`(${e} + NUMTODSINTERVAL(${n*a.multiplier}, '${a.unit}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Dameng aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_CHAR(${e})`}concat(e){return`(${e.join(" || ")})`}substring(e,r,n){return`SUBSTR(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Dameng regex options: ${n}`);return`REGEXP_LIKE(${e}, ${r}${n?", 'i'":""})`}async execute(e){return(await this.#o(e,!1)).rows}async runSQL(e){return this.#o(e,!0)}getTableList(e){return dt(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}describeTable(e){return Ye(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=await n.getConnection();try{e.signal?.throwIfAborted();const i=await o.execute(e.sql,e.parameters.map(Js),{outFormat:4002,...r?{autoCommit:!0}:{}});if(e.signal?.throwIfAborted(),!(r&&i.rows===void 0)&&!Array.isArray(i.rows))throw new Error("Dameng provider expected an array result");return{rows:i.rows??[],...typeof i.rowsAffected=="number"?{affectedRows:i.rowsAffected}:{}}}finally{await o.close()}}async close(){const e=this.#r;if(!e)return;await(await e).close(0),this.#r=void 0}}const X={quoteIdentifier(t){return`\`${t.replaceAll("`","``")}\``},tableAlias(t,e){return`${t} AS ${this.quoteIdentifier(e)}`},paginate(t,e,r){return`${t} LIMIT ${e}${r>0?` OFFSET ${r}`:""}`},parameter(t,e){return"?"},displayQuery(t,e){return mp(t,e)},dateBucket(t,e){const r={hour:"%Y-%m-%d %H:00:00",day:"%Y-%m-%d",month:"%Y-%m-01",year:"%Y-01-01"};if(e==="week")return`DATE_SUB(DATE(${t}), INTERVAL WEEKDAY(${t}) DAY)`;if(e==="quarter")return`MAKEDATE(YEAR(${t}), 1) + INTERVAL (QUARTER(${t}) - 1) QUARTER`;const n=r[e];if(!n)throw new Error(`Unsupported MySQL-compatible date level: ${e}`);return`DATE_FORMAT(${t}, '${n}')`},datePart(t,e){const r={second:"SECOND",minute:"MINUTE",hour:"HOUR",day:"DAYOFMONTH",month:"MONTH",quarter:"QUARTER",year:"YEAR"};if(e==="weekday")return`(WEEKDAY(${t}) + 1)`;if(e==="week")return`WEEK(${t}, 3)`;const n=r[e];if(!n)throw new Error(`Unsupported MySQL-compatible date part: ${e}`);return`${n}(${t})`},dateShift(t,e,r){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(e)||!Number.isInteger(r))throw new Error(`Unsupported MySQL-compatible date shift: ${e}/${r}`);return`DATE_ADD(${t}, INTERVAL ${r} ${e.toUpperCase()})`},datePeriodBoundary(t,e,r){if(r==="start")return this.dateBucket(t,e);switch(e){case"hour":return`DATE_FORMAT(${t}, '%Y-%m-%d %H:59:59')`;case"day":return`TIMESTAMP(DATE(${t}), '23:59:59')`;case"month":return`TIMESTAMP(LAST_DAY(${t}), '23:59:59')`;case"year":return`CONCAT(YEAR(${t}), '-12-31 23:59:59')`;default:return this.dateShift(this.dateShift(this.dateBucket(t,e),e,1),"second",-1)}},aggregateFunction(t,e="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(t))throw new Error(`Unsupported MySQL-compatible aggregate function: ${t}`);return`${t.toUpperCase()}(${e})`},stringify(t){return`CAST(${t} AS CHAR)`},concat(t){return`CONCAT(${t.join(", ")})`},substring(t,e,r){return`SUBSTRING(${t}, ${e}, ${r})`},stringLength(t){return`CHAR_LENGTH(${t})`},regex(t,e,r){if(r&&r!=="i")throw new Error(`Unsupported MySQL-compatible regex options: ${r}`);return r==="i"?`LOWER(${t}) REGEXP LOWER(${e})`:`${t} REGEXP ${e}`},arrayContains(t,e){return`JSON_OVERLAPS(${t}, JSON_ARRAY(${e}))`},expandArray(t,e,r){const n=this.quoteIdentifier(e),o=this.quoteIdentifier(r);return{joinSql:`CROSS JOIN JSON_TABLE(CASE WHEN JSON_TYPE(${t}) = 'ARRAY' THEN ${t} ELSE JSON_ARRAY() END, '$[*]' COLUMNS (${o} JSON PATH '$')) AS ${n}`,valueExpression:`${n}.${o}`}}},Lp={connectionLimit:30,maxIdle:10,idleTimeout:6e4,enableKeepAlive:!0,keepAliveInitialDelay:0};class vr{supportsRecursiveCte=!0;#e;#t;constructor(e={}){this.#e=e.connection??{},this.#t=e.pool?Promise.resolve(e.pool):void 0}async#r(){this.#t??=(async()=>{const{createPool:e}=await import("mysql2/promise").catch(r=>{throw Je("mysql2",r)});return e({...Lp,decimalNumbers:!0,...this.#e})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return X.quoteIdentifier(e)}tableAlias(e,r){return X.tableAlias(e,r)}paginate(e,r,n){return X.paginate(e,r,n)}parameter(e,r){return X.parameter(e,r)}displayQuery(e,r){return X.displayQuery(e,r)}dateBucket(e,r){return X.dateBucket(e,r)}datePart(e,r){return X.datePart(e,r)}dateShift(e,r,n){return X.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=X.datePeriodBoundary?.bind(X);if(!o)throw new Error("MySQL date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return X.aggregateFunction(e,r)}stringify(e){return X.stringify(e)}concat(e){return X.concat(e)}substring(e,r,n){return X.substring(e,r,n)}stringLength(e){return X.stringLength(e)}regex(e,r,n){return X.regex(e,r,n)}arrayContains(e,r){const n=X.arrayContains?.bind(X);if(!n)throw new Error("MySQL-compatible array conditions are unavailable");return n(e,r)}expandArray(e,r,n){const o=X.expandArray?.bind(X);if(!o)throw new Error("MySQL-compatible array expansion is unavailable");return o(e,r,n)}async execute(e){return(await this.#n(e,!1)).rows}async runSQL(e){return this.#n(e,!0)}getTableList(e){return dt(this,e)}describeTable(e){return Ye(this,e)}async#n(e,r){e.signal?.throwIfAborted();const n=await this.#r();e.signal?.throwIfAborted();const[o]=await n.execute(e.sql,e.parameters);if(e.signal?.throwIfAborted(),r&&typeof o=="object"&&o!==null&&"affectedRows"in o&&typeof o.affectedRows=="number")return{rows:[],affectedRows:o.affectedRows};if(!Array.isArray(o))throw new Error(`${this.kind} provider expected an array result`);return{rows:o}}async close(){const e=this.#t;if(!e)return;await(await e).end(),this.#t=void 0}}class Dp extends vr{kind="doris";constructor(e={}){super(e)}}class Cp extends vr{kind="gbase";supportsRecursiveCte=!1;constructor(e={}){super({...e,connection:{port:5258,...e.connection}})}}class kp{kind="maxcompute";supportsRecursiveCte=!1;#e;#t=!1;constructor(e){this.#e=e.client}quoteIdentifier(e){return X.quoteIdentifier(e)}tableAlias(e,r){return X.tableAlias(e,r)}paginate(e,r,n){return X.paginate(e,r,n)}parameter(e,r){return X.parameter(e,r)}displayQuery(e,r){return X.displayQuery(e,r)}dateBucket(e,r){return X.dateBucket(e,r)}datePart(e,r){return X.datePart(e,r)}dateShift(e,r,n){return X.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=X.datePeriodBoundary?.bind(X);if(!o)throw new Error("MaxCompute date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return X.aggregateFunction(e,r)}stringify(e){return X.stringify(e)}concat(e){return X.concat(e)}substring(e,r,n){return X.substring(e,r,n)}stringLength(e){return X.stringLength(e)}regex(e,r,n){return X.regex(e,r,n)}async execute(e){e.signal?.throwIfAborted();const r=await this.#e.execute(e);if(e.signal?.throwIfAborted(),!Array.isArray(r))throw new Error("MaxCompute provider expected an array result");return r}async runSQL(e){e.signal?.throwIfAborted();const r=this.#e.runSQL?await this.#e.runSQL(e):{rows:await this.execute(e)};return e.signal?.throwIfAborted(),r}async getTableList(e){if(e.signal?.throwIfAborted(),or(e),this.#e.getTableList){const n=await this.#e.getTableList(e);return e.signal?.throwIfAborted(),n}return e.database!==void 0&&Pe(this,"database"),e.schema!==void 0&&Pe(this,"schema"),(await this.execute({sql:"SHOW TABLES",parameters:[],...e.signal?{signal:e.signal}:{}})).map(n=>({name:Oe(n,"table_name"),type:"table"}))}async close(){this.#t||(await this.#e.close(),this.#t=!0)}async describeTable(e){if(e.signal?.throwIfAborted(),ho(e),!this.#e.describeTable)return Ye(this,e);const r=await this.#e.describeTable(e);return e.signal?.throwIfAborted(),r}}class Up extends vr{kind="mysql";constructor(e={}){super(e)}}const Xs=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported Oracle parameter type: ${typeof t}`)},Mp=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class qp{kind="oracle";supportsHavingAlias=!1;maxInListItems=1e3;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} ${this.quoteIdentifier(r)}`}paginate(e,r,n){return n>0?`${e} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`:`${e} FETCH FIRST ${r} ROWS ONLY`}parameter(e,r){return`:${e+1}`}displayQuery(e,r){return pp(e,r.map(Xs))}dateBucket(e,r){const n={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(r in n))throw new Error(`Unsupported Oracle date level: ${r}`);const o=n[r];return o?`TRUNC(${e}, '${o}')`:`TRUNC(${e})`}datePart(e,r){return r==="weekday"?`(TRUNC(${e}) - TRUNC(${e}, 'IW') + 1)`:`TO_NUMBER(TO_CHAR(${e}, '${{second:"SS",minute:"MI",hour:"HH24",day:"DD",week:"IW",month:"MM",quarter:"Q",year:"YYYY"}[r]}'))`}dateShift(e,r,n){if(!Number.isInteger(n))throw new Error(`Unsupported Oracle date shift: ${r}/${n}`);const i={month:1,quarter:3,year:12}[r];if(i)return`ADD_MONTHS(${e}, ${n*i})`;const a={second:{unit:"SECOND",multiplier:1},minute:{unit:"MINUTE",multiplier:1},hour:{unit:"HOUR",multiplier:1},day:{unit:"DAY",multiplier:1},week:{unit:"DAY",multiplier:7}}[r];if(!a)throw new Error(`Unsupported Oracle date shift: ${r}/${n}`);return`(${e} + NUMTODSINTERVAL(${n*a.multiplier}, '${a.unit}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Oracle aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_CHAR(${e})`}concat(e){return`(${e.join(" || ")})`}substring(e,r,n){return`SUBSTR(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Oracle regex options: ${n}`);return`REGEXP_LIKE(${e}, ${r}${n?", 'i'":""})`}arrayContains(e,r){return`JSON_EXISTS(${e}, '$?(@ == $value)' PASSING ${r} AS "value")`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS APPLY JSON_TABLE(${e}, '$[*]' COLUMNS (${i} VARCHAR2(4000) PATH '$')) ${o}`,valueExpression:`${o}.${i}`}}async#n(){this.#r??=(async()=>{if(this.#t)return this.#t.createPool(this.#e);const{default:e}=await import("oracledb").catch(r=>{throw Je("oracledb",r)});return e.createPool(this.#e)})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}async execute(e){return(await this.#o(e,!1)).rows}async runSQL(e){return this.#o(e,!0)}getTableList(e){return dt(this,e)}describeTable(e){return Ye(this,e)}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=await n.getConnection(),i=e.signal,s=()=>{o.break().catch(()=>{})};i?.addEventListener("abort",s,{once:!0});try{i?.throwIfAborted();const a=await o.execute(e.sql,e.parameters.map(Xs),{outFormat:4002,...r?{autoCommit:!0}:{}});if(i?.throwIfAborted(),!(r&&a.rows===void 0)&&!Array.isArray(a.rows))throw new Error("Oracle provider expected an array result");return{rows:a.rows??[],...typeof a.rowsAffected=="number"?{affectedRows:a.rowsAffected}:{}}}catch(a){throw i?.aborted?Mp(i):a}finally{i?.removeEventListener("abort",s),await o.close()}}async close(){const e=this.#r;if(!e)return;await(await e).close(0),this.#r=void 0}}class jp{kind="postgresql";supportsHavingAlias=!1;supportsRecursiveCte=!0;#e;#t;constructor(e={}){this.#e=e.connection??{},this.#t=e.pool?Promise.resolve(e.pool):void 0}async#r(){this.#t??=(async()=>{const{Pool:e}=await import("pg").catch(r=>{throw Je("pg",r)});return new e(this.#e)})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return`$${e+1}`}displayQuery(e,r){return fp(e,r)}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported PostgreSQL date level: ${r}`);return`DATE_TRUNC('${r}', ${e})`}datePart(e,r){return`EXTRACT(${r==="weekday"?"ISODOW":r.toUpperCase()} FROM ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported PostgreSQL date shift: ${r}/${n}`);return`(${e} + (${n} * INTERVAL '1 ${r}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported PostgreSQL aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS TEXT)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e} FROM ${r} FOR ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported PostgreSQL regex options: ${n}`);return`${e} ${n==="i"?"~*":"~"} ${r}`}arrayContains(e,r){return`${r} = ANY(${e})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS JOIN LATERAL unnest(${e}) AS ${o}(${i})`,valueExpression:`${o}.${i}`}}async execute(e){return(await this.runSQL(e)).rows}getTableList(e){return dt(this,e)}describeTable(e){return Ye(this,e)}async runSQL(e){e.signal?.throwIfAborted();const r=await this.#r();e.signal?.throwIfAborted();const n=await r.query(e.sql,[...e.parameters]);if(e.signal?.throwIfAborted(),!Array.isArray(n.rows))throw new Error("PostgreSQL provider expected an array result");return{rows:n.rows,...typeof n.rowCount=="number"&&["INSERT","UPDATE","DELETE","MERGE"].includes(n.command??"")?{affectedRows:n.rowCount}:{}}}async close(){const e=this.#t;if(!e)return;await(await e).end(),this.#t=void 0}}const Zs=t=>{if(t==null)return null;if(t instanceof Date)return t.toISOString();if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;throw new TypeError(`Unsupported Snowflake parameter type: ${typeof t}`)},xp=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class Bp{kind="snowflake";#e;#t;#r=!1;#n;constructor(e={}){this.#e=e.connection??{},this.#t=e.client?Promise.resolve(e.client):void 0}async#o(){this.#t??=(async()=>{const{default:e}=await import("snowflake-sdk").catch(r=>{throw Je("snowflake-sdk",r)});return e.createConnection(this.#e)})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return yo(e,r.map(Zs))}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Snowflake date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${e})`}datePart(e,r){return`DATE_PART(${r==="weekday"?"DAYOFWEEKISO":r==="week"?"WEEKISO":r.toUpperCase()}, ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported Snowflake date shift: ${r}/${n}`);return`DATEADD(${r.toUpperCase()}, ${n}, ${e})`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Snowflake aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_VARCHAR(${e})`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Snowflake regex options: ${n}`);return n?`REGEXP_INSTR(${e}, ${r}, 1, 1, 0, '${n}') > 0`:`REGEXP_INSTR(${e}, ${r}) > 0`}arrayContains(e,r){return`ARRAY_CONTAINS(${r}::VARIANT, ${e})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`, LATERAL FLATTEN(INPUT => ${e}) ${o}`,valueExpression:`${o}.VALUE`}}async#s(){if(this.#r)return;const e=await this.#o();this.#n??=new Promise((r,n)=>{e.connect(o=>{if(o){n(o);return}this.#r=!0,r()})});try{await this.#n}catch(r){throw this.#n=void 0,r}}async execute(e){return(await this.#i(e,!1)).rows}async runSQL(e){return this.#i(e,!0)}getTableList(e){return dt(this,e)}describeTable(e){return Ye(this,e)}async#i(e,r){e.signal?.throwIfAborted(),await this.#s(),e.signal?.throwIfAborted();const n=await this.#o();e.signal?.throwIfAborted();const o=e.parameters.map(Zs);return new Promise((i,s)=>{const a=e.signal,u={};let c=!1;const p=f=>{c||(c=!0,a?.removeEventListener("abort",l),f())},l=()=>{u.current?.cancel(),a&&p(()=>s(xp(a)))};a?.addEventListener("abort",l,{once:!0}),u.current=n.execute({sqlText:e.sql,binds:o,complete:(f,m,y)=>{if(f){p(()=>s(f));return}if(!(r&&y===void 0)&&!Array.isArray(y)){p(()=>s(new Error("Snowflake provider expected an array result")));return}const h=r?m.getNumUpdatedRows?.():void 0;p(()=>i({rows:y??[],...typeof h=="number"&&h>=0?{affectedRows:h}:{}}))}}),a?.aborted&&l()})}async close(){if(!this.#r)return;const e=await this.#o();await new Promise((r,n)=>{e.destroy(o=>{if(o){n(o);return}this.#r=!1,this.#n=void 0,this.#t=void 0,r()})})}}const Vp=t=>{const{host:e,server:r,options:n,pool:o,...i}=t;return{...i,server:r??e??"localhost",port:t.port??1433,requestTimeout:t.requestTimeout??6e4,connectionTimeout:t.connectionTimeout??3e4,options:{encrypt:!1,trustServerCertificate:!0,enableArithAbort:!0,...n},pool:{max:10,min:0,idleTimeoutMillis:3e4,...o}}},vp=t=>{if(t==null)return null;if(typeof t=="bigint")return t.toString();if(typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t instanceof Date||Buffer.isBuffer(t))return t;throw new TypeError(`Unsupported SQL Server parameter type: ${typeof t}`)},Fp=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError"),Yp=t=>t instanceof Error?t:new Error("SQL Server query failed",{cause:t}),Hp=t=>{let e=0,r;for(let n=0;n<t.length;n+=1){const o=t[n];if(o){if(r){o===r&&(t[n+1]===r?n+=1:r=void 0);continue}if(o==="'"||o==='"')r=o;else if(o==="[")r="]";else if(o==="(")e+=1;else if(o===")")e=Math.max(0,e-1);else if(e===0&&/^ORDER\s+BY\b/i.test(t.slice(n)))return!0}}return!1};class Qp{kind="sqlserver";supportsHavingAlias=!1;#e;#t;#r;constructor(e={}){this.#e=e.connection??{},this.#t=e.driver,this.#r=e.pool?Promise.resolve(e.pool):void 0}async#n(){this.#r??=(async()=>{const e=this.#t??await import("mssql").then(n=>n.default,n=>{throw Je("mssql",n)}),r=new e.ConnectionPool(Vp(this.#e));return await r.connect(),r})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`[${e.replaceAll("]","]]")}]`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${Hp(e)?e:`${e} ORDER BY (SELECT NULL)`} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`}parameter(e,r){return`@p${e}`}displayQuery(e,r){return hp(e,r)}dateBucket(e,r){const n=new Set(["second","minute","hour","day","month","quarter","year"]);if(r==="week")return`DATEADD(DAY, -(((DATEDIFF(DAY, '19000101', ${e}) % 7) + 7) % 7), CAST(${e} AS DATE))`;if(!n.has(r))throw new Error(`Unsupported SQL Server date level: ${r}`);const o=r==="second"||r==="minute"?"'20000101'":"0";return`DATEADD(${r.toUpperCase()}, DATEDIFF(${r.toUpperCase()}, ${o}, ${e}), ${o})`}datePart(e,r){return r==="weekday"?`((((DATEDIFF(DAY, '19000101', ${e}) % 7) + 7) % 7) + 1)`:`DATEPART(${r==="week"?"ISO_WEEK":r.toUpperCase()}, ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported SQL Server date shift: ${r}/${n}`);return`DATEADD(${r.toUpperCase()}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`CAST(${e} AS DATETIME2)`:r==="date"?`CAST(${e} AS DATE)`:r==="string"?`CAST(${e} AS NVARCHAR(MAX))`:e}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported SQL Server aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS NVARCHAR(MAX))`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`LEN(${e})`}regex(e,r,n){throw new Error("SQL Server does not provide a native regular-expression predicate")}arrayContains(e,r){return`EXISTS (SELECT 1 FROM OPENJSON(${e}) AS [semanticdb_array] WHERE [semanticdb_array].[value] = ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`CROSS APPLY OPENJSON(${e}) AS ${o}`,valueExpression:`${o}.[value]`}}async execute(e){return(await this.#o(e,!1)).rows}async runSQL(e){return this.#o(e,!0)}getTableList(e){return dt(this,e)}describeTable(e){return Ye(this,e)}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=n.request();return e.parameters.forEach((i,s)=>o.input(`p${s}`,vp(i))),new Promise((i,s)=>{const a=e.signal;let u=!1;const c=l=>{u||(u=!0,a?.removeEventListener("abort",p),l())},p=()=>{o.cancel(),a&&c(()=>s(Fp(a)))};a?.addEventListener("abort",p,{once:!0}),o.query(e.sql).then(l=>{if(!Array.isArray(l.recordset)&&!(r&&l.recordset===void 0)){c(()=>s(new Error("SQL Server provider expected an array result")));return}c(()=>i({rows:l.recordset??[],...l.rowsAffected?{affectedRows:l.rowsAffected.reduce((f,m)=>f+m,0)}:{}}))},l=>c(()=>s(Yp(l)))),a?.aborted&&p()})}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}class Gp extends vr{kind="starrocks";constructor(e={}){super(e)}}const Le=t=>{const{id:e,kind:r,...n}=t;return n},Wp=Object.freeze([{kind:"mysql",create:t=>new Up({connection:Le(t)})},{kind:"doris",create:t=>new Dp({connection:Le(t)})},{kind:"gbase",create:t=>new Cp({connection:Le(t)})},{kind:"starrocks",create:t=>new Gp({connection:Le(t)})},{kind:"maxcompute",create:t=>new kp(Le(t))},{kind:"postgresql",create:t=>new jp({connection:Le(t)})},{kind:"clickhouse",create:t=>new Ip(Le(t))},{kind:"databricks",create:t=>new Op({connection:Le(t)})},{kind:"dameng",create:t=>new Pp({connection:Le(t)})},{kind:"snowflake",create:t=>new Bp({connection:Le(t)})},{kind:"sqlserver",create:t=>new Qp({connection:Le(t)})},{kind:"oracle",create:t=>new qp({connection:Le(t)})}]);class ea{#e=new Map;constructor(e=Wp){e.forEach(r=>this.register(r))}register(e){if(!e.kind)throw new d("INVALID_PROVIDER","Provider kind must not be empty");if(this.#e.has(e.kind))throw new d("PROVIDER_ALREADY_REGISTERED",`Provider is already registered: ${e.kind}`,{provider:e.kind});return this.#e.set(e.kind,e),this}create(e){const r=this.#e.get(e.kind);if(!r)throw new d("PROVIDER_NOT_FOUND",`Provider is not registered: ${e.kind}`,{provider:e.kind});return r.create(e)}has(e){return this.#e.has(e)}}const ta=new ea,ra=(t,e=ta)=>e.create(t);class zp{create;#e=new Map;constructor(e=ra){this.create=e}get(e){const r=this.#e.get(e.id);if(r){if(!ba.isDeepStrictEqual(r.connection,e))throw new d("DATABASE_CONNECTION_CONFIGURATION_MISMATCH",`Database connection configuration changed for id: ${e.id}`,{connectionId:e.id});return r.provider}const n=this.create(e);return this.#e.set(e.id,{connection:e,provider:n}),n}async close(){const e=[...this.#e.values()].map(({provider:o})=>o);this.#e.clear();const r=await Promise.allSettled(e.map(async o=>o.close())),n=[];for(const o of r)o.status==="rejected"&&n.push(o.reason);if(n.length>0)throw new AggregateError(n,"Failed to close one or more database connections")}}const Fr=new Map,Kp=t=>{const e=Fr.get(t);if(e)return e;const r=new zp(n=>ra(n,t));return Fr.set(t,r),r},Yr=(t,e=ta)=>Kp(e).get(t),na=async()=>{const t=[...Fr.values()];Fr.clear();const r=(await Promise.allSettled(t.map(async n=>n.close()))).flatMap(n=>n.status==="rejected"?[n.reason]:[]);if(r.length>0)throw new AggregateError(r,"Failed to close one or more connection registries")},Jp=async t=>{if(t.signal?.throwIfAborted(),!t.sql.trim())throw new d("INVALID_SQL","SQL must not be empty");const e=Yr(t.connection,t.providerRegistry);if(!e.runSQL)throw new d("UNSUPPORTED_RAW_SQL",`Provider does not support native SQL: ${e.kind}`);const r=await e.runSQL({sql:t.sql,parameters:t.parameters??[],...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},Xp=async t=>{t.signal?.throwIfAborted(),or(t);const e=Yr(t.connection,t.providerRegistry);if(!e.getTableList)throw new d("UNSUPPORTED_TABLE_DISCOVERY",`Provider does not support table discovery: ${e.kind}`);const r=await e.getTableList({...t.database!==void 0?{database:t.database}:{},...t.schema!==void 0?{schema:t.schema}:{},...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},Zp=async t=>{t.signal?.throwIfAborted(),ho(t);const e=Yr(t.connection,t.providerRegistry);if(!e.describeTable)throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`Provider does not support table description: ${e.kind}`);const r=await e.describeTable({table:t.table,...t.database!==void 0?{database:t.database}:{},...t.schema!==void 0?{schema:t.schema}:{},...t.includeSample!==void 0?{includeSample:t.includeSample}:{},...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},ef=Object.freeze({runSQL:Jp,getTableList:Xp,describeTable:Zp,close:na}),tf=t=>{const{name:e,kind:r}=t;switch(r){case"boolean":return{name:e,kind:r,type:pe.BOOLEAN,sqlType:"BOOLEAN"};case"date":return{name:e,kind:r,type:pe.TIMESTAMP,sqlType:"TIMESTAMP"};case"number":return{name:e,kind:r,type:pe.DOUBLE,sqlType:"DOUBLE"};case"string":return{name:e,kind:r,type:pe.VARCHAR,sqlType:"VARCHAR"}}},rf=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="true"?!0:t===0||t==="0"||t==="false"?!1:!!t,nf=(t,e)=>{if(t==null)return null;switch(e.kind){case"boolean":return pe.jsToDuckDBValue(rf(t),pe.BOOLEAN);case"date":{const r=t instanceof Date?t:new Date(typeof t=="number"||typeof t=="string"?t:Number.NaN);return Number.isNaN(r.getTime())?null:pe.jsToDuckDBValue(r,pe.TIMESTAMP)}case"number":{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?pe.jsToDuckDBValue(r,pe.DOUBLE):null}case"string":return typeof t=="string"?pe.jsToDuckDBValue(t,pe.VARCHAR):typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?pe.jsToDuckDBValue(t.toString(),pe.VARCHAR):typeof t=="symbol"?pe.jsToDuckDBValue(t.description??"",pe.VARCHAR):typeof t=="function"?pe.jsToDuckDBValue(t.name,pe.VARCHAR):pe.jsToDuckDBValue(JSON.stringify(t),pe.VARCHAR)}},of=t=>{if(t==null)return null;if(t instanceof Date)return pe.jsToDuckDBValue(t,pe.TIMESTAMP);if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"||typeof t=="string")return t;if(Buffer.isBuffer(t))return pe.blobValue(t);throw new TypeError(`Unsupported DuckDB coordinator parameter: ${typeof t}`)};class Kr{instance;connection;kind="duckdb";supportsHavingAlias=!0;supportsRecursiveCte=!0;static async create(){const e=await pe.DuckDBInstance.create(":memory:"),r=await e.connect();return new Kr(e,r)}constructor(e,r){this.instance=e,this.connection=r}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return yo(e,r)}dateBucket(e,r){return`DATE_TRUNC('${r.replaceAll("'","''")}', ${e})`}datePart(e,r){return`EXTRACT(${r==="weekday"?"ISODOW":r.toUpperCase()} FROM ${e})`}dateShift(e,r,n){return`(${e} + INTERVAL '${n} ${r.replaceAll("'","''")}')`}datePeriodBoundary(e,r,n){const o=this.dateBucket(e,r);return n==="start"?o:`(${o} + INTERVAL '1 ${r.replaceAll("'","''")}' - INTERVAL '1 microsecond')`}castValue(e,r){return`CAST(${e} AS ${r==="timestamp"?"TIMESTAMP":r==="date"?"DATE":"VARCHAR"})`}scalarExtremum(e,r){return`${e.toUpperCase()}(${r.join(", ")})`}aggregateFunction(e,r){const n={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"};if(e==="countDistinct")return`COUNT(DISTINCT ${r??"*"})`;const o=n[e];if(!o)throw new Error(`Unsupported DuckDB aggregate: ${e}`);return`${o}(${r??"*"})`}stringify(e){return`CAST(${e} AS VARCHAR)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){return n?`REGEXP_MATCHES(${e}, ${r}, '${n.replaceAll("'","''")}')`:`REGEXP_MATCHES(${e}, ${r})`}arrayContains(e,r){return`LIST_CONTAINS(${e}, ${r})`}async materialize(e,r,n){const o=r.map(tf),i=o.map(a=>`${this.quoteIdentifier(a.name)} ${a.sqlType}`).join(", ");await this.connection.run(`CREATE TABLE ${this.quoteIdentifier(e)} (${i})`);const s=await this.connection.createAppender(e);try{for(const a of n){for(const u of o){const c=nf(a[u.name],u);c===null?s.appendNull():s.appendValue(c,u.type)}s.endRow()}s.flushSync()}finally{s.closeSync()}}async execute(e){e.signal?.throwIfAborted();const r=await this.connection.runAndReadAll(e.sql,e.parameters.map(of));return e.signal?.throwIfAborted(),r.getRowObjectsJS()}close(){return this.connection.closeSync(),this.instance.closeSync(),Promise.resolve()}}const Ao="__sdb_total__",sf="__sdb_total_source__",$o=t=>{const e={...t,orderBy:[]};return delete e.pagination,e},af=t=>{const e={...t};return delete e.limit,delete e.page,e},wo=(t,e)=>({sql:`SELECT ${e.aggregateFunction("count")} AS ${e.quoteIdentifier(Ao)} FROM ${e.tableAlias(`(${t.sql})`,sf)}`,parameters:t.parameters}),Hr=t=>{if(t.length===0)return 0;const e=t[0]??{},r=e[Ao]??e[Ao.toUpperCase()]??Object.values(e)[0],n=typeof r=="number"?r:Number(r);if(!Number.isSafeInteger(n)||n<0)throw new d("INVALID_TOTAL_RESULT","The total query must return a non-negative safe integer",{total:r});return n},kt="__semanticdb_coordinator__",oa=(t,e)=>{const r=new Set;for(const n of we(t)){const o=e.findSource(n.schemaId,n.source,n.connectionId);if(!o)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${n.schemaId}:${n.source}`,{schemaId:n.schemaId,source:n.source});r.add(o.connectionId)}return[...r]},ir=(t,e)=>!!t.subplans&&new Set(t.subplans?.flatMap(r=>oa(r,e))).size>1||!!(t.sourcePlan&&ir(t.sourcePlan,e)),cf=(t,e)=>({name:t,expression:{kind:"column",property:t,column:t,qualifier:e}}),uf=(t,e)=>{const r=t.map(n=>n[e]).find(n=>n!=null);return typeof r=="number"||typeof r=="bigint"?"number":typeof r=="boolean"?"boolean":r instanceof Date?"date":"string"},ia=(t,e)=>{const r=new Map((t.columnProperties??[]).map(n=>[n.name,n]));return[...t.projections.map(({name:n})=>n),"_id"].map(n=>{const o=r.get(n),i=n==="_id"?"string":o?.primal_type==="number"?"number":o?.primal_type==="boolean"?"boolean":o?.primal_type==="date"?"date":o?.primal_type==="entity"||o?.primal_type==="object"?uf(e,n):"string";return{name:n,kind:i}})},df=(t,e)=>{const r=t.projections.map(({name:n})=>n);return{schemaId:t.schemaId,source:e,sourceAlias:e,fields:Object.fromEntries([...r,"_id"].map(n=>[n,n])),projections:[...r,"_id"].map(n=>cf(n,e)),...t.columnProperties?{columnProperties:t.columnProperties}:{},groupBy:[],orderBy:[],rowIdentity:{kind:"generated"}}},lf=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:JSON.stringify(r.names.map(o=>{const i=n[o];return i==null?["null"]:i instanceof Date?["date",i.toISOString()]:typeof i=="bigint"?["bigint",i.toString()]:typeof i=="object"?"_id"in i||"id"in i?["entity",Tr(i)]:["object",JSON.stringify(i)]:[typeof i,i]}))}))}if(e.rowIdentity.kind==="singleton")return t.map(r=>({...r,_id:"0"}));throw new d("UNSTABLE_FEDERATED_IDENTITY","A federated composition branch must be grouped or aggregate to a singleton row")},sa=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:Gn(n,r.names,r.separator,r.nullLabel)}))}return e.rowIdentity.kind==="singleton"?t.map(r=>({...r,_id:"0"})):[...t]},Qr=async(t,e)=>{if(!Number.isSafeInteger(e.maxMaterializedRows)||e.maxMaterializedRows<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:e.maxMaterializedRows});if(t.sourcePlan&&ir(t.sourcePlan,e.schemaMappings)){const s=await Qr(t.sourcePlan,e),a=await Kr.create();try{const u="__federated_source";await a.materialize(u,ia(t.sourcePlan,s.rows),s.rows);const c={...t,source:u};delete c.sourcePlan,delete c.sourceLogicform,delete c.connectionId;const p=ge(c,a,e.operators),l=wo(ge($o(c),a,e.operators),a);e.onCompiled({compiled:p,connectionId:kt,provider:a,type:"computation",logicform:e.logicform}),e.onCompiled({compiled:l,connectionId:kt,provider:a,type:"total",logicform:e.logicform});const f=await a.execute({...l,...e.signal?{signal:e.signal}:{}}),m=await a.execute({...p,...e.signal?{signal:e.signal}:{}});return{rows:sa(m,t),total:Hr(f),connections:s.connections}}finally{await a.close()}}if(!t.subplans||t.subplans.length<2)throw new d("INVALID_FEDERATED_PLAN","A federated composition requires at least two child plans");const r=new Map,n=await Promise.all(t.subplans.map(async s=>{const a=oa(s,e.schemaMappings);if(a.length!==1)throw new d("CROSS_CONNECTION_FRAGMENT_UNSUPPORTED","A federated branch must compile completely on one physical connection",{schemaId:s.schemaId,connectionIds:a});const u=a[0],c=e.providerForConnection(u);r.set(u,c.kind);const p=ge(s,c,e.operators);e.onCompiled({compiled:p,connectionId:u,provider:c,type:"computation",logicform:e.logicform});const l=await Ne(p,we(s),{provider:c,connectionId:u,schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}}),f=await it(l,s.projections,e.operators);return{child:s,rows:lf(f,s)}})),o=n.reduce((s,a)=>s+a.rows.length,0);if(o>e.maxMaterializedRows)throw new d("FEDERATED_RESULT_LIMIT_EXCEEDED",`Federated execution materialized ${o} rows; maximum is ${e.maxMaterializedRows}`,{materializedRowCount:o,maxMaterializedRows:e.maxMaterializedRows});const i=await Kr.create();try{const s=n.flatMap(({rows:m})=>m),a=[];for(const[m,{child:y,rows:h}]of n.entries()){const g=`__federated_branch_${m}`;await i.materialize(g,ia(y,s),h),a.push(df(y,g))}const u={...t,subplans:a},c=ge(u,i,e.operators),p=wo(ge($o(u),i,e.operators),i);e.onCompiled({compiled:c,connectionId:kt,provider:i,type:"computation",logicform:e.logicform}),e.onCompiled({compiled:p,connectionId:kt,provider:i,type:"total",logicform:e.logicform});const l=await i.execute({...p,...e.signal?{signal:e.signal}:{}}),f=await i.execute({...c,...e.signal?{signal:e.signal}:{}});return{rows:sa(f,t),total:Hr(l),connections:[...r].map(([m,y])=>({connectionId:m,provider:y}))}}finally{await i.close()}},pf=new Set(["$sply","$splm","$splq","$splw","$yoy","$mom","$qoq","$wow","$yoyd","$momd","$qoqd","$wowd","$percentage"]),Eo=t=>!W(t)||!Array.isArray(t.properties)?[]:t.properties.filter(W),ff=(t,e)=>{const r=e[t];return W(r)?r:Object.values(e).find(n=>W(n)&&(n.id===t||n._id===t))},aa=(t,e,r)=>{const n=ff(t,r);if(!n)return;const i=Eo(n).map(s=>{const u=[s.id,s._id,s.name].filter(c=>typeof c=="string").filter(c=>e===c||e.startsWith(`${c}_`)).sort((c,p)=>p.length-c.length)[0];return u?{property:s,key:u}:void 0}).filter(s=>s!==void 0).sort((s,a)=>a.key.length-s.key.length)[0];if(i)return e===i.key?i.property:typeof i.property.ref=="string"?aa(i.property.ref,e.slice(i.key.length+1),r):void 0},Ut=(t,e,r)=>{const n=(o,i,s)=>{const c=Eo(r[o]).map(y=>{const h=typeof y.id=="string"?y.id:void 0,g=typeof y.name=="string"?y.name:void 0,w=[h,g].filter(S=>!!S&&(i===S||i.startsWith(`${S}_`))).sort((S,E)=>E.length-S.length)[0];return w?{property:y,key:w}:void 0}).filter(y=>!!y).sort((y,h)=>h.key.length-y.key.length)[0];if(!c)return;const p=String(c.property.id??c.property.name),l=i===c.key?"":i.slice(c.key.length+1);if(!l)return p;const f=typeof c.property.ref=="string"?c.property.ref:void 0;if(!f||s.has(f))return;const m=n(f,l,new Set(s).add(f));return m?`${p}_${m}`:void 0};return n(t,e,new Set([t]))},_o=(t,e,r)=>{const n=Eo(r[t]).filter(o=>typeof o.id=="string").sort((o,i)=>String(i.id).length-String(o.id).length).find(o=>e===o.id||e.startsWith(`${String(o.id)}_`));if(!(!n||typeof n.id!="string")){if(e===n.id)return n.id;if(typeof n.ref=="string")return _o(n.ref,e.slice(n.id.length+1),r)}},ca=t=>Object.keys(t).filter(e=>e!=="$and"&&e!=="$or"),W=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ua=t=>typeof t=="string"&&/^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?$/.test(t),da=t=>{if(!W(t))return t;if(W(t.$offset)){const e=Object.entries(t.$offset),r=e[0];if(e.length===1&&r&&Number.isInteger(r[1]))return{granularity:r[0],offset:r[1]}}return t},mf=t=>typeof t=="string"&&t.length>0||typeof t=="number"&&Number.isSafeInteger(t),yf=(t,e)=>{if(!e)return;const r=e[t]??Object.values(e).find(u=>W(u)&&(u.id===t||u._id===t));if(!W(r))return;const n=r.hierarchy,o=Array.isArray(n)?n:W(n)&&Array.isArray(n.levels)?n.levels:void 0;if(!o)return;const i=o.map(u=>{if(!W(u)||typeof u.name!="string")return;const c=u.codeLength??u.code_length;return Number.isInteger(c)&&Number(c)>0?{name:u.name,codeLength:Number(c)}:void 0});if(i.length===0||i.some(u=>u===void 0))return;const s=o[0],a=Array.isArray(n)?W(s)&&s.use_full_length===!0?"zero-padded":"compact":W(n)&&n.storage==="zero-padded"?"zero-padded":"compact";return{levels:i.filter(u=>u!==void 0),storage:a}},hf=(t,e,r)=>{const n=yf(t,r);if(!n)return;const o=String(e),i=n.levels.reduce((a,u)=>a+u.codeLength,0);let s=0;for(const a of n.levels)if(s+=a.codeLength,o.length===s||n.storage==="zero-padded"&&o.length===i&&o.slice(s)==="0".repeat(i-s))return a.name;throw new d("LEGACY_HIERARCHY_LEVEL_INFERENCE_FAILED",`Cannot infer hierarchy level from entity_id ${o} in Schema ${t}`,{schemaId:t,entityId:e})},gf=(t,e)=>e.length===0?t:e.length===1&&t.$expr===void 0?{...t,$expr:e[0]}:{$and:[...Object.keys(t).length>0?[t]:[],...e.map(n=>({$expr:n}))]},So=(t,e)=>{const r={},n=[];for(const[o,i]of Object.entries(t)){if((o==="$and"||o==="$or")&&Array.isArray(i)){r[o]=i.map(y=>W(y)?So(y,e):y);continue}if(!W(i)){r[o]=i;continue}const s=i.entity_id;if(typeof i.schema!="string"||!W(i.query)||!mf(s)){r[o]=i;continue}const a=i.entity_level,u=typeof a=="string"&&a.length>0?a:hf(i.schema,s,e);if(!u){r[o]=i;continue}const{entity_id:c,entity_level:p,...l}=i,f=So(i.query,e),m=Object.keys(l).filter(y=>y!=="schema"&&y!=="version"&&y!=="query");(Object.keys(f).length>0||m.length>0)&&(r[o]={...l,query:f}),n.push({pred:{operator:"$hierarchyLevel",pred:o,args:{level:u}},condition:s})}return gf(r,n)},Af=(t,e)=>{const n=t&&({$sply:"$periodShift",$splm:"$periodShift",$splq:"$periodShift",$splw:"$periodShift",$yoy:"$periodGrowth",$mom:"$periodGrowth",$qoq:"$periodGrowth",$wow:"$periodGrowth",$yoyd:"$periodDifference",$momd:"$periodDifference",$qoqd:"$periodDifference",$wowd:"$periodDifference",$dailyavg:"$averagePerPeriod",$weeklyavg:"$averagePerPeriod",$monthlyavg:"$averagePerPeriod",$startOfPeriod:"$periodValue",$endOfPeriod:"$periodValue",$dateLevel:"$dateBucket",$uniq:"$countDistinct",$percentage:"$shareOfTotal"}[t]??t),o={...e};return t==="$sply"||t==="$yoy"||t==="$yoyd"?o.time??={granularity:"year",offset:-1}:t==="$splm"||t==="$mom"||t==="$momd"?o.time??={granularity:"month",offset:-1}:t==="$splq"||t==="$qoq"||t==="$qoqd"?o.time??={granularity:"quarter",offset:-1}:t==="$splw"||t==="$wow"||t==="$wowd"?o.time??={granularity:"week",offset:-1}:t==="$dailyavg"?o.granularity??="day":t==="$weeklyavg"?o.granularity??="week":t==="$monthlyavg"?o.granularity??="month":t==="$startOfPeriod"?o.boundary??="start":t==="$endOfPeriod"&&(o.boundary??="end"),{...n?{operator:n}:{},args:o}},la=(t,e)=>{if(!W(e)||!Array.isArray(e.cases)||e.cases.length===0)throw new d("INVALID_LEGACY_CASE_ARGS",`${t} requires a non-empty params.cases array`);return{cases:e.cases.map((n,o)=>{if(!W(n))throw new d("INVALID_LEGACY_CASE_ARGS",`${t} case ${o} must be an object`);if(n.sql!==void 0)throw new d("LEGACY_CASE_SQL_UNSUPPORTED",`${t} case.sql cannot be migrated to the structured v2 $case operator`);if(!W(n.query)||typeof n.name!="string"||n.name.length===0)throw new d("INVALID_LEGACY_CASE_ARGS",`${t} case ${o} requires query and a non-empty name`);return{when:n.query,then:n.name}}),...Object.hasOwn(e,"default")?{default:e.default}:{}}},He=(t,e,r)=>{if(Array.isArray(t))return t.map(u=>He(u,e,r));if(!W(t))return t;const n=da(t);if(n!==t)return n;const o=t,i=typeof o.schema=="string"?o.schema:r,s={};for(const[u,c]of Object.entries(o))u==="skip"||u==="_snapshot"||u==="_snapshots"||(s[u]=He(c,e,i));if(typeof o.version=="string"&&/^1\./.test(o.version)&&(s.version="2.0"),Array.isArray(o.groupby)){const u=o.groupby;s.groupby=u.map(c=>{if(!W(c))return c;const p=He(c,e,i);if(!W(p))return p;const{_id:l,level:f,...m}=p,y={...m,...m.pred===void 0&&typeof l=="string"?{pred:l}:{}};return typeof f=="string"&&(y.operator="$dateBucket",y.args={...W(y.args)?y.args:{},granularity:f}),y})}const a=o.skip;if(typeof a=="number"&&Number.isInteger(a)&&a>=0){const u=o.limit;a===0?delete s.skip:typeof u=="number"&&Number.isInteger(u)&&u>0&&a%u===0?s.page=a/u+1:s.skip=a}else a!==void 0&&(s.skip=He(a,e,i));if(o.operator&&typeof o.operator=="string"){const u=Af(o.operator,W(s.args)?s.args:{});if(u.operator&&(s.operator=u.operator),s.args=u.args,o.operator==="$comp"||o.operator==="$compabs"){const c=W(s.args)?s.args.preds:void 0;if(!Array.isArray(c)||c.length!==2)throw new d("INVALID_LEGACY_COMP_ARGS",`${o.operator} requires exactly 2 preds in args.preds`);const p={operator:"$subtract",pred:c,args:{nullAsZero:!0}};s.operator=o.operator==="$comp"?"$subtract":"$abs",s.pred=o.operator==="$compabs"?p:c,s.args=o.operator==="$comp"?{nullAsZero:!0}:{}}if(o.operator==="$switch"){const c=W(s.params)?s.params:s.args;s.operator="$case",s.args=la("$switch",c),delete s.params}if(o.operator==="$piecewise"){const c=typeof s.pred=="string"?s.pred:typeof o._id=="string"?o._id:void 0;if(e&&i&&c&&aa(i,c,e)?.cases!==void 0)throw new d("LEGACY_PIECEWISE_PROPERTY_CASES_UNSUPPORTED","$piecewise property cases contain trusted SQL and cannot be migrated safely to v2 $case",{schemaId:i,property:c});const p=W(s.params)?s.params:W(s.args)?s.args:{};s.operator="$case",s.args=Array.isArray(p.cases)?la("$piecewise",p):{mode:"auto",buckets:Number.isInteger(p.buckets)?p.buckets:10},delete s.params}pf.has(o.operator)&&typeof s.pred=="string"&&(s.pred={operator:"$sum",pred:s.pred})}return o.params!==void 0&&s.args===void 0&&(s.args=Array.isArray(o.params)?{values:He(o.params,e,i)}:He(o.params,e,i)),o.inputs!==void 0&&s.pred===void 0&&Array.isArray(o.inputs)&&(s.pred=o.inputs.map(u=>He(u,e,i)),W(s.args)&&delete s.args.inputs),o.pred===void 0&&typeof o.operator=="string"&&o.operator==="$sql"&&typeof o.sql=="string"&&(s.args={...W(s.args)?s.args:{},sql:o.sql},delete s.sql),o.$options!==void 0&&s.$regex!==void 0?(s.args={...W(s.args)?s.args:{},options:o.$options},delete s.$options):"$options"in o&&ua(o.$gte)&&ua(o.$lte)&&delete s.$options,o.query&&W(o.query)&&(s.query=$f(o.query,e,i)),s},$f=(t,e,r)=>{const n=He(t,e,r);for(const[o,i]of Object.entries(n))n[o]=da(i);return So(n,e)},pa=(t,e)=>{const r=W(t)?t:void 0,n=He(t,e);if(!W(n))return n;if(r&&typeof r.operator=="string"&&r.preds===void 0){const o={};for(const a of["version","schema","query","groupby","having","sort","limit","page","skip","output","representation","currency"])n[a]!==void 0&&(o[a]=n[a]);const i=new Set(["version","schema","query","groupby","having","sort","limit","page","skip","output","representation","currency"]),s=Object.fromEntries(Object.entries(n).filter(([a])=>!i.has(a)));return o.preds=[s],pa(o,e)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),e?wf(n,e):n},wf=(t,e)=>{const r=t;if(!Array.isArray(r.preds))return t;const n=r.preds,o=typeof r.schema=="string"?r.schema:void 0;if(!o)return t;const i=new Set([o]);for(const u of n)W(u)&&typeof u.schema=="string"&&i.add(u.schema);if(i.size<2)return t;if(!e)throw new Error("Cannot migrate cross-Schema LogicForm without Schema metadata for field alignment");const s=Array.isArray(r.groupby)?r.groupby.map(u=>W(u)&&typeof u.pred=="string"?Ut(o,u.pred,e):void 0):[];for(const u of i)if(Array.isArray(r.groupby)&&r.groupby.map((c,p)=>{if(!W(c)||typeof c.pred!="string")return c;const l=u===o?Ut(u,c.pred,e):Ut(u,_o(o,s[p]??"",e)??c.pred,e);if(!l)return c;const f=l.split("_").at(-1)??c.pred;return{...c,pred:l,name:f}}),W(r.query))for(const c of ca(r.query)){const p=Ut(o,c,e);if(!(u===o?p:Ut(u,(p&&_o(o,p,e))??c,e))&&u===o)throw new Error(`Cannot align legacy query field ${c} in Schema ${u}`)}const a={...r};if(Array.isArray(r.groupby)&&(a.groupby=r.groupby.map((u,c)=>{if(!W(u)||typeof u.pred!="string")return u;const p=s[c];return p?{...u,pred:p}:u})),W(r.query)){const u=r.query,c=ca(u).map(p=>[Ut(o,p,e)??p,u[p]]);a.query=Object.fromEntries(c)}return a},Ef=t=>{const e=(r,n)=>{if(Array.isArray(r)){r.forEach((o,i)=>e(o,`${n}[${i}]`));return}if(W(r))for(const[o,i]of Object.entries(r)){if(["is_snapshot","is_observation","_snapshot","_snapshots","$options","params","inputs","entity_level","entity_codelength"].includes(o))throw new d("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);if(o==="_id"&&(n.endsWith(".groupby")||n.includes(".groupby[")))throw new d("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);e(i,`${n}.${o}`)}};e(t,"$")},Io=t=>{if(Array.isArray(t))return t.map(Io).filter(n=>n!==void 0);if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return t;const e=Object.entries(t),r=e.filter(([,n])=>n!==null).map(([n,o])=>[n,Io(o)]).filter(([,n])=>n!==void 0);if(!(e.length>0&&r.length===0))return Object.fromEntries(r)},_f=t=>{if(t.comparable!=null)return t.comparable;if(t.is_comparable!==!0||t.isArray===!0||t.type!=="string"&&t.type!=="category"||!Array.isArray(t.constraints?.enum))return;const r=t.constraints.enum.map(n=>Array.isArray(n)?n[0]:n);if(!(r.length===0||r.some(n=>typeof n!="string")))return{values:[...new Set(r)],direction:t.comparable_order===-1?-1:1}},Sf=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const e=t;if(e.sql!=null)return Object.keys(e).every(r=>r==="sql")?t:{sql:e.sql}},If=(t,e=[],r=!0)=>{const n=ye(e),o={},i=new Set(n.flatMap(s=>[...s.schemaMetadata?.keys??[],...s.legacySchemaKeys??[]]));for(const[s,a]of Object.entries(t)){const u=Io(a),c=u,l=(Array.isArray(c.properties)?c.properties:[]).some(S=>S.is_observation===!0)||c.is_observation===!0,f=c.is_snapshot===!0,m=typeof u.id=="string"&&u.id.length>0?u.id:r&&typeof u._id=="string"&&u._id.length>0?u._id:u.id,{properties:y}=u,h=Object.fromEntries(Object.entries(u).filter(([S])=>(r?!["_id","_sid","sid","is_observation","is_snapshot"].includes(S):S!=="properties")&&S!=="properties"&&!i.has(S))),g=y.map(S=>{const E=S,A=typeof E.id=="string"&&E.id.length>0?E.id:r&&typeof E._id=="string"&&E._id.length>0?E._id:E.id,{udf:R,...O}=E,D=_f(E),M=Sf(R),z=D!==void 0&&E.comparable==null?"category":E.type==="object"?"entity":E.type;return{...r?Object.fromEntries(Object.entries(O).filter(([v])=>!["_id","_sid","sid","is_observation","is_comparable","comparable_order"].includes(v))):O,type:z,...E.primal_type==="object"?{primal_type:"entity"}:{},...A!==void 0?{id:A}:{},...M!==void 0?{udf:M}:{},...D!==void 0?{comparable:D}:{}}});let $={};for(const S of n)for(const E of S.schemaMetadata?.keys??[])u[E]!==void 0&&($={...$,[E]:u[E]});for(const S of n)$={...$,...S.normalizeLegacySchema?.({source:u,properties:g})};const w={...h,...m!==void 0?{id:m}:{},properties:g,...r&&(f||l)?{temporalSemantics:"snapshot"}:{},...$};o[s]=w}return o},fa=(t,e)=>[...ye(t).flatMap(r=>r.locales??[]),...e===void 0?[]:"locale"in e?[e]:e],Gr=t=>({kind:"query",logicform:t.logicform,...t.prepare!==void 0?{prepare:t.prepare}:{},...t.mapResult?{mapResult:t.mapResult}:{},...t.groupKeyShifts?{groupKeyShifts:t.groupKeyShifts}:{}}),ma=t=>t instanceof Error?t:new Error(String(t)),bf=(t,e="zh-CN",r)=>t instanceof d?t.localizedMessage(e,r):t.message,Rf=(t,e,r={},n="zh-CN",o)=>{const i=ma(t);return{errorCode:"100",error:bf(i,n,o),result:[],...r.schema?{schema:r.schema}:{},normedLogicform:r.normedLogicform??e,sqls:r.sqls??[],...r.provider?{provider:r.provider}:{},...r.lineage?{lineage:r.lineage}:{}}},Nf=(t,e,r)=>{const n=e.projections.map(({name:c})=>c),o=new Map((e.columnProperties??[]).map(c=>[c.name,c])),i=[],s=(c,p)=>{const l=r.parameter(i.length,p);i.push(p);const f=o.get(c)?.type;return f&&(f==="date"||f==="timestamp")&&r.castValue?r.castValue(l,f):l},a=c=>`SELECT ${n.map(p=>`${s(p,c[p])} AS ${r.quoteIdentifier(p)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""}`;return{sql:t.length>0?t.map(a).join(" UNION ALL "):`SELECT ${n.map(c=>`NULL AS ${r.quoteIdentifier(c)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""} WHERE 1 = 0`,parameters:i}},Of=(t,e,r)=>{if(t.length<2||t.some(i=>i.kind==="js"||i.kind==="query"&&i.unit.mapResult))return!1;const n=new Set,o=[...t.flatMap(({sources:i})=>i),...we(r)];for(const i of o){const s=po(i,e);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},Tf=async(t,e,r)=>{await t?.({...e,partialResult:r})},Pf=(t,e,r,n,o,i,s=r,a)=>({type:r,...a?{connectionId:a}:{},provider:e.kind,explain:i.translate(o,s==="time-watermark"?"sql.timeWatermark":s==="auto-case"?"sql.autoCase":s==="entity-expansion"?"sql.entityExpansion":s==="total"?"sql.total":s==="computation"?"sql.computation":"sql.semanticResolution"),logicform:n,sql:t.sql,parameters:[...t.parameters],displaySql:e.displayQuery(t.sql,t.parameters)}),bo=(t,e)=>{if(e.connectionId)for(const r of we(t)){const n=po(r,e.schemaMappings);if(!n)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${r.schemaId}:${r.source}`,{schemaId:r.schemaId,source:r.source});if(n.connectionId!==e.connectionId)throw new d("CROSS_CONNECTION_QUERY_UNSUPPORTED",`One physical query cannot use multiple database connections: ${e.connectionId}, ${n.connectionId}`,{schemaId:r.schemaId,source:r.source,connectionId:n.connectionId})}},Lf=t=>{const e=new Set,r=n=>{n.from&&r(n.from),n.schema&&e.add(n.schema);for(const o of n.preds??[])for(const i of Ro(o))e.add(i)};return r(t),[...e]},Ro=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...Ro(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:Ro(r))]:e},Df=async(t,e)=>{const r=e.locale??"zh-CN",n=e.localeRegistry??lr(fa(e.plugins,e.locales)),o=e.plugins??[],i=t.version,s=typeof i=="string"&&(/^2\./.test(i)||/^[3-9]\d*\./.test(i)),a=i===void 0||typeof i=="string"&&/^1\./.test(i);s&&Ef(t);const u=a?pa(t,e.schemas):t,c={...e,locale:r,localeRegistry:n,schemas:If(e.schemas,o,a)},p=Xr.performance.now(),l=c.semanticTypes===void 0?ro(o):c.semanticTypesResolved?c.semanticTypes:As(c.semanticTypes,o),f=c.operators??De(o);if(c.operators&&!c.operatorsResolved)for(const C of o)for(const F of C.operators??[])if(f.has(F.name)){if(f.get(F.name)!==F)throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${F.name}`,{operator:F.name,plugin:C.name})}else f.register(F);const m=c.schemaMappings,y=new Date,h=new Map,g=new Map,$=[],w=new Set,S=C=>{const F=JSON.stringify(C);w.has(F)||(w.add(F),$.push(C),E={...E,schemaMappingSelections:[...$]})};let E={provider:c.provider.kind};const A=[],R=new Map;c.connectionId&&R.set(c.connectionId,c.provider.kind);const O=(C,F,Z,j=F,le=c.provider,_=c.connectionId)=>{_&&_!==kt&&R.set(_,le.kind),A.push(Pf(Bs(C),le,F,Z,c.locale??"zh-CN",n,j,_)),E={...E,sqls:[...A],providers:[...R].map(([I,b])=>({connectionId:I,provider:b}))}},D=async(C,F={})=>{E={...E,...F},await Tf(c.onProgress,C,E)},M=C=>fs(ic(C,c.schemas),l,o),z=new Map,q=C=>{const F=z.get(C);return F||(Fe(c.permissions,C),M(C))},v=C=>{if(C.schema)return q(C.schema);if(C.from)return v(C.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},k=C=>{if(C.schema)return M(C.schema);if(C.from)return k(C.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},H={plugins:o,resolveSchema:q,onSchemaMappingSelection:S,...c.connectionId?{preferredConnectionId:c.connectionId}:{},canUsePropertyRowIdentity:(C,F)=>ct(c.permissions,C.id,F)},ae=(C,F)=>{const Z=Fi(Te(C,v(C),f,m,H),F);return z.set(Z.id,Z),Z},te=async(C,F,Z)=>{const j=`${C.id}:${F.id}:${Z.toISOString()}`,le=h.get(j);if(le)return le;const _=(async()=>{const I=ye(o).find(ee=>ee.createTimeWatermarkLogicform)?.createTimeWatermarkLogicform;if(!I)return;const b=I({logicform:u,rootSchema:C,rootProperty:F,requestedUpperBound:Z,now:y,...c.timeWatermark?{defaultPolicy:c.timeWatermark}:{},resolveSchema:q,inferPropertyPath:(ee,J,B)=>Cs(ee,J,B,q)}),T=ut(b,c.permissions,q,!1,new Set,o),P=await at(T,C,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,resolveFromSchema:ae}),Y=Te(P,C,f,m,H);let K;if(ir(Y,m)){const ee=c.providerForConnection;if(!ee)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated timeWatermark resolution requires a provider resolver");K=(await Qr(Y,{logicform:P,operators:f,schemaMappings:m,providerForConnection:ee,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:B,logicform:he,provider:ce,connectionId:Ce})=>O(B,"semantic-resolution",he,"time-watermark",ce,Ce)})).rows}else{bo(Y,c);const ee=ge(Y,c.provider,f);O(ee,"semantic-resolution",P,"time-watermark"),K=await Ne(ee,we(Y),c)}const re=K[0]?.__timeWatermark__??Object.values(K[0]??{})[0];if(re==null||!(re instanceof Date)&&typeof re!="string"&&typeof re!="number")return;const L=re instanceof Date?re:new Date(re);return Number.isNaN(L.getTime())?void 0:L})();return h.set(j,_),_},me=async(C,F,Z)=>{const j=JSON.stringify([C.id,F,Z??null]),le=g.get(j);if(le)return le;const _=(async()=>{const I={version:"2.0",schema:C.id,...Z?{query:Z}:{},preds:[{name:"__autoCaseMin__",operator:"$min",pred:F},{name:"__autoCaseMax__",operator:"$max",pred:F},{name:"__autoCaseCount__",operator:"$count",pred:F}]},b=await at(I,C,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,resolveFromSchema:ae}),T=Te(b,C,f,m,H);let P;if(ir(T,m)){const he=c.providerForConnection;if(!he)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated automatic bucket resolution requires a provider resolver");P=(await Qr(T,{logicform:b,operators:f,schemaMappings:m,providerForConnection:he,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:Ce,logicform:pt,provider:ft,connectionId:Xe})=>O(Ce,"semantic-resolution",pt,"auto-case",ft,Xe)})).rows}else{bo(T,c);const he=ge(T,c.provider,f);O(he,"semantic-resolution",b,"auto-case"),P=await Ne(he,we(T),c)}const Y=P[0],K=Y?.__autoCaseMin__,re=Y?.__autoCaseMax__,L=Y?.__autoCaseCount__;if(K==null||re===null||re===void 0||L===null||L===void 0||Number(L)===0)return{empty:!0};const ee=Number(K),J=Number(re),B=Number(L);if(!Number.isFinite(ee)||!Number.isFinite(J)||!Number.isSafeInteger(B)||B<0)throw new d("INVALID_AUTO_CASE_STATS","Automatic bucket statistics must contain finite min/max and a non-negative integer count",{min:K,max:re,count:L});return{min:ee,max:J,count:B}})();return g.set(j,_),_};try{c.signal?.throwIfAborted(),no(u),await D({stage:"started",logicform:u}),Wl(c.permissions,M);const C=v(u);await D({stage:"validated",schema:C});const F=ut(u,c.permissions,q,!0,new Set,o),Z=await at(F,C,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,resolveFromSchema:ae,canProjectProperty:(N,x)=>ct(c.permissions,N.id,x),requestTimeWatermark:te,requestAutoCaseBounds:me});await D({stage:"normalized",normedLogicform:Z},{normedLogicform:Z});const j=Te(Z,C,f,m,H),le=ir(j,m);le||bo(j,c);const _=j.columnProperties??[],I=vi(j,C);z.set(I.id,I),await D({stage:"planned",plan:j},{schema:I});const b=Di(j,C,c.provider,f,c.providerForConnection);if(await D({stage:"lineage",lineage:b},{lineage:b}),le){const N=c.providerForConnection;if(!N)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated execution requires a provider resolver for every physical connection");const x=await Qr(j,{logicform:Z,operators:f,schemaMappings:m,providerForConnection:N,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:_e,type:se,logicform:oe,provider:$e,connectionId:fe})=>O(_e,se,oe,se,$e,fe)});await D({stage:"compiled",sqls:[...A]},{sqls:[...A]}),await D({stage:"executing",provider:"duckdb",connectionId:kt}),await D({stage:"hydrating"});const G=x.connections.length===1?x.connections[0]?.connectionId:void 0,U=await Hs(x.rows,_,{semanticTypes:l,plugins:o,resolveSchema:q,fetchEntities:_e=>Vs(_e,{version:Z.version,operators:f,schemaMappings:m,semanticTypes:l,plugins:o,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,...c.permissions?{permissions:c.permissions}:{},provider:c.provider,providerForConnection:N,...G?{preferredConnectionId:G}:{},...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:(se,oe,$e,fe)=>O(se,"semantic-resolution",oe,"entity-expansion",$e,fe)})}),Q=Wn(U,j.rowIdentity);return await D({stage:"result",result:Q},{result:Q,total:x.total,sqls:[...A],providers:x.connections}),await D({stage:"completed",durationMs:Xr.performance.now()-p}),{result:Q,total:x.total,schema:I,normedLogicform:Z,sqls:[...A],lineage:b,provider:"duckdb",providers:x.connections,schemaMappingSelections:[...$]}}const T=Pr(Z,j,C,f,q,void 0,r,n.translator(r)),P=async(N,x)=>{const G=x&&N.logicform.schema===x.id?x:v(N.logicform),U=N.prepare?await at(ut(N.logicform,c.permissions,q,!0,new Set,o),G,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,resolveFromSchema:ae,canProjectProperty:(se,oe)=>ct(c.permissions,se.id,oe),requestTimeWatermark:te}):N.logicform,Q=Te(U,G,f,m,H),_e=Pr(U,Q,G,f,q,N.logicform,r,n.translator(r));if(_e){if(_e.length!==1)throw new Error("A generated component must produce exactly one execution unit");const se=_e[0];if("logicform"in se){const fe=await P(se,G),mt=fe.component.mapResult,xe=N.mapResult;return{...fe,component:{...N,logicform:fe.component.logicform,...mt||xe?{mapResult:Be=>{const Ze=mt?.(Be)??[...Be];return xe?.(Ze)??[...Ze]}}:{}}}}if("mergeRow"in se)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","A JavaScript composite metric cannot currently be nested as a generated component");const oe=await Promise.all(se.components.map(async fe=>({name:fe.name,prepared:await P(Gr(fe)),...fe.groupKeyShifts?{groupKeyShifts:fe.groupKeyShifts}:{},...fe.joinKeys?{joinKeys:fe.joinKeys}:{}}))),$e=Or(se,oe.map(({name:fe,prepared:mt,...xe})=>({name:fe,plan:mt.plan,...xe})),Q,se.outputName,c.provider,f);return{component:{...N,logicform:U},plan:Q,compiled:$e,sources:rr(oe.map(({prepared:fe})=>fe.sources))}}return{component:{...N,logicform:U},plan:Q,compiled:ge(Q,c.provider,f),sources:we(Q)}},Y=async(N,x)=>{const G=Pr(N,x,v(N),f,q,void 0,r,n.translator(r));if(!G)return{compiled:ge(x,c.provider,f),sources:we(x)};const U=await Promise.all(G.map(async Q=>{if("logicform"in Q){const oe=await P(Q);return{plan:oe.plan,compiled:oe.compiled,outputs:oe.plan.projections.map(({name:$e})=>$e).filter($e=>!x.groupBy.some(fe=>fe.name===$e))}}if("mergeRow"in Q)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const _e=await Promise.all(Q.components.map(async oe=>{const $e=await P(Gr(oe));return{name:oe.name,plan:$e.plan,...oe.joinKeys?{joinKeys:oe.joinKeys}:{},...oe.groupKeyShifts?{groupKeyShifts:oe.groupKeyShifts}:{}}})),se=Or(Q,_e,x,Q.outputName,c.provider,f);return{plan:x,compiled:se,outputs:[Q.outputName,...Q.components.map(oe=>oe.name)]}}));return{compiled:Yn(U,x,c.provider,f),sources:rr(U.map(({plan:Q})=>we(Q)))}},K=new WeakMap,re=async N=>{if(!N.sourcePlan||!N.sourceLogicform)return ge(N,c.provider,f);const x=k(N.sourceLogicform),G=Pr(N.sourceLogicform,N.sourcePlan,x,f,q,void 0,r,n.translator(r));if(G?.some(oe=>"mergeRow"in oe)){const oe=K.get(N.sourcePlan);if(oe){const ie={...N};delete ie.sourcePlan,delete ie.sourceLogicform;const Ge=ge({...ie,sourceSql:oe.sql,source:N.source},c.provider,f,oe.parameters.length);return{sql:Ge.sql,parameters:[...oe.parameters,...Ge.parameters]}}const $e=await Promise.all(G.map(async ie=>{if("logicform"in ie)return{kind:"query",unit:ie,prepared:await P(ie,x)};const Ge=await Promise.all(ie.components.map(async Ae=>({input:Ae,prepared:await P(Gr(Ae),x)})));return"mergeRow"in ie?{kind:"js",unit:ie,components:Ge}:{kind:"component",unit:ie,components:Ge,compiled:Or(ie,Ge.map(({input:Ae,prepared:ke})=>({name:Ae.name,plan:ke.plan,...Ae.joinKeys?{joinKeys:Ae.joinKeys}:{},...Ae.groupKeyShifts?{groupKeyShifts:Ae.groupKeyShifts}:{}})),N.sourcePlan,ie.outputName,c.provider,f)}})),fe=N.sourcePlan.groupBy.map(({name:ie})=>ie),mt=await Promise.all($e.map(async ie=>{if(ie.kind==="query"){O(ie.prepared.compiled,"computation",ie.prepared.component.logicform);const Ae=await Ne(ie.prepared.compiled,ie.prepared.sources,c),ke=await it(Ae,ie.prepared.plan.projections,f);return ie.unit.mapResult?.(ke)??ke}if(ie.kind==="component")return O(ie.compiled,"computation",N.sourceLogicform),Ne(ie.compiled,rr(ie.components.map(({prepared:Ae})=>Ae.sources)),c);const Ge=await Promise.all(ie.components.map(async({input:Ae,prepared:ke})=>{O(ke.compiled,"computation",ke.component.logicform);const ga=await Ne(ke.compiled,ke.sources,c),Po=await it(ga,ke.plan.projections,f);return Ae.mapResult?.(Po)??Po}));return Promise.all(Kn(Ge,fe).map(async Ae=>({...Ae,[ie.unit.outputName]:await ie.unit.mergeRow(Ae)})))})),xe=Jn(mt,N.sourcePlan),Be=c.federation?.maxMaterializedRows??1e5;if(!Number.isSafeInteger(Be)||Be<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:Be});if(xe.length>Be)throw new d("MATERIALIZED_RESULT_LIMIT_EXCEEDED",`Nested component materialized ${xe.length} rows; maximum is ${Be}`,{materializedRowCount:xe.length,maxMaterializedRows:Be});const Ze=Nf(xe,N.sourcePlan,c.provider);K.set(N.sourcePlan,Ze);const Jr={...N};delete Jr.sourcePlan,delete Jr.sourceLogicform;const To=ge({...Jr,sourceSql:Ze.sql,source:N.source},c.provider,f,Ze.parameters.length);return{sql:To.sql,parameters:[...Ze.parameters,...To.parameters]}}const U=await Y(N.sourceLogicform,N.sourcePlan),Q={...N};delete Q.sourcePlan,delete Q.sourceLogicform;const _e={...Q,sourceSql:U.compiled.sql,source:N.source},se=ge(_e,c.provider,f,U.compiled.parameters.length);return{sql:se.sql,parameters:[...U.compiled.parameters,...se.parameters]}},L=T?await Promise.all(T.map(async N=>{if("logicform"in N)return{kind:"query",unit:N,...await P(N)};const x=await Promise.all(N.components.map(async U=>({name:U.name,prepared:await P(Gr(U)),...U.groupKeyShifts?{groupKeyShifts:U.groupKeyShifts}:{},...U.joinKeys?{joinKeys:U.joinKeys}:{}})));if("mergeRow"in N)return{kind:"js",unit:N,components:x.map(({prepared:U})=>U)};const G=x.map(({name:U,prepared:Q,..._e})=>({name:U,plan:Q.plan,..._e}));return{kind:"component",unit:N,plan:j,compiled:Or(N,G,j,N.outputName,c.provider,f),sources:rr(x.map(({prepared:U})=>U.sources))}})):void 0,ee=L&&Of(L,m,j)?L.map(N=>{const x=new Set(j.groupBy.map(({name:U})=>U));if(N.kind==="query")return{plan:N.plan,compiled:N.compiled,outputs:N.plan.projections.map(({name:U})=>U).filter(U=>!x.has(U))};const G=N.unit.outputName;if(!G)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");return{plan:N.plan,compiled:N.compiled,outputs:[G,...N.unit.components.map(U=>U.name)]}}):void 0,J=ee?Yn(ee,j,c.provider,f):void 0,B=L?void 0:await re(j),he=$o(j),ce=j.pagination&&(J||B)?wo(ee?Yn(ee,he,c.provider,f):await re(he),c.provider):void 0;if(J)O(J,"computation",Z);else if(L)for(const N of L)if(N.kind==="js")for(const x of N.components)O(x.compiled,"computation",x.component.logicform);else O(N.compiled,"computation",Z);else O(B,"computation",Z);ce&&O(ce,"total",af(Z)),await D({stage:"compiled",sqls:[...A]},{sqls:[...A]}),await D({stage:"executing",provider:c.provider.kind});const Ce=J?await(async()=>{const N=rr([...L.map(Q=>Q.sources),we(j)]),[x,G]=await Promise.all([Ne(J,N,c),ce?Ne(ce,N,c):Promise.resolve(void 0)]),U=await it(x,j.projections,f);return{rows:U,total:G?Hr(G):U.length}})():L?await(async()=>{const N=await Promise.all(L.map(async G=>{if(G.kind==="js"){const _e=await Promise.all(G.components.map(async se=>{const oe=await Ne(se.compiled,se.sources,c),$e=await it(oe,se.plan.projections,f);return se.component.mapResult?.($e)??$e}));return Promise.all(Kn(_e,j.groupBy.map(({name:se})=>se)).map(async se=>{const oe=await G.unit.mergeRow(se);return{...se,[G.unit.outputName]:oe}}))}const U=await Ne(G.compiled,G.sources,c),Q=G.kind==="query"?await it(U,G.plan.projections,f):U;return G.kind==="query"?G.unit.mapResult?.(Q)??Q:Q})),x=Jn(N,he);return{rows:j.pagination?Jn(N,j):x,total:x.length}})():await(async()=>{const N=we(j),[x,G]=await Promise.all([Ne(B,N,c),ce?Ne(ce,N,c):Promise.resolve(void 0)]),U=await it(x,j.projections,f);return{rows:U,total:G?Hr(G):U.length}})(),{rows:pt,total:ft}=Ce;await D({stage:"hydrating"});const Xe=await Hs(pt,_,{semanticTypes:l,plugins:o,resolveSchema:q,fetchEntities:N=>Vs(N,{version:Z.version,operators:f,schemaMappings:m,semanticTypes:l,plugins:o,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,...c.permissions?{permissions:c.permissions}:{},provider:c.provider,...c.connectionId?{preferredConnectionId:c.connectionId}:{},...c.providerForConnection?{providerForConnection:c.providerForConnection}:{},...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:(x,G,U,Q)=>O(x,"semantic-resolution",G,"entity-expansion",U,Q)})}),Qe=Wn(Xe,j.rowIdentity);return await D({stage:"result",result:Qe},{result:Qe,total:ft,sqls:[...A]}),await D({stage:"completed",durationMs:Xr.performance.now()-p}),{result:Qe,total:ft,schema:I,normedLogicform:Z,sqls:[...A],lineage:b,provider:c.provider.kind,providers:[...R].map(([N,x])=>({connectionId:N,provider:x})),schemaMappingSelections:[...$],...Z.output?await(async()=>{const N=pi(Z.output?.type??"",o);return N?{output:await N.handle({rows:Qe,logicform:Z,schema:I})}:{}})():{}}}catch(C){const F=ma(C);try{await D({stage:"failed",error:F})}catch{}throw F}},Cf=async(t,e)=>{let r={};const n=e.locale??"zh-CN",o=lr(fa(e.plugins,e.locales));try{if(e.connections.length===0)throw new d("DATABASE_CONNECTION_REQUIRED","At least one database connection is required");const i=new Map;for(const $ of e.connections){if($.id.trim().length===0)throw new d("INVALID_DATABASE_CONNECTION","Database connection id must not be empty");if(i.has($.id))throw new d("DATABASE_CONNECTION_ALREADY_REGISTERED",`Database connection id is duplicated: ${$.id}`,{connectionId:$.id});i.set($.id,$)}const s=new kn(e.schemaMappings,e.plugins),u=Lf(t).flatMap($=>s.list($)).map(({connectionId:$})=>$)[0];if(!u)throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain at least one physical Schema leaf");const c=$=>{const w=i.get($);if(!w)throw new d("DATABASE_CONNECTION_NOT_FOUND",`Database connection is not registered: ${$}`,{connectionId:$});return Yr(w,e.providerRegistry)},p=c(u);r={provider:p.kind};const l=De(e.plugins),f=e.operators===void 0?[]:Array.isArray(e.operators)?e.operators:[e.operators],m=new wr(f),y=new Set(m.definitions().map(({name:$})=>$)),h=f.length===0?l:new wr([...l.definitions().filter(({name:$})=>!y.has($)),...m.definitions()]),g=e.semanticTypes===void 0?ro(e.plugins):As(e.semanticTypes,e.plugins??[]);return await Df(t,{...e,schemaMappings:s,locale:n,localeRegistry:o,provider:p,providerForConnection:c,operators:h,operatorsResolved:!0,semanticTypes:g,semanticTypesResolved:!0,connectionId:u,onProgress:async $=>{r=$.partialResult,await e.onProgress?.($)}})}catch(i){return Rf(i,t,r,n,o)}},ya="semanticdb_calendar_dates",No="semanticdb_calendar_relations",lt={dates:"__sdb_calendar_dates",relations:"__sdb_calendar_relations"},Oo=t=>`${typeof t}:${String(t)}`,kf=(t,e)=>{const r=typeof t=="number"?t:Number(t),n=typeof e=="number"?e:Number(e);return Number.isFinite(r)&&Number.isFinite(n)?r-n:String(t).localeCompare(String(e))},ha=(t,e,r)=>{const n=r.filter(u=>u.calendar===e.calendar&&u.grain===e.grain&&u.relation===e.relation&&(e.key===void 0||u.key===e.key)),o=new Map(n.map(u=>[Oo(u.sourceDateId),u])),i=t.flatMap(u=>{const c=o.get(Oo(u))?.targetDateId;return c==null?[]:[c]}),s=[...new Map(i.map(u=>[Oo(u),u])).values()].sort(kf),a=[];for(const u of s){const c=a[a.length-1];if(c&&typeof c.end=="number"&&typeof u=="number"&&u===c.end+1)c.end=u;else if(c&&String(c.end).match(/^\d{8}$/)&&String(u).match(/^\d{8}$/)){const p=Number(c.end),l=Number(u),f=new Date(Date.UTC(Math.floor(p/1e4),Math.floor(p/100)%100-1,p%100));f.setUTCDate(f.getUTCDate()+1);const m=new Date(Date.UTC(Math.floor(l/1e4),Math.floor(l/100)%100-1,l%100));if(f.getTime()===m.getTime()){c.end=u;continue}a.push({start:u,end:u})}else a.push({start:u,end:u})}return{dateIds:s,ranges:a}},Uf=async(t,e,r)=>ha(t,e,await r.loadRelations(t,e)),Mf=(t,e)=>t.filter(r=>Object.entries(e).every(([n,o])=>r[n]===o)).map(r=>r.dateId),qf=["source_date_id","target_date_id","calendar","grain","relation","relation_key"];class jf{provider;constructor(e){this.provider=e}async loadRelations(e,r){if(e.length===0)return[];const n=[...e,r.calendar,r.grain,r.relation];r.key!==void 0&&n.push(r.key);const o=e.map((c,p)=>this.provider.parameter(p,c)),i=c=>this.provider.parameter(c,n[c]),s=c=>this.provider.quoteIdentifier(c),a=[`${s("source_date_id")} IN (${o.join(", ")})`,`${s("calendar")} = ${i(e.length)}`,`${s("grain")} = ${i(e.length+1)}`,`${s("relation")} = ${i(e.length+2)}`];return r.key!==void 0&&a.push(`${s("relation_key")} = ${i(e.length+3)}`),(await this.provider.execute({sql:`SELECT ${qf.map(s).join(", ")} FROM ${s(No)} WHERE ${a.join(" AND ")}`,parameters:n})).map(c=>({sourceDateId:c.source_date_id,targetDateId:c.target_date_id,calendar:String(c.calendar),grain:String(c.grain),relation:String(c.relation),...typeof c.relation_key=="string"||typeof c.relation_key=="number"?{key:String(c.relation_key)}:{}}))}}const xf={[lt.dates]:{id:lt.dates,name:lt.dates,type:"entity",source:ya,properties:[{id:"date_id",name:"date_id",type:"id",primal_type:"string"},{id:"calendar",name:"calendar",type:"string",primal_type:"string"},{id:"grain",name:"grain",type:"string",primal_type:"string"},{id:"period_key",name:"period_key",type:"string",primal_type:"string"},{id:"relative_day",name:"relative_day",type:"int",primal_type:"number"}]},[lt.relations]:{id:lt.relations,name:lt.relations,type:"entity",source:No,properties:[{id:"source_date_id",name:"source_date_id",type:"string",primal_type:"string"},{id:"target_date_id",name:"target_date_id",type:"string",primal_type:"string"},{id:"calendar",name:"calendar",type:"string",primal_type:"string"},{id:"grain",name:"grain",type:"string",primal_type:"string"},{id:"relation",name:"relation",type:"string",primal_type:"string"},{id:"relation_key",name:"relation_key",type:"string",primal_type:"string"}]}},Bf=Object.freeze({execute:Cf,close:na});exports.CALENDAR_DATES_TABLE=ya,exports.CALENDAR_RELATIONS_TABLE=No,exports.CALENDAR_SYSTEM_SCHEMA_IDS=lt,exports.DBConnector=ef,exports.LocaleRegistry=nn,exports.Logicform=Bf,exports.OperatorRegistry=wr,exports.PlannerSemanticRegistry=Ui,exports.ProviderCalendarRelationStore=jf,exports.ProviderRegistry=ea,exports.SchemaMappingRegistry=kn,exports.SemanticDBError=d,exports.SemanticTypeRegistry=Xn,exports.builtinOperators=Od,exports.builtinSemanticTypes=Ln,exports.calendarSystemSchemas=xf,exports.createLocaleRegistry=lr,exports.createOperatorRegistry=De,exports.createPlannerSemanticRegistry=Mi,exports.createSemanticTypeRegistry=ro,exports.defaultLocaleRegistry=pr,exports.enUS=Jo,exports.fromYiAskSchemaMapping=kd,exports.resolveCalendarPeriod=ha,exports.resolveCalendarPeriodFromStore=Uf,exports.resolveOperator=Oi,exports.resolveSchema=fs,exports.selectCalendarDates=Mf,exports.validateResolvedSchema=ps,exports.zhCN=Xo;