semanticdb-v2 2.0.0-alpha.10 → 2.0.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/executor/execute.d.ts +1 -1
- package/dist/executor/federated-execution.d.ts +2 -1
- package/dist/executor/fetch-entities.d.ts +2 -2
- package/dist/executor/index.d.ts +1 -1
- package/dist/executor/partition.d.ts +17 -0
- package/dist/executor/types.d.ts +14 -10
- package/dist/index.d.ts +4 -2
- package/dist/logicform/dimensions.d.ts +16 -0
- package/dist/logicform/index.d.ts +2 -0
- package/dist/normalizer/core.d.ts +1 -1
- package/dist/operators/types.d.ts +8 -1
- package/dist/planner/build-mapping-source-plan.d.ts +6 -0
- package/dist/planner/create-logical-plan.d.ts +4 -0
- package/dist/planner/select-schema-mapping.d.ts +3 -0
- package/dist/planner/types.d.ts +12 -0
- package/dist/schema-mappings/index.d.ts +1 -0
- package/dist/schema-mappings/registry.d.ts +1 -0
- package/dist/schema-mappings/supported-dimensions.d.ts +10 -0
- package/dist/schema-mappings/types.d.ts +7 -1
- package/dist/schema-mappings/yiask.d.ts +1 -0
- package/dist/semantic-types/index.d.ts +1 -1
- package/dist/semantic-types/types.d.ts +29 -1
- package/dist/semanticdb.esm.js +5 -5
- package/dist/semanticdb.js +5 -5
- package/package.json +1 -1
package/dist/semanticdb.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var ja=Object.create;var vo=Object.defineProperty;var xa=Object.getOwnPropertyDescriptor;var Ba=Object.getOwnPropertyNames;var Va=Object.getPrototypeOf,Ya=Object.prototype.hasOwnProperty;var Fa=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ba(e))!Ya.call(t,o)&&o!==r&&vo(t,o,{get:()=>e[o],enumerable:!(n=xa(e,o))||n.enumerable});return t};var tt=(t,e,r)=>(r=t!=null?ja(Va(t)):{},Fa(e||!t||!t.__esModule?vo(r,"default",{value:t,enumerable:!0}):r,t));var mr=require("node:perf_hooks"),ce=require("dayjs"),Vt=require("dayjs/plugin/isoWeek.js"),yr=require("dayjs/plugin/quarterOfYear.js"),Qo=require("dayjs/plugin/customParseFormat.js"),pn=require("node:crypto"),Ho=require("node:util"),va=require("redis"),Qa=require("semanticdb-core"),fe=require("@duckdb/node-api");const V=t=>typeof t=="string",Yt=()=>{let t,e;const r=new Promise((n,o)=>{t=n,e=o});return r.resolve=t,r.reject=e,r},Go=t=>t==null?"":""+t,Ha=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},Ga=/###/g,zo=t=>t&&t.indexOf("###")>-1?t.replace(Ga,"."):t,Wo=t=>!t||V(t),Ft=(t,e,r)=>{const n=V(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if(Wo(t))return{};const i=zo(n[o]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++o}return Wo(t)?{}:{obj:t,k:zo(n[o])}},Ko=(t,e,r)=>{const{obj:n,k:o}=Ft(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=Ft(t,s,Object);for(;a.obj===void 0&&s.length;)i=`${s[s.length-1]}.${i}`,s=s.slice(0,s.length-1),a=Ft(t,s,Object),a?.obj&&typeof a.obj[`${a.k}.${i}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${i}`]=r},za=(t,e,r,n)=>{const{obj:o,k:i}=Ft(t,e,Object);o[i]=o[i]||[],o[i].push(r)},hr=(t,e)=>{const{obj:r,k:n}=Ft(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},Wa=(t,e,r)=>{const n=hr(t,r);return n!==void 0?n:hr(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},st=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Ka={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const Ja=t=>V(t)?t.replace(/[&<>"'\/]/g,e=>Ka[e]):t;class Xa{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 Za=[" ",",","?","!",";"],ec=new Xa(20),tc=(t,e,r)=>{e=e||"",r=r||"";const n=Za.filter(s=>e.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=ec.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},fn=(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 c=i;c<n.length;++c)if(c!==i&&(a+=r),a+=n[c],s=o[a],s!==void 0){if(["string","number","boolean"].indexOf(typeof s)>-1&&c<n.length-1)continue;i+=c-i+1;break}o=s}return o},vt=t=>t?.replace(/_/g,"-"),rc={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 sn{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||rc,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 sn(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new sn(this.logger,e)}}var Fe=new sn;class gr{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 gr{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 c=hr(this.data,a);return!c&&!r&&!n&&e.indexOf(".")>-1&&(e=a[0],r=a[1],n=a.slice(2).join(".")),c||!s||!V(n)?c:fn(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),Ko(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 c=hr(this.data,a)||{};s.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?Jo(c,n,i):c={...c,...n},Ko(this.data,a,c),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 Zo={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 ei=Symbol("i18next/PATH_KEY");function nc(){const t=[],e=Object.create(null);let r;return e.get=(n,o)=>(r?.revoke?.(),o===ei?t:(t.push(o),r=Proxy.revocable(n,e),r.proxy)),Proxy.revocable(Object.create(null),e).proxy}function At(t,e){const{[ei]:r}=t(nc()),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 ti={},mn=t=>!V(t)&&typeof t!="boolean"&&typeof t!="number";class an extends gr{constructor(e,r={}){super(),Ha(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Fe.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=mn(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&&!tc(e,n,o);if(s&&!a){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:V(i)?[i]:i};const u=e.split(n);(n!==o||n===o&&this.options.ns.indexOf(u[0])>-1)&&(i=u.shift()),e=u.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=At(e,{...this.options,...o})),Array.isArray(e)||(e=[String(e)]),e=e.map(U=>typeof U=="function"?At(U,{...this.options,...o}):String(U));const i=o.returnDetails!==void 0?o.returnDetails:this.options.returnDetails,s=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,{key:a,namespaces:c}=this.extractFromKey(e[e.length-1],o),u=c[c.length-1];let p=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;p===void 0&&(p=":");const l=o.lng||this.language,m=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l?.toLowerCase()==="cimode")return m?i?{res:`${u}${p}${a}`,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:u,usedParams:this.getUsedParamsDetails(o)}:`${u}${p}${a}`:i?{res:a,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:u,usedParams:this.getUsedParamsDetails(o)}:a;const f=this.resolve(e,o);let y=f?.res;const h=f?.usedKey||a,g=f?.exactUsedKey||a,$=["[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),w=an.hasDefaultValue(o),R=E?this.pluralResolver.getSuffix(l,o.count,o):"",C=o.ordinal&&E?this.pluralResolver.getSuffix(l,o.count,{ordinal:!1}):"",k=E&&!o.ordinal&&o.count===0,T=k&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${R}`]||o[`defaultValue${C}`]||o.defaultValue;let G=y;_&&!y&&w&&(G=T);const v=mn(G),q=Object.prototype.toString.apply(G);if(_&&G&&v&&$.indexOf(q)<0&&!(V(A)&&Array.isArray(G))){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const U=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,G,{...o,ns:c}):`key '${a} (${this.language})' returned an object instead of string.`;return i?(f.res=U,f.usedParams=this.getUsedParamsDetails(o),f):U}if(s){const U=Array.isArray(G),Y=U?[]:{},z=U?g:h;for(const Q in G)if(Object.prototype.hasOwnProperty.call(G,Q)){const W=`${z}${s}${Q}`;w&&!y?Y[Q]=this.translate(W,{...o,defaultValue:mn(T)?T[Q]:void 0,joinArrays:!1,ns:c}):Y[Q]=this.translate(W,{...o,joinArrays:!1,ns:c}),Y[Q]===W&&(Y[Q]=G[Q])}y=Y}}else if(_&&V(A)&&Array.isArray(y))y=y.join(A),y&&(y=this.extendTranslation(y,e,o,n));else{let U=!1,Y=!1;!this.isValidLookup(y)&&w&&(U=!0,y=T),this.isValidLookup(y)||(Y=!0,y=a);const Q=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&Y?void 0:y,W=w&&T!==y&&this.options.updateMissing;if(Y||U||W){if(this.logger.log(W?"updateKey":"missingKey",l,u,a,W?T:y),s){const me=this.resolve(a,{...o,keySeparator:!1});me&&me.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 ke=[];const qe=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&qe&&qe[0])for(let me=0;me<qe.length;me++)ke.push(qe[me]);else this.options.saveMissingTo==="all"?ke=this.languageUtils.toResolveHierarchy(o.lng||this.language):ke.push(o.lng||this.language);const de=(me,Re,S)=>{const I=w&&S!==y?S:Q;this.options.missingKeyHandler?this.options.missingKeyHandler(me,u,Re,I,W,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(me,u,Re,I,W,o),this.emit("missingKey",me,u,Re,y)};this.options.saveMissing&&(this.options.saveMissingPlurals&&E?ke.forEach(me=>{const Re=this.pluralResolver.getSuffixes(me,o);k&&o[`defaultValue${this.options.pluralSeparator}zero`]&&Re.indexOf(`${this.options.pluralSeparator}zero`)<0&&Re.push(`${this.options.pluralSeparator}zero`),Re.forEach(S=>{de([me],a+S,o[`defaultValue${S}`]||T)})}):de(ke,a,T))}y=this.extendTranslation(y,e,o,f,n),Y&&y===a&&this.options.appendNamespaceToMissingKey&&(y=`${u}${p}${a}`),(Y||U)&&this.options.parseMissingKeyHandler&&(y=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${p}${a}`:a,U?y:void 0,o))}return i?(f.res=y,f.usedParams=this.getUsedParamsDetails(o),f):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 c=V(e)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let u;if(c){const l=e.match(this.interpolator.nestingRegexp);u=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),c){const l=e.match(this.interpolator.nestingRegexp),m=l&&l.length;u<m&&(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=Zo.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(c=>typeof c=="function"?At(c,{...this.options,...r}):c)),e.forEach(c=>{if(this.isValidLookup(n))return;const u=this.extractFromKey(c,r),p=u.key;o=p;let l=u.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));const m=r.count!==void 0&&!V(r.count),f=m&&!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,!ti[`${h[0]}-${g}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(ti[`${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 A=[p];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(A,p,$,g,r);else{let E;m&&(E=this.pluralResolver.getSuffix($,r.count,r));const w=`${this.options.pluralSeparator}zero`,R=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(r.ordinal&&E.indexOf(R)===0&&A.push(p+E.replace(R,this.options.pluralSeparator)),A.push(p+E),f&&A.push(p+w)),y){const C=`${p}${this.options.contextSeparator||"_"}${r.context}`;A.push(C),m&&(r.ordinal&&E.indexOf(R)===0&&A.push(C+E.replace(R,this.options.pluralSeparator)),A.push(C+E),f&&A.push(C+w))}}let _;for(;_=A.pop();)this.isValidLookup(n)||(i=_,n=this.getResource($,g,_,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 ri{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Fe.create("languageUtils")}getScriptPartFromCode(e){if(e=vt(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=vt(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 ni={zero:0,one:1,two:2,few:3,many:4,other:5},oi={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class oc{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=Fe.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=vt(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!"),oi;if(!e.match(/-|_/))return oi;const c=this.languageUtils.getLanguagePartFromCode(e);s=this.getRule(c,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)=>ni[o]-ni[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 ii=(t,e,r,n=".",o=!0)=>{let i=Wa(t,e,r);return!i&&o&&V(r)&&(i=fn(t,r,n),i===void 0&&(i=fn(e,r,n))),i},yn=t=>t.replace(/\$/g,"$$$$");class si{constructor(e={}){this.logger=Fe.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:c,formatSeparator:u,unescapeSuffix:p,unescapePrefix:l,nestingPrefix:m,nestingPrefixEscaped:f,nestingSuffix:y,nestingSuffixEscaped:h,nestingOptionsSeparator:g,maxReplaces:$,alwaysFormat:A}=e.interpolation;this.escape=r!==void 0?r:Ja,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=i?st(i):s||"{{",this.suffix=a?st(a):c||"}}",this.formatSeparator=u||",",this.unescapePrefix=p?"":l||"-",this.unescapeSuffix=this.unescapePrefix?"":p||"",this.nestingPrefix=m?st(m):f||st("$t("),this.nestingSuffix=y?st(y):h||st(")"),this.nestingOptionsSeparator=g||",",this.maxReplaces=$||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 c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=f=>{if(f.indexOf(this.formatSeparator)<0){const $=ii(r,c,f,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format($,void 0,n,{...o,...r,interpolationkey:f}):$}const y=f.split(this.formatSeparator),h=y.shift().trim(),g=y.join(this.formatSeparator).trim();return this.format(ii(r,c,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:f=>yn(f)},{regex:this.regexp,safeValue:f=>this.escapeValue?yn(this.escape(f)):yn(f)}].forEach(f=>{for(a=0;i=f.regex.exec(e);){const y=i[1].trim();if(s=u(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=Go(s));const h=f.safeValue(s);if(e=e.replace(i[0],h),l?(f.regex.lastIndex+=s.length,f.regex.lastIndex-=i[0].length):f.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,r,n={}){let o,i,s;const a=(c,u)=>{const p=this.nestingOptionsSeparator;if(c.indexOf(p)<0)return c;const l=c.split(new RegExp(`${st(p)}[ ]*{`));let m=`{${l[1]}`;c=l[0],m=this.interpolate(m,s);const f=m.match(/'/g),y=m.match(/"/g);((f?.length??0)%2===0&&!y||(y?.length??0)%2!==0)&&(m=m.replace(/'/g,'"'));try{s=JSON.parse(m),u&&(s={...u,...s})}catch(h){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,h),`${c}${p}${m}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,c};for(;o=this.nestingRegexp.exec(e);){let c=[];s={...n},s=s.replace&&!V(s.replace)?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;const u=/{.*}/.test(o[1])?o[1].lastIndexOf("}")+1:o[1].indexOf(this.formatSeparator);if(u!==-1&&(c=o[1].slice(u).split(this.formatSeparator).map(p=>p.trim()).filter(Boolean),o[1]=o[1].slice(0,u)),i=r(a.call(this,o[1].trim(),s),s),i&&o[0]===e&&!V(i))return i;V(i)||(i=Go(i)),i||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${e}`),i=""),c.length&&(i=c.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 ic=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,...c]=s.split(":"),u=c.join(":").trim().replace(/^'+|'+$/g,""),p=a.trim();r[p]||(r[p]=u),u==="false"&&(r[p]=!1),u==="true"&&(r[p]=!0),isNaN(u)||(r[p]=parseInt(u,10))}})}return{formatName:e,formatOptions:r}},ai=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(vt(n),o),e[s]=a),a(r)}},sc=t=>(e,r,n)=>t(vt(r),n)(e);class ac{constructor(e={}){this.logger=Fe.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?ai:sc;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()]=ai(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(c=>c.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,a)].join(this.formatSeparator)}return i.reduce((a,c)=>{const{formatName:u,formatOptions:p}=ic(c);if(this.formats[u]){let l=a;try{const m=o?.formatParams?.[o.interpolationkey]||{},f=m.locale||m.lng||o.locale||o.lng||n;l=this.formats[u](a,f,{...p,...o,...m})}catch(m){this.logger.warn(m)}return l}else this.logger.warn(`there was no format function for ${u}`);return a},e)}}const cc=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class uc extends gr{constructor(e,r,n,o={}){super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=Fe.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={},c={};return e.forEach(u=>{let p=!0;r.forEach(l=>{const m=`${u}|${l}`;!n.reload&&this.store.hasResourceBundle(u,l)?this.state[m]=2:this.state[m]<0||(this.state[m]===1?s[m]===void 0&&(s[m]=!0):(this.state[m]=1,p=!1,s[m]===void 0&&(s[m]=!0),i[m]===void 0&&(i[m]=!0),c[l]===void 0&&(c[l]=!0)))}),p||(a[u]=!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(c)}}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(c=>{za(c.loaded,[i],s),cc(c,e),r&&c.errors.push(r),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(u=>{a[u]||(a[u]={});const p=c.loaded[u];p.length&&p.forEach(l=>{a[u][l]===void 0&&(a[u][l]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(c=>!c.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=(u,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(u&&p&&o<this.maxRetries){setTimeout(()=>{this.read.call(this,e,r,n,o+1,i*2,s)},i);return}s(u,p)},c=this.backend[n].bind(this.backend);if(c.length===2){try{const u=c(e,r);u&&typeof u.then=="function"?u.then(p=>a(null,p)).catch(a):a(null,u)}catch(u){a(u)}return}return c(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 c={...s,isUpdate:i},u=this.backend.create.bind(this.backend);if(u.length<6)try{let p;u.length===5?p=u(e,r,n,o,c):p=u(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 u(e,r,n,o,a,c)}!e||!e[0]||this.store.addResource(e[0],r,n,o)}}}const hn=()=>({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}),ci=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),Ar=()=>{},dc=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})},ui="__i18next_supportNoticeShown",lc=()=>!!(typeof globalThis<"u"&&globalThis[ui]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),pc=()=>{typeof globalThis<"u"&&(globalThis[ui]=!0)},fc=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 lr extends gr{constructor(e={},r){if(super(),this.options=ci(e),this.services={},this.logger=Fe,this.modules={external:[]},dc(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=hn();this.options={...n,...this.options,...ci(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&&!fc(this)&&!lc()&&(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}"),pc());const o=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?Fe.init(o(this.modules.logger),this.options):Fe.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=ac;const p=new ri(this.options);this.store=new Xo(this.options.resources,this.options);const l=this.services;l.logger=Fe,l.resourceStore=this.store,l.languageUtils=p,l.pluralResolver=new oc(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"),u&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(l.formatter=o(u),l.formatter.init&&l.formatter.init(l,this.options),this.options.interpolation.format=l.formatter.format.bind(l.formatter)),l.interpolator=new si(this.options),l.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},l.backendConnector=new uc(o(this.modules.backend),l.resourceStore,l,this.options),l.backendConnector.on("*",(f,...y)=>{this.emit(f,...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 an(this.services,this.options),this.translator.on("*",(f,...y)=>{this.emit(f,...y)}),this.modules.external.forEach(f=>{f.init&&f.init(this)})}if(this.format=this.options.interpolation.format,r||(r=Ar),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[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(u=>{this[u]=(...p)=>this.store[u](...p)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...p)=>(this.store[u](...p),this)});const a=Yt(),c=()=>{const u=(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 u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),a}loadResources(e,r=Ar){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(u=>{u!=="cimode"&&i.indexOf(u)<0&&i.push(u)})};o?s(o):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>s(c)),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=Yt();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=Ar),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"&&Zo.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=Yt();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,c)=>{c?this.isLanguageChangingTo===e&&(o(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,n.resolve((...u)=>this.t(...u)),r&&r(a,(...u)=>this.t(...u))},s=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const c=V(a)?a:a&&a[0],u=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(V(a)?[a]:a);u&&(this.language||o(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,p=>{i(p,u)})};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 c;typeof s!="object"?c=this.options.overloadTranslationOptionHandler([i,s].concat(a)):c={...s},c.lng=c.lng||o.lng,c.lngs=c.lngs||o.lngs,c.ns=c.ns||o.ns,c.keyPrefix!==""&&(c.keyPrefix=c.keyPrefix||n||o.keyPrefix);const u={...this.options,...c};typeof c.keyPrefix=="function"&&(c.keyPrefix=At(c.keyPrefix,u));const p=this.options.keySeparator||".";let l;return c.keyPrefix&&Array.isArray(i)?l=i.map(m=>(typeof m=="function"&&(m=At(m,u)),`${c.keyPrefix}${p}${m}`)):(typeof i=="function"&&(i=At(i,u)),l=c.keyPrefix?`${c.keyPrefix}${p}${i}`:i),this.t(l,c)};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,c)=>{const u=this.services.backendConnector.state[`${a}|${c}`];return u===-1||u===0||u===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=Yt();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=Yt();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 ri(hn());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 lr(e,r);return n.createInstance=lr.createInstance,n}cloneInstance(e={},r=Ar){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const o={...this.options,...e,isClone:!0},i=new lr(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((c,u)=>(c[u]={...this.store.data[u]},c[u]=Object.keys(c[u]).reduce((p,l)=>(p[l]={...c[u][l]},p),c[u]),c),{});i.store=new Xo(a,o),i.services.resourceStore=i.store}if(e.interpolation){const c={...hn().interpolation,...this.options.interpolation,...e.interpolation},u={...o,interpolation:c};i.services.interpolator=new si(u)}return i.translator=new an(i.services,o),i.translator.on("*",(a,...c)=>{i.emit(a,...c)}),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 Le=lr.createInstance(),mc=Le.createInstance;Le.dir,Le.init,Le.loadResources,Le.reloadResources,Le.use,Le.changeLanguage,Le.getFixedT,Le.t,Le.exists,Le.setDefaultNamespace,Le.hasLoadedNamespace,Le.loadNamespaces,Le.loadLanguages;const di={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"}},li={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"}},yc=[li,di],Qt=t=>t.trim().toLowerCase(),hc=t=>t?"locale"in t?[t]:t:[],gc=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 gn{definitions=new Map;i18n;constructor(e){this.i18n=mc(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(yc),this.register(e)}register(e){for(const r of hc(e)){const n=r;if(!gc(n))throw new TypeError("Locale definition must have a non-empty locale");const o=n,i=this.definitions.get(Qt(o.locale)),s={locale:o.locale,messages:Object.freeze({...i?.messages,...o.messages})};this.definitions.set(Qt(o.locale),s),this.i18n.addResourceBundle(o.locale,"translation",s.messages,!0,!0)}return this}resolve(e="zh-CN"){const r=this.definitions.get(Qt(e));if(r)return r;const n=Qt(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(Qt(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 wr=t=>new gn(t),$r=new gn;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=$r){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}}ce.extend(Vt),ce.extend(yr);const Ac=new Set(["year","quarter","month","week"]),An=t=>t.format("YYYY-MM-DD HH:mm:ss"),wn=(t,e)=>t.operator&&e(t.operator).kind==="aggregate"?!0:(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?wn(t.pred,e):!1)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&wn(r,e)),Er=(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:Er(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:Er(t.input,e,r)}:{},...t.inputs?{inputs:t.inputs.map(o=>Er(o,e,r))}:{}}},wc=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 Er(t.input,t,{partitionBy:e.map(o=>t.resolveKey(String(o))),orderBy:n})},$c=t=>{if(t.groupByNames.length===0)return;if(typeof t.pred.pred!="object"||Array.isArray(t.pred.pred)||!wn(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})},Ec=(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 w=E;return typeof w.$gte=="string"&&typeof w.$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=ce(String(s.$gte)),c=ce(String(s.$lte));if(!a.isValid()||!c.isValid())throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","Target date range is invalid");const u=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:An(p)}},m=new Set([...(t.groupby??[]).map(({name:E})=>E),...(t.preds??[]).map(({name:E})=>E)]),f=E=>{let w=E;for(;m.has(w);)w=`_${w}`;return m.add(w),w},y=f("__accumulate_period"),h=e.map((E,w)=>f(`__accumulate_metric_${w}`)),g=(t.groupby??[]).map(({name:E})=>String(E)),$=r==="year"||r==="quarter"?"month":"day",A={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,w)=>({...E.pred,name:h[w]??`__accumulate_metric_${w}`}))},_={version:t.version,from:A,preds:[...g.map(E=>({pred:E,name:E})),{pred:y,name:y},...e.map((E,w)=>({operator:"$accumulate",pred:h[w]??`__accumulate_metric_${w}`,args:{partitionBy:g,orderBy:[{pred:y,direction:"asc"}]},name:u[w]??`accumulate_${w}`}))]};return{version:t.version,from:_,query:{[y]:{$gte:An(a),$lte:An(c)}},preds:[...g.map(E=>({pred:E,name:E})),...u.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}:{}}},_c={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"||!Ac.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:wc,validatePlan:$c,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 Ec(t,r,n)},getOutputProperty({name:t,inputProperty:e}){return e?{...e,name:t,isArray:!1}:{name:t,type:"number",primal_type:"number",isArray:!1}}},Sc={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}}},wt=(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},_r=t=>({name:t,type:"number",primal_type:"number",isArray:!1}),Ic={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`(${wt("$add",t,2,Number.POSITIVE_INFINITY).join(" + ")})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:_r(t)}},oe=t=>structuredClone(t),bc=(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},Rc=(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},Nc=t=>{const e=t.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(e))},pi=(t,e)=>t.properties.some(r=>r!==e&&r.id===e.name)?e.id:e.name,Oc=(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)),ue=(t,e,r)=>{const n=t.properties.find(o=>o.id===e)??t.properties.find(o=>o.name===e);if(n)return{canonicalName:pi(t,n),canonicalId:n.id,schema:t,property:n,relations:[]};for(const{property:o,prefix:i}of Oc(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=ue(s,e.slice(i.length+1),r);return{canonicalName:`${pi(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})},$n=(t,e)=>t.name===e||t.id===e,Tc=(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=>$n(a,i.hierarchy?.up??"")):[],...r.properties.filter(a=>a.hierarchy?.down!==void 0&&$n(i,a.hierarchy.down))];if(s.some(a=>$n(e,a.name)))return!0;o.push(...s)}return!1},fi=(t,e,r,n)=>{if(t.operator||typeof t.pred!="string"||e.length===0)return!1;let o;try{o=ue(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=ue(r,i.pred,n)}catch{return!1}if(s.property.isArray)return!1;if(s.relations.length===0&&o.relations.length===0)return Tc(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})},Pc=({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:c})=>c==="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},Cc=(t,e,r)=>{const n=ue(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}},Dc={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=Cc(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!==ue(r,t,n).property.name)throw new d("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${a.name}`);const c=s.levels.reduce((y,h)=>y+h.codeLength,0),u=i.schema.properties.filter(({type:y})=>y==="ID"),l=i.relation&&u.length===1&&u[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:c,storage:s.storage}}}let m=0;const f=s.levels.find(y=>(m+=y.codeLength,y.name===e.level||y.syno?.includes(e.level)));if(!f)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:f.name,codeLength:m,totalLength:c,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 c=e.levels.filter(y=>typeof y=="object"&&y!==null&&!Array.isArray(y)&&typeof y.name=="string"&&Number.isInteger(y.codeLength)),u=e.totalLength,p=e.storage;if(c.length!==e.levels.length||c.length===0||!Number.isInteger(u)||Number(u)<=0||c.some(({name:y,codeLength:h},g)=>y.length===0||h<=0||h>Number(u)||g>0&&h<=Number(c[g-1]?.codeLength))||c.at(-1)?.codeLength!==u||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=c.map(g=>`WHEN ${y} = ${g.codeLength} THEN ${r.value(g.name)}`);return`(CASE ${l} ${h.join(" ")} ELSE NULL END)`}const m=c.slice(0,-1).map(y=>{const h=Number(u)-y.codeLength;return`WHEN ${r.substring(t,y.codeLength+1,h)} = ${r.value("0".repeat(h))} THEN ${r.value(y.name)}`}),f=c.at(-1);return`(CASE ${l} ${m.join(" ")} ELSE ${r.value(f?.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}}},$t=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},Et=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),En=(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)}},Sr=(t,{schema:e,mapping:r})=>r.mappings?.find(n=>n.mappingType==="property"&&n.propertyTarget?.some(o=>Et(e,o)?.id===t.id)),mi=(t,e,r)=>{const n=Et(r.schema,t);if(!n)return`hierarchy property is not available: ${t}`;const o=En(n,e,r);if(!o)return`hierarchy level is not available: ${String(e)}`;const i=Sr(n,r);if(!$t(i?.granularity))return;const s=En(n,i.granularity.level,r);return s&&s.index>=o.index?void 0:`hierarchy dimension ${t} requires ${o.name}, but source has ${s?.name}`},kc=(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 c=mi(i.pred,i.args.level,e);if(c)return c}else{const c=Et(e.schema,i.pred),u=c&&Sr(c,e);if($t(u?.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 c of a){if(typeof c=="string")continue;const u=r(c);if(u)return u}},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 c of a){const u=n(c);if(u)return u}}else if(s==="$expr"){if(typeof a!="object"||a===null||Array.isArray(a))continue;const c=a.pred;if(typeof c!="object"||c===null||Array.isArray(c))continue;const u=r(c);if(u)return u}else if(!s.startsWith("$")){const c=Et(e.schema,s),u=c&&Sr(c,e);if($t(u?.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=mi(i.pred,i.args?.level,e);if(s)return s}else if(i.operator===void 0){const s=Et(e.schema,i.pred),a=s&&Sr(s,e);if($t(a?.granularity))return`raw groupby is not covered by hierarchy-grained source: ${i.pred}`}}},Uc={kind:"hierarchy",isGranularity:$t,validateItem(t,e){const r=t.granularity;if($t(r))return t.propertyTarget?.every(n=>{const o=Et(e.schema,n);return o!==void 0&&En(o,r.level,e)!==void 0})?void 0:"physical hierarchy granularity requires a mapped hierarchy Property and level"},candidateReason:kc,supportsGroupby:t=>t.operator==="$hierarchyLevel"},Mc={keys:["hierarchy"],resolve(t,e){for(const m of e)if(m.level!==void 0){if(typeof m.level!="string"||m.level.trim().length===0)throw new d("INVALID_PROPERTY_LEVEL",`Property ${m.name} level must be a non-empty string`,{property:m.name,level:m.level});if(m.primal_type!=="entity"&&m.primal_type!=="object")throw new d("PROPERTY_LEVEL_REQUIRES_ENTITY",`Property ${m.name} level requires an entity relation`,{property:m.name,type:m.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(m=>m!=="property"&&m!=="storage"&&m!=="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 m=e.filter(f=>f.type==="ID");if(m.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:m.length});return m[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(m=>m.name===n.property||m.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 c=new Set,u=new Set,p=n.levels.map((m,f)=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${f} must be an object`);const y=m,h=Object.keys(y).filter($=>$!=="name"&&$!=="syno"&&$!=="codeLength");if(h.length>0)throw new d("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${f} 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 ${f} name must not be empty`);if(c.has(y.name)||u.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||c.has($)||u.has($))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${$}`);u.add($)}return c.add(y.name),{name:y.name,...g.length>0?{syno:[...g]}:{},codeLength:Number(y.codeLength)}});return{hierarchy:{property:s.name,storage:a,levels:p}}}},qc=Object.freeze({name:"hierarchy",schemaMetadata:Mc,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:Pc,resolveEntityFilterProperty:Lc,operators:[Dc],mappingGranularity:Uc}),jc=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp"),_n="$periodValue",xc=(t,e,r)=>{const n=e?.periodBoundaryPolicy?.({pred:t,...r?{executionContext:r}:{}});if(n)return{operator:_n,...n};if(e?.kind==="aggregate")throw new d("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${_n}; ${e.name} describes a time range`,{operator:e.name});return{operator:_n,boundary:"end",implicit:!0}},Bc={name:"observation",resolveProjection({pred:t,schema:e,sourceProperty:r,outputProperty:n,operator:o,executionContext:i}){if(!r||!jc(r,e))return;const s=xc(t,o,i);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:s.boundary,sourceProperty:r.name}}}}},Vc=new Set(["second","minute","hour","day","week","month","quarter","year"]),yi=t=>typeof t=="string"&&Vc.has(t),Yc=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 d(`${r.codePrefix}_PERIOD_INVALID_BOUND`,`${r.label} period ${e} must be a date`,{owner:e,value:t});return n},at=(t,e=2)=>String(t).padStart(e,"0"),Sn=t=>`${at(t.getFullYear(),4)}-${at(t.getMonth()+1)}-${at(t.getDate())} ${at(t.getHours())}:${at(t.getMinutes())}:${at(t.getSeconds())}.`+at(t.getMilliseconds(),3),Fc=(t,e)=>{if(!Yc(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 d(`${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 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}},vc=(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},Qc=(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},hi=(t,e,r)=>{const{lower:n,upper:o}=Fc(t,r),i=[];let s=vc(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=Qc(s,e),c=new Date(Math.min(a.getTime()-1,o));i.push({label:Sn(s),start:Sn(s),end:Sn(c)}),s=a}return i},Hc=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.name),Gc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.name)),zc=(t,e)=>{if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:l})=>l==="timestamp");if(!r)return;const n=Hc(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"||!yi(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 m=l.args?.boundary;if(m!=="start"&&m!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:m});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 u=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:u,metrics:a,periods:hi(p,s,{codePrefix:"OBSERVATION",label:"Observation"}).map(l=>({label:l.label,asOf:l[u]}))}},gi=["second","minute","hour","day","week","month","quarter","year"],Wc=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:[Bc],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(gi.indexOf(o)>gi.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=zc(t,e);if(r)return{group:r.group,property:r.timestamp,periods:r.periods,source:{kind:"latest",timestamp:r.timestamp},rewriteQuery:n=>Gc(n,r.timestamp),rewritePred:n=>r.metrics.find(o=>o.pred===n)?.effectivePred??n}}}}),Ht=(t,e)=>typeof e=="string"?t.properties.find(({id:r,name:n})=>r===e||n===e):void 0,Kc={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:m})=>m==="ID"),a=i===void 0?s.length===1?s[0]:void 0:Ht(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 c=Array.isArray(r.roots),u=c?r.roots:r.root===void 0?[]:[r.root];if(!c&&u.length===0||u.some(m=>m===void 0))throw new d("RECURSIVE_ROOT_REQUIRED","$recursive requires root or roots");const p=await Promise.all(u.map(m=>e.normalizeValue(m,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:u})=>u==="ID"):Ht(o,i),a=r.parentProperty??r.parent_property??o.parentProperty??"pid",c=Ht(o,a);s&&e.assertPropertyAllowed(o,s),c&&e.assertPropertyAllowed(o,c)},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=Ht(o,r.idProperty),s=Ht(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__"),c=r.quoteIdentifier("__recursive_id__"),u=r.quoteIdentifier("__recursive_node__"),p=r.quoteIdentifier("__recursive_child__"),l=r.quoteIdentifier(i.idColumn),m=r.quoteIdentifier(i.parentColumn),f=o(i.source,typeof i.sourceSql=="string"?i.sourceSql:void 0),y=()=>s.map(E=>n(E)).join(", "),h=(E,w=!1)=>s.length===1?`${E} ${w?"<>":"="} ${y()}`:`${E} ${w?"NOT IN":"IN"} (${y()})`,g=`${u}.${l}`,$=i.includeSelf?h(g):`${h(`${u}.${m}`)} AND ${h(g,!0)}`,A=r.recursiveCteUnion??"UNION",_=`(WITH RECURSIVE ${a}(${c}) AS ( SELECT ${g} FROM ${r.tableAlias(f,"__recursive_node__")} WHERE ${$} ${A} SELECT ${p}.${l} FROM ${r.tableAlias(f,"__recursive_child__")} JOIN ${a} ON ${p}.${m} = ${a}.${c}) SELECT DISTINCT ${c} FROM ${a})`;return`${e} IN ${_}`}},Jc=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:[Kc]});ce.extend(Vt);const In=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...In(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:In(r))]:e},Ai=(t,e)=>ce(t).endOf(e==="week"?"isoWeek":e).toDate(),bn=t=>ce(t).format("YYYY-MM-DD HH:mm:ss"),Xc=(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})},wi=(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})},Zc=Object.freeze({name:"temporal",schemaMetadata:{keys:["timeWatermark"],resolve(t){return wi(t.timeWatermark,`Schema ${t.id}`),{...t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}}},propertyMetadata:{keys:["timeWatermark"],resolve(t,e){if(wi(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 c=[...new Set((t.preds??[]).flatMap(In).filter(l=>l!==e.id))],u=[{schema:e,property:r}];for(const l of c){const m=s(l),f=t.propertyResolve?.[l],y=f?.[r.id]??f?.[r.name]??a(e,r.name,m);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=m.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});u.push({schema:m,property:h})}const p=u.map(({schema:l,property:m})=>{const f=Xc(m.timeWatermark??l.timeWatermark??i,`${l.id}.${m.id}`);if(f.type==="now_offset"){const y=Ai(ce(o).add(f.offset,"day").toDate(),m.granularity??"day");return{operator:"$constant",args:{value:bn(y),type:"timestamp"},name:`${l.name}\u6570\u636E\u65F6\u95F4`}}return{operator:"$periodBoundary",args:{boundary:"end"},pred:{operator:"$max",pred:m.name,schema:l.id},name:`${l.name}\u6700\u65B0\u65F6\u95F4`}});return p.some(({operator:l})=>l==="$periodBoundary")&&p.push({operator:"$constant",args:{value:bn(Ai(o,r.granularity??"day")),type:"timestamp"},name:"\u73B0\u5728"}),p.push({operator:"$constant",args:{value:bn(n),type:"timestamp"},name:"\u63D0\u95EE\u65F6\u95F4\u4E0A\u754C"}),{version:t.version,schema:e.id,preds:[{name:"__timeWatermark__",operator:"$least",pred:p}]}}}),br=(t,e)=>{const r=t.filter(n=>n.type===e);return r.length===1?r[0]:void 0},Gt=t=>{if(t.type!=="entity"||t.temporalSemantics==="snapshot")return;const e=br(t.properties,"ID"),r=br(t.properties,"timestamp"),n=br(t.properties,"start_date"),o=br(t.properties,"end_date");return e&&r&&n&&o?{id:e,timestamp:r,start:n,end:o}:void 0},$i=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.timestamp.name),eu=(t,e)=>$i(t,e)!==void 0,tu=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.timestamp.name)),ru=(t,e)=>{const r=$i(t,e);if(!r)return;const n=r.args?.granularity;if(r.operator!=="$dateBucket"||!yi(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:hi(o,n,{codePrefix:"VALIDITY",label:"Valid-time"}).map(({label:i,end:s})=>({label:i,asOf:s}))}},nu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ou=t=>nu(t)?t.$lte??t.$lt??t.$eq:t,Ei=(t,e)=>{if(!t)return t;const r=Object.fromEntries(Object.entries(t).map(([a,c])=>[a,(a==="$and"||a==="$or")&&Array.isArray(c)?c.map(u=>Ei(u,e)):c])),n=Object.entries(t).find(([a])=>a===e.timestamp.name);if(!n)return r;const[,o]=n,i=ou(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}]}}},_i=(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&&_i(o,e)))),iu={name:"validity",resolveQuery({logicform:t,schema:e,query:r}){const n=Gt(e);if(!n)return r;if(eu(t,n))return tu(r,n);const i=_i(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:new Date().toISOString()}};return Ei(i,n)},resolveProjection({schema:t,outputProperty:e}){if(Gt(t))return{outputProperty:{...e,temporal:{kind:"validity"}}}}},su={name:"start_date",primalType:"date"},au={name:"end_date",primalType:"date"},cu=Object.freeze({name:"validity",semanticTypes:[su,au],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:[iu],intervalSemantics:{resolve:Gt},relationSemantics:{plan({sourceSchema:t,targetSchema:e}){const r=Gt(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=Gt(e);if(!r)return;const n=ru(t,r);return n?{group:n.group,property:r.timestamp,periods:n.periods,source:{kind:"interval",start:r.start,end:r.end}}:void 0}}}),Si=(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},uu=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,c=Object.keys(a).filter(l=>l!=="up"&&l!=="down");if(c.length>0)throw new d("UNSUPPORTED_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy only supports up and down`,{property:o.name,unsupported:c});const u=Si(t,o,a.up,"up"),p=Si(t,o,a.down,"down");return{...o,hierarchy:{...u?{up:u}:{},...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}}}),Ii=Object.freeze([qc,Jc,Zc,Wc,cu,uu]),Ae=(t=[])=>{const e=[...Ii,...t],r=new Set,n=new Set,o=new Set,i=new Set,s=new Set,a=new Set,c=new Set,u=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 f of[...l.schemaMetadata?.keys??[],...l.legacySchemaKeys??[]]){if(!f)throw new d("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(n.has(f))throw new d("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${f}`,{key:f,plugin:l.name});n.add(f)}for(const f of l.propertyMetadata?.keys??[]){if(!f)throw new d("INVALID_PLUGIN_PROPERTY_METADATA_KEY","Plugin Property metadata key must not be empty");if(o.has(f))throw new d("PLUGIN_PROPERTY_METADATA_KEY_ALREADY_REGISTERED",`Plugin Property metadata key is already registered: ${f}`,{key:f,plugin:l.name});o.add(f)}for(const f of l.operators??[]){if(i.has(f.name))throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${f.name}`,{operator:f.name,plugin:l.name});i.add(f.name)}for(const f of l.semanticTypes??[]){if(s.has(f.name))throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${f.name}`,{semanticType:f.name,plugin:l.name});s.add(f.name)}for(const f of l.plannerSemantics??[]){if(!f.name||a.has(f.name))throw new d("PLUGIN_SEMANTIC_RULE_ALREADY_REGISTERED",`Plugin Planner semantic rule must be non-empty and unique: ${f.name}`,{rule:f.name,plugin:l.name});a.add(f.name)}for(const f of l.queryOperators??[]){if(!f.name||c.has(f.name))throw new d("PLUGIN_QUERY_OPERATOR_ALREADY_REGISTERED",`Plugin Query Operator must be non-empty and unique: ${f.name}`,{operator:f.name,plugin:l.name});c.add(f.name)}for(const f of l.outputHandlers??[]){if(!f.type||u.has(f.type))throw new d("PLUGIN_OUTPUT_HANDLER_ALREADY_REGISTERED",`Plugin output handler type must be non-empty and unique: ${f.type}`,{type:f.type,plugin:l.name});u.add(f.type)}const m=l.mappingGranularity;if(m){if(!m.kind||p.has(m.kind))throw new d("PLUGIN_GRANULARITY_ALREADY_REGISTERED",`Plugin physical granularity kind must be non-empty and unique: ${m.kind}`);p.add(m.kind)}}return Object.freeze(e)},_t=(t,e=[])=>Ae(e).flatMap(r=>r.queryOperators??[]).find(r=>r.name===t),Rn=(t,e=[])=>Ae(e).flatMap(r=>r.outputHandlers??[]).find(r=>r.type===t),Nn=(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},bi=(t,e=[])=>Nn("interval semantics",Ae(e).flatMap(r=>{const n=r.intervalSemantics?.resolve(t);return n?[{plugin:r.name,value:n}]:[]})),du=(t,e,r=[])=>Nn("relation semantics",Ae(r).flatMap(n=>{const o=n.relationSemantics?.plan({sourceSchema:t,targetSchema:e});return o?[{plugin:n.name,value:o}]:[]})),lu=(t,e,r=[])=>Nn("planner period semantics",Ae(r).flatMap(n=>{const o=n.plannerPeriod?.resolve(t,e);return o?[{plugin:n.name,value:o}]:[]})),On=t=>typeof t=="string"&&t.length>0&&t!=="placeholder"||typeof t=="number"&&Number.isSafeInteger(t),pu=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]},Tn=(t,e=[])=>{for(const r of Ae(e)){const n=r.resolveEntityFilterProperty?.(t);if(n)return n}return pu(t)},Pn=t=>{if(t.name)return t.name;throw new d("MISSING_PRED_NAME","A normalized groupby PredItem must have a name")},Ln=t=>typeof t.pred=="string"?t.pred:void 0,fu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),mu={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},yu={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},Cn=(t,e,r)=>{const n=e.toLowerCase().startsWith("en"),o=t.time;if(!fu(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}${mu[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${yu[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};ce.extend(Vt),ce.extend(yr);const hu=["second","minute","hour","day","week","month","quarter","year"],gu=new Set(hu),Dn=["year","quarter","month","week","day","hour","minute","second"],Ri=t=>Object.prototype.toString.call(t)==="[object Object]",rt=t=>{throw new d("INVALID_PERIOD_SHIFT_ARGS",t)},Au=t=>{const e=t.time;Ri(e)||rt("$periodShift requires args.time");const r=e;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!gu.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&rt("Relative period shift time requires only granularity and an integer offset"),r;const o=Object.entries(r);(o.length===0||o.some(([a,c])=>!Dn.includes(a)||!Number.isInteger(c)))&&rt("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&rt("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,[c,u]]of Object.entries(i)){const p=r[a];p!==void 0&&(Number(p)<c||Number(p)>u)&&rt(`Invalid absolute period shift ${a}: ${JSON.stringify(p)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&rt("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&rt("Absolute period shift day requires month"),r},Ni=(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),wu=(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 Dn){const o=e[n];typeof o=="number"&&(r=Ni(r,n,o))}return r},kn=(t,e)=>t instanceof Date?e.toDate():typeof t!="string"?t:e.format(t.includes(":")?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"),$u=(t,e,r,n,o)=>(t.groupby??[]).filter(i=>{const s=Ln(i);return s?ue(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",c="granularity"in n?-n.offset:o.originalAnchor&&o.shiftedAnchor?o.originalAnchor.diff(o.shiftedAnchor,a):0;return{name:Pn(i),granularity:a,offset:c}}),Un=(t,e,r)=>{if(Array.isArray(t))return t.map(i=>Un(i,e,r));if(Ri(t))return Object.fromEntries(Object.entries(t).map(([i,s])=>[i,Un(s,e,r)]));if(!(t instanceof Date)&&typeof t!="string")return t;const n=ce(t);if(!n.isValid())return t;const o=wu(n,e);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,kn(t,o)},Eu=(t,e,r,n,o)=>{const i=new Set,s=c=>Object.fromEntries(Object.entries(c).map(([u,p])=>{if((u==="$and"||u==="$or")&&Array.isArray(p))return[u,p.map(m=>s(m))];const l=ue(e,u,r);return l.property.primal_type!=="date"?[u,p]:(i.add(l.canonicalName),[u,Un(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},ct=t=>{const e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?e[0]:{$and:e}},nt=t=>[...t.query?[t.query]:[],...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?nt(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(r=>typeof r=="string"?[]:nt(r)):[]],_u=(t,e,r)=>{if(!(t instanceof Date)&&typeof t!="string")return t;const n=ce(t);if(!n.isValid())return t;if("granularity"in e)return kn(t,n.add(-e.offset,e.granularity));if(!r.originalAnchor)return t;let o=n;for(const i of Dn)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=Ni(o,i,s)}return kn(t,o)},Mn=({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o})=>{const i=e.pred;(!i||typeof i!="object"||Array.isArray(i))&&rt("$periodShift pred must be a nested metric");const s=Au(e.args??{}),a={shiftedValues:0},c=ct([t.query,...nt(e)]);if(!c)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const u=Eu(c,n,o,s,a),p=oe(i);p.name=r,delete p.query;const l=oe(t);l.query=u,l.preds=[p],delete l.having,delete l.sort,delete l.limit,delete l.page;const m=new Set((t.groupby??[]).filter(f=>{const y=Ln(f);return y?ue(n,y,o).property.primal_type==="date":!1}).map(Pn));return{kind:"query",logicform:l,groupKeyShifts:$u(t,n,o,s,a),mapResult:f=>f.map(y=>{const h={...y};for(const g of m)h[g]=_u(h[g],s,a);return h})}},Su={name:"$periodShift",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=Cn(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:Mn,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodShift requires a nested metric");return{...e,name:t,isArray:!1}}},Iu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Rr=t=>typeof t=="string"||typeof t=="number"||t instanceof Date,Oi=(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},Ti=(t,e)=>{if(Rr(t)){e.start??=t,e.end??=t;return}if(!Iu(t))return;const r=t.$eq;Rr(r)&&(e.start??=r,e.end??=r);const n=t.$gte??t.$gt,o=t.$lte??t.$lt;Rr(n)&&(e.start??=n),Rr(o)&&(e.end??=o);for(const i of["$and","$or"]){const s=t[i];if(Array.isArray(s))for(const a of s)Ti(a,e)}},bu=(t,e,r,n)=>{const o=Oi(e,n),i=new Set,s={},a=(l,m)=>{for(const[f,y]of Object.entries(l)){if((f==="$and"||f==="$or")&&Array.isArray(y)){for(const g of y)a(g,m||f==="$or");continue}if(f.startsWith("$"))continue;const h=ue(e,f,r);if(h.property.type==="timestamp"){if(m)throw new d("AMBIGUOUS_TIME_QUERY",`${n} does not support timestamp conditions inside $or`);i.add(h.canonicalName),Ti(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 c=[...i][0];if(!c||c!==o.name)throw new d("AMBIGUOUS_TIME_QUERY",`${n} requires the Schema timestamp property: ${o.name}`);const u=l=>{const m=[];for(const[f,y]of Object.entries(l)){if((f==="$and"||f==="$or")&&Array.isArray(y)){const h=y.map(g=>u(g)).filter(g=>g!==void 0);h.length>0&&m.push([f,h]);continue}!f.startsWith("$")&&ue(e,f,r).property.type==="timestamp"||m.push([f,y])}return m.length>0?Object.fromEntries(m):void 0},p=u(t);return{property:o,propertyName:c,...s.start!==void 0?{start:s.start}:{},...s.end!==void 0?{end:s.end}:{},...p?{queryWithoutTime:p}:{}}},Pi=(t,e,r,n,o)=>{const i=ct([t,...nt(e)]);if(!i)throw new d("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return bu(i,r,n,o)},Li=(t,e,r)=>ct([t,{[e]:r}]),Ru=new Set(["day","week","month","quarter","year"]),Nu={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Ou=t=>{if(typeof t!="string"||!Ru.has(t))throw new d("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return t},Ci=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},qn=t=>{const e=oe(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=qn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:qn(r))),e},Tu={name:"$averagePerPeriod",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${t} per ${typeof e.granularity=="string"?e.granularity:"period"}`:`${t}${Nu[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=Ou(e.args?.granularity),s=Oi(r,"$averagePerPeriod"),a=qn(e.pred),c=ct([t.query,...nt(e)]),u=Ci(t);u.preds=[{...a,name:"__avg_period_num__"}],c&&(u.query=c);const p=Ci(t);p.preds=[{operator:"$countDistinct",pred:{operator:"$dateBucket",pred:s.name,args:{granularity:i},name:"__avg_period_bucket__"},name:"__avg_period_den__"}],c&&(p.query=c);const l=o("component.numerator",`${n}\u5206\u5B50`,{outputName:n}),m=o("component.denominator",`${n}\u5206\u6BCD`,{outputName:n});return{components:[{name:l,logicform:u},{name:m,logicform:p}],expression:`${l} / NULLIF(${m}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$averagePerPeriod requires a nested metric");return{...e,name:t,isArray:!1}}},Pu={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}}},St=t=>{throw new d("INVALID_CASE_ARGS",t)},Lu=t=>{if(t.mode!=="auto")return;Object.hasOwn(t,"cases")&&St("$case auto mode cannot define args.cases"),t.empty!==void 0&&typeof t.empty!="boolean"&&St("$case auto mode args.empty must be boolean");const e=t.buckets;e!==void 0&&(!Number.isInteger(e)||e<2||e>100)&&St("$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)&&St("$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]))&&St(`$case auto mode requires resolved finite args.${o}`);t.min>t.max&&St("$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}},Cu=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},Nr=t=>{const e=Number(t.toPrecision(15));return Object.is(e,-0)?0:e},jn=t=>String(Nr(t)),Du=(t,e,r)=>{if(t===e)return[t,e];const n=Cu((e-t)/r),o=Nr(Math.floor(t/n)*n),i=Nr(Math.ceil(e/n)*n),s=Math.max(1,Math.round((i-o)/n));return Array.from({length:s+1},(a,c)=>c===s?i:Nr(o+n*c))},ku=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}})},Uu={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,c=n.maximum;if(a===c)return`CASE WHEN ${t} IS NULL THEN ${s} ELSE ${r.value(jn(a))} END`;const u=Du(a,c,n.targetBuckets),p=u.slice(0,-1).map((m,f)=>{const y=u[f+1],h=f===u.length-2?"]":")";return`[${jn(m)}, ${jn(y)}${h}`}),l=p.slice(0,-1).map((m,f)=>`WHEN ${t} < ${r.value(u[f+1])} THEN ${r.value(m)}`);return`CASE WHEN ${t} IS NULL THEN ${s} ${l.join(" ")} ELSE ${r.value(p.at(-1))} END`}const o=ku(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}}},Mu={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(wt("$concat",t,1,Number.POSITIVE_INFINITY))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},qu={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}}},ju={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}}},xu=new Set(["second","minute","hour","day","week","month","quarter","year"]),Bu={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Di=t=>{if(typeof t!="string"||!xu.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},Vu={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${Bu[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,Di(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=Di(r.granularity);return{...e,name:t,type:"date",primal_type:"date",isArray:!1,granularity:n}}},Yu={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]=wt("$divide",t,2);return`(${e} / NULLIF(${r}, 0))`},getOutputProperty({name:t}){return _r(t)}},Fu=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}}}},vu={name:"$max",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Maximum ${t}`:`${t}\u6700\u5927\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Fu,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}:{}}}},Qu=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}}}},Hu={name:"$min",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Minimum ${t}`:`${t}\u6700\u5C0F\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Qu,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}:{}}}},Gu={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`(${wt("$multiply",t,2,Number.POSITIVE_INFINITY).join(" * ")})`},getOutputProperty({name:t}){return _r(t)}},zu=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},xn=t=>{const e=oe(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=xn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:xn(r))),e},Wu={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 m=Ln(l);return m?ue(r,m,n).property.type==="timestamp":!1}))throw new d("NEWLY_TIME_GROUPBY_UNSUPPORTED","$newly does not support grouping by the timestamp property");const s=Pi(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=xn(e.pred),c=(l,m)=>{const f=zu(t);return f.query=Li(s.queryWithoutTime,s.propertyName,{$lte:l}),f.preds=[{...a,name:m}],f},u=i("component.end",`${o}\u7ED3\u675F`,{outputName:o}),p=i("component.start",`${o}\u5F00\u59CB`,{outputName:o});return{components:[{name:u,logicform:c(s.end,"__newly_end__")},{name:p,logicform:c(s.start,"__newly_start__")}],expression:`${u} - COALESCE(${p}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$newly requires a nested metric");return{...e,name:t,isArray:!1}}},Ku=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Bn=t=>{const e=oe(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},Ju={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=Pi(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 c={version:t.version,schema:n.id,query:{[s.propertyName]:{$lte:a}},preds:[{operator:"$max",pred:s.propertyName,name:"__period_boundary_date__"}]},u=Ku(t);return u.query=Li(s.queryWithoutTime,s.propertyName,c),u.preds=[{...Bn(e.pred),name:r}],{kind:"query",logicform:u}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodValue requires a nested metric");return{...e,name:t,isArray:!1}}},Xu=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Zu=({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=oe(e.pred);a.name="__period_diff_current__";const c=Xu(t);c.preds=[a];const u=ct([t.query,...nt(e)]);u&&(c.query=u);const p={pred:oe(e.pred),...e.args?{args:e.args}:{}},l=Mn({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 m=o("component.current",`${r}\u672C\u671F`,{outputName:r}),f=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:m,logicform:c},{name:f,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${m} - ${f}`}},ed={name:"$periodDifference",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=Cn(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:Zu,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodDifference requires a nested metric");return{...e,name:t,isArray:!1}}},td=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},rd=({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=oe(e.pred);a.name="__period_growth_current__";const c=td(t);c.preds=[a];const u=ct([t.query,...nt(e)]);u&&(c.query=u);const p={pred:oe(e.pred),...e.args?{args:e.args}:{}},l=Mn({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 m=o("component.current",`${r}\u672C\u671F`,{outputName:r}),f=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:m,logicform:c},{name:f,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${m} / NULLIF(ABS(${f}), 0) - 1`}},nd={name:"$periodGrowth",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=Cn(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:rd,getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},od={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}}},id={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]=wt("$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}:_r(t)}},ki=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Vn=t=>{const e=oe(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Vn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Vn(r))),e},sd={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||Pn(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),c=Vn(e.pred),u=ki(t);u.preds=[{...c,name:"__share_numerator__"}];const p=ct([t.query,...nt(e)]);p&&(u.query=p);const l=ki(t);l.groupby=a,l.preds=[{...c,name:"__share_denominator__"}];const m=n("component.numerator",`${r}\u5206\u5B50`,{outputName:r}),f=n("component.denominator",`${r}\u5206\u6BCD`,{outputName:r});return{components:[{name:m,logicform:u},{name:f,logicform:l}],expression:`${m} / NULLIF(${f}, 0)`}},getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},ad={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}}},Ui=(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 c=t[a];if(!c)continue;if(s){o+=c,c===s&&(t[a+1]===s?(o+=s,a+=1):s=void 0);continue}if(c==="'"||c==='"'||c==="`"){s=c,o+=c;continue}const u=t.slice(a,a+2);if(c===";"||u==="--"||u==="/*")throw new d("INVALID_SQL_EXPRESSION",`${n} accepts one expression and does not allow statements or SQL comments`);if(c==="?"){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+=c}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},cd=new Set(["boolean","date","number","entity","object","string"]),ud=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},dd=(t,e)=>{const r=e.type,n=e.primal_type;if(typeof r!="string"||r.length===0||!cd.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}:{}}},ld={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 Ui(t.sql,ud(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 dd(t,e)}},pd=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]},fd=t=>typeof t.pred!="string"?t:{...t,pred:{operator:"$sum",pred:t.pred,name:`${t.pred}\u5408\u8BA1`}},md=(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=pd(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=oe(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,fd(l)}),delete a.sort,delete a.limit,delete a.limitBy,delete a.page,delete a.output,delete a.representation;const c=n.map(({name:p})=>p).filter(p=>!!p),u=oe(t);return u.from=a,u.query=r,u.preds=[{pred:s,name:s},...c.map(p=>({pred:p,name:p}))],delete u.groupby,delete u.having,delete u.entity_id,delete u.propertyResolve,u},yd={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?md(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}}},hd={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}}},gd=new Set(["string","number","boolean","date","entity","object"]),Yn=t=>{if(t==="timestamp"||t==="date")return{type:t,primal_type:"date"};if(typeof t=="string"&&gd.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")},Ad={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 Yn(t.args?.type),t},toSQL({args:t,sql:e}){return Yn(t.type),e.value(t.value,t.type)},getOutputProperty({name:t,args:e}){return{name:t,...Yn(e.type),isArray:!1}}},wd={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}}},Mi="__scalarExtremumInputs",Fn=t=>{if(t.schema)return t.schema;if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred))return Fn(t.pred);if(Array.isArray(t.pred)){const e=[...new Set(t.pred.flatMap(r=>typeof r=="string"?[]:Fn(r)??[]))];if(e.length===1)return e[0]}},$d=t=>{const e=oe(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},Ed=(t,e)=>{if(e.args?.[Mi]===!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}:oe(o),a=s.name??`__scalar_extremum_input_${i}__`,c=s.schema??Fn(s);return{...s,name:a,...c?{schema:c}:{}}}),n=$d(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,[Mi]:!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}:{}}},_d=(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)`},Sd=(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}},qi=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?Ed(e,r):void 0},toSQL(e){const r=wt(t,e,2,Number.POSITIVE_INFINITY);return e.sql.scalarExtremum?.(t==="$least"?"least":"greatest",r)??_d(t,r)},getOutputProperty({name:e,inputProperties:r}){return Sd(t,e,r)}}),Id=qi("$least"),bd=qi("$greatest"),vn={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"}},Rd={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}}},Nd=t=>({name:`$${t}`,defaultName:({operandName:e,locale:r})=>r.toLowerCase().startsWith("en")?`${e} ${vn[t].en}`:`${e}${vn[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}}}),Od=Object.freeze(Object.keys(vn).map(Nd)),ji=Object.freeze([_c,od,qu,ju,Pu,Hu,vu,Su,nd,ed,Tu,Ju,Wu,Ic,id,Gu,Yu,Sc,sd,Uu,Mu,ad,Vu,ld,yd,hd,Ad,wd,Id,bd,Rd,...Od]),Td={name:"boolean",primalType:"boolean",hydrateResult(t){return typeof t=="number"?t===1:t}},Pd={name:"category",primalType:"string"},Ld={name:"currency",primalType:"number"},Cd={name:"date",primalType:"date"},Dd={name:"duration",primalType:"number"},xi=(t,{property:e,requestEntity:r})=>!e.ref||t===void 0||t===null||typeof t=="object"&&!Array.isArray(t)?t:r(e.ref,t),kd={name:"object",primalType:"object",hydrateResult:xi},Ud={name:"entity",primalType:"entity",hydrateResult:xi},Md={name:"file",primalType:"string"},qd={name:"humanName",primalType:"string"},jd={name:"ID",primalType:"string"},xd={name:"image",primalType:"string"},Bd={name:"int",primalType:"number"},Vd={name:"name",primalType:"string"},Yd={name:"number",primalType:"number"},Fd={name:"order",primalType:"number"},vd={name:"percentage",primalType:"number"},Qd={name:"string",primalType:"string"},Hd={name:"tag",primalType:"string",isArray:!0,normalizeResult:(t,{property:e})=>!e.isArray||t==null||Array.isArray(t)?t:[t]},Gd={name:"timestamp",primalType:"date"},Qn=Object.freeze([jd,Qd,Vd,qd,Pd,Hd,xd,Md,Yd,Bd,Ld,vd,Dd,Fd,Td,Gd,Cd,Ud,kd]),zd=(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},Bi=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 c=zd(e[a],a,n);c&&(s[a]=c)}if(!s.getOutputProperty&&typeof o=="string"){const a=Qn.find(({name:c})=>c===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 xt{executionContext;#e=new Map;constructor(e=[],r=Object.freeze({})){this.executionContext=r;for(const n of e)this.register(n)}withExecutionContext(e){return new xt(this.definitions(),e)}register(e){const r=Bi(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,executionContext:this.executionContext})??!1}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}}const Wd=Object.freeze([...ji,...Ii.flatMap(({operators:t})=>t??[])]),Ve=(t=[])=>new xt([...ji,...Ae(t).flatMap(({operators:e})=>e??[])]),It=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="logicform-subquery"&&typeof t.plan=="object"&&t.plan!==null,Vi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="query-operator"&&typeof t.operator=="string",Kd=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="ordinal-query",Yi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="expression-query",Jd=(t,e)=>{const r=Rc(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}:Jd(e,r)},zt=(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 c=[t.input,...t.partitionBy].map(u=>zt(u,e,r,n));return{sources:c.flatMap(({sources:u})=>u),transformations:[...c.flatMap(({transformations:u})=>u).filter(u=>u!=="projection"),`window:${t.function}`]}}if(t.kind==="cumulative"){const c=[t.input,...t.partitionBy,...t.orderBy.map(({expression:u})=>u)].map(u=>zt(u,e,r,n));return{sources:c.flatMap(({sources:u})=>u),transformations:[...c.flatMap(({transformations:u})=>u).filter(u=>u!=="projection"),`window:cumulative:${t.function}`]}}if(t.kind==="ordinal-encode"||t.kind==="ordinal-decode"){const c=zt(t.input,e,r,n);return{sources:c.sources,transformations:[...c.transformations.filter(u=>u!=="projection"),`ordinal:${t.kind==="ordinal-encode"?"encode":"decode"}`]}}const o=[...t.input?[t.input]:[],...t.inputs??[]].map(c=>zt(c,e,r,n)),i={sources:o.flatMap(({sources:c})=>c),transformations:o.flatMap(({transformations:c})=>c)},s=n.get(t.operator),a=new Set([...t.property?[t.property]:[],...s.dependencies??[],...Or(t.query)]);return{sources:[...i.sources,...[...a].filter(c=>!i.sources.some(u=>u.propertyName===c)).map(c=>Fi(e,r,c))],transformations:[...i.transformations.filter(c=>c!=="projection"),`operator:${t.operator}`]}};function Or(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(...Or(o));else r==="$expr"&&Yi(n)?e.push(...n.properties):r.startsWith("$")||e.push(r);return e}const We=t=>t.kind==="window"?[...We(t.input),...t.partitionBy.flatMap(We)]:t.kind==="cumulative"?[...We(t.input),...t.partitionBy.flatMap(We),...t.orderBy.flatMap(({expression:e})=>We(e))]:t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?We(t.input):t.kind==="operator"?[...Or(t.query),...t.input?We(t.input):[],...(t.inputs??[]).flatMap(We)]:[],vi=(t,e,r,n=Ve(),o)=>{if(t.subplans){const s=t.subplans.map(c=>vi(c,e,r,n,o)),a=new Map;for(const c of s){c.source.connectionId&&a.set(c.source.connectionId,c.source.provider);for(const u of c.source.connections??[])a.set(u.connectionId,u.provider)}return{source:{schemaId:e.id,schemaName:e.name,physicalTable:s.map(({source:c})=>c.physicalTable).join(", "),provider:r.kind,connections:[...a].map(([c,u])=>({connectionId:c,provider:u}))},outputs:t.projections.map(({name:c})=>{const u=s.flatMap(({outputs:p})=>p.filter(l=>l.name===c));return{name:c,sources:u.flatMap(({sources:p})=>p),transformations:[...new Set([...u.flatMap(({transformations:p})=>p),"compose"])]}}),filters:s.flatMap(({filters:c})=>c)}}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,...zt(s.expression,t,e,n)})),filters:[...new Set([...Or(t.query),...t.projections.flatMap(({expression:s})=>We(s))])].map(s=>Fi(t,e,s))}},Ce=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.version=="string"&&(typeof t.schema=="string"||typeof t.from=="object"),Xd=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,Qi=t=>{const e=Xd.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 d("INVALID_SOURCE_FRESHNESS","TTL freshness requires a positive integer ttlSeconds");return}if(e.mode==="daily"){if(!Qi(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}`)}}}},Zd=new Set(["second","minute","hour","day","week","month","quarter","year"]),Hn=t=>typeof t=="string"&&Zd.has(t),Gn=(t,e=Ae())=>Hn(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 Tr{#e=new Map;plugins;constructor(e=[],r=[]){this.plugins=Ae(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:c})=>!a||!c))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");Hi(s),r.add(s.id),n.add(s.source)}for(const s of e.mappings??[]){if(s.granularity!==void 0&&(s.mappingType!=="property"||!Gn(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")}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 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}definitions(){return[...this.#e.values()].flat()}findSource(e,r,n){return this.#e.get(e)?.find(o=>o.source===r&&(n===void 0||o.connectionId===n))}}const el=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`)},tl=(t,e=[])=>{const r=Ae(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"||!Gn(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:el(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 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 zi=(t=[])=>new Gi([...Ae(t).flatMap(e=>e.plannerSemantics??[])]);ce.extend(Qo),ce.extend(Vt),ce.extend(yr);const bt=["second","minute","hour","day","week","month","quarter","year"],rl=new Set(["$second","$minute","$hour","$day","$week","$month","$quarter","$year"]),nl="YYYY-MM-DD HH:mm:ss",Rt=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),ol=(t,e)=>t==="week"?e==="week":e==="week"?bt.indexOf(t)<=bt.indexOf("day"):bt.indexOf(t)<=bt.indexOf(e),Wi=(t,e,r)=>{if(typeof t!="string")return"second";const n=ce(t,nl,!0);if(!n.isValid())return"second";for(const o of[...bt].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"},Ki=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])=>rl.has(r)?[r.slice(1)]:r==="$weekday"?["day"]:r==="$and"||r==="$or"?Array.isArray(n)?n.flatMap(Ki):["second"]:r==="$gte"||r==="$gt"?[Wi(n,"lower",r==="$gte")]:r==="$lte"||r==="$lt"?[Wi(n,"upper",r==="$lte")]:["second"])},il=(t,e,r)=>{if(e.primal_type==="date"){if(t.operator){const n=r.get(t.operator).groupedSourceTimeGranularity?.({pred:t,property:e});if(n&&bt.includes(n))return n}return e.granularity??"day"}},sl=(t,e,r,n,o=Ae(),i=Ve(o))=>{const s=r.mappings??[],a=s.filter(g=>g.granularity!==void 0),c={schema:e,mapping:r,...n?{resolveSchema:n}:{}};if(a.some(g=>!Gn(g.granularity,o)))return"physical granularity is not supported by the active plugins";if(a.find(g=>Hn(g.granularity)&&!g.propertyTarget?.every($=>Rt(e,$)?.primal_type==="date")))return"physical time granularity requires mapped date Properties";for(const g of a)for(const $ of o){const A=$.mappingGranularity;if(!A||!A.isGranularity(g.granularity))continue;const _=A.validateItem?.(g,c);if(_)return _}if(!(a.length>0))return;const l=g=>s.find($=>$.mappingType==="property"&&$.propertyTarget?.some(A=>Rt(e,A)?.id===g.id)),m=(g,$,A="filterOrGroup")=>{const _=Rt(e,g);if(!_)return`property is not available: ${g}`;const E=l(_);if(!E&&!(A==="operand"&&s.some(w=>w.mappingType==="predItem"&&typeof w.predItem?.pred=="string"&&Rt(e,w.predItem.pred)?.id===_.id)))return`property is not available on grouped source: ${g}`;if(A==="filterOrGroup"&&_.primal_type==="number"&&_.type!=="category"&&_.type!=="ID")return`measure cannot be used as a grouped source dimension: ${g}`;if(_.primal_type==="date"&&(!E?.granularity||!Hn(E.granularity)||!ol(E.granularity,$??_.granularity??"day")))return`time dimension ${g} is too coarse for ${$}`};function f(g){if(g)for(const[$,A]of Object.entries(g)){if(A===void 0)continue;if($==="$and"||$==="$or"){if(!Array.isArray(A))return"unsupported dimension query";for(const w of A){const R=f(w);if(R)return R}continue}if($==="$expr"){if(typeof A!="object"||A===null||Array.isArray(A))return"unsupported expression query";const w=A.pred;if(typeof w!="object"||w===null||Array.isArray(w))return"unsupported expression query";const R=y(w);if(R)return R;continue}if($.startsWith("$"))return"unsupported dimension query";const _=Rt(e,$);if(!_)return`dimension property is not available: ${$}`;const E=_.primal_type==="date"?Ki(A):[void 0];for(const w of E){const R=m($,w);if(R)return R}}}function y(g){const $=f(g.query);if($)return $;const A=Array.isArray(g.pred)?g.pred:g.pred===void 0?[]:[g.pred];for(const _ of A){const E=typeof _=="string"?m(_,void 0,"operand"):y(_);if(E)return E}}const h=f(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 $=Rt(e,g.pred);if(!$)return`groupby property is not available: ${g.pred}`;if(g.operator!==void 0&&!i.get(g.operator).supportsGroupedSourceGroupby&&!o.some(_=>_.mappingGranularity?.supportsGroupby?.(g)))return`computed groupby is not covered: ${g.pred}`;const A=m(g.pred,il(g,$,i));if(A)return A}for(const g of o){const $=g.mappingGranularity?.candidateReason?.(t,c);if($)return $}};function Wt(t){return[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Wt(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Wt(e)):[]]}const zn=t=>t.id??t.source,Pr=(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)=>Pr(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)&&Pr(i,n[o]))},Nt=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=Nt(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=Wt(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},Wn=(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=>Wn(a,e,r)).filter(a=>a!==void 0);s.length>0&&(n[o]=s);continue}o!=="$or"&&e.some(s=>Lr(r,s.property,o)&&Pr(s.condition,i))||(n[o]=i)}return Object.keys(n).length>0?n:void 0},ut=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),Lr=(t,e,r)=>e===r||ut(t,e)?.id===ut(t,r)?.id&&ut(t,e)!==void 0&&ut(t,r)!==void 0,De=(t,e,r)=>Cr(t,e,r)?.column,Cr=(t,e,r)=>{const n=ut(e,r);if(!n)return;const o=(t.mappings??[]).find(i=>i.mappingType==="property"&&i.propertyTarget?.some(s=>Lr(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}},Kn=(t,e,r)=>!(t.mappings??[]).some(n=>n.mappingType==="property")||De(t,e,r)!==void 0,Ji=(t,e,r)=>{if(!t||!(e.mappings??[]).some(i=>i.mappingType==="property"))return;const n=Nt(t);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:i})=>!Kn(e,r,i));return o?`query property is not available: ${o.property}`:void 0},al=(t,e,r,n,o)=>{if(t.match.schema!==void 0&&t.match.schema!==n)return!1;const i=typeof e.pred=="string"?ut(r,e.pred):void 0,s=ut(r,t.match.pred),a=typeof e.pred=="string"&&Lr(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 c=Nt(t.match.query);return c!==void 0&&c.every(u=>o.some(p=>Lr(r,p.property,u.property)&&Pr(p.condition,u.condition)))},cl=(t,e,r,n,o,i=Ve(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,A=$.operator,_=$.pred;return!A||typeof _!="string"?[]:[{match:{operator:A,pred:_,...$.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 A=$.schemaMapping?.candidateReason?.(t,g);if(A)return A}return{mapping:r,logicform:t,predRewrites:[],priority:r.priority??0,specificity:0}}const c=Nt(t.query);if(!c&&s.length>0)return"query contains $or or another unsupported logical expression";const u=oe(t),p=[],l=[];for(const[g,$]of(t.preds??[]).entries()){const A=Nt($.query);if(!A&&s.length>0)return`PredItem ${g} query contains an unsupported logical expression`;if(s.length>0){const E=[...c??[],...A??[]],w=s.filter(T=>al(T,$,e,$.schema??e.id,E));if(w.length===0)return`PredItem ${g} is not mapped`;if(w.length>1)return`PredItem ${g} matches multiple mapping rules`;const R=w[0],C=Nt(R.match.query)??[];l.push(...C);const k=u.preds?.[g];if(k){const T=Wn(k.query,C,e);T?k.query=T:delete k.query}p.push({predIndex:g,column:R.column});continue}const _=Wt($).find(E=>!Kn(r,e,E));if(_)return`PredItem ${g} property is not available: ${_}`}const m=Wn(u.query,l,e);m?u.query=m:delete u.query;const f=Ji(u.query,r,e);if(f)return f;for(const[g,$]of(u.preds??[]).entries()){const A=Ji($.query,r,e);if(A)return`PredItem ${g} ${A}`}for(const g of u.groupby??[]){const A=Wt(g).find(_=>!Kn(r,e,_));if(A)return`groupby property is not available: ${A}`}const y=sl(u,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?.(u,h);if($)return $}return{mapping:r,logicform:u,predRewrites:p,priority:r.priority??0,specificity:p.length}},ul=(t,e,r,n={})=>{const o=n.plugins?Ae(n.plugins):r.plugins,i=n.operators??Ve(n.plugins),s=[],a=[];for(const l of r.list(e.id)){const m=cl(t,e,l,n.resolveSchema,o,i);typeof m=="string"?a.push({mappingId:zn(l),reason:m}):s.push(m)}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 c=n.preferredConnectionId===void 0?[]:s.filter(({mapping:l})=>l.connectionId===n.preferredConnectionId),p=(c.length>0?c:s).reduce((l,m)=>m.priority>l.priority||m.priority===l.priority&&m.specificity>l.specificity?m:l);for(const l of s){if(l===p)continue;let m;c.length>0&&l.mapping.connectionId!==n.preferredConnectionId?m=`connection ${l.mapping.connectionId} does not match preferred connection ${n.preferredConnectionId}`:l.priority<p.priority?m=`priority ${l.priority} is lower than selected priority ${p.priority}`:l.specificity<p.specificity?m=`specificity ${l.specificity} is lower than selected specificity ${p.specificity}`:m="priority and specificity tie; an earlier registered mapping was selected",a.push({mappingId:zn(l.mapping),reason:m})}return{mapping:p.mapping,logicform:p.logicform,predRewrites:p.predRewrites,selection:{schemaId:e.id,selectedMappingId:zn(p.mapping),rejectedMappings:a}}},Kt=(t,e)=>!!(t.operator&&e.get(t.operator).kind==="component"),Jt=(t,e)=>Kt(t,e)?!0:t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Jt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Jt(r,e)),Xi=(t,e)=>t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Jt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Jt(r,e)),Zi=t=>t.name??(typeof t.pred=="string"?t.pred:void 0),dl=(t,e)=>{const r=t.preds??[];if(!r.some(f=>!Kt(f,e)&&Xi(f,e)))return;const n=new Set([...r.map(({name:f})=>f).filter(f=>!!f),...(t.groupby??[]).map(Zi).filter(f=>!!f)]);let o=0;const i=()=>{let f;do f=`__nested_component_input_${o}__`,o+=1;while(n.has(f));return n.add(f),f},s=[],a=f=>{const y=i();return s.push(typeof f=="string"?{pred:f,name:y}:{...oe(f),name:y}),y},c=f=>{if(f.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=oe(f);return Array.isArray(f.pred)?y.pred=f.pred.map(h=>typeof h=="string"||!Jt(h,e)||Kt(h,e)?a(h):c(h)):f.pred&&typeof f.pred=="object"&&(y.pred=Kt(f.pred,e)?a(f.pred):c(f.pred)),y},u=r.map(f=>{const y=f.name;if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every projection to have a name");return!Kt(f,e)&&Xi(f,e)?{...c(f),name:y}:(s.push({...oe(f),name:y}),{pred:y,name:y})}),p=oe(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(f=>{const y=Zi(f);if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every groupby projection to have a name");return{pred:y,name:y}}),m=oe(t);return m.from=p,m.preds=[...l,...u],delete m.query,delete m.groupby,delete m.entity_id,delete m.propertyResolve,m},ll=(t,e)=>`result:${t}:${e.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,es=(t,e)=>{const r=(t.columnProperties??[]).map(n=>({...n,id:n.name}));return{id:ll(t.schemaId,t.columnProperties??[]),name:`${e.name} result`,type:e.type,temporalSemantics:"normal",properties:r}},ts=(t,e)=>({...es(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},Dr=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Dr(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Dr(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))}:{}}),rs=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(o=>rs(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]})),Zn=(t,e,r)=>{const n=new Set(r),o=(i,s)=>{if(!(Ce(i)||i===null)){if(Array.isArray(i)){i.forEach(a=>o(a,s));return}if(typeof i=="object"){Object.entries(i).forEach(([a,c])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(a)||o(c,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)},ns=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(i=>ns(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&&Zn(n,r,o.values),[r,o?{kind:"ordinal-query",comparable:o,condition:n}:n]})),pl=(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}:{}}},os=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},is=(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}),Ot=(t,e,r,n,o,i,s,a,c="projection")=>{const u=Jn(t);if(c==="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:os(E.field),outputProperty:is(E.reference,E.property),sourceProperty:E.property,sourceField:E.field}}const p=e.get(t.operator);if(c==="groupby"&&p.kind!=="scalar")throw new d("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(c==="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({executionContext:e.executionContext,reference:t.pred,args:t.args??{},schema:s,...a?{resolveSchema:a}:{}}):void 0,m=l?.reference??t.pred,f=l?.args??t.args??{},y=m&&typeof m=="object"&&!Array.isArray(m)?Ot(m,e,r,n,o,i,s,a,c):typeof m=="string"?Ot({pred:m,name:m},e,r,n,o,i,s,a,c):void 0,h=Array.isArray(m)?m.map(E=>Ot(typeof E=="string"?{pred:E,name:E}:E,e,r,n,o,i,s,a,c)):[];if(p.requiresProperty!==!1&&!y&&h.length===0)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a property`);const g=u,$=p.getOutputProperty?.({executionContext:e.executionContext,name:g,...y?.sourceProperty?{property:y.sourceProperty}:{},...y?{inputProperty:{...y.outputProperty,name:g}}:{},...h.length>0?{inputProperties:h.map(({outputProperty:E})=>E)}:{},args:f}),A=$?.description??p.description??y?.outputProperty.description,_={...$??(y?is(g,y.outputProperty,{isArray:!1}):{name:g,type:"number",primal_type:"number",isArray:!1}),...A!==void 0?{description:A}:{}};if(p.planExpression){const E=p.planExpression({executionContext:e.executionContext,pred:t,...y?{input:y.expression,inputProperty:y.outputProperty}:{},inputs:h.map(({expression:w})=>w),args:f,resolveKey:o,getOperator:w=>e.get(w),planQuery:i});if(E)return{expression:E,outputProperty:_,...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 w=t.args?.partitionBy??[];if(!Array.isArray(w)||w.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:w.map(R=>n(String(R))),direction:E==="asc"?"ASC":"DESC"},outputProperty:_}}return{expression:{kind:"operator",operator:t.operator,args:f,...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:_,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}},fl=(t,e,r,n,o,i,s,a,c,u,p,l=t)=>{const m=Jn(t),f=typeof t.pred=="string"?t.pred:void 0,y=!u||!f?r:A=>{const _=r(A);return A===f?{..._,field:{..._.field,column:u}}:_},h=p?{...t,operator:p}:t,g=Ot(h,e,y,n,o,i,s,a),$=c?.resolveProjection({pred:l,schema:s,executionContext:e.executionContext,...g.sourceProperty?{sourceProperty:g.sourceProperty}:{},outputProperty:{...g.outputProperty,name:m},...l.operator?{operator:e.get(l.operator)}:{}})??{...g.outputProperty,name:m};return{name:m,expression:g.expression,outputProperty:$}},ml=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)}},eo=(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},yl=(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=>je(h,eo(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(($,A)=>$!==a[A]))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 c=[],u=[],p=new Map;s.forEach((h,g)=>{h.projections.forEach(($,A)=>{const _=a.includes($.name),E=p.get($.name);if(E!==void 0&&!_)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),c.push({name:$.name,expression:{kind:"column",property:$.name,column:$.name}});const w=h.columnProperties?.[A];w&&u.push(w)})});const l=new Set(c.map(({name:h})=>h)),m=Object.entries(t.sort??{}).map(([h,g])=>{if(!l.has(h))throw new d("INVALID_SORT",`Sort field is not an output: ${h}`);const $=u.find(A=>A.name===h);return{name:h,direction:g===1?"ASC":"DESC",...$?.comparable?{comparable:$.comparable}:{},...$?.comparable?{expression:{kind:"column",property:h,column:h}}:{}}}),f=t.limitBy===void 0||a.length<2?void 0:{count:t.limitBy,partitionBy:a.slice(0,-1),orderBy:m.length>0?m:(()=>{const h=a.at(-1)??"",g=u.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(c.map(({name:h})=>[h,h])),projections:c,columnProperties:u,groupBy:c.filter(({name:h})=>a.includes(h)),...t.having?{having:ns(t.having,u)}:{},orderBy:m,rowIdentity:a.length>0?{kind:"group",names:a,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"},...f?{groupLimit:f}:{},...y?{pagination:y}:{}}},je=(t,e,r=Ve(),n=new Tr,o={})=>{const i=[...new Set((t.preds??[]).map(S=>S.schema).filter(S=>!!(S&&S!==e.id)))];if(i.length>0){const S=t.propertyResolve??{},I=[e.id,...i].map(b=>{const{having:L,sort:j,limit:te,limitBy:N,page:D,...P}=t,M=K=>{let x=K;try{x=ue(e,K,o.resolveSchema).canonicalName}catch{}return S[b]?.[K]??S[b]?.[x]??K};return{...P,schema:b,preds:(t.preds??[]).filter(K=>(K.schema??e.id)===b).map(({schema:K,...x})=>x),...b===e.id||!t.query?{}:{query:rs(t.query,M)},...b!==e.id&&t.groupby?{groupby:t.groupby.map(K=>({...K,...typeof K.pred=="string"?{pred:M(K.pred)}:{}}))}:{}}});return yl(t,I,e,r,n,o)}const s=dl(t,r);if(s)return je(s,e,r,n,o);for(const S of t.preds??[]){if(!S.operator)continue;const I=r.get(S.operator).rewriteLogicform?.({executionContext:r.executionContext,logicform:t,schema:e,getOperator:b=>r.get(b)});if(I)return je(I,e,r,n,o)}const a=o.semanticRegistry??zi(o.plugins);if(t.from){const S=eo(t.from,e,o),I=je(t.from,S,r,n,o),b=ts(I,e),L={...t};delete L.from,L.schema??=b.id;const j=je(L,b,r,n,o),te=new Set(j.projections.map(({name:x})=>x)),N=I.rowIdentity.kind==="group"&&I.rowIdentity.names.every(x=>te.has(x))||I.rowIdentity.kind==="singleton"?I.rowIdentity:{kind:"generated"},D=I.groupBy.map(({name:x})=>x).filter(x=>te.has(x)),P=D.at(-1),M=I.columnProperties?.find(x=>x.name===P),K=t.limitBy!==void 0&&D.length>0?{count:t.limitBy,partitionBy:D.slice(0,-1),orderBy:j.orderBy.length>0?j.orderBy:D.slice(-1).map(x=>({name:x,direction:"ASC",...M?.comparable?{comparable:M.comparable}:{}}))}:void 0;return{...j,source:I.source,sourcePlan:I,sourceLogicform:t.from,rowIdentity:N,...K?{groupLimit:K}:{}}}if(!t.schema)throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const c=ul(t,e,n,{operators:r,...o.plugins?{plugins:o.plugins}:{},...o.preferredConnectionId?{preferredConnectionId:o.preferredConnectionId}:{},...o.resolveSchema?{resolveSchema:o.resolveSchema}:{}});o.onSchemaMappingSelection?.(c.selection),t=c.logicform;const u=new Map(c.predRewrites.map(({predIndex:S,column:I})=>[S,I])),p=bi(e,o.plugins),l=lu(t,e,o.plugins),m=a.resolveQuery({logicform:t,schema:e,...t.query?{query:t.query}:{}}),f=l?.rewriteQuery?l.rewriteQuery(m):m,y=e.id,h=new Map,g=new Map,$=new Map,A=new Map,_=S=>{const I=g.get(S);if(I)return I.alias;const b=c.mapping.enrichments?.find(te=>te.id===S);if(!b)throw new d("SCHEMA_MAPPING_ENRICHMENT_NOT_FOUND",`Schema mapping enrichment is not registered: ${S}`,{schemaId:e.id,mappingId:c.mapping.id,enrichmentId:S});const L=`__enrichment_${S}`,j=b.temporal?(()=>{if(!p)throw new d("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${S} requires an entity with interval semantics`,{schemaId:e.id,enrichmentId:S});const te=Cr(c.mapping,e,p.start.name),N=Cr(c.mapping,e,p.end.name);if(!te||!N)throw new d("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${S} requires mapped interval boundary columns`,{schemaId:e.id,enrichmentId:S});if(te.sourceRef||N.sourceRef)throw new d("POINT_ENRICHMENT_INTERVAL_MUST_USE_BASE_SOURCE",`Point enrichment ${S} requires interval boundaries on the base source`,{schemaId:e.id,enrichmentId:S});return{kind:"point-in-interval",pointSide:"target",pointColumn:b.temporal.pointColumn,intervalSide:"source",startColumn:te.column,endColumn:N.column}})():void 0;return g.set(S,{kind:"enrichment-left",id:S,source:b.source,...b.sourceSql?{sourceSql:b.sourceSql}:{},alias:L,baseAlias:y,keys:b.on,...j?{temporalCondition:j}:{}}),L},E=S=>{const I=ue(e,S,o.resolveSchema);let b=y,L=c.mapping;const j=[];for(const P of I.relations){j.push(P.property.name);const M=j.join("_"),K=M,x=n.get(P.targetSchema.id,c.mapping.connectionId);if(L=x,!h.has(M)){const le=P.targetSchema.properties.filter(({type:Ne})=>Ne==="ID"),[ee]=le;if(le.length!==1||!ee)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${P.targetSchema.id} must contain exactly one ID property`,{schemaId:P.targetSchema.id,count:le.length});const pe=P.sourceSchema.id===e.id?c.mapping:n.get(P.sourceSchema.id,c.mapping.connectionId),re=De(pe,P.sourceSchema,P.property.name)??P.property.id,Se=De(x,P.targetSchema,ee.name)??ee.id,Ie=P.sourceSchema.properties.find(({type:Ne})=>Ne==="timestamp"),ge=P.targetSchema.properties.find(({type:Ne})=>Ne==="timestamp"),ne=du(P.sourceSchema,P.targetSchema,o.plugins),ye=Ie?De(pe,P.sourceSchema,Ie.name)??Ie.id:void 0,Te=ge?De(x,P.targetSchema,ge.name)??ge.id:void 0,Pe=ne?.kind==="date-bucket-equal"?{kind:"date-bucket-equal",sourceColumn:De(pe,P.sourceSchema,ne.sourceTimestamp.name)??ne.sourceTimestamp.id,targetColumn:De(x,P.targetSchema,ne.targetTimestamp.name)??ne.targetTimestamp.id,sourceGranularity:ne.sourceTimestamp.granularity??"day",targetGranularity:ne.targetTimestamp.granularity??"day"}:ne?.kind==="point-in-interval"?{kind:"point-in-interval",pointSide:"source",pointColumn:De(pe,P.sourceSchema,ne.point.name)??ne.point.id,intervalSide:"target",startColumn:De(x,P.targetSchema,ne.start.name)??ne.start.id,endColumn:De(x,P.targetSchema,ne.end.name)??ne.end.id}:void 0,$e=P.property.isArray?M:void 0;$e&&!$.has($e)&&$.set($e,{path:$e,sourceAlias:b,sourceColumn:re,...P.property.udf?{sourceSql:P.property.udf.sql,...ye?{sourceTimestampColumn:ye}:{}}:{},alias:`__array_${M}`}),h.set(M,{kind:"left",path:M,sourceAlias:b,sourceColumn:re,...P.property.udf?{sourceSql:P.property.udf.sql,...ye?{sourceTimestampColumn:ye}:{}}:{},targetSchemaId:P.targetSchema.id,targetConnectionId:x.connectionId,targetSource:x.source,...x.sourceSql?{targetSourceSql:x.sourceSql}:{},targetAlias:K,targetColumn:Se,...$e?{sourceArrayExpansionPath:$e}:{},...ee.udf?{targetSql:ee.udf.sql,...Te?{targetTimestampColumn:Te}:{}}:{},...Pe?{temporalCondition:Pe}:{}})}b=K}const te=Cr(L,I.schema,I.property.name);if(I.relations.length>0&&te?.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 N=te?.sourceRef?_(te.sourceRef):b,D={schemaId:I.schema.id,property:I.property.name,propertyId:I.property.id,column:te?.column??I.property.id,qualifier:N,...I.property.isArray?{isArray:!0}:{},...I.property.type==="tag"?{normalizeStringArray:!0}:{},...I.property.comparable?{comparable:I.property.comparable}:{},...pl(I.relations.length>0?e:I.schema,I.property,y)};return A.set(I.canonicalName,D),{reference:I.canonicalName,schema:I.schema,property:I.property,field:D}},w=S=>{if(S)for(const[I,b]of Object.entries(S))if((I==="$and"||I==="$or")&&Array.isArray(b))for(const L of b)typeof L=="object"&&L!==null&&!Array.isArray(L)&&w(L);else if(I==="$expr"&&typeof b=="object"&&b!==null&&!Array.isArray(b)){const L=b.pred;typeof L=="object"&&L!==null&&!Array.isArray(L)&&Dr(L).forEach(E)}else I.startsWith("$")||E(I)},R=S=>{if(Ce(S)){const I=eo(S,e,o),b=je(S,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:S.schema,projectionCount:b.projections.length});return{kind:"logicform-subquery",plan:b}}return Array.isArray(S)?S.map(R):typeof S!="object"||S===null||S instanceof Date?S:Object.fromEntries(Object.entries(S).map(([I,b])=>[I,R(b)]))},C=S=>Object.fromEntries(Object.entries(S).map(([I,b])=>{if((I==="$and"||I==="$or")&&Array.isArray(b))return[I,b.map(j=>C(j))];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 j=b;if(typeof j.pred!="object"||j.pred===null||Array.isArray(j.pred)||!Object.prototype.hasOwnProperty.call(j,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const te=j.pred,N=Ot(te,r,E,G,v,C,e,o.resolveSchema,"groupby");if(N.outputProperty.isArray)throw new d("ARRAY_EXPRESSION_QUERY_UNSUPPORTED","$expr must produce a scalar value");const D=R(j.condition);return N.outputProperty.comparable&&Zn(D,te.name??te.operator??"$expr",N.outputProperty.comparable.values),[I,{kind:"expression-query",expression:N.expression,condition:N.outputProperty.comparable?{kind:"ordinal-query",comparable:N.outputProperty.comparable,condition:D}:D,properties:Dr(te)}]}if(typeof b=="object"&&b!==null&&!Array.isArray(b)){const te=Object.entries(b).find(([N])=>_t(N,o.plugins));if(te){const[N,D]=te,P=_t(N,o.plugins);if(!P)throw new Error(`Query Operator disappeared: ${N}`);const M=E(I),K=P.plan(D,{schema:M.schema,property:M.property,connectionId:c.mapping.connectionId,...o.resolveSchema?{resolveSchema:o.resolveSchema}:{},resolveMapping:(x,le)=>n.get(x,le)});return[I,{[N]:{kind:"query-operator",operator:N,value:K.value,definition:P,...K.sources?{sources:K.sources}:{}}}]}}const L=I.startsWith("$")?void 0:E(I).property.comparable;return[I,L?{kind:"ordinal-query",comparable:L,condition:R(b)}:R(b)]})),k=S=>{const I=L=>{if(!L||typeof L!="object")return!1;if(Array.isArray(L))return L.some(I);const j=L;return Object.prototype.hasOwnProperty.call(j,"$and")||Object.values(j).some(I)};if(I(S))return S;const b=new Set(Object.keys(S).flatMap(L=>{if(L.startsWith("$"))return[];const j=ue(e,L,o.resolveSchema);return j.relations.length===1&&j.property.type==="ID"?[j.relations[0]?.property.name]:[]}));return Object.fromEntries(Object.entries(S).map(([L,j])=>{if(L==="$and"||L==="$or")return Array.isArray(j)?[L,j.map(ee=>typeof ee=="object"&&ee!==null&&!Array.isArray(ee)?k(ee):ee)]:[L,j];if(L.startsWith("$"))return[L,j];const te=ue(e,L,o.resolveSchema);if(te.relations.length===0)return[L,j];if(te.property.udf?.sql.includes("$TS")===!0||te.relations.some(({property:ee})=>ee.udf?.sql.includes("$TS")===!0))return[L,j];const D=te.relations.map(({property:ee})=>ee.name).join("_");if(h.has(D))return[L,j];const[P]=te.relations;if(!P)return[L,j];if(b.has(P.property.name))return[L,j];const M=P.property.name,K=te.canonicalName.slice(M.length+1),x=P.targetSchema.properties.find(({type:ee})=>ee==="ID");if(!x)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${P.targetSchema.id} must contain an ID property`,{schemaId:P.targetSchema.id});if(te.relations.length===1&&te.property.id===x.id)return[P.property.id,j];const le={version:t.version,schema:P.targetSchema.id,query:K?{[K]:j}:{},preds:[{pred:x.name,name:x.name}]};return[P.property.id,{$in:le}]}))},T=(t.groupby??[]).map(S=>{const I=Jn(S);S.operator&&r.get(S.operator).validateGroupby?.({pred:S,executionContext:r.executionContext});const b=Ot(S,r,E,G,v,C,e,o.resolveSchema,"groupby");let L=b.expression;if(l?.group===S&&(L={kind:"column",schemaId:e.id,property:l.property.name,propertyId:l.property.id,column:"__period_start",qualifier:"__periods"}),b.sourceProperty?.isArray&&b.sourceField){const j=`groupby:${I}`;$.set(j,{path:j,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}`,...b.sourceProperty.type==="tag"?{normalizeStringArray:!0}:{},...b.sourceProperty.type==="tag"?{elementType:"string"}:{}}),L={kind:"array-element",schemaId:b.sourceField.schemaId,property:b.sourceProperty.name,expansionPath:j}}return{name:I,expression:L,outputProperty:{...b.outputProperty,name:I,isArray:!1}}});function G(S){const I=(t.groupby??[]).findIndex(L=>typeof L.pred=="string"&&L.pred===S||L.name===S),b=I>=0?T[I]:void 0;if(!b)throw new d("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${S}`);return b.expression}function v(S){const I=(t.groupby??[]).findIndex(L=>typeof L.pred=="string"&&L.pred===S||L.name===S),b=I>=0?T[I]:void 0;return b?b.expression:os(E(S).field)}const q=S=>{S.operator&&r.get(S.operator).validatePlan?.({executionContext:r.executionContext,pred:S,groupByNames:T.map(({name:I})=>I),resolveGroupName:I=>{const b=(t.groupby??[]).findIndex(L=>L.name===I||typeof L.pred=="string"&&L.pred===I);return b>=0?T[b]?.name:void 0},getOperator:I=>r.get(I)}),S.pred&&typeof S.pred=="object"&&!Array.isArray(S.pred)&&q(S.pred);for(const I of Array.isArray(S.pred)?S.pred:[])q(typeof I=="string"?{pred:I}:I)};for(const S of t.preds??[])q(S);const U=[...T,...(t.preds??[]).map((S,I)=>{const b=l?.rewritePred?.(S)??S;return fl(b,r,E,G,v,C,e,o.resolveSchema,a,u.get(I),fi(b,t.groupby??[],e,o.resolveSchema)?"$min":void 0,S)})],Y=S=>Object.fromEntries(Object.entries(S).map(([I,b])=>{if((I==="$and"||I==="$or")&&Array.isArray(b))return[I,b.map(j=>Y(j))];if(I==="$expr")throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const L=U.find(({name:j})=>j===I)?.outputProperty.comparable;return L&&Zn(b,I,L.values),[I,L?{kind:"ordinal-query",comparable:L,condition:R(b)}:R(b)]})),z=f?k(f):void 0;w(z);const Q=S=>{w(S.query),S.pred&&typeof S.pred=="object"&&!Array.isArray(S.pred)&&Q(S.pred);for(const I of Array.isArray(S.pred)?S.pred:[])Q(typeof I=="string"?{pred:I}:I)};for(const S of t.preds??[])Q(S);if(U.length===0)throw new d("EMPTY_PROJECTION","LogicForm must contain preds or groupby");ml(U);const W=new Set(U.map(({name:S})=>S)),ke=T.length>0?{kind:"group",names:T.map(({name:S})=>S),separator:"_",nullLabel:"\u7A7A\u503C"}:U.every(({expression:S})=>S.kind==="column"||S.kind==="property-sql")||U.some(({expression:S})=>S.kind==="property-sql"&&e.properties.some(({id:I,type:b})=>b==="ID"&&I===S.propertyId))?(()=>{const S=e.properties.find(({type:I})=>I==="ID");return S&&(o.canUsePropertyRowIdentity?.(e,S)??!0)?{kind:"property",column:S.id,internalName:"_id"}:{kind:"generated"}})():{kind:"singleton"},qe=Object.entries(t.sort??{}).map(([S,I])=>{if(!W.has(S))throw new d("INVALID_SORT",`Sort field is not an output: ${S}`);const b=U.find(L=>L.name===S);return{name:S,direction:I===1?"ASC":"DESC",...b?.outputProperty.comparable?{comparable:b.outputProperty.comparable,expression:b.expression}:{}}}),de=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},me=t.limitBy===void 0?void 0:{count:t.limitBy,partitionBy:T.slice(0,-1).map(({name:S})=>S),orderBy:qe.length>0?qe:(()=>{const S=T.at(-1);return[{name:S?.name??"",direction:"ASC",...S?.outputProperty.comparable?{comparable:S.outputProperty.comparable,expression:S.expression}:{}}]})()},Re=A.size===0&&h.size===0&&g.size===0&&$.size===0&&!z&&T.length===0&&U.length>0&&U.every(({expression:S})=>S.kind==="operator"&&S.operator==="$constant");return{schemaId:e.id,source:Re?"":c.mapping.source,...Re?{}:{connectionId:c.mapping.connectionId},...!Re&&c.mapping.sourceSql?{sourceSql:c.mapping.sourceSql}:{},mappingId:c.mapping.id??c.mapping.source,sourceAlias:y,fields:{...Nc(e),...Object.fromEntries(e.properties.flatMap(S=>{const I=De(c.mapping,e,S.name);return I?[[S.name,I],[S.id,I]]:[]}))},fieldReferences:Object.fromEntries(A),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:De(c.mapping,e,l.source.start.name)??l.source.start.id,endColumn:De(c.mapping,e,l.source.end.name)??l.source.end.id}:{kind:"latest",lookupAlias:"__period_lookup",timestampColumn:De(c.mapping,e,l.source.timestamp.name)??l.source.timestamp.id}}}:{},projections:U.map(({name:S,expression:I})=>({name:S,expression:I})),columnProperties:U.map(({outputProperty:S})=>S),groupBy:T.map(({name:S,expression:I})=>({name:S,expression:I})),...z?{query:C(z)}:{},...t.having?{having:Y(t.having)}:{},orderBy:qe,rowIdentity:Re?{kind:"singleton"}:ke,...de?{pagination:de}:{},...me?{groupLimit:me}:{}}};class hl{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 gl=(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(".")},kr=(t,e,r)=>r===void 0?gl(t,e):`(${r.trim().replace(/;+\s*$/,"")})`,Xt=(t,e,r,n,o)=>{const i=Ui(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)},ve=(t,e,r,n=!1,o,i,s,a)=>{const c=(u,p)=>n&&p?`${e.quoteIdentifier(p)}.${e.quoteIdentifier(u)}`:e.quoteIdentifier(u);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 c(t.column,t.qualifier);case"property-sql":return Xt(t.sql,t.property,e,t.timestampColumn,n?t.timestampQualifier??t.qualifier:void 0);case"window":{if(Ue(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Window operators cannot consume a JavaScript operator");const u=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(m=>ve(m,e,r,n,o,i,s,a)).join(", ")} `:"",p=ve(t.input,e,r,n,o,i,s,a);return`${t.function==="rank"?"RANK":"ROW_NUMBER"}() OVER (${u}ORDER BY ${p} ${t.direction})`}case"cumulative":{if(Ue(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Cumulative expressions cannot consume a JavaScript operator");const u=ve(t.input,e,r,n,o,i,s,a),p=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(m=>ve(m,e,r,n,o,i,s,a)).join(", ")} `:"",l=t.orderBy.map(m=>`${ve(m.expression,e,r,n,o,i,s,a)} ${m.direction}`).join(", ");return`${e.aggregateFunction(t.function,u)} 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 ${ve(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 ${ve(t.input,e,r,n,o,i,s,a)} = ${t.comparable.direction*l} THEN ${i(p)}`).join(" ")} END`}case"operator":{const u=r.get(t.operator);if(u.kind==="component")throw new d("COMPONENT_OPERATOR_REQUIRES_EXECUTOR",`${t.operator} must be compiled through the executor component pipeline`);if(u.toSQL&&(t.input&&Ue(t.input,r)||t.inputs?.some(m=>Ue(m,r))))throw new d("UNSUPPORTED_MIXED_OPERATOR",`${t.operator} cannot consume a JavaScript operator in SQL`);let p=t.input?ve(t.input,e,r,n,o,i,s,a):t.column?c(t.column,t.qualifier):void 0;const l=t.inputs?.map(m=>ve(m,e,r,n,o,i,s,a));if(t.query&&Object.keys(t.query).length>0){if(u.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(u.requiresProperty!==!1&&!p)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a column`);return u.toSQL?u.toSQL({executionContext:r.executionContext,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:(m,f)=>{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","SQL value binder is unavailable");const y=i(m);return f&&e.castValue?e.castValue(y,f):y},condition:(m,f)=>{if(!s)throw new d("SQL_CONDITION_UNAVAILABLE","SQL condition compiler is unavailable");return s(m,f)}},...p?{expression:p,column:p}:{},...l?{expressions:l}:{},args:t.args}):p??"NULL"}}},Ue=(t,e)=>t.kind==="window"?Ue(t.input,e)||t.partitionBy.some(r=>Ue(r,e)):t.kind==="cumulative"?Ue(t.input,e)||t.partitionBy.some(r=>Ue(r,e))||t.orderBy.some(r=>Ue(r.expression,e)):t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?Ue(t.input,e):t.kind==="operator"&&(!e.get(t.operator).toSQL&&!!e.get(t.operator).evaluate||(t.input?Ue(t.input,e):!1)||(t.inputs?.some(r=>Ue(r,e))??!1)),Al=(t,e)=>{const r=t.sourceSql?Xt(t.sourceSql,t.sourceColumn,e,t.sourceTimestampColumn,t.sourceAlias):`${e.quoteIdentifier(t.sourceAlias)}.${e.quoteIdentifier(t.sourceColumn)}`;return t.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(r):r},ss=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).some(e=>e.startsWith("$")),as={$second:"second",$minute:"minute",$hour:"hour",$weekday:"weekday",$day:"day",$week:"week",$month:"month",$quarter:"quarter",$year:"year"},Zt=(t,e,r,n,o,i,s,a)=>{if(Vi(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:m=>n.add(m),renderSource:(m,f)=>kr(o,m,f)})}if(s(e))throw new d("INVALID_PLUGIN_QUERY",`${e} query was not planned`,{operator:e});if(e==="$eq"&&a!==void 0){if(typeof r!="string"||a!=="i")throw new d("INVALID_QUERY_VALUE",'$eq args.options supports only case-insensitive string equality with "i"');const l=n.add(r);return"LOWER("+t+") = LOWER("+l+")"}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=It(r)?`(${i(r)})`:n.add(r);return`${t} ${p} ${l}`}if(e==="$in"||e==="$nin"){const l=e==="$in"?"IN":"NOT IN";if(It(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 m=r.filter(It);if(m.length>0){if(m.length!==r.length)throw new d("MIXED_SUBQUERY_VALUES",`${e} cannot mix query LogicForm objects and literal values`);return`${t} ${l} (${m.map(i).join(" UNION ALL ")})`}const f=r.map(y=>n.add(y)).join(", ");return`${t} ${l} (${f})`}if(It(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}`)},to=(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&&!It(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=>to(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`)}},dt=(t,e,r,n,o,i)=>{if(Kd(e)){const u=()=>`CASE ${e.comparable.values.map((f,y)=>`WHEN ${t} = ${r.add(f)} THEN ${e.comparable.direction*y}`).join(" ")} END`,p=new Set(["$gt","$gte","$lt","$lte"]),l=m=>typeof m!="object"||m===null||Array.isArray(m)?dt(t,m,r,n,o,i):Object.entries(m).filter(([f])=>f!=="args").map(([f,y])=>(f==="$and"||f==="$or")&&Array.isArray(y)?`(${y.map(l).join(f==="$and"?" AND ":" OR ")})`:p.has(f)?Zt(u(),f,e.comparable.direction*e.comparable.values.indexOf(String(y)),r,n,o,i):Zt(t,f,y,r,n,o,i)).join(" AND ");return l(e.condition)}if(Array.isArray(e))return Zt(t,"$in",e,r,n,o,i);if(!ss(e))return Zt(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 u=a.options;if(u!==void 0&&typeof u!="string")throw new d("INVALID_QUERY_VALUE","Query args.options must be a string")}const c=a?.options;for(const[u,p]of Object.entries(e))if(u==="$and"||u==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${u} requires an array`);const l=p.map(m=>dt(t,m,r,n,o,i));s.push(`(${l.join(u==="$and"?" AND ":" OR ")})`)}else as[u]?(to(p,u),s.push(dt(n.datePart(t,as[u]),p,r,n,o,i))):u==="$length"?(to(p,"$length"),s.push(dt(n.stringLength(t),p,r,n,o,i))):u!=="args"&&s.push(Zt(t,u,p,r,n,o,i,u==="$regex"||u==="$eq"?c:void 0));if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},cs=(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(!ss(e))return i(e);const s=[];for(const[a,c]of Object.entries(e))if(a==="$and"||a==="$or"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const u=c.map(p=>cs(t,p,r,n));s.push(`(${u.join(a==="$and"?" AND ":" OR ")})`)}else if(a==="$eq")s.push(i(c));else if(a==="$ne")s.push(`NOT (${i(c)})`);else if(a==="$in"||a==="$nin"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const u=c.map(i),p=u.length===0?a==="$in"?"0 = 1":"1 = 1":u.join(a==="$in"?" OR ":" AND NOT ");s.push(a==="$nin"&&u.length>0?`NOT (${u.join(" OR ")})`:`(${p})`)}else if(a==="$exists")s.push(`${t} IS ${c?"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 ")},Tt=(t,e,r,n,o,i,s,a)=>{const c=[];for(const[u,p]of Object.entries(t)){if(u==="$and"||u==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${u} requires an array`);const m=p.map(f=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_QUERY_VALUE",`${u} items must be query objects`);return Tt(f,e,r,n,o,i,s,a)});c.push(`(${m.join(u==="$and"?" AND ":" OR ")})`);continue}if(u==="$expr"){if(!Yi(p))throw new d("INVALID_EXPRESSION_QUERY","$expr query was not planned");c.push(dt(s(p.expression),p.condition,n,o,i,a));continue}const l=e(u);c.push(r(u)?cs(l,p,n,o):dt(l,p,n,o,i,a))}return c.join(" AND ")},Ur=(t,e,r,n,o)=>t.orderBy.map(i=>{const s=e.quoteIdentifier(i.name),a=`${n?`${n}.`:""}${s}`,c=i.comparable,u=!n&&o&&i.expression?o(i.expression):a;return`${c?`CASE ${c.values.map((l,m)=>`WHEN ${u} = ${r.add(l)} THEN ${c.direction*m}`).join(" ")} END`:a} ${i.direction}`}).join(", "),ro=(t,e)=>{let r=t;for(;e.has(r);)r=`_${r}`;return r},us=(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`])),ds=(t,e,r,n,o)=>{const i=new Set(e.projections.map(({name:k})=>k)),s="__sdb_page_source",a="__sdb_page",c=n.quoteIdentifier(s),u=n.quoteIdentifier(a),p=ro("__sdb_row_number",i),l=ro("__sdb_total_rows",i),m=n.quoteIdentifier(p),f=n.quoteIdentifier(l),y=Ur(e,n,o,c),h=y?`ORDER BY ${y}`:"",g=`CEIL(${f} * ${r.ratio})`,$=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=>`${u}.${n.quoteIdentifier(k)}`).join(", "),w=Ur(e,n,o,u),R=`SELECT ${c}.*, ROW_NUMBER() OVER (${h}) AS ${m}, COUNT(*) OVER () AS ${f} FROM ${n.tableAlias(`(${t})`,s)}`;let C=`SELECT ${E} FROM ${n.tableAlias(`(${R})`,a)} WHERE ${u}.${m} > ${$} * ${g} AND ${u}.${m} <= ${A} * ${g}`;return w&&(C+=` ORDER BY ${w}`),C},ls=(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),c=r.quoteIdentifier(s),u=new Set(e.projections.map(({name:A})=>A)),p=ro("__sdb_limit_by_row_number",u),l=r.quoteIdentifier(p),m=o.partitionBy.map(A=>`${a}.${r.quoteIdentifier(A)}`).join(", "),f=o.orderBy.map(({name:A,direction:_,comparable:E})=>{const w=`${a}.${r.quoteIdentifier(A)}`;return`${E?`CASE ${E.values.map((C,k)=>`WHEN ${w} = ${n.add(C)} THEN ${E.direction*k}`).join(" ")} END`:w} ${_}`}).join(", "),h=[...e.projections.map(({name:A})=>A),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(A=>`${c}.${r.quoteIdentifier(A)}`).join(", "),g=`PARTITION BY ${m} ORDER BY ${f}`,$=`SELECT ${a}.*, ROW_NUMBER() OVER (${g}) AS ${l} FROM ${r.tableAlias(`(${t})`,i)}`;return`SELECT ${h} FROM ${r.tableAlias(`(${$})`,s)} WHERE ${c}.${l} <= ${o.count}`},we=(t,e,r=Ve(),n=0)=>{const o=new hl(e,n),i=w=>_t(w);if(t.subplans){const w=t.projections.map(({name:q})=>q),R=new Set(t.groupBy.map(({name:q})=>q)),C=t.subplans.map((q,U)=>{const Y=we(q,e,r,o.nextParameterOffset);o.append(Y.parameters);const z=`__composition_child_${U}`,Q=e.quoteIdentifier(z),W=new Set(q.projections.map(({name:ke})=>ke));return{aliasName:z,alias:Q,available:W,sql:Y.sql}}),k=C[0];if(!k)throw new d("INVALID_COMPOSITION","Composition has no children");const T=w.map(q=>{const U=C.filter(Q=>Q.available.has(q)),Y=U[0]??k;return`${R.has(q)&&U.length>1?`COALESCE(${U.map(Q=>`${Q.alias}.${e.quoteIdentifier(q)}`).join(", ")})`:`${Y.alias}.${e.quoteIdentifier(q)}`} AS ${e.quoteIdentifier(q)}`}),G=C.map(q=>`${q.alias} AS (${q.sql})`);let v;if(t.rowIdentity.kind==="group"){const U=e.quoteIdentifier("__composition_keys"),Y=e.quoteIdentifier("_id");G.push(`${U} AS (${C.map(z=>`SELECT ${Y} FROM ${z.alias}`).join(" UNION ")})`),T.push(`${U}.${Y} AS ${Y}`),v=`WITH ${G.join(", ")} SELECT ${T.join(", ")} FROM ${U}`;for(const z of C)v+=` LEFT JOIN ${z.alias} ON ${U}.${Y} = ${z.alias}.${Y}`}else{v=`WITH ${G.join(", ")} SELECT ${T.join(", ")} FROM ${k.alias}`;for(const q of C.slice(1))v+=` LEFT JOIN ${q.alias} ON 1 = 1`}if(t.having&&Object.keys(t.having).length>0){const q="__composition_having",U=e.quoteIdentifier(q),Y=new Set(w),z=Tt(t.having,Q=>{if(!Y.has(Q))throw new d("INVALID_HAVING",`Having field is not an output: ${Q}`);return`${U}.${e.quoteIdentifier(Q)}`},()=>!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);v=`SELECT ${U}.* FROM ${e.tableAlias(`(${v})`,q)} WHERE ${z}`}if(t.groupLimit&&(v=ls(v,t,e,o)),t.pagination?.kind==="ratio")v=ds(v,t,t.pagination,e,o);else if(t.orderBy.length>0&&(v+=` ORDER BY ${Ur(t,e,o)}`),t.pagination?.kind==="rows"){const q=(t.pagination.page-1)*t.pagination.pageSize;v=e.paginate(v,t.pagination.pageSize,q)}return{sql:v,parameters:o.values}}const s=w=>{if(w.plan.projections.some(({expression:C})=>Ue(C,r)))throw new d("JAVASCRIPT_OPERATOR_IN_SUBQUERY","A query LogicForm cannot use a JavaScript-only operator");const R=we(w.plan.rowIdentity.kind==="property"||w.plan.rowIdentity.kind==="group"?{...w.plan,rowIdentity:{kind:"generated"}}:w.plan,e,r,o.nextParameterOffset);return o.append(R.parameters),R.sql},a=(t.joins?.length??0)>0||(t.enrichmentJoins?.length??0)>0,c=(t.arrayExpansions?.length??0)>0,u=a||c||t.sourcePlan!==void 0||t.sourceSql!==void 0||t.periodSource!==void 0,p=new Map,l=(t.arrayExpansions??[]).map(w=>{if(!e.expandArray)throw new d("ARRAY_EXPANSION_UNSUPPORTED",`Provider ${e.kind} does not support array expansion`);const R=e.expandArray(Al(w,e),w.alias,"value",w.elementType);return p.set(w.path,R.valueExpression),R}),m=w=>{const R=t.fieldReferences?.[w];if(R?.sql){const T=Xt(R.sql,R.property,e,R.timestampColumn,u?R.timestampQualifier??R.qualifier:void 0);return R.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(T):T}if(R&&u){const T=`${e.quoteIdentifier(R.qualifier)}.${e.quoteIdentifier(R.column)}`;return R.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(T):T}const C=t.fields[w];if(!C)throw new d("PROPERTY_NOT_FOUND",`Query property not found: ${w}`);const k=e.quoteIdentifier(C);return R?.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(k):k},f=w=>ve(w,e,r,u,R=>Tt(R,m,C=>t.fieldReferences?.[C]?.isArray===!0,o,e,s,f,i),R=>o.add(R),(R,C)=>dt(R,C,o,e,s,i),R=>{const C=p.get(R);if(!C)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${R}`);return C}),y=t.projections.map(w=>`${f(w.expression)} AS ${e.quoteIdentifier(w.name)}`),h=t.rowIdentity.kind==="property"?`${u&&t.sourceAlias?`${e.quoteIdentifier(t.sourceAlias)}.`:""}${e.quoteIdentifier(t.rowIdentity.column)} AS ${e.quoteIdentifier(t.rowIdentity.internalName)}`:t.rowIdentity.kind==="group"?(()=>{const w=t.rowIdentity.names.map(R=>{const C=t.groupBy.find(k=>k.name===R)??t.projections.find(k=>k.name===R);if(!C)throw new d("GROUP_IDENTITY_OUTPUT_NOT_FOUND",`Group identity output not found: ${R}`);return f(C.expression)});return`${us(w,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`})():void 0,g=[...y,...h?[h]:[]].join(", "),$=t.sourcePlan?(()=>{const w=we(t.sourcePlan,e,r,o.nextParameterOffset);return o.append(w.parameters),`(${w.sql})`})():t.source?kr(e,t.source,t.sourceSql):"",A=u&&t.sourceAlias?e.tableAlias($,t.sourceAlias):$;let _=`SELECT ${g}`;if(t.periodSource){const w=t.periodSource,R=w.periods.map(({label:U,asOf:Y},z)=>{const Q=o.add(U),W=o.add(Y);return z===0?`SELECT ${Q} AS ${e.quoteIdentifier(w.labelColumn)}, ${W} AS ${e.quoteIdentifier(w.asOfColumn)}`:`SELECT ${Q}, ${W}`}).join(" UNION ALL "),C=e.tableAlias(`(${R})`,w.alias),k=e.tableAlias($,w.sourceAlias),T=e.quoteIdentifier(w.alias),G=e.quoteIdentifier(w.sourceAlias),v=`${T}.${e.quoteIdentifier(w.asOfColumn)}`,q=w.match.kind==="interval"?(()=>{const U=`${G}.${e.quoteIdentifier(w.match.startColumn)}`,Y=`${G}.${e.quoteIdentifier(w.match.endColumn)}`;return`${U} <= ${v} AND (${Y} > ${v} OR ${Y} IS NULL)`})():(()=>{const U=e.tableAlias($,w.match.lookupAlias),Y=e.quoteIdentifier(w.match.lookupAlias),z=`${G}.${e.quoteIdentifier(w.match.timestampColumn)}`,Q=`${Y}.${e.quoteIdentifier(w.match.timestampColumn)}`,W=`SELECT ${e.aggregateFunction("max",Q)} FROM ${U} WHERE ${Q} <= ${v}`;return`${z} = (${W})`})();_+=` FROM ${C} LEFT JOIN ${k} ON ${q}`,t.query&&Object.keys(t.query).length>0&&(_+=` AND ${Tt(t.query,m,U=>t.fieldReferences?.[U]?.isArray===!0,o,e,s,f,i)}`)}else A&&(_+=` FROM ${A}`);for(const w of l)_+=` ${w.joinSql}`;for(const w of t.enrichmentJoins??[]){const R=e.quoteIdentifier(w.alias),C=e.quoteIdentifier(w.baseAlias);_+=` LEFT JOIN ${e.tableAlias(kr(e,w.source,w.sourceSql),w.alias)}`;const k=w.keys.map(({baseColumn:T,targetColumn:G})=>`${C}.${e.quoteIdentifier(T)} = ${R}.${e.quoteIdentifier(G)}`);if(w.temporalCondition?.kind==="point-in-interval"){const T=Y=>Y==="source"?C:R,G=`${T(w.temporalCondition.pointSide)}.${e.quoteIdentifier(w.temporalCondition.pointColumn)}`,v=T(w.temporalCondition.intervalSide),q=`${v}.${e.quoteIdentifier(w.temporalCondition.startColumn)}`,U=`${v}.${e.quoteIdentifier(w.temporalCondition.endColumn)}`;k.push(`${q} <= ${G}`),k.push(`(${U} > ${G} OR ${U} IS NULL)`)}_+=` ON ${k.join(" AND ")}`}for(const w of t.joins??[]){_+=` LEFT JOIN ${e.tableAlias(kr(e,w.targetSource,w.targetSourceSql),w.targetAlias)}`;const R=w.sourceArrayExpansionPath?p.get(w.sourceArrayExpansionPath):w.sourceSql?Xt(w.sourceSql,w.sourceColumn,e,w.sourceTimestampColumn,w.sourceAlias):`${e.quoteIdentifier(w.sourceAlias)}.${e.quoteIdentifier(w.sourceColumn)}`,C=w.targetSql?Xt(w.targetSql,w.targetColumn,e,w.targetTimestampColumn,w.targetAlias):`${e.quoteIdentifier(w.targetAlias)}.${e.quoteIdentifier(w.targetColumn)}`;if(!R)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${w.path}`);if(_+=` ON ${R} = ${C}`,w.temporalCondition?.kind==="date-bucket-equal"){const k=`${e.quoteIdentifier(w.sourceAlias)}.${e.quoteIdentifier(w.temporalCondition.sourceColumn)}`,T=`${e.quoteIdentifier(w.targetAlias)}.${e.quoteIdentifier(w.temporalCondition.targetColumn)}`;_+=` AND ${e.dateBucket(k,w.temporalCondition.sourceGranularity)} = ${e.dateBucket(T,w.temporalCondition.targetGranularity)}`}else if(w.temporalCondition?.kind==="point-in-interval"){const k=U=>U==="source"?e.quoteIdentifier(w.sourceAlias):e.quoteIdentifier(w.targetAlias),T=`${k(w.temporalCondition.pointSide)}.${e.quoteIdentifier(w.temporalCondition.pointColumn)}`,G=k(w.temporalCondition.intervalSide),v=`${G}.${e.quoteIdentifier(w.temporalCondition.startColumn)}`,q=`${G}.${e.quoteIdentifier(w.temporalCondition.endColumn)}`;_+=` AND ${v} <= ${T} AND (${q} > ${T} OR ${q} IS NULL)`}}const E=[];if(!t.periodSource&&t.query&&Object.keys(t.query).length>0&&E.push(Tt(t.query,m,w=>t.fieldReferences?.[w]?.isArray===!0,o,e,s,f,i)),E.length>0&&(_+=` WHERE ${E.join(" AND ")}`),t.groupBy.length>0){const w=t.groupBy.map(C=>f(C.expression)),R=t.rowIdentity.kind==="group"?[us(w,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)]:[];_+=` GROUP BY ${[...w,...R].join(", ")}`}if(t.having&&Object.keys(t.having).length>0){const w=R=>{const C=t.projections.find(k=>k.name===R);if(!C)throw new d("INVALID_HAVING",`Having field is not an output: ${R}`);return e.supportsHavingAlias===!1?f(C.expression):e.quoteIdentifier(R)};_+=` HAVING ${Tt(t.having,w,()=>!1,o,e,s,f,i)}`}if(t.groupLimit&&(_=ls(_,t,e,o)),t.pagination?.kind==="ratio")_=ds(_,t,t.pagination,e,o);else if(t.orderBy.length>0&&(_+=` ORDER BY ${Ur(t,e,o,void 0,f)}`),t.pagination?.kind==="rows"){const w=(t.pagination.page-1)*t.pagination.pageSize;_=e.paginate(_,t.pagination.pageSize,w)}return{sql:_,parameters:o.values}},wl=(t,e)=>{const r=Object.keys(e).sort((m,f)=>f.length-m.length),n=[];let o=0;for(;o<t.length;){const m=t[o];if(m&&/\s/.test(m)){o+=1;continue}if(m&&/[()+\-*/,]/.test(m)){n.push(m),o+=1;continue}const f=t.slice(o).match(/^\d+(?:\.\d+)?/);if(f?.[0]){n.push(f[0]),o+=f[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(m??""),o+=1}let i=0;const s=()=>n[i],a=()=>n[i++],c=()=>{const m=a();if(!m)throw new Error("Component expression is incomplete");if(m==="("){const y=p();if(a()!==")")throw new Error("Component expression has an unclosed parenthesis");return`(${y})`}if(/^\d/.test(m))return m;if(!e[m]&&!/^[A-Za-z_$][\w$]*$/.test(m))throw new Error(`Invalid component expression token: ${m}`);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(m.toUpperCase()))throw new Error(`Unsupported component expression function: ${m}`);return`${m.toUpperCase()}(${y.join(", ")})`}const f=e[m];if(!f)throw new Error(`Unknown component in expression: ${m}`);return f},u=()=>{let m=c();for(;s()==="*"||s()==="/";)m=`${m} ${a()} ${c()}`;return m},p=()=>{let m=u();for(;s()==="+"||s()==="-";)m=`${m} ${a()} ${u()}`;return m},l=p();if(i!==n.length)throw new Error(`Unexpected component expression token: ${s()}`);return l},$l=t=>`__sdb_cte_${t}`,ps=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),_l=(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,no=(t,e,r,n=Ve())=>{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:_l(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],c=r.quoteIdentifier(a.alias),u=e.groupBy.map(({name:A})=>A),p=e.orderBy??[],l=e.rowIdentity.kind==="group",m=r.quoteIdentifier("__sdb_exec_keys");if(l){const A=_=>[...u.map(E=>`${_}.${r.quoteIdentifier(E)}`),`${_}.${r.quoteIdentifier("_id")}`].join(", ");s.push(`${m} AS (${i.map(({alias:_})=>`SELECT ${A(r.quoteIdentifier(_))} FROM ${r.quoteIdentifier(_)}`).join(" UNION ")})`)}const f=l?m:c,y=[...u,...t.flatMap(({outputs:A})=>A)],h=y.filter((A,_,E)=>E.indexOf(A)===_).map(A=>{if(u.includes(A))return`${f}.${r.quoteIdentifier(A)} AS ${r.quoteIdentifier(A)}`;const _=i.find(({outputs:w})=>w.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)}`});l&&h.push(`${f}.${r.quoteIdentifier("_id")} AS ${r.quoteIdentifier("_id")}`);let g=`SELECT ${h.join(", ")} FROM ${f}`;for(const A of l?i:i.slice(1)){const _=r.quoteIdentifier(A.alias);g+=` LEFT JOIN ${_}`,g+=l?` ON ${f}.${r.quoteIdentifier("_id")} = ${_}.${r.quoteIdentifier("_id")}`:" ON 1 = 1"}if(!!(e.having&&Object.keys(e.having).length>0||p.length>0||e.pagination||e.groupLimit)){const A={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:w,comparable:R})=>({name:E,direction:w,...R?{comparable:R}:{}})),...e.pagination?{pagination:e.pagination}:{},...e.groupLimit?{groupLimit:e.groupLimit}:{},rowIdentity:{kind:"generated"}},_=we(A,r,n,o);return{sql:`WITH ${s.join(", ")} ${_.sql}`,parameters:[...i.flatMap(({compiled:E})=>E.parameters),..._.parameters]}}return{sql:`WITH ${s.join(", ")} ${g}`,parameters:i.flatMap(({compiled:A})=>A.parameters)}},Mr=(t,e,r,n,o,i)=>{const s=[];let a=0;for(const A of e){const _=we(A.plan,o,i,a);a+=_.parameters.length,s.push({input:A,sql:_,alias:$l(A.name)})}const c=s.map(({sql:A,alias:_})=>`${o.quoteIdentifier(_)} AS (${A.sql})`).join(", "),u=s[0];if(!u)throw new Error("CTE calculation requires a current component");const p=o.quoteIdentifier(u.alias),l=r.groupBy.map(({name:A})=>A),m=l.map(A=>`${p}.${o.quoteIdentifier(A)} AS ${o.quoteIdentifier(A)}`);let f="";for(const A of s.slice(1)){const _=o.quoteIdentifier(A.alias),E=A.input.plan.groupBy.map(({name:C})=>C),R=(A.input.joinKeys??l.filter(C=>E.includes(C))).map(C=>{const k=El(A.input.groupKeyShifts,C),T=k?o.dateShift(`${_}.${o.quoteIdentifier(C)}`,k.granularity,k.offset):`${_}.${o.quoteIdentifier(C)}`;return`${p}.${o.quoteIdentifier(C)} = ${T}`});f+=` LEFT JOIN ${_} ON ${R.length>0?R.join(" AND "):"1 = 1"}`}const y=Object.fromEntries(s.map(({input:A,alias:_})=>[A.name,`${o.quoteIdentifier(_)}.${o.quoteIdentifier(ps(A.plan))}`])),h=wl(t.expression,y),g=[...m,...r.rowIdentity.kind==="group"?[`${p}.${o.quoteIdentifier("_id")} AS ${o.quoteIdentifier("_id")}`]:[],...s.map(({input:A,alias:_})=>`${`${o.quoteIdentifier(_)}.${o.quoteIdentifier(ps(A.plan))}`} AS ${o.quoteIdentifier(A.name)}`),`${h} AS ${o.quoteIdentifier(n)}`].join(", ");let $=`WITH ${c} SELECT ${g} FROM ${p}`;return $+=f,{sql:$,parameters:s.flatMap(({sql:A})=>A.parameters)}},Sl=t=>{if(typeof t!="string"||!/\bSELECT\b/i.test(t))return t;try{let e=t;const r=ms(t).length*2+2;for(let n=0;n<r;n+=1){const o=Il(e);if(o===e)return e;e=o}return e}catch{return t}},Il=t=>{const e=ms(t),r=bl(t,e);if(r!==t)return r;const n=[];for(const i of e){const s=ys(t,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?Bl(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 c=jl(Rl(t.slice(i.fromStart,i.close),i,e)),u=Nl(t,i),p=Ol(t,i);if(p&&Tl(u,p))continue;let l=s.filter(h=>{const g=hs(h);if(!g||g==="_id")return!0;const $=new RegExp(`(^|[^\\w$])${oo(g)}([^\\w$]|$)`,"i");return $.test(c)||$.test(u)}),m=!0;for(;m;){m=!1;const h=ws(l.join(" ")),g=s.filter($=>{if(l.includes($))return!1;const A=hs($);return A?new RegExp(`(^|[^\\w$])${oo(A)}([^\\w$]|$)`,"i").test(h):!1});g.length>0&&(l=s.filter($=>l.includes($)||g.includes($)),m=!0)}if(l.length===s.length)continue;const f=t.slice(i.selectEnd,i.fromStart),y=l.length===0&&xl(t,i)&&!/(^|[^\w$])\*([^\w$]|$)/.test(u)&&!/^\s*(?:DISTINCT|ALL|TOP|SQL_)\b/i.test(f)&&!/\b(?:UNION|INTERSECT|EXCEPT)\b/i.test(c);l.length===0&&!y||n.push({start:i.selectEnd,end:i.fromStart,value:f.match(/^\s*/)[0]+(y?"1":l.map(h=>h.trim()).join(", "))+f.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},bl=(t,e)=>{const r=/^\s*SELECT\b/i.exec(t);if(!r)return t;const n=r.index+r[0].length,o=fs(t,"FROM",n);if(o===-1||!ys(t,n,o)?.every(ql))return t;const s=e.find(m=>m.open>o&&t.slice(o+4,m.open).trim().length===0);if(!s||!/^\s*1\s*$/.test(t.slice(s.selectEnd,s.fromStart)))return t;const a=e.filter(m=>m.open>s.fromStart&&m.close<s.close).sort((m,f)=>f.close-f.open-(m.close-m.open))[0];if(!a||t.slice(s.fromStart+4,a.open).trim().length>0)return t;const c=t.slice(a.close+1,s.close);if(/\b(?:GROUP|HAVING|ORDER|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT)\b/i.test(c))return t;const u=Ul.exec(c)?.[1],p=Ml.exec(t.slice(s.close+1));if(!u||!p||gs(u)!==gs(p[1]))return t;const l=/;(\s*)$/.exec(t)?.[0]??"";return t.slice(0,s.open)+t.slice(a.open,s.close)+l},Rl=(t,e,r)=>Pl(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}))),Nl=(t,e)=>{const r=t.slice(0,e.open)+" ".repeat(e.close-e.open+1)+t.slice(e.close+1);return ws(r)},Ol=(t,e)=>t.slice(e.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${Ke})(?=\\s|$)`,"i"))?.[1]??null,Tl=(t,e)=>new RegExp(`(^|[^\\w$])${oo(e)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(t),Pl=(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("")},fs=(t,e,r)=>{let n=0,o=0,i="",s="";for(let a=r;a<t.length;a+=1){const c=t[a],u=t[a+1];if(s==="--"){c===`
|
|
2
|
-
`&&(s="");continue}if(s==="/*"){c==="*"&&u==="/"&&(s="",a+=1);continue}if(i){c===i&&t[a-1]!=="\\"&&(i="");continue}if(c==="-"&&u==="-"){s="--",a+=1;continue}if(c==="/"&&u==="*"){s="/*",a+=1;continue}if(c==="`"||c==='"'||c==="'"){i=c;continue}if(c==="("){n+=1;continue}if(c===")"){n-=1;continue}if(c==="["){o+=1;continue}if(c==="]"){o-=1;continue}if(n===0&&o===0&&new RegExp(`^${e}\\b`,"i").test(t.slice(a)))return a}return-1},
|
|
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 c=r.pop();if(!c)continue;const u=t.slice(c.open+1,i),p=/^\s*SELECT\b/i.exec(u);if(!p)continue;const l=c.open+1+p[0].length,m=fs(t,"FROM",l);m===-1||m>=i||e.push({open:c.open,close:i,selectEnd:l,fromStart:m})}return e},ys=(t,e,r)=>{const n=t.slice(e,r),o=[];let i=0,s=0,a=0,c="";for(let u=0;u<n.length;u+=1){const p=n[u];if(c){p===c&&n[u-1]!=="\\"&&(c="");continue}if(p==="`"||p==='"'||p==="'"){c=p;continue}p==="("?s+=1:p===")"?s-=1:p==="["?a+=1:p==="]"?a-=1:p===","&&s===0&&a===0&&(o.push(n.slice(i,u)),i=u+1)}return c||s!==0||a!==0?null:(o.push(n.slice(i)),o)},hs=t=>t.trim().match(/\bAS\s+(`[^`]+`|"[^"]+"|[A-Za-z_][\w$]*)\s*$/i)?.[1]?.replace(/^`|`$/g,"").replace(/^"|"$/g,"")??null,Ke='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',Ll=new RegExp(`\\s+AS\\s+${Ke}\\s*$`,"i"),Cl=new RegExp(`\\bAS\\s+${Ke}`,"gi"),Dl=new RegExp(`(?:${Ke}\\s*\\.\\s*)+${Ke}`,"g"),kl=new RegExp(`^${Ke}(?:\\s*\\.\\s*${Ke})*$`),Ul=new RegExp(`^\\s*(?:AS\\s+)?(${Ke})\\s+WHERE\\b`,"i"),Ml=new RegExp(`^\\s*(?:AS\\s+)?(${Ke})\\s*;?\\s*$`,"i"),gs=t=>t.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),ql=t=>{const e=t.replace(Ll,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(e)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(e)},As=(t,e)=>t.replace(e,r=>" ".repeat(r.length)),ws=t=>As(t,Cl),jl=t=>As(t,Dl),xl=(t,e)=>/\b(?:FROM|JOIN)\s*$/i.test(t.slice(0,e.open)),Bl=t=>{const e=t.trim();return kl.test(e)?e:null},oo=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),io=(t,e)=>{if(t.kind!=="operator")return!1;const r=e.get(t.operator);return!r.toSQL&&!!r.evaluate||(t.input?io(t.input,e):!1)||(t.inputs?.some(n=>io(n,e))??!1)},$s=(t,e,r,n)=>{if(t.kind!=="operator")return e[r];const o=n.get(t.operator),i=t.input?$s(t.input,e,r,n):e[r];return o.evaluate?Promise.resolve(i).then(s=>o.evaluate?.({executionContext:n.executionContext,input:s,args:t.args})):i},lt=async(t,e,r)=>{const n=e.filter(({expression:o})=>io(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 $s(s.expression,i,s.name,r);return i}))},qr=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),jr=(t,e,r="_",n="\u7A7A\u503C")=>e.map(o=>t[o]===null||t[o]===void 0?n:qr(t[o])).join(r),so=(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?jr(r,e.names,e.separator,e.nullLabel):qr(r._id)}:{...r,_id:e.kind==="singleton"?"0":pn.randomUUID()}}),ao=t=>{const e=oe(t);return delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,e},er=(t,e)=>t.operator&&e.get(t.operator).kind==="component"?!0:!!t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&er(t.pred,e)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&er(r,e)),xr=(t,e,r,n,o,i,s="zh-CN",a=$r.translator(s))=>{const c=t.preds??[],u=c.map((f,y)=>({pred:f,index:y,definition:f.operator?n.get(f.operator):void 0})).filter(({definition:f})=>f?.kind==="component"&&!f.skipComponentExecution?.({plan:e,executionContext:n.executionContext}));if(u.length===0&&e.sourcePlan||u.length===0)return;for(const f of c)if((!f.operator||n.get(f.operator).kind!=="component")&&(f.pred&&typeof f.pred=="object"&&!Array.isArray(f.pred)&&er(f.pred,n)||Array.isArray(f.pred)&&f.pred.some(y=>typeof y!="string"&&er(y,n))))throw new d("UNSUPPORTED_COMPONENT_NESTING","A component operator must currently be the top-level projection operator");const p=[],l=c.filter((f,y)=>!u.some(h=>h.index===y));if(l.length>0){const f=ao(t);f.preds=l,p.push({kind:"query",logicform:f})}const m=t.groupby?.length??0;for(const{pred:f,index:y,definition:h}of u){const g=h?.createComponent;if(!g)continue;const $=e.projections[m+y]?.name;if(!$)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");const A=i?.preds?.[y],_=g({executionContext:n.executionContext,logicform:ao(t),pred:A??f,outputName:$,locale:s,t:a,schema:r,resolveSchema:o,...i?{sourceLogicform:ao(i)}:{}});if("logicform"in _&&(_.logicform.preds??[]).some(E=>er(E,n)))throw new d("UNSUPPORTED_COMPONENT_NESTING","Nested component operators are not supported yet");p.push("components"in _?{..._,outputName:$}:_)}return p},Qe=t=>t instanceof Date?t.getTime():t,Vl=(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}`)}},co=(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(c=>co(t,c));return i==="$and"?a.every(Boolean):a.some(Boolean)}return i==="$length"?typeof t=="string"&&co(t.length,s):Vl(t,i,s,typeof o=="string"?o:void 0)})},Es=(t,e)=>Object.entries(e).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>Es(t,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return co(t[r],n)}),Yl=(t,e)=>e.length===0?"0":t._id===void 0?jr(t,e):qr(t._id),uo=(t,e)=>{const r=new Map;for(const n of t)for(const o of n){const i=Yl(o,e);r.set(i,{...r.get(i)??{},...o})}return[...r.values()]},lo=(t,e)=>{const r=e.groupBy.map(({name:o})=>o);let n=uo(t,r);if(e.having&&(n=n.filter(o=>Es(o,e.having))),e.groupLimit){const o=e.groupLimit,i=new Map;for(const s of n){const a=jr(s,o.partitionBy);i.set(a,[...i.get(a)??[],s])}n=[...i.values()].flatMap(s=>s.sort((a,c)=>{for(const u of o.orderBy){const p=Qe(a[u.name]),l=Qe(c[u.name]);if(p!==l)return p==null?u.direction==="ASC"?-1:1:l==null?u.direction==="ASC"?1:-1:(p<l?-1:1)*(u.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]),c=Qe(i[s.name]);if(a!==c)return a==null?s.direction==="ASC"?-1:1:c==null?s.direction==="ASC"?1:-1:(a<c?-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},_s=(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 po{#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 Fl=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)}},Ss=t=>{Fl(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)})},vl=new Set(["second","minute","hour","day","week","month","quarter","year"]),Ql=(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 c=a,u=Object.keys(c).filter(p=>p!=="sql");if(u.length>0)throw new d("UNSUPPORTED_PROPERTY_UDF",`Property ${t.name} udf only supports sql`,{property:t.name,unsupportedKeys:u});if(typeof c.sql!="string"||c.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(n.isArray&&t.isArray===!1)throw new d("INVALID_IS_ARRAY",`Property ${t.name} of type ${t.type} must be an array`,{property:t.name,type:t.type});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; received ${JSON.stringify(a)}`,{property:t.name,comparable:a});const c=a;if(Object.keys(c).some(u=>u!=="values"&&u!=="direction")||!Array.isArray(c.values)||c.values.length===0||c.values.some(u=>typeof u!="string")||new Set(c.values).size!==c.values.length||c.direction!==1&&c.direction!==-1)throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable requires unique string values and direction 1 or -1; received ${JSON.stringify(a)}`,{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??n.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&&!vl.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},Is=(t,e,r=[])=>{const n=Ae(r),o=n.reduce((f,y)=>y.prepareSchema?.(f)??f,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");if(o.is_calendar!==void 0&&typeof o.is_calendar!="boolean")throw new d("INVALID_CALENDAR_SCHEMA_FLAG",`Schema ${o.id} is_calendar must be a boolean`,{schemaId:o.id,is_calendar:o.is_calendar});const i=n.flatMap(f=>f.propertyMetadata?[f.propertyMetadata]:[]),s=new Set(i.flatMap(({keys:f})=>f));let a=o.properties.map(f=>{const y=Object.fromEntries(Object.entries(f).filter(([g])=>!s.has(g))),h=Ql(y,e);return i.reduce((g,$)=>({...g,...$.resolve(f,g,o)}),h)});for(const f of i)a=[...f.resolveAll?.(a,o.properties,o)??a];Ss(a);const c=n.flatMap(f=>f.schemaMetadata?[f.schemaMetadata]:[]);let u={};for(const f of c)u={...u,...f.resolve(o,a)};const p=new Set(n.flatMap(f=>[...f.schemaMetadata?.keys??[],...f.legacySchemaKeys??[]])),m={...Object.fromEntries(Object.entries(o).filter(([f])=>!p.has(f))),properties:a,...u};for(const f of n)f.validateResolvedSchema?.(m);return m};ce.extend(Qo),ce.extend(Vt),ce.extend(yr);const Hl="YYYY-MM-DD HH:mm:ss",Gl=new Set(["YTD","QTD","MTD","WTD","DTD"]),bs=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),zl=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),Br=["second","minute","hour","day","week","month","quarter","year"],pt=t=>Object.prototype.toString.call(t)==="[object Object]",Rs=(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(pt(t)){const n=Object.entries(t);if(n.length===0||n.some(([o])=>!bs.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=>Rs(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`)},fo=t=>!pt(t)||"$gte"in t||"$gt"in t||"$lte"in t||"$lt"in t||"$or"in t||"$ne"in t?!1:typeof t.granularity=="string"&&Br.includes(t.granularity)&&typeof t.offset=="number"||Br.some(e=>e in t),Pt=t=>ce(t).format(Hl),Wl=(t,e)=>Br.find(r=>r in t||e!==void 0),Kl=(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),Ns=(t,e)=>{const r=typeof t.granularity=="string"?t.granularity:void 0,n=r?{[r]:t.offset}:void 0,o=r??Wl(t,void 0)??"day";let i=ce(e).millisecond(0);for(const a of[...Br].reverse()){const c=t[a];typeof c=="number"&&(i=Kl(i,a,c));const u=n?.[a];typeof u=="number"&&u!==0&&(i=i.add(u,a))}const s=o==="week"?"isoWeek":o;return{$gte:Pt(i.startOf(s)),$lte:Pt(i.endOf(s))}},Jl=(t,e)=>{const r=ce(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:Pt(o()),$lte:Pt(r.endOf("day"))}},mo=async(t,e)=>{const r=ce(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=ce(n).endOf(i),a=ce(String(t.$gte));if(a.isValid()&&s.isBefore(a))return t;const c=s.isBefore(r)?s:r;return{...t,$lte:Pt(c)}},yo=async(t,e)=>Ce(t)?t:t instanceof Date||typeof t=="string"&&ce(t).isValid()?Pt(t):typeof t=="string"&&Gl.has(t)?mo(Jl(t,e.now),e):fo(t)?mo(Ns(t,e.now),e):t,Os=async(t,e,r)=>{if(t==="$and"||t==="$or")return Array.isArray(e)?Promise.all(e.map(o=>Vr(o,r))):e;if(Array.isArray(e))return Promise.all(e.map(o=>yo(o,r)));const n=await yo(e,r);return t==="$eq"&&pt(n)&&"$gte"in n&&"$lte"in n?n:t==="$gte"||t==="$gt"?pt(n)&&"$gte"in n?n.$gte:n:(t==="$lte"||t==="$lt")&&pt(n)&&"$lte"in n?n.$lte:n},Vr=async(t,e)=>{if(Ce(t))return t;if(Array.isArray(t))return Promise.all(t.map(o=>Vr(o,e)));if(!pt(t))return yo(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)&&(!fo(t)||!Number.isInteger(t.offset)))throw new d("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(fo(t))return mo(Ns(t,e.now),e);const r=Object.entries(t);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await Os("$eq",r[0][1],e);if(pt(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)zl.has(o)&&Rs(i,o),n[o]=bs.has(o)?await Os(o,i,e):await Vr(i,e);return n},Xl=(t,e)=>e.property.primal_type==="date"?Vr(t,e):t,ho=(t=[])=>new po([...Qn,...Ae(t).flatMap(({semanticTypes:e})=>e??[])]),Ts=(t,e)=>{const r=new po(t.definitions());for(const n of Ae(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},Zl=/^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,ep=t=>{if(typeof t!="string")return!1;const e=Zl.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},go=t=>{if(!ep(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})},Ps=(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)&&Ps(o,e))),Ls=(t,e,r,n=[])=>{if(e===void 0||e==="placeholder")return t;if(!On(e))throw new d("INVALID_ENTITY_ID","entity_id must be a non-empty string or a safe integer");const o=Tn(r,n);return t&&Ps(t,new Set([o.name,o.id]))?t:{[o.name]:e,...t??{}}},Lt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),tp={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},Cs={$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"}},Ct=(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=>Ct(n,e)).join(e?", ":"\u3001");if(!Lt(t))return e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6";if(Array.isArray(t.roots))return t.roots.map(n=>Ct(n,e)).join(e?", ":"\u3001");if(t.root!==void 0)return Ct(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])}${tp[n]??""}`);return r.length>0?r.join(e?", ":""):e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6"},Yr=(t,e,r)=>t.filter(Boolean).join(r?e==="$and"?" and ":" or ":e==="$and"?"\u4E14":"\u6216"),Ds=(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}`},tr=(t,e,r)=>{if(!Lt(e)||Object.keys(e).every(o=>!o.startsWith("$")))return Ds("$eq",t,Ct(e,r),r)??"";const n=[];for(const[o,i]of Object.entries(e))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Yr(i.map(s=>tr(t,s,r)),o,r));else if(o==="$exists")n.push(r?`${t} ${i?"exists":"does not exist"}`:`${i?"\u6709":"\u65E0"}${t}`);else if(Cs[o]){const s=Cs[o];n.push(tr(r?`${t} ${s.en}`:`${t}\u7684${s.zh}`,i,r))}else if(o==="$length")n.push(tr(r?`${t} length`:`${t}\u957F\u5EA6`,i,r));else if(o!=="args"){const s=o==="$regex"&&Lt(i)?Ct(i.pattern,r):Ct(i,r),a=Ds(o,t,s,r);a&&n.push(a)}return Yr(n,"$and",r)},ks=(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(Yr(i.map(s=>Lt(s)?ks(s,e):""),o,r));else if(o==="$expr"&&Lt(i)){const s=i.pred,a=Lt(s)&&typeof s.name=="string"?s.name:r?"expression":"\u8868\u8FBE\u5F0F";i.condition!==void 0&&n.push(tr(a,i.condition,r))}else i!==void 0&&n.push(tr(o,i,r));return Yr(n,"$and",r)},Dt=(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??$r,i=o.resolve(n).locale.toLowerCase().startsWith("en"),s=o.translator(n),a=Array.isArray(t.pred)?t.pred.map(f=>typeof f=="string"?f:Dt(f,e,r)):[],c=typeof t.pred=="string"?t.pred:t.pred&&!Array.isArray(t.pred)?Dt(t.pred,e,r):void 0,u=c??(a.length>0?a.join(i?", ":"\u3001"):s("operator.rows",i?"rows":"\u6570\u636E\u884C")),p=t.args??{},l=t.operator?(()=>{const f=e.get(t.operator),y={executionContext:e.executionContext,operandName:u,...c?{inputName:c}:{},inputNames:a,args:p,locale:n,t:s},h=f.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(f.defaultNameIsLocalized)return h;const A=typeof f.defaultNameKey=="function"?f.defaultNameKey(y):f.defaultNameKey??`operator.${t.operator}`;return s(A,h,{...p,operandName:u,inputName:c??"",inputNames:a.join($),input0:a[0]??"",input1:a[1]??"",granularity:g})})():u;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 m=ks(t.query,n);return m?i?`${l} where ${m}`:`${m}\u7684${l}`:l},rp=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},np=t=>{if(t.args===void 0||Object.keys(t.args).length>0)return t;const{args:e,...r}=t;return r},op=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}}},rr=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&&!rp(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),c=Array.isArray(t.pred)?await Promise.all(t.pred.map(f=>rr(typeof f=="string"?{pred:f}:f,s,r,n))):void 0,{query:u,...p}=t,l={...p,...a?{query:a}:{},...c?{pred:c}:{}},m=async f=>{const y=await op(f,s,r),h=y.operator?o.get(y.operator).normalizePred?.({pred:y,schema:s,executionContext:o.executionContext})??y:y;return np(h)};if(typeof t.pred=="string"){const f=ue(s,t.pred,r.resolveSchema),y={...l,pred:f.canonicalName};return m({...y,name:y.name??Dt(y,o,i)})}if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)){const f={...l,pred:await rr(t.pred,s,r,n)};return m({...f,name:f.name??Dt(f,o,i)})}if(c)return m({...l,name:l.name??Dt(l,o,i)});if(t.pred!==void 0)throw new d("UNSUPPORTED_PRED","A pred must be a property name or nested pred");return m({...l,name:l.name??Dt(l,o,i)})},ip=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),sp=t=>{if(!Ce(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},Fr=async(t,e)=>{if(Ce(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=>Fr(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 Fr(n,e)])))},Us=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>Us(o,e))]:[`${e}_${r}`,n])),Ao=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},Ms=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),wo=new Set([...Ms,"$length"]),vr=t=>Array.isArray(t)?t.some(vr):typeof t!="object"||t===null||Ce(t)?!1:Object.entries(t).some(([e,r])=>wo.has(e)||vr(r)),qs=(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&&!Ce(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=>qs(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`)}},Qr=(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)&&Qr(t.pred,e);for(const r of Array.isArray(t.pred)?t.pred:[])typeof r!="string"&&Qr(r,e)},js=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(c=>c!=="pred"&&c!=="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");Qr(i,r);const s=await rr(i,e,r,()=>Promise.resolve(void 0));Qr(s,r);const a=Ao(await Fr(n.condition,r));return wo.has(s.operator)&&qs(a,s.operator),{pred:s,condition:a}},xs=async(t,e,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||Ce(e))return{[t]:e};const o={},i=[];for(const[s,a]of Object.entries(e))wo.has(s)?i.push({$expr:await js({pred:{operator:s,pred:t},condition:a},r,n)}):(s==="$and"||s==="$or")&&Array.isArray(a)&&a.some(vr)?i.push({[s]:await Promise.all(a.map(c=>xs(t,c,r,n)))}):o[s]=a;return Object.keys(o).length>0&&i.unshift({[t]:Ao(o)}),i.length===1?i[0]??{}:{$and:i}},$o=t=>Array.isArray(t)?t.some($o):typeof t!="object"||t===null||Ce(t)?!1:Object.entries(t).some(([e,r])=>Ms.has(e)||$o(r)),Bs=async(t,e,r,n)=>{const o=u=>{if(Array.isArray(u)){u.forEach(o);return}if(typeof u!="object"||u===null||Ce(u))return;const p=u;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"&&$o(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:u=>n.requestTimeWatermark?.(e,r,u)??Promise.resolve(void 0)},a=await Xl(oe(t),s),c=i.normalizeQuery?i.normalizeQuery(a,s):a;if(r.comparable){const u=new Set(r.comparable.values),p=(l,m)=>{if(!(Ce(l)||l===null)){if(Array.isArray(l)){l.forEach(f=>p(f,m));return}if(typeof l=="object"){Object.entries(l).forEach(([f,y])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(f)||p(y,f)});return}if(!(m&&["$exists","$regex","$contains","$startsWith","$length"].includes(m))&&(typeof l!="string"||!u.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(c)}return c},Eo=async(t,e,r)=>{const n={},o=[],i=[],s=a=>{const c=Object.entries(a);if(c.length===1&&c[0]?.[0]==="$and"&&Array.isArray(c[0][1]))for(const u of c[0][1])s(u);else c.length===1&&c[0]?.[0]==="$expr"?o.push(a):c.every(([u])=>!u.startsWith("$"))?Object.assign(n,a):i.push(a)};for(const[a,c]of Object.entries(t)){if(a==="$and"||a==="$or"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);n[a]=await Promise.all(c.map(async f=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_QUERY_VALUE",`${a} items must be query objects`);return Eo(f,e,r)}));continue}if(a==="$expr"){o.push({$expr:await js(c,e,r)});continue}const u=ue(e,a,r.resolveSchema);if(sp(c)&&(u.property.primal_type==="entity"||u.property.primal_type==="object")&&u.property.ref){if(c.schema!==u.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${u.canonicalName} references ${u.property.ref}, not ${c.schema??"undefined"}`);if(!r.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");const f=await r.normalizeNestedLogicform(c);n[u.canonicalName]={$in:f};continue}if(ip(c)){if(c.version!==void 0&&go(c),u.property.primal_type!=="entity"&&u.property.primal_type!=="object")throw new d("INVALID_RELATION_QUERY",`Relation query ${a} must resolve to an entity property`);if(!u.property.ref)throw new d("INVALID_RELATION_QUERY",`Nested LogicForm query requires an object property: ${u.canonicalName}`);if(c.schema!==u.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${u.canonicalName} references ${u.property.ref}, not ${c.schema}`);const f=r.resolveSchema?.(c.schema);if(!f)throw new d("SCHEMA_RESOLVER_REQUIRED",`Nested relation query requires Schema ${c.schema}`);const y=Ls(c.query,c.entity_id,f,r.plugins),h=await Eo(y,f,r);Object.assign(n,Us(h,u.canonicalName));continue}if(typeof c=="object"&&c!==null&&!Array.isArray(c)){const f=c,y=Object.entries(f).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?.(f),!h||y.length!==1||Object.keys(f).length!==1)throw new d("INVALID_PLUGIN_QUERY","A plugin Query Operator cannot be combined with other field operators");const[$,A]=h;if(!g)throw new Error(`Query Operator disappeared: ${$}`);n[u.canonicalName]={[$]:await g.normalize(A,{schema:u.schema,property:u.property,...r.resolveSchema?{resolveSchema:r.resolveSchema}:{},normalizeValue:(_,E,w)=>Bs(_,E,w,r)})};continue}}const p=await Fr(c,r),l=await Bs(p,u.schema,u.property,r),m=Ao(l);if(vr(m)){s(await xs(u.canonicalName,m,e,r));continue}n[u.canonicalName]=m}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},Vs=async(t,e,r)=>{if(!t)return;const n=await Eo(t,e,r);return Object.keys(n).length===0?void 0:n},Ys=(t,e,r)=>Promise.all((t??[]).map(n=>rr(n,e,r,Vs))),ap=(t,e,r)=>Ys(t??[],e,r),kt=(t,e)=>{throw new d("INVALID_PAGINATION",t,e)},cp=t=>{"skip"in t&&kt("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)&&kt("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&&kt("page requires limit",{page:n});return}if((!Number.isFinite(r)||r<0&&r!==-1||r>1&&!Number.isInteger(r))&&kt("limit must be -1, a non-negative integer, or a ratio between 0 and 1",{limit:r}),r===-1){n!==void 0&&kt("page cannot be used with unlimited results",{limit:r,page:n}),delete t.limit;return}n!==void 0&&(!Number.isInteger(n)||n<1)&&kt("page must be a positive integer starting from 1",{page:n}),t.page=n??1},up=t=>t.property.name,Fs=(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(c=>c.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 c=r?.(a.ref);if(!c)continue;const u=Fs(c,e,r,n,i);if(u)return`${a.name}_${u}`}},vs=(t,e,r,n)=>{try{const o=ue(t,e,n);return Fs(r,up(o),n,o.property.type)}catch{return}},_o=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?_o(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:_o(e)):[]],Qs=t=>t?Object.entries(t).flatMap(([e,r])=>{if((e==="$and"||e==="$or")&&Array.isArray(r))return r.flatMap(n=>Qs(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)?_o(n):[]}return e.startsWith("$")?[]:[e]}):[],dp=(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 c=r.resolveSchema?.(s),u={};for(const[p,l]of Object.entries(a))try{const m=ue(e,p,r.resolveSchema),f=c?ue(c,l,r.resolveSchema):void 0;u[m.canonicalName]=f?.canonicalName??l}catch{u[p]=l}o[s]=u}const i=[...(t.groupby??[]).map(s=>s.pred),...Qs(t.query)];for(const s of i){if(typeof s!="string")continue;let a;try{a=ue(e,s,r.resolveSchema)}catch{continue}for(const c of n){const u=r.resolveSchema?.(c),p=u&&vs(e,s,u,r.resolveSchema);p&&p!==a.canonicalName&&(o[c]={...o[c]??{},[a.canonicalName]:p})}}return Object.keys(o).length>0?{...t,propertyResolve:o}:t},lp=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`)}}},pp=async(t,e,r)=>{if(!t)return;const n=_s(t,e,r);return ft(t,n,r)},ft=async(t,e,r)=>{if(r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:wr([...Ae(r.plugins).flatMap(h=>h.locales??[]),...r.locales===void 0?[]:"locale"in r.locales?[r.locales]:r.locales])},...r.operators?{}:{operators:Ve(r.plugins)}},go(t),lp(t.propertyResolve),t.output&&t.output.type!=="data"&&t.output.type!=="sql"&&!Rn(t.output.type,r.plugins))throw new d("UNSUPPORTED_OUTPUT",`Output type is not supported: ${t.output.type}`);const o=oe(t),i={...r,normalizeNestedLogicform:async h=>{const g=_s(h,e,r);return ft(h,g,r)}};cp(o);const s=await pp(o.from,e,i),a=s&&r.resolveFromSchema?r.resolveFromSchema(s,e):e,c=await Vs(Ls(o.query,o.entity_id,a,r.plugins),a,i),u=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,...c?{autoCaseQuery:c}:{}};let l=await Ys(u,a,p),m=await ap(o.groupby,a,p);const f=m.filter(h=>fi(h,m,a,r.resolveSchema));if(f.length>0){const h=new Set(f.map(({name:g})=>g));m=m.filter(({name:g})=>!h.has(g)),l=[...l,...f]}return o.preds=l,m.length>0?o.groupby=m:delete o.groupby,s?o.from=s:delete o.from,c?o.query=c:delete o.query,dp(o,a,i)},Hs=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Je=(t,e)=>{if(t){if(!Hs(t,e))throw new d("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},mt=(t,e,r)=>{const n=Je(t,e)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},nr=(t,e,r)=>{if(!mt(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})},So=(t,e,r,n)=>{const o=ue(e,t,n);for(const i of o.relations)Je(r,i.targetSchema.id),nr(r,i.sourceSchema,i.property);nr(r,o.schema,o.property)},Gs=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),Hr=(t,e,r,n)=>{if(Ce(t)){zr(t,e,r,n);return}if(Array.isArray(t)){for(const o of t)Hr(o,e,r,n);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const o of Object.values(t))Hr(o,e,r,n)};function or(t,e,r,n,o){const i=t.schema?n(t.schema):e;t.schema&&Je(r,t.schema),typeof t.pred=="string"?So(t.pred,i,r,n):t.pred&&!Array.isArray(t.pred)&&or(t.pred,i,r,n,o);for(const s of Array.isArray(t.pred)?t.pred:[])typeof s=="string"?So(s,i,r,n):or(s,i,r,n,o);Gr(t.query,i,r,n,o)}const Gr=(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 c of s)Gr(c,e,r,n,o);continue}if(i==="$expr"){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const c=s.pred;typeof c=="object"&&c!==null&&!Array.isArray(c)&&or(c,e,r,n,o),Hr(s.condition,r,n,o)}continue}const a=ue(e,i,n);if(So(i,e,r,n),typeof s=="object"&&s!==null&&!Array.isArray(s))for(const[c,u]of Object.entries(s))_t(c,o)?.authorize?.(u,{schema:a.schema,property:a.property,resolveSchema:n,assertSchemaAllowed:p=>{Je(r,p)},assertPropertyAllowed:(p,l)=>nr(r,p,l),hasRowPermissions:p=>Je(r,p)?.rowPermissions!==void 0});if(Gs(s)){if(a.property.ref!==s.schema)continue;const c=n(s.schema);Je(r,c.id),On(s.entity_id)&&nr(r,c,Tn(c,o)),Gr(s.query,c,r,n,o);continue}Hr(s,r,n,o)}},zr=(t,e,r,n=[])=>{if(!t.schema){if(t.from){zr(t.from,e,r,n);return}throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const o=r(t.schema);if(Je(e,o.id),On(t.entity_id)&&nr(e,o,Tn(o,n)),t.from){zr(t.from,e,r,n);return}Gr(t.query,o,e,r,n);for(const i of t.preds??[])or(i,o,e,r,n);for(const i of t.groupby??[])or(i,o,e,r,n)},Wr=(t,e)=>{if(Array.isArray(t))return t.map(o=>Wr(o,e));if(typeof t!="object"||t===null||t instanceof Date)return t;const r=Object.entries(t).map(([o,i])=>[o,Wr(i,e)]),n=Object.fromEntries(r);return Gs(t)&&!Hs(t,"version")&&(n.version=e),n},fp=(t,e,r)=>{const n=[],o=(s,a)=>{if(s)for(const[c,u]of Object.entries(s))if((c==="$and"||c==="$or")&&Array.isArray(u))for(const p of u)o(p,a);else if(c==="$expr"&&typeof u=="object"&&u!==null&&!Array.isArray(u)){const p=u.pred;typeof p=="object"&&p!==null&&!Array.isArray(p)&&i(p,a)}else c.startsWith("$")||n.push(ue(a,c,r))},i=(s,a)=>{const c=s.schema?r(s.schema):a;typeof s.pred=="string"?n.push(ue(c,s.pred,r)):s.pred&&!Array.isArray(s.pred)&&i(s.pred,c);for(const u of Array.isArray(s.pred)?s.pred:[])typeof u=="string"?n.push(ue(c,u,r)):i(u,c);o(s.query,c)};o(t.query,e);for(const s of t.preds??[])i(s,e);for(const s of t.groupby??[])i(s,e);return n},mp=(t,e,r)=>{if(!t.schema)return[];const n=r(t.schema),o=new Set,i=[];for(const s of fp(t,n,r)){if(s.relations.length===0)continue;let a=-1;if(s.relations.forEach(({targetSchema:l},m)=>{e[l.id]?.rowPermissions!==void 0&&(a=m)}),a<0)continue;const c=s.relations.slice(0,a+1),u=c.map(({property:l})=>l.name).join("_");if(o.has(u))continue;o.add(u);let p={};for(const l of[...c].reverse())p={[l.property.name]:{schema:l.targetSchema.id,query:p}};i.push(p)}return i},Ut=(t,e,r,n,o,i)=>Ce(t)?yt(t,e,r,n,o,i):Array.isArray(t)?t.map(s=>Ut(s,e,r,n,o,i)):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(Object.entries(t).map(([s,a])=>[s,Ut(a,e,r,n,o,i)])),Io=(t,e,r,n,o,i)=>({...t,...t.query?{query:Ut(t.query,e,r,n,o,i)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Io(t.pred,e,r,n,o,i)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(s=>typeof s=="string"?s:Io(s,e,r,n,o,i))}:{}}),yt=(t,e,r,n=!0,o=new Set,i=[])=>{if(!e)return oe(t);if(!t.schema){const f=oe(t);return f.from&&(f.from=yt(f.from,e,r,n,new Set,i)),f}n&&zr(t,e,r,i);const s=Je(e,t.schema),a=o.has(t.schema),c=new Set(o).add(t.schema),u=oe(t);u.query&&(u.query=Ut(u.query,e,r,n,new Set,i)),u.preds&&(u.preds=u.preds.map(f=>Io(f,e,r,n,new Set,i))),u.from&&(u.from=yt(u.from,e,r,n,new Set,i));const p=a||t.from?void 0:s?.rowPermissions,l=(t.from?[]:mp(t,e,r)).map(f=>Ut(Wr(f,t.version),e,r,!1,c,i));p&&l.push(Ut(Wr(oe(p),t.version),e,r,!1,c,i));const m=[u.query,...l].filter(f=>f!==void 0&&Object.keys(f).length>0);return m.length===1?u.query=m[0]:m.length>1?u.query={$and:m}:delete u.query,u},yp=(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:c})=>a===s||c===s))throw new d("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${r}.${s}`,{schemaId:r,property:s})}},zs=(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")}},Ws=(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=zs(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)},hp=(t,e)=>{const r=Qi(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=zs(e,t.timeZone);let o=Ws({...n,...r},t.timeZone);if(o.getTime()<=e.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=Ws({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},t.timeZone)}return o},gp=(t,e)=>{const r=t.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(e.getTime()+n.ttlSeconds*1e3)]:[hp(n,e)]);return r.length===0?void 0:new Date(Math.min(...r.map(n=>n.getTime())))},bo=t=>t===void 0?{type:"undefined"}:typeof t=="bigint"?{type:"bigint",value:t.toString()}:typeof t=="number"&&!Number.isFinite(t)?{type:"number",value:String(t)}:t instanceof Date?{type:"date",value:t.toISOString()}:Array.isArray(t)?t.map(bo):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,bo(r)])):t,Ks=t=>pn.createHash("sha256").update(JSON.stringify(bo(t))).digest("hex"),Ap=t=>Ks({namespace:t.namespace,provider:t.provider,connectionId:t.connectionId,sql:t.sql,parameters:t.parameters}),wp=(t,e)=>Ks({namespace:t,source:e}),Ro=t=>t===void 0?{type:"undefined"}:typeof t=="bigint"?{type:"bigint",value:t.toString()}:typeof t=="number"&&!Number.isFinite(t)?{type:"number",value:String(t)}:t instanceof Date?{type:"date",value:t.toISOString()}:Array.isArray(t)?{type:"array",value:t.map(Ro)}:t&&typeof t=="object"?{type:"object",value:Object.entries(t).map(([e,r])=>[e,Ro(r)])}:t,No=t=>{if(t===null||typeof t!="object")return t;switch(t.type){case"undefined":return;case"bigint":return BigInt(t.value);case"number":return Number(t.value);case"date":return new Date(t.value);case"array":return t.value.map(No);case"object":return Object.fromEntries(t.value.map(([e,r])=>[e,No(r)]))}},$p=t=>JSON.stringify(Ro(t)),Ep=t=>{const e=No(JSON.parse(t));if(!(!Array.isArray(e)||e.some(r=>!r||typeof r!="object"||Array.isArray(r))))return e},_p=Number.MAX_SAFE_INTEGER;class Sp{#e;#t;#r;constructor(e,r={}){this.#e=e,this.#t=r.keyPrefix??"semanticdb:cache",this.#r=r.ownsClient??!1}#n(e){return`${this.#t}:query:${Ap(e)}`}#o(e,r){return`${this.#t}:source:${wp(e,r)}`}async get(e){const r=await this.#e.get(this.#n(e));if(r!==null)return Ep(r)}async set(e,r,n){const o=this.#n(e),i=$p(r),s=n.expiresAt?.getTime(),a=s??_p,c=this.#e.multi();s===void 0?c.set(o,i):c.set(o,i,{PXAT:s});for(const u of new Set(n.sources)){const p=this.#o(e.namespace,u);c.zRemRangeByScore(p,0,Date.now()),c.zAdd(p,{score:a,value:o})}await c.exec()}async invalidateSource(e,r){const n=this.#o(e,r),o=await this.#e.zRange(n,0,-1);o.length>0&&await this.#e.del(o),await this.#e.del(n)}async close(){this.#r&&await this.#e.close()}}const Ip=async(t={})=>{const e=va.createClient(t.url?{url:t.url}:{});return e.on("error",()=>{}),await e.connect(),new Sp(e,{...t.keyPrefix?{keyPrefix:t.keyPrefix}:{},ownsClient:!0})};function bp(t){if(!t||typeof t!="object")throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache configuration must be an object");const e=t;if(typeof e.id!="string"||e.id.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache id must not be empty");if(e.kind!=="redis")throw new d("INVALID_QUERY_CACHE_CONFIGURATION",`Unsupported query cache kind: ${String(e.kind)}`);if(typeof e.url!="string"||e.url.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Redis query cache url must not be empty");if(e.keyPrefix!==void 0&&(typeof e.keyPrefix!="string"||e.keyPrefix.trim().length===0))throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Redis query cache keyPrefix must not be empty");if(typeof e.namespace!="string"||e.namespace.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache namespace must not be empty")}const Rp=({namespace:t,...e})=>e,Np=async t=>Ip({url:t.url,...t.keyPrefix?{keyPrefix:t.keyPrefix}:{}});class Op{create;#e=new Map;constructor(e=Np){this.create=e}async get(e){bp(e);const r=Rp(e),n=this.#e.get(r.id);if(n){if(!Ho.isDeepStrictEqual(n.connection,r))throw new d("QUERY_CACHE_CONFIGURATION_MISMATCH",`Query cache configuration changed for id: ${r.id}`,{cacheId:r.id});return{store:await n.store,namespace:e.namespace}}const o=this.create(r),i={connection:r,store:o};this.#e.set(r.id,i);try{return{store:await o,namespace:e.namespace}}catch(s){throw this.#e.get(r.id)===i&&this.#e.delete(r.id),s}}async close(){const e=[...this.#e.values()];this.#e.clear();const n=(await Promise.allSettled(e.map(async({store:o})=>(await o).close()))).flatMap(o=>o.status==="rejected"?[o.reason]:[]);if(n.length>0)throw new AggregateError(n,"Failed to close one or more query cache connections")}}const Js=new Op,Xs=t=>Js.get(t),Tp=()=>Js.close(),Pp=async({cache:t,source:e})=>{if(typeof e!="string"||e.trim().length===0)throw new d("INVALID_QUERY_CACHE_SOURCE","Query cache source must not be empty");const r=await Xs(t);await r.store.invalidateSource(r.namespace,e)},Lp=Object.freeze({invalidateSource:Pp}),Cp=()=>{},Kr=(t,e)=>e.findSource(t.schemaId,t.mappingSource??t.source,t.connectionId),ir=(t,e,r)=>{if(It(t)){e.push(t.plan);return}if(Vi(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)ir(n,e,r);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const n of Object.values(t))ir(n,e,r)},sr=(t,e,r)=>{if(t.kind==="window"){sr(t.input,e,r);for(const n of t.partitionBy)sr(n,e,r);return}if(t.kind==="operator"){ir(t.query,e,r),t.input&&sr(t.input,e,r);for(const n of t.inputs??[])sr(n,e,r)}},_e=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 _e(o))r(i);else if(t.sourcePlan)for(const o of _e(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=[];ir(t.query,n,e),ir(t.having,n,e);for(const o of t.projections)sr(o.expression,n,e);for(const o of n)for(const i of _e(o))r(i);return[...e.values()]},ar=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()]},Zs=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})}},Dp=(t,e)=>{const r=[];for(const n of t){const o=Kr(n,e),i=n.mappingSource?o?.enrichments?.find(({source:s})=>s===n.source)?.freshness:o?.freshness;if(!i)return;r.push(i)}return r},Oo=async(t,e,r,n=Cp)=>{t=ea(t),r.signal?.throwIfAborted();const o=r.cache?Dp(e,r.schemaMappings):void 0;if(!r.cache||!o)return n("database"),Zs(r.provider,{...t,...r.signal?{signal:r.signal}:{}});const i={namespace:r.cache.namespace,provider:r.provider.kind,...r.connectionId?{connectionId:r.connectionId}:{},sql:t.sql,parameters:t.parameters};try{const a=await r.cache.store.get(i);if(r.signal?.throwIfAborted(),a)return n("cache"),[...a]}catch{r.signal?.throwIfAborted()}n("database");const s=await Zs(r.provider,{...t,...r.signal?{signal:r.signal}:{}});try{const a=gp(o,new Date);await r.cache.store.set(i,s,{sources:[...new Set(e.map(({source:c})=>c))],...a?{expiresAt:a}:{}})}catch{}return s},ea=t=>({...t,sql:Sl(t.sql)}),kp=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")},Up=(t,e,r)=>{const n=kp(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}},ta=async(t,e)=>{if(!mt(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(g=>mt(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:Up(t.idProperty.name,t.ids,i.maxInListItems),preds:r.map(g=>({pred:g.name,name:g.name}))},a=yt(s,e.permissions,e.resolveSchema,!0,new Set,e.plugins),c=await ft(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}),u=je(c,t.schema,e.operators,e.schemaMappings,{resolveSchema:e.resolveSchema,...o?{preferredConnectionId:o}:{},canUsePropertyRowIdentity:(g,$)=>mt(e.permissions,g.id,$)}),p=new Set(_e(u).map(g=>e.schemaMappings.findSource(g.schemaId,g.source,g.connectionId)?.connectionId).filter(g=>!!g));if(p.size>1)throw new d("CROSS_CONNECTION_ENTITY_HYDRATION_UNSUPPORTED",`Entity hydration cannot span connections: ${[...p].join(", ")}`);const l=[...p][0]??o,m=l&&e.providerForConnection?e.providerForConnection(l):i,f=we(u,m,e.operators),y=e.onCompiled?.(f,c,m,l),h=await Oo(f,_e(u),{provider:m,...l?{connectionId:l}:{},schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},y);return so(h,u.rowIdentity)},ra=t=>String(t),Mp=(t,e,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${ra(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=ra(r),o},na=(t,e)=>`${t}:${String(e)}`,qp=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 jp{#e;#t=new Map;#r=new Map;#n=new Map;#o=!1;constructor(e){this.#e=e}load=(e,r)=>{const n=na(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(bi(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=qp(s);let c,u;const p=new Promise((m,f)=>{c=m,u=f}),l=this.#n.get(e)??{schema:s,idProperty:a,loads:new Map};return l.loads.set(n,{id:r,resolve:m=>c?.(m),reject:m=>u?.(m)}),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),c=i._id===a?i:{...i,_id:a};o.set(na(e.schema.id,s),c)}}for(const[i,s]of e.loads){const a=o.get(i)??Mp(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 xp=(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})}},Bp=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=r.get(i.type),a=xp(o[i.name],i),c={property:i,requestEntity:n},u=s.normalizeResult?await s.normalizeResult(a,c):a,p=s.hydrateResult;if(!p){o[i.name]=u;return}o[i.name]=i.isArray&&Array.isArray(u)?await Promise.all(u.map(l=>p(l,c))):await p(u,c)}))}))},oa=5,Vp=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Yp=(t,e)=>{const r=e.properties.find(({type:n})=>n==="ID");return r?t[r.name]:void 0},Fp=(t,e)=>{const r=Qa.getNameProperty(e);t._title=t[r.name]??t._id},vp=(t,e)=>{const r=structuredClone(t);if(!("_id"in r)){const n=Yp(r,e);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},Qp=(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})},Hp=async(t,e,r)=>{const n=new jp(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 c=a.expandEntities&&i<oa;return Bp(a.rows,a.properties,r.semanticTypes,c?n.load:(u,p)=>Promise.resolve(p))}));for(const a of o)if(a.schema)for(const c of a.rows)Fp(c,a.schema);if(i>=oa)return;const s=new Map;for(const a of o)if(a.expandEntities)for(const c of a.properties){if(c.primal_type!=="entity"&&c.primal_type!=="object"||!c.ref)continue;const u=r.resolveSchema(c.ref);for(const p of a.rows){if(!(c.name in p))continue;const l=p[c.name],m=c.isArray?Array.isArray(l)?l:[l]:[l];for(const[f,y]of m.entries()){if(!Vp(y))continue;const h=vp(y,u);c.isArray?m[f]=h:p[c.name]=h,Qp(s,u,h,!c.isArray)}c.isArray&&(p[c.name]=m)}}o=[...s.values()]}},ia=async(t,e,r)=>{const n=t.map(o=>({...o}));return await Hp(n,e,r),n},To=t=>`'${t.replaceAll("'","''")}'`,sa=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}'`},cr=(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():To(t.toString());if(typeof t=="string")return e==="mysql"?sa(t):To(t);if(t instanceof Date){const r=e==="clickhouse"||e==="mysql"?t.toISOString().replace("T"," ").replace("Z",""):t.toISOString();return e==="mysql"?sa(r):To(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}`)},Gp=(t,e)=>t.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in e?cr(e[o],"clickhouse"):r}),zp=(t,e)=>t.replace(/:([1-9]\d*)\b/g,(r,n)=>{const o=Number(n)-1;return o in e?cr(e[o],"oracle"):r}),Wp=(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 c=Number(a)-1;if(c in e){r+=cr(e[c],"postgresql"),o+=s[0].length-1;continue}}}r+=i}}return r},Po=(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+=cr(e[o],r),o+=1;continue}n+=a}}return n},Kp=(t,e)=>Po(t,e,"mysql"),Lo=(t,e)=>Po(t,e,"snowflake"),Jp=(t,e)=>Po(t,e,"dameng"),Xp=(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 c=Number(a);if(c in e){r+=cr(e[c],"sqlserver"),o+=s[0].length-1;continue}}}r+=i}}return r},ot=(t,e)=>new Error(`Database driver "${t}" is not installed or could not be loaded. Install it with: npm install ${t}`,{cause:e}),ur=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`)},xe=(t,e)=>{throw new d("UNSUPPORTED_TABLE_SCOPE",`${t.kind} table discovery does not support a ${e} override`)},He=(t,e)=>Object.entries(t).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1],Me=(t,e)=>{const r=He(t,e);if(typeof r!="string"||!r)throw new d("INVALID_TABLE_METADATA",`Expected a non-empty metadata field: ${e}`);return r},aa=t=>{const e=Me(t,"table_name"),r=He(t,"table_database"),n=He(t,"table_schema"),o=Me(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"}},Zp=t=>t.map(aa),ht=async(t,e)=>{e.signal?.throwIfAborted(),ur(e);const r=[],n=c=>{const u=t.parameter(r.length,c);return r.push(c),u},o=e.database,i=e.schema;let s;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":i!==void 0&&xe(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&&xe(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&&xe(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&&xe(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(),Zp(a)},Co=t=>{if(ur(t),!t.table.trim())throw new d("INVALID_TABLE_NAME","Table name must not be empty")},Jr=(t,e)=>{const r=He(t,e);return typeof r=="string"?r:""},ef=t=>{const e=Me(t,"column_type"),r=He(t,"type_length"),n=He(t,"type_precision"),o=He(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},ca=t=>{const e=He(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:Me(t,"column_name"),type:ef(t),comment:Jr(t,"column_comment"),...r!==void 0?{primaryKey:r}:{}}},tf=(t,e)=>{const r=[],n=u=>{const p=t.parameter(r.length,u);return r.push(u),p},o=n(e.table),{database:i,schema:s}=e;let a,c;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":{s!==void 0&&xe(t,"schema");const u=`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 ${u}`,c=`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 ${u} ORDER BY c.ORDINAL_POSITION`;break}case"postgresql":{i!==void 0&&xe(t,"database");const u=`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 ${u} AND c.relkind IN ('r', 'v', 'm', 'p', 'f')`,c=`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 ${u} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`;break}case"sqlserver":{const u=i!==void 0?`${t.quoteIdentifier(i)}.`:"",p=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"SCHEMA_NAME()"}`,l=`JOIN ${u}sys.schemas s ON s.name = c.TABLE_SCHEMA JOIN ${u}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 ${u}INFORMATION_SCHEMA.TABLES c ${l}LEFT JOIN ${u}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}`,c=`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 ${u}sys.indexes i JOIN ${u}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 ${u}INFORMATION_SCHEMA.COLUMNS c ${l}JOIN ${u}sys.columns sc ON sc.object_id = o.object_id AND sc.name = c.COLUMN_NAME LEFT JOIN ${u}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 u=`${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 ${u}.TABLES c WHERE ${p}`,c=`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 ${u}.COLUMNS c WHERE ${p} ORDER BY c.ORDINAL_POSITION`;break}case"oracle":case"dameng":{i!==void 0&&xe(t,"database");const u=`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 ${u}`,c=`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 ${u} ORDER BY c.COLUMN_ID`;break}case"clickhouse":{s!==void 0&&xe(t,"schema");const u=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 = ${u}`,c=`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 = ${u} ORDER BY c.position`;break}default:throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`No table description SQL for provider: ${t.kind}`)}return{tableSql:a,columnSql:c,parameters:r}},ua=(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(".")},Mt=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},Do=async(t,e,r)=>{if(e.includeSample===!1)return r;const n=ua(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 Mt(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},rf=async(t,e)=>{let{database:r,schema:n}=e;if(r===void 0||n===void 0){const[l]=await Mt(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??=Me(l,"table_database"),n??=Me(l,"table_schema")}const o=ua(t,{name:e.table,database:r,schema:n}),i=await Mt(t,e,`DESCRIBE TABLE EXTENDED ${o}`),s=[];let a=!0,c=!1,u="",p="table";for(const l of i){const m=He(l,"col_name"),f=He(l,"data_type"),y=(m==="# Partition Information"||m==="# Detailed Table Information")&&!f;(m===""||y)&&(a=!1),y&&m==="# Detailed Table Information"&&(c=!0),a?s.push({name:Me(l,"col_name"),type:Me(l,"data_type"),comment:Jr(l,"comment")}):c&&m==="Comment"?u=Jr(l,"data_type"):c&&m==="Type"&&f==="VIEW"&&(p="view")}if(!s.length)throw new d("INVALID_TABLE_METADATA","Databricks description did not contain columns");return Do(t,e,{columns:s,tableInfo:{name:e.table,database:r,schema:n,type:p,comment:u}})},nf=async(t,e)=>{e.database!==void 0&&xe(t,"database"),e.schema!==void 0&&xe(t,"schema");const n=(await Mt(t,e,`DESC ${t.quoteIdentifier(e.table)}`)).map(ca);if(!n.length)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);return Do(t,e,{columns:n,tableInfo:{name:e.table,type:"table",comment:""}})},Xe=async(t,e)=>{if(e.signal?.throwIfAborted(),Co(e),t.kind==="databricks")return rf(t,e);if(t.kind==="maxcompute")return nf(t,e);const{tableSql:r,columnSql:n,parameters:o}=tf(t,e),i=await Mt(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={...aa(s),comment:Jr(s,"table_comment")},c=(await Mt(t,e,n,o)).map(ca);return Do(t,e,{columns:c,tableInfo:a})},of=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}`},sf=t=>t===null?"Nullable(String)":typeof t=="boolean"?"Bool":typeof t=="number"?"Float64":t instanceof Date?"DateTime64(3)":"String",da=t=>t instanceof Date?t.toISOString().replace("T"," ").replace("Z",""):t;class af{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 ot("@clickhouse/client",r)});return e({url:of(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}:${sf(r)}}`}displayQuery(e,r){return Gp(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}`,da(i)]));return(await r.query({query:e.sql,format:"JSONEachRow",query_params:n,...e.signal?{abort_signal:e.signal}:{}})).json()}getTableList(e){return ht(this,e)}describeTable(e){return Xe(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,c)=>[`p${c}`,da(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 c=JSON.parse(a);if(typeof c!="object"||c===null||Array.isArray(c))throw new Error("ClickHouse provider expected object rows");return c}):[]}}async close(){const e=this.#t;if(!e)return;await(await e).close(),this.#t=void 0}}const cf=t=>[".azuredatabricks.net",".databricks.azure.cn",".databricks.azure.us"].some(e=>t.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]?.endsWith(e)),uf=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??(cf(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)}`)},df=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 lf{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 ot("@databricks/sql",r)})).DBSQLClient;if(this.#e)try{await e.connect(uf(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 Lo(e,r)}dateBucket(e,r){if(!new Set(["second","minute","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(df)}),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 Xe(this,{...e,...r!==void 0?{database:r}:{},...n!==void 0?{schema:n}:{}})}async getTableList(e){e.signal?.throwIfAborted(),ur(e);const r=u=>this.execute({sql:u,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[u]=await r("SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!u)throw new Error("Databricks current namespace was not returned");n??=Me(u,"table_database"),o??=Me(u,"table_schema")}const i=`${this.quoteIdentifier(n)}.${this.quoteIdentifier(o)}`,s=await r(`SHOW TABLES IN ${i}`),a=await r(`SHOW VIEWS IN ${i}`),c=new Map;for(const u of s){const p=Me(u,"tableName");c.set(p,{name:p,database:n,schema:o,type:"table"})}for(const u of a){const p=Me(u,"viewName");c.set(p,{name:p,database:n,schema:o,type:"view"})}return[...c.values()].sort((u,p)=>u.name.localeCompare(p.name))}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}const la=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}`)},pf=t=>{const{host:e,port:r,...n}=t;return{...n,connectString:t.connectString??`${e??"localhost"}:${r??5236}`}};class ff{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={...pf(this.#e),poolAlias:typeof this.#e.poolAlias=="string"?this.#e.poolAlias:`semanticdb-${pn.randomUUID()}`};if(this.#t)return this.#t.createPool(e);const{default:r}=await import("dmdb").catch(n=>{throw ot("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 Jp(e,r.map(la))}dateBucket(e,r){if(r==="second")return`CAST(${e} AS DATE)`;const n={minute:"MI",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 ht(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}describeTable(e){return Xe(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(la),{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 Kp(t,e)},dateBucket(t,e){const r={second:"%Y-%m-%d %H:%i:%s",minute:"%Y-%m-%d %H:%i:00",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,n){const o=this.quoteIdentifier(e),i=this.quoteIdentifier(r);return{joinSql:`CROSS JOIN JSON_TABLE(CASE WHEN JSON_TYPE(${t}) = 'ARRAY' THEN ${t} ELSE JSON_ARRAY() END, '$[*]' COLUMNS (${i} ${n==="string"?"VARCHAR(4000)":"JSON"} PATH '$')) AS ${o}`,valueExpression:`${o}.${i}`}}},mf={connectionLimit:30,maxIdle:10,idleTimeout:6e4,enableKeepAlive:!0,keepAliveInitialDelay:0};class Xr{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 ot("mysql2",r)});return e({...mf,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,o){const i=X.expandArray?.bind(X);if(!i)throw new Error("MySQL-compatible array expansion is unavailable");return i(e,r,n,o)}async execute(e){return(await this.#n(e,!1)).rows}async runSQL(e){return this.#n(e,!0)}getTableList(e){return ht(this,e)}describeTable(e){return Xe(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 yf extends Xr{kind="doris";constructor(e={}){super(e)}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}`}}}class hf extends Xr{kind="gbase";supportsRecursiveCte=!1;constructor(e={}){super({...e,connection:{port:5258,...e.connection}})}}class gf{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(),ur(e),this.#e.getTableList){const n=await this.#e.getTableList(e);return e.signal?.throwIfAborted(),n}return e.database!==void 0&&xe(this,"database"),e.schema!==void 0&&xe(this,"schema"),(await this.execute({sql:"SHOW TABLES",parameters:[],...e.signal?{signal:e.signal}:{}})).map(n=>({name:Me(n,"table_name"),type:"table"}))}async close(){this.#t||(await this.#e.close(),this.#t=!0)}async describeTable(e){if(e.signal?.throwIfAborted(),Co(e),!this.#e.describeTable)return Xe(this,e);const r=await this.#e.describeTable(e);return e.signal?.throwIfAborted(),r}}class Af extends Xr{kind="mysql";constructor(e={}){super(e)}}const pa=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}`)},wf=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class $f{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 zp(e,r.map(pa))}dateBucket(e,r){if(r==="second")return`CAST(${e} AS DATE)`;const n={minute:"MI",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 ot("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 ht(this,e)}describeTable(e){return Xe(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(pa),{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?wf(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 Ef{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{default:e}=await import("pg").catch(r=>{throw ot("pg",r)});return new e.Pool(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 Wp(e,r)}dateBucket(e,r){if(!new Set(["second","minute","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})`}normalizeStringArray(e){const r=`to_jsonb(${e})`;return`(CASE WHEN ${e} IS NULL THEN ARRAY[]::text[] WHEN jsonb_typeof(${r}) = 'array' THEN ARRAY(SELECT jsonb_array_elements_text(${r})) ELSE ARRAY[${r} #>> '{}'] END)`}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 ht(this,e)}describeTable(e){return Xe(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 fa=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}`)},_f=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class Sf{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 ot("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 Lo(e,r.map(fa))}dateBucket(e,r){if(!new Set(["second","minute","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 ht(this,e)}describeTable(e){return Xe(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(fa);return new Promise((i,s)=>{const a=e.signal,c={};let u=!1;const p=m=>{u||(u=!0,a?.removeEventListener("abort",l),m())},l=()=>{c.current?.cancel(),a&&p(()=>s(_f(a)))};a?.addEventListener("abort",l,{once:!0}),c.current=n.execute({sqlText:e.sql,binds:o,complete:(m,f,y)=>{if(m){p(()=>s(m));return}if(!(r&&y===void 0)&&!Array.isArray(y)){p(()=>s(new Error("Snowflake provider expected an array result")));return}const h=r?f.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 If=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}}},bf=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}`)},Rf=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError"),Nf=t=>t instanceof Error?t:new Error("SQL Server query failed",{cause:t}),Of=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 Tf{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 ot("mssql",n)}),r=new e.ConnectionPool(If(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`${Of(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 Xp(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 ht(this,e)}describeTable(e){return Xe(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}`,bf(i))),new Promise((i,s)=>{const a=e.signal;let c=!1;const u=l=>{c||(c=!0,a?.removeEventListener("abort",p),l())},p=()=>{o.cancel(),a&&u(()=>s(Rf(a)))};a?.addEventListener("abort",p,{once:!0}),o.query(e.sql).then(l=>{if(!Array.isArray(l.recordset)&&!(r&&l.recordset===void 0)){u(()=>s(new Error("SQL Server provider expected an array result")));return}u(()=>i({rows:l.recordset??[],...l.rowsAffected?{affectedRows:l.rowsAffected.reduce((m,f)=>m+f,0)}:{}}))},l=>u(()=>s(Nf(l)))),a?.aborted&&p()})}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}class Pf extends Xr{kind="starrocks";constructor(e={}){super(e)}arrayContains(e,r){return`array_contains(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`, UNNEST(${e}) AS ${o}(${i})`,valueExpression:`${o}.${i}`}}}const Be=t=>{const{id:e,kind:r,...n}=t;return n},Lf=Object.freeze([{kind:"mysql",create:t=>new Af({connection:Be(t)})},{kind:"doris",create:t=>new yf({connection:Be(t)})},{kind:"gbase",create:t=>new hf({connection:Be(t)})},{kind:"starrocks",create:t=>new Pf({connection:Be(t)})},{kind:"maxcompute",create:t=>new gf(Be(t))},{kind:"postgresql",create:t=>new Ef({connection:Be(t)})},{kind:"clickhouse",create:t=>new af(Be(t))},{kind:"databricks",create:t=>new lf({connection:Be(t)})},{kind:"dameng",create:t=>new ff({connection:Be(t)})},{kind:"snowflake",create:t=>new Sf({connection:Be(t)})},{kind:"sqlserver",create:t=>new Tf({connection:Be(t)})},{kind:"oracle",create:t=>new $f({connection:Be(t)})}]);class ma{#e=new Map;constructor(e=Lf){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 ya=new ma,ha=(t,e=ya)=>e.create(t);class Cf{create;#e=new Map;#t=new Set;#r=[];constructor(e=ha){this.create=e}get(e){const r=this.#e.get(e.id);if(r&&Ho.isDeepStrictEqual(r.connection,e))return r.provider;const n=this.create(e);return this.#e.set(e.id,{connection:{...e},provider:n}),r&&r.provider!==n&&this.#n(r.provider),n}#n(e){const r=Promise.resolve().then(()=>e.close()).then(()=>{this.#t.delete(r)},n=>{this.#t.delete(r),this.#r.push(n)});this.#t.add(r)}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()),...this.#t]),n=this.#r.splice(0);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 Zr=new Map,Df=t=>{const e=Zr.get(t);if(e)return e;const r=new Cf(n=>ha(n,t));return Zr.set(t,r),r},en=(t,e=ya)=>Df(e).get(t),kf=async()=>{const t=[...Zr.values()];Zr.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")},ga=async()=>{const e=(await Promise.allSettled([kf(),Tp()])).flatMap(r=>r.status==="rejected"?[r.reason]:[]);if(e.length>0)throw new AggregateError(e,"Failed to close one or more SemanticDB resources")},Uf=async t=>{if(t.signal?.throwIfAborted(),!t.sql.trim())throw new d("INVALID_SQL","SQL must not be empty");const e=en(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},Mf=async t=>{t.signal?.throwIfAborted(),ur(t);const e=en(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},qf=async t=>{t.signal?.throwIfAborted(),Co(t);const e=en(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},jf=Object.freeze({runSQL:Uf,getTableList:Mf,describeTable:qf,close:ga}),xf=t=>{const{name:e,kind:r}=t;switch(r){case"boolean":return{name:e,kind:r,type:fe.BOOLEAN,sqlType:"BOOLEAN"};case"date":return{name:e,kind:r,type:fe.TIMESTAMP,sqlType:"TIMESTAMP"};case"number":return{name:e,kind:r,type:fe.DOUBLE,sqlType:"DOUBLE"};case"string":return{name:e,kind:r,type:fe.VARCHAR,sqlType:"VARCHAR"}}},Bf=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="true"?!0:t===0||t==="0"||t==="false"?!1:!!t,Vf=(t,e)=>{if(t==null)return null;switch(e.kind){case"boolean":return fe.jsToDuckDBValue(Bf(t),fe.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:fe.jsToDuckDBValue(r,fe.TIMESTAMP)}case"number":{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?fe.jsToDuckDBValue(r,fe.DOUBLE):null}case"string":return typeof t=="string"?fe.jsToDuckDBValue(t,fe.VARCHAR):typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?fe.jsToDuckDBValue(t.toString(),fe.VARCHAR):typeof t=="symbol"?fe.jsToDuckDBValue(t.description??"",fe.VARCHAR):typeof t=="function"?fe.jsToDuckDBValue(t.name,fe.VARCHAR):fe.jsToDuckDBValue(JSON.stringify(t),fe.VARCHAR)}},Yf=t=>{if(t==null)return null;if(t instanceof Date)return fe.jsToDuckDBValue(t,fe.TIMESTAMP);if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"||typeof t=="string")return t;if(Buffer.isBuffer(t))return fe.blobValue(t);throw new TypeError(`Unsupported DuckDB coordinator parameter: ${typeof t}`)};class cn{instance;connection;kind="duckdb";supportsHavingAlias=!0;supportsRecursiveCte=!0;static async create(){const e=await fe.DuckDBInstance.create(":memory:"),r=await e.connect();return new cn(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 Lo(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(xf),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 c of o){const u=Vf(a[c.name],c);u===null?s.appendNull():s.appendValue(u,c.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(Yf));return e.signal?.throwIfAborted(),r.getRowObjectsJS()}close(){return this.connection.closeSync(),this.instance.closeSync(),Promise.resolve()}}const ko="__sdb_total__",Ff="__sdb_total_source__",Uo=t=>{const e={...t,orderBy:[]};return delete e.pagination,e},vf=t=>{const e={...t};return delete e.limit,delete e.page,e},Mo=(t,e)=>({sql:`SELECT ${e.aggregateFunction("count")} AS ${e.quoteIdentifier(ko)} FROM ${e.tableAlias(`(${t.sql})`,Ff)}`,parameters:t.parameters}),tn=t=>{if(t.length===0)return 0;const e=t[0]??{},r=e[ko]??e[ko.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},qt="__semanticdb_coordinator__",Aa=(t,e)=>{const r=new Set;for(const n of _e(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]},dr=(t,e)=>!!t.subplans&&new Set(t.subplans?.flatMap(r=>Aa(r,e))).size>1||!!(t.sourcePlan&&dr(t.sourcePlan,e)),Qf=(t,e)=>({name:t,expression:{kind:"column",property:t,column:t,qualifier:e}}),Hf=(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"},wa=(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"?Hf(e,n):"string";return{name:n,kind:i}})},Gf=(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=>Qf(n,e)),...t.columnProperties?{columnProperties:t.columnProperties}:{},groupBy:[],orderBy:[],rowIdentity:{kind:"generated"}}},zf=(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",qr(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")},$a=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:jr(n,r.names,r.separator,r.nullLabel)}))}return e.rowIdentity.kind==="singleton"?t.map(r=>({...r,_id:"0"})):[...t]},rn=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&&dr(t.sourcePlan,e.schemaMappings)){const s=await rn(t.sourcePlan,e),a=await cn.create();try{const c="__federated_source";await a.materialize(c,wa(t.sourcePlan,s.rows),s.rows);const u={...t,source:c};delete u.sourcePlan,delete u.sourceLogicform,delete u.connectionId;const p=we(u,a,e.operators),l=Mo(we(Uo(u),a,e.operators),a),m=e.onCompiled({compiled:p,connectionId:qt,provider:a,type:"computation",logicform:e.logicform});e.onCompiled({compiled:l,connectionId:qt,provider:a,type:"total",logicform:e.logicform})("database");const y=await a.execute({...l,...e.signal?{signal:e.signal}:{}});m("database");const h=await a.execute({...p,...e.signal?{signal:e.signal}:{}});return{rows:$a(h,t),total:tn(y),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=Aa(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 c=a[0],u=e.providerForConnection(c);r.set(c,u.kind);const p=we(s,u,e.operators),l=e.onCompiled({compiled:p,connectionId:c,provider:u,type:"computation",logicform:e.logicform}),m=await Oo(p,_e(s),{provider:u,connectionId:c,schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},l),f=await lt(m,s.projections,e.operators);return{child:s,rows:zf(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 cn.create();try{const s=n.flatMap(({rows:h})=>h),a=[];for(const[h,{child:g,rows:$}]of n.entries()){const A=`__federated_branch_${h}`;await i.materialize(A,wa(g,s),$),a.push(Gf(g,A))}const c={...t,subplans:a},u=we(c,i,e.operators),p=Mo(we(Uo(c),i,e.operators),i),l=e.onCompiled({compiled:u,connectionId:qt,provider:i,type:"computation",logicform:e.logicform});e.onCompiled({compiled:p,connectionId:qt,provider:i,type:"total",logicform:e.logicform})("database");const f=await i.execute({...p,...e.signal?{signal:e.signal}:{}});l("database");const y=await i.execute({...u,...e.signal?{signal:e.signal}:{}});return{rows:$a(y,t),total:tn(f),connections:[...r].map(([h,g])=>({connectionId:h,provider:g}))}}finally{await i.close()}},Wf=new Set(["$sply","$splm","$splq","$splw","$yoy","$mom","$qoq","$wow","$yoyd","$momd","$qoqd","$wowd","$percentage"]),nn=t=>!H(t)||!Array.isArray(t.properties)?[]:t.properties.filter(H),Ea=new Set(["second","minute","hour","day","week","month","quarter","year"]),Kf={weekday:"weekday",toQuarter:"quarter",toMonth:"month",toWeek:"week",toDay:"day",toHour:"hour",toWeekday:"weekday"},_a=(t,e)=>{const r=e[t];return H(r)?r:Object.values(e).find(n=>H(n)&&(n.id===t||n._id===t))},Sa=(t,e)=>{const r=t&&e?nn(_a(t,e)).find(o=>o.type==="timestamp"):void 0,n=r?.name??r?.id??r?._id;return typeof n=="string"&&n.length>0?n:void 0},Ia=(t,e,r)=>{const n=_a(t,r);if(!n)return;const i=nn(n).map(s=>{const c=[s.id,s._id,s.name].filter(u=>typeof u=="string").filter(u=>e===u||e.startsWith(`${u}_`)).sort((u,p)=>p.length-u.length)[0];return c?{property:s,key:c}: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"?Ia(i.property.ref,e.slice(i.key.length+1),r):void 0},jt=(t,e,r)=>{const n=(o,i,s)=>{const u=nn(r[o]).map(y=>{const h=typeof y.id=="string"?y.id:void 0,g=typeof y.name=="string"?y.name:void 0,A=[h,g].filter(_=>!!_&&(i===_||i.startsWith(`${_}_`))).sort((_,E)=>E.length-_.length)[0];return A?{property:y,key:A}:void 0}).filter(y=>!!y).sort((y,h)=>h.key.length-y.key.length)[0];if(!u)return;const p=String(u.property.id??u.property.name),l=i===u.key?"":i.slice(u.key.length+1);if(!l)return p;const m=typeof u.property.ref=="string"?u.property.ref:void 0;if(!m||s.has(m))return;const f=n(m,l,new Set(s).add(m));return f?`${p}_${f}`:void 0};return n(t,e,new Set([t]))},qo=(t,e,r)=>{const n=nn(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 qo(n.ref,e.slice(n.id.length+1),r)}},ba=t=>Object.keys(t).filter(e=>e!=="$and"&&e!=="$or"),H=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Ra=t=>typeof t=="string"&&/^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?$/.test(t),Na=t=>{if(!H(t))return t;if(H(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},Jf=t=>typeof t=="string"&&t.length>0||typeof t=="number"&&Number.isSafeInteger(t),Xf=(t,e)=>{if(!e)return;const r=e[t]??Object.values(e).find(c=>H(c)&&(c.id===t||c._id===t));if(!H(r))return;const n=r.hierarchy,o=Array.isArray(n)?n:H(n)&&Array.isArray(n.levels)?n.levels:void 0;if(!o)return;const i=o.map(c=>{if(!H(c)||typeof c.name!="string")return;const u=c.codeLength??c.code_length;return Number.isInteger(u)&&Number(u)>0?{name:c.name,codeLength:Number(u)}:void 0});if(i.length===0||i.some(c=>c===void 0))return;const s=o[0],a=Array.isArray(n)?H(s)&&s.use_full_length===!0?"zero-padded":"compact":H(n)&&n.storage==="zero-padded"?"zero-padded":"compact";return{levels:i.filter(c=>c!==void 0),storage:a}},Zf=(t,e,r)=>{const n=Xf(t,r);if(!n)return;const o=String(e),i=n.levels.reduce((a,c)=>a+c.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})},em=(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}))]},jo=(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=>H(y)?jo(y,e):y);continue}if(!H(i)){r[o]=i;continue}const s=i.entity_id;if(typeof i.schema!="string"||!H(i.query)||!Jf(s)){r[o]=i;continue}const a=i.entity_level,c=typeof a=="string"&&a.length>0?a:Zf(i.schema,s,e);if(!c){r[o]=i;continue}const{entity_id:u,entity_level:p,...l}=i,m=jo(i.query,e),f=Object.keys(l).filter(y=>y!=="schema"&&y!=="version"&&y!=="query");(Object.keys(m).length>0||f.length>0)&&(r[o]={...l,query:m}),n.push({pred:{operator:"$hierarchyLevel",pred:o,args:{level:c}},condition:s})}return em(r,n)},tm=(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}},Oa=(t,e)=>{if(!H(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(!H(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(!H(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}:{}}},Ze=(t,e,r)=>{if(Array.isArray(t))return t.map(c=>Ze(c,e,r));if(!H(t))return t;const n=Na(t);if(n!==t)return n;const o=t,i=typeof o.schema=="string"?o.schema:r,s={};for(const[c,u]of Object.entries(o))c==="skip"||c==="_snapshot"||c==="_snapshots"||(s[c]=Ze(u,e,i));if(typeof o.version=="string"&&/^1\./.test(o.version)&&(s.version="2.0"),Array.isArray(o.groupby)){const c=o.groupby;s.groupby=c.map(u=>{if(!H(u))return u;const p=Ze(u,e,i);if(!H(p))return p;const{_id:l,level:m,...f}=p;if(typeof l=="string"&&l.startsWith("$")){const h=l.slice(1);if(!Ea.has(h))throw new d("INVALID_LEGACY_TIME_GROUPBY",`Unsupported legacy time groupby: ${l}`,{groupby:l});const g=Sa(i,e);if(!g)throw new d("LEGACY_TIME_GROUPBY_TIMESTAMP_REQUIRED",`Legacy time groupby ${l} requires a timestamp Property in Schema ${i??"(unknown)"}`,{groupby:l,schemaId:i});return{...f,pred:g,operator:"$dateBucket",args:{...H(f.args)?f.args:{},granularity:h},...f.name===void 0?{name:`${g}(${h})`}:{}}}const y={...f,...f.pred===void 0&&typeof l=="string"?{pred:l}:{}};return typeof m=="string"&&(y.operator="$dateBucket",y.args={...H(y.args)?y.args:{},granularity:m}),y})}const a=o.skip;if(typeof a=="number"&&Number.isInteger(a)&&a>=0){const c=o.limit;a===0?delete s.skip:typeof c=="number"&&Number.isInteger(c)&&c>0&&a%c===0?s.page=a/c+1:s.skip=a}else a!==void 0&&(s.skip=Ze(a,e,i));if(o.operator&&typeof o.operator=="string"){const c=tm(o.operator,H(s.args)?s.args:{});c.operator&&(s.operator=c.operator),s.args=c.args;const u=typeof o.pred=="string"&&o.pred.startsWith("$")?o.pred.slice(1):"",p=Kf[u];if(o.operator==="$count"&&(Ea.has(u)||p)){const l=Sa(i,e);if(!l)throw new d("LEGACY_TIME_COUNT_TIMESTAMP_REQUIRED",`Legacy $count($${u}) requires a timestamp Property in Schema ${i??"(unknown)"}`,{schemaId:i,pred:o.pred});s.operator="$countDistinct",s.pred=p?{operator:`$${p}`,pred:l}:{operator:"$dateBucket",pred:l,args:{granularity:u}}}if(o.operator==="$comp"||o.operator==="$compabs"){const l=H(s.args)?s.args.preds:void 0;if(!Array.isArray(l)||l.length!==2)throw new d("INVALID_LEGACY_COMP_ARGS",`${o.operator} requires exactly 2 preds in args.preds`);const m={operator:"$subtract",pred:l,args:{nullAsZero:!0}};s.operator=o.operator==="$comp"?"$subtract":"$abs",s.pred=o.operator==="$compabs"?m:l,s.args=o.operator==="$comp"?{nullAsZero:!0}:{}}if(o.operator==="$switch"){const l=H(s.params)?s.params:s.args;s.operator="$case",s.args=Oa("$switch",l),delete s.params}if(o.operator==="$piecewise"){const l=typeof s.pred=="string"?s.pred:typeof o._id=="string"?o._id:void 0;if(e&&i&&l&&Ia(i,l,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:l});const m=H(s.params)?s.params:H(s.args)?s.args:{};s.operator="$case",s.args=Array.isArray(m.cases)?Oa("$piecewise",m):{mode:"auto",buckets:Number.isInteger(m.buckets)?m.buckets:10},delete s.params}Wf.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:Ze(o.params,e,i)}:Ze(o.params,e,i)),o.inputs!==void 0&&s.pred===void 0&&Array.isArray(o.inputs)&&(s.pred=o.inputs.map(c=>Ze(c,e,i)),H(s.args)&&delete s.args.inputs),o.pred===void 0&&typeof o.operator=="string"&&o.operator==="$sql"&&typeof o.sql=="string"&&(s.args={...H(s.args)?s.args:{},sql:o.sql},delete s.sql),o.$options!==void 0&&s.$regex!==void 0?(s.args={...H(s.args)?s.args:{},options:o.$options},delete s.$options):typeof o.$eq=="string"&&typeof o.$options=="string"?(s.args={...H(s.args)?s.args:{},options:o.$options},delete s.$options):"$options"in o&&Ra(o.$gte)&&Ra(o.$lte)&&delete s.$options,o.query&&H(o.query)&&(s.query=rm(o.query,e,i)),s},rm=(t,e,r)=>{const n=Ze(t,e,r);for(const[o,i]of Object.entries(n))n[o]=Na(i);return jo(n,e)},Ta=(t,e)=>{const r=H(t)?t:void 0,n=Ze(t,e);if(!H(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],Ta(o,e)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),e?nm(n,e):n},nm=(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 c of n)H(c)&&typeof c.schema=="string"&&i.add(c.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(c=>H(c)&&typeof c.pred=="string"?jt(o,c.pred,e):void 0):[];for(const c of i)if(Array.isArray(r.groupby)&&r.groupby.map((u,p)=>{if(!H(u)||typeof u.pred!="string")return u;const l=c===o?jt(c,u.pred,e):jt(c,qo(o,s[p]??"",e)??u.pred,e);if(!l)return u;const m=l.split("_").at(-1)??u.pred;return{...u,pred:l,name:m}}),H(r.query))for(const u of ba(r.query)){const p=jt(o,u,e);if(!(c===o?p:jt(c,(p&&qo(o,p,e))??u,e))&&c===o)throw new Error(`Cannot align legacy query field ${u} in Schema ${c}`)}const a={...r};if(Array.isArray(r.groupby)&&(a.groupby=r.groupby.map((c,u)=>{if(!H(c)||typeof c.pred!="string")return c;const p=s[u];return p?{...c,pred:p}:c})),H(r.query)){const c=r.query,u=ba(c).map(p=>[jt(o,p,e)??p,c[p]]);a.query=Object.fromEntries(u)}return a},om=t=>{const e=(r,n)=>{if(Array.isArray(r)){r.forEach((o,i)=>e(o,`${n}[${i}]`));return}if(H(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,"$")},xo=t=>{if(Array.isArray(t))return t.map(xo).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,xo(o)]).filter(([,n])=>n!==void 0);if(!(e.length>0&&r.length===0))return Object.fromEntries(r)},im=t=>{const e=t.constraints?.enum??t.enum;return Array.isArray(e)?e:typeof e=="string"&&e.length>0?e.split(","):void 0},sm=(t,e,r)=>{const n=t.comparable;if(!r||n!=null&&typeof n!="string")return t.comparable;const o=n==="asc"?1:n==="desc"?-1:n==null&&t.is_comparable===!0?t.comparable_order===-1?-1:1:void 0;if(o===void 0||t.isArray===!0||t.type!=="string"&&t.type!=="category"||!e)return;const i=e.map(s=>Array.isArray(s)?s[0]:s);if(!(i.length===0||i.some(s=>typeof s!="string")))return{values:[...new Set(i)],direction:o}},am=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}},cm=(t,e=[],r=!0)=>{const n=Ae(e),o={},i=new Set(n.flatMap(s=>[...s.schemaMetadata?.keys??[],...s.legacySchemaKeys??[]]));for(const[s,a]of Object.entries(t)){const c=xo(a),u=c,l=(Array.isArray(u.properties)?u.properties:[]).some(_=>_.is_observation===!0)||u.is_observation===!0,m=u.is_snapshot===!0,f=typeof c.id=="string"&&c.id.length>0?c.id:r&&typeof c._id=="string"&&c._id.length>0?c._id:c.id,{properties:y}=c,h=Object.fromEntries(Object.entries(c).filter(([_])=>(r?!["_id","_sid","sid","is_observation","is_snapshot"].includes(_):_!=="properties")&&_!=="properties"&&!i.has(_))),g=y.map(_=>{const E=_,w=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,...C}=E,k=r?im(E):void 0,T=sm(E,k,r),G=am(R),v=r&&T!==void 0&&E.type==="string"?"category":E.type==="object"?"entity":E.type,q=v==="entity"||E.primal_type==="entity"||E.primal_type==="object";return{...r?Object.fromEntries(Object.entries(C).filter(([Y])=>!["_id","_sid","sid","is_observation","is_comparable","comparable_order","comparable","enum"].includes(Y)&&(Y!=="level"||q))):C,type:v,...r&&k&&!Array.isArray(E.constraints?.enum)?{constraints:{...E.constraints,enum:k}}:{},...E.primal_type==="object"?{primal_type:"entity"}:{},...w!==void 0?{id:w}:{},...G!==void 0?{udf:G}:{},...T!==void 0?{comparable:T}:{}}});let $={};for(const _ of n)for(const E of _.schemaMetadata?.keys??[])c[E]!==void 0&&($={...$,[E]:c[E]});for(const _ of n)$={...$,..._.normalizeLegacySchema?.({source:c,properties:g})};const A={...h,...f!==void 0?{id:f}:{},properties:g,...r&&(m||l)?{temporalSemantics:"snapshot"}:{},...$};o[s]=A}return o},Pa=Symbol("legacy-empty-source"),La=t=>t!==void 0&&Pa in t,Ca=(t,e,r,n=[],o=r?[r]:[])=>{const i=[...e],s=new Set(n);for(const[a,c]of Object.entries(t)){const u=c,p=typeof u.id=="string"&&u.id.length>0?u.id:typeof u._id=="string"&&u._id.length>0?u._id:a;if(i.some(y=>y.schemaId===p))continue;const l=typeof u.db=="string"&&u.db.trim().length>0?u.db.trim():void 0;if(typeof u.from!="string"||u.from.trim().length===0){if(l){i.push({schemaId:p,connectionId:l,source:p});continue}for(const y of new Set(o.filter(Boolean))){const h={schemaId:p,connectionId:y,source:`legacy-empty-schema:${p}`,[Pa]:!0};i.push(h)}continue}const m=l??r;if(!m){if(s.has(p)||s.has(a))throw new d("LEGACY_SCHEMA_FROM_CONNECTION_REQUIRED",`Cannot create a Schema mapping for legacy Schema ${p}: provide Schema.db or one unambiguous connection`,{schemaId:p});continue}const f=u.from.trim();i.push({schemaId:p,connectionId:m,source:`legacy-schema-from:${p}`,sourceSql:f})}return i},Da=(t,e)=>[...Ae(t).flatMap(r=>r.locales??[]),...e===void 0?[]:"locale"in e?[e]:e],on=t=>({kind:"query",logicform:t.logicform,...t.prepare!==void 0?{prepare:t.prepare}:{},...t.mapResult?{mapResult:t.mapResult}:{},...t.groupKeyShifts?{groupKeyShifts:t.groupKeyShifts}:{}}),ka=t=>t instanceof Error?t:new Error(String(t)),um=(t,e="zh-CN",r)=>t instanceof d?t.localizedMessage(e,r):t.message,dm=(t,e,r={},n="zh-CN",o)=>{const i=ka(t);return{errorCode:"100",error:um(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}:{}}},lm=(t,e,r)=>{const n=e.projections.map(({name:u})=>u),o=new Map((e.columnProperties??[]).map(u=>[u.name,u])),i=[],s=(u,p)=>{const l=r.parameter(i.length,p);i.push(p);const m=o.get(u)?.type;return m&&(m==="date"||m==="timestamp")&&r.castValue?r.castValue(l,m):l},a=u=>`SELECT ${n.map(p=>`${s(p,u[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(u=>`NULL AS ${r.quoteIdentifier(u)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""} WHERE 1 = 0`,parameters:i}},pm=(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),..._e(r)];for(const i of o){const s=Kr(i,e);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},fm=async(t,e,r)=>{await t?.({...e,partialResult:r})},mm=(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 _e(t)){const n=Kr(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})}},Ua=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 Vo(o))e.add(i)};return r(t),[...e]},Vo=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...Vo(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:Vo(r))]:e},Ma=async(t,e)=>{const r=e.locale??"zh-CN",n=e.localeRegistry??wr(Da(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&&om(t);const c=a?Ta(t,e.schemas):t,u=e.schemaMappings.definitions(),p=Ua(c),l=[...new Set(u.filter(({schemaId:N})=>p.includes(N)).map(({connectionId:N})=>N))],m=e.connectionId??(l.length===1?l[0]:void 0)??e.provider.kind,f=a?Ca(e.schemas,u,m,p):u,y=f.length===u.length?e.schemaMappings:new Tr(f,e.schemaMappings.plugins),h={...e,locale:r,localeRegistry:n,schemaMappings:y,schemas:cm(e.schemas,o,a)},g=mr.performance.now(),$=h.semanticTypes===void 0?ho(o):h.semanticTypesResolved?h.semanticTypes:Ts(h.semanticTypes,o);let A=h.operators??Ve(o);if(h.operators&&!h.operatorsResolved)for(const N of o)for(const D of N.operators??[])if(A.has(D.name)){if(A.get(D.name)!==D)throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${D.name}`,{operator:D.name,plugin:N.name})}else A.register(D);const _=h.schemaMappings,E=N=>_e(N).some(D=>La(Kr(D,_))),w=new Date,R=new Map,C=new Map,k=[],T=new Set,G=N=>{const D=JSON.stringify(N);T.has(D)||(T.add(D),k.push(N),v={...v,schemaMappingSelections:[...k]})};let v={provider:h.provider.kind};const q=[],U=new WeakMap,Y=new Map;h.connectionId&&Y.set(h.connectionId,h.provider.kind);const z=(N,D,P,M=D,K=h.provider,x=h.connectionId)=>{x&&x!==qt&&Y.set(x,K.kind);const le=q.length;q.push(mm(ea(N),K,D,P,h.locale??"zh-CN",n,M,x)),v={...v,sqls:[...q],providers:[...Y].map(([pe,re])=>({connectionId:pe,provider:re}))};const ee=pe=>{q[le]={...q[le],executionSource:pe},v={...v,sqls:[...q]}};return U.set(N,ee),ee},Q=(N,D)=>Oo(N,D,h,U.get(N)),W=async(N,D={})=>{v={...v,...D},await fm(h.onProgress,N,v)},ke=N=>Is(bc(N,h.schemas),$,o),qe=new Map,de=N=>{const D=qe.get(N);return D||(Je(h.permissions,N),ke(N))},me=N=>{if(N.schema)return de(N.schema);if(N.from)return me(N.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},Re=N=>{if(N.schema)return ke(N.schema);if(N.from)return Re(N.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},S=async()=>{const N=Object.values(h.schemas).filter(re=>re.is_calendar===!0);if(N.length!==1)return Object.freeze({});const D=N[0];if(!D)return Object.freeze({});const P=_.list(D.id),M=P.find(({connectionId:re})=>re===h.connectionId)??P[0];if(!M)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${D.id}`,{schemaId:D.id});if(La(M))return Object.freeze({calendar:Object.freeze([])});const K=h.providerForConnection?.(M.connectionId)??h.provider,{onProgress:x,executionContext:le,...ee}=h,pe=await Ma({version:"2.0",schema:D.id,limit:-1},{...ee,provider:K,connectionId:M.connectionId,operators:A,operatorsResolved:!0,executionContext:Object.freeze({})});q.push(...pe.sqls.map(re=>({...re,type:"semantic-resolution",explain:n.translate(h.locale??"zh-CN","sql.semanticResolution")})));for(const re of pe.providers)Y.set(re.connectionId,re.provider);for(const re of pe.schemaMappingSelections)G(re);return Object.freeze({calendar:Object.freeze(pe.result.map(({_id:re,...Se})=>Object.freeze(Se)))})},I=e.executionContext??await S();A=A.withExecutionContext(I);const b={plugins:o,resolveSchema:de,onSchemaMappingSelection:G,...h.connectionId?{preferredConnectionId:h.connectionId}:{},canUsePropertyRowIdentity:(N,D)=>mt(h.permissions,N.id,D)},L=(N,D)=>{const P=ts(je(N,me(N),A,_,b),D);return qe.set(P.id,P),P},j=async(N,D,P)=>{const M=`${N.id}:${D.id}:${P.toISOString()}`,K=R.get(M);if(K)return K;const x=(async()=>{const le=Ae(o).find(ye=>ye.createTimeWatermarkLogicform)?.createTimeWatermarkLogicform;if(!le)return;const ee=le({logicform:c,rootSchema:N,rootProperty:D,requestedUpperBound:P,now:w,...h.timeWatermark?{defaultPolicy:h.timeWatermark}:{},resolveSchema:de,inferPropertyPath:(ye,Te,Pe)=>vs(ye,Te,Pe,de)}),pe=yt(ee,h.permissions,de,!1,new Set,o),re=await ft(pe,N,{semanticTypes:$,operators:A,plugins:o,now:w,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,resolveFromSchema:L}),Se=je(re,N,A,_,b);if(E(Se))return;let Ie;if(dr(Se,_)){const ye=h.providerForConnection;if(!ye)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated timeWatermark resolution requires a provider resolver");Ie=(await rn(Se,{logicform:re,operators:A,schemaMappings:_,providerForConnection:ye,maxMaterializedRows:h.federation?.maxMaterializedRows??1e5,...h.cache?{cache:h.cache}:{},...h.signal?{signal:h.signal}:{},onCompiled:({compiled:Pe,logicform:$e,provider:Ne,connectionId:Bt})=>z(Pe,"semantic-resolution",$e,"time-watermark",Ne,Bt)})).rows}else{Bo(Se,h);const ye=we(Se,h.provider,A);z(ye,"semantic-resolution",re,"time-watermark"),Ie=await Q(ye,_e(Se))}const ge=Ie[0]?.__timeWatermark__??Object.values(Ie[0]??{})[0];if(ge==null||!(ge instanceof Date)&&typeof ge!="string"&&typeof ge!="number")return;const ne=ge instanceof Date?ge:new Date(ge);return Number.isNaN(ne.getTime())?void 0:ne})();return R.set(M,x),x},te=async(N,D,P)=>{const M=JSON.stringify([N.id,D,P??null]),K=C.get(M);if(K)return K;const x=(async()=>{const le={version:"2.0",schema:N.id,...P?{query:P}:{},preds:[{name:"__autoCaseMin__",operator:"$min",pred:D},{name:"__autoCaseMax__",operator:"$max",pred:D},{name:"__autoCaseCount__",operator:"$count",pred:D}]},ee=await ft(le,N,{semanticTypes:$,operators:A,plugins:o,now:w,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,resolveFromSchema:L}),pe=je(ee,N,A,_,b);if(E(pe))return{empty:!0};let re;if(dr(pe,_)){const $e=h.providerForConnection;if(!$e)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated automatic bucket resolution requires a provider resolver");re=(await rn(pe,{logicform:ee,operators:A,schemaMappings:_,providerForConnection:$e,maxMaterializedRows:h.federation?.maxMaterializedRows??1e5,...h.cache?{cache:h.cache}:{},...h.signal?{signal:h.signal}:{},onCompiled:({compiled:Bt,logicform:un,provider:pr,connectionId:dn})=>z(Bt,"semantic-resolution",un,"auto-case",pr,dn)})).rows}else{Bo(pe,h);const $e=we(pe,h.provider,A);z($e,"semantic-resolution",ee,"auto-case"),re=await Q($e,_e(pe))}const Se=re[0],Ie=Se?.__autoCaseMin__,ge=Se?.__autoCaseMax__,ne=Se?.__autoCaseCount__;if(Ie==null||ge===null||ge===void 0||ne===null||ne===void 0||Number(ne)===0)return{empty:!0};const ye=Number(Ie),Te=Number(ge),Pe=Number(ne);if(!Number.isFinite(ye)||!Number.isFinite(Te)||!Number.isSafeInteger(Pe)||Pe<0)throw new d("INVALID_AUTO_CASE_STATS","Automatic bucket statistics must contain finite min/max and a non-negative integer count",{min:Ie,max:ge,count:ne});return{min:ye,max:Te,count:Pe}})();return C.set(M,x),x};try{h.signal?.throwIfAborted(),go(c),await W({stage:"started",logicform:c}),yp(h.permissions,ke);const N=me(c);await W({stage:"validated",schema:N});const D=yt(c,h.permissions,de,!0,new Set,o),P=await ft(D,N,{semanticTypes:$,operators:A,plugins:o,now:w,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,resolveFromSchema:L,canProjectProperty:(O,B)=>mt(h.permissions,O.id,B),requestTimeWatermark:j,requestAutoCaseBounds:te});await W({stage:"normalized",normedLogicform:P},{normedLogicform:P});const M=je(P,N,A,_,b),K=dr(M,_);K||Bo(M,h);const x=M.columnProperties??[],le=es(M,N);qe.set(le.id,le),await W({stage:"planned",plan:M},{schema:le});const ee=vi(M,N,h.provider,A,h.providerForConnection);if(await W({stage:"lineage",lineage:ee},{lineage:ee}),a&&E(M)){const O=[];await W({stage:"compiled",sqls:[]},{sqls:[]}),await W({stage:"result",result:O},{result:O,total:0,providers:[]}),await W({stage:"completed",durationMs:mr.performance.now()-g});const B=P.output?Rn(P.output.type,o):void 0;return{result:O,total:0,schema:le,normedLogicform:P,sqls:[],lineage:ee,provider:h.provider.kind,providers:[],schemaMappingSelections:[...k],...B?{output:await B.handle({rows:O,logicform:P,schema:le})}:{}}}if(K){const O=h.providerForConnection;if(!O)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated execution requires a provider resolver for every physical connection");const B=await rn(M,{logicform:P,operators:A,schemaMappings:_,providerForConnection:O,maxMaterializedRows:h.federation?.maxMaterializedRows??1e5,...h.cache?{cache:h.cache}:{},...h.signal?{signal:h.signal}:{},onCompiled:({compiled:Oe,type:ae,logicform:ie,provider:be,connectionId:he})=>z(Oe,ae,ie,ae,be,he)});await W({stage:"compiled",sqls:[...q]},{sqls:[...q]}),await W({stage:"executing",provider:"duckdb",connectionId:qt}),await W({stage:"hydrating"});const J=B.connections.length===1?B.connections[0]?.connectionId:void 0,F=await ia(B.rows,x,{semanticTypes:$,plugins:o,resolveSchema:de,fetchEntities:Oe=>ta(Oe,{version:P.version,operators:A,schemaMappings:_,semanticTypes:$,plugins:o,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,...h.permissions?{permissions:h.permissions}:{},provider:h.provider,providerForConnection:O,...J?{preferredConnectionId:J}:{},...h.cache?{cache:h.cache}:{},...h.signal?{signal:h.signal}:{},onCompiled:(ae,ie,be,he)=>z(ae,"semantic-resolution",ie,"entity-expansion",be,he)})}),Z=so(F,M.rowIdentity);return await W({stage:"result",result:Z},{result:Z,total:B.total,sqls:[...q],providers:B.connections}),await W({stage:"completed",durationMs:mr.performance.now()-g}),{result:Z,total:B.total,schema:le,normedLogicform:P,sqls:[...q],lineage:ee,provider:"duckdb",providers:B.connections,schemaMappingSelections:[...k]}}const pe=xr(P,M,N,A,de,void 0,r,n.translator(r)),re=async(O,B)=>{const J=B&&O.logicform.schema===B.id?B:me(O.logicform),F=O.prepare?await ft(yt(O.logicform,h.permissions,de,!0,new Set,o),J,{semanticTypes:$,operators:A,plugins:o,now:w,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,resolveFromSchema:L,canProjectProperty:(ae,ie)=>mt(h.permissions,ae.id,ie),requestTimeWatermark:j}):O.logicform,Z=je(F,J,A,_,b),Oe=xr(F,Z,J,A,de,O.logicform,r,n.translator(r));if(Oe){if(Oe.length!==1)throw new Error("A generated component must produce exactly one execution unit");const ae=Oe[0];if("logicform"in ae){const he=await re(ae,J),gt=he.component.mapResult,Ge=O.mapResult;return{...he,component:{...O,logicform:he.component.logicform,...gt||Ge?{mapResult:ze=>{const it=gt?.(ze)??[...ze];return Ge?.(it)??[...it]}}:{}}}}if("mergeRow"in ae)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","A JavaScript composite metric cannot currently be nested as a generated component");const ie=await Promise.all(ae.components.map(async he=>({name:he.name,prepared:await re(on(he)),...he.groupKeyShifts?{groupKeyShifts:he.groupKeyShifts}:{},...he.joinKeys?{joinKeys:he.joinKeys}:{}}))),be=Mr(ae,ie.map(({name:he,prepared:gt,...Ge})=>({name:he,plan:gt.plan,...Ge})),Z,ae.outputName,h.provider,A);return{component:{...O,logicform:F},plan:Z,compiled:be,sources:ar(ie.map(({prepared:he})=>he.sources))}}return{component:{...O,logicform:F},plan:Z,compiled:we(Z,h.provider,A),sources:_e(Z)}},Se=async(O,B)=>{const J=xr(O,B,me(O),A,de,void 0,r,n.translator(r));if(!J)return{compiled:we(B,h.provider,A),sources:_e(B)};const F=await Promise.all(J.map(async Z=>{if("logicform"in Z){const ie=await re(Z);return{plan:ie.plan,compiled:ie.compiled,outputs:ie.plan.projections.map(({name:be})=>be).filter(be=>!B.groupBy.some(he=>he.name===be))}}if("mergeRow"in Z)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const Oe=await Promise.all(Z.components.map(async ie=>{const be=await re(on(ie));return{name:ie.name,plan:be.plan,...ie.joinKeys?{joinKeys:ie.joinKeys}:{},...ie.groupKeyShifts?{groupKeyShifts:ie.groupKeyShifts}:{}}})),ae=Mr(Z,Oe,B,Z.outputName,h.provider,A);return{plan:B,compiled:ae,outputs:[Z.outputName,...Z.components.map(ie=>ie.name)]}}));return{compiled:no(F,B,h.provider,A),sources:ar(F.map(({plan:Z})=>_e(Z)))}},Ie=new WeakMap,ge=async O=>{if(!O.sourcePlan||!O.sourceLogicform)return we(O,h.provider,A);const B=Re(O.sourceLogicform),J=xr(O.sourceLogicform,O.sourcePlan,B,A,de,void 0,r,n.translator(r));if(J?.some(ie=>"mergeRow"in ie)){const ie=Ie.get(O.sourcePlan);if(ie){const se={...O};delete se.sourcePlan,delete se.sourceLogicform;const et=we({...se,sourceSql:ie.sql,source:O.source},h.provider,A,ie.parameters.length);return{sql:et.sql,parameters:[...ie.parameters,...et.parameters]}}const be=await Promise.all(J.map(async se=>{if("logicform"in se)return{kind:"query",unit:se,prepared:await re(se,B)};const et=await Promise.all(se.components.map(async Ee=>({input:Ee,prepared:await re(on(Ee),B)})));return"mergeRow"in se?{kind:"js",unit:se,components:et}:{kind:"component",unit:se,components:et,compiled:Mr(se,et.map(({input:Ee,prepared:Ye})=>({name:Ee.name,plan:Ye.plan,...Ee.joinKeys?{joinKeys:Ee.joinKeys}:{},...Ee.groupKeyShifts?{groupKeyShifts:Ee.groupKeyShifts}:{}})),O.sourcePlan,se.outputName,h.provider,A)}})),he=O.sourcePlan.groupBy.map(({name:se})=>se),gt=await Promise.all(be.map(async se=>{if(se.kind==="query"){z(se.prepared.compiled,"computation",se.prepared.component.logicform);const Ee=await Q(se.prepared.compiled,se.prepared.sources),Ye=await lt(Ee,se.prepared.plan.projections,A);return se.unit.mapResult?.(Ye)??Ye}if(se.kind==="component")return z(se.compiled,"computation",O.sourceLogicform),Q(se.compiled,ar(se.components.map(({prepared:Ee})=>Ee.sources)));const et=await Promise.all(se.components.map(async({input:Ee,prepared:Ye})=>{z(Ye.compiled,"computation",Ye.component.logicform);const qa=await Q(Ye.compiled,Ye.sources),Fo=await lt(qa,Ye.plan.projections,A);return Ee.mapResult?.(Fo)??Fo}));return Promise.all(uo(et,he).map(async Ee=>({...Ee,[se.unit.outputName]:await se.unit.mergeRow(Ee)})))})),Ge=lo(gt,O.sourcePlan),ze=h.federation?.maxMaterializedRows??1e5;if(!Number.isSafeInteger(ze)||ze<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:ze});if(Ge.length>ze)throw new d("MATERIALIZED_RESULT_LIMIT_EXCEEDED",`Nested component materialized ${Ge.length} rows; maximum is ${ze}`,{materializedRowCount:Ge.length,maxMaterializedRows:ze});const it=lm(Ge,O.sourcePlan,h.provider);Ie.set(O.sourcePlan,it);const ln={...O};delete ln.sourcePlan,delete ln.sourceLogicform;const Yo=we({...ln,sourceSql:it.sql,source:O.source},h.provider,A,it.parameters.length);return{sql:Yo.sql,parameters:[...it.parameters,...Yo.parameters]}}const F=await Se(O.sourceLogicform,O.sourcePlan),Z={...O};delete Z.sourcePlan,delete Z.sourceLogicform;const Oe={...Z,sourceSql:F.compiled.sql,source:O.source},ae=we(Oe,h.provider,A,F.compiled.parameters.length);return{sql:ae.sql,parameters:[...F.compiled.parameters,...ae.parameters]}},ne=pe?await Promise.all(pe.map(async O=>{if("logicform"in O)return{kind:"query",unit:O,...await re(O)};const B=await Promise.all(O.components.map(async F=>({name:F.name,prepared:await re(on(F)),...F.groupKeyShifts?{groupKeyShifts:F.groupKeyShifts}:{},...F.joinKeys?{joinKeys:F.joinKeys}:{}})));if("mergeRow"in O)return{kind:"js",unit:O,components:B.map(({prepared:F})=>F)};const J=B.map(({name:F,prepared:Z,...Oe})=>({name:F,plan:Z.plan,...Oe}));return{kind:"component",unit:O,plan:M,compiled:Mr(O,J,M,O.outputName,h.provider,A),sources:ar(B.map(({prepared:F})=>F.sources))}})):void 0,ye=ne&&pm(ne,_,M)?ne.map(O=>{const B=new Set(M.groupBy.map(({name:F})=>F));if(O.kind==="query")return{plan:O.plan,compiled:O.compiled,outputs:O.plan.projections.map(({name:F})=>F).filter(F=>!B.has(F))};const J=O.unit.outputName;if(!J)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");return{plan:O.plan,compiled:O.compiled,outputs:[J,...O.unit.components.map(F=>F.name)]}}):void 0,Te=ye?no(ye,M,h.provider,A):void 0,Pe=ne?void 0:await ge(M),$e=Uo(M),Ne=M.pagination&&(Te||Pe)?Mo(ye?no(ye,$e,h.provider,A):await ge($e),h.provider):void 0;if(Te)z(Te,"computation",P);else if(ne)for(const O of ne)if(O.kind==="js")for(const B of O.components)z(B.compiled,"computation",B.component.logicform);else z(O.compiled,"computation",P);else z(Pe,"computation",P);Ne&&z(Ne,"total",vf(P)),await W({stage:"compiled",sqls:[...q]},{sqls:[...q]}),await W({stage:"executing",provider:h.provider.kind});const Bt=Te?await(async()=>{const O=ar([...ne.map(Z=>Z.sources),_e(M)]),[B,J]=await Promise.all([Q(Te,O),Ne?Q(Ne,O):Promise.resolve(void 0)]),F=await lt(B,M.projections,A);return{rows:F,total:J?tn(J):F.length}})():ne?await(async()=>{const O=await Promise.all(ne.map(async J=>{if(J.kind==="js"){const Oe=await Promise.all(J.components.map(async ae=>{const ie=await Q(ae.compiled,ae.sources),be=await lt(ie,ae.plan.projections,A);return ae.component.mapResult?.(be)??be}));return Promise.all(uo(Oe,M.groupBy.map(({name:ae})=>ae)).map(async ae=>{const ie=await J.unit.mergeRow(ae);return{...ae,[J.unit.outputName]:ie}}))}const F=await Q(J.compiled,J.sources),Z=J.kind==="query"?await lt(F,J.plan.projections,A):F;return J.kind==="query"?J.unit.mapResult?.(Z)??Z:Z})),B=lo(O,M);return{rows:B,total:M.pagination?lo(O,$e).length:B.length}})():await(async()=>{const O=_e(M),[B,J]=await Promise.all([Q(Pe,O),Ne?Q(Ne,O):Promise.resolve(void 0)]),F=await lt(B,M.projections,A);return{rows:F,total:J?tn(J):F.length}})(),{rows:un,total:pr}=Bt;await W({stage:"hydrating"});const dn=await ia(un,x,{semanticTypes:$,plugins:o,resolveSchema:de,fetchEntities:O=>ta(O,{version:P.version,operators:A,schemaMappings:_,semanticTypes:$,plugins:o,...h.locale?{locale:h.locale}:{},localeRegistry:n,resolveSchema:de,...h.permissions?{permissions:h.permissions}:{},provider:h.provider,...h.connectionId?{preferredConnectionId:h.connectionId}:{},...h.providerForConnection?{providerForConnection:h.providerForConnection}:{},...h.cache?{cache:h.cache}:{},...h.signal?{signal:h.signal}:{},onCompiled:(B,J,F,Z)=>z(B,"semantic-resolution",J,"entity-expansion",F,Z)})}),fr=so(dn,M.rowIdentity);return await W({stage:"result",result:fr},{result:fr,total:pr,sqls:[...q]}),await W({stage:"completed",durationMs:mr.performance.now()-g}),{result:fr,total:pr,schema:le,normedLogicform:P,sqls:[...q],lineage:ee,provider:h.provider.kind,providers:[...Y].map(([O,B])=>({connectionId:O,provider:B})),schemaMappingSelections:[...k],...P.output?await(async()=>{const O=Rn(P.output?.type??"",o);return O?{output:await O.handle({rows:fr,logicform:P,schema:le})}:{}})():{}}}catch(N){const D=ka(N);try{await W({stage:"failed",error:D})}catch{}throw D}},ym=async(t,e)=>{let r={};const n=e.locale??"zh-CN",o=wr(Da(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 T of e.connections){if(T.id.trim().length===0)throw new d("INVALID_DATABASE_CONNECTION","Database connection id must not be empty");if(i.has(T.id))throw new d("DATABASE_CONNECTION_ALREADY_REGISTERED",`Database connection id is duplicated: ${T.id}`,{connectionId:T.id});i.set(T.id,T)}const s=Ua(t),a=t.version,c=a===void 0||typeof a=="string"&&/^1\./.test(a),u=[...new Set(e.schemaMappings.filter(({schemaId:T})=>s.includes(T)).map(({connectionId:T})=>T))],p=e.connections.length===1?e.connections[0]?.id:u.length===1?u[0]:void 0,l=c?Ca(e.schemas,e.schemaMappings,p,s,e.connections.map(({id:T})=>T)):e.schemaMappings,m=new Tr(l,e.plugins),f=s.flatMap(T=>m.list(T)).map(({connectionId:T})=>T)[0];if(!f)throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain at least one physical Schema leaf");const y=T=>{const G=i.get(T);if(!G)throw new d("DATABASE_CONNECTION_NOT_FOUND",`Database connection is not registered: ${T}`,{connectionId:T});return en(G,e.providerRegistry)},h=y(f);r={provider:h.kind};const g=Ve(e.plugins),$=e.operators===void 0?[]:Array.isArray(e.operators)?e.operators:[e.operators],A=new xt($),_=new Set(A.definitions().map(({name:T})=>T)),E=$.length===0?g:new xt([...g.definitions().filter(({name:T})=>!_.has(T)),...A.definitions()]),w=e.semanticTypes===void 0?ho(e.plugins):Ts(e.semanticTypes,e.plugins??[]),{cache:R,...C}=e,k=R?await Xs(R):void 0;return await Ma(t,{...C,schemaMappings:m,locale:n,localeRegistry:o,provider:h,providerForConnection:y,operators:E,operatorsResolved:!0,semanticTypes:w,semanticTypesResolved:!0,connectionId:f,...k?{cache:k}:{},onProgress:async T=>{r=T.partialResult,await e.onProgress?.(T)}})}catch(i){return dm(i,t,r,n,o)}},hm=Object.freeze({execute:ym,close:ga});exports.DBConnector=jf,exports.LocaleRegistry=gn,exports.Logicform=hm,exports.OperatorRegistry=xt,exports.PlannerSemanticRegistry=Gi,exports.ProviderRegistry=ma,exports.QueryCacheManager=Lp,exports.SchemaMappingRegistry=Tr,exports.SemanticDBError=d,exports.SemanticTypeRegistry=po,exports.builtinOperators=Wd,exports.builtinSemanticTypes=Qn,exports.createLocaleRegistry=wr,exports.createOperatorRegistry=Ve,exports.createPlannerSemanticRegistry=zi,exports.createSemanticTypeRegistry=ho,exports.defaultLocaleRegistry=$r,exports.enUS=di,exports.fromYiAskSchemaMapping=tl,exports.resolveOperator=Bi,exports.resolveSchema=Is,exports.validateResolvedSchema=Ss,exports.zhCN=li;
|
|
1
|
+
"use strict";var dc=Object.create;var ui=Object.defineProperty;var pc=Object.getOwnPropertyDescriptor;var lc=Object.getOwnPropertyNames;var fc=Object.getPrototypeOf,mc=Object.prototype.hasOwnProperty;var yc=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of lc(e))!mc.call(t,o)&&o!==r&&ui(t,o,{get:()=>e[o],enumerable:!(n=pc(e,o))||n.enumerable});return t};var ct=(t,e,r)=>(r=t!=null?dc(fc(t)):{},yc(e||!t||!t.__esModule?ui(r,"default",{value:t,enumerable:!0}):r,t));var Lr=require("node:perf_hooks"),le=require("dayjs"),tr=require("dayjs/plugin/isoWeek.js"),Cr=require("dayjs/plugin/quarterOfYear.js"),di=require("dayjs/plugin/customParseFormat.js"),Nn=require("node:crypto"),pi=require("node:util"),hc=require("redis"),gc=require("semanticdb-core"),ge=require("@duckdb/node-api");const Z=t=>typeof t=="string",rr=()=>{let t,e;const r=new Promise((n,o)=>{t=n,e=o});return r.resolve=t,r.reject=e,r},li=t=>t==null?"":""+t,Ac=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},$c=/###/g,fi=t=>t&&t.indexOf("###")>-1?t.replace($c,"."):t,mi=t=>!t||Z(t),nr=(t,e,r)=>{const n=Z(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if(mi(t))return{};const i=fi(n[o]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++o}return mi(t)?{}:{obj:t,k:fi(n[o])}},yi=(t,e,r)=>{const{obj:n,k:o}=nr(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=nr(t,s,Object);for(;a.obj===void 0&&s.length;)i=`${s[s.length-1]}.${i}`,s=s.slice(0,s.length-1),a=nr(t,s,Object),a?.obj&&typeof a.obj[`${a.k}.${i}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${i}`]=r},wc=(t,e,r,n)=>{const{obj:o,k:i}=nr(t,e,Object);o[i]=o[i]||[],o[i].push(r)},Dr=(t,e)=>{const{obj:r,k:n}=nr(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},Ec=(t,e,r)=>{const n=Dr(t,r);return n!==void 0?n:Dr(e,r)},hi=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(n in t?Z(t[n])||t[n]instanceof String||Z(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):hi(t[n],e[n],r):t[n]=e[n]);return t},yt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var _c={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const Ic=t=>Z(t)?t.replace(/[&<>"'\/]/g,e=>_c[e]):t;class Sc{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 bc=[" ",",","?","!",";"],Rc=new Sc(20),Nc=(t,e,r)=>{e=e||"",r=r||"";const n=bc.filter(s=>e.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=Rc.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},On=(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 c=i;c<n.length;++c)if(c!==i&&(a+=r),a+=n[c],s=o[a],s!==void 0){if(["string","number","boolean"].indexOf(typeof s)>-1&&c<n.length-1)continue;i+=c-i+1;break}o=s}return o},or=t=>t?.replace(/_/g,"-"),Oc={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 In{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||Oc,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:(Z(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new In(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new In(this.logger,e)}}var We=new In;class Mr{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 gi extends Mr{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):Z(n)&&i?a.push(...n.split(i)):a.push(n)));const c=Dr(this.data,a);return!c&&!r&&!n&&e.indexOf(".")>-1&&(e=a[0],r=a[1],n=a.slice(2).join(".")),c||!s||!Z(n)?c:On(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),yi(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)(Z(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 c=Dr(this.data,a)||{};s.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?hi(c,n,i):c={...c,...n},yi(this.data,a,c),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 Ai={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 $i=Symbol("i18next/PATH_KEY");function Tc(){const t=[],e=Object.create(null);let r;return e.get=(n,o)=>(r?.revoke?.(),o===$i?t:(t.push(o),r=Proxy.revocable(n,e),r.proxy)),Proxy.revocable(Object.create(null),e).proxy}function Ct(t,e){const{[$i]:r}=t(Tc()),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 wi={},Tn=t=>!Z(t)&&typeof t!="boolean"&&typeof t!="number";class Sn extends Mr{constructor(e,r={}){super(),Ac(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=We.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=Tn(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&&!Nc(e,n,o);if(s&&!a){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:Z(i)?[i]:i};const u=e.split(n);(n!==o||n===o&&this.options.ns.indexOf(u[0])>-1)&&(i=u.shift()),e=u.join(o)}return{key:e,namespaces:Z(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=Ct(e,{...this.options,...o})),Array.isArray(e)||(e=[String(e)]),e=e.map(x=>typeof x=="function"?Ct(x,{...this.options,...o}):String(x));const i=o.returnDetails!==void 0?o.returnDetails:this.options.returnDetails,s=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,{key:a,namespaces:c}=this.extractFromKey(e[e.length-1],o),u=c[c.length-1];let p=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;p===void 0&&(p=":");const l=o.lng||this.language,m=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l?.toLowerCase()==="cimode")return m?i?{res:`${u}${p}${a}`,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:u,usedParams:this.getUsedParamsDetails(o)}:`${u}${p}${a}`:i?{res:a,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:u,usedParams:this.getUsedParamsDetails(o)}:a;const f=this.resolve(e,o);let h=f?.res;const y=f?.usedKey||a,$=f?.exactUsedKey||a,E=["[object Number]","[object Function]","[object RegExp]"],A=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,g=!this.i18nFormat||this.i18nFormat.handleAsObject,w=o.count!==void 0&&!Z(o.count),L=Sn.hasDefaultValue(o),I=w?this.pluralResolver.getSuffix(l,o.count,o):"",S=o.ordinal&&w?this.pluralResolver.getSuffix(l,o.count,{ordinal:!1}):"",R=w&&!o.ordinal&&o.count===0,N=R&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${I}`]||o[`defaultValue${S}`]||o.defaultValue;let D=h;g&&!h&&L&&(D=N);const F=Tn(D),V=Object.prototype.toString.apply(D);if(g&&D&&F&&E.indexOf(V)<0&&!(Z(A)&&Array.isArray(D))){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const x=this.options.returnedObjectHandler?this.options.returnedObjectHandler(y,D,{...o,ns:c}):`key '${a} (${this.language})' returned an object instead of string.`;return i?(f.res=x,f.usedParams=this.getUsedParamsDetails(o),f):x}if(s){const x=Array.isArray(D),M=x?[]:{},j=x?$:y;for(const K in D)if(Object.prototype.hasOwnProperty.call(D,K)){const H=`${j}${s}${K}`;L&&!h?M[K]=this.translate(H,{...o,defaultValue:Tn(N)?N[K]:void 0,joinArrays:!1,ns:c}):M[K]=this.translate(H,{...o,joinArrays:!1,ns:c}),M[K]===H&&(M[K]=D[K])}h=M}}else if(g&&Z(A)&&Array.isArray(h))h=h.join(A),h&&(h=this.extendTranslation(h,e,o,n));else{let x=!1,M=!1;!this.isValidLookup(h)&&L&&(x=!0,h=N),this.isValidLookup(h)||(M=!0,h=a);const K=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&M?void 0:h,H=L&&N!==h&&this.options.updateMissing;if(M||x||H){if(this.logger.log(H?"updateKey":"missingKey",l,u,a,H?N:h),s){const fe=this.resolve(a,{...o,keySeparator:!1});fe&&fe.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 re=[];const ye=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ye&&ye[0])for(let fe=0;fe<ye.length;fe++)re.push(ye[fe]);else this.options.saveMissingTo==="all"?re=this.languageUtils.toResolveHierarchy(o.lng||this.language):re.push(o.lng||this.language);const Ue=(fe,Re,se)=>{const Ne=L&&se!==h?se:K;this.options.missingKeyHandler?this.options.missingKeyHandler(fe,u,Re,Ne,H,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(fe,u,Re,Ne,H,o),this.emit("missingKey",fe,u,Re,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&w?re.forEach(fe=>{const Re=this.pluralResolver.getSuffixes(fe,o);R&&o[`defaultValue${this.options.pluralSeparator}zero`]&&Re.indexOf(`${this.options.pluralSeparator}zero`)<0&&Re.push(`${this.options.pluralSeparator}zero`),Re.forEach(se=>{Ue([fe],a+se,o[`defaultValue${se}`]||N)})}):Ue(re,a,N))}h=this.extendTranslation(h,e,o,f,n),M&&h===a&&this.options.appendNamespaceToMissingKey&&(h=`${u}${p}${a}`),(M||x)&&this.options.parseMissingKeyHandler&&(h=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${p}${a}`:a,x?h:void 0,o))}return i?(f.res=h,f.usedParams=this.getUsedParamsDetails(o),f):h}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 c=Z(e)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let u;if(c){const l=e.match(this.interpolator.nestingRegexp);u=l&&l.length}let p=n.replace&&!Z(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),c){const l=e.match(this.interpolator.nestingRegexp),m=l&&l.length;u<m&&(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=Z(s)?[s]:s;return e!=null&&a?.length&&n.applyPostProcessor!==!1&&(e=Ai.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 Z(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?Ct(c,{...this.options,...r}):c)),e.forEach(c=>{if(this.isValidLookup(n))return;const u=this.extractFromKey(c,r),p=u.key;o=p;let l=u.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));const m=r.count!==void 0&&!Z(r.count),f=m&&!r.ordinal&&r.count===0,h=r.context!==void 0&&(Z(r.context)||typeof r.context=="number")&&r.context!=="",y=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);l.forEach($=>{this.isValidLookup(n)||(a=$,!wi[`${y[0]}-${$}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(wi[`${y[0]}-${$}`]=!0,this.logger.warn(`key "${o}" for languages "${y.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!!!")),y.forEach(E=>{if(this.isValidLookup(n))return;s=E;const A=[p];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(A,p,E,$,r);else{let w;m&&(w=this.pluralResolver.getSuffix(E,r.count,r));const L=`${this.options.pluralSeparator}zero`,I=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(r.ordinal&&w.indexOf(I)===0&&A.push(p+w.replace(I,this.options.pluralSeparator)),A.push(p+w),f&&A.push(p+L)),h){const S=`${p}${this.options.contextSeparator||"_"}${r.context}`;A.push(S),m&&(r.ordinal&&w.indexOf(I)===0&&A.push(S+w.replace(I,this.options.pluralSeparator)),A.push(S+w),f&&A.push(S+L))}}let g;for(;g=A.pop();)this.isValidLookup(n)||(i=g,n=this.getResource(E,$,g,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&&!Z(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 Ei{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=We.create("languageUtils")}getScriptPartFromCode(e){if(e=or(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=or(e),!e||e.indexOf("-")<0)return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(Z(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)),Z(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 Z(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))):Z(e)&&i(this.formatLanguageCode(e)),n.forEach(s=>{o.indexOf(s)<0&&i(this.formatLanguageCode(s))}),o}}const _i={zero:0,one:1,two:2,few:3,many:4,other:5},Ii={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Pc{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=We.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=or(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!"),Ii;if(!e.match(/-|_/))return Ii;const c=this.languageUtils.getLanguagePartFromCode(e);s=this.getRule(c,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)=>_i[o]-_i[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 Si=(t,e,r,n=".",o=!0)=>{let i=Ec(t,e,r);return!i&&o&&Z(r)&&(i=On(t,r,n),i===void 0&&(i=On(e,r,n))),i},Pn=t=>t.replace(/\$/g,"$$$$");class bi{constructor(e={}){this.logger=We.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:c,formatSeparator:u,unescapeSuffix:p,unescapePrefix:l,nestingPrefix:m,nestingPrefixEscaped:f,nestingSuffix:h,nestingSuffixEscaped:y,nestingOptionsSeparator:$,maxReplaces:E,alwaysFormat:A}=e.interpolation;this.escape=r!==void 0?r:Ic,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=i?yt(i):s||"{{",this.suffix=a?yt(a):c||"}}",this.formatSeparator=u||",",this.unescapePrefix=p?"":l||"-",this.unescapeSuffix=this.unescapePrefix?"":p||"",this.nestingPrefix=m?yt(m):f||yt("$t("),this.nestingSuffix=h?yt(h):y||yt(")"),this.nestingOptionsSeparator=$||",",this.maxReplaces=E||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 c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=f=>{if(f.indexOf(this.formatSeparator)<0){const E=Si(r,c,f,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(E,void 0,n,{...o,...r,interpolationkey:f}):E}const h=f.split(this.formatSeparator),y=h.shift().trim(),$=h.join(this.formatSeparator).trim();return this.format(Si(r,c,y,this.options.keySeparator,this.options.ignoreJSONStructure),$,n,{...o,...r,interpolationkey:y})};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:f=>Pn(f)},{regex:this.regexp,safeValue:f=>this.escapeValue?Pn(this.escape(f)):Pn(f)}].forEach(f=>{for(a=0;i=f.regex.exec(e);){const h=i[1].trim();if(s=u(h),s===void 0)if(typeof p=="function"){const $=p(e,i,o);s=Z($)?$:""}else if(o&&Object.prototype.hasOwnProperty.call(o,h))s="";else if(l){s=i[0];continue}else this.logger.warn(`missed to pass in variable ${h} for interpolating ${e}`),s="";else!Z(s)&&!this.useRawValueToEscape&&(s=li(s));const y=f.safeValue(s);if(e=e.replace(i[0],y),l?(f.regex.lastIndex+=s.length,f.regex.lastIndex-=i[0].length):f.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,r,n={}){let o,i,s;const a=(c,u)=>{const p=this.nestingOptionsSeparator;if(c.indexOf(p)<0)return c;const l=c.split(new RegExp(`${yt(p)}[ ]*{`));let m=`{${l[1]}`;c=l[0],m=this.interpolate(m,s);const f=m.match(/'/g),h=m.match(/"/g);((f?.length??0)%2===0&&!h||(h?.length??0)%2!==0)&&(m=m.replace(/'/g,'"'));try{s=JSON.parse(m),u&&(s={...u,...s})}catch(y){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,y),`${c}${p}${m}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,c};for(;o=this.nestingRegexp.exec(e);){let c=[];s={...n},s=s.replace&&!Z(s.replace)?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;const u=/{.*}/.test(o[1])?o[1].lastIndexOf("}")+1:o[1].indexOf(this.formatSeparator);if(u!==-1&&(c=o[1].slice(u).split(this.formatSeparator).map(p=>p.trim()).filter(Boolean),o[1]=o[1].slice(0,u)),i=r(a.call(this,o[1].trim(),s),s),i&&o[0]===e&&!Z(i))return i;Z(i)||(i=li(i)),i||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${e}`),i=""),c.length&&(i=c.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 Lc=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,...c]=s.split(":"),u=c.join(":").trim().replace(/^'+|'+$/g,""),p=a.trim();r[p]||(r[p]=u),u==="false"&&(r[p]=!1),u==="true"&&(r[p]=!0),isNaN(u)||(r[p]=parseInt(u,10))}})}return{formatName:e,formatOptions:r}},Ri=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(or(n),o),e[s]=a),a(r)}},Cc=t=>(e,r,n)=>t(or(r),n)(e);class Dc{constructor(e={}){this.logger=We.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?Ri:Cc;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()]=Ri(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(c=>c.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,a)].join(this.formatSeparator)}return i.reduce((a,c)=>{const{formatName:u,formatOptions:p}=Lc(c);if(this.formats[u]){let l=a;try{const m=o?.formatParams?.[o.interpolationkey]||{},f=m.locale||m.lng||o.locale||o.lng||n;l=this.formats[u](a,f,{...p,...o,...m})}catch(m){this.logger.warn(m)}return l}else this.logger.warn(`there was no format function for ${u}`);return a},e)}}const Mc=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Uc extends Mr{constructor(e,r,n,o={}){super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=We.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={},c={};return e.forEach(u=>{let p=!0;r.forEach(l=>{const m=`${u}|${l}`;!n.reload&&this.store.hasResourceBundle(u,l)?this.state[m]=2:this.state[m]<0||(this.state[m]===1?s[m]===void 0&&(s[m]=!0):(this.state[m]=1,p=!1,s[m]===void 0&&(s[m]=!0),i[m]===void 0&&(i[m]=!0),c[l]===void 0&&(c[l]=!0)))}),p||(a[u]=!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(c)}}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(c=>{wc(c.loaded,[i],s),Mc(c,e),r&&c.errors.push(r),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(u=>{a[u]||(a[u]={});const p=c.loaded[u];p.length&&p.forEach(l=>{a[u][l]===void 0&&(a[u][l]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(c=>!c.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=(u,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(u&&p&&o<this.maxRetries){setTimeout(()=>{this.read.call(this,e,r,n,o+1,i*2,s)},i);return}s(u,p)},c=this.backend[n].bind(this.backend);if(c.length===2){try{const u=c(e,r);u&&typeof u.then=="function"?u.then(p=>a(null,p)).catch(a):a(null,u)}catch(u){a(u)}return}return c(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();Z(e)&&(e=this.languageUtils.toResolveHierarchy(e)),Z(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 c={...s,isUpdate:i},u=this.backend.create.bind(this.backend);if(u.length<6)try{let p;u.length===5?p=u(e,r,n,o,c):p=u(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 u(e,r,n,o,a,c)}!e||!e[0]||this.store.addResource(e[0],r,n,o)}}}const Ln=()=>({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]),Z(t[1])&&(e.defaultValue=t[1]),Z(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}),Ni=t=>(Z(t.ns)&&(t.ns=[t.ns]),Z(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),Z(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),Ur=()=>{},qc=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})},Oi="__i18next_supportNoticeShown",kc=()=>!!(typeof globalThis<"u"&&globalThis[Oi]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),jc=()=>{typeof globalThis<"u"&&(globalThis[Oi]=!0)},xc=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 Tr extends Mr{constructor(e={},r){if(super(),this.options=Ni(e),this.services={},this.logger=We,this.modules={external:[]},qc(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&&(Z(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const n=Ln();this.options={...n,...this.options,...Ni(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&&!xc(this)&&!kc()&&(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}"),jc());const o=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?We.init(o(this.modules.logger),this.options):We.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=Dc;const p=new Ei(this.options);this.store=new gi(this.options.resources,this.options);const l=this.services;l.logger=We,l.resourceStore=this.store,l.languageUtils=p,l.pluralResolver=new Pc(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"),u&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(l.formatter=o(u),l.formatter.init&&l.formatter.init(l,this.options),this.options.interpolation.format=l.formatter.format.bind(l.formatter)),l.interpolator=new bi(this.options),l.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},l.backendConnector=new Uc(o(this.modules.backend),l.resourceStore,l,this.options),l.backendConnector.on("*",(f,...h)=>{this.emit(f,...h)}),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 Sn(this.services,this.options),this.translator.on("*",(f,...h)=>{this.emit(f,...h)}),this.modules.external.forEach(f=>{f.init&&f.init(this)})}if(this.format=this.options.interpolation.format,r||(r=Ur),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[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(u=>{this[u]=(...p)=>this.store[u](...p)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...p)=>(this.store[u](...p),this)});const a=rr(),c=()=>{const u=(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 u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),a}loadResources(e,r=Ur){let n=r;const o=Z(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(u=>{u!=="cimode"&&i.indexOf(u)<0&&i.push(u)})};o?s(o):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>s(c)),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=rr();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=Ur),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"&&Ai.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=rr();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,c)=>{c?this.isLanguageChangingTo===e&&(o(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,n.resolve((...u)=>this.t(...u)),r&&r(a,(...u)=>this.t(...u))},s=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const c=Z(a)?a:a&&a[0],u=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(Z(a)?[a]:a);u&&(this.language||o(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,p=>{i(p,u)})};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 c;typeof s!="object"?c=this.options.overloadTranslationOptionHandler([i,s].concat(a)):c={...s},c.lng=c.lng||o.lng,c.lngs=c.lngs||o.lngs,c.ns=c.ns||o.ns,c.keyPrefix!==""&&(c.keyPrefix=c.keyPrefix||n||o.keyPrefix);const u={...this.options,...c};typeof c.keyPrefix=="function"&&(c.keyPrefix=Ct(c.keyPrefix,u));const p=this.options.keySeparator||".";let l;return c.keyPrefix&&Array.isArray(i)?l=i.map(m=>(typeof m=="function"&&(m=Ct(m,u)),`${c.keyPrefix}${p}${m}`)):(typeof i=="function"&&(i=Ct(i,u)),l=c.keyPrefix?`${c.keyPrefix}${p}${i}`:i),this.t(l,c)};return Z(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,c)=>{const u=this.services.backendConnector.state[`${a}|${c}`];return u===-1||u===0||u===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=rr();return this.options.ns?(Z(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=rr();Z(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 Ei(Ln());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 Tr(e,r);return n.createInstance=Tr.createInstance,n}cloneInstance(e={},r=Ur){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const o={...this.options,...e,isClone:!0},i=new Tr(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((c,u)=>(c[u]={...this.store.data[u]},c[u]=Object.keys(c[u]).reduce((p,l)=>(p[l]={...c[u][l]},p),c[u]),c),{});i.store=new gi(a,o),i.services.resourceStore=i.store}if(e.interpolation){const c={...Ln().interpolation,...this.options.interpolation,...e.interpolation},u={...o,interpolation:c};i.services.interpolator=new bi(u)}return i.translator=new Sn(i.services,o),i.translator.on("*",(a,...c)=>{i.emit(a,...c)}),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 qe=Tr.createInstance(),Bc=qe.createInstance;qe.dir,qe.init,qe.loadResources,qe.reloadResources,qe.use,qe.changeLanguage,qe.getFixedT,qe.t,qe.exists,qe.setDefaultNamespace,qe.hasLoadedNamespace,qe.loadNamespaces,qe.loadLanguages;const Ti={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","error.QUERY_NOT_COVERED_BY_DATA_SOURCE":'The data sources connected to Schema "{schemaLabel}" cannot answer this query. Check their fields, dimension combinations, and time granularity.',"error.QUERY_NOT_COVERED_BY_DATA_SOURCE.dimensions":'No data source for Schema "{schemaLabel}" fully covers the required dimensions [{dimensions}]. Check the dimension combinations in the connected tables.',"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND":'No data mapping covers shard {shardNumber} of Schema "{schemaLabel}". Check whether its candidates cover the required dimensions and time granularity.',"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.dimensions":'No data source covers dimensions [{dimensions}] for shard {shardNumber} of Schema "{schemaLabel}".',"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison":'No data mapping covers both the current and comparison periods for shard {shardNumber} of Schema "{schemaLabel}". Check whether its candidates cover the required dimensions and time granularity.',"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison.dimensions":'No data source covers dimensions [{dimensions}] for both the current and comparison periods of shard {shardNumber} of Schema "{schemaLabel}".',"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.component":'No data mapping covers the component partition of Schema "{schemaLabel}". Check whether its candidates cover the required dimensions and time granularity.',"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"}},Pi={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","error.QUERY_NOT_COVERED_BY_DATA_SOURCE":"Schema\u300C{schemaLabel}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u65E0\u6CD5\u56DE\u7B54\u6B64\u95EE\u9898\u3002\u8BF7\u68C0\u67E5\u6570\u636E\u8868\u7684\u5B57\u6BB5\u3001\u7EF4\u5EA6\u7EC4\u5408\u548C\u65F6\u95F4\u7C92\u5EA6\u3002","error.QUERY_NOT_COVERED_BY_DATA_SOURCE.dimensions":"Schema\u300C{schemaLabel}\u300D\u6CA1\u6709\u6570\u636E\u8868\u80FD\u5B8C\u6574\u8986\u76D6\u67E5\u8BE2\u6240\u9700\u7EF4\u5EA6\u3010{dimensions}\u3011\u3002\u8BF7\u68C0\u67E5\u5DF2\u63A5\u5165\u6570\u636E\u8868\u7684\u7EF4\u5EA6\u7EC4\u5408\u3002","error.SCHEMA_PARTITION_MAPPING_NOT_FOUND":"Schema\u300C{schemaLabel}\u300D\u7684\u7B2C{shardNumber}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u53EF\u7528\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002","error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.dimensions":"Schema\u300C{schemaLabel}\u300D\u7684\u7B2C{shardNumber}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u6570\u636E\u8868\u80FD\u5B8C\u6574\u8986\u76D6\u7EF4\u5EA6\u3010{dimensions}\u3011\u3002","error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison":"Schema\u300C{schemaLabel}\u300D\u7684\u7B2C{shardNumber}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u540C\u65F6\u8986\u76D6\u672C\u671F\u548C\u5BF9\u6BD4\u671F\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002","error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison.dimensions":"Schema\u300C{schemaLabel}\u300D\u7684\u7B2C{shardNumber}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u6570\u636E\u8868\u80FD\u540C\u65F6\u8986\u76D6\u672C\u671F\u548C\u5BF9\u6BD4\u671F\u6240\u9700\u7EF4\u5EA6\u3010{dimensions}\u3011\u3002","error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.component":"Schema\u300C{schemaLabel}\u300D\u7684\u7EC4\u4EF6\u5206\u7247\u6CA1\u6709\u53EF\u7528\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002","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"}},Vc=[Pi,Ti],ir=t=>t.trim().toLowerCase(),Yc=t=>t?"locale"in t?[t]:t:[],Fc=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 Cn{definitions=new Map;i18n;constructor(e){this.i18n=Bc(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(Vc),this.register(e)}register(e){for(const r of Yc(e)){const n=r;if(!Fc(n))throw new TypeError("Locale definition must have a non-empty locale");const o=n,i=this.definitions.get(ir(o.locale)),s={locale:o.locale,messages:Object.freeze({...i?.messages,...o.messages})};this.definitions.set(ir(o.locale),s),this.i18n.addResourceBundle(o.locale,"translation",s.messages,!0,!0)}return this}resolve(e="zh-CN"){const r=this.definitions.get(ir(e));if(r)return r;const n=ir(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(ir(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 qr=t=>new Cn(t),kr=new Cn;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=kr){const n=this.details?.schemaLabel,o=this.details?.uncoveredDimensions,i=Array.isArray(o)&&o.length>0&&o.every(s=>typeof s=="string")?o.join(e.toLowerCase().startsWith("en")?", ":"\u3001"):void 0;if(this.code==="QUERY_NOT_COVERED_BY_DATA_SOURCE"&&typeof n=="string")return r.translate(e,i===void 0?"error.QUERY_NOT_COVERED_BY_DATA_SOURCE":"error.QUERY_NOT_COVERED_BY_DATA_SOURCE.dimensions",this.message,{schemaLabel:n,...i?{dimensions:i}:{}});if(this.code==="SCHEMA_PARTITION_MAPPING_NOT_FOUND"&&typeof n=="string"){const s=this.details?.shardIndex;if(typeof s=="number"){const a=this.details?.comparison?i===void 0?"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison":"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.comparison.dimensions":i===void 0?"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND":"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.dimensions";return r.translate(e,a,this.message,{schemaLabel:n,shardNumber:s+1,...i?{dimensions:i}:{}})}return r.translate(e,"error.SCHEMA_PARTITION_MAPPING_NOT_FOUND.component",this.message,{schemaLabel:n})}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 s=this.details?.schemaId,a=this.details?.schemaName,c=this.details?.property,u=this.details?.propertyName;if(typeof s=="string"&&typeof a=="string"&&typeof c=="string"&&typeof u=="string")return`Property not found in Schema: ${a}(${s}): ${u}`}return this.message}}le.extend(tr),le.extend(Cr);const Hc=new Set(["year","quarter","month","week"]),Dn=t=>t.format("YYYY-MM-DD HH:mm:ss"),Mn=(t,e)=>t.operator&&e(t.operator).kind==="aggregate"?!0:(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Mn(t.pred,e):!1)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Mn(r,e)),jr=(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:jr(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:jr(t.input,e,r)}:{},...t.inputs?{inputs:t.inputs.map(o=>jr(o,e,r))}:{}}},Qc=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 jr(t.input,t,{partitionBy:e.map(o=>t.resolveKey(String(o))),orderBy:n})},vc=t=>{if(t.groupByNames.length===0)return;if(typeof t.pred.pred!="object"||Array.isArray(t.pred.pred)||!Mn(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})},Gc=(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(([,w])=>{if(typeof w!="object"||w===null||Array.isArray(w))return!1;const L=w;return typeof L.$gte=="string"&&typeof L.$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=le(String(s.$gte)),c=le(String(s.$lte));if(!a.isValid()||!c.isValid())throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","Target date range is invalid");const u=e.map(w=>{if(!w.name)throw new d("MISSING_PRED_NAME","$accumulate args.period requires normalized names");return w.name}),p=r==="week"?a.startOf("isoWeek"):a.startOf(r),l={...t.query,[o]:{...s,$gte:Dn(p)}},m=new Set([...(t.groupby??[]).map(({name:w})=>w),...(t.preds??[]).map(({name:w})=>w)]),f=w=>{let L=w;for(;m.has(L);)L=`_${L}`;return m.add(L),L},h=f("__accumulate_period"),y=e.map((w,L)=>f(`__accumulate_metric_${L}`)),$=(t.groupby??[]).map(({name:w})=>String(w)),E=r==="year"||r==="quarter"?"month":"day",A={version:t.version,...t.schema?{schema:t.schema}:{},query:l,groupby:[...t.groupby??[],{operator:"$dateBucket",pred:o,args:{granularity:E},name:h}],preds:e.map((w,L)=>({...w.pred,name:y[L]??`__accumulate_metric_${L}`}))},g={version:t.version,from:A,preds:[...$.map(w=>({pred:w,name:w})),{pred:h,name:h},...e.map((w,L)=>({operator:"$accumulate",pred:y[L]??`__accumulate_metric_${L}`,args:{partitionBy:$,orderBy:[{pred:h,direction:"asc"}]},name:u[L]??`accumulate_${L}`}))]};return{version:t.version,from:g,query:{[h]:{$gte:Dn(a),$lte:Dn(c)}},preds:[...$.map(w=>({pred:w,name:w})),...u.map(w=>({pred:w,name:w}))],...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}:{}}},zc={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"||!Hc.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:Qc,validatePlan:vc,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 Gc(t,r,n)},getOutputProperty({name:t,inputProperty:e}){return e?{...e,name:t,isArray:!1}:{name:t,type:"number",primal_type:"number",isArray:!1}}},Wc={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}}},Dt=(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},xr=t=>({name:t,type:"number",primal_type:"number",isArray:!1}),Kc={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`(${Dt("$add",t,2,Number.POSITIVE_INFINITY).join(" + ")})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:xr(t)}},ae=t=>structuredClone(t),Li=(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},Jc=(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},Xc=t=>{const e=t.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(e))},Ci=(t,e)=>t.properties.some(r=>r!==e&&r.id===e.name)?e.id:e.name,Zc=(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)),oe=(t,e,r)=>{const n=t.properties.find(o=>o.id===e)??t.properties.find(o=>o.name===e);if(n)return{canonicalName:Ci(t,n),canonicalId:n.id,schema:t,property:n,relations:[]};for(const{property:o,prefix:i}of Zc(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=oe(s,e.slice(i.length+1),r);return{canonicalName:`${Ci(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})},Un=(t,e)=>t.name===e||t.id===e,eu=(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=>Un(a,i.hierarchy?.up??"")):[],...r.properties.filter(a=>a.hierarchy?.down!==void 0&&Un(i,a.hierarchy.down))];if(s.some(a=>Un(e,a.name)))return!0;o.push(...s)}return!1},Di=(t,e,r,n)=>{if(t.operator||typeof t.pred!="string"||e.length===0)return!1;let o;try{o=oe(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=oe(r,i.pred,n)}catch{return!1}if(s.property.isArray)return!1;if(s.relations.length===0&&o.relations.length===0)return eu(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})},tu=({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:c})=>c==="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}}},ru=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},nu=(t,e,r)=>{const n=oe(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}},ou={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(h=>h!=="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=nu(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:h})=>h===s.property);if(!a)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${s.property}`);if(!i.relation&&a.name!==oe(r,t,n).property.name)throw new d("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${a.name}`);const c=s.levels.reduce((h,y)=>h+y.codeLength,0),u=i.schema.properties.filter(({type:h})=>h==="ID"),l=i.relation&&u.length===1&&u[0]?.name===a.name?i.reference:i.relation?`${i.reference}_${a.name}`:i.reference;if(e.level===void 0){let h=0;return{reference:l,args:{levels:s.levels.map(({name:y,codeLength:$})=>(h+=$,{name:y,codeLength:h})),totalLength:c,storage:s.storage}}}let m=0;const f=s.levels.find(h=>(m+=h.codeLength,h.name===e.level||h.syno?.includes(e.level)));if(!f)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:f.name,codeLength:m,totalLength:c,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 c=e.levels.filter(h=>typeof h=="object"&&h!==null&&!Array.isArray(h)&&typeof h.name=="string"&&Number.isInteger(h.codeLength)),u=e.totalLength,p=e.storage;if(c.length!==e.levels.length||c.length===0||!Number.isInteger(u)||Number(u)<=0||c.some(({name:h,codeLength:y},$)=>h.length===0||y<=0||y>Number(u)||$>0&&y<=Number(c[$-1]?.codeLength))||c.at(-1)?.codeLength!==u||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 h=r.stringLength(t),y=c.map($=>`WHEN ${h} = ${$.codeLength} THEN ${r.value($.name)}`);return`(CASE ${l} ${y.join(" ")} ELSE NULL END)`}const m=c.slice(0,-1).map(h=>{const y=Number(u)-h.codeLength;return`WHEN ${r.substring(t,h.codeLength+1,y)} = ${r.value("0".repeat(y))} THEN ${r.value(h.name)}`}),f=c.at(-1);return`(CASE ${l} ${m.join(" ")} ELSE ${r.value(f?.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}}},Mt=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},Ut=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),qn=(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)}},Br=(t,{schema:e,mapping:r})=>r.mappings?.find(n=>n.mappingType==="property"&&n.propertyTarget?.some(o=>Ut(e,o)?.id===t.id)),Mi=(t,e,r)=>{const n=Ut(r.schema,t);if(!n)return`hierarchy property is not available: ${t}`;const o=qn(n,e,r);if(!o)return`hierarchy level is not available: ${String(e)}`;const i=Br(n,r);if(!Mt(i?.granularity))return;const s=qn(n,i.granularity.level,r);return s&&s.index>=o.index?void 0:`hierarchy dimension ${t} requires ${o.name}, but source has ${s?.name}`},iu=(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 c=Mi(i.pred,i.args.level,e);if(c)return c}else{const c=Ut(e.schema,i.pred),u=c&&Br(c,e);if(Mt(u?.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 c of a){if(typeof c=="string")continue;const u=r(c);if(u)return u}},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 c of a){const u=n(c);if(u)return u}}else if(s==="$expr"){if(typeof a!="object"||a===null||Array.isArray(a))continue;const c=a.pred;if(typeof c!="object"||c===null||Array.isArray(c))continue;const u=r(c);if(u)return u}else if(!s.startsWith("$")){const c=Ut(e.schema,s),u=c&&Br(c,e);if(Mt(u?.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=Mi(i.pred,i.args?.level,e);if(s)return s}else if(i.operator===void 0){const s=Ut(e.schema,i.pred),a=s&&Br(s,e);if(Mt(a?.granularity))return`raw groupby is not covered by hierarchy-grained source: ${i.pred}`}}},su={kind:"hierarchy",isGranularity:Mt,validateItem(t,e){const r=t.granularity;if(Mt(r))return t.propertyTarget?.every(n=>{const o=Ut(e.schema,n);return o!==void 0&&qn(o,r.level,e)!==void 0})?void 0:"physical hierarchy granularity requires a mapped hierarchy Property and level"},candidateReason:iu,supportsGroupby:t=>t.operator==="$hierarchyLevel"},au={keys:["hierarchy"],resolve(t,e){for(const m of e)if(m.level!==void 0){if(typeof m.level!="string"||m.level.trim().length===0)throw new d("INVALID_PROPERTY_LEVEL",`Property ${m.name} level must be a non-empty string`,{property:m.name,level:m.level});if(m.primal_type!=="entity"&&m.primal_type!=="object")throw new d("PROPERTY_LEVEL_REQUIRES_ENTITY",`Property ${m.name} level requires an entity relation`,{property:m.name,type:m.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(m=>m!=="property"&&m!=="storage"&&m!=="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 m=e.filter(f=>f.type==="ID");if(m.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:m.length});return m[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(m=>m.name===n.property||m.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 c=new Set,u=new Set,p=n.levels.map((m,f)=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${f} must be an object`);const h=m,y=Object.keys(h).filter(E=>E!=="name"&&E!=="syno"&&E!=="codeLength");if(y.length>0)throw new d("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${f} only supports name, syno, and codeLength`,{unsupportedKeys:y});if(typeof h.name!="string"||h.name.length===0)throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${f} name must not be empty`);if(c.has(h.name)||u.has(h.name))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level name: ${h.name}`);if(!Number.isInteger(h.codeLength)||Number(h.codeLength)<=0)throw new d("INVALID_HIERARCHY_CODE_LENGTH",`Hierarchy level ${h.name} codeLength must be a positive integer`);if(h.syno!==void 0&&(!Array.isArray(h.syno)||h.syno.some(E=>typeof E!="string"||E.length===0)))throw new d("INVALID_HIERARCHY_SYNONYMS",`Hierarchy level ${h.name} syno must contain only non-empty strings`);const $=h.syno??[];for(const E of $){if(E===h.name||c.has(E)||u.has(E))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${E}`);u.add(E)}return c.add(h.name),{name:h.name,...$.length>0?{syno:[...$]}:{},codeLength:Number(h.codeLength)}});return{hierarchy:{property:s.name,storage:a,levels:p}}}},cu=Object.freeze({name:"hierarchy",schemaMetadata:au,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:tu,resolveEntityFilterProperty:ru,operators:[ou],mappingGranularity:su}),uu=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp"),kn="$periodValue",du=(t,e,r)=>{const n=e?.periodBoundaryPolicy?.({pred:t,...r?{executionContext:r}:{}});if(n)return{operator:kn,...n};if(e?.kind==="aggregate")throw new d("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${kn}; ${e.name} describes a time range`,{operator:e.name});return{operator:kn,boundary:"end",implicit:!0}},pu={name:"observation",resolveProjection({pred:t,schema:e,sourceProperty:r,outputProperty:n,operator:o,executionContext:i}){if(!r||!uu(r,e))return;const s=du(t,o,i);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:s.boundary,sourceProperty:r.name}}}}},lu=new Set(["second","minute","hour","day","week","month","quarter","year"]),Ui=t=>typeof t=="string"&&lu.has(t),fu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Vr=(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},ht=(t,e=2)=>String(t).padStart(e,"0"),jn=t=>`${ht(t.getFullYear(),4)}-${ht(t.getMonth()+1)}-${ht(t.getDate())} ${ht(t.getHours())}:${ht(t.getMinutes())}:${ht(t.getSeconds())}.`+ht(t.getMilliseconds(),3),mu=(t,e)=>{if(!fu(t)){const a=Vr(t,"point",e);return{lower:a,upper:a}}const r=t.$eq;if(r!==void 0){const a=Vr(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=Vr(n,t.$gte!==void 0?"$gte":"$gt",e)+(t.$gte===void 0?1:0),s=Vr(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}},yu=(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},hu=(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},qi=(t,e,r)=>{const{lower:n,upper:o}=mu(t,r),i=[];let s=yu(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=hu(s,e),c=new Date(Math.min(a.getTime()-1,o));i.push({label:jn(s),start:jn(s),end:jn(c)}),s=a}return i},gu=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.name),Au=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.name)),$u=(t,e)=>{if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:l})=>l==="timestamp");if(!r)return;const n=gu(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"||!Ui(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 m=l.args?.boundary;if(m!=="start"&&m!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:m});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 u=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:u,metrics:a,periods:qi(p,s,{codePrefix:"OBSERVATION",label:"Observation"}).map(l=>({label:l.label,asOf:l[u]}))}},ki=["second","minute","hour","day","week","month","quarter","year"],wu=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:[pu],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(ki.indexOf(o)>ki.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=$u(t,e);if(r)return{group:r.group,property:r.timestamp,periods:r.periods,source:{kind:"latest",timestamp:r.timestamp},rewriteQuery:n=>Au(n,r.timestamp),rewritePred:n=>r.metrics.find(o=>o.pred===n)?.effectivePred??n}}}}),sr=(t,e)=>typeof e=="string"?t.properties.find(({id:r,name:n})=>r===e||n===e):void 0,Eu={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:m})=>m==="ID"),a=i===void 0?s.length===1?s[0]:void 0:sr(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 c=Array.isArray(r.roots),u=c?r.roots:r.root===void 0?[]:[r.root];if(!c&&u.length===0||u.some(m=>m===void 0))throw new d("RECURSIVE_ROOT_REQUIRED","$recursive requires root or roots");const p=await Promise.all(u.map(m=>e.normalizeValue(m,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:u})=>u==="ID"):sr(o,i),a=r.parentProperty??r.parent_property??o.parentProperty??"pid",c=sr(o,a);s&&e.assertPropertyAllowed(o,s),c&&e.assertPropertyAllowed(o,c)},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=sr(o,r.idProperty),s=sr(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__"),c=r.quoteIdentifier("__recursive_id__"),u=r.quoteIdentifier("__recursive_node__"),p=r.quoteIdentifier("__recursive_child__"),l=r.quoteIdentifier(i.idColumn),m=r.quoteIdentifier(i.parentColumn),f=o(i.source,typeof i.sourceSql=="string"?i.sourceSql:void 0),h=()=>s.map(w=>n(w)).join(", "),y=(w,L=!1)=>s.length===1?`${w} ${L?"<>":"="} ${h()}`:`${w} ${L?"NOT IN":"IN"} (${h()})`,$=`${u}.${l}`,E=i.includeSelf?y($):`${y(`${u}.${m}`)} AND ${y($,!0)}`,A=r.recursiveCteUnion??"UNION",g=`(WITH RECURSIVE ${a}(${c}) AS ( SELECT ${$} FROM ${r.tableAlias(f,"__recursive_node__")} WHERE ${E} ${A} SELECT ${p}.${l} FROM ${r.tableAlias(f,"__recursive_child__")} JOIN ${a} ON ${p}.${m} = ${a}.${c}) SELECT DISTINCT ${c} FROM ${a})`;return`${e} IN ${g}`}},_u=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:[Eu]});le.extend(tr);const xn=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...xn(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:xn(r))]:e},ji=(t,e)=>le(t).endOf(e==="week"?"isoWeek":e).toDate(),Bn=t=>le(t).format("YYYY-MM-DD HH:mm:ss"),Iu=(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})},xi=(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})},Su=Object.freeze({name:"temporal",schemaMetadata:{keys:["timeWatermark"],resolve(t){return xi(t.timeWatermark,`Schema ${t.id}`),{...t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}}},propertyMetadata:{keys:["timeWatermark"],resolve(t,e){if(xi(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 c=[...new Set((t.preds??[]).flatMap(xn).filter(l=>l!==e.id))],u=[{schema:e,property:r}];for(const l of c){const m=s(l),f=t.propertyResolve?.[l],h=f?.[r.id]??f?.[r.name]??a(e,r.name,m);if(!h)throw new d("TIME_WATERMARK_PROPERTY_RESOLVE_REQUIRED",`Cross-Schema timeWatermark requires propertyResolve for ${l}.${r.name}`,{schemaId:l,property:r.name});const y=m.properties.find(({id:$,name:E})=>$===h||E===h);if(!y||y.primal_type!=="date")throw new d("TIME_WATERMARK_PROPERTY_REQUIRED",`timeWatermark Property is not a date Property: ${l}.${h}`,{schemaId:l,property:h});u.push({schema:m,property:y})}const p=u.map(({schema:l,property:m})=>{const f=Iu(m.timeWatermark??l.timeWatermark??i,`${l.id}.${m.id}`);if(f.type==="now_offset"){const h=ji(le(o).add(f.offset,"day").toDate(),m.granularity??"day");return{operator:"$constant",args:{value:Bn(h),type:"timestamp"},name:`${l.name}\u6570\u636E\u65F6\u95F4`}}return{operator:"$periodBoundary",args:{boundary:"end"},pred:{operator:"$max",pred:m.name,schema:l.id},name:`${l.name}\u6700\u65B0\u65F6\u95F4`}});return p.some(({operator:l})=>l==="$periodBoundary")&&p.push({operator:"$constant",args:{value:Bn(ji(o,r.granularity??"day")),type:"timestamp"},name:"\u73B0\u5728"}),p.push({operator:"$constant",args:{value:Bn(n),type:"timestamp"},name:"\u63D0\u95EE\u65F6\u95F4\u4E0A\u754C"}),{version:t.version,schema:e.id,preds:[{name:"__timeWatermark__",operator:"$least",pred:p}]}}}),Yr=(t,e)=>{const r=t.filter(n=>n.type===e);return r.length===1?r[0]:void 0},ar=t=>{if(t.type!=="entity"||t.temporalSemantics==="snapshot")return;const e=Yr(t.properties,"ID"),r=Yr(t.properties,"timestamp"),n=Yr(t.properties,"start_date"),o=Yr(t.properties,"end_date");return e&&r&&n&&o?{id:e,timestamp:r,start:n,end:o}:void 0},Bi=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.timestamp.name),bu=(t,e)=>Bi(t,e)!==void 0,Ru=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.timestamp.name)),Nu=(t,e)=>{const r=Bi(t,e);if(!r)return;const n=r.args?.granularity;if(r.operator!=="$dateBucket"||!Ui(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:qi(o,n,{codePrefix:"VALIDITY",label:"Valid-time"}).map(({label:i,end:s})=>({label:i,asOf:s}))}},Ou=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Tu=t=>Ou(t)?t.$lte??t.$lt??t.$eq:t,Vi=(t,e)=>{if(!t)return t;const r=Object.fromEntries(Object.entries(t).map(([a,c])=>[a,(a==="$and"||a==="$or")&&Array.isArray(c)?c.map(u=>Vi(u,e)):c])),n=Object.entries(t).find(([a])=>a===e.timestamp.name);if(!n)return r;const[,o]=n,i=Tu(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}]}}},Yi=(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&&Yi(o,e)))),Pu={name:"validity",resolveQuery({logicform:t,schema:e,query:r}){const n=ar(e);if(!n)return r;if(bu(t,n))return Ru(r,n);const i=Yi(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:new Date().toISOString()}};return Vi(i,n)},resolveProjection({schema:t,outputProperty:e}){if(ar(t))return{outputProperty:{...e,temporal:{kind:"validity"}}}}},Lu={name:"start_date",primalType:"date"},Cu={name:"end_date",primalType:"date"},Du=Object.freeze({name:"validity",semanticTypes:[Lu,Cu],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:[Pu],intervalSemantics:{resolve:ar},relationSemantics:{plan({sourceSchema:t,targetSchema:e}){const r=ar(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=ar(e);if(!r)return;const n=Nu(t,r);return n?{group:n.group,property:r.timestamp,periods:n.periods,source:{kind:"interval",start:r.start,end:r.end}}:void 0}}}),Fi=(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},Mu=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,c=Object.keys(a).filter(l=>l!=="up"&&l!=="down");if(c.length>0)throw new d("UNSUPPORTED_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy only supports up and down`,{property:o.name,unsupported:c});const u=Fi(t,o,a.up,"up"),p=Fi(t,o,a.down,"down");return{...o,hierarchy:{...u?{up:u}:{},...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}}}),Fr=Object.freeze([cu,_u,Su,wu,Du,Mu]),be=(t=[])=>{const e=[...Fr,...t],r=new Set,n=new Set,o=new Set,i=new Set,s=new Set,a=new Set,c=new Set,u=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 f of[...l.schemaMetadata?.keys??[],...l.legacySchemaKeys??[]]){if(!f)throw new d("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(n.has(f))throw new d("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${f}`,{key:f,plugin:l.name});n.add(f)}for(const f of l.propertyMetadata?.keys??[]){if(!f)throw new d("INVALID_PLUGIN_PROPERTY_METADATA_KEY","Plugin Property metadata key must not be empty");if(o.has(f))throw new d("PLUGIN_PROPERTY_METADATA_KEY_ALREADY_REGISTERED",`Plugin Property metadata key is already registered: ${f}`,{key:f,plugin:l.name});o.add(f)}for(const f of l.operators??[]){if(i.has(f.name))throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${f.name}`,{operator:f.name,plugin:l.name});i.add(f.name)}for(const f of l.semanticTypes??[]){if(s.has(f.name))throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${f.name}`,{semanticType:f.name,plugin:l.name});s.add(f.name)}for(const f of l.plannerSemantics??[]){if(!f.name||a.has(f.name))throw new d("PLUGIN_SEMANTIC_RULE_ALREADY_REGISTERED",`Plugin Planner semantic rule must be non-empty and unique: ${f.name}`,{rule:f.name,plugin:l.name});a.add(f.name)}for(const f of l.queryOperators??[]){if(!f.name||c.has(f.name))throw new d("PLUGIN_QUERY_OPERATOR_ALREADY_REGISTERED",`Plugin Query Operator must be non-empty and unique: ${f.name}`,{operator:f.name,plugin:l.name});c.add(f.name)}for(const f of l.outputHandlers??[]){if(!f.type||u.has(f.type))throw new d("PLUGIN_OUTPUT_HANDLER_ALREADY_REGISTERED",`Plugin output handler type must be non-empty and unique: ${f.type}`,{type:f.type,plugin:l.name});u.add(f.type)}const m=l.mappingGranularity;if(m){if(!m.kind||p.has(m.kind))throw new d("PLUGIN_GRANULARITY_ALREADY_REGISTERED",`Plugin physical granularity kind must be non-empty and unique: ${m.kind}`);p.add(m.kind)}}return Object.freeze(e)},qt=(t,e=[])=>be(e).flatMap(r=>r.queryOperators??[]).find(r=>r.name===t),Vn=(t,e=[])=>be(e).flatMap(r=>r.outputHandlers??[]).find(r=>r.type===t),Yn=(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},Fn=(t,e=[])=>Yn("interval semantics",be(e).flatMap(r=>{const n=r.intervalSemantics?.resolve(t);return n?[{plugin:r.name,value:n}]:[]})),Uu=(t,e,r=[])=>Yn("relation semantics",be(r).flatMap(n=>{const o=n.relationSemantics?.plan({sourceSchema:t,targetSchema:e});return o?[{plugin:n.name,value:o}]:[]})),qu=(t,e,r=[])=>Yn("planner period semantics",be(r).flatMap(n=>{const o=n.plannerPeriod?.resolve(t,e);return o?[{plugin:n.name,value:o}]:[]})),Hn=t=>typeof t=="string"&&t.length>0&&t!=="placeholder"||typeof t=="number"&&Number.isSafeInteger(t),ku=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]},Qn=(t,e=[])=>{for(const r of be(e)){const n=r.resolveEntityFilterProperty?.(t);if(n)return n}return ku(t)},vn=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,ju=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),xu={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Bu={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},zn=(t,e,r)=>{const n=e.toLowerCase().startsWith("en"),o=t.time;if(!ju(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}${xu[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${Bu[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};le.extend(tr),le.extend(Cr);const Vu=["second","minute","hour","day","week","month","quarter","year"],Yu=new Set(Vu),Wn=["year","quarter","month","week","day","hour","minute","second"],Hi=t=>Object.prototype.toString.call(t)==="[object Object]",ut=t=>{throw new d("INVALID_PERIOD_SHIFT_ARGS",t)},Fu=t=>{const e=t.time;Hi(e)||ut("$periodShift requires args.time");const r=e;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!Yu.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&ut("Relative period shift time requires only granularity and an integer offset"),r;const o=Object.entries(r);(o.length===0||o.some(([a,c])=>!Wn.includes(a)||!Number.isInteger(c)))&&ut("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&ut("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,[c,u]]of Object.entries(i)){const p=r[a];p!==void 0&&(Number(p)<c||Number(p)>u)&&ut(`Invalid absolute period shift ${a}: ${JSON.stringify(p)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&ut("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&ut("Absolute period shift day requires month"),r},Qi=(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),Hu=(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 Wn){const o=e[n];typeof o=="number"&&(r=Qi(r,n,o))}return r},Kn=(t,e)=>t instanceof Date?e.toDate():typeof t!="string"?t:e.format(t.includes(":")?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"),Qu=(t,e,r,n,o)=>(t.groupby??[]).filter(i=>{const s=Gn(i);return s?oe(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",c="granularity"in n?-n.offset:o.originalAnchor&&o.shiftedAnchor?o.originalAnchor.diff(o.shiftedAnchor,a):0;return{name:vn(i),granularity:a,offset:c}}),Jn=(t,e,r)=>{if(Array.isArray(t))return t.map(i=>Jn(i,e,r));if(Hi(t))return Object.fromEntries(Object.entries(t).map(([i,s])=>[i,Jn(s,e,r)]));if(!(t instanceof Date)&&typeof t!="string")return t;const n=le(t);if(!n.isValid())return t;const o=Hu(n,e);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,Kn(t,o)},vi=(t,e,r,n,o)=>{const i=new Set,s=c=>Object.fromEntries(Object.entries(c).map(([u,p])=>{if((u==="$and"||u==="$or")&&Array.isArray(p))return[u,p.map(m=>s(m))];const l=oe(e,u,r);return l.property.primal_type!=="date"?[u,p]:(i.add(l.canonicalName),[u,Jn(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},gt=t=>{const e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?e[0]:{$and:e}},dt=t=>[...t.query?[t.query]:[],...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?dt(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(r=>typeof r=="string"?[]:dt(r)):[]],vu=(t,e,r)=>{if(!(t instanceof Date)&&typeof t!="string")return t;const n=le(t);if(!n.isValid())return t;if("granularity"in e)return Kn(t,n.add(-e.offset,e.granularity));if(!r.originalAnchor)return t;let o=n;for(const i of Wn)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=Qi(o,i,s)}return Kn(t,o)},Xn=({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o})=>{const i=e.pred;(!i||typeof i!="object"||Array.isArray(i))&&ut("$periodShift pred must be a nested metric");const s=Fu(e.args??{}),a={shiftedValues:0},c=gt([t.query,...dt(e)]);if(!c)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const u=vi(c,n,o,s,a),p=ae(i);p.name=r,delete p.query;const l=ae(t);l.query=u,l.preds=[p],delete l.having,delete l.sort,delete l.limit,delete l.page;const m=new Set((t.groupby??[]).filter(f=>{const h=Gn(f);return h?oe(n,h,o).property.primal_type==="date":!1}).map(vn));return{kind:"query",logicform:l,partitionCurrentLogicform:{...ae(t),query:c,preds:[{...ae(p),name:"__partition_current__"}]},partitionQuery:f=>vi(f,n,o,s,{shiftedValues:0}),groupKeyShifts:Qu(t,n,o,s,a),mapResult:f=>f.map(h=>{const y={...h};for(const $ of m)y[$]=vu(y[$],s,a);return y})}},Gu={name:"$periodShift",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=zn(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:Xn,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodShift requires a nested metric");return{...e,name:t,isArray:!1}}},zu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Hr=t=>typeof t=="string"||typeof t=="number"||t instanceof Date,Gi=(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},zi=(t,e)=>{if(Hr(t)){e.start??=t,e.end??=t;return}if(!zu(t))return;const r=t.$eq;Hr(r)&&(e.start??=r,e.end??=r);const n=t.$gte??t.$gt,o=t.$lte??t.$lt;Hr(n)&&(e.start??=n),Hr(o)&&(e.end??=o);for(const i of["$and","$or"]){const s=t[i];if(Array.isArray(s))for(const a of s)zi(a,e)}},Wu=(t,e,r,n)=>{const o=Gi(e,n),i=new Set,s={},a=(l,m)=>{for(const[f,h]of Object.entries(l)){if((f==="$and"||f==="$or")&&Array.isArray(h)){for(const $ of h)a($,m||f==="$or");continue}if(f.startsWith("$"))continue;const y=oe(e,f,r);if(y.property.type==="timestamp"){if(m)throw new d("AMBIGUOUS_TIME_QUERY",`${n} does not support timestamp conditions inside $or`);i.add(y.canonicalName),zi(h,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 c=[...i][0];if(!c||c!==o.name)throw new d("AMBIGUOUS_TIME_QUERY",`${n} requires the Schema timestamp property: ${o.name}`);const u=l=>{const m=[];for(const[f,h]of Object.entries(l)){if((f==="$and"||f==="$or")&&Array.isArray(h)){const y=h.map($=>u($)).filter($=>$!==void 0);y.length>0&&m.push([f,y]);continue}!f.startsWith("$")&&oe(e,f,r).property.type==="timestamp"||m.push([f,h])}return m.length>0?Object.fromEntries(m):void 0},p=u(t);return{property:o,propertyName:c,...s.start!==void 0?{start:s.start}:{},...s.end!==void 0?{end:s.end}:{},...p?{queryWithoutTime:p}:{}}},Wi=(t,e,r,n,o)=>{const i=gt([t,...dt(e)]);if(!i)throw new d("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return Wu(i,r,n,o)},Ki=(t,e,r)=>gt([t,{[e]:r}]),Ku=new Set(["day","week","month","quarter","year"]),Ju={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Xu=t=>{if(typeof t!="string"||!Ku.has(t))throw new d("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return t},Ji=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Zn=t=>{const e=ae(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Zn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Zn(r))),e},Zu={name:"$averagePerPeriod",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${t} per ${typeof e.granularity=="string"?e.granularity:"period"}`:`${t}${Ju[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=Xu(e.args?.granularity),s=Gi(r,"$averagePerPeriod"),a=Zn(e.pred),c=gt([t.query,...dt(e)]),u=Ji(t);u.preds=[{...a,name:"__avg_period_num__"}],c&&(u.query=c);const p=Ji(t);p.preds=[{operator:"$countDistinct",pred:{operator:"$dateBucket",pred:s.name,args:{granularity:i},name:"__avg_period_bucket__"},name:"__avg_period_den__"}],c&&(p.query=c);const l=o("component.numerator",`${n}\u5206\u5B50`,{outputName:n}),m=o("component.denominator",`${n}\u5206\u6BCD`,{outputName:n});return{components:[{name:l,logicform:u},{name:m,logicform:p}],expression:`${l} / NULLIF(${m}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$averagePerPeriod requires a nested metric");return{...e,name:t,isArray:!1}}},ed={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}}},kt=t=>{throw new d("INVALID_CASE_ARGS",t)},td=t=>{if(t.mode!=="auto")return;Object.hasOwn(t,"cases")&&kt("$case auto mode cannot define args.cases"),t.empty!==void 0&&typeof t.empty!="boolean"&&kt("$case auto mode args.empty must be boolean");const e=t.buckets;e!==void 0&&(!Number.isInteger(e)||e<2||e>100)&&kt("$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)&&kt("$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]))&&kt(`$case auto mode requires resolved finite args.${o}`);t.min>t.max&&kt("$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}},rd=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},Qr=t=>{const e=Number(t.toPrecision(15));return Object.is(e,-0)?0:e},eo=t=>String(Qr(t)),nd=(t,e,r)=>{if(t===e)return[t,e];const n=rd((e-t)/r),o=Qr(Math.floor(t/n)*n),i=Qr(Math.ceil(e/n)*n),s=Math.max(1,Math.round((i-o)/n));return Array.from({length:s+1},(a,c)=>c===s?i:Qr(o+n*c))},od=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}})},id={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=td(e);if(n){const s=r.value("\u672A\u77E5");if(n.empty)return s;const a=n.minimum,c=n.maximum;if(a===c)return`CASE WHEN ${t} IS NULL THEN ${s} ELSE ${r.value(eo(a))} END`;const u=nd(a,c,n.targetBuckets),p=u.slice(0,-1).map((m,f)=>{const h=u[f+1],y=f===u.length-2?"]":")";return`[${eo(m)}, ${eo(h)}${y}`}),l=p.slice(0,-1).map((m,f)=>`WHEN ${t} < ${r.value(u[f+1])} THEN ${r.value(m)}`);return`CASE WHEN ${t} IS NULL THEN ${s} ${l.join(" ")} ELSE ${r.value(p.at(-1))} END`}const o=od(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}}},sd={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(Dt("$concat",t,1,Number.POSITIVE_INFINITY))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},ad={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}}},cd={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}}},ud=new Set(["second","minute","hour","day","week","month","quarter","year"]),dd={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Xi=t=>{if(typeof t!="string"||!ud.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},pd={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${dd[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,Xi(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=Xi(r.granularity);return{...e,name:t,type:"date",primal_type:"date",isArray:!1,granularity:n}}},ld={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]=Dt("$divide",t,2);return`(${e} / NULLIF(${r}, 0))`},getOutputProperty({name:t}){return xr(t)}},fd=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}}}},md={name:"$max",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Maximum ${t}`:`${t}\u6700\u5927\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:fd,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}:{}}}},yd=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}}}},hd={name:"$min",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Minimum ${t}`:`${t}\u6700\u5C0F\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:yd,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}:{}}}},gd={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`(${Dt("$multiply",t,2,Number.POSITIVE_INFINITY).join(" * ")})`},getOutputProperty({name:t}){return xr(t)}},Ad=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},to=t=>{const e=ae(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=to(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:to(r))),e},$d={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 m=Gn(l);return m?oe(r,m,n).property.type==="timestamp":!1}))throw new d("NEWLY_TIME_GROUPBY_UNSUPPORTED","$newly does not support grouping by the timestamp property");const s=Wi(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=to(e.pred),c=(l,m)=>{const f=Ad(t);return f.query=Ki(s.queryWithoutTime,s.propertyName,{$lte:l}),f.preds=[{...a,name:m}],f},u=i("component.end",`${o}\u7ED3\u675F`,{outputName:o}),p=i("component.start",`${o}\u5F00\u59CB`,{outputName:o});return{components:[{name:u,logicform:c(s.end,"__newly_end__")},{name:p,logicform:c(s.start,"__newly_start__")}],expression:`${u} - COALESCE(${p}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$newly requires a nested metric");return{...e,name:t,isArray:!1}}},wd=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},ro=t=>{const e=ae(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=ro(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:ro(r))),e},Ed={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=Wi(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 c={version:t.version,schema:n.id,query:{[s.propertyName]:{$lte:a}},preds:[{operator:"$max",pred:s.propertyName,name:"__period_boundary_date__"}]},u=wd(t);return u.query=Ki(s.queryWithoutTime,s.propertyName,c),u.preds=[{...ro(e.pred),name:r}],{kind:"query",logicform:u}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodValue requires a nested metric");return{...e,name:t,isArray:!1}}},_d=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Id=({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=ae(e.pred);a.name="__period_diff_current__";const c=_d(t);c.preds=[a];const u=gt([t.query,...dt(e)]);u&&(c.query=u);const p={pred:ae(e.pred),...e.args?{args:e.args}:{}},l=Xn({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 m=o("component.current",`${r}\u672C\u671F`,{outputName:r}),f=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:m,logicform:c},{name:f,logicform:l.logicform,comparisonOf:m,...l.partitionQuery?{partitionQuery:l.partitionQuery}:{},...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${m} - ${f}`}},Sd={name:"$periodDifference",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=zn(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:Id,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodDifference requires a nested metric");return{...e,name:t,isArray:!1}}},bd=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Rd=({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=ae(e.pred);a.name="__period_growth_current__";const c=bd(t);c.preds=[a];const u=gt([t.query,...dt(e)]);u&&(c.query=u);const p={pred:ae(e.pred),...e.args?{args:e.args}:{}},l=Xn({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 m=o("component.current",`${r}\u672C\u671F`,{outputName:r}),f=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:m,logicform:c},{name:f,logicform:l.logicform,comparisonOf:m,...l.partitionQuery?{partitionQuery:l.partitionQuery}:{},...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${m} / NULLIF(ABS(${f}), 0) - 1`}},Nd={name:"$periodGrowth",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=zn(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:Rd,getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},Od={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}}},Td={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]=Dt("$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}:xr(t)}},Zi=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},no=t=>{const e=ae(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=no(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:no(r))),e},Pd={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(h=>typeof h.pred=="string"&&h.pred===o||vn(h)===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((h,y)=>y!==s),c=no(e.pred),u=Zi(t);u.preds=[{...c,name:"__share_numerator__"}];const p=gt([t.query,...dt(e)]);p&&(u.query=p);const l=Zi(t);l.groupby=a,l.preds=[{...c,name:"__share_denominator__"}];const m=n("component.numerator",`${r}\u5206\u5B50`,{outputName:r}),f=n("component.denominator",`${r}\u5206\u6BCD`,{outputName:r});return{components:[{name:m,logicform:u},{name:f,logicform:l}],expression:`${m} / NULLIF(${f}, 0)`}},getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},Ld={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}}},es=(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 c=t[a];if(!c)continue;if(s){o+=c,c===s&&(t[a+1]===s?(o+=s,a+=1):s=void 0);continue}if(c==="'"||c==='"'||c==="`"){s=c,o+=c;continue}const u=t.slice(a,a+2);if(c===";"||u==="--"||u==="/*")throw new d("INVALID_SQL_EXPRESSION",`${n} accepts one expression and does not allow statements or SQL comments`);if(c==="?"){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+=c}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},Cd=new Set(["boolean","date","number","entity","object","string"]),Dd=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},Md=(t,e)=>{const r=e.type,n=e.primal_type;if(typeof r!="string"||r.length===0||!Cd.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}:{}}},Ud={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 es(t.sql,Dd(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 Md(t,e)}},qd=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]},kd=t=>typeof t.pred!="string"?t:{...t,pred:{operator:"$sum",pred:t.pred,name:`${t.pred}\u5408\u8BA1`}},jd=(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=qd(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=ae(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,kd(l)}),delete a.sort,delete a.limit,delete a.limitBy,delete a.page,delete a.output,delete a.representation;const c=n.map(({name:p})=>p).filter(p=>!!p),u=ae(t);return u.from=a,u.query=r,u.preds=[{pred:s,name:s},...c.map(p=>({pred:p,name:p}))],delete u.groupby,delete u.having,delete u.entity_id,delete u.propertyResolve,u},xd={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?jd(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}}},Bd={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}}},Vd=new Set(["string","number","boolean","date","entity","object"]),oo=t=>{if(t==="timestamp"||t==="date")return{type:t,primal_type:"date"};if(typeof t=="string"&&Vd.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")},Yd={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 oo(t.args?.type),t},toSQL({args:t,sql:e}){return oo(t.type),e.value(t.value,t.type)},getOutputProperty({name:t,args:e}){return{name:t,...oo(e.type),isArray:!1}}},Fd={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}}},ts="__scalarExtremumInputs",io=t=>{if(t.schema)return t.schema;if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred))return io(t.pred);if(Array.isArray(t.pred)){const e=[...new Set(t.pred.flatMap(r=>typeof r=="string"?[]:io(r)??[]))];if(e.length===1)return e[0]}},Hd=t=>{const e=ae(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},Qd=(t,e)=>{if(e.args?.[ts]===!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}:ae(o),a=s.name??`__scalar_extremum_input_${i}__`,c=s.schema??io(s);return{...s,name:a,...c?{schema:c}:{}}}),n=Hd(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,[ts]:!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}:{}}},vd=(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)`},Gd=(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}},rs=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?Qd(e,r):void 0},toSQL(e){const r=Dt(t,e,2,Number.POSITIVE_INFINITY);return e.sql.scalarExtremum?.(t==="$least"?"least":"greatest",r)??vd(t,r)},getOutputProperty({name:e,inputProperties:r}){return Gd(t,e,r)}}),zd=rs("$least"),Wd=rs("$greatest"),so={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"}},Kd={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}}},Jd=t=>({name:`$${t}`,defaultName:({operandName:e,locale:r})=>r.toLowerCase().startsWith("en")?`${e} ${so[t].en}`:`${e}${so[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}}}),Xd=Object.freeze(Object.keys(so).map(Jd)),ns=Object.freeze([zc,Od,ad,cd,ed,hd,md,Gu,Nd,Sd,Zu,Ed,$d,Kc,Td,gd,ld,Wc,Pd,id,sd,Ld,pd,Ud,xd,Bd,Yd,Fd,zd,Wd,Kd,...Xd]),Zd={name:"boolean",primalType:"boolean",hydrateResult(t){return typeof t=="number"?t===1:t}},ep={name:"category",primalType:"string"},tp={name:"currency",primalType:"number"},rp={name:"date",primalType:"date"},np={name:"duration",primalType:"number"},os=(t,{property:e,requestEntity:r})=>!e.ref||t===void 0||t===null||typeof t=="object"&&!Array.isArray(t)?t:r(e.ref,t),op={name:"object",primalType:"object",hydrateResult:os},ip={name:"entity",primalType:"entity",hydrateResult:os},sp={name:"file",primalType:"string"},ap={name:"humanName",primalType:"string"},cp={name:"ID",primalType:"string"},up={name:"image",primalType:"string"},dp={name:"int",primalType:"number"},pp={name:"name",primalType:"string"},lp={name:"number",primalType:"number"},fp={name:"order",primalType:"number"},mp={name:"percentage",primalType:"number"},yp={name:"string",primalType:"string"},hp={name:"tag",primalType:"string",isArray:!0,normalizeResult:(t,{property:e})=>!e.isArray||t==null||Array.isArray(t)?t:[t]},gp={name:"timestamp",primalType:"date"},ao=Object.freeze([cp,yp,pp,ap,ep,hp,up,sp,lp,dp,tp,mp,np,fp,Zd,gp,rp,ip,op]),Ap=(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},is=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 c=Ap(e[a],a,n);c&&(s[a]=c)}if(!s.getOutputProperty&&typeof o=="string"){const a=ao.find(({name:c})=>c===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 er{executionContext;#e=new Map;constructor(e=[],r=Object.freeze({})){this.executionContext=r;for(const n of e)this.register(n)}withExecutionContext(e){return new er(this.definitions(),e)}register(e){const r=is(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,executionContext:this.executionContext})??!1}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}}const $p=Object.freeze([...ns,...Fr.flatMap(({operators:t})=>t??[])]),Qe=(t=[])=>new er([...ns,...be(t).flatMap(({operators:e})=>e??[])]),jt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="logicform-subquery"&&typeof t.plan=="object"&&t.plan!==null,ss=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="query-operator"&&typeof t.operator=="string",wp=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="ordinal-query",as=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="expression-query",Ep=(t,e)=>{const r=Jc(t,e);return{schemaId:t.id,propertyId:r.id,propertyName:r.name,physicalColumn:r.udf?.sql??r.id}},cs=(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}:Ep(e,r)},cr=(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 c=[t.input,...t.partitionBy].map(u=>cr(u,e,r,n));return{sources:c.flatMap(({sources:u})=>u),transformations:[...c.flatMap(({transformations:u})=>u).filter(u=>u!=="projection"),`window:${t.function}`]}}if(t.kind==="cumulative"){const c=[t.input,...t.partitionBy,...t.orderBy.map(({expression:u})=>u)].map(u=>cr(u,e,r,n));return{sources:c.flatMap(({sources:u})=>u),transformations:[...c.flatMap(({transformations:u})=>u).filter(u=>u!=="projection"),`window:cumulative:${t.function}`]}}if(t.kind==="ordinal-encode"||t.kind==="ordinal-decode"){const c=cr(t.input,e,r,n);return{sources:c.sources,transformations:[...c.transformations.filter(u=>u!=="projection"),`ordinal:${t.kind==="ordinal-encode"?"encode":"decode"}`]}}const o=[...t.input?[t.input]:[],...t.inputs??[]].map(c=>cr(c,e,r,n)),i={sources:o.flatMap(({sources:c})=>c),transformations:o.flatMap(({transformations:c})=>c)},s=n.get(t.operator),a=new Set([...t.property?[t.property]:[],...s.dependencies??[],...vr(t.query)]);return{sources:[...i.sources,...[...a].filter(c=>!i.sources.some(u=>u.propertyName===c)).map(c=>cs(e,r,c))],transformations:[...i.transformations.filter(c=>c!=="projection"),`operator:${t.operator}`]}};function vr(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(...vr(o));else r==="$expr"&&as(n)?e.push(...n.properties):r.startsWith("$")||e.push(r);return e}const tt=t=>t.kind==="window"?[...tt(t.input),...t.partitionBy.flatMap(tt)]:t.kind==="cumulative"?[...tt(t.input),...t.partitionBy.flatMap(tt),...t.orderBy.flatMap(({expression:e})=>tt(e))]:t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?tt(t.input):t.kind==="operator"?[...vr(t.query),...t.input?tt(t.input):[],...(t.inputs??[]).flatMap(tt)]:[],us=(t,e,r,n=Qe(),o)=>{if(t.subplans){const s=t.subplans.map(c=>us(c,e,r,n,o)),a=new Map;for(const c of s){c.source.connectionId&&a.set(c.source.connectionId,c.source.provider);for(const u of c.source.connections??[])a.set(u.connectionId,u.provider)}return{source:{schemaId:e.id,schemaName:e.name,physicalTable:s.map(({source:c})=>c.physicalTable).join(", "),provider:r.kind,connections:[...a].map(([c,u])=>({connectionId:c,provider:u}))},outputs:t.projections.map(({name:c})=>{const u=s.flatMap(({outputs:p})=>p.filter(l=>l.name===c));return{name:c,sources:u.flatMap(({sources:p})=>p),transformations:[...new Set([...u.flatMap(({transformations:p})=>p),t.sumPartition?"sum-partition":t.splitGroup?"split-group":"compose"])]}}),filters:s.flatMap(({filters:c})=>c)}}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),...(t.mappingSourcePlan?.sourcePlan?.enrichmentJoins??t.mappingSourcePlan?.enrichmentJoins??[]).map(({source:s})=>s)].filter(Boolean).join(", "),provider:i.kind,...t.connectionId?{connectionId:t.connectionId}:{}},outputs:t.projections.map(s=>({name:s.name,...cr(s.expression,t,e,n)})),filters:[...new Set([...vr(t.query),...t.projections.flatMap(({expression:s})=>tt(s))])].map(s=>cs(t,e,s))}},Me=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.version=="string"&&(typeof t.schema=="string"||typeof t.from=="object"),_p=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,ds=t=>{const e=_p.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}},ps=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(!ds(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}`)}}}},Ip=new Set(["second","minute","hour","day","week","month","quarter","year"]),Gr=t=>typeof t=="string"&&Ip.has(t),co=(t,e=be())=>Gr(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 At{#e=new Map;plugins;constructor(e=[],r=[]){this.plugins=be(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:c})=>!a||!c))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");ps(s),r.add(s.id),n.add(s.source)}for(const s of e.mappings??[]){if(s.propertySql!==void 0&&(s.mappingType!=="property"||typeof s.propertySql!="string"||s.propertySql.trim().length===0))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping propertySql requires a property item and a non-empty SQL expression");if(s.granularity!==void 0&&(s.mappingType!=="property"||!co(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.propertySql||!s.propertyTarget?.length))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping property items require sourceColumn or propertySql, and propertyTarget");if(s.mappingType==="predItem"&&(!s.sourceColumn||typeof s.predItem?.pred!="string"||s.predItem.operator!==void 0&&!s.predItem.operator))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping PredItem items require sourceColumn and predItem pred; operator must be non-empty when supplied");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")}ps(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}findById(e,r){const n=this.#e.get(e)?.filter(o=>(o.id??o.source)===r)??[];if(n.length>1)throw new d("SCHEMA_MAPPING_ID_AMBIGUOUS",`Schema mapping id ${r} is ambiguous across connections for ${e}`,{schemaId:e,mappingId:r,connectionIds:n.map(({connectionId:o})=>o)});return n[0]}definitions(){return[...this.#e.values()].flat()}findSource(e,r,n){return this.#e.get(e)?.find(o=>o.source===r&&(n===void 0||o.connectionId===n))}}const Sp=new Set(["$sply","$splm","$splq","$splw","$yoy","$mom","$qoq","$wow","$yoyd","$momd","$qoqd","$wowd","$percentage"]),zr=t=>!te(t)||!Array.isArray(t.properties)?[]:t.properties.filter(te),ls=new Set(["second","minute","hour","day","week","month","quarter","year"]),bp={weekday:"weekday",toQuarter:"quarter",toMonth:"month",toWeek:"week",toDay:"day",toHour:"hour",toWeekday:"weekday"},fs=(t,e)=>{const r=e[t];return te(r)?r:Object.values(e).find(n=>te(n)&&(n.id===t||n._id===t))},ms=(t,e)=>{const r=t&&e?zr(fs(t,e)).find(o=>o.type==="timestamp"):void 0,n=r?.name??r?.id??r?._id;return typeof n=="string"&&n.length>0?n:void 0},ys=(t,e,r)=>{const n=fs(t,r);if(!n)return;const i=zr(n).map(s=>{const c=[s.id,s._id,s.name].filter(u=>typeof u=="string").filter(u=>e===u||e.startsWith(`${u}_`)).sort((u,p)=>p.length-u.length)[0];return c?{property:s,key:c}: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"?ys(i.property.ref,e.slice(i.key.length+1),r):void 0},xt=(t,e,r)=>{const n=(o,i,s)=>{const u=zr(r[o]).map(h=>{const y=typeof h.id=="string"?h.id:void 0,$=typeof h.name=="string"?h.name:void 0,A=[y,$].filter(g=>!!g&&(i===g||i.startsWith(`${g}_`))).sort((g,w)=>w.length-g.length)[0];return A?{property:h,key:A}:void 0}).filter(h=>!!h).sort((h,y)=>y.key.length-h.key.length)[0];if(!u)return;const p=String(u.property.id??u.property.name),l=i===u.key?"":i.slice(u.key.length+1);if(!l)return p;const m=typeof u.property.ref=="string"?u.property.ref:void 0;if(!m||s.has(m))return;const f=n(m,l,new Set(s).add(m));return f?`${p}_${f}`:void 0};return n(t,e,new Set([t]))},uo=(t,e,r)=>{const n=zr(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 uo(n.ref,e.slice(n.id.length+1),r)}},hs=t=>Object.keys(t).filter(e=>e!=="$and"&&e!=="$or"),te=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),gs=t=>typeof t=="string"&&/^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?$/.test(t),As=t=>{if(!te(t))return t;if(te(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},Rp=t=>typeof t=="string"&&t.length>0||typeof t=="number"&&Number.isSafeInteger(t),Np=(t,e)=>{if(!e)return;const r=e[t]??Object.values(e).find(c=>te(c)&&(c.id===t||c._id===t));if(!te(r))return;const n=r.hierarchy,o=Array.isArray(n)?n:te(n)&&Array.isArray(n.levels)?n.levels:void 0;if(!o)return;const i=o.map(c=>{if(!te(c)||typeof c.name!="string")return;const u=c.codeLength??c.code_length;return Number.isInteger(u)&&Number(u)>0?{name:c.name,codeLength:Number(u)}:void 0});if(i.length===0||i.some(c=>c===void 0))return;const s=o[0],a=Array.isArray(n)?te(s)&&s.use_full_length===!0?"zero-padded":"compact":te(n)&&n.storage==="zero-padded"?"zero-padded":"compact";return{levels:i.filter(c=>c!==void 0),storage:a}},Op=(t,e,r)=>{const n=Np(t,r);if(!n)return;const o=String(e),i=n.levels.reduce((a,c)=>a+c.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})},Tp=(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}))]},po=(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(h=>te(h)?po(h,e):h);continue}if(!te(i)){r[o]=i;continue}const s=i.entity_id;if(typeof i.schema!="string"||!te(i.query)||!Rp(s)){r[o]=i;continue}const a=i.entity_level,c=typeof a=="string"&&a.length>0?a:Op(i.schema,s,e);if(!c){r[o]=i;continue}const{entity_id:u,entity_level:p,...l}=i,m=po(i.query,e),f=Object.keys(l).filter(h=>h!=="schema"&&h!=="version"&&h!=="query");(Object.keys(m).length>0||f.length>0)&&(r[o]={...l,query:m}),n.push({pred:{operator:"$hierarchyLevel",pred:o,args:{level:c}},condition:s})}return Tp(r,n)},Pp=(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}},$s=(t,e)=>{if(!te(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(!te(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(!te(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}:{}}},rt=(t,e,r,n=!1)=>{if(Array.isArray(t))return t.map(u=>rt(u,e,r));if(!te(t))return t;const o=As(t);if(o!==t)return o;const i=t,s=typeof i.schema=="string"?i.schema:r,a={};for(const[u,p]of Object.entries(i))u==="skip"||u==="_snapshot"||u==="_snapshots"||(a[u]=rt(p,e,s,u==="from"));if(typeof i.version=="string"&&/^1\./.test(i.version)&&(a.version="2.0"),i.version===void 0&&(n||typeof i.schema=="string"&&(Array.isArray(i.preds)||Array.isArray(i.groupby)||i.from!==void 0))&&(a.version="2.0"),Array.isArray(i.groupby)){const u=i.groupby;a.groupby=u.map(p=>{if(!te(p))return p;const l=rt(p,e,s);if(!te(l))return l;const{_id:m,level:f,...h}=l;if(typeof m=="string"&&m.startsWith("$")){const $=m.slice(1);if(!ls.has($))throw new d("INVALID_LEGACY_TIME_GROUPBY",`Unsupported legacy time groupby: ${m}`,{groupby:m});const E=ms(s,e);if(!E)throw new d("LEGACY_TIME_GROUPBY_TIMESTAMP_REQUIRED",`Legacy time groupby ${m} requires a timestamp Property in Schema ${s??"(unknown)"}`,{groupby:m,schemaId:s});return{...h,pred:E,operator:"$dateBucket",args:{...te(h.args)?h.args:{},granularity:$},...h.name===void 0?{name:`${E}(${$})`}:{}}}const y={...h,...h.pred===void 0&&typeof m=="string"?{pred:m}:{}};return typeof f=="string"&&(y.operator="$dateBucket",y.args={...te(y.args)?y.args:{},granularity:f}),y})}const c=i.skip;if(typeof c=="number"&&Number.isInteger(c)&&c>=0){const u=i.limit;c===0?delete a.skip:typeof u=="number"&&Number.isInteger(u)&&u>0&&c%u===0?a.page=c/u+1:a.skip=c}else c!==void 0&&(a.skip=rt(c,e,s));if(i.operator&&typeof i.operator=="string"){const u=Pp(i.operator,te(a.args)?a.args:{});u.operator&&(a.operator=u.operator),a.args=u.args;const p=typeof i.pred=="string"&&i.pred.startsWith("$")?i.pred.slice(1):"",l=bp[p];if(i.operator==="$count"&&(ls.has(p)||l)){const m=ms(s,e);if(!m)throw new d("LEGACY_TIME_COUNT_TIMESTAMP_REQUIRED",`Legacy $count($${p}) requires a timestamp Property in Schema ${s??"(unknown)"}`,{schemaId:s,pred:i.pred});a.operator="$countDistinct",a.pred=l?{operator:`$${l}`,pred:m}:{operator:"$dateBucket",pred:m,args:{granularity:p}}}if(i.operator==="$comp"||i.operator==="$compabs"){const m=te(a.args)?a.args.preds:void 0;if(!Array.isArray(m)||m.length!==2)throw new d("INVALID_LEGACY_COMP_ARGS",`${i.operator} requires exactly 2 preds in args.preds`);const f={operator:"$subtract",pred:m,args:{nullAsZero:!0}};a.operator=i.operator==="$comp"?"$subtract":"$abs",a.pred=i.operator==="$compabs"?f:m,a.args=i.operator==="$comp"?{nullAsZero:!0}:{}}if(i.operator==="$switch"){const m=te(a.params)?a.params:a.args;a.operator="$case",a.args=$s("$switch",m),delete a.params}if(i.operator==="$piecewise"){const m=typeof a.pred=="string"?a.pred:typeof i._id=="string"?i._id:void 0;if(e&&s&&m&&ys(s,m,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:s,property:m});const f=te(a.params)?a.params:te(a.args)?a.args:{};a.operator="$case",a.args=Array.isArray(f.cases)?$s("$piecewise",f):{mode:"auto",buckets:Number.isInteger(f.buckets)?f.buckets:10},delete a.params}Sp.has(i.operator)&&typeof a.pred=="string"&&(a.pred={operator:"$sum",pred:a.pred})}return i.params!==void 0&&a.args===void 0&&(a.args=Array.isArray(i.params)?{values:rt(i.params,e,s)}:rt(i.params,e,s)),i.inputs!==void 0&&a.pred===void 0&&Array.isArray(i.inputs)&&(a.pred=i.inputs.map(u=>rt(u,e,s)),te(a.args)&&delete a.args.inputs),i.pred===void 0&&typeof i.operator=="string"&&i.operator==="$sql"&&typeof i.sql=="string"&&(a.args={...te(a.args)?a.args:{},sql:i.sql},delete a.sql),i.$options!==void 0&&a.$regex!==void 0?(a.args={...te(a.args)?a.args:{},options:i.$options},delete a.$options):typeof i.$eq=="string"&&typeof i.$options=="string"?(a.args={...te(a.args)?a.args:{},options:i.$options},delete a.$options):"$options"in i&&gs(i.$gte)&&gs(i.$lte)&&delete a.$options,i.query&&te(i.query)&&(a.query=Lp(i.query,e,s)),a},Lp=(t,e,r)=>{const n=rt(t,e,r);for(const[o,i]of Object.entries(n))n[o]=As(i);return po(n,e)},ws=(t,e)=>{const r=te(t)?t:void 0,n=rt(t,e);if(!te(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],ws(o,e)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),e?Cp(n,e):n},Cp=(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 c of n)te(c)&&typeof c.schema=="string"&&i.add(c.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(c=>te(c)&&typeof c.pred=="string"?xt(o,c.pred,e):void 0):[];for(const c of i)if(Array.isArray(r.groupby)&&r.groupby.map((u,p)=>{if(!te(u)||typeof u.pred!="string")return u;const l=c===o?xt(c,u.pred,e):xt(c,uo(o,s[p]??"",e)??u.pred,e);if(!l)return u;const m=l.split("_").at(-1)??u.pred;return{...u,pred:l,name:m}}),te(r.query))for(const u of hs(r.query)){const p=xt(o,u,e);if(!(c===o?p:xt(c,(p&&uo(o,p,e))??u,e))&&c===o)throw new Error(`Cannot align legacy query field ${u} in Schema ${c}`)}const a={...r};if(Array.isArray(r.groupby)&&(a.groupby=r.groupby.map((c,u)=>{if(!te(c)||typeof c.pred!="string")return c;const p=s[u];return p?{...c,pred:p}:c})),te(r.query)){const c=r.query,u=hs(c).map(p=>[xt(o,p,e)??p,c[p]]);a.query=Object.fromEntries(u)}return a},Dp=t=>{const e=(r,n)=>{if(Array.isArray(r)){r.forEach((o,i)=>e(o,`${n}[${i}]`));return}if(te(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,"$")},lo=t=>{if(Array.isArray(t))return t.map(lo).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,lo(o)]).filter(([,n])=>n!==void 0);if(!(e.length>0&&r.length===0))return Object.fromEntries(r)},Mp=t=>{const e=t.constraints?.enum??t.enum;return Array.isArray(e)?e:typeof e=="string"&&e.length>0?e.split(","):void 0},Up=(t,e,r)=>{const n=t.comparable;if(!r||n!=null&&typeof n!="string")return t.comparable;const o=n==="asc"?1:n==="desc"?-1:n==null&&t.is_comparable===!0?t.comparable_order===-1?-1:1:void 0;if(o===void 0||t.isArray===!0||t.type!=="string"&&t.type!=="category"||!e)return;const i=e.map(s=>Array.isArray(s)?s[0]:s);if(!(i.length===0||i.some(s=>typeof s!="string")))return{values:[...new Set(i)],direction:o}},qp=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}},Es=(t,e=[],r=!0)=>{const n=be(e),o={},i=new Set(n.flatMap(s=>[...s.schemaMetadata?.keys??[],...s.legacySchemaKeys??[]]));for(const[s,a]of Object.entries(t)){const c=lo(a),u=c,l=(Array.isArray(u.properties)?u.properties:[]).some(g=>g.is_observation===!0)||u.is_observation===!0,m=u.is_snapshot===!0,f=typeof c.id=="string"&&c.id.length>0?c.id:r&&typeof c._id=="string"&&c._id.length>0?c._id:c.id,{properties:h}=c,y=Object.fromEntries(Object.entries(c).filter(([g])=>(r?!["_id","_sid","sid","is_observation","is_snapshot"].includes(g):g!=="properties")&&g!=="properties"&&!i.has(g))),$=h.map(g=>{const w=g,L=typeof w.id=="string"&&w.id.length>0?w.id:r&&typeof w._id=="string"&&w._id.length>0?w._id:w.id,{udf:I,...S}=w,R=r?Mp(w):void 0,N=Up(w,R,r),D=qp(I),F=r&&N!==void 0&&w.type==="string"?"category":w.type==="object"?"entity":w.type,V=F==="entity"||w.primal_type==="entity"||w.primal_type==="object";return{...r?Object.fromEntries(Object.entries(S).filter(([M])=>!["_id","_sid","sid","is_observation","is_comparable","comparable_order","comparable","enum"].includes(M)&&(M!=="level"||V))):S,type:F,...r&&R&&!Array.isArray(w.constraints?.enum)?{constraints:{...w.constraints,enum:R}}:{},...w.primal_type==="object"?{primal_type:"entity"}:{},...L!==void 0?{id:L}:{},...D!==void 0?{udf:D}:{},...N!==void 0?{comparable:N}:{}}});let E={};for(const g of n)for(const w of g.schemaMetadata?.keys??[])c[w]!==void 0&&(E={...E,[w]:c[w]});for(const g of n)E={...E,...g.normalizeLegacySchema?.({source:c,properties:$})};const A={...y,...f!==void 0?{id:f}:{},properties:$,...r&&(m||l)?{temporalSemantics:"snapshot"}:{},...E};o[s]=A}return o},_s=Symbol("legacy-empty-source"),Is=t=>t!==void 0&&_s in t,Ss=(t,e,r,n=[],o=r?[r]:[])=>{const i=[...e],s=new Set(n);for(const[a,c]of Object.entries(t)){const u=c,p=typeof u.id=="string"&&u.id.length>0?u.id:typeof u._id=="string"&&u._id.length>0?u._id:a;if(i.some(h=>h.schemaId===p))continue;const l=typeof u.db=="string"&&u.db.trim().length>0?u.db.trim():void 0;if(typeof u.from!="string"||u.from.trim().length===0){if(l){i.push({schemaId:p,connectionId:l,source:p});continue}for(const h of new Set(o.filter(Boolean))){const y={schemaId:p,connectionId:h,source:`legacy-empty-schema:${p}`,[_s]:!0};i.push(y)}continue}const m=l??r;if(!m){if(s.has(p)||s.has(a))throw new d("LEGACY_SCHEMA_FROM_CONNECTION_REQUIRED",`Cannot create a Schema mapping for legacy Schema ${p}: provide Schema.db or one unambiguous connection`,{schemaId:p});continue}const f=u.from.trim();i.push({schemaId:p,connectionId:m,source:`legacy-schema-from:${p}`,sourceSql:f})}return i},Bt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),kp=t=>Bt(t)&&typeof t.schema=="string"&&Bt(t.query),jp=t=>Bt(t)&&["preds","groupby","from","having","sort","limit","limitBy","page"].some(e=>t[e]!==void 0),ur=(t,e,r,n="")=>{if(typeof t=="string"){r.push({reference:n?`${n}_${t}`:t,use:e});return}t&&(Wr(t.query,r,n),Array.isArray(t.pred)?t.pred.forEach(o=>ur(o,e,r,n)):ur(t.pred,e,r,n))},Wr=(t,e,r="")=>{if(t)for(const[n,o]of Object.entries(t)){if(n==="$and"||n==="$or"){Array.isArray(o)&&o.forEach(s=>{Bt(s)&&Wr(s,e,r)});continue}if(n==="$expr"){Bt(o)&&"pred"in o&&Bt(o.pred)&&ur(o.pred,"query",e,r);continue}if(n.startsWith("$"))continue;const i=r?`${r}_${n}`:n;kp(o)&&!jp(o)?(o.entity_id!==void 0&&o.entity_id!=="placeholder"&&e.push({reference:i,use:"query"}),Wr(o.query,e,i)):e.push({reference:i,use:"query"})}},dr=t=>{const e=[];return Wr(t.query,e),t.preds?.forEach(r=>ur(r,"pred",e)),t.groupby?.forEach(r=>ur(r,"groupby",e)),e},xp=(t,e)=>e.length>0&&dr(t).some(({reference:r})=>r===e);class fo{#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 Bp=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)}},bs=t=>{Bp(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)})},Vp=new Set(["second","minute","hour","day","week","month","quarter","year"]),Yp=(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 c=a,u=Object.keys(c).filter(p=>p!=="sql");if(u.length>0)throw new d("UNSUPPORTED_PROPERTY_UDF",`Property ${t.name} udf only supports sql`,{property:t.name,unsupportedKeys:u});if(typeof c.sql!="string"||c.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(n.isArray&&t.isArray===!1)throw new d("INVALID_IS_ARRAY",`Property ${t.name} of type ${t.type} must be an array`,{property:t.name,type:t.type});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; received ${JSON.stringify(a)}`,{property:t.name,comparable:a});const c=a;if(Object.keys(c).some(u=>u!=="values"&&u!=="direction")||!Array.isArray(c.values)||c.values.length===0||c.values.some(u=>typeof u!="string")||new Set(c.values).size!==c.values.length||c.direction!==1&&c.direction!==-1)throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable requires unique string values and direction 1 or -1; received ${JSON.stringify(a)}`,{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??n.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&&!Vp.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},mo=(t,e,r=[])=>{const n=be(r),o=n.reduce((f,h)=>h.prepareSchema?.(f)??f,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");if(o.is_calendar!==void 0&&typeof o.is_calendar!="boolean")throw new d("INVALID_CALENDAR_SCHEMA_FLAG",`Schema ${o.id} is_calendar must be a boolean`,{schemaId:o.id,is_calendar:o.is_calendar});if(o.partition!==void 0&&typeof o.partition!="function")throw new d("INVALID_SCHEMA_PARTITION",`Schema ${o.id} partition must be a function`,{schemaId:o.id});const i=n.flatMap(f=>f.propertyMetadata?[f.propertyMetadata]:[]),s=new Set(i.flatMap(({keys:f})=>f));let a=o.properties.map(f=>{const h=Object.fromEntries(Object.entries(f).filter(([$])=>!s.has($))),y=Yp(h,e);return i.reduce(($,E)=>({...$,...E.resolve(f,$,o)}),y)});for(const f of i)a=[...f.resolveAll?.(a,o.properties,o)??a];bs(a);const c=n.flatMap(f=>f.schemaMetadata?[f.schemaMetadata]:[]);let u={};for(const f of c)u={...u,...f.resolve(o,a)};const p=new Set(n.flatMap(f=>[...f.schemaMetadata?.keys??[],...f.legacySchemaKeys??[]])),m={...Object.fromEntries(Object.entries(o).filter(([f])=>!p.has(f))),properties:a,...u};for(const f of n)f.validateResolvedSchema?.(m);return m};le.extend(di),le.extend(tr),le.extend(Cr);const Fp="YYYY-MM-DD HH:mm:ss",Hp=new Set(["YTD","QTD","MTD","WTD","DTD"]),Rs=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),Qp=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),Kr=["second","minute","hour","day","week","month","quarter","year"],$t=t=>Object.prototype.toString.call(t)==="[object Object]",Ns=(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($t(t)){const n=Object.entries(t);if(n.length===0||n.some(([o])=>!Rs.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=>Ns(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`)},yo=t=>!$t(t)||"$gte"in t||"$gt"in t||"$lte"in t||"$lt"in t||"$or"in t||"$ne"in t?!1:typeof t.granularity=="string"&&Kr.includes(t.granularity)&&typeof t.offset=="number"||Kr.some(e=>e in t),Vt=t=>le(t).format(Fp),vp=(t,e)=>Kr.find(r=>r in t||e!==void 0),Gp=(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),Os=(t,e)=>{const r=typeof t.granularity=="string"?t.granularity:void 0,n=r?{[r]:t.offset}:void 0,o=r??vp(t,void 0)??"day";let i=le(e).millisecond(0);for(const a of[...Kr].reverse()){const c=t[a];typeof c=="number"&&(i=Gp(i,a,c));const u=n?.[a];typeof u=="number"&&u!==0&&(i=i.add(u,a))}const s=o==="week"?"isoWeek":o;return{$gte:Vt(i.startOf(s)),$lte:Vt(i.endOf(s))}},zp=(t,e)=>{const r=le(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:Vt(o()),$lte:Vt(r.endOf("day"))}},ho=async(t,e)=>{const r=le(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=le(n).endOf(i),a=le(String(t.$gte));if(a.isValid()&&s.isBefore(a))return t;const c=s.isBefore(r)?s:r;return{...t,$lte:Vt(c)}},go=async(t,e)=>Me(t)?t:t instanceof Date||typeof t=="string"&&le(t).isValid()?Vt(t):typeof t=="string"&&Hp.has(t)?ho(zp(t,e.now),e):yo(t)?ho(Os(t,e.now),e):t,Ts=async(t,e,r)=>{if(t==="$and"||t==="$or")return Array.isArray(e)?Promise.all(e.map(o=>Jr(o,r))):e;if(Array.isArray(e))return Promise.all(e.map(o=>go(o,r)));const n=await go(e,r);return t==="$eq"&&$t(n)&&"$gte"in n&&"$lte"in n?n:t==="$gte"||t==="$gt"?$t(n)&&"$gte"in n?n.$gte:n:(t==="$lte"||t==="$lt")&&$t(n)&&"$lte"in n?n.$lte:n},Jr=async(t,e)=>{if(Me(t))return t;if(Array.isArray(t))return Promise.all(t.map(o=>Jr(o,e)));if(!$t(t))return go(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)&&(!yo(t)||!Number.isInteger(t.offset)))throw new d("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(yo(t))return ho(Os(t,e.now),e);const r=Object.entries(t);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await Ts("$eq",r[0][1],e);if($t(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)Qp.has(o)&&Ns(i,o),n[o]=Rs.has(o)?await Ts(o,i,e):await Jr(i,e);return n},Wp=(t,e)=>e.property.primal_type==="date"?Jr(t,e):t,Xr=(t=[])=>new fo([...ao,...be(t).flatMap(({semanticTypes:e})=>e??[])]),Ps=(t,e)=>{const r=new fo(t.definitions());for(const n of be(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},Ls=t=>!t.isArray&&(t.primal_type!=="number"||t.type==="ID"||t.type==="category"||t.is_categorical===!0),Cs=(t,e,r)=>{const n=t.mappings??[];if(!n.some(i=>i.mappingType==="property"||i.mappingType==="predItem"))return{};const o=n.find(i=>i.mappingType==="property"&&(i.sourceColumn||i.propertySql)&&i.propertyTarget?.some(s=>e.properties.find(({id:c,name:u})=>c===s||u===s)?.id===r.id));return o?{...o.sourceRef?{sourceRef:o.sourceRef}:{}}:void 0},Ao=t=>{if(!(t instanceof d&&t.code==="PROPERTY_NOT_FOUND"))throw t},Kp=(t,e,r)=>{const n=r.plugins.filter(m=>!Fr.some(f=>f.name===m.name)),o=Es(e,n),i=Xr(n),s=new Map,a=m=>{const f=s.get(m);if(f)return f;const h=mo(Li(m,o),i,n);return s.set(m,h),h},c=a(t),u=new Set,p=m=>{for(const f of m.mappings??[]){if(f.mappingType!=="predItem"||!f.sourceColumn||!f.predItem?.query||typeof f.predItem.pred!="string"||f.predItem.schema&&f.predItem.schema!==t)continue;try{oe(c,f.predItem.pred,a)}catch($){Ao($);continue}const h=dr({query:f.predItem.query}).filter(({use:$})=>$==="query").map(({reference:$})=>$),y=new Set(h.flatMap($=>{try{return[oe(c,$,a).canonicalId]}catch(E){return Ao(E),[]}}));for(const $ of f.propertyTarget?.length?[f.propertyTarget.join("_")]:h)try{const E=oe(c,$,a);y.has(E.canonicalId)&&Ls(E.property)&&u.add(E.canonicalName)}catch(E){Ao(E)}}},l=(m,f,h,y)=>{for(const $ of m.properties){const E=Cs(f,m,$);if(!E)continue;const A=oe(m,$.id).canonicalName,g=h?`${h}_${A}`:A;if(Ls($)&&(!h||$.type!=="ID")&&u.add(g),$.primal_type!=="entity"&&$.primal_type!=="object"||!$.ref||E.sourceRef||y.has($.ref))continue;const w=a($.ref),L=w.properties.find(S=>S.type==="ID");if(!L)continue;let I;try{I=r.get(w.id,f.connectionId)}catch(S){if(!(S instanceof d)||!["SCHEMA_MAPPING_CONNECTION_NOT_FOUND","SCHEMA_MAPPING_AMBIGUOUS"].includes(S.code))throw S;continue}Cs(I,w,L)&&l(w,I,g,new Set([...y,w.id]))}};for(const m of r.list(t))l(c,m,"",new Set([t])),p(m);return[...u]},Jp=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`)},Xp=(t,e=[])=>{const r=be(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.propertySql!==void 0&&(o.mappingType!=="property"||typeof o.propertySql!="string"||o.propertySql.trim().length===0||!o.propertyTarget?.length))throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping propertySql requires a valid property item and a non-empty SQL expression");if(o.granularity!==void 0&&(o.mappingType!=="property"||!co(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.propertySql||!o.propertyTarget?.length){if(o.granularity!==void 0)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires sourceColumn or propertySql, and propertyTarget");continue}n.push(o);continue}o.mappingType==="predItem"&&(!o.sourceColumn||typeof o.predItem?.pred!="string"||o.predItem.operator!==void 0&&!o.predItem.operator||n.push(o))}return{id:String(t.id),schemaId:t.schemaSid,connectionId:t.datasourceSid,source:Jp(t),...t.sourceSql?{sourceSql:t.sourceSql}:{},...t.enrichments?{enrichments:t.enrichments}:{},mappings:n}};class Ds{#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 Ms=(t=[])=>new Ds([...be(t).flatMap(e=>e.plannerSemantics??[])]);le.extend(di),le.extend(tr),le.extend(Cr);const Yt=["second","minute","hour","day","week","month","quarter","year"],Zp=new Set(["$second","$minute","$hour","$day","$week","$month","$quarter","$year"]),el="YYYY-MM-DD HH:mm:ss",wt=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),tl=(t,e)=>t==="week"?e==="week":e==="week"?Yt.indexOf(t)<=Yt.indexOf("day"):Yt.indexOf(t)<=Yt.indexOf(e),Us=(t,e,r)=>{if(typeof t!="string")return"second";const n=le(t,el,!0);if(!n.isValid())return"second";for(const o of[...Yt].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"},qs=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])=>Zp.has(r)?[r.slice(1)]:r==="$weekday"?["day"]:r==="$and"||r==="$or"?Array.isArray(n)?n.flatMap(qs):["second"]:r==="$gte"||r==="$gt"?[Us(n,"lower",r==="$gte")]:r==="$lte"||r==="$lt"?[Us(n,"upper",r==="$lte")]:["second"])},rl=(t,e,r)=>{if(e.primal_type==="date"){if(t.operator){const n=r.get(t.operator).groupedSourceTimeGranularity?.({pred:t,property:e});if(n&&Yt.includes(n))return n}return e.granularity??"day"}},nl=(t,e,r,n,o=be(),i=Qe(o))=>{const s=r.mappings??[],a=s.filter($=>$.granularity!==void 0),c={schema:e,mapping:r,...n?{resolveSchema:n}:{}};if(a.some($=>!co($.granularity,o)))return"physical granularity is not supported by the active plugins";if(a.find($=>Gr($.granularity)&&!$.propertyTarget?.every(E=>wt(e,E)?.primal_type==="date")))return"physical time granularity requires mapped date Properties";for(const $ of a)for(const E of o){const A=E.mappingGranularity;if(!A||!A.isGranularity($.granularity))continue;const g=A.validateItem?.($,c);if(g)return g}if(!(a.length>0))return;const l=$=>s.find(E=>E.mappingType==="property"&&E.propertyTarget?.some(A=>wt(e,A)?.id===$.id)),m=($,E,A="filterOrGroup")=>{const g=wt(e,$);if(!g)return`property is not available: ${$}`;const w=l(g);if(!w&&!(A==="operand"&&s.some(L=>L.mappingType==="predItem"&&typeof L.predItem?.pred=="string"&&wt(e,L.predItem.pred)?.id===g.id)))return`property is not available on grouped source: ${$}`;if(A==="filterOrGroup"&&g.primal_type==="number"&&g.type!=="category"&&g.type!=="ID")return`measure cannot be used as a grouped source dimension: ${$}`;if(g.primal_type==="date"&&(!w?.granularity||!Gr(w.granularity)||!tl(w.granularity,E??g.granularity??"day")))return`time dimension ${$} is too coarse for ${E}`};function f($){if($)for(const[E,A]of Object.entries($)){if(A===void 0)continue;if(E==="$and"||E==="$or"){if(!Array.isArray(A))return"unsupported dimension query";for(const L of A){const I=f(L);if(I)return I}continue}if(E==="$expr"){if(typeof A!="object"||A===null||Array.isArray(A))return"unsupported expression query";const L=A.pred;if(typeof L!="object"||L===null||Array.isArray(L))return"unsupported expression query";const I=h(L);if(I)return I;continue}if(E.startsWith("$"))return"unsupported dimension query";const g=wt(e,E);if(!g)return`dimension property is not available: ${E}`;const w=g.primal_type==="date"?qs(A):[void 0];for(const L of w){const I=m(E,L);if(I)return I}}}function h($){const E=f($.query);if(E)return E;const A=Array.isArray($.pred)?$.pred:$.pred===void 0?[]:[$.pred];for(const g of A){const w=typeof g=="string"&&($.operator==="$max"||$.operator==="$min")?wt(e,g):void 0,L=w?.primal_type==="date"?l(w)?.granularity:void 0,I=typeof g=="string"?m(g,Gr(L)?L:void 0,"operand"):h(g);if(I)return I}}const y=f(t.query);if(y)return y;if(!t.preds?.length)return"grouped source requires an aggregating PredItem";for(const $ of t.preds){const E=h($);if(E)return E;if(typeof $.pred!="string"||!$.operator||!i.get($.operator).supportsGroupedSourceRollup)return`PredItem ${$.operator??"(projection)"} cannot be rolled up from a grouped source`}for(const $ of t.groupby??[]){if(typeof $.pred!="string")return"computed groupby is not covered by the grouped source";const E=wt(e,$.pred);if(!E)return`groupby property is not available: ${$.pred}`;if($.operator!==void 0&&!i.get($.operator).supportsGroupedSourceGroupby&&!o.some(g=>g.mappingGranularity?.supportsGroupby?.($)))return`computed groupby is not covered: ${$.pred}`;const A=m($.pred,rl($,E,i));if(A)return A}for(const $ of o){const E=$.mappingGranularity?.candidateReason?.(t,c);if(E)return E}},nt=t=>t.mappings?.some(e=>e.mappingType==="property"&&!!e.propertySql)??!1;function Et(t){return[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Et(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Et(e)):[]]}const Ft=t=>t.id??t.source,pr=(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)=>pr(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)&&pr(i,n[o]))},_t=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=_t(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=Et(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},$o=(t,e,r,n)=>{if(!t)return;const o={};for(const[i,s]of Object.entries(t))if(s!==void 0){if(i==="$and"&&Array.isArray(s)){const a=s.map(c=>$o(c,e,r,n)).filter(c=>c!==void 0);a.length>0&&(o[i]=a);continue}i!=="$or"&&e.some(a=>St(r,a.property,i,n)&&pr(a.condition,s))||(o[i]=s)}return Object.keys(o).length>0?o:void 0},It=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),St=(t,e,r,n)=>{if(e===r)return!0;const o=It(t,e),i=It(t,r);if(o&&i)return o.id===i.id;if(!n)return!1;try{return oe(t,e,n).canonicalId===oe(t,r,n).canonicalId}catch{return!1}},Le=(t,e,r)=>{const n=ve(t,e,r);if(n)return nt(t)?It(e,r)?.id:n.column},ve=(t,e,r)=>{const n=It(e,r);if(!n)return;const o=(t.mappings??[]).find(i=>i.mappingType==="property"&&i.propertyTarget?.some(s=>St(e,s,r)));return o?.sourceColumn||o?.propertySql?{column:o.sourceColumn||n.id,...o.sourceRef?{sourceRef:o.sourceRef}:{},...o.propertySql?{sql:o.propertySql}:{}}:(t.mappings??[]).some(i=>i.mappingType==="property"||i.mappingType==="predItem")?void 0:{column:n.id}},Ht=(t,e,r)=>!(t.mappings??[]).some(n=>n.mappingType==="property"||n.mappingType==="predItem")||Le(t,e,r)!==void 0,wo=(t,e,r,n,o)=>{if(Ht(t,e,r))return!0;if(!o)return!1;try{const i=oe(e,r,o);if(i.relations.length===0)return!1;for(const a of i.relations){const c=a.sourceSchema.id===e.id?t:n.get(a.sourceSchema.id,t.connectionId),u=ve(c,a.sourceSchema,a.property.id),p=n.get(a.targetSchema.id,t.connectionId),l=a.targetSchema.properties.find(({type:m})=>m==="ID");if(!u||u.sourceRef||!l||Le(p,a.targetSchema,l.id)===void 0)return!1}const s=n.get(i.schema.id,t.connectionId);return Le(s,i.schema,i.property.id)!==void 0}catch{return!1}},ks=(t,e,r)=>{if(!t||!(e.mappings??[]).some(i=>i.mappingType==="property"||i.mappingType==="predItem"))return;const n=_t(t);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:i})=>!Ht(e,r,i));return o?`query property is not available: ${o.property}`:void 0},ol=(t,e,r,n,o,i,s)=>{if(t.match.schema!==void 0&&t.match.schema!==n)return!1;const a=typeof e.pred=="string"?It(r,e.pred):void 0,c=It(r,t.match.pred);if(!(typeof e.pred=="string"&&St(r,e.pred,t.match.pred)&&!!(a&&c))||!e.operator)return!1;if(t.match.operator===void 0){if(s.get(e.operator).kind!=="aggregate")return!1}else if(e.operator!==t.match.operator)return!1;if(Array.isArray(e.pred)||e.args&&Object.keys(e.args).length>0)return!1;const p=_t(t.match.query);return p!==void 0&&p.every(l=>o.some(m=>St(r,m.property,l.property,i)&&pr(m.condition,l.condition)))},il=(t,e,r,n,o,i,s=Qe(i))=>{const a=(r.mappings??[]).flatMap(S=>{if(S.mappingType!=="predItem"||!S.sourceColumn||!S.predItem||typeof S.predItem.pred!="string")return[];const R=S.predItem,N=R.operator,D=R.pred;return typeof D!="string"?[]:[{match:{pred:D,...N?{operator:N}:{},...R.schema?{schema:R.schema}:{},...R.query?{query:R.query}:{}},column:S.sourceColumn,...S.propertyTarget?{propertyTarget:S.propertyTarget}:{}}]}),c=(r.mappings??[]).some(S=>S.mappingType==="property");if(a.length===0&&!c){const S={schema:e,mapping:r,...o?{resolveSchema:o}:{}};for(const R of i??[]){const N=R.schemaMapping?.candidateReason?.(t,S);if(N)return N}return{mapping:r,logicform:t,predRewrites:[],priority:r.priority??0,specificity:0}}const u=_t(t.query),p=ae(t),l=[],m=[],f=new Map,h=S=>Ht(r,e,S)||a.some(R=>{const N=_t(R.match.query)??[];return N.some(F=>St(e,F.property,S,o))?(R.propertyTarget?.length?[R.propertyTarget.join("_")]:N.map(({property:F})=>F)).some(F=>St(e,F,S,o)):!1}),y=S=>{let R=It(e,S),N=R?.name;if(!R&&o)try{const D=oe(e,S,o);R=D.property,N=D.canonicalName}catch{return}if(!(!R||R.primal_type==="number"&&R.type!=="category"&&R.type!=="ID"))return N},$=()=>{const S=new Set;for(const{reference:R,use:N}of dr(p)){if(N!=="query"||h(R))continue;const D=y(R);D&&S.add(D)}for(const R of p.groupby??[])for(const N of Et(R)){if(wo(r,e,N,n,o))continue;const D=y(N);D&&S.add(D)}return[...S]},E=S=>{const R=$();return{reason:S,...R.length>0?{missingDimensions:R}:{}}};for(const{reference:S,use:R}of dr(t)){if(R==="pred"||!y(S))continue;if(!(R==="groupby"?wo(r,e,S,n,o):h(S)))return E(`${R} property is not available: ${S}`)}if(!u&&a.length>0)return"query contains $or or another unsupported logical expression";for(const[S,R]of(t.preds??[]).entries()){const N=_t(R.query);if(!N&&a.length>0)return`PredItem ${S} query contains an unsupported logical expression`;if(a.length>0){const F=t.groupby?.length?[...N??[]]:[...u??[],...N??[]],V=a.filter(K=>ol(K,R,e,R.schema??e.id,F,o,s));if(V.length===0){const K=Et(R);if(!(K.length===0&&R.operator!==void 0&&s.get(R.operator).requiresProperty===!1)&&(K.length===0||K.some(re=>!Ht(r,e,re))))return`PredItem ${S} is not mapped`;continue}if(V.length>1)return`PredItem ${S} matches multiple mapping rules`;const x=V[0],M=_t(x.match.query)??[];f.set(S,M),t.groupby?.length||m.push(...M);const j=p.preds?.[S];if(j){const K=$o(j.query,M,e,o);K?j.query=K:delete j.query}l.push({predIndex:S,column:x.column});continue}const D=Et(R).find(F=>!Ht(r,e,F));if(D)return`PredItem ${S} property is not available: ${D}`}const A=(u??[]).filter(({property:S})=>!Ht(r,e,S));for(const[S]of(t.preds??[]).entries()){const R=A.find(N=>!f.get(S)?.some(D=>St(e,D.property,N.property,o)&&pr(D.condition,N.condition)));if(R){const N=y(R.property);return{reason:`PredItem ${S} cannot apply root query dimension: ${R.property}`,...N?{missingDimensions:[N]}:{}}}}const g=$o(p.query,m,e,o);g?p.query=g:delete p.query;const w=ks(p.query,r,e);if(w)return w.startsWith("query property is not available:")?E(w):w;for(const[S,R]of(p.preds??[]).entries()){const N=ks(R.query,r,e);if(N)return N.startsWith("query property is not available:")?E(`PredItem ${S} ${N}`):`PredItem ${S} ${N}`}for(const S of p.groupby??[]){const N=Et(S).find(D=>!wo(r,e,D,n,o));if(N)return E(`groupby property is not available: ${N}`)}const L=nl(p,e,r,o,i,s);if(L)return L;const I={schema:e,mapping:r,...o?{resolveSchema:o}:{}};for(const S of i??[]){const R=S.schemaMapping?.candidateReason?.(p,I);if(R)return R}return{mapping:r,logicform:p,predRewrites:l,priority:r.priority??0,specificity:l.length}},sl=(t,e,r,n={})=>{const o=n.plugins?be(n.plugins):r.plugins,i=n.operators??Qe(n.plugins),s=[],a=[];for(const l of r.list(e.id)){if(n.mappingCandidates&&!n.mappingCandidates.includes(Ft(l))){a.push({mappingId:Ft(l),reason:"mapping is not a partition candidate"});continue}const m=il(t,e,l,r,n.resolveSchema,o,i);typeof m=="string"?a.push({mappingId:Ft(l),reason:m}):"reason"in m?a.push({mappingId:Ft(l),...m}):s.push(m)}if(s.length===0){const l=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id,m=a.filter(({reason:h})=>h!=="mapping is not a partition candidate"),f=m.length>0&&m.every(({missingDimensions:h})=>h&&h.length>0)?[...new Set(m.flatMap(({missingDimensions:h})=>h??[]))]:[];throw new d("QUERY_NOT_COVERED_BY_DATA_SOURCE",f.length>0?`Schema\u300C${l}\u300D\u6CA1\u6709\u6570\u636E\u8868\u80FD\u5B8C\u6574\u8986\u76D6\u67E5\u8BE2\u6240\u9700\u7EF4\u5EA6\u3010${f.join("\u3001")}\u3011\u3002\u8BF7\u68C0\u67E5\u5DF2\u63A5\u5165\u6570\u636E\u8868\u7684\u7EF4\u5EA6\u7EC4\u5408\u3002`:`Schema\u300C${l}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u65E0\u6CD5\u56DE\u7B54\u6B64\u95EE\u9898\u3002\u8BF7\u68C0\u67E5\u6570\u636E\u8868\u7684\u5B57\u6BB5\u3001\u7EF4\u5EA6\u7EC4\u5408\u548C\u65F6\u95F4\u7C92\u5EA6\u3002`,{schemaId:e.id,schemaLabel:l,...f.length>0?{uncoveredDimensions:f}:{},rejectedMappings:a})}const c=n.preferredConnectionId===void 0?[]:s.filter(({mapping:l})=>l.connectionId===n.preferredConnectionId),p=(c.length>0?c:s).reduce((l,m)=>m.priority>l.priority||m.priority===l.priority&&m.specificity>l.specificity?m:l);for(const l of s){if(l===p)continue;let m;c.length>0&&l.mapping.connectionId!==n.preferredConnectionId?m=`connection ${l.mapping.connectionId} does not match preferred connection ${n.preferredConnectionId}`:l.priority<p.priority?m=`priority ${l.priority} is lower than selected priority ${p.priority}`:l.specificity<p.specificity?m=`specificity ${l.specificity} is lower than selected specificity ${p.specificity}`:m="priority and specificity tie; an earlier registered mapping was selected",a.push({mappingId:Ft(l.mapping),reason:m})}return{mapping:p.mapping,logicform:p.logicform,predRewrites:p.predRewrites,selection:{schemaId:e.id,selectedMappingId:Ft(p.mapping),rejectedMappings:a}}},js=(t,e,r)=>{const n=t.id,o="__sdb_mapping",i=t.properties.flatMap(g=>{const w=ve(e,t,g.id);return w?[{property:g,source:w}]:[]}),s=(e.mappings??[]).flatMap(g=>g.mappingType==="predItem"&&g.sourceColumn?[{column:g.sourceColumn,sourceRef:g.sourceRef}]:[]),a=new Set([...i.flatMap(({source:g})=>g.sourceRef?[g.sourceRef]:[]),...s.flatMap(({sourceRef:g})=>g?[g]:[])]),c=Fn(t,r),u=(e.enrichments??[]).filter(({id:g})=>a.has(g)).map(g=>{const w=g.temporal?(()=>{if(!c)throw new d("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${g.id} requires an entity with interval semantics`);const L=ve(e,t,c.start.name),I=ve(e,t,c.end.name);if(!L||!I||L.sourceRef||I.sourceRef)throw new d("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${g.id} requires base-source interval columns`);return{kind:"point-in-interval",pointSide:"target",pointColumn:g.temporal.pointColumn,intervalSide:"source",startColumn:L.column,endColumn:I.column}})():void 0;return{kind:"enrichment-left",id:g.id,source:g.source,...g.sourceSql?{sourceSql:g.sourceSql}:{},alias:`__enrichment_${g.id}`,baseAlias:n,keys:g.on,...w?{temporalCondition:w}:{}}}),p=t.properties.find(({type:g})=>g==="timestamp"),l=p?ve(e,t,p.id):void 0,m=i.map(({property:g,source:w})=>({name:g.id,expression:w.sql?{kind:"property-sql",schemaId:t.id,property:g.name,propertyId:g.id,sql:w.sql,qualifier:w.sourceRef?`__enrichment_${w.sourceRef}`:n,...l?{timestampColumn:l.column}:{},...l?.sourceRef?{timestampQualifier:`__enrichment_${l.sourceRef}`}:{timestampQualifier:n}}:{kind:"column",schemaId:t.id,property:g.name,propertyId:g.id,column:w.column,qualifier:w.sourceRef?`__enrichment_${w.sourceRef}`:n}})),f=new Set(i.map(({property:g})=>g.id)),h=new Set;for(const g of[...i.map(w=>w.source),...s])f.has(g.column)||h.has(g.column)||(h.add(g.column),m.push({name:g.column,expression:{kind:"column",property:g.column,column:g.column,qualifier:g.sourceRef?`__enrichment_${g.sourceRef}`:n}}));const y={schemaId:t.id,source:e.source,connectionId:e.connectionId,...e.sourceSql?{sourceSql:e.sourceSql}:{},sourceAlias:n,fields:{},enrichmentJoins:u,projections:m,groupBy:[],orderBy:[],rowIdentity:{kind:"singleton"}};if(!i.some(({property:g})=>g.udf?.sql))return y;const $=l?p?.id:void 0,E=i.map(({property:g})=>{const w=g.udf?.sql?{kind:"property-sql",schemaId:t.id,property:g.name,propertyId:g.id,sql:g.udf.sql,qualifier:o,...$?{timestampColumn:$}:{},timestampQualifier:o}:{kind:"column",schemaId:t.id,property:g.name,propertyId:g.id,column:g.id,qualifier:o};return{name:g.id,expression:w}});for(const{column:g}of s)f.has(g)||E.some(({name:w})=>w===g)||E.push({name:g,expression:{kind:"column",property:g,column:g,qualifier:o}});const A=i.find(({property:g})=>g.type==="ID");return A&&E.push({name:"__sdb_physical_id",expression:{kind:"column",property:A.property.name,column:A.property.id,qualifier:o}}),{schemaId:t.id,source:e.source,connectionId:e.connectionId,sourcePlan:y,sourceAlias:o,fields:{},projections:E,groupBy:[],orderBy:[],rowIdentity:{kind:"singleton"}}},lr=(t,e)=>!!(t.operator&&e.get(t.operator).kind==="component"),fr=(t,e)=>lr(t,e)?!0:t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?fr(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&fr(r,e)),xs=(t,e)=>t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?fr(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&fr(r,e)),Bs=t=>t.name??(typeof t.pred=="string"?t.pred:void 0),al=(t,e)=>{const r=t.preds??[];if(!r.some(f=>!lr(f,e)&&xs(f,e)))return;const n=new Set([...r.map(({name:f})=>f).filter(f=>!!f),...(t.groupby??[]).map(Bs).filter(f=>!!f)]);let o=0;const i=()=>{let f;do f=`__nested_component_input_${o}__`,o+=1;while(n.has(f));return n.add(f),f},s=[],a=f=>{const h=i();return s.push(typeof f=="string"?{pred:f,name:h}:{...ae(f),name:h}),h},c=f=>{if(f.query)throw new d("UNSUPPORTED_COMPONENT_NESTING","An operator above a component cannot define pred.query; apply the query inside a materialized input");const h=ae(f);return Array.isArray(f.pred)?h.pred=f.pred.map(y=>typeof y=="string"||!fr(y,e)||lr(y,e)?a(y):c(y)):f.pred&&typeof f.pred=="object"&&(h.pred=lr(f.pred,e)?a(f.pred):c(f.pred)),h},u=r.map(f=>{const h=f.name;if(!h)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every projection to have a name");return!lr(f,e)&&xs(f,e)?{...c(f),name:h}:(s.push({...ae(f),name:h}),{pred:h,name:h})}),p=ae(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(f=>{const h=Bs(f);if(!h)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every groupby projection to have a name");return{pred:h,name:h}}),m=ae(t);return m.from=p,m.preds=[...l,...u],delete m.query,delete m.groupby,delete m.entity_id,delete m.propertyResolve,m},cl=(t,e)=>`result:${t}:${e.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,Vs=(t,e)=>{const r=(t.columnProperties??[]).map(n=>({...n,id:n.name}));return{id:cl(t.schemaId,t.columnProperties??[]),name:`${e.name} result`,type:e.type,temporalSemantics:"normal",properties:r}},Ys=(t,e)=>({...Vs(t,e),id:e.id,name:e.name,type:e.type}),mr=t=>{if(!t.name)throw new d("MISSING_PRED_NAME","Planner requires every normalized PredItem to have a name");return t.name},Zr=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Zr(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Zr(e)):[]],Eo=(t,e)=>({...t,...typeof t.pred=="string"?{pred:e(t.pred)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Eo(t.pred,e)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(r=>typeof r=="string"?e(r):Eo(r,e))}:{}}),Fs=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(o=>Fs(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:Eo(o,e)}]}return[r.startsWith("$")?r:e(r),n]})),_o=(t,e,r)=>{const n=new Set(r),o=(i,s)=>{if(!(Me(i)||i===null)){if(Array.isArray(i)){i.forEach(a=>o(a,s));return}if(typeof i=="object"){Object.entries(i).forEach(([a,c])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(a)||o(c,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)},Io=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(i=>Io(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&&_o(n,r,o.values),[r,o?{kind:"ordinal-query",comparable:o,condition:n}:n]})),ul=(t,e,r,n)=>{if(!e)return{};const o=e.includes("$TS"),i=o?t.properties.find(({type:a})=>a==="timestamp"):void 0,s=o?i&&(Le(r,t,i.name)??i.id):void 0;return{sql:e,...s?{timestampColumn:s}:{},...s&&n?{timestampQualifier:n}:{}}},Hs=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},Qs=(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}),Qt=(t,e,r,n,o,i,s,a,c="projection")=>{const u=mr(t);if(c==="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 w=r(t.pred);return{expression:Hs(w.field),outputProperty:Qs(w.reference,w.property),sourceProperty:w.property,sourceField:w.field}}const p=e.get(t.operator);if(c==="groupby"&&p.kind!=="scalar")throw new d("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(c==="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({executionContext:e.executionContext,reference:t.pred,args:t.args??{},schema:s,...a?{resolveSchema:a}:{}}):void 0,m=l?.reference??t.pred,f=l?.args??t.args??{},h=m&&typeof m=="object"&&!Array.isArray(m)?Qt(m,e,r,n,o,i,s,a,c):typeof m=="string"?Qt({pred:m,name:m},e,r,n,o,i,s,a,c):void 0,y=Array.isArray(m)?m.map(w=>Qt(typeof w=="string"?{pred:w,name:w}:w,e,r,n,o,i,s,a,c)):[];if(p.requiresProperty!==!1&&!h&&y.length===0)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a property`);const $=u,E=p.getOutputProperty?.({executionContext:e.executionContext,name:$,...h?.sourceProperty?{property:h.sourceProperty}:{},...h?{inputProperty:{...h.outputProperty,name:$}}:{},...y.length>0?{inputProperties:y.map(({outputProperty:w})=>w)}:{},args:f}),A=E?.description??p.description??h?.outputProperty.description,g={...E??(h?Qs($,h.outputProperty,{isArray:!1}):{name:$,type:"number",primal_type:"number",isArray:!1}),...A!==void 0?{description:A}:{}};if(p.planExpression){const w=p.planExpression({executionContext:e.executionContext,pred:t,...h?{input:h.expression,inputProperty:h.outputProperty}:{},inputs:y.map(({expression:L})=>L),args:f,resolveKey:o,getOperator:L=>e.get(L),planQuery:i});if(w)return{expression:w,outputProperty:g,...h?.sourceProperty?{sourceProperty:h.sourceProperty}:{},...h?.sourceField?{sourceField:h.sourceField}:{}}}if(p.kind==="window"){if(!h||y.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 w=t.args?.direction??"desc";if(w!=="asc"&&w!=="desc")throw new d("INVALID_WINDOW_ARGS",`${t.operator} direction must be asc or desc`);const L=t.args?.partitionBy??[];if(!Array.isArray(L)||L.some(I=>typeof I!="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:h.expression,partitionBy:L.map(I=>n(String(I))),direction:w==="asc"?"ASC":"DESC"},outputProperty:g}}return{expression:{kind:"operator",operator:t.operator,args:f,...t.query?{query:i(t.query)}:{},...h?{input:h.expression}:{},...y.length>0?{inputs:y.map(({expression:w})=>w)}:{},...h?.sourceProperty?{property:h.sourceProperty.name,column:h.sourceProperty.id}:{},...h?.sourceField?{qualifier:h.sourceField.qualifier,schemaId:h.sourceField.schemaId}:{}},outputProperty:g,...h?.sourceProperty?{sourceProperty:h.sourceProperty}:{},...h?.sourceField?{sourceField:h.sourceField}:{}}},dl=(t,e,r,n,o,i,s,a,c,u,p,l=t)=>{const m=mr(t),f=typeof t.pred=="string"?t.pred:void 0,h=!u||!f?r:A=>{const g=r(A);return A===f?{...g,field:{...g.field,column:u}}:g},y=p?{...t,operator:p}:t,$=Qt(y,e,h,n,o,i,s,a),E=c?.resolveProjection({pred:l,schema:s,executionContext:e.executionContext,...$.sourceProperty?{sourceProperty:$.sourceProperty}:{},outputProperty:{...$.outputProperty,name:m},...l.operator?{operator:e.get(l.operator)}:{}})??{...$.outputProperty,name:m};return{name:m,expression:$.expression,outputProperty:E}},vs=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)}},So=(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},pl=(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(y=>Ce(y,So(y,r,i),n,o,i)),a=s[0]?.groupBy.map(({name:y})=>y)??[];for(const y of s){const $=y.groupBy.map(({name:E})=>E);if($.length!==a.length||$.some((E,A)=>E!==a[A]))throw new d("INCOMPATIBLE_COMPOSITION_GROUPBY","All composed LogicForm objects must have the same groupby output names in the same order",{expected:a,received:$});if(y.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 c=[],u=[],p=new Map;s.forEach((y,$)=>{y.projections.forEach((E,A)=>{const g=a.includes(E.name),w=p.get(E.name);if(w!==void 0&&!g)throw new d("DUPLICATE_COMPOSITION_OUTPUT",`Composed LogicForm objects produce the same output: ${E.name}`,{name:E.name,childIndexes:[w,$]});if(w!==void 0)return;p.set(E.name,$),c.push({name:E.name,expression:{kind:"column",property:E.name,column:E.name}});const L=y.columnProperties?.[A];L&&u.push(L)})});const l=new Set(c.map(({name:y})=>y)),m=Object.entries(t.sort??{}).map(([y,$])=>{if(!l.has(y))throw new d("INVALID_SORT",`Sort field is not an output: ${y}`);const E=u.find(A=>A.name===y);return{name:y,direction:$===1?"ASC":"DESC",...E?.comparable?{comparable:E.comparable}:{},...E?.comparable?{expression:{kind:"column",property:y,column:y}}:{}}}),f=t.limitBy===void 0||a.length<2?void 0:{count:t.limitBy,partitionBy:a.slice(0,-1),orderBy:m.length>0?m:(()=>{const y=a.at(-1)??"",$=u.find(E=>E.name===y);return[{name:y,direction:"ASC",...$?.comparable?{comparable:$.comparable}:{}}]})()},h=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(c.map(({name:y})=>[y,y])),projections:c,columnProperties:u,groupBy:c.filter(({name:y})=>a.includes(y)),...t.having?{having:Io(t.having,u)}:{},orderBy:m,rowIdentity:a.length>0?{kind:"group",names:a,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"},...f?{groupLimit:f}:{},...h?{pagination:h}:{}}},ll=(t,e,r,n,o)=>{const i=t.groupby??[];if(i.length===0||!t.preds?.length)return;const a=i.filter(_=>typeof _.pred=="string"&&!_.operator&&!_.args).flatMap(_=>{try{const T=oe(e,_.pred,o.resolveSchema);return Array.isArray(T.property.constraints?.enum)&&T.property.constraints.enum.length>0?[{group:_,path:T}]:[]}catch{return[]}});if(a.length!==1)return;const{group:c,path:u}=a[0],p=i.filter(_=>_!==c),l=i.map(mr);if(new Set(l).size!==l.length)return;const f=(u.property.constraints?.enum).map(_=>Array.isArray(_)?_[0]:_);if(f.some(_=>typeof _!="string"||_.length===0)||new Set(f).size!==f.length)return;const h=f,y=_=>{try{return oe(e,_,o.resolveSchema).canonicalId===u.canonicalId}catch{return!1}},$=_=>Object.entries(_).some(([T,k])=>T==="$expr"||(T==="$and"||T==="$or")&&Array.isArray(k)&&k.some(U=>$(U))||!T.startsWith("$")&&y(T)),E=Object.entries(t.query??{}).filter(([_])=>y(_)),A=Object.fromEntries(Object.entries(t.query??{}).filter(([_])=>!y(_)));if(E.length>1||$(A))return;const g=E[0]?.[1],w=g===void 0?h:typeof g=="string"?[g]:typeof g=="object"&&g!==null&&!Array.isArray(g)&&Array.isArray(g.$in)?g.$in:[],L=h.filter(_=>w.includes(_));if(L.length===0)return;const I=t.preds;if(I.some(_=>typeof _.pred!="string"||_.query||_.args||!_.operator||!["$sum","$avg","$min","$max"].includes(_.operator)||_.schema&&_.schema!==e.id))return;const S=n.list(e.id);if(!S.some(_=>I.every(T=>h.every(k=>(_.mappings??[]).filter(U=>{if(U.mappingType!=="predItem"||!U.sourceColumn||typeof U.predItem?.pred!="string"||!U.predItem.query||U.predItem.schema&&U.predItem.schema!==e.id||U.propertyTarget?.length&&!y(U.propertyTarget.join("_"))||U.predItem.operator&&U.predItem.operator!==T.operator)return!1;const B=e.properties.find(G=>G.id===T.pred||G.name===T.pred),Y=e.properties.find(G=>G.id===U.predItem?.pred||G.name===U.predItem?.pred);if(!B||B.id!==Y?.id)return!1;const v=Object.entries(U.predItem.query);return v.length===1&&v.some(([G,z])=>y(G)&&z===k)}).length===1)))){if(!S.some(k=>(k.mappings??[]).some(U=>{if(U.mappingType!=="predItem"||typeof U.predItem?.pred!="string"||!U.predItem.query||U.propertyTarget?.length&&!y(U.propertyTarget.join("_")))return!1;const B=e.properties.find(Y=>Y.id===U.predItem?.pred||Y.name===U.predItem?.pred);return I.some(Y=>{const v=e.properties.find(G=>G.id===Y.pred||G.name===Y.pred);return!!(v&&B&&v.id===B.id)&&Object.keys(U.predItem?.query??{}).some(y)})})))return;const T=`${e.name}(${e.id})`;throw new d("QUERY_NOT_COVERED_BY_DATA_SOURCE",`Schema\u300C${T}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u65E0\u6CD5\u56DE\u7B54\u6B64\u95EE\u9898\u3002\u8BF7\u68C0\u67E5\u6570\u636E\u8868\u7684\u5B57\u6BB5\u3001\u7EF4\u5EA6\u7EC4\u5408\u548C\u65F6\u95F4\u7C92\u5EA6\u3002`,{schemaId:e.id,schemaLabel:T,reason:"enumerated group is missing a unique conditional measure for every enum value"})}const{query:N,groupby:D,having:F,sort:V,limit:x,limitBy:M,page:j,...K}=t,H=L.map(_=>Ce({...K,...Object.keys(A).length>0?{query:A}:{},...p.length>0?{groupby:p}:{},preds:I.map(T=>({...T,query:{[c.pred]:_}}))},e,r,n,o));if(new Set(H.map(_=>_.connectionId)).size!==1)throw new d("SPLIT_GROUP_CONNECTION_MISMATCH","Enumerated group branches must use one physical connection");const re=mr(c),ye={name:re,type:u.property.type,primal_type:u.property.primal_type,isArray:!1,...u.property.comparable?{comparable:u.property.comparable}:{}},Ue=H[0],fe=l.map(_=>({name:_,expression:{kind:"column",property:_,column:_}})),Re=Ue.projections.filter(_=>!p.some(T=>T.name===_.name)),se=[...fe,...Re.map(({name:_})=>({name:_,expression:{kind:"column",property:_,column:_}}))];vs(se);const Ne=Ue.columnProperties??[],b=[...l.map(_=>_===re?ye:Ne.find(T=>T.name===_)),...Ne.filter(_=>!l.includes(_.name))],O=new Set(se.map(_=>_.name)),C=Object.entries(t.sort??{}).map(([_,T])=>{if(!O.has(_))throw new d("INVALID_SORT",`Sort field is not an output: ${_}`);const k=b.find(U=>U.name===_)?.comparable;return{name:_,direction:T===1?"ASC":"DESC",...k?{comparable:k,expression:{kind:"column",property:_,column:_}}:{}}}),q=t.limitBy!==void 0?{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:e.id,source:"",...Ue.connectionId?{connectionId:Ue.connectionId}:{},subplans:H,splitGroup:{name:re,values:L,groupNames:l},fields:Object.fromEntries(se.map(_=>[_.name,_.name])),projections:se,columnProperties:b,groupBy:fe,...t.having?{having:Io(t.having,b)}:{},orderBy:C,rowIdentity:{kind:"group",names:l,separator:"_",nullLabel:"\u7A7A\u503C"},...q?{pagination:q}:{}}},Ce=(t,e,r=Qe(),n=new At,o={})=>{if(!o.mappingCandidates){const b=o.preplannedPartitions?.get(JSON.stringify(t));if(b)return b}const i=[...new Set((t.preds??[]).map(b=>b.schema).filter(b=>!!(b&&b!==e.id)))];if(i.length>0){const b=t.propertyResolve??{},O=[e.id,...i].map(C=>{const{having:q,sort:_,limit:T,limitBy:k,page:U,...B}=t,Y=v=>{let G=v;try{G=oe(e,v,o.resolveSchema).canonicalName}catch{}return b[C]?.[v]??b[C]?.[G]??v};return{...B,schema:C,preds:(t.preds??[]).filter(v=>(v.schema??e.id)===C).map(({schema:v,...G})=>G),...C===e.id||!t.query?{}:{query:Fs(t.query,Y)},...C!==e.id&&t.groupby?{groupby:t.groupby.map(v=>({...v,...typeof v.pred=="string"?{pred:Y(v.pred)}:{}}))}:{}}});return pl(t,O,e,r,n,o)}const s=al(t,r);if(s)return Ce(s,e,r,n,o);for(const b of t.preds??[]){if(!b.operator)continue;const O=r.get(b.operator).rewriteLogicform?.({executionContext:r.executionContext,logicform:t,schema:e,getOperator:C=>r.get(C)});if(O)return Ce(O,e,r,n,o)}const a=o.semanticRegistry??Ms(o.plugins);if(t.from){const b=So(t.from,e,o),O=Ce(t.from,b,r,n,o),C=Ys(O,e),q={...t};delete q.from,q.schema??=C.id;const _=new At([...n.definitions().filter(({schemaId:ee})=>ee!==C.id),{schemaId:C.id,connectionId:O.connectionId??o.preferredConnectionId??"__derived__",source:O.source||"__derived__"}],n.plugins.filter(ee=>!Fr.includes(ee))),{onSchemaMappingSelection:T,...k}=o,U=Ce(q,C,r,_,k),B=new Set(U.projections.map(({name:ee})=>ee)),Y=O.rowIdentity.kind==="group"&&O.rowIdentity.names.every(ee=>B.has(ee))||O.rowIdentity.kind==="singleton"?O.rowIdentity:{kind:"generated"},v=O.groupBy.map(({name:ee})=>ee).filter(ee=>B.has(ee)),G=v.at(-1),z=O.columnProperties?.find(ee=>ee.name===G),W=t.limitBy!==void 0&&v.length>0?{count:t.limitBy,partitionBy:v.slice(0,-1),orderBy:U.orderBy.length>0?U.orderBy:v.slice(-1).map(ee=>({name:ee,direction:"ASC",...z?.comparable?{comparable:z.comparable}:{}}))}:void 0;return{...U,source:O.source||"__derived__",sourcePlan:O,sourceLogicform:t.from,rowIdentity:Y,...W?{groupLimit:W}:{}}}if(!t.schema)throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const c=ll(t,e,r,n,o);if(c)return c;const u=sl(t,e,n,{operators:r,...o.mappingCandidates?{mappingCandidates:o.mappingCandidates}:{},...o.plugins?{plugins:o.plugins}:{},...o.preferredConnectionId?{preferredConnectionId:o.preferredConnectionId}:{},...o.resolveSchema?{resolveSchema:o.resolveSchema}:{}});o.onSchemaMappingSelection?.(u.selection),t=u.logicform;const p=nt(u.mapping)&&e.properties.some(b=>b.udf?.sql&&ve(u.mapping,e,b.id)),l=new Map(u.predRewrites.map(({predIndex:b,column:O})=>[b,O])),m=Fn(e,o.plugins),f=qu(t,e,o.plugins),h=a.resolveQuery({logicform:t,schema:e,...t.query?{query:t.query}:{}}),y=f?.rewriteQuery?f.rewriteQuery(h):h,$=e.id,E=new Map,A=new Map,g=new Map,w=new Map,L=b=>{const O=A.get(b);if(O)return O.alias;const C=u.mapping.enrichments?.find(T=>T.id===b);if(!C)throw new d("SCHEMA_MAPPING_ENRICHMENT_NOT_FOUND",`Schema mapping enrichment is not registered: ${b}`,{schemaId:e.id,mappingId:u.mapping.id,enrichmentId:b});const q=`__enrichment_${b}`,_=C.temporal?(()=>{if(!m)throw new d("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${b} requires an entity with interval semantics`,{schemaId:e.id,enrichmentId:b});const T=ve(u.mapping,e,m.start.name),k=ve(u.mapping,e,m.end.name);if(!T||!k)throw new d("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${b} requires mapped interval boundary columns`,{schemaId:e.id,enrichmentId:b});if(T.sourceRef||k.sourceRef)throw new d("POINT_ENRICHMENT_INTERVAL_MUST_USE_BASE_SOURCE",`Point enrichment ${b} requires interval boundaries on the base source`,{schemaId:e.id,enrichmentId:b});return{kind:"point-in-interval",pointSide:"target",pointColumn:C.temporal.pointColumn,intervalSide:"source",startColumn:T.column,endColumn:k.column}})():void 0;return A.set(b,{kind:"enrichment-left",id:b,source:C.source,...C.sourceSql?{sourceSql:C.sourceSql}:{},alias:q,baseAlias:$,keys:C.on,..._?{temporalCondition:_}:{}}),q},I=b=>{const O=oe(e,b,o.resolveSchema);let C=$,q=u.mapping;const _=[];for(const Y of O.relations){_.push(Y.property.name);const v=_.join("_"),G=v,z=n.get(Y.targetSchema.id,u.mapping.connectionId);if(q=z,!E.has(v)){const W=Y.targetSchema.properties.filter(({type:He})=>He==="ID"),[ee]=W;if(W.length!==1||!ee)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${Y.targetSchema.id} must contain exactly one ID property`,{schemaId:Y.targetSchema.id,count:W.length});const de=Y.sourceSchema.id===e.id?u.mapping:n.get(Y.sourceSchema.id,u.mapping.connectionId),Ae=Le(de,Y.sourceSchema,Y.property.name)??Y.property.id,Ee=nt(de)?void 0:Y.property.udf?.sql,_e=Le(z,Y.targetSchema,ee.name)??ee.id,me=nt(z)?void 0:ee.udf?.sql,Ie=Y.sourceSchema.properties.find(({type:He})=>He==="timestamp"),Oe=Y.targetSchema.properties.find(({type:He})=>He==="timestamp"),he=Uu(Y.sourceSchema,Y.targetSchema,o.plugins),Be=Ie?Le(de,Y.sourceSchema,Ie.name)??Ie.id:void 0,Ge=Oe?Le(z,Y.targetSchema,Oe.name)??Oe.id:void 0,Pt=he?.kind==="date-bucket-equal"?{kind:"date-bucket-equal",sourceColumn:Le(de,Y.sourceSchema,he.sourceTimestamp.name)??he.sourceTimestamp.id,targetColumn:Le(z,Y.targetSchema,he.targetTimestamp.name)??he.targetTimestamp.id,sourceGranularity:he.sourceTimestamp.granularity??"day",targetGranularity:he.targetTimestamp.granularity??"day"}:he?.kind==="point-in-interval"?{kind:"point-in-interval",pointSide:"source",pointColumn:Le(de,Y.sourceSchema,he.point.name)??he.point.id,intervalSide:"target",startColumn:Le(z,Y.targetSchema,he.start.name)??he.start.id,endColumn:Le(z,Y.targetSchema,he.end.name)??he.end.id}:void 0,Fe=Y.property.isArray?v:void 0;Fe&&!g.has(Fe)&&g.set(Fe,{path:Fe,sourceAlias:C,sourceColumn:Ae,...Ee?{sourceSql:Ee,...Be?{sourceTimestampColumn:Be}:{}}:{},alias:`__array_${v}`}),E.set(v,{kind:"left",path:v,sourceAlias:C,sourceColumn:Ae,...Ee?{sourceSql:Ee,...Be?{sourceTimestampColumn:Be}:{}}:{},targetSchemaId:Y.targetSchema.id,targetConnectionId:z.connectionId,targetSource:z.source,...z.sourceSql?{targetSourceSql:z.sourceSql}:{},...nt(z)?{targetMappingSourcePlan:js(Y.targetSchema,z,o.plugins)}:{},targetAlias:G,targetColumn:_e,...Fe?{sourceArrayExpansionPath:Fe}:{},...me?{targetSql:me,...Ge?{targetTimestampColumn:Ge}:{}}:{},...Pt?{temporalCondition:Pt}:{}})}C=G}const T=ve(q,O.schema,O.property.name);if(O.relations.length>0&&T?.sourceRef)throw new d("RELATION_MAPPING_ENRICHMENT_UNSUPPORTED",`Related property ${O.canonicalName} cannot be sourced from a mapping enrichment`,{schemaId:O.schema.id,property:O.property.name});const k=nt(q),U=!k&&T?.sourceRef?L(T.sourceRef):C,B={schemaId:O.schema.id,property:O.property.name,propertyId:O.property.id,column:k?O.property.id:T?.column??O.property.id,qualifier:U,...O.property.isArray?{isArray:!0}:{},...O.property.type==="tag"?{normalizeStringArray:!0}:{},...O.property.comparable?{comparable:O.property.comparable}:{},...ul(O.relations.length>0?e:O.schema,k?void 0:O.property.udf?.sql,O.relations.length>0?u.mapping:q,$)};return w.set(O.canonicalName,B),{reference:O.canonicalName,schema:O.schema,property:O.property,field:B}},S=b=>{if(b)for(const[O,C]of Object.entries(b))if((O==="$and"||O==="$or")&&Array.isArray(C))for(const q of C)typeof q=="object"&&q!==null&&!Array.isArray(q)&&S(q);else if(O==="$expr"&&typeof C=="object"&&C!==null&&!Array.isArray(C)){const q=C.pred;typeof q=="object"&&q!==null&&!Array.isArray(q)&&Zr(q).forEach(I)}else O.startsWith("$")||I(O)},R=b=>{if(Me(b)){const O=So(b,e,o),C=Ce(b,O,r,n,o);if(C.projections.length!==1)throw new d("SUBQUERY_SINGLE_COLUMN_REQUIRED",`Query LogicForm must output exactly one column, received ${C.projections.length}`,{schemaId:b.schema,projectionCount:C.projections.length});return{kind:"logicform-subquery",plan:C}}return Array.isArray(b)?b.map(R):typeof b!="object"||b===null||b instanceof Date?b:Object.fromEntries(Object.entries(b).map(([O,C])=>[O,R(C)]))},N=b=>Object.fromEntries(Object.entries(b).map(([O,C])=>{if((O==="$and"||O==="$or")&&Array.isArray(C))return[O,C.map(_=>N(_))];if(O==="$expr"){if(typeof C!="object"||C===null||Array.isArray(C))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const _=C;if(typeof _.pred!="object"||_.pred===null||Array.isArray(_.pred)||!Object.prototype.hasOwnProperty.call(_,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const T=_.pred,k=Qt(T,r,I,V,x,N,e,o.resolveSchema,"groupby");if(k.outputProperty.isArray)throw new d("ARRAY_EXPRESSION_QUERY_UNSUPPORTED","$expr must produce a scalar value");const U=R(_.condition);return k.outputProperty.comparable&&_o(U,T.name??T.operator??"$expr",k.outputProperty.comparable.values),[O,{kind:"expression-query",expression:k.expression,condition:k.outputProperty.comparable?{kind:"ordinal-query",comparable:k.outputProperty.comparable,condition:U}:U,properties:Zr(T)}]}if(typeof C=="object"&&C!==null&&!Array.isArray(C)){const T=Object.entries(C).find(([k])=>qt(k,o.plugins));if(T){const[k,U]=T,B=qt(k,o.plugins);if(!B)throw new Error(`Query Operator disappeared: ${k}`);const Y=I(O),v=B.plan(U,{schema:Y.schema,property:Y.property,connectionId:u.mapping.connectionId,...o.resolveSchema?{resolveSchema:o.resolveSchema}:{},resolveMapping:(G,z)=>n.get(G,z)});return[O,{[k]:{kind:"query-operator",operator:k,value:v.value,definition:B,...v.sources?{sources:v.sources}:{}}}]}}const q=O.startsWith("$")?void 0:I(O).property.comparable;return[O,q?{kind:"ordinal-query",comparable:q,condition:R(C)}:R(C)]})),D=b=>{const O=q=>{if(!q||typeof q!="object")return!1;if(Array.isArray(q))return q.some(O);const _=q;return Object.prototype.hasOwnProperty.call(_,"$and")||Object.values(_).some(O)};if(O(b))return b;const C=new Set(Object.keys(b).flatMap(q=>{if(q.startsWith("$"))return[];const _=oe(e,q,o.resolveSchema);return _.relations.length===1&&_.property.type==="ID"?[_.relations[0]?.property.name]:[]}));return Object.fromEntries(Object.entries(b).map(([q,_])=>{if(q==="$and"||q==="$or")return Array.isArray(_)?[q,_.map(W=>typeof W=="object"&&W!==null&&!Array.isArray(W)?D(W):W)]:[q,_];if(q.startsWith("$"))return[q,_];const T=oe(e,q,o.resolveSchema);if(T.relations.length===0)return[q,_];if(T.property.udf?.sql.includes("$TS")===!0||T.relations.some(({property:W})=>W.udf?.sql.includes("$TS")===!0))return[q,_];const U=T.relations.map(({property:W})=>W.name).join("_");if(E.has(U))return[q,_];const[B]=T.relations;if(!B)return[q,_];if(C.has(B.property.name))return[q,_];const Y=B.property.name,v=T.canonicalName.slice(Y.length+1),G=B.targetSchema.properties.find(({type:W})=>W==="ID");if(!G)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${B.targetSchema.id} must contain an ID property`,{schemaId:B.targetSchema.id});if(T.relations.length===1&&T.property.id===G.id)return[B.property.id,_];const z={version:t.version,schema:B.targetSchema.id,query:v?{[v]:_}:{},preds:[{pred:G.name,name:G.name}]};return[B.property.id,{$in:z}]}))},F=(t.groupby??[]).map(b=>{const O=mr(b);b.operator&&r.get(b.operator).validateGroupby?.({pred:b,executionContext:r.executionContext});const C=Qt(b,r,I,V,x,N,e,o.resolveSchema,"groupby");let q=C.expression;if(f?.group===b&&(q={kind:"column",schemaId:e.id,property:f.property.name,propertyId:f.property.id,column:"__period_start",qualifier:"__periods"}),C.sourceProperty?.isArray&&C.sourceField){const _=`groupby:${O}`;g.set(_,{path:_,sourceAlias:C.sourceField.qualifier,sourceColumn:C.sourceField.column,...C.sourceField.sql?{sourceSql:C.sourceField.sql,...C.sourceField.timestampColumn?{sourceTimestampColumn:C.sourceField.timestampColumn}:{}}:{},alias:`__array_group_${g.size}`,...C.sourceProperty.type==="tag"?{normalizeStringArray:!0}:{},...C.sourceProperty.type==="tag"?{elementType:"string"}:{}}),q={kind:"array-element",schemaId:C.sourceField.schemaId,property:C.sourceProperty.name,expansionPath:_}}return{name:O,expression:q,outputProperty:{...C.outputProperty,name:O,isArray:!1}}});function V(b){const O=(t.groupby??[]).findIndex(q=>typeof q.pred=="string"&&q.pred===b||q.name===b),C=O>=0?F[O]:void 0;if(!C)throw new d("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${b}`);return C.expression}function x(b){const O=(t.groupby??[]).findIndex(q=>typeof q.pred=="string"&&q.pred===b||q.name===b),C=O>=0?F[O]:void 0;return C?C.expression:Hs(I(b).field)}const M=b=>{b.operator&&r.get(b.operator).validatePlan?.({executionContext:r.executionContext,pred:b,groupByNames:F.map(({name:O})=>O),resolveGroupName:O=>{const C=(t.groupby??[]).findIndex(q=>q.name===O||typeof q.pred=="string"&&q.pred===O);return C>=0?F[C]?.name:void 0},getOperator:O=>r.get(O)}),b.pred&&typeof b.pred=="object"&&!Array.isArray(b.pred)&&M(b.pred);for(const O of Array.isArray(b.pred)?b.pred:[])M(typeof O=="string"?{pred:O}:O)};for(const b of t.preds??[])M(b);const j=[...F,...(t.preds??[]).map((b,O)=>{const C=f?.rewritePred?.(b)??b;return dl(C,r,I,V,x,N,e,o.resolveSchema,a,l.get(O),Di(C,t.groupby??[],e,o.resolveSchema)?"$min":void 0,b)})],K=b=>Object.fromEntries(Object.entries(b).map(([O,C])=>{if((O==="$and"||O==="$or")&&Array.isArray(C))return[O,C.map(_=>K(_))];if(O==="$expr")throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const q=j.find(({name:_})=>_===O)?.outputProperty.comparable;return q&&_o(C,O,q.values),[O,q?{kind:"ordinal-query",comparable:q,condition:R(C)}:R(C)]})),H=y?D(y):void 0;S(H);const re=b=>{S(b.query),b.pred&&typeof b.pred=="object"&&!Array.isArray(b.pred)&&re(b.pred);for(const O of Array.isArray(b.pred)?b.pred:[])re(typeof O=="string"?{pred:O}:O)};for(const b of t.preds??[])re(b);if(j.length===0)throw new d("EMPTY_PROJECTION","LogicForm must contain preds or groupby");vs(j);const ye=new Set(j.map(({name:b})=>b)),Ue=F.length>0?{kind:"group",names:F.map(({name:b})=>b),separator:"_",nullLabel:"\u7A7A\u503C"}:j.every(({expression:b})=>b.kind==="column"||b.kind==="property-sql")||j.some(({expression:b})=>b.kind==="property-sql"&&e.properties.some(({id:O,type:C})=>C==="ID"&&O===b.propertyId))?(()=>{const b=e.properties.find(({type:C})=>C==="ID");if(!b||!(o.canUsePropertyRowIdentity?.(e,b)??!0))return{kind:"generated"};const O=ve(u.mapping,e,b.name);return{kind:"property",column:p&&O?"__sdb_physical_id":nt(u.mapping)&&O?b.id:O?.column??b.id,internalName:"_id"}})():{kind:"singleton"},fe=Object.entries(t.sort??{}).map(([b,O])=>{if(!ye.has(b))throw new d("INVALID_SORT",`Sort field is not an output: ${b}`);const C=j.find(q=>q.name===b);return{name:b,direction:O===1?"ASC":"DESC",...C?.outputProperty.comparable?{comparable:C.outputProperty.comparable,expression:C.expression}:{}}}),Re=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},se=t.limitBy===void 0?void 0:{count:t.limitBy,partitionBy:F.slice(0,-1).map(({name:b})=>b),orderBy:fe.length>0?fe:(()=>{const b=F.at(-1);return[{name:b?.name??"",direction:"ASC",...b?.outputProperty.comparable?{comparable:b.outputProperty.comparable,expression:b.expression}:{}}]})()},Ne=w.size===0&&E.size===0&&A.size===0&&g.size===0&&!H&&F.length===0&&j.length>0&&j.every(({expression:b})=>b.kind==="operator"&&b.operator==="$constant");return{schemaId:e.id,source:Ne?"":u.mapping.source,...Ne?{}:{connectionId:u.mapping.connectionId},...!Ne&&u.mapping.sourceSql?{sourceSql:u.mapping.sourceSql}:{},...!Ne&&nt(u.mapping)?{mappingSourcePlan:js(e,u.mapping,o.plugins)}:{},mappingId:u.mapping.id??u.mapping.source,sourceAlias:$,fields:{...Xc(e),...Object.fromEntries(e.properties.flatMap(b=>{const O=Le(u.mapping,e,b.name);return O?[[b.name,O],[b.id,O]]:[]}))},fieldReferences:Object.fromEntries(w),joins:[...E.values()],enrichmentJoins:nt(u.mapping)?[]:[...A.values()],arrayExpansions:[...g.values()],...f?{periodSource:{alias:"__periods",labelColumn:"__period_start",asOfColumn:"__as_of",sourceAlias:$,periods:f.periods,match:f.source.kind==="interval"?{kind:"interval",startColumn:Le(u.mapping,e,f.source.start.name)??f.source.start.id,endColumn:Le(u.mapping,e,f.source.end.name)??f.source.end.id}:{kind:"latest",lookupAlias:"__period_lookup",timestampColumn:Le(u.mapping,e,f.source.timestamp.name)??f.source.timestamp.id}}}:{},projections:j.map(({name:b,expression:O})=>({name:b,expression:O})),columnProperties:j.map(({outputProperty:b})=>b),groupBy:F.map(({name:b,expression:O})=>({name:b,expression:O})),...H?{query:N(H)}:{},...t.having?{having:K(t.having)}:{},orderBy:fe,rowIdentity:Ne?{kind:"singleton"}:Ue,...Re?{pagination:Re}:{},...se?{groupLimit:se}:{}}};class fl{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 ml=(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(".")},en=(t,e,r)=>r===void 0?ml(t,e):`(${r.trim().replace(/;+\s*$/,"")})`,yr=(t,e,r,n,o)=>{const i=es(t,[],String,`Property ${e} SQL expression`);if(!i.includes("$TS"))return i;if(!n)throw new d("PROPERTY_UDF_TIMESTAMP_REQUIRED",`Property ${e} SQL expression 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)},Ke=(t,e,r,n=!1,o,i,s,a)=>{const c=(u,p)=>n&&p?`${e.quoteIdentifier(p)}.${e.quoteIdentifier(u)}`:e.quoteIdentifier(u);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 c(t.column,t.qualifier);case"property-sql":return yr(t.sql,t.property,e,t.timestampColumn,n?t.timestampQualifier??t.qualifier:void 0);case"window":{if(je(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Window operators cannot consume a JavaScript operator");const u=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(m=>Ke(m,e,r,n,o,i,s,a)).join(", ")} `:"",p=Ke(t.input,e,r,n,o,i,s,a);return`${t.function==="rank"?"RANK":"ROW_NUMBER"}() OVER (${u}ORDER BY ${p} ${t.direction})`}case"cumulative":{if(je(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Cumulative expressions cannot consume a JavaScript operator");const u=Ke(t.input,e,r,n,o,i,s,a),p=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(m=>Ke(m,e,r,n,o,i,s,a)).join(", ")} `:"",l=t.orderBy.map(m=>`${Ke(m.expression,e,r,n,o,i,s,a)} ${m.direction}`).join(", ");return`${e.aggregateFunction(t.function,u)} 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 ${Ke(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 ${Ke(t.input,e,r,n,o,i,s,a)} = ${t.comparable.direction*l} THEN ${i(p)}`).join(" ")} END`}case"operator":{const u=r.get(t.operator);if(u.kind==="component")throw new d("COMPONENT_OPERATOR_REQUIRES_EXECUTOR",`${t.operator} must be compiled through the executor component pipeline`);if(u.toSQL&&(t.input&&je(t.input,r)||t.inputs?.some(m=>je(m,r))))throw new d("UNSUPPORTED_MIXED_OPERATOR",`${t.operator} cannot consume a JavaScript operator in SQL`);let p=t.input?Ke(t.input,e,r,n,o,i,s,a):t.column?c(t.column,t.qualifier):void 0;const l=t.inputs?.map(m=>Ke(m,e,r,n,o,i,s,a));if(t.query&&Object.keys(t.query).length>0){if(u.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(u.requiresProperty!==!1&&!p)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a column`);return u.toSQL?u.toSQL({executionContext:r.executionContext,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:(m,f)=>{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","SQL value binder is unavailable");const h=i(m);return f&&e.castValue?e.castValue(h,f):h},condition:(m,f)=>{if(!s)throw new d("SQL_CONDITION_UNAVAILABLE","SQL condition compiler is unavailable");return s(m,f)}},...p?{expression:p,column:p}:{},...l?{expressions:l}:{},args:t.args}):p??"NULL"}}},je=(t,e)=>t.kind==="window"?je(t.input,e)||t.partitionBy.some(r=>je(r,e)):t.kind==="cumulative"?je(t.input,e)||t.partitionBy.some(r=>je(r,e))||t.orderBy.some(r=>je(r.expression,e)):t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?je(t.input,e):t.kind==="operator"&&(!e.get(t.operator).toSQL&&!!e.get(t.operator).evaluate||(t.input?je(t.input,e):!1)||(t.inputs?.some(r=>je(r,e))??!1)),yl=(t,e)=>{const r=t.sourceSql?yr(t.sourceSql,t.sourceColumn,e,t.sourceTimestampColumn,t.sourceAlias):`${e.quoteIdentifier(t.sourceAlias)}.${e.quoteIdentifier(t.sourceColumn)}`;return t.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(r):r},Gs=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).some(e=>e.startsWith("$")),zs={$second:"second",$minute:"minute",$hour:"hour",$weekday:"weekday",$day:"day",$week:"week",$month:"month",$quarter:"quarter",$year:"year"},hr=(t,e,r,n,o,i,s,a)=>{if(ss(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:m=>n.add(m),renderSource:(m,f)=>en(o,m,f)})}if(s(e))throw new d("INVALID_PLUGIN_QUERY",`${e} query was not planned`,{operator:e});if(e==="$eq"&&a!==void 0){if(typeof r!="string"||a!=="i")throw new d("INVALID_QUERY_VALUE",'$eq args.options supports only case-insensitive string equality with "i"');const l=n.add(r);return"LOWER("+t+") = LOWER("+l+")"}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=jt(r)?`(${i(r)})`:n.add(r);return`${t} ${p} ${l}`}if(e==="$in"||e==="$nin"){const l=e==="$in"?"IN":"NOT IN";if(jt(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 m=r.filter(jt);if(m.length>0){if(m.length!==r.length)throw new d("MIXED_SUBQUERY_VALUES",`${e} cannot mix query LogicForm objects and literal values`);return`${t} ${l} (${m.map(i).join(" UNION ALL ")})`}const f=r.map(h=>n.add(h)).join(", ");return`${t} ${l} (${f})`}if(jt(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}`)},bo=(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&&!jt(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=>bo(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`)}},bt=(t,e,r,n,o,i)=>{if(wp(e)){const u=()=>`CASE ${e.comparable.values.map((f,h)=>`WHEN ${t} = ${r.add(f)} THEN ${e.comparable.direction*h}`).join(" ")} END`,p=new Set(["$gt","$gte","$lt","$lte"]),l=m=>typeof m!="object"||m===null||Array.isArray(m)?bt(t,m,r,n,o,i):Object.entries(m).filter(([f])=>f!=="args").map(([f,h])=>(f==="$and"||f==="$or")&&Array.isArray(h)?`(${h.map(l).join(f==="$and"?" AND ":" OR ")})`:p.has(f)?hr(u(),f,e.comparable.direction*e.comparable.values.indexOf(String(h)),r,n,o,i):hr(t,f,h,r,n,o,i)).join(" AND ");return l(e.condition)}if(Array.isArray(e))return hr(t,"$in",e,r,n,o,i);if(!Gs(e))return hr(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 u=a.options;if(u!==void 0&&typeof u!="string")throw new d("INVALID_QUERY_VALUE","Query args.options must be a string")}const c=a?.options;for(const[u,p]of Object.entries(e))if(u==="$and"||u==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${u} requires an array`);const l=p.map(m=>bt(t,m,r,n,o,i));s.push(`(${l.join(u==="$and"?" AND ":" OR ")})`)}else zs[u]?(bo(p,u),s.push(bt(n.datePart(t,zs[u]),p,r,n,o,i))):u==="$length"?(bo(p,"$length"),s.push(bt(n.stringLength(t),p,r,n,o,i))):u!=="args"&&s.push(hr(t,u,p,r,n,o,i,u==="$regex"||u==="$eq"?c:void 0));if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},Ws=(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(!Gs(e))return i(e);const s=[];for(const[a,c]of Object.entries(e))if(a==="$and"||a==="$or"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const u=c.map(p=>Ws(t,p,r,n));s.push(`(${u.join(a==="$and"?" AND ":" OR ")})`)}else if(a==="$eq")s.push(i(c));else if(a==="$ne")s.push(`NOT (${i(c)})`);else if(a==="$in"||a==="$nin"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const u=c.map(i),p=u.length===0?a==="$in"?"0 = 1":"1 = 1":u.join(a==="$in"?" OR ":" AND NOT ");s.push(a==="$nin"&&u.length>0?`NOT (${u.join(" OR ")})`:`(${p})`)}else if(a==="$exists")s.push(`${t} IS ${c?"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 ")},pt=(t,e,r,n,o,i,s,a)=>{const c=[];for(const[u,p]of Object.entries(t)){if(u==="$and"||u==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${u} requires an array`);const m=p.map(f=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_QUERY_VALUE",`${u} items must be query objects`);return pt(f,e,r,n,o,i,s,a)});c.push(`(${m.join(u==="$and"?" AND ":" OR ")})`);continue}if(u==="$expr"){if(!as(p))throw new d("INVALID_EXPRESSION_QUERY","$expr query was not planned");c.push(bt(s(p.expression),p.condition,n,o,i,a));continue}const l=e(u);c.push(r(u)?Ws(l,p,n,o):bt(l,p,n,o,i,a))}return c.join(" AND ")},vt=(t,e,r,n,o)=>t.orderBy.map(i=>{const s=e.quoteIdentifier(i.name),a=`${n?`${n}.`:""}${s}`,c=i.comparable,u=!n&&o&&i.expression?o(i.expression):a;return`${c?`CASE ${c.values.map((l,m)=>`WHEN ${u} = ${r.add(l)} THEN ${c.direction*m}`).join(" ")} END`:a} ${i.direction}`}).join(", "),Ro=(t,e)=>{let r=t;for(;e.has(r);)r=`_${r}`;return r},tn=(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`])),rn=(t,e,r,n,o)=>{const i=new Set(e.projections.map(({name:R})=>R)),s="__sdb_page_source",a="__sdb_page",c=n.quoteIdentifier(s),u=n.quoteIdentifier(a),p=Ro("__sdb_row_number",i),l=Ro("__sdb_total_rows",i),m=n.quoteIdentifier(p),f=n.quoteIdentifier(l),h=vt(e,n,o,c),y=h?`ORDER BY ${h}`:"",$=`CEIL(${f} * ${r.ratio})`,E=r.page-1,A=r.page,w=[...e.projections.map(({name:R})=>R),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(R=>`${u}.${n.quoteIdentifier(R)}`).join(", "),L=vt(e,n,o,u),I=`SELECT ${c}.*, ROW_NUMBER() OVER (${y}) AS ${m}, COUNT(*) OVER () AS ${f} FROM ${n.tableAlias(`(${t})`,s)}`;let S=`SELECT ${w} FROM ${n.tableAlias(`(${I})`,a)} WHERE ${u}.${m} > ${E} * ${$} AND ${u}.${m} <= ${A} * ${$}`;return L&&(S+=` ORDER BY ${L}`),S},Ks=(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),c=r.quoteIdentifier(s),u=new Set(e.projections.map(({name:A})=>A)),p=Ro("__sdb_limit_by_row_number",u),l=r.quoteIdentifier(p),m=o.partitionBy.map(A=>`${a}.${r.quoteIdentifier(A)}`).join(", "),f=o.orderBy.map(({name:A,direction:g,comparable:w})=>{const L=`${a}.${r.quoteIdentifier(A)}`;return`${w?`CASE ${w.values.map((S,R)=>`WHEN ${L} = ${n.add(S)} THEN ${w.direction*R}`).join(" ")} END`:L} ${g}`}).join(", "),y=[...e.projections.map(({name:A})=>A),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(A=>`${c}.${r.quoteIdentifier(A)}`).join(", "),$=`PARTITION BY ${m} ORDER BY ${f}`,E=`SELECT ${a}.*, ROW_NUMBER() OVER (${$}) AS ${l} FROM ${r.tableAlias(`(${t})`,i)}`;return`SELECT ${y} FROM ${r.tableAlias(`(${E})`,s)} WHERE ${c}.${l} <= ${o.count}`},we=(t,e,r=Qe(),n=0)=>{const o=new fl(e,n),i=I=>qt(I);if(t.sumPartition){const I=t.subplans??[];if(I.length===0)throw new d("INVALID_PARTITION_PLAN","A sum partition requires child plans");const S=t.groupBy.map(({name:j})=>j),R=t.projections.map(({name:j})=>j).filter(j=>!S.includes(j)),N=I.map((j,K)=>{const H=we(j,e,r,o.nextParameterOffset);o.append(H.parameters);const re=`__sum_partition_child_${K}`,ye=e.quoteIdentifier(re);return`SELECT ${[...S,...R].map(fe=>`${ye}.${e.quoteIdentifier(fe)}`).join(", ")} FROM ${e.tableAlias(`(${H.sql})`,re)}`}),D="__sum_partition",F=e.quoteIdentifier(D),V=S.map(j=>`${F}.${e.quoteIdentifier(j)}`),x=[...V.map((j,K)=>`${j} AS ${e.quoteIdentifier(S[K])}`),...R.map(j=>`SUM(${F}.${e.quoteIdentifier(j)}) AS ${e.quoteIdentifier(j)}`)];t.rowIdentity.kind==="group"&&x.push(`${tn(V,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`);let M=`SELECT ${x.join(", ")} FROM ${e.tableAlias(`(${N.join(" UNION ALL ")})`,D)}`;if(V.length>0&&(M+=` GROUP BY ${V.join(", ")}`),t.having&&Object.keys(t.having).length>0){const j="__sum_partition_having",K=e.quoteIdentifier(j),H=new Set(t.projections.map(({name:ye})=>ye)),re=pt(t.having,ye=>{if(!H.has(ye))throw new d("INVALID_HAVING",`Having field is not an output: ${ye}`);return`${K}.${e.quoteIdentifier(ye)}`},()=>!1,o,e,()=>{throw new d("SUBQUERY_IN_PARTITION_HAVING_UNSUPPORTED","Partition having cannot contain a LogicForm subquery")},()=>{throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query")},i);M=`SELECT ${K}.* FROM ${e.tableAlias(`(${M})`,j)} WHERE ${re}`}if(t.pagination?.kind==="ratio")M=rn(M,t,t.pagination,e,o);else if(t.orderBy.length>0&&(M+=` ORDER BY ${vt(t,e,o)}`),t.pagination?.kind==="rows"){const j=(t.pagination.page-1)*t.pagination.pageSize;M=e.paginate(M,t.pagination.pageSize,j)}return{sql:M,parameters:o.values}}if(t.splitGroup){const I=t.splitGroup,S=I.name,R=t.projections.map(({name:F})=>F).filter(F=>!I.groupNames.includes(F));let D=(t.subplans??[]).map((F,V)=>{const x=I.values[V];if(x===void 0)throw new d("INVALID_SPLIT_GROUP","A split group branch has no enum value");const M=I.groupNames.map(se=>se===S?o.add(x):`${e.quoteIdentifier(`__split_group_${V}`)}.${e.quoteIdentifier(se)}`),j=I.groupNames.map(se=>se===S?`'${x.replaceAll("'","''")}'`:`${e.quoteIdentifier(`__split_group_${V}`)}.${e.quoteIdentifier(se)}`),K=tn(j,e,t.rowIdentity.kind==="group"?t.rowIdentity.separator:"_",t.rowIdentity.kind==="group"?t.rowIdentity.nullLabel:"\u7A7A\u503C"),H=we(F,e,r,o.nextParameterOffset);o.append(H.parameters);const re=`__split_group_${V}`,ye=e.quoteIdentifier(re),Ue=I.groupNames.map((se,Ne)=>`${M[Ne]} AS ${e.quoteIdentifier(se)}`),fe=R.map(se=>`${ye}.${e.quoteIdentifier(se)} AS ${e.quoteIdentifier(se)}`),Re=R.map(se=>`${ye}.${e.quoteIdentifier(se)} IS NOT NULL`).join(" OR ");return`SELECT ${[...Ue,...fe].join(", ")}, ${K} AS ${e.quoteIdentifier("_id")} FROM ${e.tableAlias(`(${H.sql})`,re)} WHERE (${Re})`}).join(" UNION ALL ");if(t.having&&Object.keys(t.having).length>0){const F="__split_group_having",V=e.quoteIdentifier(F),x=new Set(t.projections.map(({name:j})=>j)),M=pt(t.having,j=>{if(!x.has(j))throw new d("INVALID_HAVING",`Having field is not an output: ${j}`);return`${V}.${e.quoteIdentifier(j)}`},()=>!1,o,e,()=>{throw new d("SUBQUERY_IN_COMPOSITION_HAVING_UNSUPPORTED","A split group 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);D=`SELECT ${V}.* FROM ${e.tableAlias(`(${D})`,F)} WHERE ${M}`}if(t.pagination?.kind==="ratio")D=rn(D,t,t.pagination,e,o);else if(t.orderBy.length>0&&(D+=` ORDER BY ${vt(t,e,o)}`),t.pagination?.kind==="rows"){const F=(t.pagination.page-1)*t.pagination.pageSize;D=e.paginate(D,t.pagination.pageSize,F)}return{sql:D,parameters:o.values}}if(t.subplans){const I=t.projections.map(({name:x})=>x),S=new Set(t.groupBy.map(({name:x})=>x)),R=t.subplans.map((x,M)=>{const j=we(x,e,r,o.nextParameterOffset);o.append(j.parameters);const K=`__composition_child_${M}`,H=e.quoteIdentifier(K),re=new Set(x.projections.map(({name:ye})=>ye));return{aliasName:K,alias:H,available:re,sql:j.sql}}),N=R[0];if(!N)throw new d("INVALID_COMPOSITION","Composition has no children");const D=I.map(x=>{const M=R.filter(H=>H.available.has(x)),j=M[0]??N;return`${S.has(x)&&M.length>1?`COALESCE(${M.map(H=>`${H.alias}.${e.quoteIdentifier(x)}`).join(", ")})`:`${j.alias}.${e.quoteIdentifier(x)}`} AS ${e.quoteIdentifier(x)}`}),F=R.map(x=>`${x.alias} AS (${x.sql})`);let V;if(t.rowIdentity.kind==="group"){const M=e.quoteIdentifier("__composition_keys"),j=e.quoteIdentifier("_id");F.push(`${M} AS (${R.map(K=>`SELECT ${j} FROM ${K.alias}`).join(" UNION ")})`),D.push(`${M}.${j} AS ${j}`),V=`WITH ${F.join(", ")} SELECT ${D.join(", ")} FROM ${M}`;for(const K of R)V+=` LEFT JOIN ${K.alias} ON ${M}.${j} = ${K.alias}.${j}`}else{V=`WITH ${F.join(", ")} SELECT ${D.join(", ")} FROM ${N.alias}`;for(const x of R.slice(1))V+=` LEFT JOIN ${x.alias} ON 1 = 1`}if(t.having&&Object.keys(t.having).length>0){const x="__composition_having",M=e.quoteIdentifier(x),j=new Set(I),K=pt(t.having,H=>{if(!j.has(H))throw new d("INVALID_HAVING",`Having field is not an output: ${H}`);return`${M}.${e.quoteIdentifier(H)}`},()=>!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);V=`SELECT ${M}.* FROM ${e.tableAlias(`(${V})`,x)} WHERE ${K}`}if(t.groupLimit&&(V=Ks(V,t,e,o)),t.pagination?.kind==="ratio")V=rn(V,t,t.pagination,e,o);else if(t.orderBy.length>0&&(V+=` ORDER BY ${vt(t,e,o)}`),t.pagination?.kind==="rows"){const x=(t.pagination.page-1)*t.pagination.pageSize;V=e.paginate(V,t.pagination.pageSize,x)}return{sql:V,parameters:o.values}}const s=I=>{if(I.plan.projections.some(({expression:R})=>je(R,r)))throw new d("JAVASCRIPT_OPERATOR_IN_SUBQUERY","A query LogicForm cannot use a JavaScript-only operator");const S=we(I.plan.rowIdentity.kind==="property"||I.plan.rowIdentity.kind==="group"?{...I.plan,rowIdentity:{kind:"generated"}}:I.plan,e,r,o.nextParameterOffset);return o.append(S.parameters),S.sql},a=(t.joins?.length??0)>0||(t.enrichmentJoins?.length??0)>0,c=(t.arrayExpansions?.length??0)>0,u=a||c||t.sourcePlan!==void 0||t.mappingSourcePlan!==void 0||t.sourceSql!==void 0||t.periodSource!==void 0,p=new Map,l=(t.arrayExpansions??[]).map(I=>{if(!e.expandArray)throw new d("ARRAY_EXPANSION_UNSUPPORTED",`Provider ${e.kind} does not support array expansion`);const S=e.expandArray(yl(I,e),I.alias,"value",I.elementType);return p.set(I.path,S.valueExpression),S}),m=I=>{const S=t.fieldReferences?.[I];if(S?.sql){const D=yr(S.sql,S.property,e,S.timestampColumn,u?S.timestampQualifier??S.qualifier:void 0);return S.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(D):D}if(S&&u){const D=`${e.quoteIdentifier(S.qualifier)}.${e.quoteIdentifier(S.column)}`;return S.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(D):D}const R=t.fields[I];if(!R)throw new d("PROPERTY_NOT_FOUND",`Query property not found: ${I}`);const N=e.quoteIdentifier(R);return S?.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(N):N},f=I=>Ke(I,e,r,u,S=>pt(S,m,R=>t.fieldReferences?.[R]?.isArray===!0,o,e,s,f,i),S=>o.add(S),(S,R)=>bt(S,R,o,e,s,i),S=>{const R=p.get(S);if(!R)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${S}`);return R}),h=t.projections.map(I=>`${f(I.expression)} AS ${e.quoteIdentifier(I.name)}`),y=t.rowIdentity.kind==="property"?`${u&&t.sourceAlias?`${e.quoteIdentifier(t.sourceAlias)}.`:""}${e.quoteIdentifier(t.rowIdentity.column)} AS ${e.quoteIdentifier(t.rowIdentity.internalName)}`:t.rowIdentity.kind==="group"?(()=>{const I=t.rowIdentity.names.map(S=>{const R=t.groupBy.find(N=>N.name===S)??t.projections.find(N=>N.name===S);if(!R)throw new d("GROUP_IDENTITY_OUTPUT_NOT_FOUND",`Group identity output not found: ${S}`);return f(R.expression)});return`${tn(I,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`})():void 0,$=[...h,...y?[y]:[]].join(", "),E=t.sourcePlan??t.mappingSourcePlan,A=E?(()=>{const I=we(E,e,r,o.nextParameterOffset);return o.append(I.parameters),`(${I.sql})`})():t.source?en(e,t.source,t.sourceSql):"",g=u&&t.sourceAlias?e.tableAlias(A,t.sourceAlias):A;let w=`SELECT ${$}`;if(t.periodSource){const I=t.periodSource,S=I.periods.map(({label:M,asOf:j},K)=>{const H=o.add(M),re=o.add(j);return K===0?`SELECT ${H} AS ${e.quoteIdentifier(I.labelColumn)}, ${re} AS ${e.quoteIdentifier(I.asOfColumn)}`:`SELECT ${H}, ${re}`}).join(" UNION ALL "),R=e.tableAlias(`(${S})`,I.alias),N=e.tableAlias(A,I.sourceAlias),D=e.quoteIdentifier(I.alias),F=e.quoteIdentifier(I.sourceAlias),V=`${D}.${e.quoteIdentifier(I.asOfColumn)}`,x=I.match.kind==="interval"?(()=>{const M=`${F}.${e.quoteIdentifier(I.match.startColumn)}`,j=`${F}.${e.quoteIdentifier(I.match.endColumn)}`;return`${M} <= ${V} AND (${j} > ${V} OR ${j} IS NULL)`})():(()=>{const M=e.tableAlias(A,I.match.lookupAlias),j=e.quoteIdentifier(I.match.lookupAlias),K=`${F}.${e.quoteIdentifier(I.match.timestampColumn)}`,H=`${j}.${e.quoteIdentifier(I.match.timestampColumn)}`,re=`SELECT ${e.aggregateFunction("max",H)} FROM ${M} WHERE ${H} <= ${V}`;return`${K} = (${re})`})();w+=` FROM ${R} LEFT JOIN ${N} ON ${x}`,t.query&&Object.keys(t.query).length>0&&(w+=` AND ${pt(t.query,m,M=>t.fieldReferences?.[M]?.isArray===!0,o,e,s,f,i)}`)}else g&&(w+=` FROM ${g}`);for(const I of l)w+=` ${I.joinSql}`;for(const I of t.enrichmentJoins??[]){const S=e.quoteIdentifier(I.alias),R=e.quoteIdentifier(I.baseAlias);w+=` LEFT JOIN ${e.tableAlias(en(e,I.source,I.sourceSql),I.alias)}`;const N=I.keys.map(({baseColumn:D,targetColumn:F})=>`${R}.${e.quoteIdentifier(D)} = ${S}.${e.quoteIdentifier(F)}`);if(I.temporalCondition?.kind==="point-in-interval"){const D=j=>j==="source"?R:S,F=`${D(I.temporalCondition.pointSide)}.${e.quoteIdentifier(I.temporalCondition.pointColumn)}`,V=D(I.temporalCondition.intervalSide),x=`${V}.${e.quoteIdentifier(I.temporalCondition.startColumn)}`,M=`${V}.${e.quoteIdentifier(I.temporalCondition.endColumn)}`;N.push(`${x} <= ${F}`),N.push(`(${M} > ${F} OR ${M} IS NULL)`)}w+=` ON ${N.join(" AND ")}`}for(const I of t.joins??[]){const S=I.targetMappingSourcePlan?(()=>{const D=we(I.targetMappingSourcePlan,e,r,o.nextParameterOffset);return o.append(D.parameters),`(${D.sql})`})():en(e,I.targetSource,I.targetSourceSql);w+=` LEFT JOIN ${e.tableAlias(S,I.targetAlias)}`;const R=I.sourceArrayExpansionPath?p.get(I.sourceArrayExpansionPath):I.sourceSql?yr(I.sourceSql,I.sourceColumn,e,I.sourceTimestampColumn,I.sourceAlias):`${e.quoteIdentifier(I.sourceAlias)}.${e.quoteIdentifier(I.sourceColumn)}`,N=I.targetSql?yr(I.targetSql,I.targetColumn,e,I.targetTimestampColumn,I.targetAlias):`${e.quoteIdentifier(I.targetAlias)}.${e.quoteIdentifier(I.targetColumn)}`;if(!R)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${I.path}`);if(w+=` ON ${R} = ${N}`,I.temporalCondition?.kind==="date-bucket-equal"){const D=`${e.quoteIdentifier(I.sourceAlias)}.${e.quoteIdentifier(I.temporalCondition.sourceColumn)}`,F=`${e.quoteIdentifier(I.targetAlias)}.${e.quoteIdentifier(I.temporalCondition.targetColumn)}`;w+=` AND ${e.dateBucket(D,I.temporalCondition.sourceGranularity)} = ${e.dateBucket(F,I.temporalCondition.targetGranularity)}`}else if(I.temporalCondition?.kind==="point-in-interval"){const D=j=>j==="source"?e.quoteIdentifier(I.sourceAlias):e.quoteIdentifier(I.targetAlias),F=`${D(I.temporalCondition.pointSide)}.${e.quoteIdentifier(I.temporalCondition.pointColumn)}`,V=D(I.temporalCondition.intervalSide),x=`${V}.${e.quoteIdentifier(I.temporalCondition.startColumn)}`,M=`${V}.${e.quoteIdentifier(I.temporalCondition.endColumn)}`;w+=` AND ${x} <= ${F} AND (${M} > ${F} OR ${M} IS NULL)`}}const L=[];if(!t.periodSource&&t.query&&Object.keys(t.query).length>0&&L.push(pt(t.query,m,I=>t.fieldReferences?.[I]?.isArray===!0,o,e,s,f,i)),L.length>0&&(w+=` WHERE ${L.join(" AND ")}`),t.groupBy.length>0){const I=t.groupBy.map(R=>f(R.expression)),S=t.rowIdentity.kind==="group"?[tn(I,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)]:[];w+=` GROUP BY ${[...I,...S].join(", ")}`}if(t.having&&Object.keys(t.having).length>0){const I=S=>{const R=t.projections.find(N=>N.name===S);if(!R)throw new d("INVALID_HAVING",`Having field is not an output: ${S}`);return e.supportsHavingAlias===!1?f(R.expression):e.quoteIdentifier(S)};w+=` HAVING ${pt(t.having,I,()=>!1,o,e,s,f,i)}`}if(t.groupLimit&&(w=Ks(w,t,e,o)),t.pagination?.kind==="ratio")w=rn(w,t,t.pagination,e,o);else if(t.orderBy.length>0&&(w+=` ORDER BY ${vt(t,e,o,void 0,f)}`),t.pagination?.kind==="rows"){const I=(t.pagination.page-1)*t.pagination.pageSize;w=e.paginate(w,t.pagination.pageSize,I)}return{sql:w,parameters:o.values}},hl=(t,e)=>{const r=Object.keys(e).sort((m,f)=>f.length-m.length),n=[];let o=0;for(;o<t.length;){const m=t[o];if(m&&/\s/.test(m)){o+=1;continue}if(m&&/[()+\-*/,]/.test(m)){n.push(m),o+=1;continue}const f=t.slice(o).match(/^\d+(?:\.\d+)?/);if(f?.[0]){n.push(f[0]),o+=f[0].length;continue}const h=r.find($=>t.startsWith($,o));if(h){n.push(h),o+=h.length;continue}const y=t.slice(o).match(/^[A-Za-z_$][\w$]*/);if(y?.[0]){n.push(y[0]),o+=y[0].length;continue}n.push(m??""),o+=1}let i=0;const s=()=>n[i],a=()=>n[i++],c=()=>{const m=a();if(!m)throw new Error("Component expression is incomplete");if(m==="("){const h=p();if(a()!==")")throw new Error("Component expression has an unclosed parenthesis");return`(${h})`}if(/^\d/.test(m))return m;if(!e[m]&&!/^[A-Za-z_$][\w$]*$/.test(m))throw new Error(`Invalid component expression token: ${m}`);if(s()==="("){a();const h=[];if(s()!==")")for(;h.push(p()),s()===",";)a();if(a()!==")")throw new Error("Component expression has an unclosed function call");if(!["ABS","NULLIF","COALESCE"].includes(m.toUpperCase()))throw new Error(`Unsupported component expression function: ${m}`);return`${m.toUpperCase()}(${h.join(", ")})`}const f=e[m];if(!f)throw new Error(`Unknown component in expression: ${m}`);return f},u=()=>{let m=c();for(;s()==="*"||s()==="/";)m=`${m} ${a()} ${c()}`;return m},p=()=>{let m=u();for(;s()==="+"||s()==="-";)m=`${m} ${a()} ${u()}`;return m},l=p();if(i!==n.length)throw new Error(`Unexpected component expression token: ${s()}`);return l},gl=t=>`__sdb_cte_${t}`,Js=t=>{const e=t.projections[t.groupBy.length];if(!e)throw new Error("CTE component must produce one metric projection");return e.name},Al=(t,e)=>t?.find(r=>r.name===e),$l=(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,No=(t,e,r,n=Qe())=>{if(t.length===0)throw new Error("CTE query combination requires at least one unit");let o=0;const i=t.map((A,g)=>{const w={...A.compiled,sql:$l(A.compiled.sql,r,o)};return o+=A.compiled.parameters.length,{...A,compiled:w,alias:`__sdb_exec_${g}`}}),s=i.map(({alias:A,compiled:g})=>`${r.quoteIdentifier(A)} AS (${g.sql})`),a=i[0],c=r.quoteIdentifier(a.alias),u=e.groupBy.map(({name:A})=>A),p=e.orderBy??[],l=e.rowIdentity.kind==="group",m=r.quoteIdentifier("__sdb_exec_keys");if(l){const A=g=>[...u.map(w=>`${g}.${r.quoteIdentifier(w)}`),`${g}.${r.quoteIdentifier("_id")}`].join(", ");s.push(`${m} AS (${i.map(({alias:g})=>`SELECT ${A(r.quoteIdentifier(g))} FROM ${r.quoteIdentifier(g)}`).join(" UNION ")})`)}const f=l?m:c,h=[...u,...t.flatMap(({outputs:A})=>A)],y=h.filter((A,g,w)=>w.indexOf(A)===g).map(A=>{if(u.includes(A))return`${f}.${r.quoteIdentifier(A)} AS ${r.quoteIdentifier(A)}`;const g=i.find(({outputs:L})=>L.includes(A));if(!g)throw new Error(`CTE execution unit does not expose output projection: ${A}`);return`${r.quoteIdentifier(g.alias)}.${r.quoteIdentifier(A)} AS ${r.quoteIdentifier(A)}`});l&&y.push(`${f}.${r.quoteIdentifier("_id")} AS ${r.quoteIdentifier("_id")}`);let $=`SELECT ${y.join(", ")} FROM ${f}`;for(const A of l?i:i.slice(1)){const g=r.quoteIdentifier(A.alias);$+=` LEFT JOIN ${g}`,$+=l?` ON ${f}.${r.quoteIdentifier("_id")} = ${g}.${r.quoteIdentifier("_id")}`:" ON 1 = 1"}if(!!(e.having&&Object.keys(e.having).length>0||p.length>0||e.pagination||e.groupLimit)){const A={schemaId:e.schemaId,source:"__sdb_cte_result_source",sourceSql:$,sourceAlias:"__sdb_cte_result",fields:Object.fromEntries(h.map(w=>[w,w])),projections:h.map(w=>({name:w,expression:{kind:"column",property:w,column:w}})),groupBy:[],...e.having&&Object.keys(e.having).length>0?{query:e.having}:{},orderBy:p.map(({name:w,direction:L,comparable:I})=>({name:w,direction:L,...I?{comparable:I}:{}})),...e.pagination?{pagination:e.pagination}:{},...e.groupLimit?{groupLimit:e.groupLimit}:{},rowIdentity:{kind:"generated"}},g=we(A,r,n,o);return{sql:`WITH ${s.join(", ")} ${g.sql}`,parameters:[...i.flatMap(({compiled:w})=>w.parameters),...g.parameters]}}return{sql:`WITH ${s.join(", ")} ${$}`,parameters:i.flatMap(({compiled:A})=>A.parameters)}},nn=(t,e,r,n,o,i)=>{const s=[];let a=0;for(const A of e){const g=we(A.plan,o,i,a);a+=g.parameters.length,s.push({input:A,sql:g,alias:gl(A.name)})}const c=s.map(({sql:A,alias:g})=>`${o.quoteIdentifier(g)} AS (${A.sql})`).join(", "),u=s[0];if(!u)throw new Error("CTE calculation requires a current component");const p=o.quoteIdentifier(u.alias),l=r.groupBy.map(({name:A})=>A),m=l.map(A=>`${p}.${o.quoteIdentifier(A)} AS ${o.quoteIdentifier(A)}`);let f="";for(const A of s.slice(1)){const g=o.quoteIdentifier(A.alias),w=A.input.plan.groupBy.map(({name:S})=>S),I=(A.input.joinKeys??l.filter(S=>w.includes(S))).map(S=>{const R=Al(A.input.groupKeyShifts,S),N=R?o.dateShift(`${g}.${o.quoteIdentifier(S)}`,R.granularity,R.offset):`${g}.${o.quoteIdentifier(S)}`;return`${p}.${o.quoteIdentifier(S)} = ${N}`});f+=` LEFT JOIN ${g} ON ${I.length>0?I.join(" AND "):"1 = 1"}`}const h=Object.fromEntries(s.map(({input:A,alias:g})=>[A.name,`${o.quoteIdentifier(g)}.${o.quoteIdentifier(Js(A.plan))}`])),y=hl(t.expression,h),$=[...m,...r.rowIdentity.kind==="group"?[`${p}.${o.quoteIdentifier("_id")} AS ${o.quoteIdentifier("_id")}`]:[],...s.map(({input:A,alias:g})=>`${`${o.quoteIdentifier(g)}.${o.quoteIdentifier(Js(A.plan))}`} AS ${o.quoteIdentifier(A.name)}`),`${y} AS ${o.quoteIdentifier(n)}`].join(", ");let E=`WITH ${c} SELECT ${$} FROM ${p}`;return E+=f,{sql:E,parameters:s.flatMap(({sql:A})=>A.parameters)}},wl=t=>{if(typeof t!="string"||!/\bSELECT\b/i.test(t))return t;try{let e=t;const r=Zs(t).length*2+2;for(let n=0;n<r;n+=1){const o=El(e);if(o===e)return e;e=o}return e}catch{return t}},El=t=>{const e=Zs(t),r=_l(t,e);if(r!==t)return r;const n=[];for(const i of e){const s=ea(t,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?kl(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(y=>y.trim()==="*"))continue;const c=Ul(Il(t.slice(i.fromStart,i.close),i,e)),u=Sl(t,i),p=bl(t,i);if(p&&Rl(u,p))continue;let l=s.filter(y=>{const $=ta(y);if(!$||$==="_id")return!0;const E=new RegExp(`(^|[^\\w$])${Oo($)}([^\\w$]|$)`,"i");return E.test(c)||E.test(u)}),m=!0;for(;m;){m=!1;const y=oa(l.join(" ")),$=s.filter(E=>{if(l.includes(E))return!1;const A=ta(E);return A?new RegExp(`(^|[^\\w$])${Oo(A)}([^\\w$]|$)`,"i").test(y):!1});$.length>0&&(l=s.filter(E=>l.includes(E)||$.includes(E)),m=!0)}if(l.length===s.length)continue;const f=t.slice(i.selectEnd,i.fromStart),h=l.length===0&&ql(t,i)&&!/(^|[^\w$])\*([^\w$]|$)/.test(u)&&!/^\s*(?:DISTINCT|ALL|TOP|SQL_)\b/i.test(f)&&!/\b(?:UNION|INTERSECT|EXCEPT)\b/i.test(c);l.length===0&&!h||n.push({start:i.selectEnd,end:i.fromStart,value:f.match(/^\s*/)[0]+(h?"1":l.map(y=>y.trim()).join(", "))+f.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},_l=(t,e)=>{const r=/^\s*SELECT\b/i.exec(t);if(!r)return t;const n=r.index+r[0].length,o=Xs(t,"FROM",n);if(o===-1||!ea(t,n,o)?.every(Ml))return t;const s=e.find(m=>m.open>o&&t.slice(o+4,m.open).trim().length===0);if(!s||!/^\s*1\s*$/.test(t.slice(s.selectEnd,s.fromStart)))return t;const a=e.filter(m=>m.open>s.fromStart&&m.close<s.close).sort((m,f)=>f.close-f.open-(m.close-m.open))[0];if(!a||t.slice(s.fromStart+4,a.open).trim().length>0)return t;const c=t.slice(a.close+1,s.close);if(/\b(?:GROUP|HAVING|ORDER|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT)\b/i.test(c))return t;const u=Cl.exec(c)?.[1],p=Dl.exec(t.slice(s.close+1));if(!u||!p||ra(u)!==ra(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)=>Nl(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 oa(r)},bl=(t,e)=>t.slice(e.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${ot})(?=\\s|$)`,"i"))?.[1]??null,Rl=(t,e)=>new RegExp(`(^|[^\\w$])${Oo(e)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(t),Nl=(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("")},Xs=(t,e,r)=>{let n=0,o=0,i="",s="";for(let a=r;a<t.length;a+=1){const c=t[a],u=t[a+1];if(s==="--"){c===`
|
|
2
|
+
`&&(s="");continue}if(s==="/*"){c==="*"&&u==="/"&&(s="",a+=1);continue}if(i){c===i&&t[a-1]!=="\\"&&(i="");continue}if(c==="-"&&u==="-"){s="--",a+=1;continue}if(c==="/"&&u==="*"){s="/*",a+=1;continue}if(c==="`"||c==='"'||c==="'"){i=c;continue}if(c==="("){n+=1;continue}if(c===")"){n-=1;continue}if(c==="["){o+=1;continue}if(c==="]"){o-=1;continue}if(n===0&&o===0&&new RegExp(`^${e}\\b`,"i").test(t.slice(a)))return a}return-1},Zs=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 c=r.pop();if(!c)continue;const u=t.slice(c.open+1,i),p=/^\s*SELECT\b/i.exec(u);if(!p)continue;const l=c.open+1+p[0].length,m=Xs(t,"FROM",l);m===-1||m>=i||e.push({open:c.open,close:i,selectEnd:l,fromStart:m})}return e},ea=(t,e,r)=>{const n=t.slice(e,r),o=[];let i=0,s=0,a=0,c="";for(let u=0;u<n.length;u+=1){const p=n[u];if(c){p===c&&n[u-1]!=="\\"&&(c="");continue}if(p==="`"||p==='"'||p==="'"){c=p;continue}p==="("?s+=1:p===")"?s-=1:p==="["?a+=1:p==="]"?a-=1:p===","&&s===0&&a===0&&(o.push(n.slice(i,u)),i=u+1)}return c||s!==0||a!==0?null:(o.push(n.slice(i)),o)},ta=t=>t.trim().match(/\bAS\s+(`[^`]+`|"[^"]+"|[A-Za-z_][\w$]*)\s*$/i)?.[1]?.replace(/^`|`$/g,"").replace(/^"|"$/g,"")??null,ot='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',Ol=new RegExp(`\\s+AS\\s+${ot}\\s*$`,"i"),Tl=new RegExp(`\\bAS\\s+${ot}`,"gi"),Pl=new RegExp(`(?:${ot}\\s*\\.\\s*)+${ot}`,"g"),Ll=new RegExp(`^${ot}(?:\\s*\\.\\s*${ot})*$`),Cl=new RegExp(`^\\s*(?:AS\\s+)?(${ot})\\s+WHERE\\b`,"i"),Dl=new RegExp(`^\\s*(?:AS\\s+)?(${ot})\\s*;?\\s*$`,"i"),ra=t=>t.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),Ml=t=>{const e=t.replace(Ol,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(e)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(e)},na=(t,e)=>t.replace(e,r=>" ".repeat(r.length)),oa=t=>na(t,Tl),Ul=t=>na(t,Pl),ql=(t,e)=>/\b(?:FROM|JOIN)\s*$/i.test(t.slice(0,e.open)),kl=t=>{const e=t.trim();return Ll.test(e)?e:null},Oo=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),To=(t,e)=>{if(t.kind!=="operator")return!1;const r=e.get(t.operator);return!r.toSQL&&!!r.evaluate||(t.input?To(t.input,e):!1)||(t.inputs?.some(n=>To(n,e))??!1)},ia=(t,e,r,n)=>{if(t.kind!=="operator")return e[r];const o=n.get(t.operator),i=t.input?ia(t.input,e,r,n):e[r];return o.evaluate?Promise.resolve(i).then(s=>o.evaluate?.({executionContext:n.executionContext,input:s,args:t.args})):i},Rt=async(t,e,r)=>{const n=e.filter(({expression:o})=>To(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 ia(s.expression,i,s.name,r);return i}))},on=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),sn=(t,e,r="_",n="\u7A7A\u503C")=>e.map(o=>t[o]===null||t[o]===void 0?n:on(t[o])).join(r),Po=(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?sn(r,e.names,e.separator,e.nullLabel):on(r._id)}:{...r,_id:e.kind==="singleton"?"0":Nn.randomUUID()}}),Lo=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,e},gr=(t,e)=>t.operator&&e.get(t.operator).kind==="component"?!0:!!t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&gr(t.pred,e)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&gr(r,e)),an=(t,e,r,n,o,i,s="zh-CN",a=kr.translator(s))=>{const c=t.preds??[],u=c.map((f,h)=>({pred:f,index:h,definition:f.operator?n.get(f.operator):void 0})).filter(({definition:f})=>f?.kind==="component"&&!f.skipComponentExecution?.({plan:e,executionContext:n.executionContext}));if(u.length===0&&e.sourcePlan||u.length===0)return;for(const f of c)if((!f.operator||n.get(f.operator).kind!=="component")&&(f.pred&&typeof f.pred=="object"&&!Array.isArray(f.pred)&&gr(f.pred,n)||Array.isArray(f.pred)&&f.pred.some(h=>typeof h!="string"&&gr(h,n))))throw new d("UNSUPPORTED_COMPONENT_NESTING","A component operator must currently be the top-level projection operator");const p=[],l=c.filter((f,h)=>!u.some(y=>y.index===h));if(l.length>0){const f=Lo(t);f.preds=l,p.push({kind:"query",logicform:f})}const m=t.groupby?.length??0;for(const{pred:f,index:h,definition:y}of u){const $=y?.createComponent;if(!$)continue;const E=e.projections[m+h]?.name;if(!E)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");const A=i?.preds?.[h],g=$({executionContext:n.executionContext,logicform:Lo(t),pred:A??f,outputName:E,locale:s,t:a,schema:r,resolveSchema:o,...i?{sourceLogicform:Lo(i)}:{}});if("logicform"in g&&(g.logicform.preds??[]).some(w=>gr(w,n)))throw new d("UNSUPPORTED_COMPONENT_NESTING","Nested component operators are not supported yet");p.push("components"in g?{...g,outputName:E}:g)}return p},Je=t=>t instanceof Date?t.getTime():t,jl=(t,e,r,n)=>{const o=Je(t),i=Je(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=>Je(s)===o);case"$nin":return Array.isArray(r)&&r.every(s=>Je(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}`)}},Co=(t,e)=>{if(!e||typeof e!="object"||Array.isArray(e))return Je(t)===Je(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(c=>Co(t,c));return i==="$and"?a.every(Boolean):a.some(Boolean)}return i==="$length"?typeof t=="string"&&Co(t.length,s):jl(t,i,s,typeof o=="string"?o:void 0)})},sa=(t,e)=>Object.entries(e).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>sa(t,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return Co(t[r],n)}),xl=(t,e)=>e.length===0?"0":t._id===void 0?sn(t,e):on(t._id),Do=(t,e)=>{const r=new Map;for(const n of t)for(const o of n){const i=xl(o,e);r.set(i,{...r.get(i)??{},...o})}return[...r.values()]},Mo=(t,e)=>{const r=e.groupBy.map(({name:o})=>o);let n=Do(t,r);if(e.having&&(n=n.filter(o=>sa(o,e.having))),e.groupLimit){const o=e.groupLimit,i=new Map;for(const s of n){const a=sn(s,o.partitionBy);i.set(a,[...i.get(a)??[],s])}n=[...i.values()].flatMap(s=>s.sort((a,c)=>{for(const u of o.orderBy){const p=Je(a[u.name]),l=Je(c[u.name]);if(p!==l)return p==null?u.direction==="ASC"?-1:1:l==null?u.direction==="ASC"?1:-1:(p<l?-1:1)*(u.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=Je(o[s.name]),c=Je(i[s.name]);if(a!==c)return a==null?s.direction==="ASC"?-1:1:c==null?s.direction==="ASC"?1:-1:(a<c?-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},aa=(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},Bl=/^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Vl=t=>{if(typeof t!="string")return!1;const e=Bl.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},Uo=t=>{if(!Vl(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})},ca=(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)&&ca(o,e))),ua=(t,e,r,n=[])=>{if(e===void 0||e==="placeholder")return t;if(!Hn(e))throw new d("INVALID_ENTITY_ID","entity_id must be a non-empty string or a safe integer");const o=Qn(r,n);return t&&ca(t,new Set([o.name,o.id]))?t:{[o.name]:e,...t??{}}},Gt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Yl={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},da={$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"}},zt=(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=>zt(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=>zt(n,e)).join(e?", ":"\u3001");if(t.root!==void 0)return zt(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])}${Yl[n]??""}`);return r.length>0?r.join(e?", ":""):e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6"},cn=(t,e,r)=>t.filter(Boolean).join(r?e==="$and"?" and ":" or ":e==="$and"?"\u4E14":"\u6216"),pa=(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}`},Ar=(t,e,r)=>{if(!Gt(e)||Object.keys(e).every(o=>!o.startsWith("$")))return pa("$eq",t,zt(e,r),r)??"";const n=[];for(const[o,i]of Object.entries(e))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(cn(i.map(s=>Ar(t,s,r)),o,r));else if(o==="$exists")n.push(r?`${t} ${i?"exists":"does not exist"}`:`${i?"\u6709":"\u65E0"}${t}`);else if(da[o]){const s=da[o];n.push(Ar(r?`${t} ${s.en}`:`${t}\u7684${s.zh}`,i,r))}else if(o==="$length")n.push(Ar(r?`${t} length`:`${t}\u957F\u5EA6`,i,r));else if(o!=="args"){const s=o==="$regex"&&Gt(i)?zt(i.pattern,r):zt(i,r),a=pa(o,t,s,r);a&&n.push(a)}return cn(n,"$and",r)},la=(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(cn(i.map(s=>Gt(s)?la(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(Ar(a,i.condition,r))}else i!==void 0&&n.push(Ar(o,i,r));return cn(n,"$and",r)},Wt=(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??kr,i=o.resolve(n).locale.toLowerCase().startsWith("en"),s=o.translator(n),a=Array.isArray(t.pred)?t.pred.map(f=>typeof f=="string"?f:Wt(f,e,r)):[],c=typeof t.pred=="string"?t.pred:t.pred&&!Array.isArray(t.pred)?Wt(t.pred,e,r):void 0,u=c??(a.length>0?a.join(i?", ":"\u3001"):s("operator.rows",i?"rows":"\u6570\u636E\u884C")),p=t.args??{},l=t.operator?(()=>{const f=e.get(t.operator),h={executionContext:e.executionContext,operandName:u,...c?{inputName:c}:{},inputNames:a,args:p,locale:n,t:s},y=f.defaultName(h);if(typeof y!="string"||y.length===0)throw new d("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});const $=typeof p.granularity=="string"?s(`time.granularity.${p.granularity}`,p.granularity):s("time.granularity.period","\u5468\u671F"),E=i?t.operator==="$concat"?" and ":t.operator==="$multiply"?" times ":" plus ":t.operator==="$concat"?"\u4E0E":t.operator==="$multiply"?"\u4E58\u4EE5":"\u52A0";if(f.defaultNameIsLocalized)return y;const A=typeof f.defaultNameKey=="function"?f.defaultNameKey(h):f.defaultNameKey??`operator.${t.operator}`;return s(A,y,{...p,operandName:u,inputName:c??"",inputNames:a.join(E),input0:a[0]??"",input1:a[1]??"",granularity:$})})():u;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 m=la(t.query,n);return m?i?`${l} where ${m}`:`${m}\u7684${l}`:l},Fl=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},Hl=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}}},$r=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&&!Fl(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),c=Array.isArray(t.pred)?await Promise.all(t.pred.map(f=>$r(typeof f=="string"?{pred:f}:f,s,r,n))):void 0,{query:u,...p}=t,l={...p,...a?{query:a}:{},...c?{pred:c}:{}},m=async f=>{const h=await Ql(f,s,r),y=h.operator?o.get(h.operator).normalizePred?.({pred:h,schema:s,executionContext:o.executionContext})??h:h;return Hl(y)};if(typeof t.pred=="string"){const f=oe(s,t.pred,r.resolveSchema),h={...l,pred:f.canonicalName};return m({...h,name:h.name??Wt(h,o,i)})}if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)){const f={...l,pred:await $r(t.pred,s,r,n)};return m({...f,name:f.name??Wt(f,o,i)})}if(c)return m({...l,name:l.name??Wt(l,o,i)});if(t.pred!==void 0)throw new d("UNSUPPORTED_PRED","A pred must be a property name or nested pred");return m({...l,name:l.name??Wt(l,o,i)})},vl=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),Gl=t=>{if(!Me(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},un=async(t,e)=>{if(Me(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=>un(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 un(n,e)])))},fa=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>fa(o,e))]:[`${e}_${r}`,n])),qo=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},ma=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),ko=new Set([...ma,"$length"]),dn=t=>Array.isArray(t)?t.some(dn):typeof t!="object"||t===null||Me(t)?!1:Object.entries(t).some(([e,r])=>ko.has(e)||dn(r)),ya=(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&&!Me(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=>ya(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`)}},pn=(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)&&pn(t.pred,e);for(const r of Array.isArray(t.pred)?t.pred:[])typeof r!="string"&&pn(r,e)},ha=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(c=>c!=="pred"&&c!=="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");pn(i,r);const s=await $r(i,e,r,()=>Promise.resolve(void 0));pn(s,r);const a=qo(await un(n.condition,r));return ko.has(s.operator)&&ya(a,s.operator),{pred:s,condition:a}},ga=async(t,e,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||Me(e))return{[t]:e};const o={},i=[];for(const[s,a]of Object.entries(e))ko.has(s)?i.push({$expr:await ha({pred:{operator:s,pred:t},condition:a},r,n)}):(s==="$and"||s==="$or")&&Array.isArray(a)&&a.some(dn)?i.push({[s]:await Promise.all(a.map(c=>ga(t,c,r,n)))}):o[s]=a;return Object.keys(o).length>0&&i.unshift({[t]:qo(o)}),i.length===1?i[0]??{}:{$and:i}},jo=t=>Array.isArray(t)?t.some(jo):typeof t!="object"||t===null||Me(t)?!1:Object.entries(t).some(([e,r])=>ma.has(e)||jo(r)),Aa=async(t,e,r,n)=>{const o=u=>{if(Array.isArray(u)){u.forEach(o);return}if(typeof u!="object"||u===null||Me(u))return;const p=u;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"&&jo(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:u=>n.requestTimeWatermark?.(e,r,u)??Promise.resolve(void 0)},a=await Wp(ae(t),s),c=i.normalizeQuery?i.normalizeQuery(a,s):a;if(r.comparable){const u=new Set(r.comparable.values),p=(l,m)=>{if(!(Me(l)||l===null)){if(Array.isArray(l)){l.forEach(f=>p(f,m));return}if(typeof l=="object"){Object.entries(l).forEach(([f,h])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(f)||p(h,f)});return}if(!(m&&["$exists","$regex","$contains","$startsWith","$length"].includes(m))&&(typeof l!="string"||!u.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(c)}return c},xo=async(t,e,r)=>{const n={},o=[],i=[],s=a=>{const c=Object.entries(a);if(c.length===1&&c[0]?.[0]==="$and"&&Array.isArray(c[0][1]))for(const u of c[0][1])s(u);else c.length===1&&c[0]?.[0]==="$expr"?o.push(a):c.every(([u])=>!u.startsWith("$"))?Object.assign(n,a):i.push(a)};for(const[a,c]of Object.entries(t)){if(a==="$and"||a==="$or"){if(!Array.isArray(c))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);n[a]=await Promise.all(c.map(async f=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_QUERY_VALUE",`${a} items must be query objects`);return xo(f,e,r)}));continue}if(a==="$expr"){o.push({$expr:await ha(c,e,r)});continue}const u=oe(e,a,r.resolveSchema);if(Gl(c)&&(u.property.primal_type==="entity"||u.property.primal_type==="object")&&u.property.ref){if(c.schema!==u.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${u.canonicalName} references ${u.property.ref}, not ${c.schema??"undefined"}`);if(!r.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");const f=await r.normalizeNestedLogicform(c);n[u.canonicalName]={$in:f};continue}if(vl(c)){if(c.version!==void 0&&Uo(c),u.property.primal_type!=="entity"&&u.property.primal_type!=="object")throw new d("INVALID_RELATION_QUERY",`Relation query ${a} must resolve to an entity property`);if(!u.property.ref)throw new d("INVALID_RELATION_QUERY",`Nested LogicForm query requires an object property: ${u.canonicalName}`);if(c.schema!==u.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${u.canonicalName} references ${u.property.ref}, not ${c.schema}`);const f=r.resolveSchema?.(c.schema);if(!f)throw new d("SCHEMA_RESOLVER_REQUIRED",`Nested relation query requires Schema ${c.schema}`);const h=ua(c.query,c.entity_id,f,r.plugins),y=await xo(h,f,r);Object.assign(n,fa(y,u.canonicalName));continue}if(typeof c=="object"&&c!==null&&!Array.isArray(c)){const f=c,h=Object.entries(f).filter(([y])=>qt(y,r.plugins));if(h.length>0){const[y]=h,$=y?qt(y[0],r.plugins):void 0;if($?.validateCondition?.(f),!y||h.length!==1||Object.keys(f).length!==1)throw new d("INVALID_PLUGIN_QUERY","A plugin Query Operator cannot be combined with other field operators");const[E,A]=y;if(!$)throw new Error(`Query Operator disappeared: ${E}`);n[u.canonicalName]={[E]:await $.normalize(A,{schema:u.schema,property:u.property,...r.resolveSchema?{resolveSchema:r.resolveSchema}:{},normalizeValue:(g,w,L)=>Aa(g,w,L,r)})};continue}}const p=await un(c,r),l=await Aa(p,u.schema,u.property,r),m=qo(l);if(dn(m)){s(await ga(u.canonicalName,m,e,r));continue}n[u.canonicalName]=m}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},$a=async(t,e,r)=>{if(!t)return;const n=await xo(t,e,r);return Object.keys(n).length===0?void 0:n},wa=(t,e,r)=>Promise.all((t??[]).map(n=>$r(n,e,r,$a))),zl=(t,e,r)=>wa(t??[],e,r),Kt=(t,e)=>{throw new d("INVALID_PAGINATION",t,e)},Wl=t=>{"skip"in t&&Kt("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)&&Kt("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&&Kt("page requires limit",{page:n});return}if((!Number.isFinite(r)||r<0&&r!==-1||r>1&&!Number.isInteger(r))&&Kt("limit must be -1, a non-negative integer, or a ratio between 0 and 1",{limit:r}),r===-1){n!==void 0&&Kt("page cannot be used with unlimited results",{limit:r,page:n}),delete t.limit;return}n!==void 0&&(!Number.isInteger(n)||n<1)&&Kt("page must be a positive integer starting from 1",{page:n}),t.page=n??1},Kl=t=>t.property.name,Ea=(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(c=>c.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 c=r?.(a.ref);if(!c)continue;const u=Ea(c,e,r,n,i);if(u)return`${a.name}_${u}`}},_a=(t,e,r,n)=>{try{const o=oe(t,e,n);return Ea(r,Kl(o),n,o.property.type)}catch{return}},Bo=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Bo(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Bo(e)):[]],Ia=t=>t?Object.entries(t).flatMap(([e,r])=>{if((e==="$and"||e==="$or")&&Array.isArray(r))return r.flatMap(n=>Ia(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)?Bo(n):[]}return e.startsWith("$")?[]:[e]}):[],Jl=(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 c=r.resolveSchema?.(s),u={};for(const[p,l]of Object.entries(a))try{const m=oe(e,p,r.resolveSchema),f=c?oe(c,l,r.resolveSchema):void 0;u[m.canonicalName]=f?.canonicalName??l}catch{u[p]=l}o[s]=u}const i=[...(t.groupby??[]).map(s=>s.pred),...Ia(t.query)];for(const s of i){if(typeof s!="string")continue;let a;try{a=oe(e,s,r.resolveSchema)}catch{continue}for(const c of n){const u=r.resolveSchema?.(c),p=u&&_a(e,s,u,r.resolveSchema);p&&p!==a.canonicalName&&(o[c]={...o[c]??{},[a.canonicalName]:p})}}return Object.keys(o).length>0?{...t,propertyResolve:o}:t},Xl=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`)}}},Zl=async(t,e,r)=>{if(!t)return;const n=aa(t,e,r);return lt(t,n,r)},lt=async(t,e,r)=>{if(r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:qr([...be(r.plugins).flatMap(y=>y.locales??[]),...r.locales===void 0?[]:"locale"in r.locales?[r.locales]:r.locales])},...r.operators?{}:{operators:Qe(r.plugins)}},Uo(t),Xl(t.propertyResolve),t.output&&t.output.type!=="data"&&t.output.type!=="sql"&&!Vn(t.output.type,r.plugins))throw new d("UNSUPPORTED_OUTPUT",`Output type is not supported: ${t.output.type}`);const o=ae(t),i={...r,normalizeNestedLogicform:async y=>{const $=aa(y,e,r);return lt(y,$,r)}};Wl(o);const s=await Zl(o.from,e,i),a=s&&r.resolveFromSchema?await r.resolveFromSchema(s,e):e,c=await $a(ua(o.query,o.entity_id,a,r.plugins),a,i),u=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,p={...i,...c?{autoCaseQuery:c}:{}};let l=await wa(u,a,p),m=await zl(o.groupby,a,p);const f=m.filter(y=>Di(y,m,a,r.resolveSchema));if(f.length>0){const y=new Set(f.map(({name:$})=>$));m=m.filter(({name:$})=>!y.has($)),l=[...l,...f]}return o.preds=l,m.length>0?o.groupby=m:delete o.groupby,s?o.from=s:delete o.from,c?o.query=c:delete o.query,Jl(o,a,i)},Sa=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),it=(t,e)=>{if(t){if(!Sa(t,e))throw new d("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},Nt=(t,e,r)=>{const n=it(t,e)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},wr=(t,e,r)=>{if(!Nt(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})},Vo=(t,e,r,n)=>{const o=oe(e,t,n);for(const i of o.relations)it(r,i.targetSchema.id),wr(r,i.sourceSchema,i.property);wr(r,o.schema,o.property)},ba=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),ln=(t,e,r,n)=>{if(Me(t)){mn(t,e,r,n);return}if(Array.isArray(t)){for(const o of t)ln(o,e,r,n);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const o of Object.values(t))ln(o,e,r,n)};function Er(t,e,r,n,o){const i=t.schema?n(t.schema):e;t.schema&&it(r,t.schema),typeof t.pred=="string"?Vo(t.pred,i,r,n):t.pred&&!Array.isArray(t.pred)&&Er(t.pred,i,r,n,o);for(const s of Array.isArray(t.pred)?t.pred:[])typeof s=="string"?Vo(s,i,r,n):Er(s,i,r,n,o);fn(t.query,i,r,n,o)}const fn=(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 c of s)fn(c,e,r,n,o);continue}if(i==="$expr"){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const c=s.pred;typeof c=="object"&&c!==null&&!Array.isArray(c)&&Er(c,e,r,n,o),ln(s.condition,r,n,o)}continue}const a=oe(e,i,n);if(Vo(i,e,r,n),typeof s=="object"&&s!==null&&!Array.isArray(s))for(const[c,u]of Object.entries(s))qt(c,o)?.authorize?.(u,{schema:a.schema,property:a.property,resolveSchema:n,assertSchemaAllowed:p=>{it(r,p)},assertPropertyAllowed:(p,l)=>wr(r,p,l),hasRowPermissions:p=>it(r,p)?.rowPermissions!==void 0});if(ba(s)){if(a.property.ref!==s.schema)continue;const c=n(s.schema);it(r,c.id),Hn(s.entity_id)&&wr(r,c,Qn(c,o)),fn(s.query,c,r,n,o);continue}ln(s,r,n,o)}},mn=(t,e,r,n=[])=>{if(!t.schema){if(t.from){mn(t.from,e,r,n);return}throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const o=r(t.schema);if(it(e,o.id),Hn(t.entity_id)&&wr(e,o,Qn(o,n)),t.from){mn(t.from,e,r,n);return}fn(t.query,o,e,r,n);for(const i of t.preds??[])Er(i,o,e,r,n);for(const i of t.groupby??[])Er(i,o,e,r,n)},yn=(t,e)=>{if(Array.isArray(t))return t.map(o=>yn(o,e));if(typeof t!="object"||t===null||t instanceof Date)return t;const r=Object.entries(t).map(([o,i])=>[o,yn(i,e)]),n=Object.fromEntries(r);return ba(t)&&!Sa(t,"version")&&(n.version=e),n},ef=(t,e,r)=>{const n=[],o=(s,a)=>{if(s)for(const[c,u]of Object.entries(s))if((c==="$and"||c==="$or")&&Array.isArray(u))for(const p of u)o(p,a);else if(c==="$expr"&&typeof u=="object"&&u!==null&&!Array.isArray(u)){const p=u.pred;typeof p=="object"&&p!==null&&!Array.isArray(p)&&i(p,a)}else c.startsWith("$")||n.push(oe(a,c,r))},i=(s,a)=>{const c=s.schema?r(s.schema):a;typeof s.pred=="string"?n.push(oe(c,s.pred,r)):s.pred&&!Array.isArray(s.pred)&&i(s.pred,c);for(const u of Array.isArray(s.pred)?s.pred:[])typeof u=="string"?n.push(oe(c,u,r)):i(u,c);o(s.query,c)};o(t.query,e);for(const s of t.preds??[])i(s,e);for(const s of t.groupby??[])i(s,e);return n},tf=(t,e,r)=>{if(!t.schema)return[];const n=r(t.schema),o=new Set,i=[];for(const s of ef(t,n,r)){if(s.relations.length===0)continue;let a=-1;if(s.relations.forEach(({targetSchema:l},m)=>{e[l.id]?.rowPermissions!==void 0&&(a=m)}),a<0)continue;const c=s.relations.slice(0,a+1),u=c.map(({property:l})=>l.name).join("_");if(o.has(u))continue;o.add(u);let p={};for(const l of[...c].reverse())p={[l.property.name]:{schema:l.targetSchema.id,query:p}};i.push(p)}return i},Jt=(t,e,r,n,o,i)=>Me(t)?Ot(t,e,r,n,o,i):Array.isArray(t)?t.map(s=>Jt(s,e,r,n,o,i)):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(Object.entries(t).map(([s,a])=>[s,Jt(a,e,r,n,o,i)])),Yo=(t,e,r,n,o,i)=>({...t,...t.query?{query:Jt(t.query,e,r,n,o,i)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Yo(t.pred,e,r,n,o,i)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(s=>typeof s=="string"?s:Yo(s,e,r,n,o,i))}:{}}),Ot=(t,e,r,n=!0,o=new Set,i=[])=>{if(!e)return ae(t);if(!t.schema){const f=ae(t);return f.from&&(f.from=Ot(f.from,e,r,n,new Set,i)),f}n&&mn(t,e,r,i);const s=it(e,t.schema),a=o.has(t.schema),c=new Set(o).add(t.schema),u=ae(t);u.query&&(u.query=Jt(u.query,e,r,n,new Set,i)),u.preds&&(u.preds=u.preds.map(f=>Yo(f,e,r,n,new Set,i))),u.from&&(u.from=Ot(u.from,e,r,n,new Set,i));const p=a||t.from?void 0:s?.rowPermissions,l=(t.from?[]:tf(t,e,r)).map(f=>Jt(yn(f,t.version),e,r,!1,c,i));p&&l.push(Jt(yn(ae(p),t.version),e,r,!1,c,i));const m=[u.query,...l].filter(f=>f!==void 0&&Object.keys(f).length>0);return m.length===1?u.query=m[0]:m.length>1?u.query={$and:m}:delete u.query,u},rf=(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:c})=>a===s||c===s))throw new d("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${r}.${s}`,{schemaId:r,property:s})}},Ra=(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")}},Na=(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=Ra(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)},nf=(t,e)=>{const r=ds(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=Ra(e,t.timeZone);let o=Na({...n,...r},t.timeZone);if(o.getTime()<=e.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=Na({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},t.timeZone)}return o},of=(t,e)=>{const r=t.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(e.getTime()+n.ttlSeconds*1e3)]:[nf(n,e)]);return r.length===0?void 0:new Date(Math.min(...r.map(n=>n.getTime())))},Fo=t=>t===void 0?{type:"undefined"}:typeof t=="bigint"?{type:"bigint",value:t.toString()}:typeof t=="number"&&!Number.isFinite(t)?{type:"number",value:String(t)}:t instanceof Date?{type:"date",value:t.toISOString()}:Array.isArray(t)?t.map(Fo):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,Fo(r)])):t,Oa=t=>Nn.createHash("sha256").update(JSON.stringify(Fo(t))).digest("hex"),sf=t=>Oa({namespace:t.namespace,provider:t.provider,connectionId:t.connectionId,sql:t.sql,parameters:t.parameters}),af=(t,e)=>Oa({namespace:t,source:e}),Ho=t=>t===void 0?{type:"undefined"}:typeof t=="bigint"?{type:"bigint",value:t.toString()}:typeof t=="number"&&!Number.isFinite(t)?{type:"number",value:String(t)}:t instanceof Date?{type:"date",value:t.toISOString()}:Array.isArray(t)?{type:"array",value:t.map(Ho)}:t&&typeof t=="object"?{type:"object",value:Object.entries(t).map(([e,r])=>[e,Ho(r)])}:t,Qo=t=>{if(t===null||typeof t!="object")return t;switch(t.type){case"undefined":return;case"bigint":return BigInt(t.value);case"number":return Number(t.value);case"date":return new Date(t.value);case"array":return t.value.map(Qo);case"object":return Object.fromEntries(t.value.map(([e,r])=>[e,Qo(r)]))}},cf=t=>JSON.stringify(Ho(t)),uf=t=>{const e=Qo(JSON.parse(t));if(!(!Array.isArray(e)||e.some(r=>!r||typeof r!="object"||Array.isArray(r))))return e},df=Number.MAX_SAFE_INTEGER;class pf{#e;#t;#r;constructor(e,r={}){this.#e=e,this.#t=r.keyPrefix??"semanticdb:cache",this.#r=r.ownsClient??!1}#n(e){return`${this.#t}:query:${sf(e)}`}#o(e,r){return`${this.#t}:source:${af(e,r)}`}async get(e){const r=await this.#e.get(this.#n(e));if(r!==null)return uf(r)}async set(e,r,n){const o=this.#n(e),i=cf(r),s=n.expiresAt?.getTime(),a=s??df,c=this.#e.multi();s===void 0?c.set(o,i):c.set(o,i,{PXAT:s});for(const u of new Set(n.sources)){const p=this.#o(e.namespace,u);c.zRemRangeByScore(p,0,Date.now()),c.zAdd(p,{score:a,value:o})}await c.exec()}async invalidateSource(e,r){const n=this.#o(e,r),o=await this.#e.zRange(n,0,-1);o.length>0&&await this.#e.del(o),await this.#e.del(n)}async close(){this.#r&&await this.#e.close()}}const lf=async(t={})=>{const e=hc.createClient(t.url?{url:t.url}:{});return e.on("error",()=>{}),await e.connect(),new pf(e,{...t.keyPrefix?{keyPrefix:t.keyPrefix}:{},ownsClient:!0})};function ff(t){if(!t||typeof t!="object")throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache configuration must be an object");const e=t;if(typeof e.id!="string"||e.id.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache id must not be empty");if(e.kind!=="redis")throw new d("INVALID_QUERY_CACHE_CONFIGURATION",`Unsupported query cache kind: ${String(e.kind)}`);if(typeof e.url!="string"||e.url.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Redis query cache url must not be empty");if(e.keyPrefix!==void 0&&(typeof e.keyPrefix!="string"||e.keyPrefix.trim().length===0))throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Redis query cache keyPrefix must not be empty");if(typeof e.namespace!="string"||e.namespace.trim().length===0)throw new d("INVALID_QUERY_CACHE_CONFIGURATION","Query cache namespace must not be empty")}const mf=({namespace:t,...e})=>e,yf=async t=>lf({url:t.url,...t.keyPrefix?{keyPrefix:t.keyPrefix}:{}});class hf{create;#e=new Map;constructor(e=yf){this.create=e}async get(e){ff(e);const r=mf(e),n=this.#e.get(r.id);if(n){if(!pi.isDeepStrictEqual(n.connection,r))throw new d("QUERY_CACHE_CONFIGURATION_MISMATCH",`Query cache configuration changed for id: ${r.id}`,{cacheId:r.id});return{store:await n.store,namespace:e.namespace}}const o=this.create(r),i={connection:r,store:o};this.#e.set(r.id,i);try{return{store:await o,namespace:e.namespace}}catch(s){throw this.#e.get(r.id)===i&&this.#e.delete(r.id),s}}async close(){const e=[...this.#e.values()];this.#e.clear();const n=(await Promise.allSettled(e.map(async({store:o})=>(await o).close()))).flatMap(o=>o.status==="rejected"?[o.reason]:[]);if(n.length>0)throw new AggregateError(n,"Failed to close one or more query cache connections")}}const Ta=new hf,Pa=t=>Ta.get(t),gf=()=>Ta.close(),Af=async({cache:t,source:e})=>{if(typeof e!="string"||e.trim().length===0)throw new d("INVALID_QUERY_CACHE_SOURCE","Query cache source must not be empty");const r=await Pa(t);await r.store.invalidateSource(r.namespace,e)},$f=Object.freeze({invalidateSource:Af}),wf=()=>{},_r=(t,e)=>e.findSource(t.schemaId,t.mappingSource??t.source,t.connectionId),Ir=(t,e,r)=>{if(jt(t)){e.push(t.plan);return}if(ss(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)Ir(n,e,r);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const n of Object.values(t))Ir(n,e,r)},Sr=(t,e,r)=>{if(t.kind==="window"){Sr(t.input,e,r);for(const n of t.partitionBy)Sr(n,e,r);return}if(t.kind==="operator"){Ir(t.query,e,r),t.input&&Sr(t.input,e,r);for(const n of t.inputs??[])Sr(n,e,r)}},Pe=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 Pe(o))r(i);else if(t.sourcePlan)for(const o of Pe(t.sourcePlan))r(o);else if(t.mappingSourcePlan)for(const o of Pe(t.mappingSourcePlan))r(o);else t.source&&r({schemaId:t.schemaId,source:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});for(const o of t.joins??[])if(r({schemaId:o.targetSchemaId,source:o.targetSource,...o.targetConnectionId?{connectionId:o.targetConnectionId}:{}}),o.targetMappingSourcePlan)for(const i of Pe(o.targetMappingSourcePlan))r(i);for(const o of t.enrichmentJoins??[])r({schemaId:t.schemaId,source:o.source,mappingSource:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});const n=[];Ir(t.query,n,e),Ir(t.having,n,e);for(const o of t.projections)Sr(o.expression,n,e);for(const o of n)for(const i of Pe(o))r(i);return[...e.values()]},Xt=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()]},La=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})}},Ef=(t,e)=>{const r=[];for(const n of t){const o=_r(n,e),i=n.mappingSource?o?.enrichments?.find(({source:s})=>s===n.source)?.freshness:o?.freshness;if(!i)return;r.push(i)}return r},vo=async(t,e,r,n=wf)=>{t=Ca(t),r.signal?.throwIfAborted();const o=r.cache?Ef(e,r.schemaMappings):void 0;if(!r.cache||!o)return n("database"),La(r.provider,{...t,...r.signal?{signal:r.signal}:{}});const i={namespace:r.cache.namespace,provider:r.provider.kind,...r.connectionId?{connectionId:r.connectionId}:{},sql:t.sql,parameters:t.parameters};try{const a=await r.cache.store.get(i);if(r.signal?.throwIfAborted(),a)return n("cache"),[...a]}catch{r.signal?.throwIfAborted()}n("database");const s=await La(r.provider,{...t,...r.signal?{signal:r.signal}:{}});try{const a=of(o,new Date);await r.cache.store.set(i,s,{sources:[...new Set(e.map(({source:c})=>c))],...a?{expiresAt:a}:{}})}catch{}return s},Ca=t=>({...t,sql:wl(t.sql)}),_f=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")},If=(t,e,r)=>{const n=_f(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}},Da=async(t,e)=>{if(!Nt(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(E=>Nt(e.permissions,t.schema.id,E)),n=e.schemaMappings.list(t.schema.id),o=n.find(({connectionId:E})=>E===e.preferredConnectionId)?.connectionId??n[0]?.connectionId,i=o&&e.providerForConnection?e.providerForConnection(o):e.provider,s={version:e.version,schema:t.schema.id,query:If(t.idProperty.name,t.ids,i.maxInListItems),preds:r.map(E=>({pred:E.name,name:E.name}))},a=Ot(s,e.permissions,e.resolveSchema,!0,new Set,e.plugins),c=await lt(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}),u=Ce(c,t.schema,e.operators,e.schemaMappings,{resolveSchema:e.resolveSchema,...o?{preferredConnectionId:o}:{},canUsePropertyRowIdentity:(E,A)=>Nt(e.permissions,E.id,A)}),p=new Set(Pe(u).map(E=>e.schemaMappings.findSource(E.schemaId,E.source,E.connectionId)?.connectionId).filter(E=>!!E));if(p.size>1)throw new d("CROSS_CONNECTION_ENTITY_HYDRATION_UNSUPPORTED",`Entity hydration cannot span connections: ${[...p].join(", ")}`);const l=[...p][0]??o,m=l&&e.providerForConnection?e.providerForConnection(l):i,f=we(u,m,e.operators),h=Pe(u),y=e.onCompiled?.(f,c,m,l,h),$=await vo(f,h,{provider:m,...l?{connectionId:l}:{},schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},y);return Po($,u.rowIdentity)},Ma=t=>String(t),Sf=(t,e,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${Ma(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=Ma(r),o},Ua=(t,e)=>`${t}:${String(e)}`,bf=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 Rf{#e;#t=new Map;#r=new Map;#n=new Map;#o=!1;constructor(e){this.#e=e}load=(e,r)=>{const n=Ua(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(Fn(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=bf(s);let c,u;const p=new Promise((m,f)=>{c=m,u=f}),l=this.#n.get(e)??{schema:s,idProperty:a,loads:new Map};return l.loads.set(n,{id:r,resolve:m=>c?.(m),reject:m=>u?.(m)}),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),c=i._id===a?i:{...i,_id:a};o.set(Ua(e.schema.id,s),c)}}for(const[i,s]of e.loads){const a=o.get(i)??Sf(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 Nf=(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})}},Of=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=r.get(i.type),a=Nf(o[i.name],i),c={property:i,requestEntity:n},u=s.normalizeResult?await s.normalizeResult(a,c):a,p=s.hydrateResult;if(!p){o[i.name]=u;return}o[i.name]=i.isArray&&Array.isArray(u)?await Promise.all(u.map(l=>p(l,c))):await p(u,c)}))}))},qa=5,Tf=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Pf=(t,e)=>{const r=e.properties.find(({type:n})=>n==="ID");return r?t[r.name]:void 0},Lf=(t,e)=>{const r=gc.getNameProperty(e);t._title=t[r.name]??t._id},Cf=(t,e)=>{const r=structuredClone(t);if(!("_id"in r)){const n=Pf(r,e);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},Df=(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})},Mf=async(t,e,r)=>{const n=new Rf(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 c=a.expandEntities&&i<qa;return Of(a.rows,a.properties,r.semanticTypes,c?n.load:(u,p)=>Promise.resolve(p))}));for(const a of o)if(a.schema)for(const c of a.rows)Lf(c,a.schema);if(i>=qa)return;const s=new Map;for(const a of o)if(a.expandEntities)for(const c of a.properties){if(c.primal_type!=="entity"&&c.primal_type!=="object"||!c.ref)continue;const u=r.resolveSchema(c.ref);for(const p of a.rows){if(!(c.name in p))continue;const l=p[c.name],m=c.isArray?Array.isArray(l)?l:[l]:[l];for(const[f,h]of m.entries()){if(!Tf(h))continue;const y=Cf(h,u);c.isArray?m[f]=y:p[c.name]=y,Df(s,u,y,!c.isArray)}c.isArray&&(p[c.name]=m)}}o=[...s.values()]}},ka=async(t,e,r)=>{const n=t.map(o=>({...o}));return await Mf(n,e,r),n},Go=t=>`'${t.replaceAll("'","''")}'`,ja=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}'`},br=(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():Go(t.toString());if(typeof t=="string")return e==="mysql"?ja(t):Go(t);if(t instanceof Date){const r=e==="clickhouse"||e==="mysql"?t.toISOString().replace("T"," ").replace("Z",""):t.toISOString();return e==="mysql"?ja(r):Go(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}`)},Uf=(t,e)=>t.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in e?br(e[o],"clickhouse"):r}),qf=(t,e)=>t.replace(/:([1-9]\d*)\b/g,(r,n)=>{const o=Number(n)-1;return o in e?br(e[o],"oracle"):r}),kf=(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 c=Number(a)-1;if(c in e){r+=br(e[c],"postgresql"),o+=s[0].length-1;continue}}}r+=i}}return r},zo=(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+=br(e[o],r),o+=1;continue}n+=a}}return n},jf=(t,e)=>zo(t,e,"mysql"),Wo=(t,e)=>zo(t,e,"snowflake"),xf=(t,e)=>zo(t,e,"dameng"),Bf=(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 c=Number(a);if(c in e){r+=br(e[c],"sqlserver"),o+=s[0].length-1;continue}}}r+=i}}return r},ft=(t,e)=>new Error(`Database driver "${t}" is not installed or could not be loaded. Install it with: npm install ${t}`,{cause:e}),Rr=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`)},Ve=(t,e)=>{throw new d("UNSUPPORTED_TABLE_SCOPE",`${t.kind} table discovery does not support a ${e} override`)},Xe=(t,e)=>Object.entries(t).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1],xe=(t,e)=>{const r=Xe(t,e);if(typeof r!="string"||!r)throw new d("INVALID_TABLE_METADATA",`Expected a non-empty metadata field: ${e}`);return r},xa=t=>{const e=xe(t,"table_name"),r=Xe(t,"table_database"),n=Xe(t,"table_schema"),o=xe(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"}},Vf=t=>t.map(xa),Tt=async(t,e)=>{e.signal?.throwIfAborted(),Rr(e);const r=[],n=c=>{const u=t.parameter(r.length,c);return r.push(c),u},o=e.database,i=e.schema;let s;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":i!==void 0&&Ve(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&&Ve(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&&Ve(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&&Ve(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(),Vf(a)},Ko=t=>{if(Rr(t),!t.table.trim())throw new d("INVALID_TABLE_NAME","Table name must not be empty")},hn=(t,e)=>{const r=Xe(t,e);return typeof r=="string"?r:""},Yf=t=>{const e=xe(t,"column_type"),r=Xe(t,"type_length"),n=Xe(t,"type_precision"),o=Xe(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},Ba=t=>{const e=Xe(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:xe(t,"column_name"),type:Yf(t),comment:hn(t,"column_comment"),...r!==void 0?{primaryKey:r}:{}}},Ff=(t,e)=>{const r=[],n=u=>{const p=t.parameter(r.length,u);return r.push(u),p},o=n(e.table),{database:i,schema:s}=e;let a,c;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":{s!==void 0&&Ve(t,"schema");const u=`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 ${u}`,c=`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 ${u} ORDER BY c.ORDINAL_POSITION`;break}case"postgresql":{i!==void 0&&Ve(t,"database");const u=`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 ${u} AND c.relkind IN ('r', 'v', 'm', 'p', 'f')`,c=`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 ${u} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`;break}case"sqlserver":{const u=i!==void 0?`${t.quoteIdentifier(i)}.`:"",p=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"SCHEMA_NAME()"}`,l=`JOIN ${u}sys.schemas s ON s.name = c.TABLE_SCHEMA JOIN ${u}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 ${u}INFORMATION_SCHEMA.TABLES c ${l}LEFT JOIN ${u}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}`,c=`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 ${u}sys.indexes i JOIN ${u}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 ${u}INFORMATION_SCHEMA.COLUMNS c ${l}JOIN ${u}sys.columns sc ON sc.object_id = o.object_id AND sc.name = c.COLUMN_NAME LEFT JOIN ${u}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 u=`${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 ${u}.TABLES c WHERE ${p}`,c=`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 ${u}.COLUMNS c WHERE ${p} ORDER BY c.ORDINAL_POSITION`;break}case"oracle":case"dameng":{i!==void 0&&Ve(t,"database");const u=`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 ${u}`,c=`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 ${u} ORDER BY c.COLUMN_ID`;break}case"clickhouse":{s!==void 0&&Ve(t,"schema");const u=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 = ${u}`,c=`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 = ${u} ORDER BY c.position`;break}default:throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`No table description SQL for provider: ${t.kind}`)}return{tableSql:a,columnSql:c,parameters:r}},Va=(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(".")},Zt=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},Jo=async(t,e,r)=>{if(e.includeSample===!1)return r;const n=Va(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 Zt(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},Hf=async(t,e)=>{let{database:r,schema:n}=e;if(r===void 0||n===void 0){const[l]=await Zt(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??=xe(l,"table_database"),n??=xe(l,"table_schema")}const o=Va(t,{name:e.table,database:r,schema:n}),i=await Zt(t,e,`DESCRIBE TABLE EXTENDED ${o}`),s=[];let a=!0,c=!1,u="",p="table";for(const l of i){const m=Xe(l,"col_name"),f=Xe(l,"data_type"),h=(m==="# Partition Information"||m==="# Detailed Table Information")&&!f;(m===""||h)&&(a=!1),h&&m==="# Detailed Table Information"&&(c=!0),a?s.push({name:xe(l,"col_name"),type:xe(l,"data_type"),comment:hn(l,"comment")}):c&&m==="Comment"?u=hn(l,"data_type"):c&&m==="Type"&&f==="VIEW"&&(p="view")}if(!s.length)throw new d("INVALID_TABLE_METADATA","Databricks description did not contain columns");return Jo(t,e,{columns:s,tableInfo:{name:e.table,database:r,schema:n,type:p,comment:u}})},Qf=async(t,e)=>{e.database!==void 0&&Ve(t,"database"),e.schema!==void 0&&Ve(t,"schema");const n=(await Zt(t,e,`DESC ${t.quoteIdentifier(e.table)}`)).map(Ba);if(!n.length)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);return Jo(t,e,{columns:n,tableInfo:{name:e.table,type:"table",comment:""}})},st=async(t,e)=>{if(e.signal?.throwIfAborted(),Ko(e),t.kind==="databricks")return Hf(t,e);if(t.kind==="maxcompute")return Qf(t,e);const{tableSql:r,columnSql:n,parameters:o}=Ff(t,e),i=await Zt(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={...xa(s),comment:hn(s,"table_comment")},c=(await Zt(t,e,n,o)).map(Ba);return Jo(t,e,{columns:c,tableInfo:a})},vf=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}`},Gf=t=>t===null?"Nullable(String)":typeof t=="boolean"?"Bool":typeof t=="number"?"Float64":t instanceof Date?"DateTime64(3)":"String",Ya=t=>t instanceof Date?t.toISOString().replace("T"," ").replace("Z",""):t;class zf{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 ft("@clickhouse/client",r)});return e({url:vf(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}:${Gf(r)}}`}displayQuery(e,r){return Uf(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}`,Ya(i)]));return(await r.query({query:e.sql,format:"JSONEachRow",query_params:n,...e.signal?{abort_signal:e.signal}:{}})).json()}getTableList(e){return Tt(this,e)}describeTable(e){return st(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,c)=>[`p${c}`,Ya(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 c=JSON.parse(a);if(typeof c!="object"||c===null||Array.isArray(c))throw new Error("ClickHouse provider expected object rows");return c}):[]}}async close(){const e=this.#t;if(!e)return;await(await e).close(),this.#t=void 0}}const Wf=t=>[".azuredatabricks.net",".databricks.azure.cn",".databricks.azure.us"].some(e=>t.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]?.endsWith(e)),Kf=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??(Wf(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)}`)},Jf=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 Xf{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 ft("@databricks/sql",r)})).DBSQLClient;if(this.#e)try{await e.connect(Kf(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 Wo(e,r)}dateBucket(e,r){if(!new Set(["second","minute","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(Jf)}),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 st(this,{...e,...r!==void 0?{database:r}:{},...n!==void 0?{schema:n}:{}})}async getTableList(e){e.signal?.throwIfAborted(),Rr(e);const r=u=>this.execute({sql:u,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[u]=await r("SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!u)throw new Error("Databricks current namespace was not returned");n??=xe(u,"table_database"),o??=xe(u,"table_schema")}const i=`${this.quoteIdentifier(n)}.${this.quoteIdentifier(o)}`,s=await r(`SHOW TABLES IN ${i}`),a=await r(`SHOW VIEWS IN ${i}`),c=new Map;for(const u of s){const p=xe(u,"tableName");c.set(p,{name:p,database:n,schema:o,type:"table"})}for(const u of a){const p=xe(u,"viewName");c.set(p,{name:p,database:n,schema:o,type:"view"})}return[...c.values()].sort((u,p)=>u.name.localeCompare(p.name))}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}const Fa=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}`)},Zf=t=>{const{host:e,port:r,...n}=t;return{...n,connectString:t.connectString??`${e??"localhost"}:${r??5236}`}};class em{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={...Zf(this.#e),poolAlias:typeof this.#e.poolAlias=="string"?this.#e.poolAlias:`semanticdb-${Nn.randomUUID()}`};if(this.#t)return this.#t.createPool(e);const{default:r}=await import("dmdb").catch(n=>{throw ft("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 xf(e,r.map(Fa))}dateBucket(e,r){if(r==="second")return`CAST(${e} AS DATE)`;const n={minute:"MI",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 Tt(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}describeTable(e){return st(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(Fa),{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 ie={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 jf(t,e)},dateBucket(t,e){const r={second:"%Y-%m-%d %H:%i:%s",minute:"%Y-%m-%d %H:%i:00",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,n){const o=this.quoteIdentifier(e),i=this.quoteIdentifier(r);return{joinSql:`CROSS JOIN JSON_TABLE(CASE WHEN JSON_TYPE(${t}) = 'ARRAY' THEN ${t} ELSE JSON_ARRAY() END, '$[*]' COLUMNS (${i} ${n==="string"?"VARCHAR(4000)":"JSON"} PATH '$')) AS ${o}`,valueExpression:`${o}.${i}`}}},tm={connectionLimit:30,maxIdle:10,idleTimeout:6e4,enableKeepAlive:!0,keepAliveInitialDelay:0};class gn{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 ft("mysql2",r)});return e({...tm,decimalNumbers:!0,...this.#e})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return ie.quoteIdentifier(e)}tableAlias(e,r){return ie.tableAlias(e,r)}paginate(e,r,n){return ie.paginate(e,r,n)}parameter(e,r){return ie.parameter(e,r)}displayQuery(e,r){return ie.displayQuery(e,r)}dateBucket(e,r){return ie.dateBucket(e,r)}datePart(e,r){return ie.datePart(e,r)}dateShift(e,r,n){return ie.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=ie.datePeriodBoundary?.bind(ie);if(!o)throw new Error("MySQL date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return ie.aggregateFunction(e,r)}stringify(e){return ie.stringify(e)}concat(e){return ie.concat(e)}substring(e,r,n){return ie.substring(e,r,n)}stringLength(e){return ie.stringLength(e)}regex(e,r,n){return ie.regex(e,r,n)}arrayContains(e,r){const n=ie.arrayContains?.bind(ie);if(!n)throw new Error("MySQL-compatible array conditions are unavailable");return n(e,r)}expandArray(e,r,n,o){const i=ie.expandArray?.bind(ie);if(!i)throw new Error("MySQL-compatible array expansion is unavailable");return i(e,r,n,o)}async execute(e){return(await this.#n(e,!1)).rows}async runSQL(e){return this.#n(e,!0)}getTableList(e){return Tt(this,e)}describeTable(e){return st(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 rm extends gn{kind="doris";constructor(e={}){super(e)}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}`}}}class nm extends gn{kind="gbase";supportsRecursiveCte=!1;constructor(e={}){super({...e,connection:{port:5258,...e.connection}})}}class om{kind="maxcompute";supportsRecursiveCte=!1;#e;#t=!1;constructor(e){this.#e=e.client}quoteIdentifier(e){return ie.quoteIdentifier(e)}tableAlias(e,r){return ie.tableAlias(e,r)}paginate(e,r,n){return ie.paginate(e,r,n)}parameter(e,r){return ie.parameter(e,r)}displayQuery(e,r){return ie.displayQuery(e,r)}dateBucket(e,r){return ie.dateBucket(e,r)}datePart(e,r){return ie.datePart(e,r)}dateShift(e,r,n){return ie.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=ie.datePeriodBoundary?.bind(ie);if(!o)throw new Error("MaxCompute date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return ie.aggregateFunction(e,r)}stringify(e){return ie.stringify(e)}concat(e){return ie.concat(e)}substring(e,r,n){return ie.substring(e,r,n)}stringLength(e){return ie.stringLength(e)}regex(e,r,n){return ie.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(),Rr(e),this.#e.getTableList){const n=await this.#e.getTableList(e);return e.signal?.throwIfAborted(),n}return e.database!==void 0&&Ve(this,"database"),e.schema!==void 0&&Ve(this,"schema"),(await this.execute({sql:"SHOW TABLES",parameters:[],...e.signal?{signal:e.signal}:{}})).map(n=>({name:xe(n,"table_name"),type:"table"}))}async close(){this.#t||(await this.#e.close(),this.#t=!0)}async describeTable(e){if(e.signal?.throwIfAborted(),Ko(e),!this.#e.describeTable)return st(this,e);const r=await this.#e.describeTable(e);return e.signal?.throwIfAborted(),r}}class im extends gn{kind="mysql";constructor(e={}){super(e)}}const Ha=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}`)},sm=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class am{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 qf(e,r.map(Ha))}dateBucket(e,r){if(r==="second")return`CAST(${e} AS DATE)`;const n={minute:"MI",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 ft("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 Tt(this,e)}describeTable(e){return st(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(Ha),{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?sm(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 cm{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{default:e}=await import("pg").catch(r=>{throw ft("pg",r)});return new e.Pool(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 kf(e,r)}dateBucket(e,r){if(!new Set(["second","minute","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})`}normalizeStringArray(e){const r=`to_jsonb(${e})`;return`(CASE WHEN ${e} IS NULL THEN ARRAY[]::text[] WHEN jsonb_typeof(${r}) = 'array' THEN ARRAY(SELECT jsonb_array_elements_text(${r})) ELSE ARRAY[${r} #>> '{}'] END)`}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 Tt(this,e)}describeTable(e){return st(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 Qa=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}`)},um=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class dm{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 ft("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 Wo(e,r.map(Qa))}dateBucket(e,r){if(!new Set(["second","minute","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 Tt(this,e)}describeTable(e){return st(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(Qa);return new Promise((i,s)=>{const a=e.signal,c={};let u=!1;const p=m=>{u||(u=!0,a?.removeEventListener("abort",l),m())},l=()=>{c.current?.cancel(),a&&p(()=>s(um(a)))};a?.addEventListener("abort",l,{once:!0}),c.current=n.execute({sqlText:e.sql,binds:o,complete:(m,f,h)=>{if(m){p(()=>s(m));return}if(!(r&&h===void 0)&&!Array.isArray(h)){p(()=>s(new Error("Snowflake provider expected an array result")));return}const y=r?f.getNumUpdatedRows?.():void 0;p(()=>i({rows:h??[],...typeof y=="number"&&y>=0?{affectedRows:y}:{}}))}}),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 pm=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}}},lm=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}`)},fm=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError"),mm=t=>t instanceof Error?t:new Error("SQL Server query failed",{cause:t}),ym=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 hm{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 ft("mssql",n)}),r=new e.ConnectionPool(pm(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`${ym(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 Bf(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 Tt(this,e)}describeTable(e){return st(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}`,lm(i))),new Promise((i,s)=>{const a=e.signal;let c=!1;const u=l=>{c||(c=!0,a?.removeEventListener("abort",p),l())},p=()=>{o.cancel(),a&&u(()=>s(fm(a)))};a?.addEventListener("abort",p,{once:!0}),o.query(e.sql).then(l=>{if(!Array.isArray(l.recordset)&&!(r&&l.recordset===void 0)){u(()=>s(new Error("SQL Server provider expected an array result")));return}u(()=>i({rows:l.recordset??[],...l.rowsAffected?{affectedRows:l.rowsAffected.reduce((m,f)=>m+f,0)}:{}}))},l=>u(()=>s(mm(l)))),a?.aborted&&p()})}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}class gm extends gn{kind="starrocks";constructor(e={}){super(e)}arrayContains(e,r){return`array_contains(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`, UNNEST(${e}) AS ${o}(${i})`,valueExpression:`${o}.${i}`}}}const Ye=t=>{const{id:e,kind:r,...n}=t;return n},Am=Object.freeze([{kind:"mysql",create:t=>new im({connection:Ye(t)})},{kind:"doris",create:t=>new rm({connection:Ye(t)})},{kind:"gbase",create:t=>new nm({connection:Ye(t)})},{kind:"starrocks",create:t=>new gm({connection:Ye(t)})},{kind:"maxcompute",create:t=>new om(Ye(t))},{kind:"postgresql",create:t=>new cm({connection:Ye(t)})},{kind:"clickhouse",create:t=>new zf(Ye(t))},{kind:"databricks",create:t=>new Xf({connection:Ye(t)})},{kind:"dameng",create:t=>new em({connection:Ye(t)})},{kind:"snowflake",create:t=>new dm({connection:Ye(t)})},{kind:"sqlserver",create:t=>new hm({connection:Ye(t)})},{kind:"oracle",create:t=>new am({connection:Ye(t)})}]);class va{#e=new Map;constructor(e=Am){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 Ga=new va,za=(t,e=Ga)=>e.create(t);class $m{create;#e=new Map;#t=new Set;#r=[];constructor(e=za){this.create=e}get(e){const r=this.#e.get(e.id);if(r&&pi.isDeepStrictEqual(r.connection,e))return r.provider;const n=this.create(e);return this.#e.set(e.id,{connection:{...e},provider:n}),r&&r.provider!==n&&this.#n(r.provider),n}#n(e){const r=Promise.resolve().then(()=>e.close()).then(()=>{this.#t.delete(r)},n=>{this.#t.delete(r),this.#r.push(n)});this.#t.add(r)}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()),...this.#t]),n=this.#r.splice(0);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 An=new Map,wm=t=>{const e=An.get(t);if(e)return e;const r=new $m(n=>za(n,t));return An.set(t,r),r},$n=(t,e=Ga)=>wm(e).get(t),Em=async()=>{const t=[...An.values()];An.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")},Wa=async()=>{const e=(await Promise.allSettled([Em(),gf()])).flatMap(r=>r.status==="rejected"?[r.reason]:[]);if(e.length>0)throw new AggregateError(e,"Failed to close one or more SemanticDB resources")},_m=async t=>{if(t.signal?.throwIfAborted(),!t.sql.trim())throw new d("INVALID_SQL","SQL must not be empty");const e=$n(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},Im=async t=>{t.signal?.throwIfAborted(),Rr(t);const e=$n(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},Sm=async t=>{t.signal?.throwIfAborted(),Ko(t);const e=$n(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},bm=Object.freeze({runSQL:_m,getTableList:Im,describeTable:Sm,close:Wa}),Rm=t=>{const{name:e,kind:r}=t;switch(r){case"boolean":return{name:e,kind:r,type:ge.BOOLEAN,sqlType:"BOOLEAN"};case"date":return{name:e,kind:r,type:ge.TIMESTAMP,sqlType:"TIMESTAMP"};case"number":return{name:e,kind:r,type:ge.DOUBLE,sqlType:"DOUBLE"};case"string":return{name:e,kind:r,type:ge.VARCHAR,sqlType:"VARCHAR"}}},Nm=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="true"?!0:t===0||t==="0"||t==="false"?!1:!!t,Om=(t,e)=>{if(t==null)return null;switch(e.kind){case"boolean":return ge.jsToDuckDBValue(Nm(t),ge.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:ge.jsToDuckDBValue(r,ge.TIMESTAMP)}case"number":{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?ge.jsToDuckDBValue(r,ge.DOUBLE):null}case"string":return typeof t=="string"?ge.jsToDuckDBValue(t,ge.VARCHAR):typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?ge.jsToDuckDBValue(t.toString(),ge.VARCHAR):typeof t=="symbol"?ge.jsToDuckDBValue(t.description??"",ge.VARCHAR):typeof t=="function"?ge.jsToDuckDBValue(t.name,ge.VARCHAR):ge.jsToDuckDBValue(JSON.stringify(t),ge.VARCHAR)}},Tm=t=>{if(t==null)return null;if(t instanceof Date)return ge.jsToDuckDBValue(t,ge.TIMESTAMP);if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"||typeof t=="string")return t;if(Buffer.isBuffer(t))return ge.blobValue(t);throw new TypeError(`Unsupported DuckDB coordinator parameter: ${typeof t}`)};class bn{instance;connection;kind="duckdb";supportsHavingAlias=!0;supportsRecursiveCte=!0;static async create(){const e=await ge.DuckDBInstance.create(":memory:"),r=await e.connect();return new bn(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 Wo(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(Rm),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 c of o){const u=Om(a[c.name],c);u===null?s.appendNull():s.appendValue(u,c.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(Tm));return e.signal?.throwIfAborted(),r.getRowObjectsJS()}close(){return this.connection.closeSync(),this.instance.closeSync(),Promise.resolve()}}const Xo="__sdb_total__",Pm="__sdb_total_source__",Zo=t=>{const e={...t,orderBy:[]};return delete e.pagination,e},Lm=t=>{const e={...t};return delete e.limit,delete e.page,e},ei=(t,e)=>({sql:`SELECT ${e.aggregateFunction("count")} AS ${e.quoteIdentifier(Xo)} FROM ${e.tableAlias(`(${t.sql})`,Pm)}`,parameters:t.parameters}),wn=t=>{if(t.length===0)return 0;const e=t[0]??{},r=e[Xo]??e[Xo.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},Nr="__semanticdb_coordinator__",Ka=(t,e)=>{const r=new Set;for(const n of Pe(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]},Or=(t,e)=>!!t.subplans&&new Set(t.subplans?.flatMap(r=>Ka(r,e))).size>1||!!(t.sourcePlan&&Or(t.sourcePlan,e)),Cm=(t,e)=>({name:t,expression:{kind:"column",property:t,column:t,qualifier:e}}),Dm=(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"},Ja=(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"?Dm(e,n):"string";return{name:n,kind:i}})},Mm=(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=>Cm(n,e)),...t.columnProperties?{columnProperties:t.columnProperties}:{},groupBy:[],orderBy:[],rowIdentity:{kind:"generated"}}},Um=(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",on(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")},Xa=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:sn(n,r.names,r.separator,r.nullLabel)}))}return e.rowIdentity.kind==="singleton"?t.map(r=>({...r,_id:"0"})):[...t]},En=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&&Or(t.sourcePlan,e.schemaMappings)){const s=await En(t.sourcePlan,e),a=await bn.create();try{const c="__federated_source";await a.materialize(c,Ja(t.sourcePlan,s.rows),s.rows);const u={...t,source:c};delete u.sourcePlan,delete u.sourceLogicform,delete u.connectionId;const p=we(u,a,e.operators),l=ei(we(Zo(u),a,e.operators),a),m=e.onCompiled({compiled:p,sources:[],connectionId:Nr,provider:a,type:"computation",logicform:e.logicform});e.onCompiled({compiled:l,sources:[],connectionId:Nr,provider:a,type:"total",logicform:e.logicform})("database");const h=await a.execute({...l,...e.signal?{signal:e.signal}:{}});m("database");const y=await a.execute({...p,...e.signal?{signal:e.signal}:{}});return{rows:Xa(y,t),total:wn(h),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=Ka(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 c=a[0],u=e.providerForConnection(c);r.set(c,u.kind);const p=we(s,u,e.operators),l=Pe(s),m=e.onCompiled({compiled:p,sources:l,connectionId:c,provider:u,type:"computation",logicform:e.logicform}),f=await vo(p,l,{provider:u,connectionId:c,schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},m),h=await Rt(f,s.projections,e.operators);return{child:s,rows:Um(h,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 bn.create();try{const s=n.flatMap(({rows:y})=>y),a=[];for(const[y,{child:$,rows:E}]of n.entries()){const A=`__federated_branch_${y}`;await i.materialize(A,Ja($,s),E),a.push(Mm($,A))}const c={...t,subplans:a},u=we(c,i,e.operators),p=ei(we(Zo(c),i,e.operators),i),l=e.onCompiled({compiled:u,sources:[],connectionId:Nr,provider:i,type:"computation",logicform:e.logicform});e.onCompiled({compiled:p,sources:[],connectionId:Nr,provider:i,type:"total",logicform:e.logicform})("database");const f=await i.execute({...p,...e.signal?{signal:e.signal}:{}});l("database");const h=await i.execute({...u,...e.signal?{signal:e.signal}:{}});return{rows:Xa(h,t),total:wn(f),connections:[...r].map(([y,$])=>({connectionId:y,provider:$}))}}finally{await i.close()}},Za=t=>{const e={...t};return delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,e},qm=new Set(["$gt","$gte","$lt","$lte"]),ti=t=>Object.entries(t).flatMap(([e,r])=>e==="$and"&&Array.isArray(r)?r.flatMap(n=>ti(n)):[{[e]:r}]),km=(t,e)=>{if(!t||!e||typeof t!="object"||typeof e!="object"||Array.isArray(t)||Array.isArray(e))return;const r=[t,e];if(r.some(o=>Object.keys(o).some(i=>!qm.has(i))))return;const n={};for(const o of["lower","upper"]){const i=o==="lower"?["$gt","$gte"]:["$lt","$lte"],s=r.flatMap(u=>i.flatMap(p=>u[p]===void 0?[]:[{key:p,value:u[p]}]));if(s.some(({value:u})=>typeof u!="string"&&!(u instanceof Date)))return;const c=s.reduce((u,p)=>{if(!u)return p;const l=u.value instanceof Date?u.value.toISOString():u.value,m=p.value instanceof Date?p.value.toISOString():p.value;return l===m?p.key===(o==="lower"?"$gt":"$lt")?p:u:o==="lower"?m>l?p:u:m<l?p:u},void 0);c&&(n[c.key]=c.value)}return n},ec=(t,e)=>{const r=[...t?ti(t):[],...ti(e)],n=[];for(const i of r){const[s]=Object.entries(i);if(!s)continue;const[a,c]=s,u=n.findIndex(p=>Object.keys(p).length===1&&a in p);if(u>=0){const p=n[u],l=km(p[a],c);if(l){n[u]={[a]:l};continue}}n.push(i)}if(n.length===1)return n[0];const o=n.map(i=>Object.keys(i)[0]);return new Set(o).size===o.length&&o.every(i=>i&&!i.startsWith("$"))?Object.assign({},...n):{$and:n}},tc=(t,e,r)=>{if(e.length===0)throw new d("INVALID_SCHEMA_PARTITION",`Schema ${t.id} partition returned no shards`);for(const[n,o]of e.entries()){const i=o,s=i?.query,a=i?.mappingCandidates;if(!i||typeof i!="object"||!s||typeof s!="object"||Array.isArray(s)||Object.keys(s).length===0||!Array.isArray(a)||a.length===0)throw new d("INVALID_SCHEMA_PARTITION",`Schema ${t.id} partition shard ${n} requires a query and mappingCandidates`);for(const c of o.mappingCandidates)if(typeof c!="string"||!r.findById(t.id,c))throw new d("INVALID_SCHEMA_PARTITION",`Schema ${t.id} partition shard ${n} references unknown mapping ${c}`)}},rc=t=>{if(!t.preds?.length||t.preds.some(e=>e.operator!=="$sum"))throw new d("UNSUPPORTED_SCHEMA_PARTITION_AGGREGATE","Schema partition currently supports only $sum PredItems")},ri=(t,e,r,n,o,i,s)=>{if(rc(t),s&&rc(s.logicform),t.limitBy!==void 0||s?.logicform.limitBy!==void 0)throw new d("UNSUPPORTED_SCHEMA_PARTITION_LIMIT_BY","Schema partition does not support limitBy");tc(e,r,o);const a=[],c=[],u=[];let p,l;for(const[y,$]of r.entries()){const E=ec(t.query,$.query),A={...t,query:E},g=s?{...s.logicform,query:s.queryForCurrentShard(E)}:void 0;let w;const L=[],I=[];for(const R of $.mappingCandidates){const N={...i,mappingCandidates:[R]};try{const D=Ce(Za(A),e,n,o,N),F=g?Ce(Za(g),e,n,o,N):void 0;w={mappingId:R,current:D,...F?{comparison:F}:{}};break}catch(D){if(!(D instanceof d)||D.code!=="QUERY_NOT_COVERED_BY_DATA_SOURCE")throw D;L.push(`${R}: ${JSON.stringify(D.details?.rejectedMappings??[])}`);const F=D.details?.uncoveredDimensions;I.push(Array.isArray(F)?F.filter(V=>typeof V=="string"):[])}}if(!w){const R=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id,N=I.length===$.mappingCandidates.length&&I.every(D=>D.length>0)?[...new Set(I.flat())]:[];throw new d("SCHEMA_PARTITION_MAPPING_NOT_FOUND",N.length>0?s?`Schema\u300C${R}\u300D\u7684\u7B2C${y+1}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u6570\u636E\u8868\u80FD\u540C\u65F6\u8986\u76D6\u672C\u671F\u548C\u5BF9\u6BD4\u671F\u6240\u9700\u7EF4\u5EA6\u3010${N.join("\u3001")}\u3011\u3002`:`Schema\u300C${R}\u300D\u7684\u7B2C${y+1}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u6570\u636E\u8868\u80FD\u5B8C\u6574\u8986\u76D6\u7EF4\u5EA6\u3010${N.join("\u3001")}\u3011\u3002`:s?`Schema\u300C${R}\u300D\u7684\u7B2C${y+1}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u540C\u65F6\u8986\u76D6\u672C\u671F\u548C\u5BF9\u6BD4\u671F\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002`:`Schema\u300C${R}\u300D\u7684\u7B2C${y+1}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u53EF\u7528\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002`,{schemaId:e.id,schemaLabel:R,shardIndex:y,...s?{comparison:!0}:{},...N.length>0?{uncoveredDimensions:N}:{},reasons:L})}const S={...i,mappingCandidates:[w.mappingId]};p??=Ce(A,e,n,o,S),g&&(l??=Ce(g,e,n,o,S)),a.push(w.current),w.comparison&&c.push(w.comparison),u.push(w.mappingId)}const m=p,f=a.length===1?m:{...m,subplans:a,sumPartition:!0},h=l?c.length===1?l:{...l,subplans:c,sumPartition:!0}:void 0;return{current:f,...h?{comparison:h}:{},mappingIds:u}},nc=(t,e)=>[...be(t).flatMap(r=>r.locales??[]),...e===void 0?[]:"locale"in e?[e]:e],_n=t=>({kind:"query",logicform:t.logicform,...t.prepare!==void 0?{prepare:t.prepare}:{},...t.mapResult?{mapResult:t.mapResult}:{},...t.groupKeyShifts?{groupKeyShifts:t.groupKeyShifts}:{},...t.partitionQuery?{partitionQuery:t.partitionQuery}:{}}),oc=t=>t instanceof Error?t:new Error(String(t)),jm=(t,e="zh-CN",r)=>t instanceof d?t.localizedMessage(e,r):t.message,xm=(t,e,r={},n="zh-CN",o)=>{const i=oc(t);return{errorCode:"100",error:jm(i,n,o),result:[],...r.schema?{schema:r.schema}:{},normedLogicform:r.normedLogicform??e,sqls:r.sqls??[],...r.lineage?{lineage:r.lineage}:{}}},Bm=(t,e,r)=>{const n=e.projections.map(({name:u})=>u),o=new Map((e.columnProperties??[]).map(u=>[u.name,u])),i=[],s=(u,p)=>{const l=r.parameter(i.length,p);i.push(p);const m=o.get(u)?.type;return m&&(m==="date"||m==="timestamp")&&r.castValue?r.castValue(l,m):l},a=u=>`SELECT ${n.map(p=>`${s(p,u[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(u=>`NULL AS ${r.quoteIdentifier(u)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""} WHERE 1 = 0`,parameters:i}},Vm=(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),...Pe(r)];for(const i of o){const s=_r(i,e);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},Ym=async(t,e,r)=>{await t?.({...e,partialResult:r})},Fm=(t,e,r,n,o,i,s=r,a,c=[])=>({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,schemaMappings:c,sql:t.sql,parameters:[...t.parameters],displaySql:e.displayQuery(t.sql,t.parameters)}),ni=(t,e)=>{if(e.connectionId)for(const r of Pe(t)){const n=_r(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})}},ic=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 oi(o))e.add(i)};return r(t),[...e]},oi=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...oi(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:oi(r))]:e},ii=async(t,e)=>{const r=e.locale??"zh-CN",n=e.localeRegistry??qr(nc(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&&Dp(t);const c=a?ws(t,e.schemas):t,u=e.schemaMappings.definitions(),p=ic(c),l=[...new Set(u.filter(({schemaId:_})=>p.includes(_)).map(({connectionId:_})=>_))],m=e.connectionId??(l.length===1?l[0]:void 0)??e.provider.kind,f=a?Ss(e.schemas,u,m,p):u,h=f.length===u.length?e.schemaMappings:new At(f,e.schemaMappings.plugins),y={...e,locale:r,localeRegistry:n,schemaMappings:h,schemas:Es(e.schemas,o,a)},$=Lr.performance.now(),E=y.semanticTypes===void 0?Xr(o):y.semanticTypesResolved?y.semanticTypes:Ps(y.semanticTypes,o);let A=y.operators??Qe(o);if(y.operators&&!y.operatorsResolved)for(const _ of o)for(const T of _.operators??[])if(A.has(T.name)){if(A.get(T.name)!==T)throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${T.name}`,{operator:T.name,plugin:_.name})}else A.register(T);const g=y.schemaMappings,w=_=>Pe(_).some(T=>Is(_r(T,g))),L=new Date,I=new Map,S=new Map;let R={};const N=[],D=new WeakMap,F=_=>{const T=new Map;for(const k of _){const U=_r(k,g);if(!U)continue;const B=U.id??U.source;T.set(JSON.stringify([U.schemaId,U.connectionId,B]),{schemaId:U.schemaId,mappingId:B,connectionId:U.connectionId,source:U.source})}return[...T.values()]},V=(_,T,k,U=T,B=y.provider,Y=y.connectionId,v)=>{const G=N.length;N.push(Fm(Ca(_),B,T,k,y.locale??"zh-CN",n,U,Y,F(v))),R={...R,sqls:[...N]};const z=W=>{N[G]={...N[G],executionSource:W},R={...R,sqls:[...N]}};return D.set(_,z),z},x=(_,T)=>vo(_,T,y,D.get(_)),M=async(_,T={})=>{R={...R,...T},await Ym(y.onProgress,_,R)},j=_=>mo(Li(_,y.schemas),E,o),K=new Map,H=_=>{const T=K.get(_);return T||(it(y.permissions,_),j(_))},re=_=>{if(_.schema)return H(_.schema);if(_.from)return re(_.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},ye=_=>{if(_.schema)return j(_.schema);if(_.from)return ye(_.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},Ue=async()=>{const _=Object.values(y.schemas).filter(W=>W.is_calendar===!0);if(_.length!==1)return Object.freeze({});const T=_[0];if(!T)return Object.freeze({});const k=g.list(T.id),U=k.find(({connectionId:W})=>W===y.connectionId)??k[0];if(!U)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${T.id}`,{schemaId:T.id});if(Is(U))return Object.freeze({calendar:Object.freeze([])});const B=y.providerForConnection?.(U.connectionId)??y.provider,{onProgress:Y,executionContext:v,...G}=y,z=await ii({version:"2.0",schema:T.id,limit:-1},{...G,provider:B,connectionId:U.connectionId,operators:A,operatorsResolved:!0,executionContext:Object.freeze({})});return N.push(...z.sqls.map(W=>({...W,type:"semantic-resolution",explain:n.translate(y.locale??"zh-CN","sql.semanticResolution")}))),Object.freeze({calendar:Object.freeze(z.result.map(({_id:W,...ee})=>Object.freeze(ee)))})},fe=e.executionContext??await Ue();A=A.withExecutionContext(fe);const Re=new Map,se={plugins:o,preplannedPartitions:Re,resolveSchema:H,...y.connectionId?{preferredConnectionId:y.connectionId}:{},canUsePropertyRowIdentity:(_,T)=>Nt(y.permissions,_.id,T)},Ne=async(_,T)=>{const k=await q(_,re(_));return Re.set(JSON.stringify(_),k),Ys(k,T)},b=async(_,T,k)=>{const U=`${_.id}:${T.id}:${k.toISOString()}`,B=I.get(U);if(B)return B;const Y=(async()=>{const v=be(o).find(_e=>_e.createTimeWatermarkLogicform)?.createTimeWatermarkLogicform;if(!v)return;const G=v({logicform:c,rootSchema:_,rootProperty:T,requestedUpperBound:k,now:L,...y.timeWatermark?{defaultPolicy:y.timeWatermark}:{},resolveSchema:H,inferPropertyPath:(_e,me,Ie)=>_a(_e,me,Ie,H)}),z=Ot(G,y.permissions,H,!1,new Set,o),W=await lt(z,_,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,resolveFromSchema:Ne}),ee=Ce(W,_,A,g,se);if(w(ee))return;let de;if(Or(ee,g)){const _e=y.providerForConnection;if(!_e)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated timeWatermark resolution requires a provider resolver");de=(await En(ee,{logicform:W,operators:A,schemaMappings:g,providerForConnection:_e,maxMaterializedRows:y.federation?.maxMaterializedRows??1e5,...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:({compiled:Ie,sources:Oe,logicform:he,provider:Be,connectionId:Ge})=>V(Ie,"semantic-resolution",he,"time-watermark",Be,Ge,Oe)})).rows}else{ni(ee,y);const _e=we(ee,y.provider,A),me=Pe(ee);V(_e,"semantic-resolution",W,"time-watermark",y.provider,y.connectionId,me),de=await x(_e,me)}const Ae=de[0]?.__timeWatermark__??Object.values(de[0]??{})[0];if(Ae==null||!(Ae instanceof Date)&&typeof Ae!="string"&&typeof Ae!="number")return;const Ee=Ae instanceof Date?Ae:new Date(Ae);return Number.isNaN(Ee.getTime())?void 0:Ee})();return I.set(U,Y),Y},O=async(_,T,k)=>{const U=JSON.stringify([_.id,T,k??null]),B=S.get(U);if(B)return B;const Y=(async()=>{const v={version:"2.0",schema:_.id,...k?{query:k}:{},preds:[{name:"__autoCaseMin__",operator:"$min",pred:T},{name:"__autoCaseMax__",operator:"$max",pred:T},{name:"__autoCaseCount__",operator:"$count",pred:T}]},G=await lt(v,_,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,resolveFromSchema:Ne}),z=Ce(G,_,A,g,se);if(w(z))return{empty:!0};let W;if(Or(z,g)){const Oe=y.providerForConnection;if(!Oe)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated automatic bucket resolution requires a provider resolver");W=(await En(z,{logicform:G,operators:A,schemaMappings:g,providerForConnection:Oe,maxMaterializedRows:y.federation?.maxMaterializedRows??1e5,...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:({compiled:Be,sources:Ge,logicform:Pt,provider:Fe,connectionId:He})=>V(Be,"semantic-resolution",Pt,"auto-case",Fe,He,Ge)})).rows}else{ni(z,y);const Oe=we(z,y.provider,A),he=Pe(z);V(Oe,"semantic-resolution",G,"auto-case",y.provider,y.connectionId,he),W=await x(Oe,he)}const ee=W[0],de=ee?.__autoCaseMin__,Ae=ee?.__autoCaseMax__,Ee=ee?.__autoCaseCount__;if(de==null||Ae===null||Ae===void 0||Ee===null||Ee===void 0||Number(Ee)===0)return{empty:!0};const _e=Number(de),me=Number(Ae),Ie=Number(Ee);if(!Number.isFinite(_e)||!Number.isFinite(me)||!Number.isSafeInteger(Ie)||Ie<0)throw new d("INVALID_AUTO_CASE_STATS","Automatic bucket statistics must contain finite min/max and a non-negative integer count",{min:de,max:Ae,count:Ee});return{min:_e,max:me,count:Ie}})();return S.set(U,Y),Y},C=async(_,T)=>{if(!T.partition||y.partitionDisabledSchemaIds?.includes(T.id)||!_.schema||_.from)return;if(y.partitionStack?.includes(T.id))throw new d("RECURSIVE_SCHEMA_PARTITION",`Schema ${T.id} partition called itself without a pinned mapping`);const k=[...y.partitionStack??[],T.id],U=await T.partition(_,{dayjs:le,moment:le,schemas:Object.fromEntries(Object.keys(y.schemas).map(Y=>[Y,j(Y)])),schemaMappings:g.definitions(),execute:async(Y,v)=>{const G=Y.schema,z=v?.mappingId;if(z&&!G)throw new d("PARTITION_MAPPING_SCHEMA_REQUIRED","A pinned partition query requires a physical Schema");const W=z&&G?g.findById(G,z):void 0;if(z&&!W)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${G}:${z}`);const ee=W?new At([...g.definitions().filter(({schemaId:Ie})=>Ie!==G),W],o):g,de=W?.connectionId??y.connectionId,Ae=W?y.providerForConnection?.(W.connectionId)??(W.connectionId===y.connectionId?y.provider:void 0):y.provider;if(!Ae)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED",`Pinned mapping ${z} requires a provider for ${de}`);const{onProgress:Ee,..._e}=y,me=await ii(Y,{..._e,schemaMappings:ee,provider:Ae,...de?{connectionId:de}:{},partitionStack:k,...G&&W?{partitionDisabledSchemaIds:[...y.partitionDisabledSchemaIds??[],G]}:{},operators:A,operatorsResolved:!0,semanticTypes:E,semanticTypesResolved:!0});return N.push(...me.sqls.map(Ie=>({...Ie,type:"semantic-resolution",explain:n.translate(r,"sql.semanticResolution")}))),R={...R,sqls:[...N]},me}}),B=U;if(typeof B!="object"||B===null||!Array.isArray(B.shards))throw new d("INVALID_SCHEMA_PARTITION",`Schema ${T.id} partition must return shards`);return tc(T,U.shards,g),Promise.all(U.shards.map(async Y=>{const v=await lt({version:_.version,schema:T.id,query:Y.query,preds:[]},T,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,resolveFromSchema:Ne,requestTimeWatermark:b,requestAutoCaseBounds:O});if(!v.query)throw new d("INVALID_SCHEMA_PARTITION",`Schema ${T.id} partition shard query normalized to empty`);return{...Y,query:v.query}}))},q=async(_,T,k)=>{const U=await C(_,T);if(!U)return Ce(_,T,A,g,se);if(_.preds?.every(({operator:v})=>v==="$sum"))return ri(_,T,U,A,g,se).current;if(!_.preds?.some(({operator:v})=>v&&A.get(v).kind==="component"))throw new d("UNSUPPORTED_SCHEMA_PARTITION_AGGREGATE","Schema partition currently supports only $sum PredItems");for(const v of U)for(const G of v.mappingCandidates){const z={..._,query:ec(_.query,v.query)};try{return Ce(z,T,A,g,{...se,mappingCandidates:[G]})}catch(W){if(!(W instanceof d)||W.code!=="QUERY_NOT_COVERED_BY_DATA_SOURCE")throw W;const ee=g.findById(T.id,G);if(!ee)continue;const de={...ee,...ee.mappings?{mappings:ee.mappings.map(({granularity:Ee,..._e})=>_e)}:{}},Ae=new At([...g.definitions().filter(({schemaId:Ee})=>Ee!==T.id),de],o);return Ce(z,T,A,Ae,{...se,mappingCandidates:[G]})}}const Y=T.name&&T.name!==T.id?`${T.name}(${T.id})`:T.id;throw new d("SCHEMA_PARTITION_MAPPING_NOT_FOUND",`Schema\u300C${Y}\u300D\u7684\u7EC4\u4EF6\u5206\u7247\u6CA1\u6709\u53EF\u7528\u7684\u6570\u636E\u6620\u5C04\u3002\u8BF7\u68C0\u67E5\u5019\u9009\u6620\u5C04\u662F\u5426\u8986\u76D6\u6240\u9700\u7EF4\u5EA6\u548C\u65F6\u95F4\u7C92\u5EA6\u3002`,{schemaId:T.id,schemaLabel:Y,component:!0})};try{y.signal?.throwIfAborted(),Uo(c),await M({stage:"started",logicform:c}),rf(y.permissions,j);const _=re(c);await M({stage:"validated",schema:_});const T=Ot(c,y.permissions,H,!0,new Set,o),k=await lt(T,_,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,resolveFromSchema:Ne,canProjectProperty:(P,Q)=>Nt(y.permissions,P.id,Q),requestTimeWatermark:b,requestAutoCaseBounds:O});await M({stage:"normalized",normedLogicform:k},{normedLogicform:k});const U=async P=>{if(Me(P)){await U(P.from),await U(P.query),await U(P.preds);const Q=JSON.stringify(P);!Re.has(Q)&&P.schema&&!P.from&&H(P.schema).partition&&Re.set(Q,await q(P,H(P.schema)));return}if(Array.isArray(P)){for(const Q of P)await U(Q);return}if(!(typeof P!="object"||P===null||P instanceof Date))for(const Q of Object.values(P))await U(Q)};await U(k.from),await U(k.query),await U(k.preds);const B=await q(k,_),Y=Or(B,g);Y||ni(B,y);const v=B.columnProperties??[],G=Vs(B,_);K.set(G.id,G),await M({stage:"planned",plan:B},{schema:G});const z=us(B,_,y.provider,A,y.providerForConnection);if(await M({stage:"lineage",lineage:z},{lineage:z}),a&&w(B)){const P=[];await M({stage:"compiled",sqls:[]},{sqls:[]}),await M({stage:"result",result:P},{result:P,total:0}),await M({stage:"completed",durationMs:Lr.performance.now()-$});const Q=k.output?Vn(k.output.type,o):void 0;return{result:P,total:0,schema:G,normedLogicform:k,sqls:[],lineage:z,...Q?{output:await Q.handle({rows:P,logicform:k,schema:G})}:{}}}if(Y){const P=y.providerForConnection;if(!P)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated execution requires a provider resolver for every physical connection");const Q=await En(B,{logicform:k,operators:A,schemaMappings:g,providerForConnection:P,maxMaterializedRows:y.federation?.maxMaterializedRows??1e5,...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:({compiled:Se,sources:pe,type:ce,logicform:De,provider:$e,connectionId:ze})=>V(Se,ce,De,ce,$e,ze,pe)});await M({stage:"compiled",sqls:[...N]},{sqls:[...N]}),await M({stage:"executing",provider:"duckdb",connectionId:Nr}),await M({stage:"hydrating"});const X=Q.connections.length===1?Q.connections[0]?.connectionId:void 0,J=await ka(Q.rows,v,{semanticTypes:E,plugins:o,resolveSchema:H,fetchEntities:Se=>Da(Se,{version:k.version,operators:A,schemaMappings:g,semanticTypes:E,plugins:o,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,...y.permissions?{permissions:y.permissions}:{},provider:y.provider,providerForConnection:P,...X?{preferredConnectionId:X}:{},...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:(pe,ce,De,$e,ze)=>V(pe,"semantic-resolution",ce,"entity-expansion",De,$e,ze)})}),ne=Po(J,B.rowIdentity);return await M({stage:"result",result:ne},{result:ne,total:Q.total,sqls:[...N]}),await M({stage:"completed",durationMs:Lr.performance.now()-$}),{result:ne,total:Q.total,schema:G,normedLogicform:k,sqls:[...N],lineage:z}}const W=an(k,B,_,A,H,void 0,r,n.translator(r)),ee=new WeakMap;for(const P of W??[]){if("logicform"in P&&P.partitionQuery&&P.partitionCurrentLogicform){const Q=re(P.partitionCurrentLogicform),X=await C(P.partitionCurrentLogicform,Q);if(X){const J=ri(P.partitionCurrentLogicform,Q,X,A,g,se,{logicform:P.logicform,queryForCurrentShard:P.partitionQuery});ee.set(P.logicform,J.comparison)}}if("components"in P)for(const Q of P.components){if(!Q.comparisonOf||!Q.partitionQuery)continue;const X=P.components.find(({name:pe})=>pe===Q.comparisonOf);if(!X)throw new d("INVALID_COMPONENT_COMPARISON",`Comparison component ${Q.name} has no current component ${Q.comparisonOf}`);const J=re(X.logicform),ne=await C(X.logicform,J);if(!ne)continue;const Se=ri(X.logicform,J,ne,A,g,se,{logicform:Q.logicform,queryForCurrentShard:Q.partitionQuery});ee.set(X.logicform,Se.current),ee.set(Q.logicform,Se.comparison)}}const de=async(P,Q)=>{const X=Q&&P.logicform.schema===Q.id?Q:re(P.logicform),J=P.prepare?await lt(Ot(P.logicform,y.permissions,H,!0,new Set,o),X,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,resolveFromSchema:Ne,canProjectProperty:(pe,ce)=>Nt(y.permissions,pe.id,ce),requestTimeWatermark:b}):P.logicform,ne=ee.get(P.logicform)??await q(J,X),Se=an(J,ne,X,A,H,P.logicform,r,n.translator(r));if(Se){if(Se.length!==1)throw new Error("A generated component must produce exactly one execution unit");const pe=Se[0];if("logicform"in pe){const $e=await de(pe,X),ze=$e.component.mapResult,Ze=P.mapResult;return{...$e,component:{...P,logicform:$e.component.logicform,...ze||Ze?{mapResult:et=>{const mt=ze?.(et)??[...et];return Ze?.(mt)??[...mt]}}:{}}}}if("mergeRow"in pe)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","A JavaScript composite metric cannot currently be nested as a generated component");const ce=await Promise.all(pe.components.map(async $e=>({name:$e.name,prepared:await de(_n($e)),...$e.groupKeyShifts?{groupKeyShifts:$e.groupKeyShifts}:{},...$e.joinKeys?{joinKeys:$e.joinKeys}:{}}))),De=nn(pe,ce.map(({name:$e,prepared:ze,...Ze})=>({name:$e,plan:ze.plan,...Ze})),ne,pe.outputName,y.provider,A);return{component:{...P,logicform:J},plan:ne,compiled:De,sources:Xt(ce.map(({prepared:$e})=>$e.sources))}}return{component:{...P,logicform:J},plan:ne,compiled:we(ne,y.provider,A),sources:Pe(ne)}},Ae=async(P,Q)=>{const X=an(P,Q,re(P),A,H,void 0,r,n.translator(r));if(!X)return{compiled:we(Q,y.provider,A),sources:Pe(Q)};const J=await Promise.all(X.map(async ne=>{if("logicform"in ne){const ce=await de(ne);return{plan:ce.plan,compiled:ce.compiled,outputs:ce.plan.projections.map(({name:De})=>De).filter(De=>!Q.groupBy.some($e=>$e.name===De))}}if("mergeRow"in ne)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const Se=await Promise.all(ne.components.map(async ce=>{const De=await de(_n(ce));return{name:ce.name,plan:De.plan,...ce.joinKeys?{joinKeys:ce.joinKeys}:{},...ce.groupKeyShifts?{groupKeyShifts:ce.groupKeyShifts}:{}}})),pe=nn(ne,Se,Q,ne.outputName,y.provider,A);return{plan:Q,compiled:pe,outputs:[ne.outputName,...ne.components.map(ce=>ce.name)]}}));return{compiled:No(J,Q,y.provider,A),sources:Xt(J.map(({plan:ne})=>Pe(ne)))}},Ee=new WeakMap,_e=async P=>{if(!P.sourcePlan||!P.sourceLogicform)return we(P,y.provider,A);const Q=ye(P.sourceLogicform),X=an(P.sourceLogicform,P.sourcePlan,Q,A,H,void 0,r,n.translator(r));if(X?.some(ce=>"mergeRow"in ce)){const ce=Ee.get(P.sourcePlan);if(ce){const ue={...P};delete ue.sourcePlan,delete ue.sourceLogicform;const at=we({...ue,sourceSql:ce.sql,source:P.source},y.provider,A,ce.parameters.length);return{sql:at.sql,parameters:[...ce.parameters,...at.parameters]}}const De=await Promise.all(X.map(async ue=>{if("logicform"in ue)return{kind:"query",unit:ue,prepared:await de(ue,Q)};const at=await Promise.all(ue.components.map(async Te=>({input:Te,prepared:await de(_n(Te),Q)})));return"mergeRow"in ue?{kind:"js",unit:ue,components:at}:{kind:"component",unit:ue,components:at,compiled:nn(ue,at.map(({input:Te,prepared:ke})=>({name:Te.name,plan:ke.plan,...Te.joinKeys?{joinKeys:Te.joinKeys}:{},...Te.groupKeyShifts?{groupKeyShifts:Te.groupKeyShifts}:{}})),P.sourcePlan,ue.outputName,y.provider,A)}})),$e=P.sourcePlan.groupBy.map(({name:ue})=>ue),ze=await Promise.all(De.map(async ue=>{if(ue.kind==="query"){V(ue.prepared.compiled,"computation",ue.prepared.component.logicform,"computation",y.provider,y.connectionId,ue.prepared.sources);const Te=await x(ue.prepared.compiled,ue.prepared.sources),ke=await Rt(Te,ue.prepared.plan.projections,A);return ue.unit.mapResult?.(ke)??ke}if(ue.kind==="component"){const Te=Xt(ue.components.map(({prepared:ke})=>ke.sources));return V(ue.compiled,"computation",P.sourceLogicform,"computation",y.provider,y.connectionId,Te),x(ue.compiled,Te)}const at=await Promise.all(ue.components.map(async({input:Te,prepared:ke})=>{V(ke.compiled,"computation",ke.component.logicform,"computation",y.provider,y.connectionId,ke.sources);const uc=await x(ke.compiled,ke.sources),ci=await Rt(uc,ke.plan.projections,A);return Te.mapResult?.(ci)??ci}));return Promise.all(Do(at,$e).map(async Te=>({...Te,[ue.unit.outputName]:await ue.unit.mergeRow(Te)})))})),Ze=Mo(ze,P.sourcePlan),et=y.federation?.maxMaterializedRows??1e5;if(!Number.isSafeInteger(et)||et<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:et});if(Ze.length>et)throw new d("MATERIALIZED_RESULT_LIMIT_EXCEEDED",`Nested component materialized ${Ze.length} rows; maximum is ${et}`,{materializedRowCount:Ze.length,maxMaterializedRows:et});const mt=Bm(Ze,P.sourcePlan,y.provider);Ee.set(P.sourcePlan,mt);const Rn={...P};delete Rn.sourcePlan,delete Rn.sourceLogicform;const ai=we({...Rn,sourceSql:mt.sql,source:P.source},y.provider,A,mt.parameters.length);return{sql:ai.sql,parameters:[...mt.parameters,...ai.parameters]}}const J=await Ae(P.sourceLogicform,P.sourcePlan),ne={...P};delete ne.sourcePlan,delete ne.sourceLogicform;const Se={...ne,sourceSql:J.compiled.sql,source:P.source},pe=we(Se,y.provider,A,J.compiled.parameters.length);return{sql:pe.sql,parameters:[...J.compiled.parameters,...pe.parameters]}},me=W?await Promise.all(W.map(async P=>{if("logicform"in P)return{kind:"query",unit:P,...await de(P)};const Q=await Promise.all(P.components.map(async J=>({name:J.name,prepared:await de(_n(J)),...J.groupKeyShifts?{groupKeyShifts:J.groupKeyShifts}:{},...J.joinKeys?{joinKeys:J.joinKeys}:{}})));if("mergeRow"in P)return{kind:"js",unit:P,components:Q.map(({prepared:J})=>J)};const X=Q.map(({name:J,prepared:ne,...Se})=>({name:J,plan:ne.plan,...Se}));return{kind:"component",unit:P,plan:B,compiled:nn(P,X,B,P.outputName,y.provider,A),sources:Xt(Q.map(({prepared:J})=>J.sources))}})):void 0,Ie=me&&Vm(me,g,B)?me.map(P=>{const Q=new Set(B.groupBy.map(({name:J})=>J));if(P.kind==="query")return{plan:P.plan,compiled:P.compiled,outputs:P.plan.projections.map(({name:J})=>J).filter(J=>!Q.has(J))};const X=P.unit.outputName;if(!X)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");return{plan:P.plan,compiled:P.compiled,outputs:[X,...P.unit.components.map(J=>J.name)]}}):void 0,Oe=Ie?No(Ie,B,y.provider,A):void 0,he=me?void 0:await _e(B),Be=Pe(B),Ge=B.sourcePlan&&Ee.has(B.sourcePlan)?[]:Be,Pt=Oe?Xt([...me.map(P=>P.sources),Be]):void 0,Fe=Oe?Xt([...me.map(P=>P.sources),Ge]):void 0,He=Zo(B),Lt=B.pagination&&(Oe||he)?ei(Ie?No(Ie,He,y.provider,A):await _e(He),y.provider):void 0;if(Oe)V(Oe,"computation",k,"computation",y.provider,y.connectionId,Fe);else if(me)for(const P of me)if(P.kind==="js")for(const Q of P.components)V(Q.compiled,"computation",Q.component.logicform,"computation",y.provider,y.connectionId,Q.sources);else V(P.compiled,"computation",k,"computation",y.provider,y.connectionId,P.sources);else V(he,"computation",k,"computation",y.provider,y.connectionId,Ge);Lt&&V(Lt,"total",Lm(k),"total",y.provider,y.connectionId,Fe??Ge),await M({stage:"compiled",sqls:[...N]},{sqls:[...N]}),await M({stage:"executing",provider:y.provider.kind});const sc=Oe?await(async()=>{const P=Pt,[Q,X]=await Promise.all([x(Oe,P),Lt?x(Lt,P):Promise.resolve(void 0)]),J=await Rt(Q,B.projections,A);return{rows:J,total:X?wn(X):J.length}})():me?await(async()=>{const P=await Promise.all(me.map(async X=>{if(X.kind==="js"){const Se=await Promise.all(X.components.map(async pe=>{const ce=await x(pe.compiled,pe.sources),De=await Rt(ce,pe.plan.projections,A);return pe.component.mapResult?.(De)??De}));return Promise.all(Do(Se,B.groupBy.map(({name:pe})=>pe)).map(async pe=>{const ce=await X.unit.mergeRow(pe);return{...pe,[X.unit.outputName]:ce}}))}const J=await x(X.compiled,X.sources),ne=X.kind==="query"?await Rt(J,X.plan.projections,A):J;return X.kind==="query"?X.unit.mapResult?.(ne)??ne:ne})),Q=Mo(P,B);return{rows:Q,total:B.pagination?Mo(P,He).length:Q.length}})():await(async()=>{const P=Be,[Q,X]=await Promise.all([x(he,P),Lt?x(Lt,P):Promise.resolve(void 0)]),J=await Rt(Q,B.projections,A);return{rows:J,total:X?wn(X):J.length}})(),{rows:ac,total:si}=sc;await M({stage:"hydrating"});const cc=await ka(ac,v,{semanticTypes:E,plugins:o,resolveSchema:H,fetchEntities:P=>Da(P,{version:k.version,operators:A,schemaMappings:g,semanticTypes:E,plugins:o,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,...y.permissions?{permissions:y.permissions}:{},provider:y.provider,...y.connectionId?{preferredConnectionId:y.connectionId}:{},...y.providerForConnection?{providerForConnection:y.providerForConnection}:{},...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:(Q,X,J,ne,Se)=>V(Q,"semantic-resolution",X,"entity-expansion",J,ne,Se)})}),Pr=Po(cc,B.rowIdentity);return await M({stage:"result",result:Pr},{result:Pr,total:si,sqls:[...N]}),await M({stage:"completed",durationMs:Lr.performance.now()-$}),{result:Pr,total:si,schema:G,normedLogicform:k,sqls:[...N],lineage:z,...k.output?await(async()=>{const P=Vn(k.output?.type??"",o);return P?{output:await P.handle({rows:Pr,logicform:k,schema:G})}:{}})():{}}}catch(_){const T=oc(_);try{await M({stage:"failed",error:T})}catch{}throw T}},Hm=async(t,e)=>{let r={};const n=e.locale??"zh-CN",o=qr(nc(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 N of e.connections){if(N.id.trim().length===0)throw new d("INVALID_DATABASE_CONNECTION","Database connection id must not be empty");if(i.has(N.id))throw new d("DATABASE_CONNECTION_ALREADY_REGISTERED",`Database connection id is duplicated: ${N.id}`,{connectionId:N.id});i.set(N.id,N)}const s=ic(t),a=t.version,c=a===void 0||typeof a=="string"&&/^1\./.test(a),u=[...new Set(e.schemaMappings.filter(({schemaId:N})=>s.includes(N)).map(({connectionId:N})=>N))],p=e.connections.length===1?e.connections[0]?.id:u.length===1?u[0]:void 0,l=c?Ss(e.schemas,e.schemaMappings,p,s,e.connections.map(({id:N})=>N)):e.schemaMappings,m=new At(l,e.plugins),f=s.flatMap(N=>m.list(N)).map(({connectionId:N})=>N)[0];if(!f)throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain at least one physical Schema leaf");const h=N=>{const D=i.get(N);if(!D)throw new d("DATABASE_CONNECTION_NOT_FOUND",`Database connection is not registered: ${N}`,{connectionId:N});return $n(D,e.providerRegistry)},y=h(f),$=Qe(e.plugins),E=e.operators===void 0?[]:Array.isArray(e.operators)?e.operators:[e.operators],A=new er(E),g=new Set(A.definitions().map(({name:N})=>N)),w=E.length===0?$:new er([...$.definitions().filter(({name:N})=>!g.has(N)),...A.definitions()]),L=e.semanticTypes===void 0?Xr(e.plugins):Ps(e.semanticTypes,e.plugins??[]),{cache:I,...S}=e,R=I?await Pa(I):void 0;return await ii(t,{...S,schemaMappings:m,locale:n,localeRegistry:o,provider:y,providerForConnection:h,operators:w,operatorsResolved:!0,semanticTypes:L,semanticTypesResolved:!0,connectionId:f,...R?{cache:R}:{},onProgress:async N=>{r=N.partialResult,await e.onProgress?.(N)}})}catch(i){return xm(i,t,r,n,o)}},Qm=Object.freeze({execute:Hm,close:Wa});exports.DBConnector=bm,exports.LocaleRegistry=Cn,exports.Logicform=Qm,exports.OperatorRegistry=er,exports.PlannerSemanticRegistry=Ds,exports.ProviderRegistry=va,exports.QueryCacheManager=$f,exports.SchemaMappingRegistry=At,exports.SemanticDBError=d,exports.SemanticTypeRegistry=fo,exports.builtinOperators=$p,exports.builtinSemanticTypes=ao,exports.createLocaleRegistry=qr,exports.createOperatorRegistry=Qe,exports.createPlannerSemanticRegistry=Ms,exports.createSemanticTypeRegistry=Xr,exports.defaultLocaleRegistry=kr,exports.enUS=Ti,exports.fromYiAskSchemaMapping=Xp,exports.getLogicformPropertyReferences=dr,exports.getSupportedDimensions=Kp,exports.isDimensionInLogicform=xp,exports.resolveOperator=is,exports.resolveSchema=mo,exports.validateResolvedSchema=bs,exports.zhCN=Pi;
|