semanticdb-v2 2.0.0-alpha.11 → 2.0.0-alpha.12
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/README.md +39 -15
- package/dist/cache/types.d.ts +2 -1
- package/dist/compiler/compile-computation.d.ts +6 -0
- package/dist/compiler/compile-source.d.ts +5 -0
- package/dist/executor/component-properties.d.ts +22 -0
- package/dist/executor/components.d.ts +7 -3
- package/dist/executor/execute-query.d.ts +1 -0
- package/dist/executor/merge-by-id.d.ts +3 -0
- package/dist/executor/partition.d.ts +1 -0
- package/dist/executor/random-data.d.ts +5 -0
- package/dist/executor/result-hydrator/entity-fetch-conditions.d.ts +4 -0
- package/dist/executor/result-hydrator/index.d.ts +1 -0
- package/dist/executor/result-hydrator/types.d.ts +7 -0
- package/dist/executor/runtime-execution.d.ts +6 -0
- package/dist/executor/sample.d.ts +6 -0
- package/dist/executor/types.d.ts +9 -3
- package/dist/file-import/index.d.ts +2 -0
- package/dist/file-import/read-file.d.ts +2 -0
- package/dist/file-import/types.d.ts +31 -0
- package/dist/index.d.ts +8 -5
- package/dist/logicform-types.d.ts +22 -2
- package/dist/normalizer/core.d.ts +7 -0
- package/dist/normalizer/index.d.ts +1 -0
- package/dist/normalizer/main-time-range.d.ts +9 -0
- package/dist/normalizer/public-logicform.d.ts +14 -0
- package/dist/normalizer/query.d.ts +3 -2
- package/dist/normalizer/random-data.d.ts +2 -0
- package/dist/operators/builtins/period-name.d.ts +3 -0
- package/dist/operators/builtins/time-range.d.ts +2 -2
- package/dist/operators/formula-text.d.ts +10 -0
- package/dist/operators/index.d.ts +2 -1
- package/dist/operators/registry.d.ts +8 -1
- package/dist/operators/types.d.ts +107 -24
- package/dist/permissions/index.d.ts +2 -1
- package/dist/permissions/metric-permissions.d.ts +9 -0
- package/dist/permissions/permissions.d.ts +4 -3
- package/dist/permissions/types.d.ts +5 -0
- package/dist/physical/connection.d.ts +4 -0
- package/dist/physical/db-connector.d.ts +10 -0
- package/dist/physical/duckdb-coordinator-provider.d.ts +3 -23
- package/dist/physical/duckdb-dataset.d.ts +23 -0
- package/dist/physical/duckdb-provider.d.ts +26 -0
- package/dist/physical/duckdb-sql.d.ts +33 -0
- package/dist/physical/import-types.d.ts +23 -0
- package/dist/physical/import-validation.d.ts +14 -0
- package/dist/physical/index.d.ts +4 -0
- package/dist/physical/postgresql-provider.d.ts +1 -0
- package/dist/physical/provider.d.ts +4 -0
- package/dist/planner/build-lineage.d.ts +1 -1
- package/dist/planner/create-logical-plan.d.ts +11 -2
- package/dist/planner/index.d.ts +3 -2
- package/dist/planner/mapping-granularity.d.ts +1 -1
- package/dist/planner/materialize-computations.d.ts +3 -0
- package/dist/planner/select-schema-mapping.d.ts +15 -3
- package/dist/planner/types.d.ts +40 -9
- package/dist/planner/udf-inputs.d.ts +6 -0
- package/dist/plugins/types.d.ts +4 -2
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/relation-keys.d.ts +11 -0
- package/dist/schema-mappings/computations.d.ts +3 -0
- package/dist/schema-mappings/index.d.ts +4 -1
- package/dist/schema-mappings/source.d.ts +11 -0
- package/dist/schema-mappings/sql-inputs.d.ts +7 -0
- package/dist/schema-mappings/types.d.ts +103 -17
- package/dist/schema-mappings/yiask.d.ts +6 -19
- package/dist/semantic-types/types.d.ts +21 -1
- package/dist/semanticdb.esm.js +6 -5
- package/dist/semanticdb.js +6 -5
- package/dist/utils/format-date.d.ts +3 -0
- package/package.json +5 -3
- package/dist/executor/evaluate.d.ts +0 -4
- package/dist/planner/build-mapping-source-plan.d.ts +0 -6
package/dist/semanticdb.esm.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import{performance as Lr}from"node:perf_hooks";import le from"dayjs";import tr from"dayjs/plugin/isoWeek.js";import Cr from"dayjs/plugin/quarterOfYear.js";import ui from"dayjs/plugin/customParseFormat.js";import{randomUUID as di,createHash as lc}from"node:crypto";import{isDeepStrictEqual as pi}from"node:util";import{createClient as fc}from"redis";import{getNameProperty as mc}from"semanticdb-core";import{DuckDBInstance as yc,VARCHAR as Lt,DOUBLE as li,TIMESTAMP as Nn,BOOLEAN as fi,jsToDuckDBValue as et,blobValue as hc}from"@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},mi=t=>t==null?"":""+t,gc=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},Ac=/###/g,yi=t=>t&&t.indexOf("###")>-1?t.replace(Ac,"."):t,hi=t=>!t||Z(t),nr=(t,e,r)=>{const n=Z(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if(hi(t))return{};const i=yi(n[o]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++o}return hi(t)?{}:{obj:t,k:yi(n[o])}},gi=(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},$c=(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]},wc=(t,e,r)=>{const n=Dr(t,r);return n!==void 0?n:Dr(e,r)},Ai=(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]):Ai(t[n],e[n],r):t[n]=e[n]);return t},mt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Ec={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const _c=t=>Z(t)?t.replace(/[&<>"'\/]/g,e=>Ec[e]):t;class Ic{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 Sc=[" ",",","?","!",";"],bc=new Ic(20),Rc=(t,e,r)=>{e=e||"",r=r||"";const n=Sc.filter(s=>e.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=bc.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,"-"),Nc={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||Nc,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 ze=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 $i 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),gi(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?Ai(c,n,i):c={...c,...n},gi(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 wi={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 Oc(){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 Ct(t,e){const{[Ei]:r}=t(Oc()),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 _i={},Tn=t=>!Z(t)&&typeof t!="boolean"&&typeof t!="number";class Sn extends Mr{constructor(e,r={}){super(),gc(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=ze.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&&!Rc(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 Q=`${j}${s}${K}`;L&&!h?M[K]=this.translate(Q,{...o,defaultValue:Tn(N)?N[K]:void 0,joinArrays:!1,ns:c}):M[K]=this.translate(Q,{...o,joinArrays:!1,ns:c}),M[K]===Q&&(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,Q=L&&N!==h&&this.options.updateMissing;if(M||x||Q){if(this.logger.log(Q?"updateKey":"missingKey",l,u,a,Q?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 Me=(fe,be,se)=>{const Re=L&&se!==h?se:K;this.options.missingKeyHandler?this.options.missingKeyHandler(fe,u,be,Re,Q,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(fe,u,be,Re,Q,o),this.emit("missingKey",fe,u,be,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&w?re.forEach(fe=>{const be=this.pluralResolver.getSuffixes(fe,o);R&&o[`defaultValue${this.options.pluralSeparator}zero`]&&be.indexOf(`${this.options.pluralSeparator}zero`)<0&&be.push(`${this.options.pluralSeparator}zero`),be.forEach(se=>{Me([fe],a+se,o[`defaultValue${se}`]||N)})}):Me(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=wi.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=$,!_i[`${y[0]}-${$}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(_i[`${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 Ii{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=ze.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 Si={zero:0,one:1,two:2,few:3,many:4,other:5},bi={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Tc{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=ze.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!"),bi;if(!e.match(/-|_/))return bi;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)=>Si[o]-Si[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 Ri=(t,e,r,n=".",o=!0)=>{let i=wc(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 Ni{constructor(e={}){this.logger=ze.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:_c,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=i?mt(i):s||"{{",this.suffix=a?mt(a):c||"}}",this.formatSeparator=u||",",this.unescapePrefix=p?"":l||"-",this.unescapeSuffix=this.unescapePrefix?"":p||"",this.nestingPrefix=m?mt(m):f||mt("$t("),this.nestingSuffix=h?mt(h):y||mt(")"),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=Ri(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(Ri(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=mi(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(`${mt(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=mi(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 Pc=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}},Oi=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)}},Lc=t=>(e,r,n)=>t(or(r),n)(e);class Cc{constructor(e={}){this.logger=ze.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?Oi:Lc;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()]=Oi(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}=Pc(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 Dc=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Mc 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=ze.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=>{$c(c.loaded,[i],s),Dc(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}),Ti=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=()=>{},Uc=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})},Pi="__i18next_supportNoticeShown",qc=()=>!!(typeof globalThis<"u"&&globalThis[Pi]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),kc=()=>{typeof globalThis<"u"&&(globalThis[Pi]=!0)},jc=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=Ti(e),this.services={},this.logger=ze,this.modules={external:[]},Uc(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,...Ti(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&&!jc(this)&&!qc()&&(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}"),kc());const o=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?ze.init(o(this.modules.logger),this.options):ze.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=Cc;const p=new Ii(this.options);this.store=new $i(this.options.resources,this.options);const l=this.services;l.logger=ze,l.resourceStore=this.store,l.languageUtils=p,l.pluralResolver=new Tc(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 Ni(this.options),l.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},l.backendConnector=new Mc(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"&&wi.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 Ii(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 $i(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 Ni(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 Ue=Tr.createInstance(),xc=Ue.createInstance;Ue.dir,Ue.init,Ue.loadResources,Ue.reloadResources,Ue.use,Ue.changeLanguage,Ue.getFixedT,Ue.t,Ue.exists,Ue.setDefaultNamespace,Ue.hasLoadedNamespace,Ue.loadNamespaces,Ue.loadLanguages;const Li={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"}},Ci={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"}},Bc=[Ci,Li],ir=t=>t.trim().toLowerCase(),Vc=t=>t?"locale"in t?[t]:t:[],Yc=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=xc(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(Bc),this.register(e)}register(e){for(const r of Vc(e)){const n=r;if(!Yc(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 Fc=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})},Hc=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})},vc=(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}:{}}},Gc={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"||!Fc.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:Hc,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 vc(t,r,n)},getOutputProperty({name:t,inputProperty:e}){return e?{...e,name:t,isArray:!1}:{name:t,type:"number",primal_type:"number",isArray:!1}}},zc={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}),Wc={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),Di=(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},Kc=(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},Jc=t=>{const e=t.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(e))},Mi=(t,e)=>t.properties.some(r=>r!==e&&r.id===e.name)?e.id:e.name,Xc=(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:Mi(t,n),canonicalId:n.id,schema:t,property:n,relations:[]};for(const{property:o,prefix:i}of Xc(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:`${Mi(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,Zc=(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},Ui=(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 Zc(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})},eu=({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}}},tu=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},ru=(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}},nu={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=ru(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)),qi=(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}`},ou=(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=qi(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=qi(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}`}}},iu={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:ou,supportsGroupby:t=>t.operator==="$hierarchyLevel"},su={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}}}},au=Object.freeze({name:"hierarchy",schemaMetadata:su,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:eu,resolveEntityFilterProperty:tu,operators:[nu],mappingGranularity:iu}),cu=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp"),kn="$periodValue",uu=(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}},du={name:"observation",resolveProjection({pred:t,schema:e,sourceProperty:r,outputProperty:n,operator:o,executionContext:i}){if(!r||!cu(r,e))return;const s=uu(t,o,i);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:s.boundary,sourceProperty:r.name}}}}},pu=new Set(["second","minute","hour","day","week","month","quarter","year"]),ki=t=>typeof t=="string"&&pu.has(t),lu=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},yt=(t,e=2)=>String(t).padStart(e,"0"),jn=t=>`${yt(t.getFullYear(),4)}-${yt(t.getMonth()+1)}-${yt(t.getDate())} ${yt(t.getHours())}:${yt(t.getMinutes())}:${yt(t.getSeconds())}.`+yt(t.getMilliseconds(),3),fu=(t,e)=>{if(!lu(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}},mu=(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},yu=(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},ji=(t,e,r)=>{const{lower:n,upper:o}=fu(t,r),i=[];let s=mu(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=yu(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},hu=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.name),gu=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.name)),Au=(t,e)=>{if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:l})=>l==="timestamp");if(!r)return;const n=hu(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"||!ki(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:ji(p,s,{codePrefix:"OBSERVATION",label:"Observation"}).map(l=>({label:l.label,asOf:l[u]}))}},xi=["second","minute","hour","day","week","month","quarter","year"],$u=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:[du],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(xi.indexOf(o)>xi.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=Au(t,e);if(r)return{group:r.group,property:r.timestamp,periods:r.periods,source:{kind:"latest",timestamp:r.timestamp},rewriteQuery:n=>gu(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,wu={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}`}},Eu=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:[wu]});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},Bi=(t,e)=>le(t).endOf(e==="week"?"isoWeek":e).toDate(),Bn=t=>le(t).format("YYYY-MM-DD HH:mm:ss"),_u=(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})},Vi=(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})},Iu=Object.freeze({name:"temporal",schemaMetadata:{keys:["timeWatermark"],resolve(t){return Vi(t.timeWatermark,`Schema ${t.id}`),{...t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}}},propertyMetadata:{keys:["timeWatermark"],resolve(t,e){if(Vi(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=_u(m.timeWatermark??l.timeWatermark??i,`${l.id}.${m.id}`);if(f.type==="now_offset"){const h=Bi(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(Bi(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},Yi=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.timestamp.name),Su=(t,e)=>Yi(t,e)!==void 0,bu=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.timestamp.name)),Ru=(t,e)=>{const r=Yi(t,e);if(!r)return;const n=r.args?.granularity;if(r.operator!=="$dateBucket"||!ki(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:ji(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,Fi=(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=>Fi(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}]}}},Qi=(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&&Qi(o,e)))),Tu={name:"validity",resolveQuery({logicform:t,schema:e,query:r}){const n=ar(e);if(!n)return r;if(Su(t,n))return bu(r,n);const i=Qi(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:new Date().toISOString()}};return Fi(i,n)},resolveProjection({schema:t,outputProperty:e}){if(ar(t))return{outputProperty:{...e,temporal:{kind:"validity"}}}}},Pu={name:"start_date",primalType:"date"},Lu={name:"end_date",primalType:"date"},Cu=Object.freeze({name:"validity",semanticTypes:[Pu,Lu],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:[Tu],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=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}}}),Hi=(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},Du=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=Hi(t,o,a.up,"up"),p=Hi(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([au,Eu,Iu,$u,Cu,Du]),Se=(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=[])=>Se(e).flatMap(r=>r.queryOperators??[]).find(r=>r.name===t),Vn=(t,e=[])=>Se(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",Se(e).flatMap(r=>{const n=r.intervalSemantics?.resolve(t);return n?[{plugin:r.name,value:n}]:[]})),Mu=(t,e,r=[])=>Yn("relation semantics",Se(r).flatMap(n=>{const o=n.relationSemantics?.plan({sourceSchema:t,targetSchema:e});return o?[{plugin:n.name,value:o}]:[]})),Uu=(t,e,r=[])=>Yn("planner period semantics",Se(r).flatMap(n=>{const o=n.plannerPeriod?.resolve(t,e);return o?[{plugin:n.name,value:o}]:[]})),Qn=t=>typeof t=="string"&&t.length>0&&t!=="placeholder"||typeof t=="number"&&Number.isSafeInteger(t),qu=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]},Hn=(t,e=[])=>{for(const r of Se(e)){const n=r.resolveEntityFilterProperty?.(t);if(n)return n}return qu(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,ku=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ju={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},xu={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(!ku(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}${ju[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${xu[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};le.extend(tr),le.extend(Cr);const Bu=["second","minute","hour","day","week","month","quarter","year"],Vu=new Set(Bu),Wn=["year","quarter","month","week","day","hour","minute","second"],vi=t=>Object.prototype.toString.call(t)==="[object Object]",ct=t=>{throw new d("INVALID_PERIOD_SHIFT_ARGS",t)},Yu=t=>{const e=t.time;vi(e)||ct("$periodShift requires args.time");const r=e;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!Vu.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&ct("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)))&&ct("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&ct("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)&&ct(`Invalid absolute period shift ${a}: ${JSON.stringify(p)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&ct("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&ct("Absolute period shift day requires month"),r},Gi=(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),Fu=(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=Gi(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(vi(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=Fu(n,e);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,Kn(t,o)},zi=(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},ht=t=>{const e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?e[0]:{$and:e}},ut=t=>[...t.query?[t.query]:[],...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?ut(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(r=>typeof r=="string"?[]:ut(r)):[]],Hu=(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=Gi(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))&&ct("$periodShift pred must be a nested metric");const s=Yu(e.args??{}),a={shiftedValues:0},c=ht([t.query,...ut(e)]);if(!c)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const u=zi(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=>zi(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[$]=Hu(y[$],s,a);return y})}},vu={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}}},Gu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Qr=t=>typeof t=="string"||typeof t=="number"||t instanceof Date,Wi=(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},Ki=(t,e)=>{if(Qr(t)){e.start??=t,e.end??=t;return}if(!Gu(t))return;const r=t.$eq;Qr(r)&&(e.start??=r,e.end??=r);const n=t.$gte??t.$gt,o=t.$lte??t.$lt;Qr(n)&&(e.start??=n),Qr(o)&&(e.end??=o);for(const i of["$and","$or"]){const s=t[i];if(Array.isArray(s))for(const a of s)Ki(a,e)}},zu=(t,e,r,n)=>{const o=Wi(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),Ki(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}:{}}},Ji=(t,e,r,n,o)=>{const i=ht([t,...ut(e)]);if(!i)throw new d("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return zu(i,r,n,o)},Xi=(t,e,r)=>ht([t,{[e]:r}]),Wu=new Set(["day","week","month","quarter","year"]),Ku={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Ju=t=>{if(typeof t!="string"||!Wu.has(t))throw new d("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return t},Zi=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},Xu={name:"$averagePerPeriod",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${t} per ${typeof e.granularity=="string"?e.granularity:"period"}`:`${t}${Ku[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=Ju(e.args?.granularity),s=Wi(r,"$averagePerPeriod"),a=Zn(e.pred),c=ht([t.query,...ut(e)]),u=Zi(t);u.preds=[{...a,name:"__avg_period_num__"}],c&&(u.query=c);const p=Zi(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}}},Zu={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)},ed=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}},td=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},Hr=t=>{const e=Number(t.toPrecision(15));return Object.is(e,-0)?0:e},eo=t=>String(Hr(t)),rd=(t,e,r)=>{if(t===e)return[t,e];const n=td((e-t)/r),o=Hr(Math.floor(t/n)*n),i=Hr(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:Hr(o+n*c))},nd=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}})},od={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=ed(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=rd(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=nd(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}}},id={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}}},sd={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}}},ad={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}}},cd=new Set(["second","minute","hour","day","week","month","quarter","year"]),ud={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},es=t=>{if(typeof t!="string"||!cd.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},dd={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${ud[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,es(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=es(r.granularity);return{...e,name:t,type:"date",primal_type:"date",isArray:!1,granularity:n}}},pd={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)}},ld=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}}}},fd={name:"$max",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Maximum ${t}`:`${t}\u6700\u5927\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:ld,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}:{}}}},md=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}}}},yd={name:"$min",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Minimum ${t}`:`${t}\u6700\u5C0F\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:md,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}:{}}}},hd={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)}},gd=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},Ad={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=Ji(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=gd(t);return f.query=Xi(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}}},$d=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},wd={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=Ji(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=$d(t);return u.query=Xi(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}}},Ed=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},_d=({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=Ed(t);c.preds=[a];const u=ht([t.query,...ut(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}`}},Id={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:_d,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodDifference requires a nested metric");return{...e,name:t,isArray:!1}}},Sd=t=>{const e=ae(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},bd=({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=Sd(t);c.preds=[a];const u=ht([t.query,...ut(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`}},Rd={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:bd,getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},Nd={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}}},Od={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)}},ts=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},Td={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=ts(t);u.preds=[{...c,name:"__share_numerator__"}];const p=ht([t.query,...ut(e)]);p&&(u.query=p);const l=ts(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}}},Pd={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}}},rs=(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},Ld=new Set(["boolean","date","number","entity","object","string"]),Cd=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||!Ld.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}:{}}},Md={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 rs(t.sql,Cd(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)}},Ud=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]},qd=t=>typeof t.pred!="string"?t:{...t,pred:{operator:"$sum",pred:t.pred,name:`${t.pred}\u5408\u8BA1`}},kd=(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=Ud(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,qd(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},jd={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?kd(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}}},xd={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}}},Bd=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"&&Bd.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")},Vd={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}}},Yd={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}}},ns="__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]}},Fd=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?.[ns]===!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=Fd(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,[ns]:!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}:{}}},Hd=(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)`},vd=(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}},os=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)??Hd(t,r)},getOutputProperty({name:e,inputProperties:r}){return vd(t,e,r)}}),Gd=os("$least"),zd=os("$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"}},Wd={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}}},Kd=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}}}),Jd=Object.freeze(Object.keys(so).map(Kd)),is=Object.freeze([Gc,Nd,sd,ad,Zu,yd,fd,vu,Rd,Id,Xu,wd,Ad,Wc,Od,hd,pd,zc,Td,od,id,Pd,dd,Md,jd,xd,Vd,Yd,Gd,zd,Wd,...Jd]),Xd={name:"boolean",primalType:"boolean",hydrateResult(t){return typeof t=="number"?t===1:t}},Zd={name:"category",primalType:"string"},ep={name:"currency",primalType:"number"},tp={name:"date",primalType:"date"},rp={name:"duration",primalType:"number"},ss=(t,{property:e,requestEntity:r})=>!e.ref||t===void 0||t===null||typeof t=="object"&&!Array.isArray(t)?t:r(e.ref,t),np={name:"object",primalType:"object",hydrateResult:ss},op={name:"entity",primalType:"entity",hydrateResult:ss},ip={name:"file",primalType:"string"},sp={name:"humanName",primalType:"string"},ap={name:"ID",primalType:"string"},cp={name:"image",primalType:"string"},up={name:"int",primalType:"number"},dp={name:"name",primalType:"string"},pp={name:"number",primalType:"number"},lp={name:"order",primalType:"number"},fp={name:"percentage",primalType:"number"},mp={name:"string",primalType:"string"},yp={name:"tag",primalType:"string",isArray:!0,normalizeResult:(t,{property:e})=>!e.isArray||t==null||Array.isArray(t)?t:[t]},hp={name:"timestamp",primalType:"date"},ao=Object.freeze([ap,mp,dp,sp,Zd,yp,cp,ip,pp,up,ep,fp,rp,lp,Xd,hp,tp,op,np]),gp=(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},as=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=gp(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=as(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 Ap=Object.freeze([...is,...Fr.flatMap(({operators:t})=>t??[])]),Qe=(t=[])=>new er([...is,...Se(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,cs=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="query-operator"&&typeof t.operator=="string",$p=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="ordinal-query",us=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="expression-query",wp=(t,e)=>{const r=Kc(t,e);return{schemaId:t.id,propertyId:r.id,propertyName:r.name,physicalColumn:r.udf?.sql??r.id}},ds=(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}:wp(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=>ds(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"&&us(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)]:[],ps=(t,e,r,n=Qe(),o)=>{if(t.subplans){const s=t.subplans.map(c=>ps(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=>ds(t,e,s))}},De=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.version=="string"&&(typeof t.schema=="string"||typeof t.from=="object"),Ep=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,ls=t=>{const e=Ep.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}},fs=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(!ls(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}`)}}}},_p=new Set(["second","minute","hour","day","week","month","quarter","year"]),Gr=t=>typeof t=="string"&&_p.has(t),co=(t,e=Se())=>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 gt{#e=new Map;plugins;constructor(e=[],r=[]){this.plugins=Se(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");fs(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")}fs(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 Ip=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),ms=new Set(["second","minute","hour","day","week","month","quarter","year"]),Sp={weekday:"weekday",toQuarter:"quarter",toMonth:"month",toWeek:"week",toDay:"day",toHour:"hour",toWeekday:"weekday"},ys=(t,e)=>{const r=e[t];return te(r)?r:Object.values(e).find(n=>te(n)&&(n.id===t||n._id===t))},hs=(t,e)=>{const r=t&&e?zr(ys(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},gs=(t,e,r)=>{const n=ys(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"?gs(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)}},As=t=>Object.keys(t).filter(e=>e!=="$and"&&e!=="$or"),te=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),$s=t=>typeof t=="string"&&/^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?$/.test(t),ws=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},bp=t=>typeof t=="string"&&t.length>0||typeof t=="number"&&Number.isSafeInteger(t),Rp=(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}},Np=(t,e,r)=>{const n=Rp(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})},Op=(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)||!bp(s)){r[o]=i;continue}const a=i.entity_level,c=typeof a=="string"&&a.length>0?a:Np(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 Op(r,n)},Tp=(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}},Es=(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=ws(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(!ms.has($))throw new d("INVALID_LEGACY_TIME_GROUPBY",`Unsupported legacy time groupby: ${m}`,{groupby:m});const E=hs(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=Tp(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=Sp[p];if(i.operator==="$count"&&(ms.has(p)||l)){const m=hs(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=Es("$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&&gs(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)?Es("$piecewise",f):{mode:"auto",buckets:Number.isInteger(f.buckets)?f.buckets:10},delete a.params}Ip.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&&$s(i.$gte)&&$s(i.$lte)&&delete a.$options,i.query&&te(i.query)&&(a.query=Pp(i.query,e,s)),a},Pp=(t,e,r)=>{const n=rt(t,e,r);for(const[o,i]of Object.entries(n))n[o]=ws(i);return po(n,e)},_s=(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],_s(o,e)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),e?Lp(n,e):n},Lp=(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 As(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=As(c).map(p=>[xt(o,p,e)??p,c[p]]);a.query=Object.fromEntries(u)}return a},Cp=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)},Dp=t=>{const e=t.constraints?.enum??t.enum;return Array.isArray(e)?e:typeof e=="string"&&e.length>0?e.split(","):void 0},Mp=(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}},Up=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}},Is=(t,e=[],r=!0)=>{const n=Se(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?Dp(w):void 0,N=Mp(w,R,r),D=Up(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},Ss=Symbol("legacy-empty-source"),bs=t=>t!==void 0&&Ss in t,Rs=(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}`,[Ss]:!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),qp=t=>Bt(t)&&typeof t.schema=="string"&&Bt(t.query),kp=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;qp(o)&&!kp(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},jp=(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 xp=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)}},Ns=t=>{xp(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)})},Bp=new Set(["second","minute","hour","day","week","month","quarter","year"]),Vp=(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&&!Bp.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=Se(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=Vp(h,e);return i.reduce(($,E)=>({...$,...E.resolve(f,$,o)}),y)});for(const f of i)a=[...f.resolveAll?.(a,o.properties,o)??a];Ns(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(ui),le.extend(tr),le.extend(Cr);const Yp="YYYY-MM-DD HH:mm:ss",Fp=new Set(["YTD","QTD","MTD","WTD","DTD"]),Os=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"],At=t=>Object.prototype.toString.call(t)==="[object Object]",Ts=(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(At(t)){const n=Object.entries(t);if(n.length===0||n.some(([o])=>!Os.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=>Ts(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=>!At(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(Yp),Hp=(t,e)=>Kr.find(r=>r in t||e!==void 0),vp=(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),Ps=(t,e)=>{const r=typeof t.granularity=="string"?t.granularity:void 0,n=r?{[r]:t.offset}:void 0,o=r??Hp(t,void 0)??"day";let i=le(e).millisecond(0);for(const a of[...Kr].reverse()){const c=t[a];typeof c=="number"&&(i=vp(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))}},Gp=(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)=>De(t)?t:t instanceof Date||typeof t=="string"&&le(t).isValid()?Vt(t):typeof t=="string"&&Fp.has(t)?ho(Gp(t,e.now),e):yo(t)?ho(Ps(t,e.now),e):t,Ls=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"&&At(n)&&"$gte"in n&&"$lte"in n?n:t==="$gte"||t==="$gt"?At(n)&&"$gte"in n?n.$gte:n:(t==="$lte"||t==="$lt")&&At(n)&&"$lte"in n?n.$lte:n},Jr=async(t,e)=>{if(De(t))return t;if(Array.isArray(t))return Promise.all(t.map(o=>Jr(o,e)));if(!At(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(Ps(t,e.now),e);const r=Object.entries(t);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await Ls("$eq",r[0][1],e);if(At(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)Qp.has(o)&&Ts(i,o),n[o]=Os.has(o)?await Ls(o,i,e):await Jr(i,e);return n},zp=(t,e)=>e.property.primal_type==="date"?Jr(t,e):t,Xr=(t=[])=>new fo([...ao,...Se(t).flatMap(({semanticTypes:e})=>e??[])]),Cs=(t,e)=>{const r=new fo(t.definitions());for(const n of Se(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},Ds=t=>!t.isArray&&(t.primal_type!=="number"||t.type==="ID"||t.type==="category"||t.is_categorical===!0),Ms=(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},Wp=(t,e,r)=>{const n=r.plugins.filter(m=>!Fr.some(f=>f.name===m.name)),o=Is(e,n),i=Xr(n),s=new Map,a=m=>{const f=s.get(m);if(f)return f;const h=mo(Di(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)&&Ds(E.property)&&u.add(E.canonicalName)}catch(E){Ao(E)}}},l=(m,f,h,y)=>{for(const $ of m.properties){const E=Ms(f,m,$);if(!E)continue;const A=oe(m,$.id).canonicalName,g=h?`${h}_${A}`:A;if(Ds($)&&(!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}Ms(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]},Kp=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`)},Jp=(t,e=[])=>{const r=Se(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:Kp(t),...t.sourceSql?{sourceSql:t.sourceSql}:{},...t.enrichments?{enrichments:t.enrichments}:{},mappings:n}};class Us{#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 qs=(t=[])=>new Us([...Se(t).flatMap(e=>e.plannerSemantics??[])]);le.extend(ui),le.extend(tr),le.extend(Cr);const Yt=["second","minute","hour","day","week","month","quarter","year"],Xp=new Set(["$second","$minute","$hour","$day","$week","$month","$quarter","$year"]),Zp="YYYY-MM-DD HH:mm:ss",$t=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),el=(t,e)=>t==="week"?e==="week":e==="week"?Yt.indexOf(t)<=Yt.indexOf("day"):Yt.indexOf(t)<=Yt.indexOf(e),ks=(t,e,r)=>{if(typeof t!="string")return"second";const n=le(t,Zp,!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"},js=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])=>Xp.has(r)?[r.slice(1)]:r==="$weekday"?["day"]:r==="$and"||r==="$or"?Array.isArray(n)?n.flatMap(js):["second"]:r==="$gte"||r==="$gt"?[ks(n,"lower",r==="$gte")]:r==="$lte"||r==="$lt"?[ks(n,"upper",r==="$lte")]:["second"])},tl=(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"}},rl=(t,e,r,n,o=Se(),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=>$t(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=>$t(e,A)?.id===$.id)),m=($,E,A="filterOrGroup")=>{const g=$t(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"&&$t(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)||!el(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=$t(e,E);if(!g)return`dimension property is not available: ${E}`;const w=g.primal_type==="date"?js(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")?$t(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=$t(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,tl($,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 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 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]))},Et=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=Et(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},$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=>It(r,a.property,i,n)&&pr(a.condition,s))||(o[i]=s)}return Object.keys(o).length>0?o:void 0},_t=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),It=(t,e,r,n)=>{if(e===r)return!0;const o=_t(t,e),i=_t(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}},Pe=(t,e,r)=>{const n=He(t,e,r);if(n)return nt(t)?_t(e,r)?.id:n.column},He=(t,e,r)=>{const n=_t(e,r);if(!n)return;const o=(t.mappings??[]).find(i=>i.mappingType==="property"&&i.propertyTarget?.some(s=>It(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}},Qt=(t,e,r)=>!(t.mappings??[]).some(n=>n.mappingType==="property"||n.mappingType==="predItem")||Pe(t,e,r)!==void 0,wo=(t,e,r,n,o)=>{if(Qt(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=He(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||Pe(p,a.targetSchema,l.id)===void 0)return!1}const s=n.get(i.schema.id,t.connectionId);return Pe(s,i.schema,i.property.id)!==void 0}catch{return!1}},xs=(t,e,r)=>{if(!t||!(e.mappings??[]).some(i=>i.mappingType==="property"||i.mappingType==="predItem"))return;const n=Et(t);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:i})=>!Qt(e,r,i));return o?`query property is not available: ${o.property}`:void 0},nl=(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"?_t(r,e.pred):void 0,c=_t(r,t.match.pred);if(!(typeof e.pred=="string"&&It(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=Et(t.match.query);return p!==void 0&&p.every(l=>o.some(m=>It(r,m.property,l.property,i)&&pr(m.condition,l.condition)))},ol=(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=Et(t.query),p=ae(t),l=[],m=[],f=new Map,h=S=>Qt(r,e,S)||a.some(R=>{const N=Et(R.match.query)??[];return N.some(F=>It(e,F.property,S,o))?(R.propertyTarget?.length?[R.propertyTarget.join("_")]:N.map(({property:F})=>F)).some(F=>It(e,F,S,o)):!1}),y=S=>{let R=_t(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 wt(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=Et(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=>nl(K,R,e,R.schema??e.id,F,o,s));if(V.length===0){const K=wt(R);if(!(K.length===0&&R.operator!==void 0&&s.get(R.operator).requiresProperty===!1)&&(K.length===0||K.some(re=>!Qt(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=Et(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=wt(R).find(F=>!Qt(r,e,F));if(D)return`PredItem ${S} property is not available: ${D}`}const A=(u??[]).filter(({property:S})=>!Qt(r,e,S));for(const[S]of(t.preds??[]).entries()){const R=A.find(N=>!f.get(S)?.some(D=>It(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=xs(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=xs(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=wt(S).find(D=>!wo(r,e,D,n,o));if(N)return E(`groupby property is not available: ${N}`)}const L=rl(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}},il=(t,e,r,n={})=>{const o=n.plugins?Se(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=ol(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}}},Bs=(t,e,r)=>{const n=t.id,o="__sdb_mapping",i=t.properties.flatMap(g=>{const w=He(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=He(e,t,c.start.name),I=He(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?He(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)),Vs=(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)),Ys=t=>t.name??(typeof t.pred=="string"?t.pred:void 0),sl=(t,e)=>{const r=t.preds??[];if(!r.some(f=>!lr(f,e)&&Vs(f,e)))return;const n=new Set([...r.map(({name:f})=>f).filter(f=>!!f),...(t.groupby??[]).map(Ys).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)&&Vs(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=Ys(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},al=(t,e)=>`result:${t}:${e.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,Fs=(t,e)=>{const r=(t.columnProperties??[]).map(n=>({...n,id:n.name}));return{id:al(t.schemaId,t.columnProperties??[]),name:`${e.name} result`,type:e.type,temporalSemantics:"normal",properties:r}},Qs=(t,e)=>({...Fs(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))}:{}}),Hs=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(o=>Hs(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(!(De(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]})),cl=(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&&(Pe(r,t,i.name)??i.id):void 0;return{sql:e,...s?{timestampColumn:s}:{},...s&&n?{timestampQualifier:n}:{}}},vs=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},Gs=(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}),Ht=(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:vs(w.field),outputProperty:Gs(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)?Ht(m,e,r,n,o,i,s,a,c):typeof m=="string"?Ht({pred:m,name:m},e,r,n,o,i,s,a,c):void 0,y=Array.isArray(m)?m.map(w=>Ht(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?Gs($,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}:{}}},ul=(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,$=Ht(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}},zs=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},dl=(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=>Le(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}:{}}},pl=(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,Q=L.map(_=>Le({...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(Q.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}:{}},Me=Q[0],fe=l.map(_=>({name:_,expression:{kind:"column",property:_,column:_}})),be=Me.projections.filter(_=>!p.some(T=>T.name===_.name)),se=[...fe,...be.map(({name:_})=>({name:_,expression:{kind:"column",property:_,column:_}}))];zs(se);const Re=Me.columnProperties??[],b=[...l.map(_=>_===re?ye:Re.find(T=>T.name===_)),...Re.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:"",...Me.connectionId?{connectionId:Me.connectionId}:{},subplans:Q,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}:{}}},Le=(t,e,r=Qe(),n=new gt,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:Hs(t.query,Y)},...C!==e.id&&t.groupby?{groupby:t.groupby.map(v=>({...v,...typeof v.pred=="string"?{pred:Y(v.pred)}:{}}))}:{}}});return dl(t,O,e,r,n,o)}const s=sl(t,r);if(s)return Le(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 Le(O,e,r,n,o)}const a=o.semanticRegistry??qs(o.plugins);if(t.from){const b=So(t.from,e,o),O=Le(t.from,b,r,n,o),C=Qs(O,e),q={...t};delete q.from,q.schema??=C.id;const _=new gt([...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=Le(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=pl(t,e,r,n,o);if(c)return c;const u=il(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&&He(u.mapping,e,b.id)),l=new Map(u.predRewrites.map(({predIndex:b,column:O})=>[b,O])),m=Fn(e,o.plugins),f=Uu(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=He(u.mapping,e,m.start.name),k=He(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:Fe})=>Fe==="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),ge=Pe(de,Y.sourceSchema,Y.property.name)??Y.property.id,we=nt(de)?void 0:Y.property.udf?.sql,Ee=Pe(z,Y.targetSchema,ee.name)??ee.id,me=nt(z)?void 0:ee.udf?.sql,_e=Y.sourceSchema.properties.find(({type:Fe})=>Fe==="timestamp"),Ne=Y.targetSchema.properties.find(({type:Fe})=>Fe==="timestamp"),he=Mu(Y.sourceSchema,Y.targetSchema,o.plugins),xe=_e?Pe(de,Y.sourceSchema,_e.name)??_e.id:void 0,ve=Ne?Pe(z,Y.targetSchema,Ne.name)??Ne.id:void 0,Tt=he?.kind==="date-bucket-equal"?{kind:"date-bucket-equal",sourceColumn:Pe(de,Y.sourceSchema,he.sourceTimestamp.name)??he.sourceTimestamp.id,targetColumn:Pe(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:Pe(de,Y.sourceSchema,he.point.name)??he.point.id,intervalSide:"target",startColumn:Pe(z,Y.targetSchema,he.start.name)??he.start.id,endColumn:Pe(z,Y.targetSchema,he.end.name)??he.end.id}:void 0,Ye=Y.property.isArray?v:void 0;Ye&&!g.has(Ye)&&g.set(Ye,{path:Ye,sourceAlias:C,sourceColumn:ge,...we?{sourceSql:we,...xe?{sourceTimestampColumn:xe}:{}}:{},alias:`__array_${v}`}),E.set(v,{kind:"left",path:v,sourceAlias:C,sourceColumn:ge,...we?{sourceSql:we,...xe?{sourceTimestampColumn:xe}:{}}:{},targetSchemaId:Y.targetSchema.id,targetConnectionId:z.connectionId,targetSource:z.source,...z.sourceSql?{targetSourceSql:z.sourceSql}:{},...nt(z)?{targetMappingSourcePlan:Bs(Y.targetSchema,z,o.plugins)}:{},targetAlias:G,targetColumn:Ee,...Ye?{sourceArrayExpansionPath:Ye}:{},...me?{targetSql:me,...ve?{targetTimestampColumn:ve}:{}}:{},...Tt?{temporalCondition:Tt}:{}})}C=G}const T=He(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}:{},...cl(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(De(b)){const O=So(b,e,o),C=Le(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=Ht(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=Ht(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:vs(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 ul(C,r,I,V,x,N,e,o.resolveSchema,a,l.get(O),Ui(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)]})),Q=y?D(y):void 0;S(Q);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");zs(j);const ye=new Set(j.map(({name:b})=>b)),Me=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=He(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}:{}}}),be=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}:{}}]})()},Re=w.size===0&&E.size===0&&A.size===0&&g.size===0&&!Q&&F.length===0&&j.length>0&&j.every(({expression:b})=>b.kind==="operator"&&b.operator==="$constant");return{schemaId:e.id,source:Re?"":u.mapping.source,...Re?{}:{connectionId:u.mapping.connectionId},...!Re&&u.mapping.sourceSql?{sourceSql:u.mapping.sourceSql}:{},...!Re&&nt(u.mapping)?{mappingSourcePlan:Bs(e,u.mapping,o.plugins)}:{},mappingId:u.mapping.id??u.mapping.source,sourceAlias:$,fields:{...Jc(e),...Object.fromEntries(e.properties.flatMap(b=>{const O=Pe(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:Pe(u.mapping,e,f.source.start.name)??f.source.start.id,endColumn:Pe(u.mapping,e,f.source.end.name)??f.source.end.id}:{kind:"latest",lookupAlias:"__period_lookup",timestampColumn:Pe(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})),...Q?{query:N(Q)}:{},...t.having?{having:K(t.having)}:{},orderBy:fe,rowIdentity:Re?{kind:"singleton"}:Me,...be?{pagination:be}:{},...se?{groupLimit:se}:{}}};class ll{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 fl=(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?fl(t,e):`(${r.trim().replace(/;+\s*$/,"")})`,yr=(t,e,r,n,o)=>{const i=rs(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)},We=(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(ke(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=>We(m,e,r,n,o,i,s,a)).join(", ")} `:"",p=We(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(ke(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Cumulative expressions cannot consume a JavaScript operator");const u=We(t.input,e,r,n,o,i,s,a),p=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(m=>We(m,e,r,n,o,i,s,a)).join(", ")} `:"",l=t.orderBy.map(m=>`${We(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 ${We(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 ${We(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&&ke(t.input,r)||t.inputs?.some(m=>ke(m,r))))throw new d("UNSUPPORTED_MIXED_OPERATOR",`${t.operator} cannot consume a JavaScript operator in SQL`);let p=t.input?We(t.input,e,r,n,o,i,s,a):t.column?c(t.column,t.qualifier):void 0;const l=t.inputs?.map(m=>We(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"}}},ke=(t,e)=>t.kind==="window"?ke(t.input,e)||t.partitionBy.some(r=>ke(r,e)):t.kind==="cumulative"?ke(t.input,e)||t.partitionBy.some(r=>ke(r,e))||t.orderBy.some(r=>ke(r.expression,e)):t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?ke(t.input,e):t.kind==="operator"&&(!e.get(t.operator).toSQL&&!!e.get(t.operator).evaluate||(t.input?ke(t.input,e):!1)||(t.inputs?.some(r=>ke(r,e))??!1)),ml=(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},Ws=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).some(e=>e.startsWith("$")),Ks={$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(cs(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`)}},St=(t,e,r,n,o,i)=>{if($p(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)?St(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(!Ws(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=>St(t,m,r,n,o,i));s.push(`(${l.join(u==="$and"?" AND ":" OR ")})`)}else Ks[u]?(bo(p,u),s.push(St(n.datePart(t,Ks[u]),p,r,n,o,i))):u==="$length"?(bo(p,"$length"),s.push(St(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 ")},Js=(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(!Ws(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=>Js(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 ")},dt=(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 dt(f,e,r,n,o,i,s,a)});c.push(`(${m.join(u==="$and"?" AND ":" OR ")})`);continue}if(u==="$expr"){if(!us(p))throw new d("INVALID_EXPRESSION_QUERY","$expr query was not planned");c.push(St(s(p.expression),p.condition,n,o,i,a));continue}const l=e(u);c.push(r(u)?Js(l,p,n,o):St(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},Xs=(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}`},$e=(t,e,r=Qe(),n=0)=>{const o=new ll(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 Q=$e(j,e,r,o.nextParameterOffset);o.append(Q.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(`(${Q.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),Q=new Set(t.projections.map(({name:ye})=>ye)),re=dt(t.having,ye=>{if(!Q.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"),Q=$e(F,e,r,o.nextParameterOffset);o.append(Q.parameters);const re=`__split_group_${V}`,ye=e.quoteIdentifier(re),Me=I.groupNames.map((se,Re)=>`${M[Re]} AS ${e.quoteIdentifier(se)}`),fe=R.map(se=>`${ye}.${e.quoteIdentifier(se)} AS ${e.quoteIdentifier(se)}`),be=R.map(se=>`${ye}.${e.quoteIdentifier(se)} IS NOT NULL`).join(" OR ");return`SELECT ${[...Me,...fe].join(", ")}, ${K} AS ${e.quoteIdentifier("_id")} FROM ${e.tableAlias(`(${Q.sql})`,re)} WHERE (${be})`}).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=dt(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=$e(x,e,r,o.nextParameterOffset);o.append(j.parameters);const K=`__composition_child_${M}`,Q=e.quoteIdentifier(K),re=new Set(x.projections.map(({name:ye})=>ye));return{aliasName:K,alias:Q,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(Q=>Q.available.has(x)),j=M[0]??N;return`${S.has(x)&&M.length>1?`COALESCE(${M.map(Q=>`${Q.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=dt(t.having,Q=>{if(!j.has(Q))throw new d("INVALID_HAVING",`Having field is not an output: ${Q}`);return`${M}.${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 ${M}.* FROM ${e.tableAlias(`(${V})`,x)} WHERE ${K}`}if(t.groupLimit&&(V=Xs(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})=>ke(R,r)))throw new d("JAVASCRIPT_OPERATOR_IN_SUBQUERY","A query LogicForm cannot use a JavaScript-only operator");const S=$e(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(ml(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=>We(I,e,r,u,S=>dt(S,m,R=>t.fieldReferences?.[R]?.isArray===!0,o,e,s,f,i),S=>o.add(S),(S,R)=>St(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=$e(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 Q=o.add(M),re=o.add(j);return K===0?`SELECT ${Q} AS ${e.quoteIdentifier(I.labelColumn)}, ${re} AS ${e.quoteIdentifier(I.asOfColumn)}`:`SELECT ${Q}, ${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)}`,Q=`${j}.${e.quoteIdentifier(I.match.timestampColumn)}`,re=`SELECT ${e.aggregateFunction("max",Q)} FROM ${M} WHERE ${Q} <= ${V}`;return`${K} = (${re})`})();w+=` FROM ${R} LEFT JOIN ${N} ON ${x}`,t.query&&Object.keys(t.query).length>0&&(w+=` AND ${dt(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=$e(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(dt(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 ${dt(t.having,I,()=>!1,o,e,s,f,i)}`}if(t.groupLimit&&(w=Xs(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}},yl=(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},hl=t=>`__sdb_cte_${t}`,Zs=t=>{const e=t.projections[t.groupBy.length];if(!e)throw new Error("CTE component must produce one metric projection");return e.name},gl=(t,e)=>t?.find(r=>r.name===e),Al=(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:Al(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=$e(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=$e(A.plan,o,i,a);a+=g.parameters.length,s.push({input:A,sql:g,alias:hl(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=gl(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(Zs(A.plan))}`])),y=yl(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(Zs(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)}},$l=t=>{if(typeof t!="string"||!/\bSELECT\b/i.test(t))return t;try{let e=t;const r=ta(t).length*2+2;for(let n=0;n<r;n+=1){const o=wl(e);if(o===e)return e;e=o}return e}catch{return t}},wl=t=>{const e=ta(t),r=El(t,e);if(r!==t)return r;const n=[];for(const i of e){const s=ra(t,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?ql(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=Ml(_l(t.slice(i.fromStart,i.close),i,e)),u=Il(t,i),p=Sl(t,i);if(p&&bl(u,p))continue;let l=s.filter(y=>{const $=na(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=sa(l.join(" ")),$=s.filter(E=>{if(l.includes(E))return!1;const A=na(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&&Ul(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},El=(t,e)=>{const r=/^\s*SELECT\b/i.exec(t);if(!r)return t;const n=r.index+r[0].length,o=ea(t,"FROM",n);if(o===-1||!ra(t,n,o)?.every(Dl))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=Ll.exec(c)?.[1],p=Cl.exec(t.slice(s.close+1));if(!u||!p||oa(u)!==oa(p[1]))return t;const l=/;(\s*)$/.exec(t)?.[0]??"";return t.slice(0,s.open)+t.slice(a.open,s.close)+l},_l=(t,e,r)=>Rl(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}))),Il=(t,e)=>{const r=t.slice(0,e.open)+" ".repeat(e.close-e.open+1)+t.slice(e.close+1);return sa(r)},Sl=(t,e)=>t.slice(e.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${ot})(?=\\s|$)`,"i"))?.[1]??null,bl=(t,e)=>new RegExp(`(^|[^\\w$])${Oo(e)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(t),Rl=(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("")},ea=(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},ta=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=ea(t,"FROM",l);m===-1||m>=i||e.push({open:c.open,close:i,selectEnd:l,fromStart:m})}return e},ra=(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)},na=t=>t.trim().match(/\bAS\s+(`[^`]+`|"[^"]+"|[A-Za-z_][\w$]*)\s*$/i)?.[1]?.replace(/^`|`$/g,"").replace(/^"|"$/g,"")??null,ot='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',Nl=new RegExp(`\\s+AS\\s+${ot}\\s*$`,"i"),Ol=new RegExp(`\\bAS\\s+${ot}`,"gi"),Tl=new RegExp(`(?:${ot}\\s*\\.\\s*)+${ot}`,"g"),Pl=new RegExp(`^${ot}(?:\\s*\\.\\s*${ot})*$`),Ll=new RegExp(`^\\s*(?:AS\\s+)?(${ot})\\s+WHERE\\b`,"i"),Cl=new RegExp(`^\\s*(?:AS\\s+)?(${ot})\\s*;?\\s*$`,"i"),oa=t=>t.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),Dl=t=>{const e=t.replace(Nl,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(e)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(e)},ia=(t,e)=>t.replace(e,r=>" ".repeat(r.length)),sa=t=>ia(t,Ol),Ml=t=>ia(t,Tl),Ul=(t,e)=>/\b(?:FROM|JOIN)\s*$/i.test(t.slice(0,e.open)),ql=t=>{const e=t.trim();return Pl.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)},aa=(t,e,r,n)=>{if(t.kind!=="operator")return e[r];const o=n.get(t.operator),i=t.input?aa(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},bt=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 aa(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":di()}}),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},Ke=t=>t instanceof Date?t.getTime():t,kl=(t,e,r,n)=>{const o=Ke(t),i=Ke(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=>Ke(s)===o);case"$nin":return Array.isArray(r)&&r.every(s=>Ke(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 Ke(t)===Ke(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):kl(t,i,s,typeof o=="string"?o:void 0)})},ca=(t,e)=>Object.entries(e).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>ca(t,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return Co(t[r],n)}),jl=(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=jl(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=>ca(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=Ke(a[u.name]),l=Ke(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=Ke(o[s.name]),c=Ke(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},ua=(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},xl=/^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Bl=t=>{if(typeof t!="string")return!1;const e=xl.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(!Bl(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})},da=(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)&&da(o,e))),pa=(t,e,r,n=[])=>{if(e===void 0||e==="placeholder")return t;if(!Qn(e))throw new d("INVALID_ENTITY_ID","entity_id must be a non-empty string or a safe integer");const o=Hn(r,n);return t&&da(t,new Set([o.name,o.id]))?t:{[o.name]:e,...t??{}}},Gt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Vl={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},la={$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])}${Vl[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"),fa=(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 fa("$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(la[o]){const s=la[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=fa(o,t,s,r);a&&n.push(a)}return cn(n,"$and",r)},ma=(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)?ma(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=ma(t.query,n);return m?i?`${l} where ${m}`:`${m}\u7684${l}`:l},Yl=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},Fl=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&&!Yl(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 Fl(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)})},Hl=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),vl=t=>{if(!De(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(De(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)])))},ya=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>ya(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},ha=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),ko=new Set([...ha,"$length"]),dn=t=>Array.isArray(t)?t.some(dn):typeof t!="object"||t===null||De(t)?!1:Object.entries(t).some(([e,r])=>ko.has(e)||dn(r)),ga=(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&&!De(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=>ga(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)},Aa=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)&&ga(a,s.operator),{pred:s,condition:a}},$a=async(t,e,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||De(e))return{[t]:e};const o={},i=[];for(const[s,a]of Object.entries(e))ko.has(s)?i.push({$expr:await Aa({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=>$a(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||De(t)?!1:Object.entries(t).some(([e,r])=>ha.has(e)||jo(r)),wa=async(t,e,r,n)=>{const o=u=>{if(Array.isArray(u)){u.forEach(o);return}if(typeof u!="object"||u===null||De(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 zp(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(!(De(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 Aa(c,e,r)});continue}const u=oe(e,a,r.resolveSchema);if(vl(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(Hl(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=pa(c.query,c.entity_id,f,r.plugins),y=await xo(h,f,r);Object.assign(n,ya(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)=>wa(g,w,L,r)})};continue}}const p=await un(c,r),l=await wa(p,u.schema,u.property,r),m=qo(l);if(dn(m)){s(await $a(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},Ea=async(t,e,r)=>{if(!t)return;const n=await xo(t,e,r);return Object.keys(n).length===0?void 0:n},_a=(t,e,r)=>Promise.all((t??[]).map(n=>$r(n,e,r,Ea))),Gl=(t,e,r)=>_a(t??[],e,r),Kt=(t,e)=>{throw new d("INVALID_PAGINATION",t,e)},zl=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},Wl=t=>t.property.name,Ia=(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=Ia(c,e,r,n,i);if(u)return`${a.name}_${u}`}},Sa=(t,e,r,n)=>{try{const o=oe(t,e,n);return Ia(r,Wl(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)):[]],ba=t=>t?Object.entries(t).flatMap(([e,r])=>{if((e==="$and"||e==="$or")&&Array.isArray(r))return r.flatMap(n=>ba(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]}):[],Kl=(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),...ba(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&&Sa(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},Jl=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`)}}},Xl=async(t,e,r)=>{if(!t)return;const n=ua(t,e,r);return pt(t,n,r)},pt=async(t,e,r)=>{if(r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:qr([...Se(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),Jl(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 $=ua(y,e,r);return pt(y,$,r)}};zl(o);const s=await Xl(o.from,e,i),a=s&&r.resolveFromSchema?await r.resolveFromSchema(s,e):e,c=await Ea(pa(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 _a(u,a,p),m=await Gl(o.groupby,a,p);const f=m.filter(y=>Ui(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,Kl(o,a,i)},Ra=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),it=(t,e)=>{if(t){if(!Ra(t,e))throw new d("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},Rt=(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(!Rt(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)},Na=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(De(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(Na(s)){if(a.property.ref!==s.schema)continue;const c=n(s.schema);it(r,c.id),Qn(s.entity_id)&&wr(r,c,Hn(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),Qn(t.entity_id)&&wr(e,o,Hn(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 Na(t)&&!Ra(t,"version")&&(n.version=e),n},Zl=(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},ef=(t,e,r)=>{if(!t.schema)return[];const n=r(t.schema),o=new Set,i=[];for(const s of Zl(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)=>De(t)?Nt(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))}:{}}),Nt=(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=Nt(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=Nt(u.from,e,r,n,new Set,i));const p=a||t.from?void 0:s?.rowPermissions,l=(t.from?[]:ef(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},tf=(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})}},Oa=(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")}},Ta=(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=Oa(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)},rf=(t,e)=>{const r=ls(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=Oa(e,t.timeZone);let o=Ta({...n,...r},t.timeZone);if(o.getTime()<=e.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=Ta({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},t.timeZone)}return o},nf=(t,e)=>{const r=t.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(e.getTime()+n.ttlSeconds*1e3)]:[rf(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,Pa=t=>lc("sha256").update(JSON.stringify(Fo(t))).digest("hex"),of=t=>Pa({namespace:t.namespace,provider:t.provider,connectionId:t.connectionId,sql:t.sql,parameters:t.parameters}),sf=(t,e)=>Pa({namespace:t,source:e}),Qo=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(Qo)}:t&&typeof t=="object"?{type:"object",value:Object.entries(t).map(([e,r])=>[e,Qo(r)])}:t,Ho=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(Ho);case"object":return Object.fromEntries(t.value.map(([e,r])=>[e,Ho(r)]))}},af=t=>JSON.stringify(Qo(t)),cf=t=>{const e=Ho(JSON.parse(t));if(!(!Array.isArray(e)||e.some(r=>!r||typeof r!="object"||Array.isArray(r))))return e},uf=Number.MAX_SAFE_INTEGER;class df{#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:${of(e)}`}#o(e,r){return`${this.#t}:source:${sf(e,r)}`}async get(e){const r=await this.#e.get(this.#n(e));if(r!==null)return cf(r)}async set(e,r,n){const o=this.#n(e),i=af(r),s=n.expiresAt?.getTime(),a=s??uf,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 pf=async(t={})=>{const e=fc(t.url?{url:t.url}:{});return e.on("error",()=>{}),await e.connect(),new df(e,{...t.keyPrefix?{keyPrefix:t.keyPrefix}:{},ownsClient:!0})};function lf(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 ff=({namespace:t,...e})=>e,mf=async t=>pf({url:t.url,...t.keyPrefix?{keyPrefix:t.keyPrefix}:{}});class yf{create;#e=new Map;constructor(e=mf){this.create=e}async get(e){lf(e);const r=ff(e),n=this.#e.get(r.id);if(n){if(!pi(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 La=new yf,Ca=t=>La.get(t),hf=()=>La.close(),gf=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 Ca(t);await r.store.invalidateSource(r.namespace,e)},Af=Object.freeze({invalidateSource:gf}),$f=()=>{},_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(cs(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)}},Te=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 Te(o))r(i);else if(t.sourcePlan)for(const o of Te(t.sourcePlan))r(o);else if(t.mappingSourcePlan)for(const o of Te(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 Te(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 Te(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()]},Da=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})}},wf=(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=$f)=>{t=Ma(t),r.signal?.throwIfAborted();const o=r.cache?wf(e,r.schemaMappings):void 0;if(!r.cache||!o)return n("database"),Da(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 Da(r.provider,{...t,...r.signal?{signal:r.signal}:{}});try{const a=nf(o,new Date);await r.cache.store.set(i,s,{sources:[...new Set(e.map(({source:c})=>c))],...a?{expiresAt:a}:{}})}catch{}return s},Ma=t=>({...t,sql:$l(t.sql)}),Ef=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")},_f=(t,e,r)=>{const n=Ef(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}},Ua=async(t,e)=>{if(!Rt(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=>Rt(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:_f(t.idProperty.name,t.ids,i.maxInListItems),preds:r.map(E=>({pred:E.name,name:E.name}))},a=Nt(s,e.permissions,e.resolveSchema,!0,new Set,e.plugins),c=await pt(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=Le(c,t.schema,e.operators,e.schemaMappings,{resolveSchema:e.resolveSchema,...o?{preferredConnectionId:o}:{},canUsePropertyRowIdentity:(E,A)=>Rt(e.permissions,E.id,A)}),p=new Set(Te(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=$e(u,m,e.operators),h=Te(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)},qa=t=>String(t),If=(t,e,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${qa(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=qa(r),o},ka=(t,e)=>`${t}:${String(e)}`,Sf=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 bf{#e;#t=new Map;#r=new Map;#n=new Map;#o=!1;constructor(e){this.#e=e}load=(e,r)=>{const n=ka(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=Sf(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(ka(e.schema.id,s),c)}}for(const[i,s]of e.loads){const a=o.get(i)??If(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 Rf=(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})}},Nf=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=Rf(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)}))}))},ja=5,Of=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Tf=(t,e)=>{const r=e.properties.find(({type:n})=>n==="ID");return r?t[r.name]:void 0},Pf=(t,e)=>{const r=mc(e);t._title=t[r.name]??t._id},Lf=(t,e)=>{const r=structuredClone(t);if(!("_id"in r)){const n=Tf(r,e);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},Cf=(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})},Df=async(t,e,r)=>{const n=new bf(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<ja;return Nf(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)Pf(c,a.schema);if(i>=ja)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(!Of(h))continue;const y=Lf(h,u);c.isArray?m[f]=y:p[c.name]=y,Cf(s,u,y,!c.isArray)}c.isArray&&(p[c.name]=m)}}o=[...s.values()]}},xa=async(t,e,r)=>{const n=t.map(o=>({...o}));return await Df(n,e,r),n},Go=t=>`'${t.replaceAll("'","''")}'`,Ba=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"?Ba(t):Go(t);if(t instanceof Date){const r=e==="clickhouse"||e==="mysql"?t.toISOString().replace("T"," ").replace("Z",""):t.toISOString();return e==="mysql"?Ba(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}`)},Mf=(t,e)=>t.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in e?br(e[o],"clickhouse"):r}),Uf=(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}),qf=(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},kf=(t,e)=>zo(t,e,"mysql"),Wo=(t,e)=>zo(t,e,"snowflake"),jf=(t,e)=>zo(t,e,"dameng"),xf=(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},lt=(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`)},Be=(t,e)=>{throw new d("UNSUPPORTED_TABLE_SCOPE",`${t.kind} table discovery does not support a ${e} override`)},Je=(t,e)=>Object.entries(t).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1],je=(t,e)=>{const r=Je(t,e);if(typeof r!="string"||!r)throw new d("INVALID_TABLE_METADATA",`Expected a non-empty metadata field: ${e}`);return r},Va=t=>{const e=je(t,"table_name"),r=Je(t,"table_database"),n=Je(t,"table_schema"),o=je(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"}},Bf=t=>t.map(Va),Ot=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&&Be(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&&Be(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&&Be(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&&Be(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(),Bf(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=Je(t,e);return typeof r=="string"?r:""},Vf=t=>{const e=je(t,"column_type"),r=Je(t,"type_length"),n=Je(t,"type_precision"),o=Je(t,"type_scale");return/^(?:n?varchar2?|n?char|n?varbinary|binary|raw)$/i.test(e)&&typeof r=="number"?`${e}(${r===-1?"max":r})`:/^(?:number|numeric|decimal)$/i.test(e)&&typeof n=="number"?`${e}(${n}${typeof o=="number"?`,${o}`:""})`:e},Ya=t=>{const e=Je(t,"is_primary_key");let r;if(e!=null)if([!0,1,"1","true","TRUE","YES","Y"].includes(e))r=!0;else if([!1,0,"0","false","FALSE","NO","N"].includes(e))r=!1;else throw new d("INVALID_TABLE_METADATA","Invalid primary-key metadata");return{name:je(t,"column_name"),type:Vf(t),comment:hn(t,"column_comment"),...r!==void 0?{primaryKey:r}:{}}},Yf=(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&&Be(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&&Be(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&&Be(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&&Be(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}},Fa=(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=Fa(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},Ff=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??=je(l,"table_database"),n??=je(l,"table_schema")}const o=Fa(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=Je(l,"col_name"),f=Je(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:je(l,"col_name"),type:je(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&&Be(t,"database"),e.schema!==void 0&&Be(t,"schema");const n=(await Zt(t,e,`DESC ${t.quoteIdentifier(e.table)}`)).map(Ya);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 Ff(t,e);if(t.kind==="maxcompute")return Qf(t,e);const{tableSql:r,columnSql:n,parameters:o}=Yf(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={...Va(s),comment:hn(s,"table_comment")},c=(await Zt(t,e,n,o)).map(Ya);return Jo(t,e,{columns:c,tableInfo:a})},Hf=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}`},vf=t=>t===null?"Nullable(String)":typeof t=="boolean"?"Bool":typeof t=="number"?"Float64":t instanceof Date?"DateTime64(3)":"String",Qa=t=>t instanceof Date?t.toISOString().replace("T"," ").replace("Z",""):t;class Gf{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 lt("@clickhouse/client",r)});return e({url:Hf(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}:${vf(r)}}`}displayQuery(e,r){return Mf(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}`,Qa(i)]));return(await r.query({query:e.sql,format:"JSONEachRow",query_params:n,...e.signal?{abort_signal:e.signal}:{}})).json()}getTableList(e){return Ot(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}`,Qa(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 zf=t=>[".azuredatabricks.net",".databricks.azure.cn",".databricks.azure.us"].some(e=>t.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]?.endsWith(e)),Wf=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??(zf(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)}`)},Kf=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 Jf{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 lt("@databricks/sql",r)})).DBSQLClient;if(this.#e)try{await e.connect(Wf(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(Kf)}),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??=je(u,"table_database"),o??=je(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=je(u,"tableName");c.set(p,{name:p,database:n,schema:o,type:"table"})}for(const u of a){const p=je(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 Ha=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}`)},Xf=t=>{const{host:e,port:r,...n}=t;return{...n,connectString:t.connectString??`${e??"localhost"}:${r??5236}`}};class Zf{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={...Xf(this.#e),poolAlias:typeof this.#e.poolAlias=="string"?this.#e.poolAlias:`semanticdb-${di()}`};if(this.#t)return this.#t.createPool(e);const{default:r}=await import("dmdb").catch(n=>{throw lt("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 jf(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 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 Ot(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(Ha),{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 kf(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}`}}},em={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 lt("mysql2",r)});return e({...em,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 Ot(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 tm 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 rm extends gn{kind="gbase";supportsRecursiveCte=!1;constructor(e={}){super({...e,connection:{port:5258,...e.connection}})}}class nm{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&&Be(this,"database"),e.schema!==void 0&&Be(this,"schema"),(await this.execute({sql:"SHOW TABLES",parameters:[],...e.signal?{signal:e.signal}:{}})).map(n=>({name:je(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 om extends gn{kind="mysql";constructor(e={}){super(e)}}const va=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}`)},im=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class sm{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 Uf(e,r.map(va))}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 lt("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 Ot(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(va),{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?im(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 am{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 lt("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 qf(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 Ot(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 Ga=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}`)},cm=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class um{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 lt("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(Ga))}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 Ot(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(Ga);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(cm(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 dm=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}}},pm=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}`)},lm=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError"),fm=t=>t instanceof Error?t:new Error("SQL Server query failed",{cause:t}),mm=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 ym{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 lt("mssql",n)}),r=new e.ConnectionPool(dm(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`${mm(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 xf(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 Ot(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}`,pm(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(lm(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(fm(l)))),a?.aborted&&p()})}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}class hm 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 Ve=t=>{const{id:e,kind:r,...n}=t;return n},gm=Object.freeze([{kind:"mysql",create:t=>new om({connection:Ve(t)})},{kind:"doris",create:t=>new tm({connection:Ve(t)})},{kind:"gbase",create:t=>new rm({connection:Ve(t)})},{kind:"starrocks",create:t=>new hm({connection:Ve(t)})},{kind:"maxcompute",create:t=>new nm(Ve(t))},{kind:"postgresql",create:t=>new am({connection:Ve(t)})},{kind:"clickhouse",create:t=>new Gf(Ve(t))},{kind:"databricks",create:t=>new Jf({connection:Ve(t)})},{kind:"dameng",create:t=>new Zf({connection:Ve(t)})},{kind:"snowflake",create:t=>new um({connection:Ve(t)})},{kind:"sqlserver",create:t=>new ym({connection:Ve(t)})},{kind:"oracle",create:t=>new sm({connection:Ve(t)})}]);class za{#e=new Map;constructor(e=gm){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 Wa=new za,Ka=(t,e=Wa)=>e.create(t);class Am{create;#e=new Map;#t=new Set;#r=[];constructor(e=Ka){this.create=e}get(e){const r=this.#e.get(e.id);if(r&&pi(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,$m=t=>{const e=An.get(t);if(e)return e;const r=new Am(n=>Ka(n,t));return An.set(t,r),r},$n=(t,e=Wa)=>$m(e).get(t),wm=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")},Ja=async()=>{const e=(await Promise.allSettled([wm(),hf()])).flatMap(r=>r.status==="rejected"?[r.reason]:[]);if(e.length>0)throw new AggregateError(e,"Failed to close one or more SemanticDB resources")},Em=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},_m=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},Im=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},Sm=Object.freeze({runSQL:Em,getTableList:_m,describeTable:Im,close:Ja}),bm=t=>{const{name:e,kind:r}=t;switch(r){case"boolean":return{name:e,kind:r,type:fi,sqlType:"BOOLEAN"};case"date":return{name:e,kind:r,type:Nn,sqlType:"TIMESTAMP"};case"number":return{name:e,kind:r,type:li,sqlType:"DOUBLE"};case"string":return{name:e,kind:r,type:Lt,sqlType:"VARCHAR"}}},Rm=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="true"?!0:t===0||t==="0"||t==="false"?!1:!!t,Nm=(t,e)=>{if(t==null)return null;switch(e.kind){case"boolean":return et(Rm(t),fi);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:et(r,Nn)}case"number":{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?et(r,li):null}case"string":return typeof t=="string"?et(t,Lt):typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?et(t.toString(),Lt):typeof t=="symbol"?et(t.description??"",Lt):typeof t=="function"?et(t.name,Lt):et(JSON.stringify(t),Lt)}},Om=t=>{if(t==null)return null;if(t instanceof Date)return et(t,Nn);if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"||typeof t=="string")return t;if(Buffer.isBuffer(t))return hc(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 yc.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(bm),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=Nm(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(Om));return e.signal?.throwIfAborted(),r.getRowObjectsJS()}close(){return this.connection.closeSync(),this.instance.closeSync(),Promise.resolve()}}const Xo="__sdb_total__",Tm="__sdb_total_source__",Zo=t=>{const e={...t,orderBy:[]};return delete e.pagination,e},Pm=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})`,Tm)}`,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__",Xa=(t,e)=>{const r=new Set;for(const n of Te(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=>Xa(r,e))).size>1||!!(t.sourcePlan&&Or(t.sourcePlan,e)),Lm=(t,e)=>({name:t,expression:{kind:"column",property:t,column:t,qualifier:e}}),Cm=(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"},Za=(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"?Cm(e,n):"string";return{name:n,kind:i}})},Dm=(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=>Lm(n,e)),...t.columnProperties?{columnProperties:t.columnProperties}:{},groupBy:[],orderBy:[],rowIdentity:{kind:"generated"}}},Mm=(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")},ec=(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,Za(t.sourcePlan,s.rows),s.rows);const u={...t,source:c};delete u.sourcePlan,delete u.sourceLogicform,delete u.connectionId;const p=$e(u,a,e.operators),l=ei($e(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:ec(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=Xa(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=$e(s,u,e.operators),l=Te(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 bt(f,s.projections,e.operators);return{child:s,rows:Mm(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,Za($,s),E),a.push(Dm($,A))}const c={...t,subplans:a},u=$e(c,i,e.operators),p=ei($e(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:ec(h,t),total:wn(f),connections:[...r].map(([y,$])=>({connectionId:y,provider:$}))}}finally{await i.close()}},tc=t=>{const e={...t};return delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,e},Um=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}]),qm=(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=>!Um.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},rc=(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=qm(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}},nc=(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}`)}},oc=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(oc(t),s&&oc(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");nc(e,r,o);const a=[],c=[],u=[];let p,l;for(const[y,$]of r.entries()){const E=rc(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=Le(tc(A),e,n,o,N),F=g?Le(tc(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??=Le(A,e,n,o,S),g&&(l??=Le(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}},ic=(t,e)=>[...Se(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}:{}}),sc=t=>t instanceof Error?t:new Error(String(t)),km=(t,e="zh-CN",r)=>t instanceof d?t.localizedMessage(e,r):t.message,jm=(t,e,r={},n="zh-CN",o)=>{const i=sc(t);return{errorCode:"100",error:km(i,n,o),result:[],...r.schema?{schema:r.schema}:{},normedLogicform:r.normedLogicform??e,sqls:r.sqls??[],...r.lineage?{lineage:r.lineage}:{}}},xm=(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}},Bm=(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),...Te(r)];for(const i of o){const s=_r(i,e);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},Vm=async(t,e,r)=>{await t?.({...e,partialResult:r})},Ym=(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 Te(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})}},ac=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(ic(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&&Cp(t);const c=a?_s(t,e.schemas):t,u=e.schemaMappings.definitions(),p=ac(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?Rs(e.schemas,u,m,p):u,h=f.length===u.length?e.schemaMappings:new gt(f,e.schemaMappings.plugins),y={...e,locale:r,localeRegistry:n,schemaMappings:h,schemas:Is(e.schemas,o,a)},$=Lr.now(),E=y.semanticTypes===void 0?Xr(o):y.semanticTypesResolved?y.semanticTypes:Cs(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=_=>Te(_).some(T=>bs(_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(Ym(Ma(_),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 Vm(y.onProgress,_,R)},j=_=>mo(Di(_,y.schemas),E,o),K=new Map,Q=_=>{const T=K.get(_);return T||(it(y.permissions,_),j(_))},re=_=>{if(_.schema)return Q(_.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")},Me=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(bs(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 Me();A=A.withExecutionContext(fe);const be=new Map,se={plugins:o,preplannedPartitions:be,resolveSchema:Q,...y.connectionId?{preferredConnectionId:y.connectionId}:{},canUsePropertyRowIdentity:(_,T)=>Rt(y.permissions,_.id,T)},Re=async(_,T)=>{const k=await q(_,re(_));return be.set(JSON.stringify(_),k),Qs(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=Se(o).find(Ee=>Ee.createTimeWatermarkLogicform)?.createTimeWatermarkLogicform;if(!v)return;const G=v({logicform:c,rootSchema:_,rootProperty:T,requestedUpperBound:k,now:L,...y.timeWatermark?{defaultPolicy:y.timeWatermark}:{},resolveSchema:Q,inferPropertyPath:(Ee,me,_e)=>Sa(Ee,me,_e,Q)}),z=Nt(G,y.permissions,Q,!1,new Set,o),W=await pt(z,_,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,resolveFromSchema:Re}),ee=Le(W,_,A,g,se);if(w(ee))return;let de;if(Or(ee,g)){const Ee=y.providerForConnection;if(!Ee)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:Ee,maxMaterializedRows:y.federation?.maxMaterializedRows??1e5,...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:({compiled:_e,sources:Ne,logicform:he,provider:xe,connectionId:ve})=>V(_e,"semantic-resolution",he,"time-watermark",xe,ve,Ne)})).rows}else{ni(ee,y);const Ee=$e(ee,y.provider,A),me=Te(ee);V(Ee,"semantic-resolution",W,"time-watermark",y.provider,y.connectionId,me),de=await x(Ee,me)}const ge=de[0]?.__timeWatermark__??Object.values(de[0]??{})[0];if(ge==null||!(ge instanceof Date)&&typeof ge!="string"&&typeof ge!="number")return;const we=ge instanceof Date?ge:new Date(ge);return Number.isNaN(we.getTime())?void 0:we})();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 pt(v,_,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,resolveFromSchema:Re}),z=Le(G,_,A,g,se);if(w(z))return{empty:!0};let W;if(Or(z,g)){const Ne=y.providerForConnection;if(!Ne)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:Ne,maxMaterializedRows:y.federation?.maxMaterializedRows??1e5,...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:({compiled:xe,sources:ve,logicform:Tt,provider:Ye,connectionId:Fe})=>V(xe,"semantic-resolution",Tt,"auto-case",Ye,Fe,ve)})).rows}else{ni(z,y);const Ne=$e(z,y.provider,A),he=Te(z);V(Ne,"semantic-resolution",G,"auto-case",y.provider,y.connectionId,he),W=await x(Ne,he)}const ee=W[0],de=ee?.__autoCaseMin__,ge=ee?.__autoCaseMax__,we=ee?.__autoCaseCount__;if(de==null||ge===null||ge===void 0||we===null||we===void 0||Number(we)===0)return{empty:!0};const Ee=Number(de),me=Number(ge),_e=Number(we);if(!Number.isFinite(Ee)||!Number.isFinite(me)||!Number.isSafeInteger(_e)||_e<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:ge,count:we});return{min:Ee,max:me,count:_e}})();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 gt([...g.definitions().filter(({schemaId:_e})=>_e!==G),W],o):g,de=W?.connectionId??y.connectionId,ge=W?y.providerForConnection?.(W.connectionId)??(W.connectionId===y.connectionId?y.provider:void 0):y.provider;if(!ge)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED",`Pinned mapping ${z} requires a provider for ${de}`);const{onProgress:we,...Ee}=y,me=await ii(Y,{...Ee,schemaMappings:ee,provider:ge,...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(_e=>({..._e,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 nc(T,U.shards,g),Promise.all(U.shards.map(async Y=>{const v=await pt({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:Q,resolveFromSchema:Re,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 Le(_,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:rc(_.query,v.query)};try{return Le(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:we,...Ee})=>Ee)}:{}},ge=new gt([...g.definitions().filter(({schemaId:we})=>we!==T.id),de],o);return Le(z,T,A,ge,{...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}),tf(y.permissions,j);const _=re(c);await M({stage:"validated",schema:_});const T=Nt(c,y.permissions,Q,!0,new Set,o),k=await pt(T,_,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,resolveFromSchema:Re,canProjectProperty:(P,H)=>Rt(y.permissions,P.id,H),requestTimeWatermark:b,requestAutoCaseBounds:O});await M({stage:"normalized",normedLogicform:k},{normedLogicform:k});const U=async P=>{if(De(P)){await U(P.from),await U(P.query),await U(P.preds);const H=JSON.stringify(P);!be.has(H)&&P.schema&&!P.from&&Q(P.schema).partition&&be.set(H,await q(P,Q(P.schema)));return}if(Array.isArray(P)){for(const H of P)await U(H);return}if(!(typeof P!="object"||P===null||P instanceof Date))for(const H of Object.values(P))await U(H)};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=Fs(B,_);K.set(G.id,G),await M({stage:"planned",plan:B},{schema:G});const z=ps(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.now()-$});const H=k.output?Vn(k.output.type,o):void 0;return{result:P,total:0,schema:G,normedLogicform:k,sqls:[],lineage:z,...H?{output:await H.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 H=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:Ie,sources:pe,type:ce,logicform:Ce,provider:Ae,connectionId:Ge})=>V(Ie,ce,Ce,ce,Ae,Ge,pe)});await M({stage:"compiled",sqls:[...N]},{sqls:[...N]}),await M({stage:"executing",provider:"duckdb",connectionId:Nr}),await M({stage:"hydrating"});const X=H.connections.length===1?H.connections[0]?.connectionId:void 0,J=await xa(H.rows,v,{semanticTypes:E,plugins:o,resolveSchema:Q,fetchEntities:Ie=>Ua(Ie,{version:k.version,operators:A,schemaMappings:g,semanticTypes:E,plugins:o,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,...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,Ce,Ae,Ge)=>V(pe,"semantic-resolution",ce,"entity-expansion",Ce,Ae,Ge)})}),ne=Po(J,B.rowIdentity);return await M({stage:"result",result:ne},{result:ne,total:H.total,sqls:[...N]}),await M({stage:"completed",durationMs:Lr.now()-$}),{result:ne,total:H.total,schema:G,normedLogicform:k,sqls:[...N],lineage:z}}const W=an(k,B,_,A,Q,void 0,r,n.translator(r)),ee=new WeakMap;for(const P of W??[]){if("logicform"in P&&P.partitionQuery&&P.partitionCurrentLogicform){const H=re(P.partitionCurrentLogicform),X=await C(P.partitionCurrentLogicform,H);if(X){const J=ri(P.partitionCurrentLogicform,H,X,A,g,se,{logicform:P.logicform,queryForCurrentShard:P.partitionQuery});ee.set(P.logicform,J.comparison)}}if("components"in P)for(const H of P.components){if(!H.comparisonOf||!H.partitionQuery)continue;const X=P.components.find(({name:pe})=>pe===H.comparisonOf);if(!X)throw new d("INVALID_COMPONENT_COMPARISON",`Comparison component ${H.name} has no current component ${H.comparisonOf}`);const J=re(X.logicform),ne=await C(X.logicform,J);if(!ne)continue;const Ie=ri(X.logicform,J,ne,A,g,se,{logicform:H.logicform,queryForCurrentShard:H.partitionQuery});ee.set(X.logicform,Ie.current),ee.set(H.logicform,Ie.comparison)}}const de=async(P,H)=>{const X=H&&P.logicform.schema===H.id?H:re(P.logicform),J=P.prepare?await pt(Nt(P.logicform,y.permissions,Q,!0,new Set,o),X,{semanticTypes:E,operators:A,plugins:o,now:L,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,resolveFromSchema:Re,canProjectProperty:(pe,ce)=>Rt(y.permissions,pe.id,ce),requestTimeWatermark:b}):P.logicform,ne=ee.get(P.logicform)??await q(J,X),Ie=an(J,ne,X,A,Q,P.logicform,r,n.translator(r));if(Ie){if(Ie.length!==1)throw new Error("A generated component must produce exactly one execution unit");const pe=Ie[0];if("logicform"in pe){const Ae=await de(pe,X),Ge=Ae.component.mapResult,Xe=P.mapResult;return{...Ae,component:{...P,logicform:Ae.component.logicform,...Ge||Xe?{mapResult:Ze=>{const ft=Ge?.(Ze)??[...Ze];return Xe?.(ft)??[...ft]}}:{}}}}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 Ae=>({name:Ae.name,prepared:await de(_n(Ae)),...Ae.groupKeyShifts?{groupKeyShifts:Ae.groupKeyShifts}:{},...Ae.joinKeys?{joinKeys:Ae.joinKeys}:{}}))),Ce=nn(pe,ce.map(({name:Ae,prepared:Ge,...Xe})=>({name:Ae,plan:Ge.plan,...Xe})),ne,pe.outputName,y.provider,A);return{component:{...P,logicform:J},plan:ne,compiled:Ce,sources:Xt(ce.map(({prepared:Ae})=>Ae.sources))}}return{component:{...P,logicform:J},plan:ne,compiled:$e(ne,y.provider,A),sources:Te(ne)}},ge=async(P,H)=>{const X=an(P,H,re(P),A,Q,void 0,r,n.translator(r));if(!X)return{compiled:$e(H,y.provider,A),sources:Te(H)};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:Ce})=>Ce).filter(Ce=>!H.groupBy.some(Ae=>Ae.name===Ce))}}if("mergeRow"in ne)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const Ie=await Promise.all(ne.components.map(async ce=>{const Ce=await de(_n(ce));return{name:ce.name,plan:Ce.plan,...ce.joinKeys?{joinKeys:ce.joinKeys}:{},...ce.groupKeyShifts?{groupKeyShifts:ce.groupKeyShifts}:{}}})),pe=nn(ne,Ie,H,ne.outputName,y.provider,A);return{plan:H,compiled:pe,outputs:[ne.outputName,...ne.components.map(ce=>ce.name)]}}));return{compiled:No(J,H,y.provider,A),sources:Xt(J.map(({plan:ne})=>Te(ne)))}},we=new WeakMap,Ee=async P=>{if(!P.sourcePlan||!P.sourceLogicform)return $e(P,y.provider,A);const H=ye(P.sourceLogicform),X=an(P.sourceLogicform,P.sourcePlan,H,A,Q,void 0,r,n.translator(r));if(X?.some(ce=>"mergeRow"in ce)){const ce=we.get(P.sourcePlan);if(ce){const ue={...P};delete ue.sourcePlan,delete ue.sourceLogicform;const at=$e({...ue,sourceSql:ce.sql,source:P.source},y.provider,A,ce.parameters.length);return{sql:at.sql,parameters:[...ce.parameters,...at.parameters]}}const Ce=await Promise.all(X.map(async ue=>{if("logicform"in ue)return{kind:"query",unit:ue,prepared:await de(ue,H)};const at=await Promise.all(ue.components.map(async Oe=>({input:Oe,prepared:await de(_n(Oe),H)})));return"mergeRow"in ue?{kind:"js",unit:ue,components:at}:{kind:"component",unit:ue,components:at,compiled:nn(ue,at.map(({input:Oe,prepared:qe})=>({name:Oe.name,plan:qe.plan,...Oe.joinKeys?{joinKeys:Oe.joinKeys}:{},...Oe.groupKeyShifts?{groupKeyShifts:Oe.groupKeyShifts}:{}})),P.sourcePlan,ue.outputName,y.provider,A)}})),Ae=P.sourcePlan.groupBy.map(({name:ue})=>ue),Ge=await Promise.all(Ce.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 Oe=await x(ue.prepared.compiled,ue.prepared.sources),qe=await bt(Oe,ue.prepared.plan.projections,A);return ue.unit.mapResult?.(qe)??qe}if(ue.kind==="component"){const Oe=Xt(ue.components.map(({prepared:qe})=>qe.sources));return V(ue.compiled,"computation",P.sourceLogicform,"computation",y.provider,y.connectionId,Oe),x(ue.compiled,Oe)}const at=await Promise.all(ue.components.map(async({input:Oe,prepared:qe})=>{V(qe.compiled,"computation",qe.component.logicform,"computation",y.provider,y.connectionId,qe.sources);const pc=await x(qe.compiled,qe.sources),ci=await bt(pc,qe.plan.projections,A);return Oe.mapResult?.(ci)??ci}));return Promise.all(Do(at,Ae).map(async Oe=>({...Oe,[ue.unit.outputName]:await ue.unit.mergeRow(Oe)})))})),Xe=Mo(Ge,P.sourcePlan),Ze=y.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(Xe.length>Ze)throw new d("MATERIALIZED_RESULT_LIMIT_EXCEEDED",`Nested component materialized ${Xe.length} rows; maximum is ${Ze}`,{materializedRowCount:Xe.length,maxMaterializedRows:Ze});const ft=xm(Xe,P.sourcePlan,y.provider);we.set(P.sourcePlan,ft);const Rn={...P};delete Rn.sourcePlan,delete Rn.sourceLogicform;const ai=$e({...Rn,sourceSql:ft.sql,source:P.source},y.provider,A,ft.parameters.length);return{sql:ai.sql,parameters:[...ft.parameters,...ai.parameters]}}const J=await ge(P.sourceLogicform,P.sourcePlan),ne={...P};delete ne.sourcePlan,delete ne.sourceLogicform;const Ie={...ne,sourceSql:J.compiled.sql,source:P.source},pe=$e(Ie,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 H=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:H.map(({prepared:J})=>J)};const X=H.map(({name:J,prepared:ne,...Ie})=>({name:J,plan:ne.plan,...Ie}));return{kind:"component",unit:P,plan:B,compiled:nn(P,X,B,P.outputName,y.provider,A),sources:Xt(H.map(({prepared:J})=>J.sources))}})):void 0,_e=me&&Bm(me,g,B)?me.map(P=>{const H=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=>!H.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,Ne=_e?No(_e,B,y.provider,A):void 0,he=me?void 0:await Ee(B),xe=Te(B),ve=B.sourcePlan&&we.has(B.sourcePlan)?[]:xe,Tt=Ne?Xt([...me.map(P=>P.sources),xe]):void 0,Ye=Ne?Xt([...me.map(P=>P.sources),ve]):void 0,Fe=Zo(B),Pt=B.pagination&&(Ne||he)?ei(_e?No(_e,Fe,y.provider,A):await Ee(Fe),y.provider):void 0;if(Ne)V(Ne,"computation",k,"computation",y.provider,y.connectionId,Ye);else if(me)for(const P of me)if(P.kind==="js")for(const H of P.components)V(H.compiled,"computation",H.component.logicform,"computation",y.provider,y.connectionId,H.sources);else V(P.compiled,"computation",k,"computation",y.provider,y.connectionId,P.sources);else V(he,"computation",k,"computation",y.provider,y.connectionId,ve);Pt&&V(Pt,"total",Pm(k),"total",y.provider,y.connectionId,Ye??ve),await M({stage:"compiled",sqls:[...N]},{sqls:[...N]}),await M({stage:"executing",provider:y.provider.kind});const cc=Ne?await(async()=>{const P=Tt,[H,X]=await Promise.all([x(Ne,P),Pt?x(Pt,P):Promise.resolve(void 0)]),J=await bt(H,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 Ie=await Promise.all(X.components.map(async pe=>{const ce=await x(pe.compiled,pe.sources),Ce=await bt(ce,pe.plan.projections,A);return pe.component.mapResult?.(Ce)??Ce}));return Promise.all(Do(Ie,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 bt(J,X.plan.projections,A):J;return X.kind==="query"?X.unit.mapResult?.(ne)??ne:ne})),H=Mo(P,B);return{rows:H,total:B.pagination?Mo(P,Fe).length:H.length}})():await(async()=>{const P=xe,[H,X]=await Promise.all([x(he,P),Pt?x(Pt,P):Promise.resolve(void 0)]),J=await bt(H,B.projections,A);return{rows:J,total:X?wn(X):J.length}})(),{rows:uc,total:si}=cc;await M({stage:"hydrating"});const dc=await xa(uc,v,{semanticTypes:E,plugins:o,resolveSchema:Q,fetchEntities:P=>Ua(P,{version:k.version,operators:A,schemaMappings:g,semanticTypes:E,plugins:o,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:Q,...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:(H,X,J,ne,Ie)=>V(H,"semantic-resolution",X,"entity-expansion",J,ne,Ie)})}),Pr=Po(dc,B.rowIdentity);return await M({stage:"result",result:Pr},{result:Pr,total:si,sqls:[...N]}),await M({stage:"completed",durationMs:Lr.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=sc(_);try{await M({stage:"failed",error:T})}catch{}throw T}},Fm=async(t,e)=>{let r={};const n=e.locale??"zh-CN",o=qr(ic(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=ac(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?Rs(e.schemas,e.schemaMappings,p,s,e.connections.map(({id:N})=>N)):e.schemaMappings,m=new gt(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):Cs(e.semanticTypes,e.plugins??[]),{cache:I,...S}=e,R=I?await Ca(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 jm(i,t,r,n,o)}},Qm=Object.freeze({execute:Fm,close:Ja});export{Sm as DBConnector,Cn as LocaleRegistry,Qm as Logicform,er as OperatorRegistry,Us as PlannerSemanticRegistry,za as ProviderRegistry,Af as QueryCacheManager,gt as SchemaMappingRegistry,d as SemanticDBError,fo as SemanticTypeRegistry,Ap as builtinOperators,ao as builtinSemanticTypes,qr as createLocaleRegistry,Qe as createOperatorRegistry,qs as createPlannerSemanticRegistry,Xr as createSemanticTypeRegistry,kr as defaultLocaleRegistry,Li as enUS,Jp as fromYiAskSchemaMapping,dr as getLogicformPropertyReferences,Wp as getSupportedDimensions,jp as isDimensionInLogicform,as as resolveOperator,mo as resolveSchema,Ns as validateResolvedSchema,Ci as zhCN};
|
|
1
|
+
import he from"dayjs";import Fr from"dayjs/plugin/isoWeek.js";import{createHash as Sn,randomUUID as Br,randomInt as Vu}from"node:crypto";import $s from"dayjs/plugin/customParseFormat.js";import Nn from"dayjs/plugin/quarterOfYear.js";import{performance as Rn}from"node:perf_hooks";import{getNameProperty as Fu}from"semanticdb-core";import{isDeepStrictEqual as Ro}from"node:util";import{createClient as Bu}from"redis";import{join as Hr,resolve as Es,extname as Hu}from"node:path";import{jsToDuckDBValue as $t,TIMESTAMP as Oo,blobValue as Qu,DuckDBInstance as To,dateValue as Yu,timestampValue as vu,ResultReturnType as Is,VARCHAR as lr,DOUBLE as _s,BOOLEAN as bs}from"@duckdb/node-api";import{readFile as Ss,mkdir as Ns,open as Rs,rm as Po,rename as Gu,stat as zu}from"node:fs/promises";import{setTimeout as Wu}from"node:timers/promises";import{parse as Ku}from"csv-parse/sync";import Ju from"exceljs";const se=t=>typeof t=="string",Qr=()=>{let t,e;const r=new Promise((n,o)=>{t=n,e=o});return r.resolve=t,r.reject=e,r},Os=t=>t==null?"":""+t,Xu=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},Zu=/###/g,Ts=t=>t&&t.indexOf("###")>-1?t.replace(Zu,"."):t,Ps=t=>!t||se(t),Yr=(t,e,r)=>{const n=se(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if(Ps(t))return{};const i=Ts(n[o]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++o}return Ps(t)?{}:{obj:t,k:Ts(n[o])}},Ls=(t,e,r)=>{const{obj:n,k:o}=Yr(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=Yr(t,s,Object);for(;a.obj===void 0&&s.length;)i=`${s[s.length-1]}.${i}`,s=s.slice(0,s.length-1),a=Yr(t,s,Object),a?.obj&&typeof a.obj[`${a.k}.${i}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${i}`]=r},ed=(t,e,r,n)=>{const{obj:o,k:i}=Yr(t,e,Object);o[i]=o[i]||[],o[i].push(r)},On=(t,e)=>{const{obj:r,k:n}=Yr(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},td=(t,e,r)=>{const n=On(t,r);return n!==void 0?n:On(e,r)},Cs=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(n in t?se(t[n])||t[n]instanceof String||se(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):Cs(t[n],e[n],r):t[n]=e[n]);return t},Yt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var rd={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const nd=t=>se(t)?t.replace(/[&<>"'\/]/g,e=>rd[e]):t;class od{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 id=[" ",",","?","!",";"],sd=new od(20),ad=(t,e,r)=>{e=e||"",r=r||"";const n=id.filter(s=>e.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=sd.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},Lo=(t,e,r=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const n=e.split(r);let o=t;for(let i=0;i<n.length;){if(!o||typeof o!="object")return;let s,a="";for(let u=i;u<n.length;++u)if(u!==i&&(a+=r),a+=n[u],s=o[a],s!==void 0){if(["string","number","boolean"].indexOf(typeof s)>-1&&u<n.length-1)continue;i+=u-i+1;break}o=s}return o},vr=t=>t?.replace(/_/g,"-"),cd={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 Io{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||cd,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:(se(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new Io(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Io(this.logger,e)}}var pt=new Io;class Tn{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 Ds extends Tn{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):se(n)&&i?a.push(...n.split(i)):a.push(n)));const u=On(this.data,a);return!u&&!r&&!n&&e.indexOf(".")>-1&&(e=a[0],r=a[1],n=a.slice(2).join(".")),u||!s||!se(n)?u:Lo(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),Ls(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)(se(n[i])||Array.isArray(n[i]))&&this.addResource(e,r,i,n[i],{silent:!0});o.silent||this.emit("added",e,r,n)}addResourceBundle(e,r,n,o,i,s={silent:!1,skipCopy:!1}){let a=[e,r];e.indexOf(".")>-1&&(a=e.split("."),o=n,n=r,r=a[1]),this.addNamespaces(r);let u=On(this.data,a)||{};s.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?Cs(u,n,i):u={...u,...n},Ls(this.data,a,u),s.silent||this.emit("added",e,r,n)}removeResourceBundle(e,r){this.hasResourceBundle(e,r)&&delete this.data[e][r],this.removeNamespaces(r),this.emit("removed",e,r)}hasResourceBundle(e,r){return this.getResource(e,r)!==void 0}getResourceBundle(e,r){return r||(r=this.options.defaultNS),this.getResource(e,r)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const r=this.getDataByLanguage(e);return!!(r&&Object.keys(r)||[]).find(o=>r[o]&&Object.keys(r[o]).length>0)}toJSON(){return this.data}}var Ms={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 ks=Symbol("i18next/PATH_KEY");function ud(){const t=[],e=Object.create(null);let r;return e.get=(n,o)=>(r?.revoke?.(),o===ks?t:(t.push(o),r=Proxy.revocable(n,e),r.proxy)),Proxy.revocable(Object.create(null),e).proxy}function fr(t,e){const{[ks]:r}=t(ud()),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 Us={},Co=t=>!se(t)&&typeof t!="boolean"&&typeof t!="number";class _o extends Tn{constructor(e,r={}){super(),Xu(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=pt.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=Co(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&&!ad(e,n,o);if(s&&!a){const u=e.match(this.interpolator.nestingRegexp);if(u&&u.length>0)return{key:e,namespaces:se(i)?[i]:i};const c=e.split(n);(n!==o||n===o&&this.options.ns.indexOf(c[0])>-1)&&(i=c.shift()),e=c.join(o)}return{key:e,namespaces:se(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=fr(e,{...this.options,...o})),Array.isArray(e)||(e=[String(e)]),e=e.map(L=>typeof L=="function"?fr(L,{...this.options,...o}):String(L));const i=o.returnDetails!==void 0?o.returnDetails:this.options.returnDetails,s=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,{key:a,namespaces:u}=this.extractFromKey(e[e.length-1],o),c=u[u.length-1];let d=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;d===void 0&&(d=":");const p=o.lng||this.language,f=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(p?.toLowerCase()==="cimode")return f?i?{res:`${c}${d}${a}`,usedKey:a,exactUsedKey:a,usedLng:p,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:`${c}${d}${a}`:i?{res:a,usedKey:a,exactUsedKey:a,usedLng:p,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:a;const m=this.resolve(e,o);let h=m?.res;const y=m?.usedKey||a,$=m?.exactUsedKey||a,w=["[object Number]","[object Function]","[object RegExp]"],E=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,N=!this.i18nFormat||this.i18nFormat.handleAsObject,I=o.count!==void 0&&!se(o.count),S=_o.hasDefaultValue(o),D=I?this.pluralResolver.getSuffix(p,o.count,o):"",b=o.ordinal&&I?this.pluralResolver.getSuffix(p,o.count,{ordinal:!1}):"",T=I&&!o.ordinal&&o.count===0,M=T&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${D}`]||o[`defaultValue${b}`]||o.defaultValue;let Y=h;N&&!h&&S&&(Y=M);const C=Co(Y),O=Object.prototype.toString.apply(Y);if(N&&Y&&C&&w.indexOf(O)<0&&!(se(E)&&Array.isArray(Y))){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const L=this.options.returnedObjectHandler?this.options.returnedObjectHandler(y,Y,{...o,ns:u}):`key '${a} (${this.language})' returned an object instead of string.`;return i?(m.res=L,m.usedParams=this.getUsedParamsDetails(o),m):L}if(s){const L=Array.isArray(Y),q=L?[]:{},Q=L?$:y;for(const j in Y)if(Object.prototype.hasOwnProperty.call(Y,j)){const oe=`${Q}${s}${j}`;S&&!h?q[j]=this.translate(oe,{...o,defaultValue:Co(M)?M[j]:void 0,joinArrays:!1,ns:u}):q[j]=this.translate(oe,{...o,joinArrays:!1,ns:u}),q[j]===oe&&(q[j]=Y[j])}h=q}}else if(N&&se(E)&&Array.isArray(h))h=h.join(E),h&&(h=this.extendTranslation(h,e,o,n));else{let L=!1,q=!1;!this.isValidLookup(h)&&S&&(L=!0,h=M),this.isValidLookup(h)||(q=!0,h=a);const j=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&q?void 0:h,oe=S&&M!==h&&this.options.updateMissing;if(q||L||oe){if(this.logger.log(oe?"updateKey":"missingKey",p,c,a,oe?M:h),s){const F=this.resolve(a,{...o,keySeparator:!1});F&&F.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 H=[];const R=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&R&&R[0])for(let F=0;F<R.length;F++)H.push(R[F]);else this.options.saveMissingTo==="all"?H=this.languageUtils.toResolveHierarchy(o.lng||this.language):H.push(o.lng||this.language);const x=(F,G,ee)=>{const ue=S&&ee!==h?ee:j;this.options.missingKeyHandler?this.options.missingKeyHandler(F,c,G,ue,oe,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(F,c,G,ue,oe,o),this.emit("missingKey",F,c,G,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&I?H.forEach(F=>{const G=this.pluralResolver.getSuffixes(F,o);T&&o[`defaultValue${this.options.pluralSeparator}zero`]&&G.indexOf(`${this.options.pluralSeparator}zero`)<0&&G.push(`${this.options.pluralSeparator}zero`),G.forEach(ee=>{x([F],a+ee,o[`defaultValue${ee}`]||M)})}):x(H,a,M))}h=this.extendTranslation(h,e,o,m,n),q&&h===a&&this.options.appendNamespaceToMissingKey&&(h=`${c}${d}${a}`),(q||L)&&this.options.parseMissingKeyHandler&&(h=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${d}${a}`:a,L?h:void 0,o))}return i?(m.res=h,m.usedParams=this.getUsedParamsDetails(o),m):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 u=se(e)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let c;if(u){const p=e.match(this.interpolator.nestingRegexp);c=p&&p.length}let d=n.replace&&!se(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(d={...this.options.interpolation.defaultVariables,...d}),e=this.interpolator.interpolate(e,d,n.lng||this.language||o.usedLng,n),u){const p=e.match(this.interpolator.nestingRegexp),f=p&&p.length;c<f&&(n.nest=!1)}!n.lng&&o&&o.res&&(n.lng=this.language||o.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...p)=>i?.[0]===p[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${p[0]} in key: ${r[0]}`),null):this.translate(...p,r),n)),n.interpolation&&this.interpolator.reset()}const s=n.postProcess||this.options.postProcess,a=se(s)?[s]:s;return e!=null&&a?.length&&n.applyPostProcessor!==!1&&(e=Ms.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 se(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(u=>typeof u=="function"?fr(u,{...this.options,...r}):u)),e.forEach(u=>{if(this.isValidLookup(n))return;const c=this.extractFromKey(u,r),d=c.key;o=d;let p=c.namespaces;this.options.fallbackNS&&(p=p.concat(this.options.fallbackNS));const f=r.count!==void 0&&!se(r.count),m=f&&!r.ordinal&&r.count===0,h=r.context!==void 0&&(se(r.context)||typeof r.context=="number")&&r.context!=="",y=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);p.forEach($=>{this.isValidLookup(n)||(a=$,!Us[`${y[0]}-${$}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(Us[`${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(w=>{if(this.isValidLookup(n))return;s=w;const E=[d];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(E,d,w,$,r);else{let I;f&&(I=this.pluralResolver.getSuffix(w,r.count,r));const S=`${this.options.pluralSeparator}zero`,D=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(r.ordinal&&I.indexOf(D)===0&&E.push(d+I.replace(D,this.options.pluralSeparator)),E.push(d+I),m&&E.push(d+S)),h){const b=`${d}${this.options.contextSeparator||"_"}${r.context}`;E.push(b),f&&(r.ordinal&&I.indexOf(D)===0&&E.push(b+I.replace(D,this.options.pluralSeparator)),E.push(b+I),m&&E.push(b+S))}}let N;for(;N=E.pop();)this.isValidLookup(n)||(i=N,n=this.getResource(w,$,N,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&&!se(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 qs{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=pt.create("languageUtils")}getScriptPartFromCode(e){if(e=vr(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=vr(e),!e||e.indexOf("-")<0)return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(se(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)),se(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 se(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))):se(e)&&i(this.formatLanguageCode(e)),n.forEach(s=>{o.indexOf(s)<0&&i(this.formatLanguageCode(s))}),o}}const js={zero:0,one:1,two:2,few:3,many:4,other:5},xs={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class dd{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=pt.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=vr(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!"),xs;if(!e.match(/-|_/))return xs;const u=this.languageUtils.getLanguagePartFromCode(e);s=this.getRule(u,r)}return this.pluralRulesCache[i]=s,s}needsPlural(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,r,n={}){return this.getSuffixes(e,n).map(o=>`${r}${o}`)}getSuffixes(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?n.resolvedOptions().pluralCategories.sort((o,i)=>js[o]-js[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 Vs=(t,e,r,n=".",o=!0)=>{let i=td(t,e,r);return!i&&o&&se(r)&&(i=Lo(t,r,n),i===void 0&&(i=Lo(e,r,n))),i},Do=t=>t.replace(/\$/g,"$$$$");class Fs{constructor(e={}){this.logger=pt.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(r=>r),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:r,escapeValue:n,useRawValueToEscape:o,prefix:i,prefixEscaped:s,suffix:a,suffixEscaped:u,formatSeparator:c,unescapeSuffix:d,unescapePrefix:p,nestingPrefix:f,nestingPrefixEscaped:m,nestingSuffix:h,nestingSuffixEscaped:y,nestingOptionsSeparator:$,maxReplaces:w,alwaysFormat:E}=e.interpolation;this.escape=r!==void 0?r:nd,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):u||"}}",this.formatSeparator=c||",",this.unescapePrefix=d?"":p||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=f?Yt(f):m||Yt("$t("),this.nestingSuffix=h?Yt(h):y||Yt(")"),this.nestingOptionsSeparator=$||",",this.maxReplaces=w||1e3,this.alwaysFormat=E!==void 0?E:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(r,n)=>r?.source===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,r,n,o){let i,s,a;const u=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=m=>{if(m.indexOf(this.formatSeparator)<0){const w=Vs(r,u,m,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(w,void 0,n,{...o,...r,interpolationkey:m}):w}const h=m.split(this.formatSeparator),y=h.shift().trim(),$=h.join(this.formatSeparator).trim();return this.format(Vs(r,u,y,this.options.keySeparator,this.options.ignoreJSONStructure),$,n,{...o,...r,interpolationkey:y})};this.resetRegExp();const d=o?.missingInterpolationHandler||this.options.missingInterpolationHandler,p=o?.interpolation?.skipOnVariables!==void 0?o.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:m=>Do(m)},{regex:this.regexp,safeValue:m=>this.escapeValue?Do(this.escape(m)):Do(m)}].forEach(m=>{for(a=0;i=m.regex.exec(e);){const h=i[1].trim();if(s=c(h),s===void 0)if(typeof d=="function"){const $=d(e,i,o);s=se($)?$:""}else if(o&&Object.prototype.hasOwnProperty.call(o,h))s="";else if(p){s=i[0];continue}else this.logger.warn(`missed to pass in variable ${h} for interpolating ${e}`),s="";else!se(s)&&!this.useRawValueToEscape&&(s=Os(s));const y=m.safeValue(s);if(e=e.replace(i[0],y),p?(m.regex.lastIndex+=s.length,m.regex.lastIndex-=i[0].length):m.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,r,n={}){let o,i,s;const a=(u,c)=>{const d=this.nestingOptionsSeparator;if(u.indexOf(d)<0)return u;const p=u.split(new RegExp(`${Yt(d)}[ ]*{`));let f=`{${p[1]}`;u=p[0],f=this.interpolate(f,s);const m=f.match(/'/g),h=f.match(/"/g);((m?.length??0)%2===0&&!h||(h?.length??0)%2!==0)&&(f=f.replace(/'/g,'"'));try{s=JSON.parse(f),c&&(s={...c,...s})}catch(y){return this.logger.warn(`failed parsing options string in nesting for key ${u}`,y),`${u}${d}${f}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,u};for(;o=this.nestingRegexp.exec(e);){let u=[];s={...n},s=s.replace&&!se(s.replace)?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;const c=/{.*}/.test(o[1])?o[1].lastIndexOf("}")+1:o[1].indexOf(this.formatSeparator);if(c!==-1&&(u=o[1].slice(c).split(this.formatSeparator).map(d=>d.trim()).filter(Boolean),o[1]=o[1].slice(0,c)),i=r(a.call(this,o[1].trim(),s),s),i&&o[0]===e&&!se(i))return i;se(i)||(i=Os(i)),i||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${e}`),i=""),u.length&&(i=u.reduce((d,p)=>this.format(d,p,n.lng,{...n,interpolationkey:o[1].trim()}),i.trim())),e=e.replace(o[0],i),this.regexp.lastIndex=0}return e}}const pd=t=>{let e=t.toLowerCase().trim();const r={};if(t.indexOf("(")>-1){const n=t.split("(");e=n[0].toLowerCase().trim();const o=n[1].substring(0,n[1].length-1);e==="currency"&&o.indexOf(":")<0?r.currency||(r.currency=o.trim()):e==="relativetime"&&o.indexOf(":")<0?r.range||(r.range=o.trim()):o.split(";").forEach(s=>{if(s){const[a,...u]=s.split(":"),c=u.join(":").trim().replace(/^'+|'+$/g,""),d=a.trim();r[d]||(r[d]=c),c==="false"&&(r[d]=!1),c==="true"&&(r[d]=!0),isNaN(c)||(r[d]=parseInt(c,10))}})}return{formatName:e,formatOptions:r}},Bs=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(vr(n),o),e[s]=a),a(r)}},ld=t=>(e,r,n)=>t(vr(r),n)(e);class fd{constructor(e={}){this.logger=pt.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?Bs:ld;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()]=Bs(r)}format(e,r,n,o={}){const i=r.split(this.formatSeparator);if(i.length>1&&i[0].indexOf("(")>1&&i[0].indexOf(")")<0&&i.find(a=>a.indexOf(")")>-1)){const a=i.findIndex(u=>u.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,a)].join(this.formatSeparator)}return i.reduce((a,u)=>{const{formatName:c,formatOptions:d}=pd(u);if(this.formats[c]){let p=a;try{const f=o?.formatParams?.[o.interpolationkey]||{},m=f.locale||f.lng||o.locale||o.lng||n;p=this.formats[c](a,m,{...d,...o,...f})}catch(f){this.logger.warn(f)}return p}else this.logger.warn(`there was no format function for ${c}`);return a},e)}}const md=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class yd extends Tn{constructor(e,r,n,o={}){super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=pt.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=o.maxParallelReads||10,this.readingCalls=0,this.maxRetries=o.maxRetries>=0?o.maxRetries:5,this.retryTimeout=o.retryTimeout>=1?o.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,o.backend,o)}queueLoad(e,r,n,o){const i={},s={},a={},u={};return e.forEach(c=>{let d=!0;r.forEach(p=>{const f=`${c}|${p}`;!n.reload&&this.store.hasResourceBundle(c,p)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?s[f]===void 0&&(s[f]=!0):(this.state[f]=1,d=!1,s[f]===void 0&&(s[f]=!0),i[f]===void 0&&(i[f]=!0),u[p]===void 0&&(u[p]=!0)))}),d||(a[c]=!0)}),(Object.keys(i).length||Object.keys(s).length)&&this.queue.push({pending:s,pendingCount:Object.keys(s).length,loaded:{},errors:[],callback:o}),{toLoad:Object.keys(i),pending:Object.keys(s),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(u)}}loaded(e,r,n){const o=e.split("|"),i=o[0],s=o[1];r&&this.emit("failedLoading",i,s,r),!r&&n&&this.store.addResourceBundle(i,s,n,void 0,void 0,{skipCopy:!0}),this.state[e]=r?-1:2,r&&n&&(this.state[e]=0);const a={};this.queue.forEach(u=>{ed(u.loaded,[i],s),md(u,e),r&&u.errors.push(r),u.pendingCount===0&&!u.done&&(Object.keys(u.loaded).forEach(c=>{a[c]||(a[c]={});const d=u.loaded[c];d.length&&d.forEach(p=>{a[c][p]===void 0&&(a[c][p]=!0)})}),u.done=!0,u.errors.length?u.callback(u.errors):u.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(u=>!u.done)}read(e,r,n,o=0,i=this.retryTimeout,s){if(!e.length)return s(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:r,fcName:n,tried:o,wait:i,callback:s});return}this.readingCalls++;const a=(c,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const p=this.waitingReads.shift();this.read(p.lng,p.ns,p.fcName,p.tried,p.wait,p.callback)}if(c&&d&&o<this.maxRetries){setTimeout(()=>{this.read.call(this,e,r,n,o+1,i*2,s)},i);return}s(c,d)},u=this.backend[n].bind(this.backend);if(u.length===2){try{const c=u(e,r);c&&typeof c.then=="function"?c.then(d=>a(null,d)).catch(a):a(null,c)}catch(c){a(c)}return}return u(e,r,a)}prepareLoading(e,r,n={},o){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),o&&o();se(e)&&(e=this.languageUtils.toResolveHierarchy(e)),se(r)&&(r=[r]);const i=this.queueLoad(e,r,n,o);if(!i.toLoad.length)return i.pending.length||o(),null;i.toLoad.forEach(s=>{this.loadOne(s)})}load(e,r,n){this.prepareLoading(e,r,{},n)}reload(e,r,n){this.prepareLoading(e,r,{reload:!0},n)}loadOne(e,r=""){const n=e.split("|"),o=n[0],i=n[1];this.read(o,i,"read",void 0,void 0,(s,a)=>{s&&this.logger.warn(`${r}loading namespace ${i} for language ${o} failed`,s),!s&&a&&this.logger.log(`${r}loaded namespace ${i} for language ${o}`,a),this.loaded(e,s,a)})}saveMissing(e,r,n,o,i,s={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(r)){this.logger.warn(`did not save key "${n}" as the namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if(this.backend?.create){const u={...s,isUpdate:i},c=this.backend.create.bind(this.backend);if(c.length<6)try{let d;c.length===5?d=c(e,r,n,o,u):d=c(e,r,n,o),d&&typeof d.then=="function"?d.then(p=>a(null,p)).catch(a):a(null,d)}catch(d){a(d)}else c(e,r,n,o,a,u)}!e||!e[0]||this.store.addResource(e[0],r,n,o)}}}const Mo=()=>({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]),se(t[1])&&(e.defaultValue=t[1]),se(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}),Hs=t=>(se(t.ns)&&(t.ns=[t.ns]),se(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),se(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),Pn=()=>{},hd=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})},Qs="__i18next_supportNoticeShown",gd=()=>!!(typeof globalThis<"u"&&globalThis[Qs]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),wd=()=>{typeof globalThis<"u"&&(globalThis[Qs]=!0)},Ad=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 _n extends Tn{constructor(e={},r){if(super(),this.options=Hs(e),this.services={},this.logger=pt,this.modules={external:[]},hd(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&&(se(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const n=Mo();this.options={...n,...this.options,...Hs(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&&!Ad(this)&&!gd()&&(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}"),wd());const o=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?pt.init(o(this.modules.logger),this.options):pt.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=fd;const d=new qs(this.options);this.store=new Ds(this.options.resources,this.options);const p=this.services;p.logger=pt,p.resourceStore=this.store,p.languageUtils=d,p.pluralResolver=new dd(d,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),c&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(p.formatter=o(c),p.formatter.init&&p.formatter.init(p,this.options),this.options.interpolation.format=p.formatter.format.bind(p.formatter)),p.interpolator=new Fs(this.options),p.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},p.backendConnector=new yd(o(this.modules.backend),p.resourceStore,p,this.options),p.backendConnector.on("*",(m,...h)=>{this.emit(m,...h)}),this.modules.languageDetector&&(p.languageDetector=o(this.modules.languageDetector),p.languageDetector.init&&p.languageDetector.init(p,this.options.detection,this.options)),this.modules.i18nFormat&&(p.i18nFormat=o(this.modules.i18nFormat),p.i18nFormat.init&&p.i18nFormat.init(this)),this.translator=new _o(this.services,this.options),this.translator.on("*",(m,...h)=>{this.emit(m,...h)}),this.modules.external.forEach(m=>{m.init&&m.init(this)})}if(this.format=this.options.interpolation.format,r||(r=Pn),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...d)=>this.store[c](...d)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...d)=>(this.store[c](...d),this)});const a=Qr(),u=()=>{const c=(d,p)=>{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(p),r(d,p)};if(this.languages&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?u():setTimeout(u,0),a}loadResources(e,r=Pn){let n=r;const o=se(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(o?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const i=[],s=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(c=>{c!=="cimode"&&i.indexOf(c)<0&&i.push(c)})};o?s(o):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>s(u)),this.options.preload?.forEach?.(a=>s(a)),this.services.backendConnector.load(i,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(a)})}else n(null)}reloadResources(e,r,n){const o=Qr();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=Pn),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"&&Ms.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=Qr();this.emit("languageChanging",e);const o=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},i=(a,u)=>{u?this.isLanguageChangingTo===e&&(o(u),this.translator.changeLanguage(u),this.isLanguageChangingTo=void 0,this.emit("languageChanged",u),this.logger.log("languageChanged",u)):this.isLanguageChangingTo=void 0,n.resolve((...c)=>this.t(...c)),r&&r(a,(...c)=>this.t(...c))},s=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const u=se(a)?a:a&&a[0],c=this.store.hasLanguageSomeTranslations(u)?u:this.services.languageUtils.getBestMatchFromCodes(se(a)?[a]:a);c&&(this.language||o(c),this.translator.language||this.translator.changeLanguage(c),this.services.languageDetector?.cacheUserLanguage?.(c)),this.loadResources(c,d=>{i(d,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?s(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(s):this.services.languageDetector.detect(s):s(e),n}getFixedT(e,r,n){const o=(i,s,...a)=>{let u;typeof s!="object"?u=this.options.overloadTranslationOptionHandler([i,s].concat(a)):u={...s},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs,u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||n||o.keyPrefix);const c={...this.options,...u};typeof u.keyPrefix=="function"&&(u.keyPrefix=fr(u.keyPrefix,c));const d=this.options.keySeparator||".";let p;return u.keyPrefix&&Array.isArray(i)?p=i.map(f=>(typeof f=="function"&&(f=fr(f,c)),`${u.keyPrefix}${d}${f}`)):(typeof i=="function"&&(i=fr(i,c)),p=u.keyPrefix?`${u.keyPrefix}${d}${i}`:i),this.t(p,u)};return se(e)?o.lng=e:o.lngs=e,o.ns=r,o.keyPrefix=n,o}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,r={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=r.lng||this.resolvedLanguage||this.languages[0],o=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const s=(a,u)=>{const c=this.services.backendConnector.state[`${a}|${u}`];return c===-1||c===0||c===2};if(r.precheck){const a=r.precheck(this,s);if(a!==void 0)return a}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||s(n,e)&&(!o||s(i,e)))}loadNamespaces(e,r){const n=Qr();return this.options.ns?(se(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=Qr();se(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 qs(Mo());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 _n(e,r);return n.createInstance=_n.createInstance,n}cloneInstance(e={},r=Pn){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const o={...this.options,...e,isClone:!0},i=new _n(o);if((e.debug!==void 0||e.prefix!==void 0)&&(i.logger=i.logger.clone(e)),["store","services","language"].forEach(a=>{i[a]=this[a]}),i.services={...this.services},i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},n){const a=Object.keys(this.store.data).reduce((u,c)=>(u[c]={...this.store.data[c]},u[c]=Object.keys(u[c]).reduce((d,p)=>(d[p]={...u[c][p]},d),u[c]),u),{});i.store=new Ds(a,o),i.services.resourceStore=i.store}if(e.interpolation){const u={...Mo().interpolation,...this.options.interpolation,...e.interpolation},c={...o,interpolation:u};i.services.interpolator=new Fs(c)}return i.translator=new _o(i.services,o),i.translator.on("*",(a,...u)=>{i.emit(a,...u)}),i.init(o,r),i.translator.options=o,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Xe=_n.createInstance(),$d=Xe.createInstance;Xe.dir,Xe.init,Xe.loadResources,Xe.reloadResources,Xe.use,Xe.changeLanguage,Xe.getFixedT,Xe.t,Xe.exists,Xe.setDefaultNamespace,Xe.hasLoadedNamespace,Xe.loadNamespaces,Xe.loadLanguages;const Ys={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.DATABASE_CONNECTION_REQUIRED":"At least one database connection is required","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"}},vs={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.DATABASE_CONNECTION_REQUIRED":"\u81F3\u5C11\u9700\u8981\u914D\u7F6E\u4E00\u4E2A\u6570\u636E\u5E93\u8FDE\u63A5","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"}},Ed=[vs,Ys],Gr=t=>t.trim().toLowerCase(),Id=t=>t?"locale"in t?[t]:t:[],_d=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 ko{definitions=new Map;i18n;constructor(e){this.i18n=$d(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(Ed),this.register(e)}register(e){for(const r of Id(e)){const n=r;if(!_d(n))throw new TypeError("Locale definition must have a non-empty locale");const o=n,i=this.definitions.get(Gr(o.locale)),s={locale:o.locale,messages:Object.freeze({...i?.messages,...o.messages})};this.definitions.set(Gr(o.locale),s),this.i18n.addResourceBundle(o.locale,"translation",s.messages,!0,!0)}return this}resolve(e="zh-CN"){const r=this.definitions.get(Gr(e));if(r)return r;const n=Gr(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(Gr(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 zr=t=>new ko(t),Ln=new ko;class l extends Error{code;details;constructor(e,r,n){super(r),this.code=e,this.details=n,this.name="SemanticDBError"}localizedMessage(e="zh-CN",r=Ln){if(this.code==="DATABASE_CONNECTION_REQUIRED")return r.translate(e,"error.DATABASE_CONNECTION_REQUIRED",this.message);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,u=this.details?.property,c=this.details?.propertyName;if(typeof s=="string"&&typeof a=="string"&&typeof u=="string"&&typeof c=="string")return`Property not found in Schema: ${a}(${s}): ${c}`}return this.message}}const bd=({source:t,properties:e})=>{const r=t.hierarchy;if(!Array.isArray(r))return r===void 0?{}:{hierarchy:r};let n=t.hierarchy_property;if(typeof n!="string"||n.length===0){const s=e.filter(({type:u})=>u==="ID");if(s.length!==1)throw new l("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}}},Sd=t=>{if(!t.hierarchy)return;const e=t.properties.find(({name:r})=>r===t.hierarchy?.property);if(!e)throw new l("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${t.hierarchy.property}`,{schemaId:t.id,property:t.hierarchy.property});return e},Gs=(t,e)=>t.properties.some(r=>r!==e&&r.id===e.name)?e.id:e.name,Nd=(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)),ne=(t,e,r)=>{const n=t.properties.find(o=>o.id===e)??t.properties.find(o=>o.name===e);if(n)return{canonicalName:Gs(t,n),canonicalId:n.id,schema:t,property:n,relations:[]};for(const{property:o,prefix:i}of Nd(t,e)){if(o.primal_type!=="entity"&&o.primal_type!=="object"||!o.ref)continue;if(!r)throw new l("SCHEMA_RESOLVER_REQUIRED",`Resolving property path ${e} requires a Schema resolver`);const s=r(o.ref),a=ne(s,e.slice(i.length+1),r);return{canonicalName:`${Gs(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 l("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})},Rd=(t,e,r)=>{const n=ne(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 l("ARRAY_HIERARCHY_RELATION_UNSUPPORTED",`$hierarchyLevel cannot group an array relation: ${n.canonicalName}`);if(!n.property.ref||!r)throw new l("SCHEMA_RESOLVER_REQUIRED",`$hierarchyLevel requires a Schema resolver for relation ${n.canonicalName}`);return{schema:r(n.property.ref),reference:n.canonicalName,relation:!0}},Od={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 l("INVALID_HIERARCHY_LEVEL_ARGS","$hierarchyLevel args may contain only one non-empty level string",{unsupportedArgs:o});const i=Rd(r,t,n),s=i.schema.hierarchy;if(!s)throw new l("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 l("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${s.property}`);if(!i.relation&&a.name!==ne(r,t,n).property.name)throw new l("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${a.name}`);const u=s.levels.reduce((h,y)=>h+y.codeLength,0),c=i.schema.properties.filter(({type:h})=>h==="ID"),p=i.relation&&c.length===1&&c[0]?.name===a.name?i.reference:i.relation?`${i.reference}_${a.name}`:i.reference;if(e.level===void 0){let h=0;return{reference:p,args:{levels:s.levels.map(({name:y,codeLength:$})=>(h+=$,{name:y,codeLength:h})),totalLength:u,storage:s.storage}}}let f=0;const m=s.levels.find(h=>(f+=h.codeLength,h.name===e.level||h.syno?.includes(e.level)));if(!m)throw new l("HIERARCHY_LEVEL_NOT_FOUND",`Schema ${i.schema.id} does not declare hierarchy level: ${e.level}`,{schemaId:i.schema.id,level:e.level});return{reference:p,args:{level:m.name,codeLength:f,totalLength:u,storage:s.storage}}},toSQL({expression:t,args:e,sql:r}){if(!t)throw new Error("$hierarchyLevel requires a hierarchy pred");if(Array.isArray(e.levels)){const u=e.levels.filter(h=>typeof h=="object"&&h!==null&&!Array.isArray(h)&&typeof h.name=="string"&&Number.isInteger(h.codeLength)),c=e.totalLength,d=e.storage;if(u.length!==e.levels.length||u.length===0||!Number.isInteger(c)||Number(c)<=0||u.some(({name:h,codeLength:y},$)=>h.length===0||y<=0||y>Number(c)||$>0&&y<=Number(u[$-1]?.codeLength))||u.at(-1)?.codeLength!==c||d!=="compact"&&d!=="zero-padded")throw new l("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const p=`WHEN ${t} IS NULL THEN NULL`;if(d==="compact"){const h=r.stringLength(t),y=u.map($=>`WHEN ${h} = ${$.codeLength} THEN ${r.value($.name)}`);return`(CASE ${p} ${y.join(" ")} ELSE NULL END)`}const f=u.slice(0,-1).map(h=>{const y=Number(c)-h.codeLength;return`WHEN ${r.substring(t,h.codeLength+1,y)} = ${r.value("0".repeat(y))} THEN ${r.value(h.name)}`}),m=u.at(-1);return`(CASE ${p} ${f.join(" ")} ELSE ${r.value(m?.name)} END)`}const n=e.codeLength,o=e.totalLength,i=e.storage;if(!Number.isInteger(n)||!Number.isInteger(o)||Number(n)<=0||Number(o)<Number(n)||i!=="compact"&&i!=="zero-padded")throw new l("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}}},mr=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},yr=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),Uo=(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)}},Cn=(t,{schema:e,mapping:r})=>r.mappings?.filter(n=>n.mappingType==="property").find(n=>yr(e,n.propertyId)?.id===t.id),zs=(t,e,r)=>{const n=yr(r.schema,t);if(!n)return`hierarchy property is not available: ${t}`;const o=Uo(n,e,r);if(!o)return`hierarchy level is not available: ${String(e)}`;const i=Cn(n,r);if(!mr(i?.granularity))return;const s=Uo(n,i.granularity.level,r);return s&&s.index>=o.index?void 0:`hierarchy dimension ${t} requires ${o.name}, but source has ${s?.name}`},Td=(t,e)=>{const r=i=>{const s=n(i.query);if(s)return s;if(i.operator==="$hierarchyLevel"&&typeof i.pred=="string")if(i.args?.level!==void 0){const u=zs(i.pred,i.args.level,e);if(u)return u}else{const u=yr(e.schema,i.pred),c=u&&Cn(u,e);if(mr(c?.granularity))return`$hierarchyLevel without args.level is not covered by hierarchy-grained source: ${i.pred}`}const a=Array.isArray(i.pred)?i.pred:i.pred===void 0?[]:[i.pred];for(const u of a){if(typeof u=="string")continue;const c=r(u);if(c)return c}},n=i=>{if(i){for(const[s,a]of Object.entries(i))if(a!==void 0){if(s==="$and"||s==="$or"){if(!Array.isArray(a))continue;for(const u of a){const c=n(u);if(c)return c}}else if(s==="$expr"){if(typeof a!="object"||a===null||Array.isArray(a))continue;const u=a.pred;if(typeof u!="object"||u===null||Array.isArray(u))continue;const c=r(u);if(c)return c}else if(!s.startsWith("$")){const u=yr(e.schema,s),c=u&&Cn(u,e);if(mr(c?.granularity))return`query on hierarchy-grained property requires an explicit $hierarchyLevel: ${s}`}}}},o=n(t.query);if(o)return o;for(const i of t.preds??[]){const s=r(i);if(s)return s}for(const i of t.groupby??[])if(typeof i.pred=="string"){if(i.operator==="$hierarchyLevel"){const s=zs(i.pred,i.args?.level,e);if(s)return s}else if(i.operator===void 0){const s=yr(e.schema,i.pred),a=s&&Cn(s,e);if(mr(a?.granularity))return`raw groupby is not covered by hierarchy-grained source: ${i.pred}`}}},Pd={kind:"hierarchy",isGranularity:mr,validateItem(t,e){if(t.mappingType!=="property")return;const r=t.granularity;if(!mr(r))return;const n=yr(e.schema,t.propertyId);return n!==void 0&&Uo(n,r.level,e)!==void 0?void 0:"physical hierarchy granularity requires a mapped hierarchy Property and level"},candidateReason:Td,supportsGroupby:t=>t.operator==="$hierarchyLevel"},Ld={keys:["hierarchy"],resolve(t,e){for(const f of e)if(f.level!==void 0){if(typeof f.level!="string"||f.level.trim().length===0)throw new l("INVALID_PROPERTY_LEVEL",`Property ${f.name} level must be a non-empty string`,{property:f.name,level:f.level});if(f.primal_type!=="entity"&&f.primal_type!=="object")throw new l("PROPERTY_LEVEL_REQUIRES_ENTITY",`Property ${f.name} level requires an entity relation`,{property:f.name,type:f.type})}if("hierarchy_property"in t)throw new l("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 l("INVALID_HIERARCHY","Schema hierarchy must be an object containing property, levels, and optional storage");const n=r,o=Object.keys(n).filter(f=>f!=="property"&&f!=="storage"&&f!=="levels");if(o.length>0)throw new l("UNSUPPORTED_HIERARCHY_FIELD","Schema hierarchy only supports property, storage, and levels",{unsupportedKeys:o});const i=n.property===void 0?(()=>{const f=e.filter(m=>m.type==="ID");if(f.length!==1)throw new l("HIERARCHY_ID_PROPERTY_REQUIRED","Schema hierarchy.property may be omitted only when the Schema has exactly one ID Property",{idPropertyCount:f.length});return f[0]})():void 0;if(n.property!==void 0&&(typeof n.property!="string"||n.property.length===0))throw new l("HIERARCHY_PROPERTY_REQUIRED","Schema hierarchy.property must be a non-empty property name or id when provided");const s=i??e.find(f=>f.name===n.property||f.id===n.property);if(!s)throw new l("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${n.property}`,{property:n.property});if(s.primal_type!=="string")throw new l("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 l("INVALID_HIERARCHY_STORAGE","Schema hierarchy.storage must be compact or zero-padded");if(!Array.isArray(n.levels)||n.levels.length===0)throw new l("HIERARCHY_LEVELS_REQUIRED","Schema hierarchy.levels must be a non-empty array");const u=new Set,c=new Set,d=n.levels.map((f,m)=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new l("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} must be an object`);const h=f,y=Object.keys(h).filter(w=>w!=="name"&&w!=="syno"&&w!=="codeLength");if(y.length>0)throw new l("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${m} only supports name, syno, and codeLength`,{unsupportedKeys:y});if(typeof h.name!="string"||h.name.length===0)throw new l("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} name must not be empty`);if(u.has(h.name)||c.has(h.name))throw new l("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level name: ${h.name}`);if(!Number.isInteger(h.codeLength)||Number(h.codeLength)<=0)throw new l("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(w=>typeof w!="string"||w.length===0)))throw new l("INVALID_HIERARCHY_SYNONYMS",`Hierarchy level ${h.name} syno must contain only non-empty strings`);const $=h.syno??[];for(const w of $){if(w===h.name||u.has(w)||c.has(w))throw new l("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${w}`);c.add(w)}return u.add(h.name),{name:h.name,...$.length>0?{syno:[...$]}:{},codeLength:Number(h.codeLength)}});return{hierarchy:{property:s.name,storage:a,levels:d}}}},Cd=Object.freeze({name:"hierarchy",schemaMetadata:Ld,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:bd,resolveEntityFilterProperty:Sd,operators:[Od],mappingGranularity:Pd}),Dd=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp"),qo="$periodValue",Md=(t,e,r)=>{const n=e?.periodBoundaryPolicy?.({pred:t,...r?{executionContext:r}:{}});if(n)return{operator:qo,...n};if(e?.kind==="aggregate")throw new l("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${qo}; ${e.name} describes a time range`,{operator:e.name});return{operator:qo,boundary:"end",implicit:!0}},kd={name:"observation",resolveProjection({pred:t,schema:e,sourceProperty:r,outputProperty:n,operator:o,executionContext:i}){if(!r||!Dd(r,e))return;const s=Md(t,o,i);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:s.boundary,sourceProperty:r.name}}}}},Ud=new Set(["second","minute","hour","day","week","month","quarter","year"]),Ws=t=>typeof t=="string"&&Ud.has(t),qd=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Dn=(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 l(`${r.codePrefix}_PERIOD_INVALID_BOUND`,`${r.label} period ${e} must be a date`,{owner:e,value:t});return n},vt=(t,e=2)=>String(t).padStart(e,"0"),jo=t=>`${vt(t.getFullYear(),4)}-${vt(t.getMonth()+1)}-${vt(t.getDate())} ${vt(t.getHours())}:${vt(t.getMinutes())}:${vt(t.getSeconds())}.`+vt(t.getMilliseconds(),3),jd=(t,e)=>{if(!qd(t)){const a=Dn(t,"point",e);return{lower:a,upper:a}}const r=t.$eq;if(r!==void 0){const a=Dn(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 l(`${e.codePrefix}_PERIOD_BOUNDS_REQUIRED`,`${e.label} period grouping requires both a lower and an upper time bound`);const i=Dn(n,t.$gte!==void 0?"$gte":"$gt",e)+(t.$gte===void 0?1:0),s=Dn(o,t.$lte!==void 0?"$lte":"$lt",e)-(t.$lte===void 0?1:0);if(i>s)throw new l(`${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}},xd=(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},Vd=(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},Ks=(t,e,r)=>{const{lower:n,upper:o}=jd(t,r),i=[];let s=xd(n,e);for(;s.getTime()<=o;){if(i.length>=1e4)throw new l(`${r.codePrefix}_PERIOD_LIMIT_EXCEEDED`,`${r.label} period grouping cannot generate more than 10000 periods`);const a=Vd(s,e),u=new Date(Math.min(a.getTime()-1,o));i.push({label:jo(s),start:jo(s),end:jo(u)}),s=a}return i},Fd=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.name),Bd=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.name)),Hd=(t,e)=>{if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:p})=>p==="timestamp");if(!r)return;const n=Fd(t,r),o=t.preds??[],i=o.filter(({operator:p})=>p==="$periodValue");if(!n||i.length===0)return;const s=n.args?.granularity;if(n.operator!=="$dateBucket"||!Ws(s))throw new l("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 l("OBSERVATION_PERIOD_METRICS_REQUIRED","A grouped observation query cannot mix $periodValue with ordinary projections");const a=i.map(p=>{const f=p.args?.boundary;if(f!=="start"&&f!=="end")throw new l("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:f});if(!p.pred||typeof p.pred!="object"||Array.isArray(p.pred))throw new l("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");return{pred:p,effectivePred:{...p.pred,...p.name?{name:p.name}:{}}}});if(new Set(i.map(({args:p})=>p?.boundary)).size!==1)throw new l("OBSERVATION_PERIOD_BOUNDARY_MISMATCH","Grouped observation metrics in one query must use the same period boundary");const c=i[0]?.args?.boundary,d=t.query?.[r.name];if(d===void 0)throw new l("OBSERVATION_PERIOD_BOUNDS_REQUIRED",`Grouped observation values on ${r.name} require a bounded query`,{property:r.name});return{group:n,timestamp:r,boundary:c,metrics:a,periods:Ks(d,s,{codePrefix:"OBSERVATION",label:"Observation"}).map(p=>({label:p.label,asOf:p[c]}))}},Js=["second","minute","hour","day","week","month","quarter","year"],Qd=Object.freeze({name:"observation",schemaMetadata:{keys:["temporalSemantics"],resolve(t){const e=t.temporalSemantics??"normal";if(e!=="normal"&&e!=="snapshot")throw new l("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 l("SNAPSHOT_TIMESTAMP_REQUIRED","A snapshot Schema must declare exactly one timestamp Property",{schemaId:t.id})},plannerSemantics:[kd],relationSemantics:{plan({sourceSchema:t,targetSchema:e}){if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:s})=>s==="timestamp");if(!r)throw new l("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 l("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(Js.indexOf(o)>Js.indexOf(i))throw new l("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=Hd(t,e);if(r)return{group:r.group,property:r.timestamp,periods:r.periods,source:{kind:"latest",timestamp:r.timestamp},rewriteQuery:n=>Bd(n,r.timestamp),rewritePred:n=>r.metrics.find(o=>o.pred===n)?.effectivePred??n}}}}),Wr=(t,e)=>typeof e=="string"?t.properties.find(({id:r,name:n})=>r===e||n===e):void 0,Yd={name:"$recursive",validateCondition(t){if(Object.keys(t).some(e=>e!=="$recursive"))throw new l("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 l("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=r.idProperty??r.id_property,s=o.properties.filter(({type:f})=>f==="ID"),a=i===void 0?s.length===1?s[0]:void 0:Wr(o,i);if(!a||i===void 0&&s.length!==1)throw new l("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive Schema ${n} must have exactly one ID property or idProperty`);const u=Array.isArray(r.roots),c=u?r.roots:r.root===void 0?[]:[r.root];if(!u&&c.length===0||c.some(f=>f===void 0))throw new l("RECURSIVE_ROOT_REQUIRED","$recursive requires root or roots");const d=await Promise.all(c.map(f=>e.normalizeValue(f,o,a))),p=r.parentProperty??r.parent_property??o.parentProperty??"pid";if(typeof p!="string"||p.length===0)throw new l("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 l("INVALID_RECURSIVE_QUERY","$recursive includeSelf must be boolean");return{schema:n,roots:d,includeSelf:r.includeSelf??r.include_self??!0,idProperty:a.name,parentProperty:p}},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 l("RECURSIVE_ROW_PERMISSION_UNSUPPORTED",`$recursive cannot safely apply row permissions for Schema ${n}`,{schemaId:n});const i=r.idProperty??r.id_property,s=i===void 0?o.properties.find(({type:c})=>c==="ID"):Wr(o,i),a=r.parentProperty??r.parent_property??o.parentProperty??"pid",u=Wr(o,a);s&&e.assertPropertyAllowed(o,s),u&&e.assertPropertyAllowed(o,u)},plan(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("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 l("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=Wr(o,r.idProperty),s=Wr(o,r.parentProperty);if(!i)throw new l("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive ID property not found: ${String(r.idProperty)}`);if(!s)throw new l("RECURSIVE_PARENT_PROPERTY_REQUIRED",`$recursive parent property not found: ${String(r.parentProperty)}`);if(!Array.isArray(r.roots)||typeof r.includeSelf!="boolean")throw new l("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const a=e.resolveMapping(n,e.connectionId),u=e.resolveSource(a.source);return{value:{schemaId:n,connectionId:a.connectionId,source:u,idColumn:i.id,parentColumn:s.id,roots:r.roots,includeSelf:r.includeSelf},sources:[{schemaId:n,source:u.identity,...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 l("INVALID_RECURSIVE_QUERY","$recursive query was not planned");const i=t;if(!i.source||typeof i.idColumn!="string"||typeof i.parentColumn!="string"||!Array.isArray(i.roots)||typeof i.includeSelf!="boolean")throw new l("INVALID_RECURSIVE_QUERY","$recursive query was not planned");if(!r.supportsRecursiveCte)throw new l("RECURSIVE_QUERY_UNSUPPORTED",`Provider ${r.kind} does not support recursive queries`);const s=Array.isArray(i.roots)?i.roots:[];if(s.length===0)return`${e} IN (SELECT NULL WHERE 1 = 0)`;const a=r.quoteIdentifier("__recursive_tree__"),u=r.quoteIdentifier("__recursive_id__"),c=r.quoteIdentifier("__recursive_node__"),d=r.quoteIdentifier("__recursive_child__"),p=r.quoteIdentifier(i.idColumn),f=r.quoteIdentifier(i.parentColumn),m=o(i.source),h=()=>s.map(I=>n(I)).join(", "),y=(I,S=!1)=>s.length===1?`${I} ${S?"<>":"="} ${h()}`:`${I} ${S?"NOT IN":"IN"} (${h()})`,$=`${c}.${p}`,w=i.includeSelf?y($):`${y(`${c}.${f}`)} AND ${y($,!0)}`,E=r.recursiveCteUnion??"UNION",N=`(WITH RECURSIVE ${a}(${u}) AS ( SELECT ${$} FROM ${r.tableAlias(m,"__recursive_node__")} WHERE ${w} ${E} SELECT ${d}.${p} FROM ${r.tableAlias(m,"__recursive_child__")} JOIN ${a} ON ${d}.${f} = ${a}.${u}) SELECT DISTINCT ${u} FROM ${a})`;return`${e} IN ${N}`}},vd=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 l("RECURSIVE_PARENT_PROPERTY_REQUIRED",`Schema parentProperty does not exist: ${t.parentProperty}`,{schemaId:t.id,property:t.parentProperty});return{parentProperty:r.name}}},queryOperators:[Yd]});he.extend(Fr);const xo=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...xo(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:xo(r))]:e},Gd=(t,e)=>he(t).endOf(e==="week"?"isoWeek":e).toDate(),Xs=t=>he(t).format("YYYY-MM-DD HH:mm:ss"),zd=(t,e)=>{const r=t??{type:"database_latest"};if(r.type==="database_latest"||Number.isInteger(r.offset))return r;throw new l("INVALID_TIME_WATERMARK",`${e} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:e,timeWatermark:t})},Zs=(t,e)=>{if(t===void 0)return;if(typeof t!="object"||t===null||Array.isArray(t))throw new l("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 l("INVALID_TIME_WATERMARK",`${e} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:e,timeWatermark:t})},Wd=Object.freeze({name:"temporal",schemaMetadata:{keys:["timeWatermark"],resolve(t){return Zs(t.timeWatermark,`Schema ${t.id}`),{...t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}}},propertyMetadata:{keys:["timeWatermark"],resolve(t,e){if(Zs(t.timeWatermark,`Property ${t.name}`),t.timeWatermark&&e.primal_type!=="date")throw new l("TIME_WATERMARK_DATE_PROPERTY_REQUIRED",`Property ${e.name} timeWatermark is only supported by date Properties`,{property:e.name});return t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}},createTimeWatermarkLogicform({logicform:t,rootSchema:e,rootProperty:r,requestedUpperBound:n,now:o,defaultPolicy:i,resolveSchema:s,inferPropertyPath:a}){const u=[...new Set((t.preds??[]).flatMap(xo).filter(p=>p!==e.id))],c=[{schema:e,property:r}];for(const p of u){const f=s(p),m=t.propertyResolve?.[p],h=m?.[r.id]??m?.[r.name]??a(e,r.name,f);if(!h)throw new l("TIME_WATERMARK_PROPERTY_RESOLVE_REQUIRED",`Cross-Schema timeWatermark requires propertyResolve for ${p}.${r.name}`,{schemaId:p,property:r.name});const y=f.properties.find(({id:$,name:w})=>$===h||w===h);if(!y||y.primal_type!=="date")throw new l("TIME_WATERMARK_PROPERTY_REQUIRED",`timeWatermark Property is not a date Property: ${p}.${h}`,{schemaId:p,property:h});c.push({schema:f,property:y})}const d=c.map(({schema:p,property:f})=>{const m=zd(f.timeWatermark??p.timeWatermark??i,`${p.id}.${f.id}`);if(m.type==="now_offset"){const h=Gd(he(o).add(m.offset,"day").toDate(),f.granularity??"day");return{operator:"$constant",args:{value:Xs(h),type:"timestamp"},name:`${p.name}\u6570\u636E\u65F6\u95F4`}}return{operator:"$periodBoundary",args:{boundary:"end"},pred:{operator:"$max",pred:f.name,schema:p.id},name:`${p.name}\u6700\u65B0\u65F6\u95F4`}});return d.push({operator:"$constant",args:{value:Xs(n),type:"timestamp"},name:"\u63D0\u95EE\u65F6\u95F4\u4E0A\u754C"}),{version:t.version,schema:e.id,preds:[{name:"__timeWatermark__",operator:"$least",pred:d}]}}}),Mn=(t,e)=>{const r=t.filter(n=>n.type===e);return r.length===1?r[0]:void 0},Kr=t=>{if(t.type!=="entity"||t.temporalSemantics==="snapshot")return;const e=Mn(t.properties,"ID"),r=Mn(t.properties,"timestamp"),n=Mn(t.properties,"start_date"),o=Mn(t.properties,"end_date");return e&&r&&n&&o?{id:e,timestamp:r,start:n,end:o}:void 0},ea=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.timestamp.name),Kd=(t,e)=>ea(t,e)!==void 0,Jd=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.timestamp.name)),Xd=(t,e)=>{const r=ea(t,e);if(!r)return;const n=r.args?.granularity;if(r.operator!=="$dateBucket"||!Ws(n))throw new l("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 l("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:Ks(o,n,{codePrefix:"VALIDITY",label:"Valid-time"}).map(({label:i,end:s})=>({label:i,asOf:s}))}},Et=t=>he(t).format("YYYY-MM-DD HH:mm:ss"),Zd=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ep=t=>Zd(t)?t.$lte??t.$lt??t.$eq:t,ta=(t,e)=>{if(!t)return t;const r=Object.fromEntries(Object.entries(t).map(([a,u])=>[a,(a==="$and"||a==="$or")&&Array.isArray(u)?u.map(c=>ta(c,e)):u])),n=Object.entries(t).find(([a])=>a===e.timestamp.name);if(!n)return r;const[,o]=n,i=ep(o);if(i===void 0)throw new l("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}]}}},ra=(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&&ra(o,e)))),tp={name:"validity",resolveQuery({logicform:t,schema:e,query:r}){const n=Kr(e);if(!n)return r;if(Kd(t,n))return Jd(r,n);const i=ra(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:Et(new Date)}};return ta(i,n)},resolveProjection({schema:t,outputProperty:e}){if(Kr(t))return{outputProperty:{...e,temporal:{kind:"validity"}}}}},rp={name:"start_date",primalType:"date"},np={name:"end_date",primalType:"date"},op=Object.freeze({name:"validity",semanticTypes:[rp,np],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:[tp],intervalSemantics:{resolve:Kr},relationSemantics:{plan({sourceSchema:t,targetSchema:e}){const r=Kr(e);if(!r)return;const n=t.properties.find(({type:o})=>o==="timestamp");if(!n)throw new l("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=Kr(e);if(!r)return;const n=Xd(t,r);return n?{group:n.group,property:r.timestamp,periods:n.periods,source:{kind:"interval",start:r.start,end:r.end}}:void 0}}}),na=(t,e,r,n)=>{if(r===void 0)return;if(typeof r!="string"||r.length===0)throw new l("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 l("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 l("PROPERTY_HIERARCHY_CYCLE",`Property ${e.name} cannot point to itself in hierarchy.${n}`,{property:e.name,direction:n});return o.name},ip=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 l("INVALID_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy must be an object containing up and/or down`,{property:o.name,hierarchy:s});const a=s,u=Object.keys(a).filter(p=>p!=="up"&&p!=="down");if(u.length>0)throw new l("UNSUPPORTED_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy only supports up and down`,{property:o.name,unsupported:u});const c=na(t,o,a.up,"up"),d=na(t,o,a.down,"down");return{...o,hierarchy:{...c?{up:c}:{},...d?{down:d}:{}}}}),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 l("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}}}),hr=Object.freeze([Cd,vd,Wd,Qd,op,ip]),Pe=(t=[])=>{const e=[...hr,...t],r=new Set,n=new Set,o=new Set,i=new Set,s=new Set,a=new Set,u=new Set,c=new Set,d=new Set;for(const p of e){if(!p.name)throw new l("INVALID_PLUGIN","Plugin name must not be empty");if(r.has(p.name))throw new l("PLUGIN_ALREADY_REGISTERED",`Plugin is already registered: ${p.name}`,{plugin:p.name});r.add(p.name);for(const m of[...p.schemaMetadata?.keys??[],...p.legacySchemaKeys??[]]){if(!m)throw new l("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(n.has(m))throw new l("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${m}`,{key:m,plugin:p.name});n.add(m)}for(const m of p.propertyMetadata?.keys??[]){if(!m)throw new l("INVALID_PLUGIN_PROPERTY_METADATA_KEY","Plugin Property metadata key must not be empty");if(o.has(m))throw new l("PLUGIN_PROPERTY_METADATA_KEY_ALREADY_REGISTERED",`Plugin Property metadata key is already registered: ${m}`,{key:m,plugin:p.name});o.add(m)}for(const m of p.operators??[]){if(i.has(m.name))throw new l("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${m.name}`,{operator:m.name,plugin:p.name});i.add(m.name)}for(const m of p.semanticTypes??[]){if(s.has(m.name))throw new l("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${m.name}`,{semanticType:m.name,plugin:p.name});s.add(m.name)}for(const m of p.plannerSemantics??[]){if(!m.name||a.has(m.name))throw new l("PLUGIN_SEMANTIC_RULE_ALREADY_REGISTERED",`Plugin Planner semantic rule must be non-empty and unique: ${m.name}`,{rule:m.name,plugin:p.name});a.add(m.name)}for(const m of p.queryOperators??[]){if(!m.name||u.has(m.name))throw new l("PLUGIN_QUERY_OPERATOR_ALREADY_REGISTERED",`Plugin Query Operator must be non-empty and unique: ${m.name}`,{operator:m.name,plugin:p.name});u.add(m.name)}for(const m of p.outputHandlers??[]){if(!m.type||c.has(m.type))throw new l("PLUGIN_OUTPUT_HANDLER_ALREADY_REGISTERED",`Plugin output handler type must be non-empty and unique: ${m.type}`,{type:m.type,plugin:p.name});c.add(m.type)}const f=p.mappingGranularity;if(f){if(!f.kind||d.has(f.kind))throw new l("PLUGIN_GRANULARITY_ALREADY_REGISTERED",`Plugin physical granularity kind must be non-empty and unique: ${f.kind}`);d.add(f.kind)}}return Object.freeze(e)},gr=(t,e=[])=>Pe(e).flatMap(r=>r.queryOperators??[]).find(r=>r.name===t),kn=(t,e=[])=>Pe(e).flatMap(r=>r.outputHandlers??[]).find(r=>r.type===t),Vo=(t,e)=>{if(e.length>1)throw new l("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},oa=(t,e=[])=>Vo("interval semantics",Pe(e).flatMap(r=>{const n=r.intervalSemantics?.resolve(t);return n?[{plugin:r.name,value:n}]:[]})),sp=(t,e,r=[])=>Vo("relation semantics",Pe(r).flatMap(n=>{const o=n.relationSemantics?.plan({sourceSchema:t,targetSchema:e});return o?[{plugin:n.name,value:o}]:[]})),ap=(t,e,r=[])=>Vo("planner period semantics",Pe(r).flatMap(n=>{const o=n.plannerPeriod?.resolve(t,e);return o?[{plugin:n.name,value:o}]:[]})),cp=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,ia=t=>{const e=cp.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}},Fo=t=>{const e=t.freshness;if(e){if(e.mode==="ttl"){if(!Number.isInteger(e.ttlSeconds)||e.ttlSeconds<=0)throw new l("INVALID_SOURCE_FRESHNESS","TTL freshness requires a positive integer ttlSeconds");return}if(e.mode==="daily"){if(!ia(e.expireAt))throw new l("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 l("INVALID_SOURCE_FRESHNESS",`Invalid freshness timeZone: ${e.timeZone}`)}}}},sa=t=>{const e=[];let r=0,n=0;for(;n<t.length;){const o=t[n];if(o==="'"||o==='"'||o==="`"||o==="["){const i=o==="["?"]":o;for(n++;n<t.length;){if(t[n]===i){if(t[n+1]===i){n+=2;continue}n++;break}t[n]==="\\"&&n++,n++}continue}if(t.startsWith("--",n)){const i=t.indexOf(`
|
|
2
|
+
`,n+2);n=i<0?t.length:i+1;continue}if(t.startsWith("/*",n)){let i=1;for(n+=2;n<t.length&&i;)t.startsWith("/*",n)?(i++,n+=2):t.startsWith("*/",n)?(i--,n+=2):n++;continue}if(o==="$"){const i=/^(?:\$\$|\$[A-Za-z_][A-Za-z0-9_]*\$)/.exec(t.slice(n))?.[0];if(i){const s=t.indexOf(i,n+i.length);n=s<0?t.length:s+i.length;continue}}if(t.startsWith("{{",n)){const i=t.indexOf("}}",n+2);if(i<0)throw new l("INVALID_SCHEMA_MAPPING","SQL value contains an unclosed input reference");const s=t.slice(n+2,i).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw new l("INVALID_SCHEMA_MAPPING","SQL input names must be identifiers");e.push(t.slice(r,n),{input:s}),n=i+2,r=n;continue}n++}return e.push(t.slice(r)),e},Bo=t=>{const e=new Set,r=n=>{"input"in n?e.add(n.input):"op"in n&&("left"in n?(r(n.left),r(n.right)):"args"in n?n.args.forEach(r):"arg"in n?r(n.arg):(n.cases.forEach(o=>{r(o.when),r(o.then)}),r(n.else)))};return t.kind==="sql"?[...new Set(sa(t.sql).flatMap(n=>typeof n=="string"?[]:[n.input]))]:(r(t.expression),[...e])},up=t=>{const e=n=>{throw new l("INVALID_SCHEMA_MAPPING",n)},r=new Set;for(const n of t.mappings??[]){if(n.mappingType!=="property")continue;(typeof n.propertyId!="string"||!n.propertyId.trim()||r.has(n.propertyId))&&e("Property mapping targets must be non-empty and unique"),r.add(n.propertyId);const o=n.value;(!o||typeof o!="object"||Array.isArray(o))&&e("Property mapping requires a value");const i=n.value,s=o,a=s.kind==="column"?["kind","column","sourceRef"]:s.kind==="expression"?["kind","inputs","expression"]:s.kind==="sql"?["kind","inputs","sql","freshness"]:[];if((!a.length||Object.keys(s).some(p=>!a.includes(p)))&&e("Invalid or ambiguous Property mapping value"),i.kind==="column"){(typeof i.column!="string"||!i.column.trim())&&e("Column value requires a non-empty column"),i.sourceRef!==void 0&&!t.enrichments?.some(({id:p})=>p===i.sourceRef)&&e("Column sourceRef requires a registered enrichment id");continue}const u=i;(!s.inputs||typeof s.inputs!="object"||Array.isArray(s.inputs))&&e(`Computation ${n.propertyId} requires an inputs object`);for(const[p,f]of Object.entries(u.inputs)){const m=f,h=m&&Object.keys(m).length===1&&typeof m.property=="string"&&m.property.trim(),y=m&&Object.keys(m).every($=>$==="sourceColumn"||$==="sourceRef")&&typeof m.sourceColumn=="string"&&m.sourceColumn.trim()&&(m.sourceRef===void 0||t.enrichments?.some(({id:$})=>$===m.sourceRef));(!p.trim()||!m||Array.isArray(m)||!h&&!y)&&e(`Computation ${n.propertyId} inputs require exactly one non-empty property or sourceColumn, with a valid optional sourceRef`)}if(u.kind==="sql"){typeof u.sql!="string"&&e("SQL value requires SQL text"),Fo(u);for(const p of Bo(u))Object.hasOwn(u.inputs,p)||e(`Unknown input in SQL value: ${p}`);continue}const c=new Set,d=(p,f=0)=>{(!p||typeof p!="object"||Array.isArray(p)||f>100||c.has(p))&&e(`Invalid or cyclic expression in computation ${n.propertyId}`);const m=p;c.add(m);const h=$=>d($,f+1),y=Object.keys(m);if("input"in m)(y.length!==1||typeof m.input!="string"||!Object.hasOwn(u.inputs,m.input))&&e(`Unknown input in computation ${n.propertyId}`);else if("value"in m)(y.length!==1||!(m.value===null||typeof m.value=="string"||typeof m.value=="boolean"||typeof m.value=="number"&&Number.isFinite(m.value)))&&e("Computation literals must be null, strings, booleans, or finite numbers");else if(["eq","ne","gt","gte","lt","lte","like","add","subtract","multiply","divide"].includes(String(m.op)))y.length!==3&&e("Binary computation expressions require op, left and right"),h(m.left),h(m.right);else if(["and","or","coalesce"].includes(String(m.op)))(y.length!==2||!Array.isArray(m.args)||m.args.length<2)&&e("Computation args require at least two expressions"),m.args.forEach(h);else if(["not","isNull","isNotNull"].includes(String(m.op)))y.length!==2&&e("Unary computation expressions require op and arg"),h(m.arg);else if(m.op==="case"){(y.length!==3||!Array.isArray(m.cases)||!m.cases.length)&&e("Computation case requires branches and else");for(const $ of m.cases){(!$||typeof $!="object"||Array.isArray($))&&e("Invalid computation case branch");const w=$;Object.keys(w).length!==2&&e("Invalid computation case branch"),h(w.when),h(w.then)}h(m.else)}else e(`Unknown computation expression operator: ${String(m.op)}`);c.delete(m)};d(u.expression)}},aa=t=>`sql:${Sn("sha256").update(t).digest("hex")}`,rt=t=>(Ho(t),t.kind==="table"?Object.freeze({kind:"table",identity:t.table,path:Object.freeze(t.table.split("."))}):Object.freeze({kind:"sql",identity:aa(t.sql),sql:t.sql.trim().replace(/;+\s*$/,"")})),lt=t=>rt(t).identity,It=t=>t.id??lt(t.source),dp=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.identity!="string"||!e.identity?!1:e.kind==="table"?Array.isArray(e.path)&&e.path.length>0&&e.path.every(r=>typeof r=="string"&&r.trim().length>0):e.kind==="sql"&&typeof e.sql=="string"&&e.sql.trim().length>0},Ho=t=>{const e=()=>{throw new l("INVALID_SCHEMA_MAPPING",'Source requires exactly { kind: "table", table } or { kind: "sql", sql }')};(!t||typeof t!="object"||Array.isArray(t))&&e();const r=t;Object.keys(r).length!==2&&e(),r.kind==="table"?(typeof r.table!="string"||r.table.split(".").some(n=>!n.trim()))&&e():r.kind==="sql"?(typeof r.sql!="string"||!r.sql.trim().replace(/;+\s*$/,"").trim())&&e():e()},Qo=t=>{if(["sourceSql","tablePath","sourceMode","physicalDatabase","physicalSchema","physicalTable"].some(e=>e in t))throw new l("INVALID_SCHEMA_MAPPING","Obsolete source fields; define the row set inside source")},pp=new Set(["second","minute","hour","day","week","month","quarter","year"]),Un=t=>typeof t=="string"&&pp.has(t),ca=(t,e=Pe())=>Un(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)}),ua=t=>Array.isArray(t);class Dt{#e=new Map;plugins;constructor(e=[],r=[]){this.plugins=Pe(r);for(const n of e)this.register(n)}register(e){Qo(e),Ho(e.source);for(const u of this.plugins){const c=u.schemaMapping?.validate?.(e);if(c)throw new l("INVALID_SCHEMA_MAPPING_PLUGIN",`Schema mapping is rejected by plugin ${u.name}: ${c}`,{plugin:u.name,reason:c})}if(!e.schemaId)throw new l("INVALID_SCHEMA_MAPPING","Schema mapping schemaId must not be empty");if(e.id!==void 0&&!e.id)throw new l("INVALID_SCHEMA_MAPPING","Schema mapping id must not be empty");if(e.connectionId.trim().length===0)throw new l("INVALID_SCHEMA_MAPPING","Schema mapping connectionId must not be empty");if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new l("INVALID_SCHEMA_MAPPING","Schema mapping priority must be finite");if("dimensions"in e)throw new l("INVALID_SCHEMA_MAPPING","Schema mapping dimensions is removed; declare time granularity on property mapping items");if("computations"in e)throw new l("INVALID_SCHEMA_MAPPING","Define Property values inside mappings; computations is removed");const r=new Set,n=new Set;for(const u of e.enrichments??[]){if(!u.id||r.has(u.id))throw new l("INVALID_SCHEMA_MAPPING","Schema mapping enrichment ids must be non-empty and unique");Qo(u),Ho(u.source);const c=lt(u.source);if(c===lt(e.source)||n.has(c))throw new l("INVALID_SCHEMA_MAPPING","Schema mapping enrichment sources must be non-empty and unique");if(u.on.length===0||u.on.some(({baseColumn:d,targetColumn:p})=>!d||!p))throw new l("INVALID_SCHEMA_MAPPING","Schema mapping enrichments require non-empty baseColumn/targetColumn keys");if(u.temporal?.kind==="point"&&!u.temporal.pointColumn)throw new l("INVALID_SCHEMA_MAPPING","Point-in-time Schema mapping enrichments require pointColumn");Fo(u),r.add(u.id),n.add(lt(u.source))}const o=e.mappings;if(o!==void 0&&!Array.isArray(o))throw new l("INVALID_SCHEMA_MAPPING","Schema mapping mappings must be an array");for(const u of e.mappings??[]){const c=u;if(!c||typeof c!="object"||Array.isArray(c))throw new l("INVALID_SCHEMA_MAPPING","Schema mapping item must be an object");const d=c,p=d.mappingType==="property"?["mappingType","propertyId","value","granularity"]:d.mappingType==="predItem"?["mappingType","sourceColumn","predItem","propertyTarget"]:d.mappingType==="ignored"?["mappingType","sourceColumn"]:[];if(!p.length||Object.keys(d).some(f=>!p.includes(f)))throw new l("INVALID_SCHEMA_MAPPING","Invalid or obsolete mapping item fields");if(u.mappingType==="property"&&u.granularity!==void 0&&!ca(u.granularity,this.plugins))throw new l("INVALID_SCHEMA_MAPPING","Property mapping granularity is not supported");if(u.mappingType==="predItem"&&(typeof d.sourceColumn!="string"||!d.sourceColumn.trim()||!d.predItem||typeof d.predItem.pred!="string"||u.predItem.operator!==void 0&&!u.predItem.operator))throw new l("INVALID_SCHEMA_MAPPING","PredItem mapping requires sourceColumn and predItem pred");if(u.mappingType==="ignored"&&(typeof d.sourceColumn!="string"||!d.sourceColumn.trim()))throw new l("INVALID_SCHEMA_MAPPING","Ignored mapping requires sourceColumn")}up(e);const i=new Set;for(const u of e.queryPathMappings??[]){if(!ua(u.path)||!ua(u.bindings)||u.path.length===0||u.path.some(p=>typeof p!="string"||p.trim().length===0)||u.bindings.length===0)throw new l("INVALID_SCHEMA_MAPPING","Query path mappings require a non-empty path and bindings");const c=JSON.stringify(u.path);if(i.has(c))throw new l("INVALID_SCHEMA_MAPPING",`Duplicate query path mapping: ${u.path.join(".")}`);i.add(c);const d=new Set;for(const p of u.bindings){if(typeof p.sourceColumn!="string"||p.sourceColumn.trim().length===0||d.has(p.sourceColumn))throw new l("INVALID_SCHEMA_MAPPING","Query path bindings require distinct non-empty sourceColumn values");if(d.add(p.sourceColumn),!["literal","value"].includes(p.mappingType))throw new l("INVALID_SCHEMA_MAPPING","Query path binding mappingType must be literal or value");if(p.mappingType==="literal"){if((typeof p.value!="string"||p.value.length===0)&&(typeof p.value!="number"||!Number.isFinite(p.value))&&typeof p.value!="boolean")throw new l("INVALID_SCHEMA_MAPPING","A literal query path binding requires a string, finite number, or boolean value")}else{const f=u.path;if(!Array.isArray(p.valuePath)||p.valuePath.length!==f.length||p.valuePath.some((m,h)=>m!==f[h]))throw new l("INVALID_SCHEMA_MAPPING","A value query path binding must point to the matched entity path")}}}Fo(e);const s=this.#e.get(e.schemaId)??[],a=It(e);if(s.some(u=>u.connectionId===e.connectionId&&(It(u)===a||lt(u.source)===lt(e.source))))throw new l("SCHEMA_MAPPING_ALREADY_REGISTERED",`Schema mapping is already registered: ${e.schemaId}:${e.connectionId}:${a}`,{schemaId:e.schemaId,connectionId:e.connectionId,mappingId:a});return this.#e.set(e.schemaId,[...s,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 l("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 l("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(It)})}list(e){const r=this.#e.get(e);if(!r||r.length===0)throw new l("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=>It(o)===r)??[];if(n.length>1)throw new l("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=>lt(o.source)===r&&(n===void 0||o.connectionId===n))}}const lp=new Set(["$sply","$splm","$splq","$splw","$yoy","$mom","$qoq","$wow","$yoyd","$momd","$qoqd","$wowd","$percentage","$startOfPeriod","$endOfPeriod"]),qn=t=>!ce(t)||!Array.isArray(t.properties)?[]:t.properties.filter(ce),wr=new Set(["second","minute","hour","day","week","month","quarter","year"]),fp={weekday:"weekday",toQuarter:"quarter",toMonth:"month",toWeek:"week",toDay:"day",toHour:"hour",toWeekday:"weekday"},da=(t,e)=>{const r=e[t];return ce(r)?r:Object.values(e).find(n=>ce(n)&&(n.id===t||n._id===t))},pa=(t,e)=>{const r=t&&e?qn(da(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},la=(t,e,r)=>{const n=da(t,r);if(!n)return;const i=qn(n).map(s=>{const u=[s.id,s._id,s.name].filter(c=>typeof c=="string").filter(c=>e===c||e.startsWith(`${c}_`)).sort((c,d)=>d.length-c.length)[0];return u?{property:s,key:u}:void 0}).filter(s=>s!==void 0).sort((s,a)=>a.key.length-s.key.length)[0];if(i)return e===i.key?i.property:typeof i.property.ref=="string"?la(i.property.ref,e.slice(i.key.length+1),r):void 0},Ar=(t,e,r)=>{const n=(o,i,s)=>{const c=qn(r[o]).map(h=>{const y=typeof h.id=="string"?h.id:void 0,$=typeof h.name=="string"?h.name:void 0,E=[y,$].filter(N=>!!N&&(i===N||i.startsWith(`${N}_`))).sort((N,I)=>I.length-N.length)[0];return E?{property:h,key:E}:void 0}).filter(h=>!!h).sort((h,y)=>y.key.length-h.key.length)[0];if(!c)return;const d=String(c.property.id??c.property.name),p=i===c.key?"":i.slice(c.key.length+1);if(!p)return d;const f=typeof c.property.ref=="string"?c.property.ref:void 0;if(!f||s.has(f))return;const m=n(f,p,new Set(s).add(f));return m?`${d}_${m}`:void 0};return n(t,e,new Set([t]))},Yo=(t,e,r)=>{const n=qn(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 Yo(n.ref,e.slice(n.id.length+1),r)}},fa=t=>Object.keys(t).filter(e=>e!=="$and"&&e!=="$or"),ce=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ma=t=>typeof t=="string"&&/^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?$/.test(t),ya=new Set(["$gte","$lte"]),vo=t=>{if(!ce(t))return t;if(ce(t.$offset)){const e=Object.entries(t.$offset),r=e[0];if(e.length===1&&r&&Number.isInteger(r[1])&&wr.has(r[0])){const n=Object.fromEntries(Object.entries(t).filter(([s])=>s!=="$offset"));if(Object.keys(n).every(s=>wr.has(s)))return{granularity:r[0],offset:r[1],...n};const o=Object.fromEntries(Object.entries(n).filter(([s])=>wr.has(s))),i=Object.entries(n).filter(([s])=>ya.has(s));if(i.length>0&&Object.keys(n).every(s=>wr.has(s)||ya.has(s))){const s=i.map(([a,u])=>[a,ce(u)?vo({$offset:t.$offset,...o,...u}):u]);if(s.every(([,a])=>ce(a)&&!("$offset"in a)))return Object.fromEntries(s)}}}return t},mp=t=>typeof t=="string"&&t.length>0||typeof t=="number"&&Number.isSafeInteger(t),yp=(t,e)=>{if(!e)return;const r=e[t]??Object.values(e).find(u=>ce(u)&&(u.id===t||u._id===t));if(!ce(r))return;const n=r.hierarchy,o=Array.isArray(n)?n:ce(n)&&Array.isArray(n.levels)?n.levels:void 0;if(!o)return;const i=o.map(u=>{if(!ce(u)||typeof u.name!="string")return;const c=u.codeLength??u.code_length;return Number.isInteger(c)&&Number(c)>0?{name:u.name,codeLength:Number(c)}:void 0});if(i.length===0||i.some(u=>u===void 0))return;const s=o[0],a=Array.isArray(n)?ce(s)&&s.use_full_length===!0?"zero-padded":"compact":ce(n)&&n.storage==="zero-padded"?"zero-padded":"compact";return{levels:i.filter(u=>u!==void 0),storage:a}},hp=(t,e,r)=>{const n=yp(t,r);if(!n)return;const o=String(e),i=n.levels.reduce((a,u)=>a+u.codeLength,0);let s=0;for(const a of n.levels)if(s+=a.codeLength,o.length===s||n.storage==="zero-padded"&&o.length===i&&o.slice(s)==="0".repeat(i-s))return a.name;throw new l("LEGACY_HIERARCHY_LEVEL_INFERENCE_FAILED",`Cannot infer hierarchy level from entity_id ${o} in Schema ${t}`,{schemaId:t,entityId:e})},gp=(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}))]},Go=(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=>ce(h)?Go(h,e):h);continue}if(!ce(i)){r[o]=i;continue}const s=i.entity_id;if(typeof i.schema!="string"||!ce(i.query)||!mp(s)){r[o]=i;continue}const a=i.entity_level,u=typeof a=="string"&&a.length>0?a:hp(i.schema,s,e);if(!u){r[o]=i;continue}const{entity_id:c,entity_level:d,...p}=i,f=Go(i.query,e),m=Object.keys(p).filter(h=>h!=="schema"&&h!=="version"&&h!=="query");(Object.keys(f).length>0||m.length>0)&&(r[o]={...p,query:f}),n.push({pred:{operator:"$hierarchyLevel",pred:o,args:{level:u}},condition:s})}return gp(r,n)},wp=(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}},ha=(t,e)=>{if(!ce(e)||!Array.isArray(e.cases)||e.cases.length===0)throw new l("INVALID_LEGACY_CASE_ARGS",`${t} requires a non-empty params.cases array`);return{cases:e.cases.map((n,o)=>{if(!ce(n))throw new l("INVALID_LEGACY_CASE_ARGS",`${t} case ${o} must be an object`);if(n.sql!==void 0)throw new l("LEGACY_CASE_SQL_UNSUPPORTED",`${t} case.sql cannot be migrated to the structured v2 $case operator`);if(!ce(n.query)||typeof n.name!="string"||n.name.length===0)throw new l("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}:{}}},_t=(t,e,r,n=!1)=>{if(Array.isArray(t))return t.map(c=>_t(c,e,r));if(!ce(t))return t;const o=typeof t.year=="number"&&typeof t["year.inferred"]=="boolean"?Object.fromEntries(Object.entries(t).filter(([c])=>c!=="year.inferred")):t,i=vo(o);if(i!==o)return i;const s=typeof o.schema=="string"?o.schema:r,a={};for(const[c,d]of Object.entries(o))c==="skip"||c==="_snapshot"||c==="_snapshots"||(a[c]=_t(d,e,s,c==="from"));if(typeof o.version=="string"&&/^1\./.test(o.version)&&(a.version="2.0"),o.version===void 0&&(n||typeof o.schema=="string"&&(Array.isArray(o.preds)||Array.isArray(o.groupby)||o.from!==void 0))&&(a.version="2.0"),Array.isArray(o.groupby)){const c=o.groupby;a.groupby=c.map(d=>{if(!ce(d))return d;const p=_t(d,e,s);if(!ce(p))return p;const{_id:f,level:m,...h}=p;if(typeof f=="string"&&f.startsWith("$")){const $=f.slice(1);if(!wr.has($))throw new l("INVALID_LEGACY_TIME_GROUPBY",`Unsupported legacy time groupby: ${f}`,{groupby:f});const w=pa(s,e);if(!w)throw new l("LEGACY_TIME_GROUPBY_TIMESTAMP_REQUIRED",`Legacy time groupby ${f} requires a timestamp Property in Schema ${s??"(unknown)"}`,{groupby:f,schemaId:s});return{...h,pred:w,operator:"$dateBucket",args:{...ce(h.args)?h.args:{},granularity:$},...h.name===void 0?{name:`${w}(${$})`}:{}}}const y={...h,...h.pred===void 0&&typeof f=="string"?{pred:f}:{}};return typeof m=="string"&&(y.operator="$dateBucket",y.args={...ce(y.args)?y.args:{},granularity:m}),y})}const u=o.skip;if(typeof u=="number"&&Number.isInteger(u)&&u>=0){const c=o.limit;u===0?delete a.skip:typeof c=="number"&&Number.isInteger(c)&&c>0&&u%c===0?a.page=u/c+1:a.skip=u}else u!==void 0&&(a.skip=_t(u,e,s));if(o.operator&&typeof o.operator=="string"){const c=wp(o.operator,ce(a.args)?a.args:{});c.operator&&(a.operator=c.operator),a.args=c.args,o.operator==="$dateLevel"&&Array.isArray(a.params)&&(a.args={...c.args,granularity:c.args.granularity??a.params[0]},delete a.params);const d=typeof o.pred=="string"&&o.pred.startsWith("$")?o.pred.slice(1):"",p=fp[d];if(o.operator==="$count"&&(wr.has(d)||p)){const f=pa(s,e);if(!f)throw new l("LEGACY_TIME_COUNT_TIMESTAMP_REQUIRED",`Legacy $count($${d}) requires a timestamp Property in Schema ${s??"(unknown)"}`,{schemaId:s,pred:o.pred});a.operator="$countDistinct",a.pred=p?{operator:`$${p}`,pred:f}:{operator:"$dateBucket",pred:f,args:{granularity:d}}}if(o.operator==="$comp"||o.operator==="$compabs"){const f=ce(a.args)?a.args.preds:void 0;if(!Array.isArray(f)||f.length!==2)throw new l("INVALID_LEGACY_COMP_ARGS",`${o.operator} requires exactly 2 preds in args.preds`);const m={operator:"$subtract",pred:f,args:{nullAsZero:!0}};a.operator=o.operator==="$comp"?"$subtract":"$abs",a.pred=o.operator==="$compabs"?m:f,a.args=o.operator==="$comp"?{nullAsZero:!0}:{}}if(o.operator==="$switch"){const f=ce(a.params)?a.params:a.args;a.operator="$case",a.args=ha("$switch",f),delete a.params}if(o.operator==="$piecewise"){const f=typeof a.pred=="string"?a.pred:typeof o._id=="string"?o._id:void 0;if(e&&s&&f&&la(s,f,e)?.cases!==void 0)throw new l("LEGACY_PIECEWISE_PROPERTY_CASES_UNSUPPORTED","$piecewise property cases contain trusted SQL and cannot be migrated safely to v2 $case",{schemaId:s,property:f});const m=ce(a.params)?a.params:ce(a.args)?a.args:{};a.operator="$case",a.args=Array.isArray(m.cases)?ha("$piecewise",m):{mode:"auto",buckets:Number.isInteger(m.buckets)?m.buckets:10},delete a.params}lp.has(o.operator)&&typeof a.pred=="string"&&(a.pred={operator:"$sum",pred:a.pred})}if(o.params!==void 0&&a.args===void 0&&(a.args=Array.isArray(o.params)?{values:_t(o.params,e,s)}:_t(o.params,e,s)),o.inputs!==void 0&&a.pred===void 0&&Array.isArray(o.inputs)&&(a.pred=o.inputs.map(c=>_t(c,e,s)),ce(a.args)&&delete a.args.inputs),o.operator==="$sql"){const c={...ce(a.args)?a.args:{}};for(const d of["type","primal_type","isArray","ref"])o[d]!==void 0&&(c[d]=a[d]);delete a.type,delete a.primal_type,delete a.isArray,delete a.ref,typeof o.pred=="string"?(c.sql=o.pred,delete a.pred,delete a.sql):o.pred===void 0&&typeof o.sql=="string"&&(c.sql=o.sql,delete a.sql),a.args=c}return o.$options!==void 0&&a.$regex!==void 0?(a.args={...ce(a.args)?a.args:{},options:o.$options},delete a.$options):typeof o.$eq=="string"&&typeof o.$options=="string"?(a.args={...ce(a.args)?a.args:{},options:o.$options},delete a.$options):"$options"in o&&ma(o.$gte)&&ma(o.$lte)&&delete a.$options,o.query&&ce(o.query)&&(a.query=Ap(o.query,e,s)),a},Ap=(t,e,r)=>{const n=_t(t,e,r);for(const[o,i]of Object.entries(n))n[o]=vo(i);return Go(n,e)},jn=(t,e)=>{const r=ce(t)?t:void 0,n=_t(t,e);if(!ce(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","sample","limit","page","skip","output","representation","currency"])n[a]!==void 0&&(o[a]=n[a]);const i=new Set(["version","schema","query","groupby","having","sort","sample","limit","page","skip","output","representation","currency"]),s=Object.fromEntries(Object.entries(n).filter(([a])=>!i.has(a)));return o.preds=[s],jn(o,e)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),e?$p(n,e):n},$p=(t,e)=>{const r=t;if(!Array.isArray(r.preds))return t;const n=r.preds,o=typeof r.schema=="string"?r.schema:void 0;if(!o)return t;const i=new Set([o]);for(const u of n)ce(u)&&typeof u.schema=="string"&&i.add(u.schema);if(i.size<2)return t;if(!e)throw new Error("Cannot migrate cross-Schema LogicForm without Schema metadata for field alignment");const s=Array.isArray(r.groupby)?r.groupby.map(u=>ce(u)&&typeof u.pred=="string"?Ar(o,u.pred,e):void 0):[];for(const u of i)if(Array.isArray(r.groupby)&&r.groupby.map((c,d)=>{if(!ce(c)||typeof c.pred!="string")return c;const p=u===o?Ar(u,c.pred,e):Ar(u,Yo(o,s[d]??"",e)??c.pred,e);if(!p)return c;const f=p.split("_").at(-1)??c.pred;return{...c,pred:p,name:f}}),ce(r.query))for(const c of fa(r.query)){const d=Ar(o,c,e);if(!(u===o?d:Ar(u,(d&&Yo(o,d,e))??c,e))&&u===o)throw new Error(`Cannot align legacy query field ${c} in Schema ${u}`)}const a={...r};if(Array.isArray(r.groupby)&&(a.groupby=r.groupby.map((u,c)=>{if(!ce(u)||typeof u.pred!="string")return u;const d=s[c];return d?{...u,pred:d}:u})),ce(r.query)){const u=r.query,c=fa(u).map(d=>[Ar(o,d,e)??d,u[d]]);a.query=Object.fromEntries(c)}return a},ga=t=>{const e=(r,n)=>{if(Array.isArray(r)){r.forEach((o,i)=>e(o,`${n}[${i}]`));return}if(ce(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 l("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 l("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);e(i,`${n}.${o}`)}};e(t,"$")},zo=t=>{if(Array.isArray(t))return t.map(zo).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,zo(o)]).filter(([,n])=>n!==void 0);if(!(e.length>0&&r.length===0))return Object.fromEntries(r)},Ep=t=>{const e=t.constraints?.enum??t.enum;return Array.isArray(e)?e:typeof e=="string"&&e.length>0?e.split(","):void 0},Ip=(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}},_p=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}},Wo=(t,e=[],r=!0)=>{const n=Pe(e),o={},i=new Set(n.flatMap(s=>[...s.schemaMetadata?.keys??[],...s.legacySchemaKeys??[]]));for(const[s,a]of Object.entries(t)){const u=zo(a),c=u,p=(Array.isArray(c.properties)?c.properties:[]).some(N=>N.is_observation===!0)||c.is_observation===!0,f=c.is_snapshot===!0,m=typeof u.id=="string"&&u.id.length>0?u.id:r&&typeof u._id=="string"&&u._id.length>0?u._id:u.id,{properties:h}=u,y=Object.fromEntries(Object.entries(u).filter(([N])=>(r?!["_id","_sid","sid","is_observation","is_snapshot"].includes(N):N!=="properties")&&N!=="properties"&&!i.has(N))),$=h.map(N=>{const I=N,S=typeof I.id=="string"&&I.id.length>0?I.id:r&&typeof I._id=="string"&&I._id.length>0?I._id:I.id,{udf:D,...b}=I,T=r?Ep(I):void 0,M=Ip(I,T,r),Y=_p(D),C=r&&M!==void 0&&I.type==="string"?"category":I.type==="object"?"entity":I.type,O=C==="entity"||I.primal_type==="entity"||I.primal_type==="object";return{...r?Object.fromEntries(Object.entries(b).filter(([q])=>!["_id","_sid","sid","is_observation","is_comparable","comparable_order","comparable","enum"].includes(q)&&(q!=="level"||O))):b,type:C,...r&&T&&!Array.isArray(I.constraints?.enum)?{constraints:{...I.constraints,enum:T}}:{},...I.primal_type==="object"?{primal_type:"entity"}:{},...S!==void 0?{id:S}:{},...Y!==void 0?{udf:Y}:{},...M!==void 0?{comparable:M}:{}}});let w={};for(const N of n)for(const I of N.schemaMetadata?.keys??[])u[I]!==void 0&&(w={...w,[I]:u[I]});for(const N of n)w={...w,...N.normalizeLegacySchema?.({source:u,properties:$})};const E={...y,...m!==void 0?{id:m}:{},properties:$,...r&&(f||p)?{temporalSemantics:"snapshot"}:{},...w};o[s]=E}return o},wa=Symbol("legacy-empty-source"),Aa=t=>t!==void 0&&wa in t,$a=(t,e,r,n=[],o=r?[r]:[])=>{const i=[...e],s=new Set(n);for(const[a,u]of Object.entries(t)){const c=u,d=typeof c.id=="string"&&c.id.length>0?c.id:typeof c._id=="string"&&c._id.length>0?c._id:a;if(i.some(h=>h.schemaId===d))continue;const p=typeof c.db=="string"&&c.db.trim().length>0?c.db.trim():void 0;if(typeof c.from!="string"||c.from.trim().length===0){if(p){i.push({schemaId:d,connectionId:p,source:{kind:"table",table:d}});continue}for(const h of new Set(o.filter(Boolean))){const y={schemaId:d,connectionId:h,source:{kind:"table",table:`legacy-empty-schema:${d}`},[wa]:!0};i.push(y)}continue}const f=p??r;if(!f){if(s.has(d)||s.has(a))throw new l("LEGACY_SCHEMA_FROM_CONNECTION_REQUIRED",`Cannot create a Schema mapping for legacy Schema ${d}: provide Schema.db or one unambiguous connection`,{schemaId:d});continue}const m=c.from.trim();i.push({schemaId:d,connectionId:f,source:{kind:"sql",sql:m}})}return i},$r=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),bp=t=>$r(t)&&typeof t.schema=="string"&&$r(t.query),Sp=t=>$r(t)&&["preds","groupby","from","having","sort","limit","limitBy","page"].some(e=>t[e]!==void 0),Jr=(t,e,r,n="")=>{if(typeof t=="string"){r.push({reference:n?`${n}_${t}`:t,use:e});return}t&&(xn(t.query,r,n),Array.isArray(t.pred)?t.pred.forEach(o=>Jr(o,e,r,n)):Jr(t.pred,e,r,n))},xn=(t,e,r="")=>{if(t)for(const[n,o]of Object.entries(t)){if(n==="$and"||n==="$or"){Array.isArray(o)&&o.forEach(s=>{$r(s)&&xn(s,e,r)});continue}if(n==="$expr"){$r(o)&&"pred"in o&&$r(o.pred)&&Jr(o.pred,"query",e,r);continue}if(n.startsWith("$"))continue;const i=r?`${r}_${n}`:n;bp(o)&&!Sp(o)?(o.entity_id!==void 0&&o.entity_id!=="placeholder"&&e.push({reference:i,use:"query"}),xn(o.query,e,i)):e.push({reference:i,use:"query"})}},Gt=t=>{const e=[];return xn(t.query,e),t.preds?.forEach(r=>Jr(r,"pred",e)),t.groupby?.forEach(r=>Jr(r,"groupby",e)),e},Np=(t,e)=>e.length>0&&Gt(t).some(({reference:r})=>r===e),Ko=(t,e)=>{const r=e[t];if(!r)throw new l("SCHEMA_NOT_FOUND",`Schema not found: ${t}`,{schemaId:t});if("_id"in r||"_sid"in r)throw new l("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported",{schemaId:t});if("sid"in r)throw new l("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid",{schemaId:t});if(r.id!==t)throw new l("SCHEMA_ID_MISMATCH",`Schema registry key ${t} does not match schema.id ${r.id}`,{registryKey:t,schemaId:r.id});return r},Ea=(t,e)=>{const r=t.properties.find(n=>n.id===e)??t.properties.find(n=>n.name===e);if(!r)throw new l("PROPERTY_NOT_FOUND",`Property not found in ${t.id}: ${e}`,{schemaId:t.id,property:e});return r},Rp=t=>{const e=t.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(e))},Jo=t=>{const e=t.properties.filter(({type:n})=>n==="ID"),[r]=e;if(e.length!==1||!r)throw new l("RELATION_TARGET_ID_REQUIRED",`Relation target ${t.id} must contain exactly one ID property`,{schemaId:t.id,count:e.length});return r},Er=t=>t.reverse_ref!==void 0||t.is_virtual===!0&&t.ref_cardinality==="one-to-one"&&!t.isArray&&(t.primal_type==="entity"||t.primal_type==="object"),Vn=t=>{if(!Er(t.property))return{source:t.property,target:Jo(t.targetSchema)};const e=t.property.reverse_ref,r=t.targetSchema.properties.filter(o=>o.ref===t.sourceSchema.id&&o.ref_cardinality==="one-to-one"&&!o.isArray&&!o.is_virtual&&!o.reverse_ref&&(o.primal_type==="entity"||o.primal_type==="object")&&(!e||e.schemaId===t.targetSchema.id&&e.propertyId===o.id)),[n]=r;if(r.length!==1||!n)throw new l("INVALID_REVERSE_REF",`Reverse relation ${t.sourceSchema.id}.${t.property.name} requires exactly one original one-to-one foreign key`,{schemaId:t.sourceSchema.id,property:t.property.name,targetSchemaId:t.targetSchema.id,candidates:r.map(({id:o})=>o)});return{source:Jo(t.sourceSchema),target:n}},Xo=(t,e)=>{if(!Er(t.property)||!t.property.ref)return t;if(!e)throw new l("SCHEMA_RESOLVER_REQUIRED",`Resolving reverse relation ${t.canonicalName} requires a Schema resolver`);const r=e(t.property.ref);return{...t,schema:r,property:Jo(r),relations:[...t.relations,{sourceSchema:t.schema,property:t.property,targetSchema:r}]}},Zo=(t,e)=>t.name===e||t.id===e,Op=(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=>Zo(a,i.hierarchy?.up??"")):[],...r.properties.filter(a=>a.hierarchy?.down!==void 0&&Zo(i,a.hierarchy.down))];if(s.some(a=>Zo(e,a.name)))return!0;o.push(...s)}return!1},Ia=(t,e,r,n)=>{if(t.operator||typeof t.pred!="string"||e.length===0)return!1;let o;try{o=ne(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=ne(r,i.pred,n)}catch{return!1}if(s.property.isArray)return!1;if(s.relations.length===0&&o.relations.length===0)return Op(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})},zt=t=>typeof t=="string"&&t.length>0&&t!=="placeholder"||typeof t=="number"&&Number.isSafeInteger(t),Tp=t=>{const e=t.properties.filter(({type:r})=>r==="ID");if(e.length!==1)throw new l("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]},Fn=(t,e=[])=>{for(const r of Pe(e)){const n=r.resolveEntityFilterProperty?.(t);if(n)return n}return Tp(t)},Pp={name:"boolean",primalType:"boolean",hydrateResult(t){return typeof t=="number"?t===1:t}},Lp={name:"category",primalType:"string"},Cp={name:"currency",primalType:"number"},Dp={name:"date",primalType:"date"},Mp={name:"duration",primalType:"number"},_a=(t,{property:e,requestEntity:r})=>!e.ref||t===void 0||t===null||typeof t=="object"&&!Array.isArray(t)?t:r(e.ref,t),kp={name:"object",primalType:"object",hydrateResult:_a},Up={name:"entity",primalType:"entity",hydrateResult:_a},qp={name:"file",primalType:"string"},jp={name:"humanName",primalType:"string"},xp={name:"ID",primalType:"string"},Vp={name:"image",primalType:"string"},Fp={name:"int",primalType:"number"},Bp={name:"name",primalType:"string"},Hp={name:"number",primalType:"number"},Qp={name:"order",primalType:"number"},Yp={name:"percentage",primalType:"number"},vp={name:"string",primalType:"string"},Gp={name:"tag",primalType:"string",isArray:!0,normalizeResult:(t,{property:e})=>!e.isArray||t==null||Array.isArray(t)?t:[t]},zp={name:"timestamp",primalType:"date"},ei=Object.freeze([xp,vp,Bp,jp,Lp,Gp,Vp,qp,Hp,Fp,Cp,Yp,Mp,Qp,Pp,zp,Dp,Up,kp]);class ti{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new l("INVALID_SEMANTIC_TYPE","Semantic type name must not be empty");if(this.#e.has(e.name))throw new l("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 l("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 Wp=t=>{const e=new Set,r=new Set;for(const n of t){if(!n.name)throw new l("INVALID_PROPERTY_NAME","Property name must not be empty");if(!n.id)throw new l("INVALID_PROPERTY_ID",`Property ${n.name} physical id must not be empty`);if(e.has(n.name))throw new l("DUPLICATE_PROPERTY_NAME",`Duplicate property name: ${n.name}`,{property:n.name});if(r.has(n.id))throw new l("DUPLICATE_PROPERTY_ID",`Duplicate property physical id: ${n.id}`,{propertyId:n.id});e.add(n.name),r.add(n.id)}},ba=t=>{Wp(t);const e=t.filter(({type:r})=>r==="timestamp");if(e.length>1)throw new l("MULTIPLE_TIMESTAMP_PROPERTIES","A Schema can declare at most one timestamp Property",{properties:e.map(({name:r})=>r)})},Kp=new Set(["second","minute","hour","day","week","month","quarter","year"]),Sa=(t,e)=>{if("_id"in t||"_sid"in t)throw new l("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 l("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 l("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 c=t.udf;if(typeof c!="object"||c===null||Array.isArray(c))throw new l("INVALID_PROPERTY_UDF",`Property ${t.name} udf must be an object containing only sql`,{property:t.name});const d=c,p=Object.keys(d).filter(f=>f!=="sql");if(p.length>0)throw new l("UNSUPPORTED_PROPERTY_UDF",`Property ${t.name} udf only supports sql`,{property:t.name,unsupportedKeys:p});if(typeof d.sql!="string"||d.sql.trim().length===0)throw new l("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 l("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 l("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 l("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 l("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 c=t.comparable;if(typeof c!="object"||c===null||Array.isArray(c))throw new l("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable must contain values and direction; received ${JSON.stringify(c)}`,{property:t.name,comparable:c});const d=c;if(Object.keys(d).some(p=>p!=="values"&&p!=="direction")||!Array.isArray(d.values)||d.values.length===0||d.values.some(p=>typeof p!="string")||new Set(d.values).size!==d.values.length||d.direction!==1&&d.direction!==-1)throw new l("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable requires unique string values and direction 1 or -1; received ${JSON.stringify(c)}`,{property:t.name,comparable:c});if(t.type!=="category"||t.isArray===!0)throw new l("COMPARABLE_CATEGORY_REQUIRED",`Property ${t.name} comparable is only supported by scalar category properties`,{property:t.name,type:t.type})}const{componentProperties:i,...s}=t,a={...s,id:t.id??t.name,primal_type:n.primalType,isArray:t.isArray??n.isArray??!1,is_dynamic:t.udf?.sql!==void 0,...i?{componentProperties:i.map(c=>Sa(c,e))}:{},...n.primalType==="date"?{granularity:t.granularity??"day"}:{}};if(n.primalType==="entity"||n.primalType==="object"){if(typeof a.ref!="string"||a.ref.length===0)throw new l("PROPERTY_REF_REQUIRED",`Entity property ${a.name} must declare ref`,{property:a.name,type:a.type})}else if(a.ref!==void 0)throw new l("PROPERTY_REF_NOT_ALLOWED",`Property ${a.name} cannot declare ref unless its primal_type is entity`,{property:a.name,type:a.type});if(n.primalType==="date"||t.type==="duration"){if(a.granularity!==void 0&&!Kp.has(a.granularity))throw new l("INVALID_GRANULARITY",`Property ${a.name} has unsupported granularity: ${a.granularity}`,{property:a.name,granularity:a.granularity})}else if(a.granularity!==void 0)throw new l("GRANULARITY_NOT_ALLOWED",`Property ${a.name} cannot declare granularity unless its type supports it`,{property:a.name,type:a.type});return n.validateProperty?.(a),a},Bn=(t,e,r=[])=>{const n=Pe(r),o=n.reduce((m,h)=>h.prepareSchema?.(m)??m,t);if("_id"in o||"_sid"in o)throw new l("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported");if("sid"in o)throw new l("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid");if("is_snapshot"in o||"is_observation"in o)throw new l("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED","Schema must use temporalSemantics instead of is_snapshot/is_observation",{schemaId:o.id});if(!o.id)throw new l("INVALID_SCHEMA_ID","Schema id must not be empty");if(o.is_calendar!==void 0&&typeof o.is_calendar!="boolean")throw new l("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 l("INVALID_SCHEMA_PARTITION",`Schema ${o.id} partition must be a function`,{schemaId:o.id});const i=n.flatMap(m=>m.propertyMetadata?[m.propertyMetadata]:[]),s=new Set(i.flatMap(({keys:m})=>m));let a=o.properties.map(m=>{const h=Object.fromEntries(Object.entries(m).filter(([$])=>!s.has($))),y=Sa(h,e);return i.reduce(($,w)=>({...$,...w.resolve(m,$,o)}),y)});for(const m of i)a=[...m.resolveAll?.(a,o.properties,o)??a];ba(a);const u=n.flatMap(m=>m.schemaMetadata?[m.schemaMetadata]:[]);let c={};for(const m of u)c={...c,...m.resolve(o,a)};const d=new Set(n.flatMap(m=>[...m.schemaMetadata?.keys??[],...m.legacySchemaKeys??[]])),f={...Object.fromEntries(Object.entries(o).filter(([m])=>!d.has(m))),properties:a,...c};for(const m of n)m.validateResolvedSchema?.(f);return f},Re=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.version=="string"&&(typeof t.schema=="string"||typeof t.from=="object");he.extend($s),he.extend(Fr),he.extend(Nn);const Jp=new Set(["YTD","QTD","MTD","WTD","DTD"]),Na=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),Xp=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),Ir=["second","minute","hour","day","week","month","quarter","year"],Wt=t=>Object.prototype.toString.call(t)==="[object Object]",ri=(t,e)=>{const r=n=>{if(typeof n!="number"||!Number.isSafeInteger(n))throw new l("INVALID_DATE_PART_QUERY",`${e} requires integer values`)};if(typeof t=="number"){r(t);return}if(Array.isArray(t)){t.forEach(r);return}if(Wt(t)){const n=Object.entries(t);if(n.length===0||n.some(([o])=>!Na.has(o)))throw new l("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 l("INVALID_DATE_PART_QUERY",`${e}.${o} requires a non-empty array`);i.forEach(s=>ri(s,e))}else if(o==="$in"||o==="$nin"){if(!Array.isArray(i))throw new l("INVALID_DATE_PART_QUERY",`${e}.${o} requires an array`);i.forEach(r)}else r(i);return}throw new l("INVALID_DATE_PART_QUERY",`${e} requires integer values`)},ni=t=>!Wt(t)||"$gte"in t||"$gt"in t||"$lte"in t||"$lt"in t||"$or"in t||"$ne"in t?!1:typeof t.granularity=="string"&&Ir.includes(t.granularity)&&typeof t.offset=="number"||Ir.some(e=>e in t),Zp=(t,e)=>Ir.find(r=>r in t||e!==void 0&&r in e),el=(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),tl=(t,e)=>{const r=typeof t.granularity=="string"?t.granularity:void 0,n=r?{[r]:t.offset}:void 0,o=Zp(t,n)??"day";let i=he(e).millisecond(0);for(const a of[...Ir].reverse()){const u=t[a];typeof u=="number"&&(i=el(i,a,u));const c=n?.[a];typeof c=="number"&&c!==0&&(i=i.add(c,a))}const s=o==="week"?"isoWeek":o;return{$gte:Et(i.startOf(s)),$lte:Et(i.endOf(s))}},rl=(t,e,r="day")=>{const n=he(e),i={DTD:()=>n.startOf("day"),WTD:()=>n.startOf("isoWeek"),MTD:()=>n.startOf("month"),QTD:()=>n.startOf("quarter"),YTD:()=>n.startOf("year")}[t],s=r==="week"?"isoWeek":r;return{$gte:Et(i()),$lte:Et(n.endOf(s))}},Ra=async(t,e)=>{const r=he(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=he(n).endOf(i),a=he(String(t.$gte));if(a.isValid()&&s.isBefore(a))return t;const u=s.isBefore(r)?s:r;return{...t,$lte:Et(u)}},Oa=async(t,e)=>{const r=[...Ir].reverse(),n=r.findIndex(c=>c in t&&typeof t[c]!="number");for(const c of r)c in t&&ri(t[c],c);const o={},i={};for(const[c,d]of r.entries())d in t&&(n<0||c<n?o[d]=t[d]:i[`$${d}`]=t[d]);if("granularity"in t){if(n>=0&&r.indexOf(t.granularity)>=n)throw new l("INVALID_DATE_VALUE","Relative date offsets must be coarser than calendar comparison conditions");o.granularity=t.granularity,o.offset=t.offset}const a={...Object.keys(o).length>0?await Ra(tl(o,e.now),e):{},...i},u=Object.fromEntries(Object.entries(t).filter(([c])=>!Ir.includes(c)&&c!=="granularity"&&c!=="offset"&&c!=="period"));return Object.keys(u).length===0?a:{$and:[a,await Kt(u,e)]}},oi=async(t,e)=>Re(t)?t:t instanceof Date||typeof t=="string"&&he(t).isValid()?Et(t):typeof t=="string"&&Jp.has(t)?Ra(rl(t,e.now,e.property.granularity??"day"),e):ni(t)?Oa(t,e):t,Ta=async(t,e,r)=>{if(t==="$and"||t==="$or")return Array.isArray(e)?Promise.all(e.map(o=>Kt(o,r))):e;if(Array.isArray(e))return Promise.all(e.map(o=>oi(o,r)));const n=await oi(e,r);return t==="$eq"&&Wt(n)&&"$gte"in n&&"$lte"in n?n:t==="$gte"||t==="$gt"?Wt(n)&&"$gte"in n?n.$gte:n:(t==="$lte"||t==="$lt")&&Wt(n)&&"$lte"in n?n.$lte:n},Kt=async(t,e)=>{if(Re(t))return t;if(Array.isArray(t))return Promise.all(t.map(o=>Kt(o,e)));if(!Wt(t))return oi(t,e);if("$options"in t)throw new l("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");if("$offset"in t)throw new l("UNSUPPORTED_DATE_VALUE","The legacy {$offset: ...} date form is not supported; use { granularity, offset }");if(("granularity"in t||"offset"in t)&&(!ni(t)||!Number.isInteger(t.offset)))throw new l("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(ni(t))return Oa(t,e);const r=Object.entries(t);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await Ta("$eq",r[0][1],e);if(Wt(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)Xp.has(o)&&ri(i,o),n[o]=Na.has(o)?await Ta(o,i,e):await Kt(i,e);return n},nl=async(t,e)=>{if(!e.onDateQueryNormalized)return Kt(t,e);const r=[],n=await Kt(t,{...e,requestTimeWatermark:async i=>{const s=await e.requestTimeWatermark(i);return s&&r.push(s),s}}),o=r.length>0?await Kt(t,{...e,requestTimeWatermark:()=>Promise.resolve(void 0)}):n;return e.onDateQueryNormalized(r.length>1?void 0:o,n,r.length===1?r[0]:void 0),n},ol=(t,e)=>e.property.primal_type==="date"?nl(t,e):t,Mt=(t=[])=>new ti([...ei,...Pe(t).flatMap(({semanticTypes:e})=>e??[])]),ii=(t,e)=>{const r=new ti(t.definitions());for(const n of Pe(e))for(const o of n.semanticTypes??[])if(!r.has(o.name))r.register(o);else if(r.get(o.name)!==o)throw new l("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${o.name}`,{semanticType:o.name,plugin:n.name});return r},Xr=t=>!t.isArray&&(t.primal_type!=="number"||t.type==="ID"||t.type==="category"||t.is_categorical===!0),Pa=(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"&&e.properties.some(({id:s,name:a})=>s===r.id&&(s===i.propertyId||a===i.propertyId)));return o?.mappingType==="property"?{...o.value.kind==="column"&&o.value.sourceRef?{sourceRef:o.value.sourceRef}:{}}:void 0},Zr=t=>{if(!(t instanceof l&&t.code==="PROPERTY_NOT_FOUND"))throw t},il=(t,e,r)=>{const n=r.plugins.filter(f=>!hr.some(m=>m.name===f.name)),o=Wo(e,n),i=Mt(n),s=new Map,a=f=>{const m=s.get(f);if(m)return m;const h=Bn(Ko(f,o),i,n);return s.set(f,h),h},u=a(t),c=new Set,d=f=>{for(const m of f.mappings??[]){if(m.mappingType!=="predItem"||!m.sourceColumn||!m.predItem.query||typeof m.predItem.pred!="string"||m.predItem.schema&&m.predItem.schema!==t)continue;try{ne(u,m.predItem.pred,a)}catch($){Zr($);continue}const h=Gt({query:m.predItem.query}).filter(({use:$})=>$==="query").map(({reference:$})=>$),y=new Set(h.flatMap($=>{try{return[ne(u,$,a).canonicalId]}catch(w){return Zr(w),[]}}));for(const $ of m.propertyTarget?.length?[m.propertyTarget.join("_")]:h)try{const w=ne(u,$,a);y.has(w.canonicalId)&&Xr(w.property)&&c.add(w.canonicalName)}catch(w){Zr(w)}}},p=(f,m,h,y)=>{for(const $ of f.properties){const w=Er($)&&$.ref?a($.ref):void 0,E=w?Vn({sourceSchema:f,property:$,targetSchema:w}):void 0,N=Pa(m,f,E?.source??$);if(!N)continue;const I=ne(f,$.id).canonicalName,S=h?`${h}_${I}`:I;if(Xr($)&&(!h||$.type!=="ID")&&c.add(S),$.primal_type!=="entity"&&$.primal_type!=="object"||!$.ref||N.sourceRef||y.has($.ref))continue;const D=a($.ref),b=E?.target??D.properties.find(M=>M.type==="ID");if(!b)continue;let T;try{T=r.get(D.id,m.connectionId)}catch(M){if(!(M instanceof l)||!["SCHEMA_MAPPING_CONNECTION_NOT_FOUND","SCHEMA_MAPPING_AMBIGUOUS"].includes(M.code))throw M;continue}Pa(T,D,b)&&p(D,T,S,new Set([...y,D.id]))}};for(const f of r.list(t)){p(u,f,"",new Set([t]));for(const m of f.mappings??[])if(!(m.mappingType!=="property"||m.value.kind!=="column"))try{const h=ne(u,m.propertyId,a);if(h.relations.length>0&&Xr(h.property)&&(c.add(h.canonicalName),h.relations.length===1&&h.property.type==="ID")){const y=h.relations[0]?.property;y&&Xr(y)&&c.add(ne(u,y.id).canonicalName)}}catch(h){Zr(h)}d(f);for(const m of f.queryPathMappings??[])if(m.bindings.filter(({mappingType:h})=>h==="value").length===1)try{let h=u;const y=[];for(const E of m.path){const N=h.properties.find(({id:I})=>I===E)??h.properties.find(({name:I})=>I===E);if(!N?.ref||N.primal_type!=="entity"&&N.primal_type!=="object")break;y.push(N.id),h=a(N.ref)}if(y.length!==m.path.length)continue;try{r.list(h.id)}catch(E){if(E instanceof l&&E.code==="SCHEMA_MAPPING_NOT_FOUND")continue;throw E}const $=ne(u,m.path.join("_"),a),w=[...$.relations.map(({property:E})=>E.id),$.property.id];y.every((E,N)=>w[N]===E)&&w.length===y.length&&Xr($.property)&&c.add($.canonicalName)}catch(h){Zr(h)}}return[...c]},sl=(t,e=[])=>{if(Qo(t),!t.schemaId||!t.connectionId)throw new l("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping requires schemaId and connectionId");if(t.enabled===!1)throw new l("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping is disabled: ${t.id}`);if("computations"in t)throw new l("INVALID_SCHEMA_MAPPING","Define Property values inside mappings; computations is removed");if("dimensions"in t)throw new l("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping dimensions is removed; set granularity on property items");const r=t.mappings.filter(o=>o.mappingType!=="ignored"),n={id:String(t.id),schemaId:t.schemaId,connectionId:t.connectionId,source:t.source,...t.enrichments?{enrichments:t.enrichments}:{},...t.queryPathMappings?{queryPathMappings:t.queryPathMappings}:{},mappings:r};return new Dt([n],e),n},Hn=(t,e)=>{if(!dp(t))throw new l("INVALID_SOURCE","Expected a resolved row-set source");return t.kind==="table"?t.path.map(r=>e.quoteIdentifier(r)).join("."):`(${t.sql})`},al=t=>t?.kind==="sql",cl=(t,e,r,n)=>{const{definition:o,inputs:i}=t,s=["sqlserver","oracle","dameng"].includes(e.kind),a=(d,p)=>s&&!p?`(CASE WHEN ${d} THEN 1 ELSE 0 END)`:d,u=(d,p)=>s&&p?`(${d} = ${n(!0)})`:d,c=(d,p=!1)=>{if("input"in d){const f=i[d.input];if(!f)throw new l("COMPUTATION_INPUT_NOT_FOUND",`Unknown computation input: ${d.input}`);return u(r(f),p)}if("value"in d)return u(d.value===null?"NULL":n(d.value),p);if("left"in d){const f={eq:"=",ne:"<>",gt:">",gte:">=",lt:"<",lte:"<=",like:"LIKE",add:"+",subtract:"-",multiply:"*",divide:"/"};if((d.op==="eq"||d.op==="ne")&&"value"in d.right&&d.right.value===null)return a(`(${c(d.left)} IS ${d.op==="ne"?"NOT ":""}NULL)`,p);const m=`(${c(d.left)} ${f[d.op]} ${c(d.right)})`;return["add","subtract","multiply","divide"].includes(d.op)?u(m,p):a(m,p)}return"args"in d?d.op==="coalesce"?u(`COALESCE(${d.args.map(f=>c(f)).join(", ")})`,p):a(`(${d.args.map(f=>c(f,!0)).join(d.op==="and"?" AND ":" OR ")})`,p):"arg"in d?d.op==="not"?a(`(NOT ${c(d.arg,!0)})`,p):a(`(${c(d.arg)} IS ${d.op==="isNotNull"?"NOT ":""}NULL)`,p):u(`(CASE ${d.cases.map(f=>`WHEN ${c(f.when,!0)} THEN ${c(f.then)}`).join(" ")} ELSE ${c(d.else)} END)`,p)};return o.kind==="sql"?`(${sa(o.sql).map(d=>{if(typeof d=="string")return d;const p=i[d.input];if(!p)throw new l("COMPUTATION_INPUT_NOT_FOUND",`Unknown SQL input: ${d.input}`);return`(${r(p)})`}).join("")})`:c(o.expression)};function en(t){if(t===null)return null;let e=0,r;for(let n=0;n<t.length;n+=1){const o=t[n];if(r)o==="\\"?n+=1:o===r&&(r=void 0);else if(o==='"'||o==="'"||o==="`")r=o;else if(o==="(")e+=1;else if(o===")")e-=1;else if(e===0&&"+-*/".includes(o))return`(${t})`}return t}const xe=t=>e=>`${t}(${[...e.input===void 0?e.inputs:[e.input],...Object.entries(e.args).map(([r,n])=>`${r}=${JSON.stringify(n)}`)].join(", ")})`,La=(t,e)=>{if(!t.getFormulaText||e.input===null||e.inputs.includes(null))return null;const{input:r,inputs:n,...o}=e,i=t.getFormulaText({...o,...r===void 0?{}:{input:r},inputs:n.filter(s=>s!==null)});if(typeof i!="string"||i.trim().length===0)throw new l("INVALID_FORMULA_TEXT",`Operator getFormulaText must return a non-empty string: ${t.name}`);return en(i)};he.extend(Fr),he.extend(Nn);const ul=new Set(["year","quarter","month","week"]),si=t=>t.format("YYYY-MM-DD HH:mm:ss"),ai=(t,e)=>t.operator&&e(t.operator).kind==="aggregate"?!0:(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?ai(t.pred,e):!1)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&ai(r,e)),Qn=(t,e,r)=>{if(t.kind==="window"||t.kind==="cumulative")throw new l("ACCUMULATE_WINDOW_UNSUPPORTED","$accumulate cannot contain another window expression");if(t.kind==="ordinal-decode")return{...t,input:Qn(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 l("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 l("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 l("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain ${t.operator}`);return{...t,...t.input?{input:Qn(t.input,e,r)}:{},...t.inputs?{inputs:t.inputs.map(o=>Qn(o,e,r))}:{}}},dl=t=>{if(!t.input||t.inputs.length>0||t.pred.query)throw new l("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 l("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 l("INVALID_ACCUMULATE_ARGS","$accumulate partitionBy must be an array of groupby names");if(!Array.isArray(r)||r.length===0)throw new l("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 l("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 l("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 Qn(t.input,t,{partitionBy:e.map(o=>t.resolveKey(String(o))),orderBy:n})},pl=t=>{if(t.groupByNames.length===0)return;if(typeof t.pred.pred!="object"||Array.isArray(t.pred.pred)||!ai(t.pred.pred,t.getOperator))throw new l("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 l("INCOMPLETE_ACCUMULATE_DIMENSIONS","$accumulate partitionBy and orderBy must cover every groupby item exactly once",{expected:t.groupByNames,received:o})},ll=(t,e,r)=>{if(t.from||t.having)throw new l("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period currently requires a physical LogicForm without from or having");if((t.preds?.length??0)!==e.length)throw new l("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period cannot currently be mixed with non-period projections");const n=t.query&&Object.entries(t.query).find(([,I])=>{if(typeof I!="object"||I===null||Array.isArray(I))return!1;const S=I;return typeof S.$gte=="string"&&typeof S.$lte=="string"});if(!n)throw new l("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires one bounded date query identifying the target period");const[o,i]=n,s=i,a=he(String(s.$gte)),u=he(String(s.$lte));if(!a.isValid()||!u.isValid())throw new l("ACCUMULATE_PERIOD_QUERY_REQUIRED","Target date range is invalid");const c=e.map(I=>{if(!I.name)throw new l("MISSING_PRED_NAME","$accumulate args.period requires normalized names");return I.name}),d=r==="week"?a.startOf("isoWeek"):a.startOf(r),p={...t.query,[o]:{...s,$gte:si(d)}},f=new Set([...(t.groupby??[]).map(({name:I})=>I),...(t.preds??[]).map(({name:I})=>I)]),m=I=>{let S=I;for(;f.has(S);)S=`_${S}`;return f.add(S),S},h=m("__accumulate_period"),y=e.map((I,S)=>m(`__accumulate_metric_${S}`)),$=(t.groupby??[]).map(({name:I})=>String(I)),w=r==="year"||r==="quarter"?"month":"day",E={version:t.version,...t.schema?{schema:t.schema}:{},query:p,groupby:[...t.groupby??[],{operator:"$dateBucket",pred:o,args:{granularity:w},name:h}],preds:e.map((I,S)=>({...I.pred,name:y[S]??`__accumulate_metric_${S}`}))},N={version:t.version,from:E,preds:[...$.map(I=>({pred:I,name:I})),{pred:h,name:h},...e.map((I,S)=>({operator:"$accumulate",pred:y[S]??`__accumulate_metric_${S}`,args:{partitionBy:$,orderBy:[{pred:h,direction:"asc"}]},name:c[S]??`accumulate_${S}`}))]};return{version:t.version,from:N,query:{[h]:{$gte:si(a),$lte:si(u)}},preds:[...$.map(I=>({pred:I,name:I})),...c.map(I=>({pred:I,name:I}))],...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}:{}}},fl={name:"$accumulate",getFormulaText:xe("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"||!ul.has(e)))throw new l("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 l("INVALID_ACCUMULATE_ARGS","$accumulate args.period cannot be combined with partitionBy or orderBy");return t},planExpression:dl,validatePlan:pl,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 l("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 l("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires exactly one queried date property");return ll(t,r,n)},getOutputProperty({name:t,inputProperty:e}){return e?{...e,name:t,isArray:!1}:{name:t,type:"number",primal_type:"number",isArray:!1}}},ml={name:"$abs",getFormulaText:xe("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 l("PRED_PROPERTY_REQUIRED","$abs requires a pred");return`ABS(${t})`},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new l("PRED_PROPERTY_REQUIRED","$abs requires a pred");return{...e,name:t,isArray:!1}}},_r=(t,e,r,n=r)=>{const o=e.expressions??[];if(o.length<r||o.length>n)throw new l("INVALID_OPERATOR_COMPONENTS",`${t} requires ${r===n?String(r):`${r}-${n}`} pred inputs`);return o},Yn=t=>({name:t,type:"number",primal_type:"number",isArray:!1}),yl={name:"$add",getFormulaText:({inputs:t})=>`(${t.join(" + ")})`,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`(${_r("$add",t,2,Number.POSITIVE_INFINITY).join(" + ")})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:Yn(t)}},ge=t=>structuredClone(t),ci=t=>{if(t.name)return t.name;throw new l("MISSING_PRED_NAME","A normalized groupby PredItem must have a name")},ui=t=>typeof t.pred=="string"?t.pred:void 0,Ca=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Da={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},di={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},pi=({input:t,args:e})=>{const r=e.time;let n="\u540C\u671F";if(Ca(r))if(typeof r.granularity=="string"&&typeof r.offset=="number"){const o={year:"\u53BB\u5E74\u540C\u671F",quarter:"\u4E0A\u5B63\u5EA6\u540C\u671F",month:"\u4E0A\u6708\u540C\u671F",week:"\u4E0A\u5468\u540C\u671F"};n=r.offset===0?"\u672C\u671F":r.offset===-1&&o[r.granularity]?o[r.granularity]:`${r.offset<0?"\u524D":"\u540E"}${Math.abs(r.offset)}${Da[r.granularity]??r.granularity}\u540C\u671F`}else n=Object.keys(di).filter(o=>r[o]!==void 0).map(o=>`${String(r[o])}${di[o]}`).join("");return`PERIOD_SHIFT(${t}, ${n})`},li=(t,e,r)=>{const n=e.toLowerCase().startsWith("en"),o=t.time;if(!Ca(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}${Da[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${di[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};he.extend(Fr),he.extend(Nn);const hl=["second","minute","hour","day","week","month","quarter","year"],gl=new Set(hl),fi=["year","quarter","month","week","day","hour","minute","second"],Ma=t=>Object.prototype.toString.call(t)==="[object Object]",kt=t=>{throw new l("INVALID_PERIOD_SHIFT_ARGS",t)},wl=t=>{const e=t.time;Ma(e)||kt("$periodShift requires args.time");const r=e;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!gl.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&kt("Relative period shift time requires only granularity and an integer offset"),r;const o=Object.entries(r);(o.length===0||o.some(([a,u])=>!fi.includes(a)||!Number.isInteger(u)))&&kt("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&kt("Absolute period shift time requires year");const i={quarter:[1,4],month:[1,12],week:[1,53],day:[1,31],hour:[0,23],minute:[0,59],second:[0,59]};for(const[a,[u,c]]of Object.entries(i)){const d=r[a];d!==void 0&&(Number(d)<u||Number(d)>c)&&kt(`Invalid absolute period shift ${a}: ${JSON.stringify(d)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&kt("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&kt("Absolute period shift day requires month"),r},ka=(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),Al=(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 fi){const o=e[n];typeof o=="number"&&(r=ka(r,n,o))}return r},mi=(t,e)=>t instanceof Date?e.toDate():typeof t!="string"?t:e.format(t.includes(":")?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"),$l=(t,e,r,n,o)=>(t.groupby??[]).filter(i=>{const s=ui(i);return s?ne(e,s,r).property.primal_type==="date":!1}).map(i=>{const s=i.operator==="$dateBucket"?i.args?.granularity:void 0,a="granularity"in n?n.granularity:s??"day",u="granularity"in n?-n.offset:o.originalAnchor&&o.shiftedAnchor?o.originalAnchor.diff(o.shiftedAnchor,a):0;return{name:ci(i),granularity:a,offset:u}}),yi=(t,e,r)=>{if(Array.isArray(t))return t.map(i=>yi(i,e,r));if(Ma(t))return Object.fromEntries(Object.entries(t).map(([i,s])=>[i,yi(s,e,r)]));if(!(t instanceof Date)&&typeof t!="string")return t;const n=he(t);if(!n.isValid())return t;const o=Al(n,e);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,mi(t,o)},Ua=(t,e,r,n,o)=>{const i=new Set,s=u=>Object.fromEntries(Object.entries(u).map(([c,d])=>{if((c==="$and"||c==="$or")&&Array.isArray(d))return[c,d.map(f=>s(f))];const p=ne(e,c,r);return p.property.primal_type!=="date"?[c,d]:(i.add(p.canonicalName),[c,yi(d,n,o)])})),a=s(t);if(i.size===0||o.shiftedValues===0)throw new l("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a concrete date condition in the LogicForm query");if(i.size>1)throw new l("AMBIGUOUS_PERIOD_SHIFT_TIME","$periodShift query contains more than one date property",{properties:[...i]});return a},Jt=t=>{const e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?e[0]:{$and:e}},Ut=t=>[...t.query?[t.query]:[],...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Ut(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(r=>typeof r=="string"?[]:Ut(r)):[]],El=(t,e,r)=>{if(!(t instanceof Date)&&typeof t!="string")return t;const n=he(t);if(!n.isValid())return t;if("granularity"in e)return mi(t,n.add(-e.offset,e.granularity));if(!r.originalAnchor)return t;let o=n;for(const i of fi)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=ka(o,i,s)}return mi(t,o)},hi=({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o})=>{const i=e.pred;(!i||typeof i!="object"||Array.isArray(i))&&kt("$periodShift pred must be a nested metric");const s=wl(e.args??{}),a={shiftedValues:0},u=Jt([t.query,...Ut(e)]);if(!u)throw new l("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const c=Ua(u,n,o,s,a),d=ge(i);d.name=r,delete d.query;const p=ge(t);p.query=c,p.preds=[d],delete p.having,delete p.sort,delete p.limit,delete p.page;const f=new Set((t.groupby??[]).filter(m=>{const h=ui(m);return h?ne(n,h,o).property.primal_type==="date":!1}).map(ci));return{kind:"query",logicform:p,partitionCurrentLogicform:{...ge(t),query:u,preds:[{...ge(d),name:"__partition_current__"}]},partitionQuery:m=>Ua(m,n,o,s,{shiftedValues:0}),groupKeyShifts:$l(t,n,o,s,a),mapResult:m=>m.map(h=>{const y={...h};for(const $ of f)y[$]=El(y[$],s,a);return y})}},Il={name:"$periodShift",getFormulaText:pi,defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=li(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:hi,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodShift requires a nested metric");return{...e,name:t,isArray:!1}}},_l=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),vn=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 l("TIMESTAMP_PROPERTY_REQUIRED",`${e} requires a timestamp property in the Schema`);return r},qa=(t,e)=>{if(vn(t)){e.start??=t,e.end??=t;return}if(!_l(t))return;const r=t.$eq;vn(r)&&(e.start??=r,e.end??=r);const n=t.$gte??t.$gt,o=t.$lte??t.$lt;vn(n)&&(e.start??=n),vn(o)&&(e.end??=o);for(const i of["$and","$or"]){const s=t[i];if(Array.isArray(s))for(const a of s)qa(a,e)}},bl=(t,e,r,n,o)=>{const i=gi(e,n),s=new Set,a={},u=(f,m)=>{for(const[h,y]of Object.entries(f)){if((h==="$and"||h==="$or")&&Array.isArray(y)){for(const w of y)u(w,m||h==="$or");continue}if(h.startsWith("$"))continue;const $=ne(e,h,r);if($.property.type==="timestamp"){if(m)throw new l("AMBIGUOUS_TIME_QUERY",`${n} does not support timestamp conditions inside $or`);s.add($.canonicalName),qa(y,a)}}};if(u(t,!1),s.size===0&&o!==void 0&&(s.add(i.name),a.start=o,a.end=o),s.size!==1)throw new l(s.size===0?"TIME_QUERY_REQUIRED":"AMBIGUOUS_TIME_QUERY",`${n} requires a concrete condition on the Schema timestamp property`);const c=[...s][0];if(!c||c!==i.name)throw new l("AMBIGUOUS_TIME_QUERY",`${n} requires the Schema timestamp property: ${i.name}`);const d=f=>{const m=[];for(const[h,y]of Object.entries(f)){if((h==="$and"||h==="$or")&&Array.isArray(y)){const $=y.map(w=>d(w)).filter(w=>w!==void 0);$.length>0&&m.push([h,$]);continue}!h.startsWith("$")&&ne(e,h,r).property.type==="timestamp"||m.push([h,y])}return m.length>0?Object.fromEntries(m):void 0},p=d(t);return{property:i,propertyName:c,...a.start!==void 0?{start:a.start}:{},...a.end!==void 0?{end:a.end}:{},...p?{queryWithoutTime:p}:{}}},ja=(t,e,r,n,o,i)=>{const s=Jt([t,...Ut(e)]);if(!s&&i===void 0)throw new l("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return bl(s??{},r,n,o,i)},xa=(t,e,r)=>Jt([t,{[e]:r}]),Sl=new Set(["day","week","month","quarter","year"]),Nl={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Rl=t=>{if(typeof t!="string"||!Sl.has(t))throw new l("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return t},Va=t=>{const e=ge(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},wi=t=>{const e=ge(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=wi(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:wi(r))),e},Ol={name:"$averagePerPeriod",getFormulaText:({input:t,args:e,schema:r})=>{const n=gi(r,"$averagePerPeriod");return`(${t} / NULLIF(COUNT_DISTINCT(DATE_BUCKET(${n.name}, ${JSON.stringify(e.granularity)})), 0))`},defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${t} per ${typeof e.granularity=="string"?e.granularity:"period"}`:`${t}${Nl[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 l("INVALID_AVERAGE_PER_PERIOD_INPUT","$averagePerPeriod pred must be a nested metric");const i=Rl(e.args?.granularity),s=gi(r,"$averagePerPeriod"),a=wi(e.pred),u=Jt([t.query,...Ut(e)]),c=Va(t);c.preds=[{...a,name:"__avg_period_num__"}],u&&(c.query=u);const d=Va(t);d.preds=[{operator:"$countDistinct",pred:{operator:"$dateBucket",pred:s.name,args:{granularity:i},name:"__avg_period_bucket__"},name:"__avg_period_den__"}],u&&(d.query=u);const p=o("component.numerator",`${n}\u5206\u5B50`,{outputName:n}),f=o("component.denominator",`${n}\u5206\u6BCD`,{outputName:n});return{components:[{name:p,logicform:c},{name:f,logicform:d}],expression:`${p} / NULLIF(${f}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$averagePerPeriod requires a nested metric");return{...e,name:t,isArray:!1}}},Tl={name:"$avg",getFormulaText:xe("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}}},br=t=>{throw new l("INVALID_CASE_ARGS",t)},Pl=t=>{if(t.mode!=="auto")return;Object.hasOwn(t,"cases")&&br("$case auto mode cannot define args.cases"),t.empty!==void 0&&typeof t.empty!="boolean"&&br("$case auto mode args.empty must be boolean");const e=t.buckets;e!==void 0&&(!Number.isInteger(e)||e<2||e>100)&&br("$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)&&br("$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]))&&br(`$case auto mode requires resolved finite args.${o}`);t.min>t.max&&br("$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}},Ll=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},Gn=t=>{const e=Number(t.toPrecision(15));return Object.is(e,-0)?0:e},Ai=t=>String(Gn(t)),Cl=(t,e,r)=>{if(t===e)return[t,e];const n=Ll((e-t)/r),o=Gn(Math.floor(t/n)*n),i=Gn(Math.ceil(e/n)*n),s=Math.max(1,Math.round((i-o)/n));return Array.from({length:s+1},(a,u)=>u===s?i:Gn(o+n*u))},Dl=t=>{if(!Array.isArray(t)||t.length===0)throw new l("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 l("INVALID_CASE_ARGS","Each $case item requires when and then");const r=e;return{when:r.when,then:r.then}})},Ml={name:"$case",getFormulaText:xe("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 l("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 l("PRED_PROPERTY_REQUIRED","$case requires a pred");const n=Pl(e);if(n){const s=r.value("\u672A\u77E5");if(n.empty)return s;const a=n.minimum,u=n.maximum;if(a===u)return`CASE WHEN ${t} IS NULL THEN ${s} ELSE ${r.value(Ai(a))} END`;const c=Cl(a,u,n.targetBuckets),d=c.slice(0,-1).map((f,m)=>{const h=c[m+1],y=m===c.length-2?"]":")";return`[${Ai(f)}, ${Ai(h)}${y}`}),p=d.slice(0,-1).map((f,m)=>`WHEN ${t} < ${r.value(c[m+1])} THEN ${r.value(f)}`);return`CASE WHEN ${t} IS NULL THEN ${s} ${p.join(" ")} ELSE ${r.value(d.at(-1))} END`}const o=Dl(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}}},kl={name:"$concat",getFormulaText:xe("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(_r("$concat",t,1,Number.POSITIVE_INFINITY))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},Ul={name:"$count",getFormulaText:({input:t})=>`COUNT(${t??"*"})`,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}}},ql={name:"$countDistinct",getFormulaText:xe("COUNT_DISTINCT"),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}}},jl=new Set(["second","minute","hour","day","week","month","quarter","year"]),xl={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Fa=t=>{if(typeof t!="string"||!jl.has(t))throw new l("INVALID_DATE_BUCKET_ARGS","$dateBucket args.granularity must be second, minute, hour, day, week, month, quarter, or year");return t},Vl={name:"$dateBucket",getFormulaText:xe("DATE_BUCKET"),defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} by ${typeof e.granularity=="string"?e.granularity:"time"}`:`${t}\uFF08\u6309${xl[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,Fa(e.granularity))},getOutputProperty({name:t,inputProperty:e,args:r}){if(!e||e.primal_type!=="date")throw new l("DATE_BUCKET_DATE_REQUIRED","$dateBucket requires a date-valued pred");const n=Fa(r.granularity);return{...e,name:t,type:"date",primal_type:"date",isArray:!1,granularity:n}}},Fl={name:"$divide",getFormulaText:({inputs:t})=>`(${t[0]} / NULLIF(${t[1]}, 0))`,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]=_r("$divide",t,2);return`(${e} / NULLIF(${r}, 0))`},getOutputProperty({name:t}){return Yn(t)}},Bl=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}}}},Hl={name:"$max",getFormulaText:xe("MAX"),defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Maximum ${t}`:`${t}\u6700\u5927\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Bl,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}:{}}}},Ql=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}}}},Yl={name:"$min",getFormulaText:xe("MIN"),defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Minimum ${t}`:`${t}\u6700\u5C0F\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Ql,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}:{}}}},vl={name:"$multiply",getFormulaText:({inputs:t})=>`(${t.join(" * ")})`,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`(${_r("$multiply",t,2,Number.POSITIVE_INFINITY).join(" * ")})`},getOutputProperty({name:t}){return Yn(t)}},Gl=t=>{const e=ge(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},$i=t=>{const e=ge(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=$i(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:$i(r))),e},zl={name:"$newly",getFormulaText:({input:t})=>`(PERIOD_END(${t}) - COALESCE(PERIOD_START(${t}), 0))`,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 l("INVALID_NEWLY_INPUT","$newly pred must be a nested metric");if((t.groupby??[]).some(p=>{const f=ui(p);return f?ne(r,f,n).property.type==="timestamp":!1}))throw new l("NEWLY_TIME_GROUPBY_UNSUPPORTED","$newly does not support grouping by the timestamp property");const s=ja(t.query,e,r,n,"$newly");if(s.start===void 0||s.end===void 0)throw new l("NEWLY_RANGE_REQUIRED","$newly requires both start and end timestamp bounds");const a=$i(e.pred),u=(p,f)=>{const m=Gl(t);return m.query=xa(s.queryWithoutTime,s.propertyName,{$lte:p}),m.preds=[{...a,name:f}],m},c=i("component.end",`${o}\u7ED3\u675F`,{outputName:o}),d=i("component.start",`${o}\u5F00\u59CB`,{outputName:o});return{components:[{name:c,logicform:u(s.end,"__newly_end__")},{name:d,logicform:u(s.start,"__newly_start__")}],expression:`${c} - COALESCE(${d}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$newly requires a nested metric");return{...e,name:t,isArray:!1}}},Wl=t=>{const e=ge(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Ei=t=>{const e=ge(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Ei(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Ei(r))),e},Kl={name:"$periodValue",getFormulaText:({input:t,args:e})=>`${e.boundary==="start"?"PERIOD_START":"PERIOD_END"}(${t})`,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 l("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 l("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");const i=e.args?.boundary;if(i!=="start"&&i!=="end")throw new l("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end");const s=ja(t.query,e,n,o,"$periodValue",he().format("YYYY-MM-DD HH:mm:ss")),a=i==="start"?s.start:s.end;if(a===void 0)throw new l("PERIOD_BOUNDARY_RANGE_REQUIRED",`$periodValue cannot resolve the ${i} of the timestamp query`);const u={version:t.version,schema:n.id,query:{[s.propertyName]:{$lte:a}},preds:[{operator:"$max",pred:s.propertyName,name:"__period_boundary_date__"}]},c=Wl(t);return c.query=xa(s.queryWithoutTime,s.propertyName,u),c.preds=[{...Ei(e.pred),name:r}],{kind:"query",logicform:c,semanticPreds:[e]}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodValue requires a nested metric");return{...e,name:t,isArray:!1}}},Jl=t=>{const e=ge(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Xl=t=>{const{logicform:e,pred:r,outputName:n,t:o}=t;if(!r.pred||typeof r.pred!="object"||Array.isArray(r.pred))throw new Error("$periodDifference pred must be a nested metric");const i=ge(r.pred);i.name="__period_diff_current__";const s=Jl(e);s.preds=[i];const a=Jt([e.query,...Ut(r)]);a&&(s.query=a);const u={pred:ge(r.pred),...r.args?{args:r.args}:{}},c=hi({...t,pred:u,outputName:"__period_diff_prev__"});if(!("logicform"in c))throw new Error("$periodDifference period shift must produce a query component");const d=o("component.current",`${n}\u672C\u671F`,{outputName:n}),p=o("component.previous",`${n}\u4E0A\u671F`,{outputName:n});return{components:[{name:d,logicform:s},{name:p,logicform:c.logicform,comparisonOf:d,...c.partitionQuery?{partitionQuery:c.partitionQuery}:{},...c.groupKeyShifts?{groupKeyShifts:c.groupKeyShifts}:{}}],expression:`${d} - ${p}`}},Zl={name:"$periodDifference",getFormulaText:t=>`(${t.input} - ${pi(t)})`,defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=li(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:Xl,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodDifference requires a nested metric");return{...e,name:t,isArray:!1}}},Ba=(t,e)=>`${t} / NULLIF(ABS(${e}), 0) - 1`,ef=t=>{const e=ge(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},tf=t=>{const{logicform:e,pred:r,outputName:n,t:o}=t;if(!r.pred||typeof r.pred!="object"||Array.isArray(r.pred))throw new Error("$periodGrowth pred must be a nested metric");const i=ge(r.pred);i.name="__period_growth_current__";const s=ef(e);s.preds=[i];const a=Jt([e.query,...Ut(r)]);a&&(s.query=a);const u={pred:ge(r.pred),...r.args?{args:r.args}:{}},c=hi({...t,pred:u,outputName:"__period_growth_prev__"});if(!("logicform"in c))throw new Error("$periodGrowth period shift must produce a query component");const d=o("component.current",`${n}\u672C\u671F`,{outputName:n}),p=o("component.previous",`${n}\u4E0A\u671F`,{outputName:n});return{components:[{name:d,logicform:s},{name:p,logicform:c.logicform,comparisonOf:d,...c.partitionQuery?{partitionQuery:c.partitionQuery}:{},...c.groupKeyShifts?{groupKeyShifts:c.groupKeyShifts}:{}}],expression:Ba(d,p)}},rf={name:"$periodGrowth",getFormulaText:t=>`(${Ba(t.input??"",pi(t))})`,defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=li(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:tf,getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},nf={name:"$sum",getFormulaText:xe("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}}},of={name:"$subtract",getFormulaText:({inputs:t,args:e})=>{const[r,n]=t;return e.nullAsZero===!0?`(COALESCE(${r}, 0) - COALESCE(${n}, 0))`:`(${r} - ${n})`},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]=_r("$subtract",t,2);if(t.args.nullAsZero!==void 0&&typeof t.args.nullAsZero!="boolean")throw new l("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}:Yn(t)}},Ha=t=>{const e=ge(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Ii=t=>{const e=ge(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Ii(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Ii(r))),e},sf={name:"$shareOfTotal",getFormulaText:({input:t})=>`(${t} / NULLIF(TOTAL(${t}), 0))`,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 l("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 l("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||ci(h)===o);if(o!==void 0&&s<0)throw new l("SHARE_OF_TOTAL_DIMENSION_NOT_FOUND",`$shareOfTotal dimension is not grouped: ${o}`);const a=i.filter((h,y)=>y!==s),u=Ii(e.pred),c=Ha(t);c.preds=[{...u,name:"__share_numerator__"}];const d=Jt([t.query,...Ut(e)]);d&&(c.query=d);const p=Ha(t);p.groupby=a,p.preds=[{...u,name:"__share_denominator__"}];const f=n("component.numerator",`${r}\u5206\u5B50`,{outputName:r}),m=n("component.denominator",`${r}\u5206\u6BCD`,{outputName:r});return{components:[{name:f,logicform:c},{name:m,logicform:p}],expression:`${f} / NULLIF(${m}, 0)`}},getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},af={name:"$substring",getFormulaText:xe("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 l("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 l("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}}},Qa=(t,e,r,n="$sql")=>{if(typeof t!="string"||t.trim().length===0)throw new l("INVALID_SQL_ARGS",`${n} requires a non-empty args.sql expression`);let o="",i=0,s;for(let a=0;a<t.length;a+=1){const u=t[a];if(!u)continue;if(s){o+=u,u===s&&(t[a+1]===s?(o+=s,a+=1):s=void 0);continue}if(u==="'"||u==='"'||u==="`"){s=u,o+=u;continue}const c=t.slice(a,a+2);if(u===";"||c==="--"||c==="/*")throw new l("INVALID_SQL_EXPRESSION",`${n} accepts one expression and does not allow statements or SQL comments`);if(u==="?"){if(i>=e.length)throw new l("INVALID_SQL_PARAMETERS",`${n} contains more placeholders than args.parameters values`);o+=r(e[i]),i+=1;continue}o+=u}if(s)throw new l("INVALID_SQL_EXPRESSION",`${n} contains an unterminated quote`);if(i!==e.length)throw new l("INVALID_SQL_PARAMETERS",`${n} args.parameters contains more values than SQL placeholders`);return o},cf=new Set(["boolean","date","number","entity","object","string"]),uf=t=>{if(t===void 0)return[];if(!Array.isArray(t))throw new l("INVALID_SQL_ARGS","$sql args.parameters must be an array");return t},df=(t,e,r=Mt())=>{const n=e.type;if(typeof n!="string"||n.length===0)throw new l("INVALID_SQL_OUTPUT","$sql requires args.type");const o=r.get(n),i=o.primalType==="object"?"entity":o.primalType;if(e.primal_type!==void 0){const s=e.primal_type==="object"?"entity":e.primal_type;if(!cf.has(e.primal_type)||s!==i)throw new l("INVALID_SQL_OUTPUT",`$sql requires a valid args.primal_type matching args.type (${n}: ${i})`)}if(e.isArray!==void 0&&typeof e.isArray!="boolean")throw new l("INVALID_SQL_OUTPUT","$sql args.isArray must be boolean");if(e.ref!==void 0&&typeof e.ref!="string")throw new l("INVALID_SQL_OUTPUT","$sql args.ref must be a Schema id");return{name:t,type:n,primal_type:i,isArray:typeof e.isArray=="boolean"?e.isArray:o.isArray??!1,...typeof e.ref=="string"?{ref:e.ref}:{}}},pf={name:"$sql",getFormulaText:({args:t})=>`SQL(${JSON.stringify(t.sql)}${t.parameters===void 0?"":`, parameters=${JSON.stringify(t.parameters)}`})`,defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Calculated value":"\u8BA1\u7B97\u503C",kind:"scalar",requiresProperty:!1,createQueryComponent({logicform:t,pred:e,outputName:r}){const{query:n,...o}=e;return{kind:"query",logicform:{...t,query:t.query&&Object.keys(t.query).length>0?{$and:[t.query,n??{}]}:n??{},preds:[{...o,name:r}]}}},toSQL({args:t,expression:e,expressions:r,sql:n}){if(e||r&&r.length>0)throw new l("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return Qa(t.sql,uf(t.parameters),o=>n.value(o))},getOutputProperty({name:t,args:e,inputProperty:r,inputProperties:n,semanticTypes:o}){if(r||n&&n.length>0)throw new l("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return df(t,e,o)}},lf=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]},ff=t=>typeof t.pred!="string"?t:{...t,pred:{operator:"$sum",pred:t.pred,name:`${t.pred}\u5408\u8BA1`}},mf=(t,e,r)=>{const n=t.preds;if(n.filter(d=>d.operator==="$rank"&&d.query).length!==1)throw new l("AMBIGUOUS_RANK_TARGET","A LogicForm without groupby must contain exactly one $rank pred.query target");const i=lf(r),[s]=i;if(i.length!==1||!s)throw new l("AMBIGUOUS_RANK_DIMENSION","$rank pred.query must reference exactly one property when groupby is omitted",{properties:i});const a=ge(t);a.groupby=[{pred:s,name:s}],a.preds=n.map(d=>{if(d.name!==e.name)return d;const p={...d};return delete p.query,ff(p)}),delete a.sort,delete a.limit,delete a.limitBy,delete a.page,delete a.output,delete a.representation;const u=n.map(({name:d})=>d).filter(d=>!!d),c=ge(t);return c.from=a,c.query=r,c.preds=[{pred:s,name:s},...u.map(d=>({pred:d,name:d}))],delete c.groupby,delete c.having,delete c.entity_id,delete c.propertyResolve,c},yf={name:"$rank",getFormulaText:xe("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?mf(t,e,e.query):void 0},validatePlan({pred:t,groupByNames:e}){if(!t.pred||Array.isArray(t.pred))throw new l("INVALID_WINDOW_OPERATOR_INPUT","$rank requires exactly one pred");if(e.length===0&&!t.query&&typeof t.pred!="string")throw new l("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}}},hf={name:"$rowNumber",getFormulaText:xe("ROW_NUMBER"),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}}},gf=new Set(["string","number","boolean","date","entity","object"]),_i=t=>{if(t==="timestamp"||t==="date")return{type:t,primal_type:"date"};if(typeof t=="string"&&gf.has(t))return{type:t,primal_type:t};throw new l("INVALID_CONSTANT_TYPE","$constant args.type must be timestamp, date, string, number, boolean, entity, or object")},wf={name:"$constant",getFormulaText:({args:t})=>JSON.stringify(t.value??null),defaultName:({locale:t})=>t.toLowerCase().startsWith("en")?"Constant":"\u5E38\u91CF",kind:"scalar",requiresProperty:!1,normalizePred({pred:t}){if(t.pred!==void 0)throw new l("INVALID_CONSTANT_INPUT","$constant does not accept pred");return _i(t.args?.type),t},toSQL({args:t,sql:e}){return _i(t.type),e.value(t.value,t.type)},getOutputProperty({name:t,args:e}){return{name:t,..._i(e.type),isArray:!1}}},Af={name:"$periodBoundary",getFormulaText:xe("PERIOD_BOUNDARY"),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 l("PRED_PROPERTY_REQUIRED","$periodBoundary requires pred");const n=e.boundary;if(n!=="start"&&n!=="end")throw new l("INVALID_PERIOD_BOUNDARY_ARGS","$periodBoundary args.boundary must be start or end");const o=e.granularity;if(typeof o!="string")throw new l("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 l("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 l("PERIOD_BOUNDARY_DATE_REQUIRED","$periodBoundary requires a date-valued pred");const n=e.granularity??r.granularity;if(typeof n!="string")throw new l("END_OF_PERIOD_GRANULARITY_REQUIRED","$periodBoundary requires the input Property granularity");return{...e,name:t,granularity:n,isArray:!1}}},Ya="__scalarExtremumInputs",bi=t=>{if(t.schema)return t.schema;if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred))return bi(t.pred);if(Array.isArray(t.pred)){const e=[...new Set(t.pred.flatMap(r=>typeof r=="string"?[]:bi(r)??[]))];if(e.length===1)return e[0]}},$f=t=>{const e=ge(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},Ef=(t,e)=>{if(e.args?.[Ya]===!0||!Array.isArray(e.pred))return;if(t.preds?.length!==1)throw new l("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}:ge(o),a=s.name??`__scalar_extremum_input_${i}__`,u=s.schema??bi(s);return{...s,name:a,...u?{schema:u}:{}}}),n=$f(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,[Ya]:!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}:{}}},If=(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)`},_f=(t,e,r)=>{const[n,...o]=r??[];if(!n)throw new l("INVALID_OPERATOR_INPUTS",`${t} requires pred inputs`);if(o.some(({primal_type:i})=>i!==n.primal_type))throw new l("INCOMPATIBLE_OPERATOR_INPUTS",`${t} pred inputs must have the same primal type`);return{...n,name:e,isArray:!1}},va=t=>({name:t,getFormulaText:xe(t==="$least"?"LEAST":"GREATEST"),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 l("INVALID_OPERATOR_INPUTS",`${t} requires at least two pred inputs`);return e},rewriteLogicform({logicform:e}){const r=e.preds?.[0];return r?.operator===t?Ef(e,r):void 0},toSQL(e){const r=_r(t,e,2,Number.POSITIVE_INFINITY);return e.sql.scalarExtremum?.(t==="$least"?"least":"greatest",r)??If(t,r)},getOutputProperty({name:e,inputProperties:r}){return _f(t,e,r)}}),bf=va("$least"),Sf=va("$greatest"),Si={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"}},Nf={name:"$length",getFormulaText:xe("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 l("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 l("LENGTH_STRING_REQUIRED","$length requires a scalar string-valued pred");return{name:t,type:"int",primal_type:"number",isArray:!1}}},Rf=t=>({name:`$${t}`,getFormulaText:xe(t.toUpperCase()),defaultName:({operandName:e,locale:r})=>r.toLowerCase().startsWith("en")?`${e} ${Si[t].en}`:`${e}${Si[t].zh}`,kind:"scalar",toSQL({expression:e,sql:r}){if(!e)throw new l("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 l("DATE_PART_DATE_REQUIRED",`$${t} requires a scalar date-valued pred`);return{name:e,type:"int",primal_type:"number",isArray:!1}}}),Of=Object.freeze(Object.keys(Si).map(Rf)),Ga=Object.freeze([fl,nf,Ul,ql,Tl,Yl,Hl,Il,rf,Zl,Ol,Kl,zl,yl,of,vl,Fl,ml,sf,Ml,kl,af,Vl,pf,yf,hf,wf,Af,bf,Sf,Nf,...Of]),Tf=(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},za=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","getFormulaText","getOutputProperty","planInput","normalizePred","planExpression","periodBoundaryPolicy","validatePlan","rewriteLogicform","requiresPerPeriodEvaluation","toSQL","createComponent","createQueryComponent","run"]),s=Object.fromEntries(Object.entries(e).filter(([a])=>!i.has(a)));s.name=r;for(const a of i){const u=Tf(e[a],a,n);u&&(s[a]=u)}if(!s.getOutputProperty&&typeof o=="string"){const a=ei.find(({name:u})=>u===o);if(!a)throw new TypeError(`Semantic type is not registered: ${o}`);s.getOutputProperty=()=>({name:n,type:o,primal_type:a.primalType,isArray:!1})}return s};class Vr{executionContext;#e=new Set;#t=new Map;constructor(e=[],r=Object.freeze({}),n=[]){this.executionContext=r;for(const o of e)this.register(o);for(const o of n)this.#e.add(o.name)}withExecutionContext(e){return new Vr(this.definitions(),e,this.definitions().filter(({name:r})=>this.isBuiltin(r)))}register(e){if("evaluate"in e)throw new l("INVALID_OPERATOR","Operator evaluate is no longer supported");const r=za(e);if(!r.name)throw new l("INVALID_OPERATOR","Operator name must not be empty");if(typeof r.defaultName!="function")throw new l("INVALID_OPERATOR",`Operator must implement defaultName: ${r.name}`);if(this.#t.has(r.name))throw new l("OPERATOR_ALREADY_REGISTERED",`Operator is already registered: ${r.name}`,{operator:r.name});const n=r;if(!(n.kind==="scalar"&&typeof n.toSQL=="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"||n.kind==="runtime"&&typeof n.run=="function"))throw new l("INVALID_OPERATOR",`Operator kind and implementation do not match: ${r.name}`);return this.#t.set(r.name,r),this}isBuiltin(e){return this.#e.has(e)}get(e){const r=this.#t.get(e);if(!r)throw new l("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}isComponent(e){if(!e.operator)return!1;const r=this.get(e.operator);return r.kind==="component"||r.kind==="scalar"&&r.createQueryComponent!==void 0&&e.query!==void 0&&Object.keys(e.query).length>0}has(e){return this.#t.has(e)}definitions(){return[...this.#t.values()]}}const Wa=Object.freeze([...Ga,...hr.flatMap(({operators:t})=>t??[])]),at=(t=[])=>new Vr([...Ga,...Pe(t).flatMap(({operators:e})=>e??[])],Object.freeze({}),Wa),Pf=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="output-reference"&&typeof t.name=="string",qt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="logicform-subquery"&&typeof t.plan=="object"&&t.plan!==null,Ka=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="query-operator"&&typeof t.operator=="string",Lf=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="ordinal-query",zn=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="expression-query",Cf=(t,e)=>{const r=Ea(t,e);return{schemaId:t.id,propertyId:r.id,propertyName:r.name,physicalColumn:r.udf?.sql??r.id}},Ja=(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}:Cf(e,r)},Xt=(t,e,r,n)=>{if(t.kind==="mapping-computation"){const u=Object.values(t.inputs).map(c=>Xt(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c),`computation:${t.definition.id}`]}}if(t.kind==="column"){const u=e.sourcePlan??e.mappingSourcePlan,c=u?.projections.find(({name:d})=>d===t.column);return c&&u&&t.qualifier===e.sourceAlias?Xt(c.expression,u,r,n):{sources:[{schemaId:t.schemaId??r.id,propertyId:t.propertyId??t.column,propertyName:t.property,physicalColumn:t.column}],transformations:["projection"]}}if(t.kind==="property-sql")return{sources:[{schemaId:t.schemaId,propertyId:t.propertyId,propertyName:t.property,physicalColumn:t.sql}],transformations:["property-sql"]};if(t.kind==="array-element")return{sources:[{schemaId:t.schemaId,propertyId:t.property,propertyName:t.property,physicalColumn:t.property}],transformations:["array-expand"]};if(t.kind==="window"){const u=[t.input,...t.partitionBy].map(c=>Xt(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:${t.function}`]}}if(t.kind==="cumulative"){const u=[t.input,...t.partitionBy,...t.orderBy.map(({expression:c})=>c)].map(c=>Xt(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:cumulative:${t.function}`]}}if(t.kind==="ordinal-encode"||t.kind==="ordinal-decode"){const u=Xt(t.input,e,r,n);return{sources:u.sources,transformations:[...u.transformations.filter(c=>c!=="projection"),`ordinal:${t.kind==="ordinal-encode"?"encode":"decode"}`]}}const o=[...t.input?[t.input]:[],...t.inputs??[]].map(u=>Xt(u,e,r,n)),i={sources:o.flatMap(({sources:u})=>u),transformations:o.flatMap(({transformations:u})=>u)},s=n.get(t.operator),a=new Set([...t.property?[t.property]:[],...s.dependencies??[],...Wn(t.query)]);return{sources:[...i.sources,...[...a].filter(u=>!i.sources.some(c=>c.propertyName===u)).map(u=>Ja(e,r,u))],transformations:[...i.transformations.filter(u=>u!=="projection"),`operator:${t.operator}`]}};function Wn(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(...Wn(o));else r==="$expr"&&zn(n)?e.push(...n.properties):r.startsWith("$")||e.push(r);return e}const bt=t=>t.kind==="window"?[...bt(t.input),...t.partitionBy.flatMap(bt)]:t.kind==="cumulative"?[...bt(t.input),...t.partitionBy.flatMap(bt),...t.orderBy.flatMap(({expression:e})=>bt(e))]:t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?bt(t.input):t.kind==="operator"?[...Wn(t.query),...t.input?bt(t.input):[],...(t.inputs??[]).flatMap(bt)]:[],Ni=t=>[...(t.computationSources??[]).map(({source:e})=>e),...(t.enrichmentJoins??[]).map(({source:e})=>e.identity),...t.sourcePlan?Ni(t.sourcePlan):[],...t.mappingSourcePlan?Ni(t.mappingSourcePlan):[]],Xa=(t,e,r,n=at(),o,i)=>{if(t.subplans){const a=t.subplans.map(c=>Xa(c,c.schemaId===e.id?e:i?.(c.schemaId)??e,r,n,o,i)),u=new Map;for(const c of a){c.source.connectionId&&u.set(c.source.connectionId,c.source.provider);for(const d of c.source.connections??[])u.set(d.connectionId,d.provider)}return{source:{schemaId:e.id,schemaName:e.name,physicalTable:a.map(({source:c})=>c.physicalTable).join(", "),provider:r.kind,connections:[...u].map(([c,d])=>({connectionId:c,provider:d}))},outputs:t.projections.map(({name:c})=>{const d=a.flatMap(({outputs:p})=>p.filter(f=>f.name===c));return{name:c,sources:d.flatMap(({sources:p})=>p),transformations:[...new Set([...d.flatMap(({transformations:p})=>p),t.sumPartition?"sum-partition":t.rowPartition?"row-partition":t.splitGroup?"split-group":"compose"])]}}),filters:a.flatMap(({filters:c})=>c)}}const s=t.connectionId&&o?o(t.connectionId):r;return{source:{schemaId:e.id,schemaName:e.name,physicalTable:[t.source?.identity,...new Set(Ni(t))].filter(Boolean).join(", "),provider:s.kind,...t.connectionId?{connectionId:t.connectionId}:{}},outputs:t.projections.map(a=>({name:a.name,...Xt(a.expression,t,e,n)})),filters:[...new Set([...Wn(t.query),...t.projections.flatMap(({expression:a})=>bt(a))])].map(a=>Ja(t,e,a))}},Df=(t,e)=>{const r={},n=new Map;return{sql:t.replace(/'(?:''|\\.|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:\]\]|[^\]])*\]|\$TS|[A-Za-z_\u0080-\uffff][A-Za-z0-9_\u0080-\uffff]*/g,(i,s)=>{if(i.startsWith("'")||/^\s*\(/.test(t.slice(s+i.length)))return i;const a=i.startsWith('"')?i.slice(1,-1).replaceAll('""','"'):i.startsWith("`")?i.slice(1,-1).replaceAll("``","`"):i.startsWith("[")?i.slice(1,-1).replaceAll("]]","]"):i,u=i==="$TS"?e.properties.find(({type:d})=>d==="timestamp"):e.properties.find(({id:d,name:p})=>a===d||a===p);if(!u&&i==="$TS")throw new l("PROPERTY_UDF_TIMESTAMP_REQUIRED","Property UDF requires a timestamp Property");if(!u)return i;let c=n.get(u.id);return c||(c=`property_${n.size}`,n.set(u.id,c),r[c]=u.id),`{{${c}}}`}),references:r}};class Za{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){if(!e.name)throw new l("INVALID_SEMANTIC_RULE","Semantic rule name must not be empty");if(this.#e.has(e.name))throw new l("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 ec=(t=[])=>new Za([...Pe(t).flatMap(e=>e.plannerSemantics??[])]);he.extend($s),he.extend(Fr),he.extend(Nn);const Sr=["second","minute","hour","day","week","month","quarter","year"],Mf=new Set(["$second","$minute","$hour","$day","$week","$month","$quarter","$year"]),kf="YYYY-MM-DD HH:mm:ss",jt=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),Uf=(t,e)=>t==="week"?e==="week":e==="week"?Sr.indexOf(t)<=Sr.indexOf("day"):Sr.indexOf(t)<=Sr.indexOf(e),tc=(t,e,r)=>{if(typeof t!="string")return"second";const n=he(t,kf,!0);if(!n.isValid())return"second";for(const o of[...Sr].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"},rc=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])=>Mf.has(r)?[r.slice(1)]:r==="$weekday"?["day"]:r==="$and"||r==="$or"?Array.isArray(n)?n.flatMap(rc):["second"]:r==="$gte"||r==="$gt"?[tc(n,"lower",r==="$gte")]:r==="$lte"||r==="$lt"?[tc(n,"upper",r==="$lte")]:["second"])},qf=(t,e,r)=>{if(e.primal_type==="date"){if(t.operator){const n=r.get(t.operator).groupedSourceTimeGranularity?.({pred:t,property:e});if(n&&Sr.includes(n))return n}return e.granularity??"day"}},jf=(t,e,r,n,o=Pe(),i=at(o))=>{const s=r.mappings??[],a=s.filter(w=>w.mappingType==="property").filter(w=>w.granularity!==void 0),u={schema:e,mapping:r,...n?{resolveSchema:n}:{}};if(a.some(w=>!ca(w.granularity,o)))return"physical granularity is not supported by the active plugins";if(a.find(w=>Un(w.granularity)&&jt(e,w.propertyId)?.primal_type!=="date"))return"physical time granularity requires mapped date Properties";for(const w of a)for(const E of o){const N=E.mappingGranularity;if(!N||!N.isGranularity(w.granularity))continue;const I=N.validateItem?.(w,u);if(I)return I}if(!(a.length>0))return;const p=w=>s.filter(E=>E.mappingType==="property").find(E=>jt(e,E.propertyId)?.id===w.id),f=(w,E,N="filterOrGroup")=>{const I=jt(e,w);if(!I)return`property is not available: ${w}`;const S=p(I);if(!S&&!(N==="operand"&&s.some(D=>D.mappingType==="predItem"&&typeof D.predItem.pred=="string"&&jt(e,D.predItem.pred)?.id===I.id)))return`property is not available on grouped source: ${w}`;if(N==="filterOrGroup"&&I.primal_type==="number"&&I.type!=="category"&&I.type!=="ID")return`measure cannot be used as a grouped source dimension: ${w}`;if(I.primal_type==="date"&&(!S?.granularity||!Un(S.granularity)||!Uf(S.granularity,E??I.granularity??"day")))return`time dimension ${w} is too coarse for ${E}`};function m(w){if(w)for(const[E,N]of Object.entries(w)){if(N===void 0)continue;if(E==="$and"||E==="$or"){if(!Array.isArray(N))return"unsupported dimension query";for(const D of N){const b=m(D);if(b)return b}continue}if(E==="$expr"){if(typeof N!="object"||N===null||Array.isArray(N))return"unsupported expression query";const D=N.pred;if(typeof D!="object"||D===null||Array.isArray(D))return"unsupported expression query";const b=h(D);if(b)return b;continue}if(E.startsWith("$"))return"unsupported dimension query";const I=jt(e,E);if(!I)return`dimension property is not available: ${E}`;const S=I.primal_type==="date"?rc(N):[void 0];for(const D of S){const b=f(E,D);if(b)return b}}}function h(w){const E=m(w.query);if(E)return E;const N=Array.isArray(w.pred)?w.pred:w.pred===void 0?[]:[w.pred];for(const I of N){const S=typeof I=="string"&&(w.operator==="$max"||w.operator==="$min")?jt(e,I):void 0,D=typeof I=="string"&&!w.operator?jt(e,I):void 0,b=S?.primal_type==="date"?S:D?.primal_type==="date"?D:void 0,T=b?p(b)?.granularity:void 0,M=typeof I=="string"?f(I,Un(T)?T:void 0,"operand"):h(I);if(M)return M}}const y=m(t.query);if(y)return y;const $=!t.groupby?.length&&(t.preds??[]).every(w=>!w.operator&&typeof w.pred=="string");if(!t.preds?.length&&t.groupby?.length)return"grouped query requires an aggregating PredItem";for(const w of t.preds??[]){const E=h(w);if(E)return E;if(!$&&(typeof w.pred!="string"||!w.operator||!i.get(w.operator).supportsGroupedSourceRollup))return`PredItem ${w.operator??"(projection)"} cannot be rolled up from a grouped source`}for(const w of t.groupby??[]){if(typeof w.pred!="string")return"computed groupby is not covered by the grouped source";const E=jt(e,w.pred);if(!E)return`groupby property is not available: ${w.pred}`;if(w.operator!==void 0&&!i.get(w.operator).supportsGroupedSourceGroupby&&!o.some(I=>I.mappingGranularity?.supportsGroupby?.(w)))return`computed groupby is not covered: ${w.pred}`;const N=f(w.pred,qf(w,E,i));if(N)return N}for(const w of o){const E=w.mappingGranularity?.candidateReason?.(t,u);if(E)return E}};function Zt(t){return[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Zt(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Zt(e)):[]]}const Nr=It,er=(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)=>er(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)&&er(i,n[o]))},tr=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=tr(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=Zt(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},Kn=(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(u=>Kn(u,e,r,n)).filter(u=>u!==void 0);a.length>0&&(o[i]=a);continue}i!=="$or"&&e.some(a=>ft(r,a.property,i,n)&&er(a.condition,s))||(o[i]=s)}return Object.keys(o).length>0?o:void 0},rr=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),ft=(t,e,r,n)=>{if(e===r)return!0;const o=rr(t,e),i=rr(t,r);if(o&&i)return o.id===i.id;if(!n)return!1;try{return ne(t,e,n).canonicalId===ne(t,r,n).canonicalId}catch{return!1}},nc=(t,e,r)=>{let n=t;const o=[];for(const a of e.path){const u=n.properties.find(c=>c.id===a)??n.properties.find(c=>c.name===a);if(!u?.ref||u.primal_type!=="entity"&&u.primal_type!=="object")throw new l("INVALID_SCHEMA_MAPPING",`Query path mapping must follow entity relations: ${e.path.join(".")}`);o.push(u.id),n=r(u.ref)}const i=ne(t,e.path.join("_"),r),s=[...i.relations.map(({property:a})=>a.id),i.property.id];if(s.length!==o.length||s.some((a,u)=>a!==o[u]))throw new l("INVALID_SCHEMA_MAPPING",`Query path mapping does not match the resolved relation path: ${e.path.join(".")}`);return{path:i,targetSchema:n,relationIds:o}},xf=(t,e,r,n,o)=>{if(!r.queryPathMappings?.length||!t.query)return{logicform:t,filters:[],matchCount:0,consumed:[]};if(!n)return{reason:"query path mappings require a Schema resolver"};const i=tr(t.query);if(!i)return{logicform:t,filters:[],matchCount:0,consumed:[]};const s=[],a=[];let u=0;for(const p of r.queryPathMappings){const{path:f,targetSchema:m,relationIds:h}=nc(e,p,n),y=Fn(m,o?.filter(T=>!hr.includes(T))),$=`${f.canonicalName}_${y.name}`,w=i.filter(({property:T})=>{try{const M=ne(e,T,n),Y=[...M.relations.map(({property:C})=>C.id),M.property.id];return Y.length>=h.length&&h.every((C,O)=>Y[O]===C)}catch{return!1}});if(w.length===0)continue;for(const T of w){if(s.some(M=>M===T))throw new l("INVALID_SCHEMA_MAPPING",`Multiple query path mappings consume ${T.property}`);s.push(T)}const E=w.filter(({property:T,condition:M})=>ft(e,T,$,n)&&zt(M)),N=w.length===1&&E.length===1?E[0]?.condition:void 0,I=w.length===1&&ft(e,w[0]?.property??"",f.canonicalName,n)&&typeof w[0]?.condition=="object"&&w[0].condition!==null?w[0].condition.$in:void 0;if(Re(I)){const T=I.preds?.[0];if(I.preds?.length===1&&(I.groupby?.length||T?.operator||T?.pred!==y.id&&T?.pred!==y.name))throw new l("INVALID_QUERY_PATH_VALUE",`Query path value must project the entity ID: ${f.canonicalName}`)}const S=[];if(N===void 0&&!Re(I))for(const T of w){const Y=ne(e,T.property,n).canonicalName.slice(f.canonicalName.length+1);if(!Y)throw new l("INVALID_SCHEMA_MAPPING",`Query path mapping requires a scalar ID or an entity query: ${f.canonicalName}`);S.push({[Y]:T.condition})}const D=S.length===1?S[0]:{$and:S},b=N??(Re(I)?I:{version:t.version,schema:m.id,query:D,preds:[{pred:y.name,name:y.name}]});for(const T of p.bindings)a.push({sourceColumn:T.sourceColumn,value:T.mappingType==="literal"?T.value:b});u+=1}if(s.length===0)return{logicform:t,filters:a,matchCount:u,consumed:s};const c=ge(t),d=Kn(c.query,s,e,n);return d?c.query=d:delete c.query,{logicform:c,filters:a,matchCount:u,consumed:s}},Vf=(t,e,r,n,o)=>{if(!t.groupby?.length||!r.queryPathMappings?.length||!n)return{bindings:[],filters:o};const i=[],s=[...o];for(const a of t.groupby){if(a.operator||typeof a.pred!="string")continue;const u=ne(e,a.pred,n);for(const c of r.queryPathMappings){const{path:d,targetSchema:p}=nc(e,c,n);if(d.canonicalId!==u.canonicalId)continue;const f=c.bindings.filter(h=>h.mappingType==="value"),m=f[0];if(f.length!==1||!m)return{reason:`groupby path ${a.pred} requires exactly one value binding`};i.push({canonicalId:u.canonicalId,sourceColumn:m.sourceColumn,targetSchemaId:p.id});for(const h of c.bindings){if(h.mappingType!=="literal")continue;const y=s.find($=>$.sourceColumn===h.sourceColumn);if(y&&!er(y.value,h.value))return{reason:`groupby path ${a.pred} conflicts with a query path binding on ${h.sourceColumn}`};y||s.push({sourceColumn:h.sourceColumn,value:h.value})}}}return{bindings:i,filters:s}},Be=(t,e,r)=>{const n=xt(t,e,r);if(n)return n.column},xt=(t,e,r)=>{const n=rr(e,r);if(!n||Er(n))return;const o=t.mappings?.filter(s=>s.mappingType==="property"&&ft(e,s.propertyId,r))??[];if(o.length>1)throw new l("INVALID_SCHEMA_MAPPING",`Property ${n.id} has multiple value mappings`);const i=o[0];return i?.mappingType==="property"?i.value.kind==="column"?{column:i.value.column,...i.value.sourceRef?{sourceRef:i.value.sourceRef}:{}}:{column:n.id,calculation:i.value,propertyId:i.propertyId}:(t.mappings??[]).some(s=>s.mappingType==="property"||s.mappingType==="predItem")?void 0:{column:n.id}},Rr=(t,e,r,n)=>{if(!n)return;let o;try{o=ne(e,r,n)}catch(s){if(s instanceof l&&s.code==="PROPERTY_NOT_FOUND")return;throw s}if(o.relations.length===0)return;const i=(t.mappings??[]).find(s=>{if(s.mappingType!=="property"||s.value.kind!=="column")return!1;try{return ne(e,s.propertyId,n).canonicalId===o.canonicalId}catch{return!1}});return i?.mappingType==="property"&&i.value.kind==="column"?{column:i.value.column,...i.value.sourceRef?{sourceRef:i.value.sourceRef}:{}}:void 0},Or=(t,e,r,n)=>{if(!n)return;const o=rr(e,r);if(!o?.ref||o.primal_type!=="entity"&&o.primal_type!=="object")return;const s=n(o.ref).properties.filter(({type:u})=>u==="ID"),[a]=s;if(!(s.length!==1||!a))return Rr(t,e,`${o.id}_${a.id}`,n)},nr=(t,e,r,n,o)=>!(t.mappings??[]).some(i=>i.mappingType==="property"||i.mappingType==="predItem")||Be(t,e,r)!==void 0||Or(t,e,r,n)!==void 0||Rr(t,e,r,n)!==void 0||o!==void 0&&Jn(t,e,r,o,n),Jn=(t,e,r,n,o,i=[])=>{if(nr(t,e,r,o))return!0;if(!o)return!1;try{const s=Xo(ne(e,r,o),o);if(i.some(({canonicalId:u})=>u===s.canonicalId))return!0;if(s.relations.length===0)return!1;for(const u of s.relations){const c=u.sourceSchema.id===e.id?t:n.get(u.sourceSchema.id,t.connectionId),d=Vn(u),p=xt(c,u.sourceSchema,d.source.id)??Or(c,u.sourceSchema,d.source.id,o),f=n.get(u.targetSchema.id,t.connectionId);if(!p||p.sourceRef||Be(f,u.targetSchema,d.target.id)===void 0)return!1}const a=n.get(s.schema.id,t.connectionId);return xt(a,s.schema,s.property.id)!==void 0||Or(a,s.schema,s.property.id,o)!==void 0}catch{return!1}},oc=(t,e,r,n,o)=>{if(!t||!(e.mappings??[]).some(a=>a.mappingType==="property"||a.mappingType==="predItem"))return;const s=Gt({query:t}).find(({reference:a})=>!nr(e,r,a,n,o));return s?`query property is not available: ${s.reference}`:void 0},Ff=(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"?rr(r,e.pred):void 0,u=rr(r,t.match.pred);if(!(typeof e.pred=="string"&&ft(r,e.pred,t.match.pred)&&!!(a&&u))||!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 d=tr(t.match.query);return d!==void 0&&d.every(p=>o.some(f=>ft(r,f.property,p.property,i)&&er(f.condition,p.condition)))},Bf=(t,e,r,n,o,i,s=at(i))=>{const a=t,u=xf(t,e,r,o,i);if("reason"in u)return u;const c=Vf(t,e,r,o,u.filters);if("reason"in c)return c;for(const{targetSchemaId:C}of c.bindings)try{n.list(C)}catch(O){if(O instanceof l&&O.code==="SCHEMA_MAPPING_NOT_FOUND")return{reason:`groupby entity ${C} has no Schema mapping for result hydration`};throw O}t=u.logicform;const d=(r.mappings??[]).flatMap(C=>{if(C.mappingType!=="predItem"||!C.sourceColumn||typeof C.predItem.pred!="string")return[];const O=C.predItem,L=O.operator,q=O.pred;return typeof q!="string"?[]:[{match:{pred:q,...L?{operator:L}:{},...O.schema?{schema:O.schema}:{},...O.query?{query:O.query}:{}},column:C.sourceColumn,...C.propertyTarget?{propertyTarget:C.propertyTarget}:{}}]}),p=(r.mappings??[]).some(C=>C.mappingType==="property");if(d.length===0&&!p){const C={schema:e,mapping:r,...o?{resolveSchema:o}:{}};for(const O of i??[]){const L=O.schemaMapping?.candidateReason?.(t,C);if(L)return L}return{mapping:r,logicform:t,predRewrites:[],physicalQueryFilters:c.filters,groupPathBindings:c.bindings,priority:r.priority??0,specificity:u.matchCount}}const f=tr(a.query),m=ge(t),h=[],y=[],$=new Map,w=C=>nr(r,e,C,o,n)||d.some(O=>{const L=tr(O.match.query)??[];return L.some(Q=>ft(e,Q.property,C,o))?(O.propertyTarget?.length?[O.propertyTarget.join("_")]:L.map(({property:Q})=>Q)).some(Q=>ft(e,Q,C,o)):!1}),E=C=>{let O=rr(e,C),L=O?.name;if(!O&&o)try{const q=ne(e,C,o);O=q.property,L=q.canonicalName}catch{return}if(!(!O||O.primal_type==="number"&&O.type!=="category"&&O.type!=="ID"))return L},N=()=>{const C=new Set;for(const{reference:O,use:L}of Gt(m)){if(L!=="query"||w(O))continue;const q=E(O);q&&C.add(q)}for(const O of m.groupby??[])for(const L of Zt(O)){if(Jn(r,e,L,n,o,c.bindings))continue;const q=E(L);q&&C.add(q)}return[...C]},I=C=>{const O=N();return{reason:C,...O.length>0?{missingDimensions:O}:{}}};for(const{reference:C,use:O}of Gt(t)){if(O==="pred"||!E(C))continue;if(!(O==="groupby"?Jn(r,e,C,n,o,c.bindings):w(C)))return I(`${O} property is not available: ${C}`)}if(!f&&d.length>0)return"query contains $or or another unsupported logical expression";for(const[C,O]of(t.preds??[]).entries()){const L=tr(O.query);if(!L&&d.length>0)return`PredItem ${C} query contains an unsupported logical expression`;if(d.length>0){const Q=t.groupby?.length?[...L??[]]:[...f??[],...L??[]],j=d.filter(x=>Ff(x,O,e,O.schema??e.id,Q,o,s));if(j.length===0){const x=Zt(O);if(!(x.length===0&&O.operator!==void 0&&s.get(O.operator).requiresProperty===!1)&&(x.length===0||x.some(G=>!nr(r,e,G,o,n))))return`PredItem ${C} is not mapped`;continue}if(j.length>1)return`PredItem ${C} matches multiple mapping rules`;const oe=j[0],H=tr(oe.match.query)??[];$.set(C,H),t.groupby?.length||y.push(...H);const R=m.preds?.[C];if(R){const x=Kn(R.query,H,e,o);x?R.query=x:delete R.query}h.push({predIndex:C,column:oe.column});continue}const q=Zt(O).find(Q=>!nr(r,e,Q,o,n));if(q)return`PredItem ${C} property is not available: ${q}`}const S=(f??[]).filter(({property:C,condition:O})=>!nr(r,e,C,o,n)&&!u.consumed.some(L=>ft(e,L.property,C,o)&&er(L.condition,O)));for(const[C]of(t.preds??[]).entries()){const O=S.find(L=>!$.get(C)?.some(q=>ft(e,q.property,L.property,o)&&er(q.condition,L.condition)));if(O){const L=E(O.property);return{reason:`PredItem ${C} cannot apply root query dimension: ${O.property}`,...L?{missingDimensions:[L]}:{}}}}const D=Kn(m.query,y,e,o);D?m.query=D:delete m.query;const b=oc(m.query,r,e,o,n);if(b)return b.startsWith("query property is not available:")?I(b):b;for(const[C,O]of(m.preds??[]).entries()){const L=oc(O.query,r,e,o,n);if(L)return L.startsWith("query property is not available:")?I(`PredItem ${C} ${L}`):`PredItem ${C} ${L}`}for(const C of m.groupby??[]){const L=Zt(C).find(q=>!Jn(r,e,q,n,o,c.bindings));if(L)return I(`groupby property is not available: ${L}`)}const T=(C,O,L,q=[])=>{try{if(!n.definitions().some(x=>x.mappings?.some(F=>F.mappingType==="property"&&F.value.kind!=="column")))return;const Q=Xo(ne(C,L,o),o);if(Rr(O,C,L,o)||C.id===e.id&&c.bindings.some(({canonicalId:x})=>x===Q.canonicalId))return;const j=Q.relations.length?n.get(Q.schema.id,O.connectionId):O,oe=xt(j,Q.schema,Q.property.id);if(!oe?.calculation)return;const H=`${Q.schema.id}:${It(j)}:${Q.property.id}`;if(q.includes(H))return`Cyclic computation dependency: ${[...q,H].join(" -> ")}`;const R=oe.calculation;if(j.connectionId!==O.connectionId)return"Computation inputs must use the same connection";for(const x of Bo(R)){const F=R.inputs[x];if(!F)return`Unknown computation input: ${x}`;if(F.sourceColumn!==void 0)continue;const G=F.property,ee=ne(Q.schema,G,o);if(ee.property.isArray||ee.relations.some(({property:Ee})=>Ee.isArray))return`Computation input must be scalar: ${G}`;if(!nr(j,Q.schema,G,o,n))return`Computation ${Q.property.id} input is not available: ${G}`;const ue=T(Q.schema,j,G,[...q,H]);if(ue)return ue}}catch(Q){return`Computation dependency cannot be resolved: ${Q instanceof Error?Q.message:String(Q)}`}};for(const{reference:C}of Gt(m)){const O=T(e,r,C);if(O)return O}const M=jf(m,e,r,o,i,s);if(M)return M;const Y={schema:e,mapping:r,...o?{resolveSchema:o}:{}};for(const C of i??[]){const O=C.schemaMapping?.candidateReason?.(m,Y);if(O)return O}return{mapping:r,logicform:m,predRewrites:h,physicalQueryFilters:c.filters,groupPathBindings:c.bindings,priority:r.priority??0,specificity:h.length+u.matchCount}},Hf=(t,e,r,n={})=>{const o=n.plugins?Pe(n.plugins):r.plugins,i=n.operators??at(n.plugins),s=[],a=[];for(const p of r.list(e.id)){if(n.mappingCandidates&&!n.mappingCandidates.includes(Nr(p))){a.push({mappingId:Nr(p),reason:"mapping is not a partition candidate"});continue}const f=Bf(t,e,p,r,n.resolveSchema,o,i);typeof f=="string"?a.push({mappingId:Nr(p),reason:f}):"reason"in f?a.push({mappingId:Nr(p),...f}):s.push(f)}if(s.length===0){const p=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id,f=a.filter(({reason:h})=>h!=="mapping is not a partition candidate"),m=f.length>0&&f.every(({missingDimensions:h})=>h&&h.length>0)?[...new Set(f.flatMap(({missingDimensions:h})=>h??[]))]:[];throw new l("QUERY_NOT_COVERED_BY_DATA_SOURCE",m.length>0?`Schema\u300C${p}\u300D\u6CA1\u6709\u6570\u636E\u8868\u80FD\u5B8C\u6574\u8986\u76D6\u67E5\u8BE2\u6240\u9700\u7EF4\u5EA6\u3010${m.join("\u3001")}\u3011\u3002\u8BF7\u68C0\u67E5\u5DF2\u63A5\u5165\u6570\u636E\u8868\u7684\u7EF4\u5EA6\u7EC4\u5408\u3002`:`Schema\u300C${p}\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:p,...m.length>0?{uncoveredDimensions:m}:{},rejectedMappings:a})}const u=n.preferredConnectionId===void 0?[]:s.filter(({mapping:p})=>p.connectionId===n.preferredConnectionId),d=(u.length>0?u:s).reduce((p,f)=>f.priority>p.priority||f.priority===p.priority&&f.specificity>p.specificity?f:p);for(const p of s){if(p===d)continue;let f;u.length>0&&p.mapping.connectionId!==n.preferredConnectionId?f=`connection ${p.mapping.connectionId} does not match preferred connection ${n.preferredConnectionId}`:p.priority<d.priority?f=`priority ${p.priority} is lower than selected priority ${d.priority}`:p.specificity<d.specificity?f=`specificity ${p.specificity} is lower than selected specificity ${d.specificity}`:f="priority and specificity tie; an earlier registered mapping was selected",a.push({mappingId:Nr(p.mapping),reason:f})}return{mapping:d.mapping,logicform:d.logicform,predRewrites:d.predRewrites,physicalQueryFilters:d.physicalQueryFilters,groupPathBindings:d.groupPathBindings,selection:{schemaId:e.id,selectedMappingId:Nr(d.mapping),rejectedMappings:a}}},Qf=t=>{const e=Object.values(t.fieldReferences??{});if(!e.some(R=>R.computation))return t;if(t.periodSource)throw new l("COMPUTATION_PERIOD_SOURCE_UNSUPPORTED","Row computations on generated entity-period sources are not supported");const r=R=>JSON.stringify(R.kind==="column"?["column",R.qualifier,R.column]:R.kind==="property-sql"?["sql",R.qualifier,R.sql,R.timestampColumn,R.timestampQualifier]:R),n=R=>R.sql?{kind:"property-sql",schemaId:R.schemaId,property:R.property,propertyId:R.propertyId??R.column,sql:R.sql,qualifier:R.qualifier,...R.timestampColumn?{timestampColumn:R.timestampColumn}:{},...R.timestampQualifier?{timestampQualifier:R.timestampQualifier}:{}}:{kind:"column",column:R.column,qualifier:R.qualifier,schemaId:R.schemaId,property:R.property,...R.propertyId?{propertyId:R.propertyId}:{}},o=new Map(e.flatMap(R=>R.computation?[[r(n(R)),R.computation]]:[])),i=new Map,s={usedAsValue:!1},a=(R,x=!1)=>{const F=r(R),G=o.get(F);G?.kind==="mapping-computation"?(i.set(F,(i.get(F)??0)+1),x||(s.usedAsValue=!0),Object.values(G.inputs).forEach(ee=>a(ee,x))):R.kind==="operator"?(R.input&&a(R.input,x),R.inputs?.forEach(ee=>a(ee,x)),u(R.query)):R.kind==="window"||R.kind==="cumulative"?(a(R.input,x),R.partitionBy.forEach(ee=>a(ee,x)),R.kind==="cumulative"&&R.orderBy.forEach(({expression:ee})=>a(ee,x))):(R.kind==="ordinal-encode"||R.kind==="ordinal-decode")&&a(R.input,x)},u=R=>{for(const[x,F]of Object.entries(R??{}))if((x==="$and"||x==="$or")&&Array.isArray(F))F.forEach(u);else if(x==="$expr"&&zn(F))a(F.expression,!0);else if(!x.startsWith("$")){const G=t.fieldReferences?.[x];G&&a(n(G),!0)}};if(t.projections.forEach(({expression:R})=>a(R)),t.groupBy.forEach(({expression:R})=>a(R)),t.orderBy.forEach(({expression:R})=>{R&&a(R)}),u(t.query),!s.usedAsValue&&[...o.keys()].every(R=>i.get(R)===1)){const R=F=>{const G=o.get(r(F));return G?.kind==="mapping-computation"?{...G,inputs:Object.fromEntries(Object.entries(G.inputs).map(([ee,ue])=>[ee,R(ue)]))}:F.kind==="operator"?{...F,...F.input?{input:R(F.input)}:{},...F.inputs?{inputs:F.inputs.map(R)}:{},...F.query?{query:x(F.query)}:{}}:F},x=F=>Object.fromEntries(Object.entries(F).map(([G,ee])=>[G,(G==="$and"||G==="$or")&&Array.isArray(ee)?ee.map(x):G==="$expr"&&zn(ee)?{...ee,expression:R(ee.expression)}:ee]));return{...t,projections:t.projections.map(F=>({...F,expression:R(F.expression)})),...t.query?{query:x(t.query)}:{},fieldReferences:Object.fromEntries(Object.entries(t.fieldReferences??{}).map(([F,G])=>[F,G.computation?{...G,computation:R(n(G))}:G]))}}const c=new Map,d=new Map,p=new Set,f=new Set,m=R=>{R.kind==="column"&&!o.has(r(R))&&f.add(R.column.toLowerCase()),R.kind==="mapping-computation"&&Object.values(R.inputs).forEach(m)};e.forEach(R=>{m(n(R)),R.computation&&m(R.computation)});const h=(R,x)=>{let F=R,G=2;for(;p.has(F.toLowerCase())||x&&f.has(F.toLowerCase());)F=`${R}_${G++}`;return p.add(F.toLowerCase()),F},y=R=>{const x=r(R),F=o.get(x),G=F?d:c;let ee=G.get(x);if(!ee){const ue=F?.kind==="mapping-computation"?`__calc_${F.definition.id}`:R.kind==="column"?p.has(R.column.toLowerCase())&&R.qualifier?`${R.qualifier}_${R.column}`:R.column:`__calc_${"propertyId"in R?R.propertyId:"expression"}`,Ee=h(ue,!!F),Ge=F?.kind==="mapping-computation"?{...F,inputs:Object.fromEntries(Object.entries(F.inputs).map(([Ze,ze])=>[Ze,w(ze)]))}:R;ee={name:Ee,expression:Ge},G.set(x,ee)}return{kind:"column",column:ee.name,qualifier:t.sourceAlias??t.schemaId,property:"property"in R&&R.property?R.property:ee.name}},$=R=>{if(qt(R))return R;if(Array.isArray(R))return R.map($);if(!R||typeof R!="object"||R instanceof Date)return R;const x=R;return x.kind==="expression-query"?{...x,expression:w(x.expression)}:Object.fromEntries(Object.entries(x).map(([F,G])=>[F,$(G)]))},w=R=>R.kind==="operator"?{...R,...R.input?{input:w(R.input)}:{},...R.inputs?{inputs:R.inputs.map(w)}:{},...R.query?{query:$(R.query)}:{}}:R.kind==="window"||R.kind==="cumulative"?{...R,input:w(R.input),partitionBy:R.partitionBy.map(w),...R.kind==="cumulative"?{orderBy:R.orderBy.map(x=>({...x,expression:w(x.expression)}))}:{}}:R.kind==="ordinal-encode"||R.kind==="ordinal-decode"?{...R,input:w(R.input)}:y(R),E=t.projections.map(R=>({...R,expression:w(R.expression)})),N=t.groupBy.map(R=>({...R,expression:w(R.expression)})),I=Object.fromEntries(Object.entries(t.fieldReferences??{}).map(([R,x])=>{const F=y(n(x));if(F.kind!=="column")throw new Error("Expected materialized column");const{sql:G,computation:ee,timestampColumn:ue,timestampQualifier:Ee,...Ge}=x;return[R,{...Ge,column:F.column,qualifier:F.qualifier??t.schemaId}]})),S=$(t.query),D=t.orderBy.map(R=>({...R,...R.expression?{expression:w(R.expression)}:{}}));let b=t.rowIdentity;if(b.kind==="property"){const R=y({kind:"column",column:b.column,qualifier:t.sourceAlias??t.schemaId,property:b.column});R.kind==="column"&&(b={...b,column:R.column})}let T={schemaId:t.schemaId,source:t.source,...t.connectionId?{connectionId:t.connectionId}:{},...t.mappingSourcePlan?{mappingSourcePlan:t.mappingSourcePlan}:{},...t.mappingId?{mappingId:t.mappingId}:{},...t.sourceAlias?{sourceAlias:t.sourceAlias}:{},...t.joins?{joins:t.joins}:{},...t.enrichmentJoins?{enrichmentJoins:t.enrichmentJoins}:{},...t.arrayExpansions?{arrayExpansions:t.arrayExpansions}:{},...t.physicalQueryFilters?{physicalQueryFilters:t.physicalQueryFilters}:{},fields:t.fields,projections:c.size?[...c.values()]:[{name:"__sdb_row",expression:{kind:"operator",operator:"$constant",args:{value:1,type:"number"}}}],groupBy:[],orderBy:[],rowIdentity:{kind:"singleton"}};const M=new Map,Y=new Map;for(const R of d.values()){const x=R.expression,F=x.kind==="mapping-computation"?Object.values(x.inputs):[],G=Math.max(0,...F.map(ee=>ee.kind==="column"?(M.get(ee.column)??-1)+1:0));M.set(R.name,G),Y.set(G,[...Y.get(G)??[],R])}const C=new Map([...c.values()].map(({name:R,expression:x})=>[R,x]));for(const[R,x]of Y){const F=t.computationSources?.filter(({alias:G})=>x.some(({expression:ee})=>ee.kind==="mapping-computation"&&ee.alias===G));R===0?T={...T,...F?.length?{computationSources:F}:{},projections:[...c.values(),...x.map(G=>({...G,expression:G.expression.kind==="mapping-computation"?{...G.expression,inputs:Object.fromEntries(Object.entries(G.expression.inputs).map(([ee,ue])=>[ee,ue.kind==="column"?C.get(ue.column)??ue:ue]))}:G.expression}))]}:T={schemaId:t.schemaId,source:t.source,...t.connectionId?{connectionId:t.connectionId}:{},...t.mappingId?{mappingId:t.mappingId}:{},sourceAlias:t.sourceAlias??t.schemaId,sourcePlan:T,...F?.length?{computationSources:F}:{},projections:[...T.projections.map(({name:G})=>({name:G,expression:{kind:"column",column:G,qualifier:t.sourceAlias??t.schemaId,property:G}})),...x],fields:{},groupBy:[],orderBy:[],rowIdentity:{kind:"singleton"}}}const{mappingSourcePlan:O,joins:L,enrichmentJoins:q,arrayExpansions:Q,physicalQueryFilters:j,computationSources:oe,...H}=t;return{...H,sourcePlan:T,projections:E,groupBy:N,fieldReferences:I,fields:{...t.fields,...Object.fromEntries(Object.entries(I).map(([R,x])=>[R,x.column]))},...S?{query:S}:{},orderBy:D,rowIdentity:b}},tn=(t,e)=>e.isComponent(t),rn=(t,e)=>tn(t,e)?!0:t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?rn(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&rn(r,e)),ic=(t,e)=>t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?rn(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&rn(r,e)),sc=t=>t.name??(typeof t.pred=="string"?t.pred:void 0),Yf=(t,e)=>{const r=t.preds??[];if(!r.some(m=>!tn(m,e)&&ic(m,e)))return;const n=new Set([...r.map(({name:m})=>m).filter(m=>!!m),...(t.groupby??[]).map(sc).filter(m=>!!m)]);let o=0;const i=()=>{let m;do m=`__nested_component_input_${o}__`,o+=1;while(n.has(m));return n.add(m),m},s=[],a=m=>{const h=i();return s.push(typeof m=="string"?{pred:m,name:h}:{...ge(m),name:h}),h},u=m=>{if(m.query)throw new l("UNSUPPORTED_COMPONENT_NESTING","An operator above a component cannot define pred.query; apply the query inside a materialized input");const h=ge(m);return Array.isArray(m.pred)?h.pred=m.pred.map(y=>typeof y=="string"||!rn(y,e)||tn(y,e)?a(y):u(y)):m.pred&&typeof m.pred=="object"&&(h.pred=tn(m.pred,e)?a(m.pred):u(m.pred)),h},c=r.map(m=>{const h=m.name;if(!h)throw new l("MISSING_PRED_NAME","Nested component rewrite requires every projection to have a name");return!tn(m,e)&&ic(m,e)?{...u(m),name:h}:(s.push({...ge(m),name:h}),{pred:h,name:h})}),d=ge(t);d.preds=s,delete d.having,delete d.sort,delete d.limit,delete d.limitBy,delete d.page,delete d.sample,delete d.output,delete d.representation;const p=(t.groupby??[]).map(m=>{const h=sc(m);if(!h)throw new l("MISSING_PRED_NAME","Nested component rewrite requires every groupby projection to have a name");return{pred:h,name:h}}),f=ge(t);return f.from=d,f.preds=[...p,...c],delete f.query,delete f.groupby,delete f.entity_id,delete f.propertyResolve,f},vf=(t,e)=>`result:${t}:${e.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,Ri=t=>{const{componentProperties:e,...r}=t;return{...r,id:t.name,...e?{componentProperties:e.map(Ri)}:{}}},ac=(t,e)=>{const r=(t.columnProperties??[]).map(Ri);return{id:vf(t.schemaId,t.columnProperties??[]),name:`${e.name} result`,type:e.type,temporalSemantics:"normal",properties:r}},cc=(t,e)=>({...ac(t,e),id:e.id,name:e.name,type:e.type}),nn=t=>{if(!t.name)throw new l("MISSING_PRED_NAME","Planner requires every normalized PredItem to have a name");return t.name},Xn=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Xn(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Xn(e)):[]],Oi=(t,e)=>({...t,...typeof t.pred=="string"?{pred:e(t.pred)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Oi(t.pred,e)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(r=>typeof r=="string"?e(r):Oi(r,e))}:{}}),uc=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(o=>uc(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:Oi(o,e)}]}return[r.startsWith("$")?r:e(r),n]})),Ti=(t,e,r)=>{const n=new Set(r),o=(i,s)=>{if(!(Re(i)||i===null)){if(Array.isArray(i)){i.forEach(a=>o(a,s));return}if(typeof i=="object"){Object.entries(i).forEach(([a,u])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(a)||o(u,a)});return}if(!(s&&["$exists","$regex","$contains","$startsWith","$length"].includes(s))&&(typeof i!="string"||!n.has(i)))throw new l("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${e} does not contain value: ${JSON.stringify(i)}`,{property:e,value:i})}};o(t)},Pi=(t,e)=>{const r=n=>{const o=n.slice(1);if(!e.some(i=>i.name===o))throw new l("INVALID_HAVING",`Having field is not an output: ${o}`);return{kind:"output-reference",name:o}};return typeof t=="string"&&t.startsWith("$")?r(t):typeof t!="object"||t===null||Array.isArray(t)||t instanceof Date||Re(t)?t:Object.fromEntries(Object.entries(t).map(([n,o])=>(n==="$and"||n==="$or")&&Array.isArray(o)?[n,o.map(i=>Pi(i,e))]:[n,["$eq","$ne","$gt","$gte","$lt","$lte"].includes(n)&&typeof o=="string"&&o.startsWith("$")?r(o):o]))},Li=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(i=>Li(i,e))];if(r==="$expr")throw new l("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&&Ti(n,r,o.values),[r,o?{kind:"ordinal-query",comparable:o,condition:n}:Pi(n,e)]})),Gf=(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&&(Be(r,t,i.name)??i.id):void 0;return{sql:e,...s?{timestampColumn:s}:{},...s&&n?{timestampQualifier:n}:{}}},on=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},dc=(t,e,r={})=>({name:t,type:e.type,primal_type:e.primal_type,isArray:e.isArray,formulaText:en(e.formulaText===void 0?t:e.formulaText),...e.description!==void 0?{description:e.description}:{},...e.ref?{ref:e.ref}:{},...e.comparable?{comparable:e.comparable}:{},...e.componentProperties?{componentProperties:e.componentProperties}:{},...r}),Tr=(t,e,r,n,o,i,s,a,u="projection",c=Mt())=>{const d=nn(t);if(u==="groupby"&&t.query)throw new l("GROUPBY_QUERY_NOT_ALLOWED","A groupby expression cannot define pred.query");if(!t.operator){if(typeof t.pred!="string")throw new l("PRED_PROPERTY_REQUIRED","A projection must reference a property");const S=r(t.pred);return{expression:on(S.field),outputProperty:dc(S.reference,S.property),sourceProperty:S.property,sourceField:S.field}}const p=e.get(t.operator);for(const S of p.dependencies??[])r(S);if(u==="groupby"&&p.kind!=="scalar")throw new l("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(p.planInput&&typeof t.pred!="string")throw new l("OPERATOR_DIRECT_PROPERTY_REQUIRED",`${t.operator} requires a direct property pred`);const f=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=f?.reference??t.pred,h=f?.args??t.args??{},y=m&&typeof m=="object"&&!Array.isArray(m)?Tr(m,e,r,n,o,i,s,a,u,c):typeof m=="string"?Tr({pred:m,name:m},e,r,n,o,i,s,a,u,c):void 0,$=Array.isArray(m)?m.map(S=>Tr(typeof S=="string"?{pred:S,name:S}:S,e,r,n,o,i,s,a,u,c)):[];if(p.requiresProperty!==!1&&!y&&$.length===0)throw new l("PRED_PROPERTY_REQUIRED",`${t.operator} requires a property`);const w=d,E=p.getOutputProperty?.({semanticTypes:c,executionContext:e.executionContext,name:w,...y?.sourceProperty?{property:y.sourceProperty}:{},...y?{inputProperty:{...y.outputProperty,name:w}}:{},...$.length>0?{inputProperties:$.map(({outputProperty:S})=>S)}:{},args:h}),N=E?.description??p.description??y?.outputProperty.description,I={...E??(y?dc(w,y.outputProperty,{isArray:!1}):{name:w,type:"number",primal_type:"number",isArray:!1}),...$.length>0?{componentProperties:$.map(({outputProperty:S})=>S)}:y?.outputProperty.componentProperties?{componentProperties:y.outputProperty.componentProperties}:{},...N!==void 0?{description:N}:{},formulaText:La(p,{executionContext:e.executionContext,schema:s,...y?{input:y.outputProperty.formulaText===void 0?y.outputProperty.name:y.outputProperty.formulaText}:{},inputs:$.map(({outputProperty:S})=>S.formulaText===void 0?S.name:S.formulaText),args:h})};if(p.planExpression){const S=p.planExpression({executionContext:e.executionContext,pred:t,...y?{input:y.expression,inputProperty:y.outputProperty}:{},inputs:$.map(({expression:D})=>D),args:h,resolveKey:o,getOperator:D=>e.get(D),planQuery:i});if(S)return{expression:S,outputProperty:I,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}}if(p.kind==="window"){if(!y||$.length>0||t.query)throw new l("INVALID_WINDOW_OPERATOR_INPUT",`${t.operator} requires exactly one nested pred and does not accept pred.query`);const S=t.args?.direction??"desc";if(S!=="asc"&&S!=="desc")throw new l("INVALID_WINDOW_ARGS",`${t.operator} direction must be asc or desc`);const D=t.args?.partitionBy??[];if(!Array.isArray(D)||D.some(b=>typeof b!="string"))throw new l("INVALID_WINDOW_ARGS",`${t.operator} partitionBy must be an array of groupby names`);return{expression:{kind:"window",function:p.windowFunction,input:y.expression,partitionBy:D.map(b=>n(String(b))),direction:S==="asc"?"ASC":"DESC"},outputProperty:I}}return{expression:{kind:"operator",operator:t.operator,args:h,...t.query?{query:i(t.query)}:{},...y?{input:y.expression}:{},...$.length>0?{inputs:$.map(({expression:S})=>S)}:{},...y?.sourceProperty?{property:y.sourceProperty.name,column:y.sourceProperty.id}:{},...y?.sourceField?{qualifier:y.sourceField.qualifier,schemaId:y.sourceField.schemaId}:{}},outputProperty:I,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}},zf=(t,e,r,n,o,i,s,a,u,c,d,p=t,f)=>{const m=nn(t),h=typeof t.pred=="string"?t.pred:void 0,y=!c||!h?r:N=>{const I=r(N);return N===h?{...I,field:{...I.field,column:c}}:I},$=d?{...t,operator:d}:t,w=Tr($,e,y,n,o,i,s,a,"projection",f),E=u?.resolveProjection({pred:p,schema:s,executionContext:e.executionContext,...w.sourceProperty?{sourceProperty:w.sourceProperty}:{},outputProperty:{...w.outputProperty,name:m},...p.operator?{operator:e.get(p.operator)}:{}})??{...w.outputProperty,name:m};return{name:m,expression:w.expression,outputProperty:E}},pc=t=>{const e=new Set;for(const r of t){if(r.name==="_id")throw new l("RESERVED_OUTPUT_NAME","Output name _id is reserved for executor-owned row identity");if(e.has(r.name))throw new l("DUPLICATE_OUTPUT_NAME",`Duplicate output name: ${r.name}`);e.add(r.name)}},Zn=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new l("SCHEMA_RESOLVER_REQUIRED",`Cannot plan nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n},Wf=(t,e,r,n,o,i)=>{if(e.length<2)throw new l("COMPOSITION_REQUIRES_MULTIPLE_BRANCHES","A cross-Schema plan requires at least two branches");const s=e.map(y=>Me(y,Zn(y,r,i),n,o,i)),a=s[0]?.groupBy.map(({name:y})=>y)??[];for(const y of s){const $=y.groupBy.map(({name:w})=>w);if($.length!==a.length||$.some((w,E)=>w!==a[E]))throw new l("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 l("UNSTABLE_COMPOSITION_IDENTITY","Composed LogicForm objects must be grouped or aggregate to a singleton row")}const u=[],c=[],d=new Map;s.forEach((y,$)=>{y.projections.forEach((w,E)=>{const N=a.includes(w.name),I=d.get(w.name);if(I!==void 0&&!N)throw new l("DUPLICATE_COMPOSITION_OUTPUT",`Composed LogicForm objects produce the same output: ${w.name}`,{name:w.name,childIndexes:[I,$]});if(I!==void 0)return;d.set(w.name,$),u.push({name:w.name,expression:{kind:"column",property:w.name,column:w.name}});const S=y.columnProperties?.[E];S&&c.push(S)})});const p=new Set(u.map(({name:y})=>y)),f=Object.entries(t.sort??{}).map(([y,$])=>{if(!p.has(y))throw new l("INVALID_SORT",`Sort field is not an output: ${y}`);const w=c.find(E=>E.name===y);return{name:y,direction:$===1?"ASC":"DESC",...w?.comparable?{comparable:w.comparable}:{},...w?.comparable?{expression:{kind:"column",property:y,column:y}}:{}}}),m=t.limitBy===void 0||a.length<2?void 0:{count:t.limitBy,partitionBy:a.slice(0,-1),orderBy:f.length>0?f:(()=>{const y=a.at(-1)??"",$=c.find(w=>w.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:void 0,subplans:s,fields:Object.fromEntries(u.map(({name:y})=>[y,y])),projections:u,columnProperties:c,groupBy:u.filter(({name:y})=>a.includes(y)),...t.having?{having:Li(t.having,c)}:{},orderBy:f,rowIdentity:a.length>0?{kind:"group",names:a,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"},...m?{groupLimit:m}:{},...h?{pagination:h}:{}}},Kf=(t,e,r,n,o)=>{const i=t.groupby??[];if(i.length===0||!t.preds?.length)return;const a=i.filter(v=>typeof v.pred=="string"&&!v.operator&&!v.args).flatMap(v=>{try{const Ae=ne(e,v.pred,o.resolveSchema);return Array.isArray(Ae.property.constraints?.enum)&&Ae.property.constraints.enum.length>0?[{group:v,path:Ae}]:[]}catch{return[]}});if(a.length!==1)return;const{group:u,path:c}=a[0],d=i.filter(v=>v!==u),p=i.map(nn);if(new Set(p).size!==p.length)return;const m=(c.property.constraints?.enum).map(v=>Array.isArray(v)?v[0]:v);if(m.some(v=>typeof v!="string"||v.length===0)||new Set(m).size!==m.length)return;const h=m,y=v=>{try{return ne(e,v,o.resolveSchema).canonicalId===c.canonicalId}catch{return!1}},$=v=>Object.entries(v).some(([Ae,Le])=>Ae==="$expr"||(Ae==="$and"||Ae==="$or")&&Array.isArray(Le)&&Le.some($e=>$($e))||!Ae.startsWith("$")&&y(Ae)),w=Object.entries(t.query??{}).filter(([v])=>y(v)),E=Object.fromEntries(Object.entries(t.query??{}).filter(([v])=>!y(v)));if(w.length>1||$(E))return;const N=w[0]?.[1],I=N===void 0?h:typeof N=="string"?[N]:typeof N=="object"&&N!==null&&!Array.isArray(N)&&Array.isArray(N.$in)?N.$in:[],S=h.filter(v=>I.includes(v));if(S.length===0)return;const D=t.preds;if(D.some(v=>typeof v.pred!="string"||v.query||v.args||!v.operator||!["$sum","$avg","$min","$max"].includes(v.operator)||v.schema&&v.schema!==e.id))return;const b=n.list(e.id);if(!b.some(v=>D.every(Ae=>h.every(Le=>(v.mappings??[]).filter($e=>{if($e.mappingType!=="predItem"||!$e.sourceColumn||typeof $e.predItem.pred!="string"||!$e.predItem.query||$e.predItem.schema&&$e.predItem.schema!==e.id||$e.propertyTarget?.length&&!y($e.propertyTarget.join("_"))||$e.predItem.operator&&$e.predItem.operator!==Ae.operator)return!1;const We=e.properties.find(A=>A.id===Ae.pred||A.name===Ae.pred),k=e.properties.find(A=>A.id===$e.predItem.pred||A.name===$e.predItem.pred);if(!We||We.id!==k?.id)return!1;const g=Object.entries($e.predItem.query);return g.length===1&&g.some(([A,_])=>y(A)&&_===Le)}).length===1)))){if(!b.some(Le=>(Le.mappings??[]).some($e=>{if($e.mappingType!=="predItem"||typeof $e.predItem.pred!="string"||!$e.predItem.query||$e.propertyTarget?.length&&!y($e.propertyTarget.join("_")))return!1;const We=e.properties.find(k=>k.id===$e.predItem.pred||k.name===$e.predItem.pred);return D.some(k=>{const g=e.properties.find(A=>A.id===k.pred||A.name===k.pred);return!!(g&&We&&g.id===We.id)&&Object.keys($e.predItem.query??{}).some(y)})})))return;const Ae=`${e.name}(${e.id})`;throw new l("QUERY_NOT_COVERED_BY_DATA_SOURCE",`Schema\u300C${Ae}\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:Ae,reason:"enumerated group is missing a unique conditional measure for every enum value"})}const{query:M,groupby:Y,having:C,sort:O,limit:L,limitBy:q,page:Q,...j}=t,oe=S.map(v=>Me({...j,...Object.keys(E).length>0?{query:E}:{},...d.length>0?{groupby:d}:{},preds:D.map(Ae=>({...Ae,query:{[u.pred]:v}}))},e,r,n,o));if(new Set(oe.map(v=>v.connectionId)).size!==1)throw new l("SPLIT_GROUP_CONNECTION_MISMATCH","Enumerated group branches must use one physical connection");const H=nn(u),R={name:H,formulaText:en(c.property.formulaText===void 0?c.canonicalName:c.property.formulaText),type:c.property.type,primal_type:c.property.primal_type,isArray:!1,...c.property.comparable?{comparable:c.property.comparable}:{}},x=oe[0],F=p.map(v=>({name:v,expression:{kind:"column",property:v,column:v}})),G=x.projections.filter(v=>!d.some(Ae=>Ae.name===v.name)),ee=[...F,...G.map(({name:v})=>({name:v,expression:{kind:"column",property:v,column:v}}))];pc(ee);const ue=x.columnProperties??[],Ee=[...p.map(v=>v===H?R:ue.find(Ae=>Ae.name===v)),...ue.filter(v=>!p.includes(v.name))],Ge=new Set(ee.map(v=>v.name)),Ze=Object.entries(t.sort??{}).map(([v,Ae])=>{if(!Ge.has(v))throw new l("INVALID_SORT",`Sort field is not an output: ${v}`);const Le=Ee.find($e=>$e.name===v)?.comparable;return{name:v,direction:Ae===1?"ASC":"DESC",...Le?{comparable:Le,expression:{kind:"column",property:v,column:v}}:{}}}),ze=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:void 0,...x.connectionId?{connectionId:x.connectionId}:{},subplans:oe,splitGroup:{name:H,values:S,groupNames:p},fields:Object.fromEntries(ee.map(v=>[v.name,v.name])),projections:ee,columnProperties:Ee,groupBy:F,...t.having?{having:Li(t.having,Ee)}:{},orderBy:Ze,rowIdentity:{kind:"group",names:p,separator:"_",nullLabel:"\u7A7A\u503C"},...ze?{pagination:ze}:{}}},Me=(t,e,r=at(),n=new Dt,o={})=>{o.authorizeLogicform?.(t);const i=o.semanticTypes??Mt(o.plugins),{semanticPreds:s,...a}={...o,semanticTypes:i};if(o=a,t.sample===!0)throw new l("INVALID_SAMPLE","sample is only supported by top-level execution");if(!o.mappingCandidates){const g=o.preplannedPartitions?.get(JSON.stringify(t));if(g)return g}const u=[...new Set((t.preds??[]).map(g=>g.schema).filter(g=>!!(g&&g!==e.id)))];if(u.length>0){const g=t.propertyResolve??{},A=[e.id,...u].map(_=>{const{having:P,sort:B,limit:X,limitBy:Z,page:V,...z}=t,K=ie=>{let me=ie;try{me=ne(e,ie,o.resolveSchema).canonicalName}catch{}return g[_]?.[ie]??g[_]?.[me]??ie};return{...z,schema:_,preds:(t.preds??[]).filter(ie=>(ie.schema??e.id)===_).map(({schema:ie,...me})=>me),..._===e.id||!t.query?{}:{query:uc(t.query,K)},..._!==e.id&&t.groupby?{groupby:t.groupby.map(ie=>({...ie,...typeof ie.pred=="string"?{pred:K(ie.pred)}:{}}))}:{}}});return Wf(t,A,e,r,n,o)}const c=Yf(t,r);if(c)return Me(c,e,r,n,o);for(const g of t.preds??[]){if(!g.operator)continue;const A=r.get(g.operator).rewriteLogicform?.({executionContext:r.executionContext,logicform:t,schema:e,getOperator:_=>r.get(_)});if(A)return Me(A,e,r,n,o)}const d=o.semanticRegistry??ec(o.plugins);if(t.from){const g=Zn(t.from,e,o),A=Me(t.from,g,r,n,o),_=cc(A,e),P={...t};delete P.from,P.schema??=_.id;const B=new Dt([...n.definitions().filter(({schemaId:re})=>re!==_.id),{schemaId:_.id,connectionId:A.connectionId??o.preferredConnectionId??"__derived__",source:{kind:"table",table:"__derived__"}}],n.plugins.filter(re=>!hr.includes(re))),{onSchemaMappingSelection:X,...Z}=o,V=Me(P,_,r,B,Z),z=new Set(V.projections.map(({name:re})=>re)),K=A.rowIdentity.kind==="group"&&A.rowIdentity.names.every(re=>z.has(re))||A.rowIdentity.kind==="singleton"?A.rowIdentity:{kind:"generated"},ie=A.groupBy.map(({name:re})=>re).filter(re=>z.has(re)),me=ie.at(-1),W=A.columnProperties?.find(re=>re.name===me),J=t.limitBy!==void 0&&ie.length>0?{count:t.limitBy,partitionBy:ie.slice(0,-1),orderBy:V.orderBy.length>0?V.orderBy:ie.slice(-1).map(re=>({name:re,direction:"ASC",...W?.comparable?{comparable:W.comparable}:{}}))}:void 0;return{...V,source:A.source,sourcePlan:A,sourceLogicform:t.from,rowIdentity:K,...J?{groupLimit:J}:{}}}if(!t.schema)throw new l("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const p=Kf(t,e,r,n,o);if(p)return p;const f=Hf(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?.(f.selection),t=f.logicform;const m=f.physicalQueryFilters.map(g=>{if(!Re(g.value))return g;const A=Zn(g.value,e,o),{mappingCandidates:_,...P}=o,B=Me(g.value,A,r,n,{...P,preferredConnectionId:f.mapping.connectionId});if(B.projections.length!==1)throw new l("SUBQUERY_SINGLE_COLUMN_REQUIRED",`Query path value must output exactly one column, received ${B.projections.length}`);if(B.connectionId!==f.mapping.connectionId)throw new l("QUERY_PATH_MAPPING_CONNECTION_MISMATCH",`Query path value for ${g.sourceColumn} must use connection ${f.mapping.connectionId}`);return{...g,value:{kind:"logicform-subquery",plan:B}}}),h=new Map(f.predRewrites.map(({predIndex:g,column:A})=>[g,A])),y=oa(e,o.plugins),$=ap(t,e,o.plugins),w=d.resolveQuery({logicform:t,schema:e,...t.query?{query:t.query}:{}}),E=$?.rewriteQuery?$.rewriteQuery(w):w,N=e.id,I=new Map,S=new Map,D=new Map,b=new Map,T=new Set,M=new Map,Y=[],C=new Set,O=new Map,L=(g,A,_)=>{const P=g.property.udf?.sql;if(!P||!(g.relations.length?n.get(g.schema.id,f.mapping.connectionId):f.mapping).mappings?.some(J=>J.mappingType==="property"&&J.value.kind!=="column"))return A;if(A.sql){const{sql:J,timestampColumn:re,timestampQualifier:pe,...de}=A;A=de}O.set(g.canonicalName,A),b.set(g.canonicalName,A);const X=Df(P,g.schema),Z=g.relations.map(({property:J})=>J.name).join("_"),V=Object.fromEntries(Object.entries(X.references).map(([J,re])=>{const pe=Z?`${Z}_${re}`:re;o.authorizeComputationInput?.(e,pe);const de=re===g.property.id?A:j(pe).field;return[J,on(de)]})),z={...A,column:`${A.column}_udf`,qualifier:_,computation:{kind:"mapping-computation",alias:`${A.column}_udf_source`,definition:{id:`${g.property.id}_udf`,kind:"sql",sql:X.sql,inputs:Object.fromEntries(Object.entries(X.references).map(([J,re])=>[J,{property:re}]))},inputs:V}},{sql:K,timestampColumn:ie,timestampQualifier:me,...W}=z;return b.set(`${g.canonicalName}.__physical`,A),W},q=new Map(f.groupPathBindings.map(({canonicalId:g,sourceColumn:A})=>[g,A])),Q=g=>{const A=S.get(g);if(A)return A.alias;const _=f.mapping.enrichments?.find(X=>X.id===g);if(!_)throw new l("SCHEMA_MAPPING_ENRICHMENT_NOT_FOUND",`Schema mapping enrichment is not registered: ${g}`,{schemaId:e.id,mappingId:f.mapping.id,enrichmentId:g});const P=`__enrichment_${g}`,B=_.temporal?(()=>{if(!y)throw new l("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${g} requires an entity with interval semantics`,{schemaId:e.id,enrichmentId:g});const X=xt(f.mapping,e,y.start.name),Z=xt(f.mapping,e,y.end.name);if(!X||!Z)throw new l("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${g} requires mapped interval boundary columns`,{schemaId:e.id,enrichmentId:g});if(X.sourceRef||Z.sourceRef)throw new l("POINT_ENRICHMENT_INTERVAL_MUST_USE_BASE_SOURCE",`Point enrichment ${g} requires interval boundaries on the base source`,{schemaId:e.id,enrichmentId:g});return{kind:"point-in-interval",pointSide:"target",pointColumn:_.temporal.pointColumn,intervalSide:"source",startColumn:X.column,endColumn:Z.column}})():void 0;return S.set(g,{kind:"enrichment-left",id:g,source:rt(_.source),alias:P,baseAlias:N,keys:_.on,...B?{temporalCondition:B}:{}}),P},j=g=>{const A=ne(e,g,o.resolveSchema),_=Xo(A,o.resolveSchema),P=b.get(_.canonicalName);if(P)return{reference:_.canonicalName,schema:_.schema,property:_.property,field:P};const B=q.get(_.canonicalId);if(B){const J={schemaId:_.schema.id,property:_.property.name,propertyId:_.property.id,column:B,qualifier:N};return b.set(_.canonicalName,J),{reference:_.canonicalName,schema:_.schema,property:_.property,field:J}}const X=Rr(f.mapping,e,g,o.resolveSchema);if(X){const J={schemaId:_.schema.id,property:_.property.name,propertyId:_.property.id,column:X.column,qualifier:X.sourceRef?Q(X.sourceRef):N,..._.property.isArray?{isArray:!0}:{},..._.property.type==="tag"?{normalizeStringArray:!0}:{},..._.property.comparable?{comparable:_.property.comparable}:{}};return b.set(_.canonicalName,J),{reference:_.canonicalName,schema:_.schema,property:_.property,field:J}}let Z=N,V=f.mapping;const z=[];for(const J of _.relations){z.push(J.property.name);const re=z.join("_"),pe=re,de=n.get(J.targetSchema.id,f.mapping.connectionId);if(V=de,!I.has(re)){const ye=Vn(J),Ce=J.sourceSchema.id===e.id?f.mapping:n.get(J.sourceSchema.id,f.mapping.connectionId),De=Be(Ce,J.sourceSchema,ye.source.name)??Or(Ce,J.sourceSchema,ye.source.name,o.resolveSchema)?.column??ye.source.id,Ke=ye.source.udf?.sql,ut=Be(de,J.targetSchema,ye.target.name)??ye.target.id,gt=ye.target.udf?.sql,He=J.sourceSchema.properties.find(({type:it})=>it==="timestamp"),Ve=J.targetSchema.properties.find(({type:it})=>it==="timestamp"),Te=sp(J.sourceSchema,J.targetSchema,o.plugins),Fe=He?Be(Ce,J.sourceSchema,He.name)??He.id:void 0,fe=Ve?Be(de,J.targetSchema,Ve.name)??Ve.id:void 0,qe=Te?.kind==="date-bucket-equal"?{kind:"date-bucket-equal",sourceColumn:Be(Ce,J.sourceSchema,Te.sourceTimestamp.name)??Te.sourceTimestamp.id,targetColumn:Be(de,J.targetSchema,Te.targetTimestamp.name)??Te.targetTimestamp.id,sourceGranularity:Te.sourceTimestamp.granularity??"day",targetGranularity:Te.targetTimestamp.granularity??"day"}:Te?.kind==="point-in-interval"?{kind:"point-in-interval",pointSide:"source",pointColumn:Be(Ce,J.sourceSchema,Te.point.name)??Te.point.id,intervalSide:"target",startColumn:Be(de,J.targetSchema,Te.start.name)??Te.start.id,endColumn:Be(de,J.targetSchema,Te.end.name)??Te.end.id}:void 0,Je=J.property.isArray?re:void 0;Je&&!D.has(Je)&&D.set(Je,{path:Je,sourceAlias:Z,sourceColumn:De,...Ke?{sourceSql:Ke,...Fe?{sourceTimestampColumn:Fe}:{}}:{},alias:`__array_${re}`}),I.set(re,{kind:"left",path:re,sourceAlias:Z,sourceColumn:De,...Ke?{sourceSql:Ke,...Fe?{sourceTimestampColumn:Fe}:{}}:{},targetSchemaId:J.targetSchema.id,targetConnectionId:de.connectionId,targetSource:rt(de.source),targetAlias:pe,targetColumn:ut,...Je?{sourceArrayExpansionPath:Je}:{},...gt?{targetSql:gt,...fe?{targetTimestampColumn:fe}:{}}:{},...qe?{temporalCondition:qe}:{}});const Pt=Vn(J),Lt=z.slice(0,-1).join("_"),Ct=j(Lt?`${Lt}_${Pt.source.id}`:Pt.source.id).field,ot=j(`${re}_${Pt.target.id}`).field,ur=it=>it.computation?.kind!=="mapping-computation"?on(it):{...it.computation,inputs:Object.fromEntries(Object.entries(it.computation.inputs).map(([So,dt])=>{const No=[...b.values()].find(U=>U.column===(dt.kind==="column"?dt.column:void 0)&&U.qualifier===(dt.kind==="column"?dt.qualifier:void 0));return[So,No?.computation?ur(No):dt]}))},bn=I.get(re);bn&&I.set(re,{...bn,...Ct.computation?{sourceExpression:ur(Ct)}:{},...ot.computation?{targetExpression:ur(ot)}:{}})}Z=pe}const K=xt(V,_.schema,_.property.name)??Or(V,_.schema,_.property.name,o.resolveSchema);if(_.relations.length>0&&K?.sourceRef)throw new l("RELATION_MAPPING_ENRICHMENT_UNSUPPORTED",`Related property ${_.canonicalName} cannot be sourced from a mapping enrichment`,{schemaId:_.schema.id,property:_.property.name});if(K?.calculation){const J=`${_.relations.map(({property:fe})=>fe.id).join(".")}:${_.schema.id}:${It(V)}:${_.property.id}`,re=M.get(J);if(re){const fe={...re,property:_.property.name,propertyId:_.property.id};return b.set(_.canonicalName,fe),{reference:_.canonicalName,schema:_.schema,property:_.property,field:fe}}if(T.has(J))throw new l("CYCLIC_COMPUTATION",`Cyclic computation dependency: ${J}`);const pe={...K.calculation,id:_.property.id};if(V.connectionId!==f.mapping.connectionId)throw new l("COMPUTATION_CONNECTION_MISMATCH","Computation inputs must use the same connection");T.add(J);const de=_.relations.map(({property:fe})=>fe.name).join("_"),ye=Object.fromEntries(Bo(pe).map(fe=>{const qe=pe.inputs[fe];if(!qe)throw new l("COMPUTATION_INPUT_NOT_FOUND",`Unknown computation input: ${fe}`);if(qe.sourceColumn!==void 0){const Ct=qe.sourceColumn;if(qe.sourceRef&&_.relations.length)throw new l("RELATION_MAPPING_ENRICHMENT_UNSUPPORTED","Related calculations cannot read mapping enrichments");const ot=qe.sourceRef?Q(qe.sourceRef):Z;return[fe,{kind:"column",column:Ct,qualifier:ot,schemaId:_.schema.id,property:_.property.name,propertyId:_.property.id}]}const Je=qe.property,Pt=de?`${de}_${Je}`:Je;o.authorizeComputationInput?.(e,Pt);const Lt=j(Pt);if(Lt.property.isArray)throw new l("COMPUTATION_SCALAR_INPUT_REQUIRED",`Computation input must be scalar: ${Je}`);return[fe,on(Lt.field)]}));T.delete(J);const Ce=new Set([...e.properties.map(({id:fe})=>fe),...f.mapping.mappings?.flatMap(fe=>fe.mappingType==="property"?fe.value.kind==="column"?[fe.value.column]:Object.values(fe.value.inputs).flatMap(qe=>qe.sourceColumn?[qe.sourceColumn]:[]):[fe.sourceColumn])??[],...[...b.values()].map(({column:fe})=>fe)].map(fe=>fe.toLowerCase()));let De=b.size,Ke=`__sdb_computation_${De}`;for(;Ce.has(Ke.toLowerCase());)Ke=`__sdb_computation_${++De}`;const ut=`__calc_${de?`${de}_`:""}${pe.id}_source`,gt=new Set([N,...[...I.values()].map(({targetAlias:fe})=>fe),...[...S.values()].map(({alias:fe})=>fe),...[...D.values()].map(({alias:fe})=>fe)].map(fe=>fe.toLowerCase()));let He=ut,Ve=2;for(;C.has(He.toLowerCase())||gt.has(He.toLowerCase());)He=`${ut}_${Ve++}`;C.add(He.toLowerCase());const Te={schemaId:_.schema.id,property:_.property.name,propertyId:_.property.id,column:Ke,qualifier:N,computation:{kind:"mapping-computation",definition:pe,inputs:ye,alias:He}};pe.kind==="sql"&&Y.push({id:K.propertyId??_.property.id,alias:He,source:aa(pe.sql),schemaId:V.schemaId,mappingSource:rt(V.source).identity,connectionId:V.connectionId});const Fe=L(_,Te,Z);return M.set(J,Fe),b.set(_.canonicalName,Fe),{reference:_.canonicalName,schema:_.schema,property:_.property,field:Fe}}const ie=K?.sourceRef?Q(K.sourceRef):Z,me={schemaId:_.schema.id,property:_.property.name,propertyId:_.property.id,column:K?.column??_.property.id,qualifier:ie,..._.property.isArray?{isArray:!0}:{},..._.property.type==="tag"?{normalizeStringArray:!0}:{},..._.property.comparable?{comparable:_.property.comparable}:{},...Gf(_.relations.length>0?e:_.schema,_.property.udf?.sql,_.relations.length>0?f.mapping:V,N)},W=L(_,me,Z);return b.set(_.canonicalName,W),{reference:_.canonicalName,schema:_.schema,property:A.property,field:W}},oe=g=>{if(g)for(const[A,_]of Object.entries(g))if((A==="$and"||A==="$or")&&Array.isArray(_))for(const P of _)typeof P=="object"&&P!==null&&!Array.isArray(P)&&oe(P);else if(A==="$expr"&&typeof _=="object"&&_!==null&&!Array.isArray(_)){const P=_.pred;typeof P=="object"&&P!==null&&!Array.isArray(P)&&Xn(P).forEach(j)}else A.startsWith("$")||j(A)},H=g=>{if(Re(g)){const A=Zn(g,e,o),_=Me(g,A,r,n,o);if(_.projections.length!==1)throw new l("SUBQUERY_SINGLE_COLUMN_REQUIRED",`Query LogicForm must output exactly one column, received ${_.projections.length}`,{schemaId:g.schema,projectionCount:_.projections.length});return{kind:"logicform-subquery",plan:_}}return Array.isArray(g)?g.map(H):typeof g!="object"||g===null||g instanceof Date?g:Object.fromEntries(Object.entries(g).map(([A,_])=>[A,H(_)]))},R=g=>Object.fromEntries(Object.entries(g).map(([A,_])=>{if((A==="$and"||A==="$or")&&Array.isArray(_))return[A,_.map(B=>R(B))];if(A==="$expr"){if(typeof _!="object"||_===null||Array.isArray(_))throw new l("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const B=_;if(typeof B.pred!="object"||B.pred===null||Array.isArray(B.pred)||!Object.prototype.hasOwnProperty.call(B,"condition"))throw new l("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const X=B.pred,Z=Tr(X,r,j,G,ee,R,e,o.resolveSchema,"groupby",i);if(Z.outputProperty.isArray)throw new l("ARRAY_EXPRESSION_QUERY_UNSUPPORTED","$expr must produce a scalar value");const V=H(B.condition);return Z.outputProperty.comparable&&Ti(V,X.name??X.operator??"$expr",Z.outputProperty.comparable.values),[A,{kind:"expression-query",expression:Z.expression,condition:Z.outputProperty.comparable?{kind:"ordinal-query",comparable:Z.outputProperty.comparable,condition:V}:V,properties:Xn(X)}]}if(typeof _=="object"&&_!==null&&!Array.isArray(_)){const X=Object.entries(_).find(([Z])=>gr(Z,o.plugins));if(X){const[Z,V]=X,z=gr(Z,o.plugins);if(!z)throw new Error(`Query Operator disappeared: ${Z}`);const K=j(A),ie=z.plan(V,{schema:K.schema,property:K.property,connectionId:f.mapping.connectionId,resolveSource:rt,...o.resolveSchema?{resolveSchema:o.resolveSchema}:{},resolveMapping:(me,W)=>n.get(me,W)});return[A,{[Z]:{kind:"query-operator",operator:Z,value:ie.value,definition:z,...ie.sources?{sources:ie.sources}:{}}}]}}const P=A.startsWith("$")?void 0:j(A).property.comparable;return[A,P?{kind:"ordinal-query",comparable:P,condition:H(_)}:H(_)]})),x=g=>{const A=V=>{if(!V||typeof V!="object")return!1;if(Array.isArray(V))return V.some(A);const z=V;return Object.prototype.hasOwnProperty.call(z,"$and")||Object.values(z).some(A)};if(A(g))return g;const _=new Set(Object.keys(g).flatMap(V=>{if(V.startsWith("$"))return[];const z=ne(e,V,o.resolveSchema);return z.relations.length===1&&z.property.type==="ID"?[z.relations[0]?.property.name]:[]})),P=Object.entries(g).map(([V,z])=>{if(V==="$and"||V==="$or")return Array.isArray(z)?[V,z.map(ye=>typeof ye=="object"&&ye!==null&&!Array.isArray(ye)?x(ye):ye)]:[V,z];if(V.startsWith("$"))return[V,z];const K=ne(e,V,o.resolveSchema);if(K.relations.length===0||Er(K.property)||K.relations[0]&&Er(K.relations[0].property))return[V,z];if(Rr(f.mapping,e,V,o.resolveSchema))return[V,z];if(K.property.udf?.sql.includes("$TS")===!0||K.relations.some(({property:ye})=>ye.udf?.sql.includes("$TS")===!0))return[V,z];const me=K.relations.map(({property:ye})=>ye.name).join("_");if(I.has(me))return[V,z];const[W]=K.relations;if(!W)return[V,z];if(_.has(W.property.name))return[V,z];const J=W.property.name,re=K.canonicalName.slice(J.length+1),pe=W.targetSchema.properties.find(({type:ye})=>ye==="ID");if(!pe)throw new l("RELATION_TARGET_ID_REQUIRED",`Relation target ${W.targetSchema.id} must contain an ID property`,{schemaId:W.targetSchema.id});if(K.relations.length===1&&K.property.id===pe.id)return[W.property.id,z];const de={version:t.version,schema:W.targetSchema.id,query:re?{[re]:z}:{},preds:[{pred:pe.name,name:pe.name}]};return[W.property.id,{$in:de}]}),B=new Map;for(const[V,z]of P){const K=B.get(V)??[];K.push(z),B.set(V,K)}const X=Object.fromEntries([...B].filter(([,V])=>V.length===1).map(([V,z])=>[V,z[0]])),Z=[...B].flatMap(([V,z])=>z.length>1?z.map(K=>({[V]:K})):[]);return Z.length>0?{...X,$and:Z}:X},F=(t.groupby??[]).map(g=>{const A=nn(g);g.operator&&r.get(g.operator).validateGroupby?.({pred:g,executionContext:r.executionContext});const _=Tr(g,r,j,G,ee,R,e,o.resolveSchema,"groupby",i);let P=_.expression;if($?.group===g&&(P={kind:"column",schemaId:e.id,property:$.property.name,propertyId:$.property.id,column:"__period_start",qualifier:"__periods"}),_.sourceProperty?.isArray&&_.sourceField){const B=`groupby:${A}`;D.set(B,{path:B,sourceAlias:_.sourceField.qualifier,sourceColumn:_.sourceField.column,..._.sourceField.sql?{sourceSql:_.sourceField.sql,..._.sourceField.timestampColumn?{sourceTimestampColumn:_.sourceField.timestampColumn}:{}}:{},alias:`__array_group_${D.size}`,..._.sourceProperty.type==="tag"?{normalizeStringArray:!0}:{},..._.sourceProperty.type==="tag"?{elementType:"string"}:{}}),P={kind:"array-element",schemaId:_.sourceField.schemaId,property:_.sourceProperty.name,expansionPath:B}}return{name:A,expression:P,outputProperty:{..._.outputProperty,name:A,isArray:!1}}});function G(g){const A=(t.groupby??[]).findIndex(P=>typeof P.pred=="string"&&P.pred===g||P.name===g),_=A>=0?F[A]:void 0;if(!_)throw new l("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${g}`);return _.expression}function ee(g){const A=(t.groupby??[]).findIndex(P=>typeof P.pred=="string"&&P.pred===g||P.name===g),_=A>=0?F[A]:void 0;return _?_.expression:on(j(g).field)}const ue=g=>{g.operator&&r.get(g.operator).validatePlan?.({executionContext:r.executionContext,pred:g,groupByNames:F.map(({name:A})=>A),resolveGroupName:A=>{const _=(t.groupby??[]).findIndex(P=>P.name===A||typeof P.pred=="string"&&P.pred===A);return _>=0?F[_]?.name:void 0},getOperator:A=>r.get(A)}),g.pred&&typeof g.pred=="object"&&!Array.isArray(g.pred)&&ue(g.pred);for(const A of Array.isArray(g.pred)?g.pred:[])ue(typeof A=="string"?{pred:A}:A)};for(const g of t.preds??[])ue(g);const Ee=[...F,...(t.preds??[]).map((g,A)=>{const _=$?.rewritePred?.(g)??g;return zf(_,r,j,G,ee,R,e,o.resolveSchema,d,h.get(A),Ia(_,t.groupby??[],e,o.resolveSchema)?"$min":void 0,s?.[A]??g,i)})],Ge=g=>Object.fromEntries(Object.entries(g).map(([A,_])=>{if((A==="$and"||A==="$or")&&Array.isArray(_))return[A,_.map(B=>Ge(B))];if(A==="$expr")throw new l("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const P=Ee.find(({name:B})=>B===A)?.outputProperty.comparable;return P&&Ti(_,A,P.values),[A,P?{kind:"ordinal-query",comparable:P,condition:H(_)}:H(Pi(_,Ee.map(({outputProperty:B})=>B)))]})),Ze=E?x(E):void 0;oe(Ze);const ze=g=>{oe(g.query),g.pred&&typeof g.pred=="object"&&!Array.isArray(g.pred)&&ze(g.pred);for(const A of Array.isArray(g.pred)?g.pred:[])ze(typeof A=="string"?{pred:A}:A)};for(const g of t.preds??[])ze(g);if(Ee.length===0)throw new l("EMPTY_PROJECTION","LogicForm must contain preds or groupby");pc(Ee);const v=new Set(Ee.map(({name:g})=>g)),Ae=F.length>0?{kind:"group",names:F.map(({name:g})=>g),separator:"_",nullLabel:"\u7A7A\u503C"}:Ee.every(({expression:g})=>g.kind==="column"||g.kind==="property-sql")||Ee.some(({expression:g})=>g.kind==="property-sql"&&e.properties.some(({id:A,type:_})=>_==="ID"&&A===g.propertyId))?(()=>{const g=e.properties.find(({type:B})=>B==="ID");if(!g||!(o.canUsePropertyRowIdentity?.(e,g)??!0))return{kind:"generated"};const A=xt(f.mapping,e,g.name),_=A?.calculation?j(g.id).field:void 0;return{kind:"property",column:(O.get(g.name)??_)?.column??A?.column??g.id,internalName:"_id"}})():{kind:"singleton"},Le=Object.entries(t.sort??{}).map(([g,A])=>{if(!v.has(g))throw new l("INVALID_SORT",`Sort field is not an output: ${g}`);const _=Ee.find(P=>P.name===g);return{name:g,direction:A===1?"ASC":"DESC",..._?.outputProperty.comparable?{comparable:_.outputProperty.comparable,expression:_.expression}:{}}}),$e=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},We=t.limitBy===void 0?void 0:{count:t.limitBy,partitionBy:F.slice(0,-1).map(({name:g})=>g),orderBy:Le.length>0?Le:(()=>{const g=F.at(-1);return[{name:g?.name??"",direction:"ASC",...g?.outputProperty.comparable?{comparable:g.outputProperty.comparable,expression:g.expression}:{}}]})()},k=b.size===0&&m.length===0&&I.size===0&&S.size===0&&D.size===0&&!Ze&&F.length===0&&Ee.length>0&&Ee.every(({expression:g})=>g.kind==="operator"&&g.operator==="$constant");return Qf({schemaId:e.id,source:k?void 0:rt(f.mapping.source),...k?{}:{connectionId:f.mapping.connectionId},mappingId:It(f.mapping),sourceAlias:N,fields:{...Rp(e),...Object.fromEntries(e.properties.flatMap(g=>{const A=Be(f.mapping,e,g.name)??Or(f.mapping,e,g.name,o.resolveSchema)?.column;return A?[[g.name,A],[g.id,A]]:[]})),...Object.fromEntries((f.mapping.mappings??[]).flatMap(g=>{if(g.mappingType!=="property")return[];const A=g.propertyId,_=Rr(f.mapping,e,A,o.resolveSchema);if(!_)return[];const P=ne(e,A,o.resolveSchema);return[[P.canonicalName,_.column],[P.canonicalId,_.column]]}))},fieldReferences:Object.fromEntries(b),computationSources:Y,joins:[...I.values()],enrichmentJoins:[...S.values()],arrayExpansions:[...D.values()],...m.length>0?{physicalQueryFilters:m}:{},...$?{periodSource:{alias:"__periods",labelColumn:"__period_start",asOfColumn:"__as_of",sourceAlias:N,periods:$.periods,match:$.source.kind==="interval"?{kind:"interval",startColumn:Be(f.mapping,e,$.source.start.name)??$.source.start.id,endColumn:Be(f.mapping,e,$.source.end.name)??$.source.end.id}:{kind:"latest",lookupAlias:"__period_lookup",timestampColumn:Be(f.mapping,e,$.source.timestamp.name)??$.source.timestamp.id}}}:{},projections:Ee.map(({name:g,expression:A})=>({name:g,expression:A})),columnProperties:Ee.map(({outputProperty:g})=>g),groupBy:F.map(({name:g,expression:A})=>({name:g,expression:A})),...Ze?{query:R(Ze)}:{},...t.having?{having:Ge(t.having)}:{},orderBy:Le,rowIdentity:k?{kind:"singleton"}:Ae,...$e?{pagination:$e}:{},...We?{groupLimit:We}:{}})};class Jf{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 sn=(t,e,r,n,o)=>{const i=Qa(t,[],String,`Property ${e} SQL expression`);if(!i.includes("$TS"))return i;if(!n)throw new l("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)},ct=(t,e,r,n=!1,o,i,s,a)=>{const u=(c,d)=>n&&d?`${e.quoteIdentifier(d)}.${e.quoteIdentifier(c)}`:e.quoteIdentifier(c);switch(t.kind){case"mapping-computation":return cl(t,e,c=>ct(c,e,r,!0,o,i,s,a),i??(()=>{throw new Error("Computation literals require a parameter binder")}));case"array-element":if(!a)throw new l("ARRAY_EXPANSION_UNAVAILABLE","Array expansion compiler is unavailable");return a(t.expansionPath);case"column":return u(t.column,t.qualifier);case"property-sql":return sn(t.sql,t.property,e,t.timestampColumn,n?t.timestampQualifier??t.qualifier:void 0);case"window":{const c=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>ct(f,e,r,n,o,i,s,a)).join(", ")} `:"",d=ct(t.input,e,r,n,o,i,s,a);return`${t.function==="rank"?"RANK":"ROW_NUMBER"}() OVER (${c}ORDER BY ${d} ${t.direction})`}case"cumulative":{const c=ct(t.input,e,r,n,o,i,s,a),d=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>ct(f,e,r,n,o,i,s,a)).join(", ")} `:"",p=t.orderBy.map(f=>`${ct(f.expression,e,r,n,o,i,s,a)} ${f.direction}`).join(", ");return`${e.aggregateFunction(t.function,c)} OVER (${d}ORDER BY ${p} ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`}case"ordinal-encode":{if(!i)throw new l("SQL_BINDER_UNAVAILABLE","Ordinal encoding requires a value binder");return`CASE ${t.comparable.values.map((d,p)=>`WHEN ${ct(t.input,e,r,n,o,i,s,a)} = ${i(d)} THEN ${t.comparable.direction*p}`).join(" ")} END`}case"ordinal-decode":{if(!i)throw new l("SQL_BINDER_UNAVAILABLE","Ordinal decoding requires a value binder");return`CASE ${t.comparable.values.map((d,p)=>`WHEN ${ct(t.input,e,r,n,o,i,s,a)} = ${t.comparable.direction*p} THEN ${i(d)}`).join(" ")} END`}case"operator":{const c=r.get(t.operator);if(r.isComponent({operator:t.operator,...t.query?{query:t.query}:{}}))throw new l("COMPONENT_OPERATOR_REQUIRES_EXECUTOR",`${t.operator} must be compiled through the executor component pipeline`);let d=t.input?ct(t.input,e,r,n,o,i,s,a):t.column?u(t.column,t.qualifier):void 0;const p=t.inputs?.map(f=>ct(f,e,r,n,o,i,s,a));if(t.query&&Object.keys(t.query).length>0){if(c.kind!=="aggregate")throw new l("OPERATOR_QUERY_REQUIRES_AGGREGATION",`Pred query is only supported by aggregation operators: ${t.operator}`);if(!o)throw new l("INVALID_OPERATOR_QUERY","Operator query compiler is unavailable");d=`CASE WHEN ${o(t.query)} THEN ${d??"1"} END`}if(c.requiresProperty!==!1&&!d)throw new l("PRED_PROPERTY_REQUIRED",`${t.operator} requires a column`);if(!c.toSQL)throw new l("OPERATOR_SQL_REQUIRED",`${t.operator} cannot be compiled to SQL`);return c.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:(f,m)=>{if(!i)throw new l("SQL_BINDER_UNAVAILABLE","SQL value binder is unavailable");const h=i(f);return m&&e.castValue?e.castValue(h,m):h},condition:(f,m)=>{if(!s)throw new l("SQL_CONDITION_UNAVAILABLE","SQL condition compiler is unavailable");return s(f,m)}},...d?{expression:d,column:d}:{},...p?{expressions:p}:{},args:t.args})}}},Xf=(t,e)=>{const r=t.sourceSql?sn(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},lc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).some(e=>e.startsWith("$")),fc={$second:"second",$minute:"minute",$hour:"hour",$weekday:"weekday",$day:"day",$week:"week",$month:"month",$quarter:"quarter",$year:"year"},an=(t,e,r,n,o,i,s,a,u)=>{if(Ka(r)){if(r.operator!==e)throw new l("INVALID_PLUGIN_QUERY",`Query Operator plan does not match ${e}`);const f=r.definition??s(e);if(!f)throw new l("UNSUPPORTED_QUERY_OPERATOR",`Query Operator is not registered: ${e}`);return f.compile(r.value,{field:t,provider:o,bind:m=>n.add(m),renderSource:m=>Hn(m,o)})}if(s(e))throw new l("INVALID_PLUGIN_QUERY",`${e} query was not planned`,{operator:e});if(e==="$eq"&&a!==void 0){if(typeof r!="string"||a!=="i")throw new l("INVALID_QUERY_VALUE",'$eq args.options supports only case-insensitive string equality with "i"');const f=n.add(r);return"LOWER("+t+") = LOWER("+f+")"}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){if(Pf(r)){if(!u)throw new l("INVALID_HAVING","Output reference requires a result field resolver");return`${t} ${p} ${u(r.name)}`}const f=qt(r)?`(${i(r)})`:n.add(r);return`${t} ${p} ${f}`}if(e==="$in"||e==="$nin"){const f=e==="$in"?"IN":"NOT IN";if(qt(r))return`${t} ${f} (${i(r)})`;if(!Array.isArray(r))throw new l("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(qt);if(m.length>0){if(m.length!==r.length)throw new l("MIXED_SUBQUERY_VALUES",`${e} cannot mix query LogicForm objects and literal values`);return`${t} ${f} (${m.map(i).join(" UNION ALL ")})`}const h=r.map(y=>n.add(y)).join(", ");return`${t} ${f} (${h})`}if(qt(r))throw new l("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 l("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 l("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 l("UNSUPPORTED_QUERY_OPERATOR",`Unsupported query operator: ${e}`)},Ci=(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 l("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}if(typeof t=="object"&&t!==null&&!qt(t)){for(const[r,n]of Object.entries(t)){if(!r.startsWith("$"))throw new l("INVALID_QUERY_VALUE",`${e} requires numeric conditions`);if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new l("INVALID_QUERY_VALUE",`${r} requires an array`);n.forEach(o=>Ci(o,e))}else if(r==="$in"||r==="$nin"){if(!Array.isArray(n)||n.some(o=>typeof o!="number"||!Number.isFinite(o)))throw new l("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}else if(typeof n!="number"||!Number.isFinite(n))throw new l("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}return}throw new l("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}},or=(t,e,r,n,o,i,s)=>{if(Lf(e)){const d=()=>`CASE ${e.comparable.values.map((h,y)=>`WHEN ${t} = ${r.add(h)} THEN ${e.comparable.direction*y}`).join(" ")} END`,p=new Set(["$gt","$gte","$lt","$lte"]),f=m=>typeof m!="object"||m===null||Array.isArray(m)?or(t,m,r,n,o,i):Object.entries(m).filter(([h])=>h!=="args").map(([h,y])=>(h==="$and"||h==="$or")&&Array.isArray(y)?`(${y.map(f).join(h==="$and"?" AND ":" OR ")})`:p.has(h)?an(d(),h,e.comparable.direction*e.comparable.values.indexOf(String(y)),r,n,o,i):an(t,h,y,r,n,o,i)).join(" AND ");return f(e.condition)}if(Array.isArray(e))return an(t,"$in",e,r,n,o,i);if(!lc(e))return an(t,"$eq",e,r,n,o,i,void 0,s);const a=[],u=e.args;if(u!==void 0){if(typeof u!="object"||u===null||Array.isArray(u))throw new l("INVALID_QUERY_VALUE","Query args.options must be a string");const d=u.options;if(d!==void 0&&typeof d!="string")throw new l("INVALID_QUERY_VALUE","Query args.options must be a string")}const c=u?.options;for(const[d,p]of Object.entries(e))if(d==="$and"||d==="$or"){if(!Array.isArray(p))throw new l("INVALID_QUERY_VALUE",`${d} requires an array`);const f=p.map(m=>or(t,m,r,n,o,i,s));a.push(`(${f.join(d==="$and"?" AND ":" OR ")})`)}else fc[d]?(Ci(p,d),a.push(or(n.datePart(t,fc[d]),p,r,n,o,i))):d==="$length"?(Ci(p,"$length"),a.push(or(n.stringLength(t),p,r,n,o,i))):d!=="args"&&a.push(an(t,d,p,r,n,o,i,d==="$regex"||d==="$eq"?c:void 0,s));if(a.length===0)throw new l("EMPTY_QUERY_CONDITION","Query condition contains no operators");return a.join(" AND ")},mc=(t,e,r,n)=>{if(!n.arrayContains)throw new l("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(!lc(e))return i(e);const s=[];for(const[a,u]of Object.entries(e))if(a==="$and"||a==="$or"){if(!Array.isArray(u))throw new l("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(d=>mc(t,d,r,n));s.push(`(${c.join(a==="$and"?" AND ":" OR ")})`)}else if(a==="$eq")s.push(i(u));else if(a==="$ne")s.push(`NOT (${i(u)})`);else if(a==="$in"||a==="$nin"){if(!Array.isArray(u))throw new l("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(i),d=c.length===0?a==="$in"?"0 = 1":"1 = 1":c.join(a==="$in"?" OR ":" AND NOT ");s.push(a==="$nin"&&c.length>0?`NOT (${c.join(" OR ")})`:`(${d})`)}else if(a==="$exists")s.push(`${t} IS ${u?"NOT ":""}NULL`);else if(a!=="args")throw new l("UNSUPPORTED_ARRAY_QUERY_OPERATOR",`Unsupported array query operator: ${a}`);if(s.length===0)throw new l("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},St=(t,e,r,n,o,i,s,a)=>{const u=[];for(const[c,d]of Object.entries(t)){if(c==="$and"||c==="$or"){if(!Array.isArray(d))throw new l("INVALID_QUERY_VALUE",`${c} requires an array`);const f=d.map(m=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new l("INVALID_QUERY_VALUE",`${c} items must be query objects`);return St(m,e,r,n,o,i,s,a)});u.push(`(${f.join(c==="$and"?" AND ":" OR ")})`);continue}if(c==="$expr"){if(!zn(d))throw new l("INVALID_EXPRESSION_QUERY","$expr query was not planned");u.push(or(s(d.expression),d.condition,n,o,i,a));continue}const p=e(c);u.push(r(c)?mc(p,d,n,o):or(p,d,n,o,i,a,e))}return u.join(" AND ")},ir=(t,e,r,n,o)=>t.orderBy.map(i=>{const s=e.quoteIdentifier(i.name),a=`${n?`${n}.`:""}${s}`,u=i.comparable,c=!n&&o&&i.expression?o(i.expression):a;return`${u?`CASE ${u.values.map((p,f)=>`WHEN ${c} = ${r.add(p)} THEN ${u.direction*f}`).join(" ")} END`:a} ${i.direction}`}).join(", "),Di=(t,e)=>{let r=t;for(;e.has(r);)r=`_${r}`;return r},eo=(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`])),cn=(t,e,r,n,o)=>{const i=new Set(e.projections.map(({name:T})=>T)),s="__sdb_page_source",a="__sdb_page",u=n.quoteIdentifier(s),c=n.quoteIdentifier(a),d=Di("__sdb_row_number",i),p=Di("__sdb_total_rows",i),f=n.quoteIdentifier(d),m=n.quoteIdentifier(p),h=ir(e,n,o,u),y=h?`ORDER BY ${h}`:"",$=`CEIL(${m} * ${r.ratio})`,w=r.page-1,E=r.page,I=[...e.projections.map(({name:T})=>T),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(T=>`${c}.${n.quoteIdentifier(T)}`).join(", "),S=ir(e,n,o,c),D=`SELECT ${u}.*, ROW_NUMBER() OVER (${y}) AS ${f}, COUNT(*) OVER () AS ${m} FROM ${n.tableAlias(`(${t})`,s)}`;let b=`SELECT ${I} FROM ${n.tableAlias(`(${D})`,a)} WHERE ${c}.${f} > ${w} * ${$} AND ${c}.${f} <= ${E} * ${$}`;return S&&(b+=` ORDER BY ${S}`),b},yc=(t,e,r,n)=>{const o=e.groupLimit;if(!o)return t;const i="__sdb_limit_by_source",s="__sdb_limit_by_ranked",a=r.quoteIdentifier(i),u=r.quoteIdentifier(s),c=new Set(e.projections.map(({name:E})=>E)),d=Di("__sdb_limit_by_row_number",c),p=r.quoteIdentifier(d),f=o.partitionBy.map(E=>`${a}.${r.quoteIdentifier(E)}`).join(", "),m=o.orderBy.map(({name:E,direction:N,comparable:I})=>{const S=`${a}.${r.quoteIdentifier(E)}`;return`${I?`CASE ${I.values.map((b,T)=>`WHEN ${S} = ${n.add(b)} THEN ${I.direction*T}`).join(" ")} END`:S} ${N}`}).join(", "),y=[...e.projections.map(({name:E})=>E),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(E=>`${u}.${r.quoteIdentifier(E)}`).join(", "),$=`PARTITION BY ${f} ORDER BY ${m}`,w=`SELECT ${a}.*, ROW_NUMBER() OVER (${$}) AS ${p} FROM ${r.tableAlias(`(${t})`,i)}`;return`SELECT ${y} FROM ${r.tableAlias(`(${w})`,s)} WHERE ${u}.${p} <= ${o.count}`},Oe=(t,e,r=at(),n=0)=>{const o=new Jf(e,n),i=b=>gr(b);if(t.rowPartition){const b=t.subplans??[];if(b.length===0)throw new l("INVALID_PARTITION_PLAN","A row partition requires child plans");const T=t.projections.map(({name:L})=>L),M=b.map((L,q)=>{const Q=Oe(L,e,r,o.nextParameterOffset);o.append(Q.parameters);const j=`__row_partition_child_${q}`,oe=e.quoteIdentifier(j);return`SELECT ${T.map(H=>`${oe}.${e.quoteIdentifier(H)} AS ${e.quoteIdentifier(H)}`).join(", ")} FROM ${e.tableAlias(`(${Q.sql})`,j)}`}),Y="__row_partition",C=e.quoteIdentifier(Y);let O=`SELECT ${C}.* FROM ${e.tableAlias(`(${M.join(" UNION ALL ")})`,Y)}`;if(t.having&&Object.keys(t.having).length>0){const L=new Set(T),q=St(t.having,Q=>{if(!L.has(Q))throw new l("INVALID_HAVING",`Having field is not an output: ${Q}`);return`${C}.${e.quoteIdentifier(Q)}`},()=>!1,o,e,()=>{throw new l("SUBQUERY_IN_PARTITION_HAVING_UNSUPPORTED","Partition having cannot contain a LogicForm subquery")},()=>{throw new l("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query")},i);O+=` WHERE ${q}`}if(t.pagination?.kind==="ratio")O=cn(O,t,t.pagination,e,o);else if(t.orderBy.length>0&&(O+=` ORDER BY ${ir(t,e,o)}`),t.pagination?.kind==="rows"){const L=(t.pagination.page-1)*t.pagination.pageSize;O=e.paginate(O,t.pagination.pageSize,L)}return{sql:O,parameters:o.values}}if(t.sumPartition){const b=t.subplans??[];if(b.length===0)throw new l("INVALID_PARTITION_PLAN","A sum partition requires child plans");const T=t.groupBy.map(({name:j})=>j),M=t.projections.map(({name:j})=>j).filter(j=>!T.includes(j)),Y=b.map((j,oe)=>{const H=Oe(j,e,r,o.nextParameterOffset);o.append(H.parameters);const R=`__sum_partition_child_${oe}`,x=e.quoteIdentifier(R);return`SELECT ${[...T,...M].map(G=>`${x}.${e.quoteIdentifier(G)}`).join(", ")} FROM ${e.tableAlias(`(${H.sql})`,R)}`}),C="__sum_partition",O=e.quoteIdentifier(C),L=T.map(j=>`${O}.${e.quoteIdentifier(j)}`),q=[...L.map((j,oe)=>`${j} AS ${e.quoteIdentifier(T[oe])}`),...M.map(j=>`SUM(${O}.${e.quoteIdentifier(j)}) AS ${e.quoteIdentifier(j)}`)];t.rowIdentity.kind==="group"&&q.push(`${eo(L,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`);let Q=`SELECT ${q.join(", ")} FROM ${e.tableAlias(`(${Y.join(" UNION ALL ")})`,C)}`;if(L.length>0&&(Q+=` GROUP BY ${L.join(", ")}`),t.having&&Object.keys(t.having).length>0){const j="__sum_partition_having",oe=e.quoteIdentifier(j),H=new Set(t.projections.map(({name:x})=>x)),R=St(t.having,x=>{if(!H.has(x))throw new l("INVALID_HAVING",`Having field is not an output: ${x}`);return`${oe}.${e.quoteIdentifier(x)}`},()=>!1,o,e,()=>{throw new l("SUBQUERY_IN_PARTITION_HAVING_UNSUPPORTED","Partition having cannot contain a LogicForm subquery")},()=>{throw new l("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query")},i);Q=`SELECT ${oe}.* FROM ${e.tableAlias(`(${Q})`,j)} WHERE ${R}`}if(t.pagination?.kind==="ratio")Q=cn(Q,t,t.pagination,e,o);else if(t.orderBy.length>0&&(Q+=` ORDER BY ${ir(t,e,o)}`),t.pagination?.kind==="rows"){const j=(t.pagination.page-1)*t.pagination.pageSize;Q=e.paginate(Q,t.pagination.pageSize,j)}return{sql:Q,parameters:o.values}}if(t.splitGroup){const b=t.splitGroup,T=b.name,M=t.projections.map(({name:O})=>O).filter(O=>!b.groupNames.includes(O));let C=(t.subplans??[]).map((O,L)=>{const q=b.values[L];if(q===void 0)throw new l("INVALID_SPLIT_GROUP","A split group branch has no enum value");const Q=b.groupNames.map(ue=>ue===T?o.add(q):`${e.quoteIdentifier(`__split_group_${L}`)}.${e.quoteIdentifier(ue)}`),j=b.groupNames.map(ue=>ue===T?`'${q.replaceAll("'","''")}'`:`${e.quoteIdentifier(`__split_group_${L}`)}.${e.quoteIdentifier(ue)}`),oe=eo(j,e,t.rowIdentity.kind==="group"?t.rowIdentity.separator:"_",t.rowIdentity.kind==="group"?t.rowIdentity.nullLabel:"\u7A7A\u503C"),H=Oe(O,e,r,o.nextParameterOffset);o.append(H.parameters);const R=`__split_group_${L}`,x=e.quoteIdentifier(R),F=b.groupNames.map((ue,Ee)=>`${Q[Ee]} AS ${e.quoteIdentifier(ue)}`),G=M.map(ue=>`${x}.${e.quoteIdentifier(ue)} AS ${e.quoteIdentifier(ue)}`),ee=M.map(ue=>`${x}.${e.quoteIdentifier(ue)} IS NOT NULL`).join(" OR ");return`SELECT ${[...F,...G].join(", ")}, ${oe} AS ${e.quoteIdentifier("_id")} FROM ${e.tableAlias(`(${H.sql})`,R)} WHERE (${ee})`}).join(" UNION ALL ");if(t.having&&Object.keys(t.having).length>0){const O="__split_group_having",L=e.quoteIdentifier(O),q=new Set(t.projections.map(({name:j})=>j)),Q=St(t.having,j=>{if(!q.has(j))throw new l("INVALID_HAVING",`Having field is not an output: ${j}`);return`${L}.${e.quoteIdentifier(j)}`},()=>!1,o,e,()=>{throw new l("SUBQUERY_IN_COMPOSITION_HAVING_UNSUPPORTED","A split group having condition cannot contain a LogicForm subquery")},()=>{throw new l("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names")},i);C=`SELECT ${L}.* FROM ${e.tableAlias(`(${C})`,O)} WHERE ${Q}`}if(t.pagination?.kind==="ratio")C=cn(C,t,t.pagination,e,o);else if(t.orderBy.length>0&&(C+=` ORDER BY ${ir(t,e,o)}`),t.pagination?.kind==="rows"){const O=(t.pagination.page-1)*t.pagination.pageSize;C=e.paginate(C,t.pagination.pageSize,O)}return{sql:C,parameters:o.values}}if(t.subplans){const b=t.projections.map(({name:q})=>q),T=new Set(t.groupBy.map(({name:q})=>q)),M=t.subplans.map((q,Q)=>{const j=Oe(q,e,r,o.nextParameterOffset);o.append(j.parameters);const oe=`__composition_child_${Q}`,H=e.quoteIdentifier(oe),R=new Set(q.projections.map(({name:x})=>x));return{aliasName:oe,alias:H,available:R,sql:j.sql}}),Y=M[0];if(!Y)throw new l("INVALID_COMPOSITION","Composition has no children");const C=b.map(q=>{const Q=M.filter(H=>H.available.has(q)),j=Q[0]??Y;return`${T.has(q)&&Q.length>1?`COALESCE(${Q.map(H=>`${H.alias}.${e.quoteIdentifier(q)}`).join(", ")})`:`${j.alias}.${e.quoteIdentifier(q)}`} AS ${e.quoteIdentifier(q)}`}),O=M.map(q=>`${q.alias} AS (${q.sql})`);let L;if(t.rowIdentity.kind==="group"){const Q=e.quoteIdentifier("__composition_keys"),j=e.quoteIdentifier("_id"),oe=e.kind==="clickhouse"?" UNION DISTINCT ":" UNION ";O.push(`${Q} AS (${M.map(H=>`SELECT ${j} FROM ${H.alias}`).join(oe)})`),C.push(`${Q}.${j} AS ${j}`),L=`WITH ${O.join(", ")} SELECT ${C.join(", ")} FROM ${Q}`;for(const H of M)L+=` LEFT JOIN ${H.alias} ON ${Q}.${j} = ${H.alias}.${j}`}else{L=`WITH ${O.join(", ")} SELECT ${C.join(", ")} FROM ${Y.alias}`;for(const q of M.slice(1))L+=` LEFT JOIN ${q.alias} ON 1 = 1`}if(t.having&&Object.keys(t.having).length>0){const q="__composition_having",Q=e.quoteIdentifier(q),j=new Set(b),oe=St(t.having,H=>{if(!j.has(H))throw new l("INVALID_HAVING",`Having field is not an output: ${H}`);return`${Q}.${e.quoteIdentifier(H)}`},()=>!1,o,e,()=>{throw new l("SUBQUERY_IN_COMPOSITION_HAVING_UNSUPPORTED","A composed result having condition cannot contain a LogicForm subquery")},()=>{throw new l("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names")},i);L=`SELECT ${Q}.* FROM ${e.tableAlias(`(${L})`,q)} WHERE ${oe}`}if(t.groupLimit&&(L=yc(L,t,e,o)),t.pagination?.kind==="ratio")L=cn(L,t,t.pagination,e,o);else if(t.orderBy.length>0&&(L+=` ORDER BY ${ir(t,e,o)}`),t.pagination?.kind==="rows"){const q=(t.pagination.page-1)*t.pagination.pageSize;L=e.paginate(L,t.pagination.pageSize,q)}return{sql:L,parameters:o.values}}const s=b=>{const T=Oe(b.plan.rowIdentity.kind==="property"||b.plan.rowIdentity.kind==="group"?{...b.plan,rowIdentity:{kind:"generated"}}:b.plan,e,r,o.nextParameterOffset);return o.append(T.parameters),T.sql},a=(t.joins?.length??0)>0||(t.enrichmentJoins?.length??0)>0,u=(t.arrayExpansions?.length??0)>0,c=a||u||(t.computationSources?.length??0)>0||Object.values(t.fieldReferences??{}).some(({computation:b})=>b!==void 0)||t.projections.some(({expression:b})=>b.kind==="mapping-computation")||t.sourcePlan!==void 0||t.mappingSourcePlan!==void 0||al(t.source)||t.periodSource!==void 0,d=new Map,p=(t.arrayExpansions??[]).map(b=>{if(!e.expandArray)throw new l("ARRAY_EXPANSION_UNSUPPORTED",`Provider ${e.kind} does not support array expansion`);const T=e.expandArray(Xf(b,e),b.alias,"value",b.elementType);return d.set(b.path,T.valueExpression),T}),f=b=>{const T=t.fieldReferences?.[b];if(T?.computation)return h(T.computation);if(T?.sql){const C=sn(T.sql,T.property,e,T.timestampColumn,c?T.timestampQualifier??T.qualifier:void 0);return T.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(C):C}if(T&&c){const C=`${e.quoteIdentifier(T.qualifier)}.${e.quoteIdentifier(T.column)}`;return T.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(C):C}const M=t.fields[b];if(!M)throw new l("PROPERTY_NOT_FOUND",`Query property not found: ${b}`);const Y=e.quoteIdentifier(M);return T?.normalizeStringArray&&e.normalizeStringArray?e.normalizeStringArray(Y):Y},m=()=>(t.physicalQueryFilters??[]).map(({sourceColumn:b,value:T})=>{const M=t.periodSource?.sourceAlias??(c?t.sourceAlias:void 0),Y=M?`${e.quoteIdentifier(M)}.${e.quoteIdentifier(b)}`:e.quoteIdentifier(b);if(qt(T))return`${Y} IN (${s(T)})`;if(Re(T))throw new l("UNPLANNED_QUERY_PATH_VALUE","Query path LogicForm must be planned before SQL compilation");return`${Y} = ${o.add(T)}`}),h=b=>ct(b,e,r,c,T=>St(T,f,M=>t.fieldReferences?.[M]?.isArray===!0,o,e,s,h,i),T=>o.add(T),(T,M)=>or(T,M,o,e,s,i),T=>{const M=d.get(T);if(!M)throw new l("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${T}`);return M}),y=t.projections.map(b=>`${h(b.expression)} AS ${e.quoteIdentifier(b.name)}`),$=t.rowIdentity.kind==="property"?`${c&&t.sourceAlias?`${e.quoteIdentifier(t.sourceAlias)}.`:""}${e.quoteIdentifier(t.rowIdentity.column)} AS ${e.quoteIdentifier(t.rowIdentity.internalName)}`:t.rowIdentity.kind==="group"?(()=>{const b=t.rowIdentity.names.map(T=>{const M=t.groupBy.find(Y=>Y.name===T)??t.projections.find(Y=>Y.name===T);if(!M)throw new l("GROUP_IDENTITY_OUTPUT_NOT_FOUND",`Group identity output not found: ${T}`);return h(M.expression)});return`${eo(b,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`})():void 0,w=[...y,...$?[$]:[]].join(", "),E=t.sourcePlan??t.mappingSourcePlan,N=E?(()=>{const b=Oe(E,e,r,o.nextParameterOffset);return o.append(b.parameters),`(${b.sql})`})():t.source?Hn(t.source,e):"",I=c&&t.sourceAlias?e.tableAlias(N,t.sourceAlias):N;let S=`SELECT ${w}`;if(t.periodSource){const b=t.periodSource,T=b.periods.map(({label:j,asOf:oe},H)=>{const R=o.add(j),x=o.add(oe);return H===0?`SELECT ${R} AS ${e.quoteIdentifier(b.labelColumn)}, ${x} AS ${e.quoteIdentifier(b.asOfColumn)}`:`SELECT ${R}, ${x}`}).join(" UNION ALL "),M=e.tableAlias(`(${T})`,b.alias),Y=e.tableAlias(N,b.sourceAlias),C=e.quoteIdentifier(b.alias),O=e.quoteIdentifier(b.sourceAlias),L=`${C}.${e.quoteIdentifier(b.asOfColumn)}`,q=b.match.kind==="interval"?(()=>{const j=`${O}.${e.quoteIdentifier(b.match.startColumn)}`,oe=`${O}.${e.quoteIdentifier(b.match.endColumn)}`;return`${j} <= ${L} AND (${oe} > ${L} OR ${oe} IS NULL)`})():(()=>{const j=e.tableAlias(N,b.match.lookupAlias),oe=e.quoteIdentifier(b.match.lookupAlias),H=`${O}.${e.quoteIdentifier(b.match.timestampColumn)}`,R=`${oe}.${e.quoteIdentifier(b.match.timestampColumn)}`,x=`SELECT ${e.aggregateFunction("max",R)} FROM ${j} WHERE ${R} <= ${L}`;return`${H} = (${x})`})();S+=` FROM ${M} LEFT JOIN ${Y} ON ${q}`;const Q=[];t.query&&Object.keys(t.query).length>0&&Q.push(St(t.query,f,j=>t.fieldReferences?.[j]?.isArray===!0,o,e,s,h,i)),Q.push(...m()),Q.length>0&&(S+=` AND ${Q.join(" AND ")}`)}else I&&(S+=` FROM ${I}`);for(const b of p)S+=` ${b.joinSql}`;for(const b of t.enrichmentJoins??[]){const T=e.quoteIdentifier(b.alias),M=e.quoteIdentifier(b.baseAlias);S+=` LEFT JOIN ${e.tableAlias(Hn(b.source,e),b.alias)}`;const Y=b.keys.map(({baseColumn:C,targetColumn:O})=>`${M}.${e.quoteIdentifier(C)} = ${T}.${e.quoteIdentifier(O)}`);if(b.temporalCondition?.kind==="point-in-interval"){const C=j=>j==="source"?M:T,O=`${C(b.temporalCondition.pointSide)}.${e.quoteIdentifier(b.temporalCondition.pointColumn)}`,L=C(b.temporalCondition.intervalSide),q=`${L}.${e.quoteIdentifier(b.temporalCondition.startColumn)}`,Q=`${L}.${e.quoteIdentifier(b.temporalCondition.endColumn)}`;Y.push(`${q} <= ${O}`),Y.push(`(${Q} > ${O} OR ${Q} IS NULL)`)}S+=` ON ${Y.join(" AND ")}`}for(const b of t.joins??[]){const T=b.targetMappingSourcePlan?(()=>{const C=Oe(b.targetMappingSourcePlan,e,r,o.nextParameterOffset);return o.append(C.parameters),`(${C.sql})`})():Hn(b.targetSource,e);S+=` LEFT JOIN ${e.tableAlias(T,b.targetAlias)}`;const M=b.sourceArrayExpansionPath?d.get(b.sourceArrayExpansionPath):b.sourceExpression?h(b.sourceExpression):b.sourceSql?sn(b.sourceSql,b.sourceColumn,e,b.sourceTimestampColumn,b.sourceAlias):`${e.quoteIdentifier(b.sourceAlias)}.${e.quoteIdentifier(b.sourceColumn)}`,Y=b.targetExpression?h(b.targetExpression):b.targetSql?sn(b.targetSql,b.targetColumn,e,b.targetTimestampColumn,b.targetAlias):`${e.quoteIdentifier(b.targetAlias)}.${e.quoteIdentifier(b.targetColumn)}`;if(!M)throw new l("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${b.path}`);if(S+=` ON ${M} = ${Y}`,b.temporalCondition?.kind==="date-bucket-equal"){const C=`${e.quoteIdentifier(b.sourceAlias)}.${e.quoteIdentifier(b.temporalCondition.sourceColumn)}`,O=`${e.quoteIdentifier(b.targetAlias)}.${e.quoteIdentifier(b.temporalCondition.targetColumn)}`;S+=` AND ${e.dateBucket(C,b.temporalCondition.sourceGranularity)} = ${e.dateBucket(O,b.temporalCondition.targetGranularity)}`}else if(b.temporalCondition?.kind==="point-in-interval"){const C=j=>j==="source"?e.quoteIdentifier(b.sourceAlias):e.quoteIdentifier(b.targetAlias),O=`${C(b.temporalCondition.pointSide)}.${e.quoteIdentifier(b.temporalCondition.pointColumn)}`,L=C(b.temporalCondition.intervalSide),q=`${L}.${e.quoteIdentifier(b.temporalCondition.startColumn)}`,Q=`${L}.${e.quoteIdentifier(b.temporalCondition.endColumn)}`;S+=` AND ${q} <= ${O} AND (${Q} > ${O} OR ${Q} IS NULL)`}}const D=[];if(!t.periodSource&&t.query&&Object.keys(t.query).length>0&&D.push(St(t.query,f,b=>t.fieldReferences?.[b]?.isArray===!0,o,e,s,h,i)),t.periodSource||D.push(...m()),D.length>0&&(S+=` WHERE ${D.join(" AND ")}`),t.groupBy.length>0){const b=t.groupBy.map(M=>h(M.expression)),T=t.rowIdentity.kind==="group"?[eo(b,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)]:[];S+=` GROUP BY ${[...b,...T].join(", ")}`}if(t.having&&Object.keys(t.having).length>0){const b=T=>{const M=t.projections.find(Y=>Y.name===T);if(!M)throw new l("INVALID_HAVING",`Having field is not an output: ${T}`);return e.supportsHavingAlias===!1?h(M.expression):e.quoteIdentifier(T)};S+=` HAVING ${St(t.having,b,()=>!1,o,e,s,h,i)}`}if(t.groupLimit&&(S=yc(S,t,e,o)),t.pagination?.kind==="ratio")S=cn(S,t,t.pagination,e,o);else if(t.orderBy.length>0&&(S+=` ORDER BY ${ir(t,e,o,void 0,h)}`),t.pagination?.kind==="rows"){const b=(t.pagination.page-1)*t.pagination.pageSize;S=e.paginate(S,t.pagination.pageSize,b)}return{sql:S,parameters:o.values}},Zf=(t,e)=>{const r=Object.keys(e).sort((f,m)=>m.length-f.length),n=[];let o=0;for(;o<t.length;){const f=t[o];if(f&&/\s/.test(f)){o+=1;continue}if(f&&/[()+\-*/,]/.test(f)){n.push(f),o+=1;continue}const m=t.slice(o).match(/^\d+(?:\.\d+)?/);if(m?.[0]){n.push(m[0]),o+=m[0].length;continue}const 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(f??""),o+=1}let i=0;const s=()=>n[i],a=()=>n[i++],u=()=>{const f=a();if(!f)throw new Error("Component expression is incomplete");if(f==="("){const h=d();if(a()!==")")throw new Error("Component expression has an unclosed parenthesis");return`(${h})`}if(/^\d/.test(f))return f;if(!e[f]&&!/^[A-Za-z_$][\w$]*$/.test(f))throw new Error(`Invalid component expression token: ${f}`);if(s()==="("){a();const h=[];if(s()!==")")for(;h.push(d()),s()===",";)a();if(a()!==")")throw new Error("Component expression has an unclosed function call");if(!["ABS","NULLIF","COALESCE"].includes(f.toUpperCase()))throw new Error(`Unsupported component expression function: ${f}`);return`${f.toUpperCase()}(${h.join(", ")})`}const m=e[f];if(!m)throw new Error(`Unknown component in expression: ${f}`);return m},c=()=>{let f=u();for(;s()==="*"||s()==="/";)f=`${f} ${a()} ${u()}`;return f},d=()=>{let f=c();for(;s()==="+"||s()==="-";)f=`${f} ${a()} ${c()}`;return f},p=d();if(i!==n.length)throw new Error(`Unexpected component expression token: ${s()}`);return p},em=t=>`__sdb_cte_${t}`,hc=t=>{const e=t.projections[t.groupBy.length];if(!e)throw new Error("CTE component must produce one metric projection");return e.name},tm=(t,e)=>t?.find(r=>r.name===e),rm=(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,Mi=(t,e,r,n=at())=>{if(t.length===0)throw new Error("CTE query combination requires at least one unit");let o=0;const i=t.map((E,N)=>{const I={...E.compiled,sql:rm(E.compiled.sql,r,o)};return o+=E.compiled.parameters.length,{...E,compiled:I,alias:`__sdb_exec_${N}`}}),s=i.map(({alias:E,compiled:N})=>`${r.quoteIdentifier(E)} AS (${N.sql})`),a=i[0],u=r.quoteIdentifier(a.alias),c=e.groupBy.map(({name:E})=>E),d=e.orderBy??[],p=e.rowIdentity.kind==="group",f=r.quoteIdentifier("__sdb_exec_keys");if(p){const E=r.kind==="clickhouse"?" UNION DISTINCT ":" UNION ",N=I=>[...c.map(S=>`${I}.${r.quoteIdentifier(S)}`),`${I}.${r.quoteIdentifier("_id")}`].join(", ");s.push(`${f} AS (${i.map(({alias:I})=>`SELECT ${N(r.quoteIdentifier(I))} FROM ${r.quoteIdentifier(I)}`).join(E)})`)}const m=p?f:u,h=[...c,...t.flatMap(({outputs:E})=>E)],y=h.filter((E,N,I)=>I.indexOf(E)===N).map(E=>{if(c.includes(E))return`${m}.${r.quoteIdentifier(E)} AS ${r.quoteIdentifier(E)}`;const N=i.find(({outputs:S})=>S.includes(E));if(!N)throw new Error(`CTE execution unit does not expose output projection: ${E}`);return`${r.quoteIdentifier(N.alias)}.${r.quoteIdentifier(E)} AS ${r.quoteIdentifier(E)}`});p&&y.push(`${m}.${r.quoteIdentifier("_id")} AS ${r.quoteIdentifier("_id")}`);let $=`SELECT ${y.join(", ")} FROM ${m}`;for(const E of p?i:i.slice(1)){const N=r.quoteIdentifier(E.alias);$+=` LEFT JOIN ${N}`,$+=p?` ON ${m}.${r.quoteIdentifier("_id")} = ${N}.${r.quoteIdentifier("_id")}`:" ON 1 = 1"}if(!!(e.having&&Object.keys(e.having).length>0||d.length>0||e.pagination||e.groupLimit)){const E={schemaId:e.schemaId,source:rt({kind:"sql",sql:$}),sourceAlias:"__sdb_cte_result",fields:Object.fromEntries(h.map(I=>[I,I])),projections:h.map(I=>({name:I,expression:{kind:"column",property:I,column:I}})),groupBy:[],...e.having&&Object.keys(e.having).length>0?{query:e.having}:{},orderBy:d.map(({name:I,direction:S,comparable:D})=>({name:I,direction:S,...D?{comparable:D}:{}})),...e.pagination?{pagination:e.pagination}:{},...e.groupLimit?{groupLimit:e.groupLimit}:{},rowIdentity:{kind:"generated"}},N=Oe(E,r,n,o);return{sql:`WITH ${s.join(", ")} ${N.sql}`,parameters:[...i.flatMap(({compiled:I})=>I.parameters),...N.parameters]}}return{sql:`WITH ${s.join(", ")} ${$}`,parameters:i.flatMap(({compiled:E})=>E.parameters)}},to=(t,e,r,n,o,i)=>{const s=[];let a=0;for(const S of e){const D=Oe(S.plan,o,i,a);a+=D.parameters.length,s.push({input:S,sql:D,alias:em(S.name)})}const u=s.map(({sql:S,alias:D})=>`${o.quoteIdentifier(D)} AS (${S.sql})`),c=s.flatMap(({sql:S})=>S.parameters),d=s[0],p=t.components.filter(S=>"literal"in S);if(!d&&p.length===0)throw new Error("CTE calculation requires a current component");const f=r.groupBy.map(({name:S})=>S);let m=d?o.quoteIdentifier(d.alias):"";if(!d&&f.length>0){const S=b=>{const T={...b,projections:b.groupBy,orderBy:[]};return delete T.having,delete T.pagination,delete T.groupLimit,b.subplans&&(T.subplans=b.subplans.map(S)),T},D=Oe(S(r),o,i,a);a+=D.parameters.length,c.push(...D.parameters),m=o.quoteIdentifier("__sdb_component_groups"),u.push(`${m} AS (${D.sql})`)}const h=o.quoteIdentifier("__sdb_component_literals");if(p.length>0){const S=p.map(b=>{const T=o.parameter(a++,b.literal);return c.push(b.literal),`(${T} * 1.0E0) AS ${o.quoteIdentifier(b.name)}`}),D=o.kind==="oracle"||o.kind==="dameng"?" FROM DUAL":"";u.push(`${h} AS (SELECT ${S.join(", ")}${D})`),m||(m=h)}const y=f.map(S=>`${m}.${o.quoteIdentifier(S)} AS ${o.quoteIdentifier(S)}`);let $="";for(const S of s.slice(1)){const D=o.quoteIdentifier(S.alias),b=S.input.plan.groupBy.map(({name:Y})=>Y),M=(S.input.joinKeys??f.filter(Y=>b.includes(Y))).map(Y=>{const C=tm(S.input.groupKeyShifts,Y),O=C?o.dateShift(`${D}.${o.quoteIdentifier(Y)}`,C.granularity,C.offset):`${D}.${o.quoteIdentifier(Y)}`;return`${m}.${o.quoteIdentifier(Y)} = ${O}`});$+=` LEFT JOIN ${D} ON ${M.length>0?M.join(" AND "):"1 = 1"}`}p.length>0&&m!==h&&($+=` CROSS JOIN ${h}`);const w=Object.fromEntries(s.map(({input:S,alias:D})=>[S.name,`${o.quoteIdentifier(D)}.${o.quoteIdentifier(hc(S.plan))}`]));for(const S of p)w[S.name]=`${h}.${o.quoteIdentifier(S.name)}`;const E=Zf(t.expression,w),N=[...y,...r.rowIdentity.kind==="group"?[`${m}.${o.quoteIdentifier("_id")} AS ${o.quoteIdentifier("_id")}`]:[],...s.map(({input:S,alias:D})=>`${`${o.quoteIdentifier(D)}.${o.quoteIdentifier(hc(S.plan))}`} AS ${o.quoteIdentifier(S.name)}`),...p.map(S=>`${w[S.name]} AS ${o.quoteIdentifier(S.name)}`),`${E} AS ${o.quoteIdentifier(n)}`].join(", ");let I=`WITH ${u.join(", ")} SELECT ${N} FROM ${m}`;return I+=$,{sql:I,parameters:c}},nm=t=>{if(typeof t!="string"||!/\bSELECT\b/i.test(t))return t;try{let e=t;const r=gc(t).length*2+2;for(let n=0;n<r;n+=1){const o=om(e);if(o===e)return e;e=o}return e}catch{return t}},om=t=>{const e=gc(t),r=im(t,e);if(r!==t)return r;const n=[];for(const i of e){const s=wc(t,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?$m(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()==="*")||Em(t,i))continue;const u=wm(sm(t.slice(i.fromStart,i.close),i,e)),c=am(t,i),d=cm(t,i);if(d&&um(c,d))continue;let p=s.filter(y=>{const $=Ac(y);if(!$||$==="_id")return!0;const w=new RegExp(`(^|[^\\w$])${Ui($)}([^\\w$]|$)`,"i");return w.test(u)||w.test(c)}),f=!0;for(;f;){f=!1;const y=Ic(p.join(" ")),$=s.filter(w=>{if(p.includes(w))return!1;const E=Ac(w);return E?new RegExp(`(^|[^\\w$])${Ui(E)}([^\\w$]|$)`,"i").test(y):!1});$.length>0&&(p=s.filter(w=>p.includes(w)||$.includes(w)),f=!0)}if(p.length===s.length)continue;const m=t.slice(i.selectEnd,i.fromStart),h=p.length===0&&Am(t,i)&&!/(^|[^\w$])\*([^\w$]|$)/.test(c)&&!/^\s*(?:DISTINCT|ALL|TOP|SQL_)\b/i.test(m)&&!/\b(?:UNION|INTERSECT|EXCEPT)\b/i.test(u);p.length===0&&!h||n.push({start:i.selectEnd,end:i.fromStart,value:m.match(/^\s*/)[0]+(h?"1":p.map(y=>y.trim()).join(", "))+m.match(/\s*$/)[0]})}n.sort((i,s)=>s.start-i.start);let o=t;for(const i of n)o=o.slice(0,i.start)+i.value+o.slice(i.end);return o},im=(t,e)=>{const r=/^\s*SELECT\b/i.exec(t);if(!r)return t;const n=r.index+r[0].length,o=ki(t,"FROM",n);if(o===-1||!wc(t,n,o)?.every(gm))return t;const s=e.find(f=>f.open>o&&t.slice(o+4,f.open).trim().length===0);if(!s||!/^\s*1\s*$/.test(t.slice(s.selectEnd,s.fromStart)))return t;const a=e.filter(f=>f.open>s.fromStart&&f.close<s.close).sort((f,m)=>m.close-m.open-(f.close-f.open))[0];if(!a||t.slice(s.fromStart+4,a.open).trim().length>0)return t;const u=t.slice(a.close+1,s.close);if(/\b(?:GROUP|HAVING|ORDER|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT)\b/i.test(u))return t;const c=ym.exec(u)?.[1],d=hm.exec(t.slice(s.close+1));if(!c||!d||$c(c)!==$c(d[1]))return t;const p=/;(\s*)$/.exec(t)?.[0]??"";return t.slice(0,s.open)+t.slice(a.open,s.close)+p},sm=(t,e,r)=>dm(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}))),am=(t,e)=>{const r=t.slice(0,e.open)+" ".repeat(e.close-e.open+1)+t.slice(e.close+1);return Ic(r)},cm=(t,e)=>t.slice(e.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${Nt})(?=\\s|$)`,"i"))?.[1]??null,um=(t,e)=>new RegExp(`(^|[^\\w$])${Ui(e)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(t),dm=(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("")},ki=(t,e,r)=>{let n=0,o=0,i="",s="";for(let a=r;a<t.length;a+=1){const u=t[a],c=t[a+1];if(s==="--"){u===`
|
|
3
|
+
`&&(s="");continue}if(s==="/*"){u==="*"&&c==="/"&&(s="",a+=1);continue}if(i){u===i&&t[a-1]!=="\\"&&(i="");continue}if(u==="-"&&c==="-"){s="--",a+=1;continue}if(u==="/"&&c==="*"){s="/*",a+=1;continue}if(u==="`"||u==='"'||u==="'"){i=u;continue}if(u==="("){n+=1;continue}if(u===")"){n-=1;continue}if(u==="["){o+=1;continue}if(u==="]"){o-=1;continue}if(n===0&&o===0&&new RegExp(`^${e}\\b`,"i").test(t.slice(a)))return a}return-1},gc=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===`
|
|
4
|
+
`&&(o="");continue}if(o==="/*"){s==="*"&&a==="/"&&(o="",i+=1);continue}if(n){s===n&&t[i-1]!=="\\"&&(n="");continue}if(s==="-"&&a==="-"){o="--",i+=1;continue}if(s==="/"&&a==="*"){o="/*",i+=1;continue}if(s==="`"||s==='"'||s==="'"){n=s;continue}if(s==="("){r.push({open:i});continue}if(s!==")")continue;const u=r.pop();if(!u)continue;const c=t.slice(u.open+1,i),d=/^\s*SELECT\b/i.exec(c);if(!d)continue;const p=u.open+1+d[0].length,f=ki(t,"FROM",p);f===-1||f>=i||e.push({open:u.open,close:i,selectEnd:p,fromStart:f})}return e},wc=(t,e,r)=>{const n=t.slice(e,r),o=[];let i=0,s=0,a=0,u="";for(let c=0;c<n.length;c+=1){const d=n[c];if(u){d===u&&n[c-1]!=="\\"&&(u="");continue}if(d==="`"||d==='"'||d==="'"){u=d;continue}d==="("?s+=1:d===")"?s-=1:d==="["?a+=1:d==="]"?a-=1:d===","&&s===0&&a===0&&(o.push(n.slice(i,c)),i=c+1)}return u||s!==0||a!==0?null:(o.push(n.slice(i)),o)},Ac=t=>t.trim().match(/\bAS\s+(`[^`]+`|"[^"]+"|[A-Za-z_][\w$]*)\s*$/i)?.[1]?.replace(/^`|`$/g,"").replace(/^"|"$/g,"")??null,Nt='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',pm=new RegExp(`\\s+AS\\s+${Nt}\\s*$`,"i"),lm=new RegExp(`\\bAS\\s+${Nt}`,"gi"),fm=new RegExp(`(?:${Nt}\\s*\\.\\s*)+${Nt}`,"g"),mm=new RegExp(`^${Nt}(?:\\s*\\.\\s*${Nt})*$`),ym=new RegExp(`^\\s*(?:AS\\s+)?(${Nt})\\s+WHERE\\b`,"i"),hm=new RegExp(`^\\s*(?:AS\\s+)?(${Nt})\\s*;?\\s*$`,"i"),$c=t=>t.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),gm=t=>{const e=t.replace(pm,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(e)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(e)},Ec=(t,e)=>t.replace(e,r=>" ".repeat(r.length)),Ic=t=>Ec(t,lm),wm=t=>Ec(t,fm),Am=(t,e)=>/\b(?:FROM|JOIN)\s*$/i.test(t.slice(0,e.open)),$m=t=>{const e=t.trim();return mm.test(e)?e:null},Em=(t,e)=>{const r=t.slice(e.selectEnd,e.close);return["UNION","INTERSECT","EXCEPT"].some(n=>ki(r,n,0)!==-1)},Ui=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ro=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),no=(t,e,r="_",n="\u7A7A\u503C")=>e.map(o=>t[o]===null||t[o]===void 0?n:ro(t[o])).join(r),oo=(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?no(r,e.names,e.separator,e.nullLabel):ro(r._id)}:{...r,_id:e.kind==="singleton"?"0":Br()}}),mt=t=>!("literal"in t),qi=t=>{const e=ge(t);return delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,delete e.sample,e},un=(t,e)=>e.isComponent(t)?!0:!!t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&un(t.pred,e)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&un(r,e)),Im=(t,e,r,n,o,i,s="zh-CN",a=Ln.translator(s))=>{const u=t.preds??[],c=u.map((m,h)=>({pred:m,index:h,definition:m.operator?n.get(m.operator):void 0})).filter(({pred:m,definition:h})=>n.isComponent(m)&&!h?.skipComponentExecution?.({plan:e,executionContext:n.executionContext}));if(c.length===0&&e.sourcePlan||c.length===0)return;for(const m of u)if(!n.isComponent(m)&&(m.pred&&typeof m.pred=="object"&&!Array.isArray(m.pred)&&un(m.pred,n)||Array.isArray(m.pred)&&m.pred.some(h=>typeof h!="string"&&un(h,n))))throw new l("UNSUPPORTED_COMPONENT_NESTING","A component operator must currently be the top-level projection operator");const d=[],p=u.filter((m,h)=>!c.some(y=>y.index===h));if(p.length>0){const m=qi(t);m.preds=p,d.push({kind:"query",logicform:m})}const f=t.groupby?.length??0;for(const{pred:m,index:h,definition:y}of c){const $=y?.kind==="scalar"?y.createQueryComponent:y?.createComponent;if(!$)continue;const w=e.projections[f+h]?.name;if(!w)throw new l("INVALID_COMPONENT_PLAN","Component output projection is missing");const E=i?.preds?.[h],N=$({dayjs:he,moment:he,executionContext:n.executionContext,logicform:qi(t),pred:E??m,outputName:w,locale:s,t:a,schema:r,resolveSchema:o,...i?{sourceLogicform:qi(i)}:{}});if("components"in N){const I=new Set;for(const S of N.components){if(!S.name||I.has(S.name))throw new l("INVALID_OPERATOR_COMPONENTS","Component names must be nonempty and unique");if(I.add(S.name),!mt(S)&&(typeof S.literal!="number"||!Number.isFinite(S.literal)||"logicform"in S))throw new l("INVALID_COMPONENT_LITERAL",`Component ${S.name} literal must be a finite number and cannot include a logicform`)}}if("logicform"in N&&(N.logicform.preds??[]).some(I=>un(I,n)))throw new l("UNSUPPORTED_COMPONENT_NESTING","Nested component operators are not supported yet");d.push({...N,outputName:w})}return d},yt=t=>t instanceof Date?t.getTime():t,_m=(t,e,r,n)=>{const o=yt(t),i=yt(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=>yt(s)===o);case"$nin":return Array.isArray(r)&&r.every(s=>yt(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 l("UNSUPPORTED_QUERY_OPERATOR",`Unsupported having operator: ${e}`)}},ji=(t,e)=>{if(!e||typeof e!="object"||Array.isArray(e))return yt(t)===yt(e);const r=Object.entries(e),n=e.args,o=n&&typeof n=="object"&&!Array.isArray(n)?n.options:void 0;return r.every(([i,s])=>{if(i==="args")return!0;if(i==="$and"||i==="$or"){if(!Array.isArray(s))return!1;const a=s.map(u=>ji(t,u));return i==="$and"?a.every(Boolean):a.some(Boolean)}return i==="$length"?typeof t=="string"&&ji(t.length,s):_m(t,i,s,typeof o=="string"?o:void 0)})},_c=(t,e)=>Object.entries(e).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>_c(t,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return ji(t[r],n)}),bm=(t,e)=>e.length===0?"0":t._id===void 0?no(t,e):ro(t._id),bc=(t,e)=>{const r=new Map;for(const n of t)for(const o of n){const i=bm(o,e);r.set(i,{...r.get(i)??{},...o})}return[...r.values()]},Sc=(t,e,r)=>{const n=bc(t,e),o=Object.fromEntries(r.components.filter(i=>!mt(i)).map(i=>[i.name,i.literal]));return t.length===0&&e.length===0&&Object.keys(o).length>0&&n.push({}),n.map(i=>({...i,...o}))},dn=(t,e)=>{const r=e.groupBy.map(({name:o})=>o);let n=bc(t,r);if(e.having&&(n=n.filter(o=>_c(o,e.having))),e.groupLimit){const o=e.groupLimit,i=new Map;for(const s of n){const a=no(s,o.partitionBy);i.set(a,[...i.get(a)??[],s])}n=[...i.values()].flatMap(s=>s.sort((a,u)=>{for(const c of o.orderBy){const d=yt(a[c.name]),p=yt(u[c.name]);if(d!==p)return d==null?c.direction==="ASC"?-1:1:p==null?c.direction==="ASC"?1:-1:(d<p?-1:1)*(c.direction==="ASC"?1:-1)}return 0}).slice(0,o.count))}if(e.orderBy.length>0&&n.sort((o,i)=>{for(const s of e.orderBy){const a=yt(o[s.name]),u=yt(i[s.name]);if(a!==u)return a==null?s.direction==="ASC"?-1:1:u==null?s.direction==="ASC"?1:-1:(a<u?-1:1)*(s.direction==="ASC"?1:-1)}return 0}),e.pagination?.kind==="rows"){const o=(e.pagination.page-1)*e.pagination.pageSize;n=n.slice(o,o+e.pagination.pageSize)}else if(e.pagination?.kind==="ratio"){const o=Math.ceil(n.length*e.pagination.ratio),i=(e.pagination.page-1)*o;n=n.slice(i,i+o)}return n},Sm=t=>{const e=new WeakMap,r=new WeakMap,n=new WeakMap,o=(a,u,c,d)=>(e.has(u)||e.set(u,t.createUnits(a,u,c,d)),e.get(u)),i=a=>{let u=r.get(a.logicform);return u||(u=(async()=>{const c=await t.prepareQuery(a);return{...c,plan:await s(c.logicform,c.plan,c.schema,a.logicform)}})(),r.set(a.logicform,u)),u},s=(a,u,c,d)=>{const p=n.get(u);if(p)return p;const f=(async()=>{let m=u;if(m.sourcePlan&&m.sourceLogicform){const w=await s(m.sourceLogicform,m.sourcePlan,t.resolveSchema(m.sourceLogicform));w!==m.sourcePlan&&(m=t.replanSource(a,c,m.sourceLogicform,w))}const h=o(a,m,c,d);if(!h)return m;await t.prepareUnits(h);const y=new Map;for(const w of h){if("logicform"in w){if(!w.outputName)continue;const N=await i(w),I=new Set(N.plan.groupBy.map(({name:D})=>D)),S=(N.plan.columnProperties??[]).filter(({name:D})=>!I.has(D));if(S.length===0)throw new l("INVALID_COMPONENT_PLAN",`Component ${w.outputName} has no metric property`);y.set(w.outputName,{componentProperties:S.length===1?S[0]?.componentProperties??S:S});continue}const E=await Promise.all(w.components.map(async N=>{if(!mt(N))return{name:N.name,type:"number",primal_type:"number",isArray:!1};const I=await i({kind:"query",logicform:N.logicform,...N.prepare!==void 0?{prepare:N.prepare}:{}}),S=I.plan.projections[I.plan.groupBy.length],D=I.plan.columnProperties?.find(({name:b})=>b===S?.name);if(!D)throw new l("INVALID_COMPONENT_PLAN",`Component ${N.name} has no metric property`);return{...D,name:N.name}}));y.set(w.outputName,{componentProperties:E,..."expression"in w?{formulaText:w.expression}:{}})}if(y.size===0)return m;const $={...m,columnProperties:m.columnProperties?.map(w=>{const E=y.get(w.name);return E?{...w,...E}:w})??[]};return e.set($,h),$})();return n.set(u,f),f};return{getUnits:o,prepareQuery:i,resolvePlan:s}},Nc=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new l("SCHEMA_RESOLVER_REQUIRED",`Cannot normalize nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n},Nm=/^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Rm=t=>{if(typeof t!="string")return!1;const e=Nm.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},xi=t=>{if(!Rm(t.version))throw new l("UNSUPPORTED_LOGICFORM_VERSION",`This library only supports LogicForm version 2.0 or later; received ${JSON.stringify(t.version)}`,{minimumVersion:"2.0",receivedVersion:t.version})},Rc=(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)&&Rc(o,e))),Oc=(t,e,r,n=[])=>{if(e===void 0||e==="placeholder")return t;if(!zt(e))throw new l("INVALID_ENTITY_ID","entity_id must be a non-empty string or a safe integer");const o=Fn(r,n);return t&&Rc(t,new Set([o.name,o.id]))?t:{[o.name]:e,...t??{}}},Pr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Om={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},Tc={$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"}},Lr=(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=>Lr(n,e)).join(e?", ":"\u3001");if(!Pr(t))return e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6";if(Array.isArray(t.roots))return t.roots.map(n=>Lr(n,e)).join(e?", ":"\u3001");if(t.root!==void 0)return Lr(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])}${Om[n]??""}`);return r.length>0?r.join(e?", ":""):e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6"},io=(t,e,r)=>t.filter(Boolean).join(r?e==="$and"?" and ":" or ":e==="$and"?"\u4E14":"\u6216"),Pc=(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}`},pn=(t,e,r)=>{if(!Pr(e)||Object.keys(e).every(o=>!o.startsWith("$")))return Pc("$eq",t,Lr(e,r),r)??"";const n=[];for(const[o,i]of Object.entries(e))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(io(i.map(s=>pn(t,s,r)),o,r));else if(o==="$exists")n.push(r?`${t} ${i?"exists":"does not exist"}`:`${i?"\u6709":"\u65E0"}${t}`);else if(Tc[o]){const s=Tc[o];n.push(pn(r?`${t} ${s.en}`:`${t}\u7684${s.zh}`,i,r))}else if(o==="$length")n.push(pn(r?`${t} length`:`${t}\u957F\u5EA6`,i,r));else if(o!=="args"){const s=o==="$regex"&&Pr(i)?Lr(i.pattern,r):Lr(i,r),a=Pc(o,t,s,r);a&&n.push(a)}return io(n,"$and",r)},Lc=(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(io(i.map(s=>Pr(s)?Lc(s,e):""),o,r));else if(o==="$expr"&&Pr(i)){const s=i.pred,a=Pr(s)&&typeof s.name=="string"?s.name:r?"expression":"\u8868\u8FBE\u5F0F";i.condition!==void 0&&n.push(pn(a,i.condition,r))}else i!==void 0&&n.push(pn(o,i,r));return io(n,"$and",r)},Cr=(t,e,r={})=>{if(t.name!==void 0){if(typeof t.name!="string"||t.name.length===0)throw new l("INVALID_PRED_NAME","PredItem name must be a non-empty string");return t.name}const n=r.locale??"zh-CN",o=r.localeRegistry??Ln,i=o.resolve(n).locale.toLowerCase().startsWith("en"),s=o.translator(n),a=Array.isArray(t.pred)?t.pred.map(m=>typeof m=="string"?m:Cr(m,e,r)):[],u=typeof t.pred=="string"?t.pred:t.pred&&!Array.isArray(t.pred)?Cr(t.pred,e,r):void 0,c=u??(a.length>0?a.join(i?", ":"\u3001"):s("operator.rows",i?"rows":"\u6570\u636E\u884C")),d=t.args??{},p=t.operator?(()=>{const m=e.get(t.operator),h={executionContext:e.executionContext,operandName:c,...u?{inputName:u}:{},inputNames:a,args:d,locale:n,t:s},y=m.defaultName(h);if(typeof y!="string"||y.length===0)throw new l("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});const $=typeof d.granularity=="string"?s(`time.granularity.${d.granularity}`,d.granularity):s("time.granularity.period","\u5468\u671F"),w=i?t.operator==="$concat"?" and ":t.operator==="$multiply"?" times ":" plus ":t.operator==="$concat"?"\u4E0E":t.operator==="$multiply"?"\u4E58\u4EE5":"\u52A0";if(m.defaultNameIsLocalized)return y;const E=typeof m.defaultNameKey=="function"?m.defaultNameKey(h):m.defaultNameKey??`operator.${t.operator}`;return s(E,y,{...d,operandName:c,inputName:u??"",inputNames:a.join(w),input0:a[0]??"",input1:a[1]??"",granularity:$})})():c;if(typeof p!="string"||p.length===0)throw new l("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});if(!t.query)return p;const f=Lc(t.query,n);return f?i?`${p} where ${f}`:`${f}\u7684${p}`:p},Tm=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},Pm=t=>{if(t.args===void 0||Object.keys(t.args).length>0)return t;const{args:e,...r}=t;return r},Lm=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 l("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}}},ln=async(t,e,r,n)=>{if("components"in t)throw new l("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 l("INVALID_PRED_NAME","PredItem name must be a non-empty string");if(t.name==="_id")throw new l("RESERVED_OUTPUT_NAME","PredItem name _id is reserved for executor-owned row identity");if(t.args!==void 0&&!Tm(t.args))throw new l("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 l("SCHEMA_RESOLVER_REQUIRED",`Cross-Schema pred requires Schema ${t.schema}`);const a=await n(t.query,s,r),u=Array.isArray(t.pred)?await Promise.all(t.pred.map(m=>ln(typeof m=="string"?{pred:m}:m,s,r,n))):void 0,{query:c,...d}=t,p={...d,...a?{query:a}:{},...u?{pred:u}:{}},f=async m=>{const h=await Lm(m,s,r),y=h.operator?o.get(h.operator).normalizePred?.({pred:h,schema:s,executionContext:o.executionContext})??h:h;return Pm(y)};if(typeof t.pred=="string"){const m=ne(s,t.pred,r.resolveSchema),h={...p,pred:m.canonicalName};return f({...h,name:h.name??Cr(h,o,i)})}if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)){const m={...p,pred:await ln(t.pred,s,r,n)};return f({...m,name:m.name??Cr(m,o,i)})}if(u)return f({...p,name:p.name??Cr(p,o,i)});if(t.pred!==void 0)throw new l("UNSUPPORTED_PRED","A pred must be a property name or nested pred");return f({...p,name:p.name??Cr(p,o,i)})},Cm=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),Dm=t=>{if(!Re(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.sample!==void 0&&e.sample!==!1||e.limit!==void 0||e.limitBy!==void 0||e.page!==void 0},so=async(t,e)=>{if(Re(t)){if(!e.normalizeNestedLogicform)throw new l("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");return e.normalizeNestedLogicform(t)}return Array.isArray(t)?Promise.all(t.map(r=>so(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 so(n,e)])))},Cc=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>Cc(o,e))]:[`${e}_${r}`,n])),Vi=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},Dc=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),Fi=new Set([...Dc,"$length"]),ao=t=>Array.isArray(t)?t.some(ao):typeof t!="object"||t===null||Re(t)?!1:Object.entries(t).some(([e,r])=>Fi.has(e)||ao(r)),Mc=(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 l("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}if(typeof t=="object"&&t!==null&&!Re(t)){for(const[r,n]of Object.entries(t)){if(!r.startsWith("$"))throw new l("INVALID_QUERY_VALUE",`${e} requires numeric conditions`);if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new l("INVALID_QUERY_VALUE",`${r} requires an array`);n.forEach(o=>Mc(o,e))}else if(r==="$in"||r==="$nin"){if(!Array.isArray(n)||n.some(o=>typeof o!="number"||!Number.isFinite(o)))throw new l("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}else if(typeof n!="number"||!Number.isFinite(n))throw new l("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}return}throw new l("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}},co=(t,e)=>{if(t.schema!==void 0)throw new l("EXPRESSION_QUERY_SCHEMA_NOT_ALLOWED","$expr.pred is scoped to the query Schema and cannot define schema");if(t.query)throw new l("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");if(e.operators.get(t.operator).kind!=="scalar")throw new l("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)&&co(t.pred,e);for(const r of Array.isArray(t.pred)?t.pred:[])typeof r!="string"&&co(r,e)},kc=async(t,e,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new l("INVALID_EXPRESSION_QUERY","$expr must be an object");const n=t,o=Object.keys(n).filter(u=>u!=="pred"&&u!=="condition");if(o.length>0||!Object.prototype.hasOwnProperty.call(n,"condition"))throw new l("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 l("INVALID_EXPRESSION_QUERY","$expr.pred must be a pred expression");const i=n.pred;if(!i.operator)throw new l("EXPRESSION_QUERY_OPERATOR_REQUIRED","$expr.pred must define a scalar operator");if(!r.operators)throw new Error("Normalizer operator registry is not initialized");co(i,r);const s=await ln(i,e,r,()=>Promise.resolve(void 0));co(s,r);const a=Vi(await so(n.condition,r));return Fi.has(s.operator)&&Mc(a,s.operator),{pred:s,condition:a}},Uc=async(t,e,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||Re(e))return{[t]:e};const o={},i=[];for(const[s,a]of Object.entries(e))Fi.has(s)?i.push({$expr:await kc({pred:{operator:s,pred:t},condition:a},r,n)}):(s==="$and"||s==="$or")&&Array.isArray(a)&&a.some(ao)?i.push({[s]:await Promise.all(a.map(u=>Uc(t,u,r,n)))}):o[s]=a;return Object.keys(o).length>0&&i.unshift({[t]:Vi(o)}),i.length===1?i[0]??{}:{$and:i}},Bi=t=>Array.isArray(t)?t.some(Bi):typeof t!="object"||t===null||Re(t)?!1:Object.entries(t).some(([e,r])=>Dc.has(e)||Bi(r)),qc=async(t,e,r,n,o)=>{const i=d=>{if(Array.isArray(d)){d.forEach(i);return}if(typeof d!="object"||d===null||Re(d))return;const p=d;if("$options"in p)throw new l("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");Object.values(p).forEach(i)};if(i(t),r.primal_type!=="date"&&Bi(t))throw new l("INVALID_DATE_PART_QUERY",`Date-part query Operators require a date Property: ${r.name}`,{property:r.name});const s=n.semanticTypes.get(r.type),a={schema:e,property:r,now:n.now??new Date,...o?{onDateQueryNormalized:o}:{},requestTimeWatermark:d=>n.requestTimeWatermark?.(e,r,d)??Promise.resolve(void 0)},u=await ol(ge(t),a),c=s.normalizeQuery?s.normalizeQuery(u,a):u;if(r.comparable){const d=new Set(r.comparable.values),p=(f,m)=>{if(!(Re(f)||f===null)){if(Array.isArray(f)){f.forEach(h=>p(h,m));return}if(typeof f=="object"){Object.entries(f).forEach(([h,y])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(h)||p(y,h)});return}if(!(m&&["$exists","$regex","$contains","$startsWith","$length"].includes(m))&&(typeof f!="string"||!d.has(f)))throw new l("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${r.name} does not contain value: ${JSON.stringify(f)}`,{property:r.name,value:f})}};p(c)}return c},Hi=async(t,e,r,n,o=["query"])=>{const i={},s=[],a=[],u=c=>{const d=Object.entries(c);if(d.length===1&&d[0]?.[0]==="$and"&&Array.isArray(d[0][1]))for(const p of d[0][1])u(p);else d.length===1&&d[0]?.[0]==="$expr"?s.push(c):d.every(([p])=>!p.startsWith("$"))?Object.assign(i,c):a.push(c)};for(const[c,d]of Object.entries(t)){if(c==="$and"||c==="$or"){if(!Array.isArray(d))throw new l("INVALID_QUERY_VALUE",`${c} requires an array`);i[c]=await Promise.all(d.map(async($,w)=>{if(typeof $!="object"||$===null||Array.isArray($))throw new l("INVALID_QUERY_VALUE",`${c} items must be query objects`);return Hi($,e,r,n,[...o,c,w])}));continue}if(c==="$expr"){n?.invalidate(),s.push({$expr:await kc(d,e,r)});continue}const p=ne(e,c,r.resolveSchema),f=p.relations.length===0?n?.observe(p.schema,p.property,[...o,c],r.semanticTypes.get(p.property.type).normalizeQuery!==void 0):void 0;if(Dm(d)&&!zt(d.entity_id)&&(p.property.primal_type==="entity"||p.property.primal_type==="object")&&p.property.ref){if(!r.normalizeNestedLogicform)throw new l("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");const $=await r.normalizeNestedLogicform(d);i[p.canonicalName]={$in:$};continue}if(Cm(d)){if(d.version!==void 0&&xi(d),p.property.primal_type!=="entity"&&p.property.primal_type!=="object")throw new l("INVALID_RELATION_QUERY",`Relation query ${c} must resolve to an entity property`);if(!p.property.ref)throw new l("INVALID_RELATION_QUERY",`Nested LogicForm query requires an object property: ${p.canonicalName}`);if(d.schema!==p.property.ref)throw new l("RELATION_SCHEMA_MISMATCH",`Relation ${p.canonicalName} references ${p.property.ref}, not ${d.schema}`);const $=r.resolveSchema?.(d.schema);if(!$)throw new l("SCHEMA_RESOLVER_REQUIRED",`Nested relation query requires Schema ${d.schema}`);const w=Oc(zt(d.entity_id)?void 0:d.query,d.entity_id,$,r.plugins),E=await Hi(w,$,r);Object.assign(i,Cc(E,p.canonicalName));continue}if(typeof d=="object"&&d!==null&&!Array.isArray(d)){const $=d,w=Object.entries($).filter(([E])=>gr(E,r.plugins));if(w.length>0){const[E]=w,N=E?gr(E[0],r.plugins):void 0;if(N?.validateCondition?.($),!E||w.length!==1||Object.keys($).length!==1)throw new l("INVALID_PLUGIN_QUERY","A plugin Query Operator cannot be combined with other field operators");const[I,S]=E;if(!N)throw new Error(`Query Operator disappeared: ${I}`);i[p.canonicalName]={[I]:await N.normalize(S,{schema:p.schema,property:p.property,...r.resolveSchema?{resolveSchema:r.resolveSchema}:{},normalizeValue:(D,b,T)=>qc(D,b,T,r)})};continue}}const m=await so(d,r),h=await qc(m,p.schema,p.property,r,f),y=Vi(h);if(ao(y)){u(await Uc(p.canonicalName,y,e,r));continue}i[p.canonicalName]=y}if(a.length>0){const c=Array.isArray(i.$and)?i.$and:[];i.$and=[...c,...a]}if(s.length===1)i.$expr=s[0]?.$expr;else if(s.length>1){const c=Array.isArray(i.$and)?i.$and:[];i.$and=[...c,...s]}return i},jc=async(t,e,r,n)=>{if(!t)return;const o=await Hi(t,e,r,n);return Object.keys(o).length===0?void 0:o},xc=(t,e,r)=>Promise.all((t??[]).map(n=>ln(n,e,r,jc))),Mm=(t,e,r)=>xc(t??[],e,r),Dr=(t,e)=>{throw new l("INVALID_PAGINATION",t,e)},km=t=>{"skip"in t&&Dr("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)&&Dr("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&&Dr("page requires limit",{page:n});return}if((!Number.isFinite(r)||r<0&&r!==-1||r>1&&!Number.isInteger(r))&&Dr("limit must be -1, a non-negative integer, or a ratio between 0 and 1",{limit:r}),r===-1){n!==void 0&&Dr("page cannot be used with unlimited results",{limit:r,page:n}),delete t.limit;return}n!==void 0&&(!Number.isInteger(n)||n<1)&&Dr("page must be a positive integer starting from 1",{page:n}),t.page=n??1},Um=(t,e,r,n)=>{const o=[{schema:t,prefix:""}],i=new Set;for(let s=0;s<o.length;s+=1){const a=o[s];if(!a||i.has(a.schema.id))continue;i.add(a.schema.id);const c=a.schema.properties.find(d=>d.id===e)??a.schema.properties.find(d=>d.name===e)??(n==="timestamp"?a.schema.properties.find(d=>d.type==="timestamp"):void 0);if(c)return ne(t,`${a.prefix}${c.id}`,r).canonicalName;for(const d of a.schema.properties){if(!d.ref||d.primal_type!=="entity"&&d.primal_type!=="object")continue;const p=r?.(d.ref);p&&o.push({schema:p,prefix:`${a.prefix}${d.id}_`})}}},Vc=(t,e,r,n)=>{try{const o=ne(t,e,n);try{return ne(r,o.canonicalName,n).canonicalName}catch{}return Um(r,o.property.name,n,o.property.type)}catch{return}},Qi=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Qi(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Qi(e)):[]],Fc=t=>t?Object.entries(t).flatMap(([e,r])=>{if((e==="$and"||e==="$or")&&Array.isArray(r))return r.flatMap(n=>Fc(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)?Qi(n):[]}return e.startsWith("$")?[]:[e]}):[],qm=(t,e,r)=>{const n=[...new Set((t.preds??[]).map(s=>s.schema).filter(s=>!!(s&&s!==e.id)))];if(n.length===0)return t;const o={};for(const[s,a]of Object.entries(t.propertyResolve??{})){const u=r.resolveSchema?.(s),c={};for(const[d,p]of Object.entries(a)){let f=d;try{f=ne(e,d,r.resolveSchema).canonicalName}catch{}c[f]=p;try{u&&(c[f]=ne(u,p,r.resolveSchema).canonicalName)}catch{}}o[s]=c}const i=[...(t.groupby??[]).map(s=>s.pred),...Fc(t.query)];for(const s of i){if(typeof s!="string")continue;let a;try{a=ne(e,s,r.resolveSchema)}catch{continue}for(const u of n){if(o[u]?.[a.canonicalName]!==void 0)continue;const c=r.resolveSchema?.(u),d=c&&Vc(e,s,c,r.resolveSchema);d&&d!==a.canonicalName&&(o[u]={...o[u]??{},[a.canonicalName]:d})}}return Object.keys(o).length>0?{...t,propertyResolve:o}:t},Yi=t=>{if(typeof t=="string"&&he(t).isValid())return Object.freeze({start:t,end:t});if(typeof t!="object"||t===null||Array.isArray(t))return;const e=t;if(Object.keys(e).length===1&&"$eq"in e)return Yi(e.$eq);if(Object.keys(e).length!==2||typeof e.$gte!="string"||typeof e.$lte!="string")return;const r=he(e.$gte),n=he(e.$lte);if(!(!r.isValid()||!n.isValid()||n.isBefore(r)))return Object.freeze({start:e.$gte,end:e.$lte})};class jm{#e=[];#t=!1;invalidate(){this.#t=!0}observe(e,r,n,o){if(r.primal_type!=="date")return;const i=this.#e.length;if(this.#e.push(void 0),!(o||n.includes("$or")))return(s,a,u)=>{const c=Yi(s),d=Yi(a);!c||!d||(this.#e[i]=Object.freeze({schemaId:e.id,propertyId:r.id,queryPath:Object.freeze([...n]),requestedRange:c,effectiveRange:d,...u?{timeWatermark:Et(u)}:{}}))}}get result(){return!this.#t&&this.#e.length===1?this.#e[0]:void 0}}const xm=(t,e=!0)=>{if(t===void 0||t===!1)return t;if(t!==!0&&(typeof t!="object"||t===null||Array.isArray(t)))throw new l("INVALID_RANDOM_DATA","randomData must be a boolean or a factor configuration");if(!e)throw new l("INVALID_RANDOM_DATA","randomData is only supported on the top-level LogicForm");const r=t===!0?{}:t;if(Object.keys(r).some(i=>i!=="minFactor"&&i!=="maxFactor"))throw new l("INVALID_RANDOM_DATA","randomData only accepts minFactor and maxFactor");const n=r.minFactor===void 0?.1:r.minFactor,o=r.maxFactor===void 0?1.5:r.maxFactor;if(typeof n!="number"||!Number.isFinite(n)||n<0||typeof o!="number"||!Number.isFinite(o)||o<n)throw new l("INVALID_RANDOM_DATA","randomData requires finite factors with 0 <= minFactor <= maxFactor");return{minFactor:n,maxFactor:o}},Vm=t=>{if(t!==void 0){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("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 l("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 l("INVALID_PROPERTY_RESOLVE",`propertyResolve.${e}.${n} must be a non-empty string`)}}},Fm=async(t,e,r)=>{if(!t)return;const n=Nc(t,e,r);return Rt(t,n,{...r,allowSample:!1,allowRandomData:!1})},Rt=async(t,e,r)=>{r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:zr([...Pe(r.plugins).flatMap(N=>N.locales??[]),...r.locales===void 0?[]:"locale"in r.locales?[r.locales]:r.locales])},...r.operators?{}:{operators:at(r.plugins)}},xi(t);const o=xm(t.randomData,r.allowRandomData);if(Vm(t.propertyResolve),t.sample!==void 0&&typeof t.sample!="boolean")throw new l("INVALID_SAMPLE","sample must be a boolean");if(t.sample===!0){if(r.allowSample===!1)throw new l("INVALID_SAMPLE","sample is only supported on the top-level LogicForm");if(typeof t.limit!="number"||!Number.isSafeInteger(t.limit)||t.limit<0)throw new l("INVALID_SAMPLE","sample requires limit to be a non-negative safe integer");if(t.groupby?.length||t.limitBy!==void 0||t.from)throw new l("INVALID_SAMPLE","sample requires an ungrouped physical entity LogicForm without limitBy or from")}if(t.output&&t.output.type!=="data"&&t.output.type!=="sql"&&!kn(t.output.type,r.plugins))throw new l("UNSUPPORTED_OUTPUT",`Output type is not supported: ${t.output.type}`);const i=ge(t);o!==void 0&&(i.randomData=o);const{onTimeRangeResolved:s,...a}=r,u={...a,normalizeNestedLogicform:async N=>{const I=Nc(N,e,r);return Rt(N,I,{...a,allowSample:!1,allowRandomData:!1})}};km(i);const c=await Fm(i.from,e,u),d=c&&r.resolveFromSchema?await r.resolveFromSchema(c,e):e,p=s&&!c?new jm:void 0,f=await jc(Oc(i.query,i.entity_id,d,r.plugins),d,u,p);s?.(c?void 0:p?.result);const m=i.preds===void 0&&i.groupby===void 0?d.properties.filter(N=>r.canProjectProperty?.(d,N)??!0).map(N=>({pred:N.name,name:N.name})):i.preds,h={...u,...f?{autoCaseQuery:f}:{}};let y=await xc(m,d,h),$=await Mm(i.groupby,d,h);const w=$.filter(N=>Ia(N,$,d,r.resolveSchema));if(w.length>0){const N=new Set(w.map(({name:I})=>I));$=$.filter(({name:I})=>!N.has(I)),y=[...y,...w]}return i.preds=y,$.length>0?i.groupby=$:delete i.groupby,c?i.from=c:delete i.from,f?i.query=f:delete i.query,qm(i,d,u)},Vt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Bc=(t,e,r,n)=>{if(!(!t||r.length===0))for(const[o,i]of Object.entries(t)){if(!Vt(i)||o.startsWith("$"))continue;let s;try{s=ne(e,o,n)}catch{continue}const a=[...s.relations.map(({property:c})=>c),...s.property.ref&&(s.property.primal_type==="entity"||s.property.primal_type==="object")?[s.property]:[]];if(a.length===0||a.length>r.length||!a.every((c,d)=>c.id===r[d]?.property.id))continue;if(a.length===r.length)return i;const u=Bc(Vt(i.query)?i.query:void 0,s.property.ref?n(s.property.ref):s.schema,r.slice(a.length),n);if(u)return u}},Ft=(t,e)=>{if(t instanceof Date)return t;if(Re(t)&&t.schema&&e)try{return Mr(t,e(t.schema),e)}catch{return t}return Array.isArray(t)?t.map(r=>Ft(r,e)):Vt(t)?Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Ft(n,e)])):t},fn=(t,e,r,n)=>{if(!t)return;const o={};for(const[i,s]of Object.entries(t)){if(i==="$and"||i==="$or"){const a=n?.[i];o[i]=Array.isArray(s)?s.map((u,c)=>Vt(u)?fn(u,e,r,Array.isArray(a)&&Vt(a[c])?a[c]:void 0):Ft(u,r)):s;continue}if(i==="$expr"){o[i]=Ft(s,r);continue}if(!r){o[i]=Ft(s,r);continue}try{const a=ne(e,i,r);if(a.relations.length===0){if(a.property.ref&&(a.property.primal_type==="entity"||a.property.primal_type==="object")&&(typeof s=="string"||typeof s=="number")){const f=r(a.property.ref),m=f.properties.find(h=>h.type==="ID");if(m){o[a.property.name]={schema:f.id,entity_id:s,query:{[m.name]:s}};continue}}o[i]=Ft(s,r);continue}let u=o,c=o;const d=Bc(n,e,a.relations,r);for(const f of a.relations){const m=f.property.name,h=u[m];c=Vt(h)?h:{schema:f.targetSchema.id,query:{}},c.schema||(c.schema=f.targetSchema.id),Vt(c.query)||(c.query={}),u[m]=c,u=c.query}const p=a.property.name;if(u[p]=Ft(s,r),d&&zt(d.entity_id)&&(Object.assign(c,d),Vt(d.query))){const{[p]:f,...m}=u;c.query={...m,...fn(d.query,a.schema,r,d.query)}}}catch{o[i]=Ft(s,r)}}return o},uo=(t,e,r,n)=>{const o={...t};if(t.query){const i=fn(t.query,e,r,n?.query);i&&(o.query=i)}return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?o.pred=uo(t.pred,e,r,n?.pred&&typeof n.pred=="object"&&!Array.isArray(n.pred)?n.pred:void 0):Array.isArray(t.pred)&&(o.pred=t.pred.map((i,s)=>typeof i=="string"?i:uo(i,e,r,Array.isArray(n?.pred)&&typeof n.pred[s]!="string"?n.pred[s]:void 0))),o},Mr=(t,e,r,n)=>{const o={...t};if(t.query){const i=fn(t.query,e,r,n?.query);i&&(o.query=i)}if(t.preds&&(o.preds=t.preds.map((i,s)=>uo(i,e,r,n?.preds?.[s]))),t.groupby&&(o.groupby=t.groupby.map((i,s)=>uo(i,e,r,n?.groupby?.[s]))),t.having){const i=fn(t.having,e,r,void 0);i&&(o.having=i)}return t.from&&r&&t.from.schema&&(o.from=Mr(t.from,r(t.from.schema),r,n?.from)),o},Hc=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Ye=(t,e)=>{if(t){if(!Hc(t,e))throw new l("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},Ot=(t,e,r)=>{const n=Ye(t,e)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},mn=(t,e,r)=>{if(!Ot(t,e.id,r))throw new l("COLUMN_PERMISSION_DENIED",`Property is not included in the column permissions: ${e.id}.${r.name}`,{schemaId:e.id,property:r.name,propertyId:r.id})},vi=(t,e,r,n)=>{const o=ne(e,t,n);for(const i of o.relations)Ye(r,i.targetSchema.id),mn(r,i.sourceSchema,i.property);mn(r,o.schema,o.property)},Qc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),po=(t,e,r,n,o)=>{if(Re(t)){sr(t,e,r,n,o);return}if(Array.isArray(t)){for(const i of t)po(i,e,r,n,o);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const i of Object.values(t))po(i,e,r,n,o)};function yn(t,e,r,n,o,i){const s=t.schema?n(t.schema):e;t.schema&&Ye(r,t.schema),typeof t.pred=="string"?vi(t.pred,s,r,n):t.pred&&!Array.isArray(t.pred)&&yn(t.pred,s,r,n,o,i);for(const a of Array.isArray(t.pred)?t.pred:[])typeof a=="string"?vi(a,s,r,n):yn(a,s,r,n,o,i);lo(t.query,s,r,n,o,i)}const lo=(t,e,r,n,o,i)=>{if(!(!t||i?.get(e.id)?.has(JSON.stringify(t))))for(const[s,a]of Object.entries(t)){if(s==="$and"||s==="$or"){if(Array.isArray(a))for(const c of a)lo(c,e,r,n,o,i);continue}if(s==="$expr"){if(typeof a=="object"&&a!==null&&!Array.isArray(a)){const c=a.pred;typeof c=="object"&&c!==null&&!Array.isArray(c)&&yn(c,e,r,n,o,i),po(a.condition,r,n,o,i)}continue}const u=ne(e,s,n);if(vi(s,e,r,n),typeof a=="object"&&a!==null&&!Array.isArray(a))for(const[c,d]of Object.entries(a))gr(c,o)?.authorize?.(d,{schema:u.schema,property:u.property,resolveSchema:n,assertSchemaAllowed:p=>{Ye(r,p)},assertPropertyAllowed:(p,f)=>mn(r,p,f),hasRowPermissions:p=>Ye(r,p)?.rowPermissions!==void 0});if(Qc(a)){if(u.property.ref!==a.schema)continue;const c=n(a.schema);Ye(r,c.id),zt(a.entity_id)&&mn(r,c,Fn(c,o)),lo(a.query,c,r,n,o,i);continue}po(a,r,n,o,i)}},sr=(t,e,r,n=[],o)=>{if(!t.schema){if(t.from){sr(t.from,e,r,n,o);return}throw new l("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const i=r(t.schema);if(Ye(e,i.id),zt(t.entity_id)&&mn(e,i,Fn(i,n)),t.from){sr(t.from,e,r,n,o);return}lo(t.query,i,e,r,n,o);for(const s of t.preds??[])yn(s,i,e,r,n,o);for(const s of t.groupby??[])yn(s,i,e,r,n,o)},fo=(t,e)=>{if(Array.isArray(t))return t.map(o=>fo(o,e));if(typeof t!="object"||t===null||t instanceof Date)return t;const r=Object.entries(t).map(([o,i])=>[o,fo(i,e)]),n=Object.fromEntries(r);return Qc(t)&&!Hc(t,"version")&&(n.version=e),n},Bm=(t,e,r,n)=>{const o=[],i=(a,u)=>{if(a)for(const[c,d]of Object.entries(a))if((c==="$and"||c==="$or")&&Array.isArray(d))for(const p of d)i(p,u);else if(c==="$expr"&&typeof d=="object"&&d!==null&&!Array.isArray(d)){const p=d.pred;typeof p=="object"&&p!==null&&!Array.isArray(p)&&s(p,u)}else c.startsWith("$")||o.push(ne(u,c,r))},s=(a,u)=>{const c=a.schema?r(a.schema):u;typeof a.pred=="string"?o.push(ne(c,a.pred,r)):a.pred&&!Array.isArray(a.pred)&&s(a.pred,c);for(const d of Array.isArray(a.pred)?a.pred:[])typeof d=="string"?o.push(ne(c,d,r)):s(d,c);if(a.operator&&n?.has(a.operator))for(const d of n.get(a.operator).dependencies??[])o.push(ne(c,d,r));i(a.query,c)};i(t.query,e);for(const a of t.preds??[])s(a,e);for(const a of t.groupby??[])s(a,e);return o},Hm=(t,e,r,n)=>{if(!t.schema)return[];const o=r(t.schema),i=new Set,s=[];for(const a of Bm(t,o,r,n)){if(a.relations.length===0)continue;let u=-1;if(a.relations.forEach(({targetSchema:f},m)=>{e[f.id]?.rowPermissions!==void 0&&(u=m)}),u<0)continue;const c=a.relations.slice(0,u+1),d=c.map(({property:f})=>f.name).join("_");if(i.has(d))continue;i.add(d);let p={};for(const f of[...c].reverse())p={[f.property.name]:{schema:f.targetSchema.id,query:p}};s.push(p)}return s},kr=(t,e,r,n,o,i,s)=>Re(t)?Bt(t,e,r,n,o,i,s):Array.isArray(t)?t.map(a=>kr(a,e,r,n,o,i,s)):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(Object.entries(t).map(([a,u])=>[a,kr(u,e,r,n,o,i,s)])),Gi=(t,e,r,n,o,i,s)=>({...t,...t.query?{query:kr(t.query,e,r,n,o,i,s)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Gi(t.pred,e,r,n,o,i,s)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(a=>typeof a=="string"?a:Gi(a,e,r,n,o,i,s))}:{}}),Bt=(t,e,r,n=!0,o=new Set,i=[],s)=>{if(!e)return ge(t);if(!t.schema){const h=ge(t);return h.from&&(h.from=Bt(h.from,e,r,n,new Set,i,s)),h}n&&sr(t,e,r,i);const a=Ye(e,t.schema),u=o.has(t.schema),c=new Set(o).add(t.schema),d=ge(t);d.query&&(d.query=kr(d.query,e,r,n,new Set,i,s)),d.preds&&(d.preds=d.preds.map(h=>Gi(h,e,r,n,new Set,i,s))),d.from&&(d.from=Bt(d.from,e,r,n,new Set,i,s));const p=u||t.from?void 0:a?.rowPermissions,f=(t.from?[]:Hm(t,e,r,s)).map(h=>kr(fo(h,t.version),e,r,!1,c,i,s));p&&f.push(kr(fo(ge(p),t.version),e,r,!1,c,i,s));const m=[d.query,...f].filter(h=>h!==void 0&&Object.keys(h).length>0);return m.length===1?d.query=m[0]:m.length>1?d.query={$and:m}:delete d.query,d},Yc=(t,e,r=Object.keys(t??{}))=>{if(t)for(const n of r){const o=Ye(t,n),i=e(n),s=o?.columnPermissions?.whitelist;if(s&&(!Array.isArray(s)||s.some(a=>typeof a!="string")))throw new l("INVALID_COLUMN_PERMISSIONS",`Column permissions whitelist must be an array of strings: ${n}`,{schemaId:n});for(const a of s??[])if(!i.properties.some(({id:u,name:c})=>u===a||c===a))throw new l("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${n}.${a}`,{schemaId:n,property:a})}},vc=(t,e)=>!e.isBuiltin(t.name)&&["aggregate","component","runtime"].includes(t.kind),Gc=(t,e,r)=>{const n=Ye(e,t.id)?.metricPermissions,o=t.metrics;if(o!==void 0&&(!Array.isArray(o)||o.some(s=>typeof s!="string")))throw new l("INVALID_SCHEMA_METRICS",`Schema metrics must be an array of operator names: ${t.id}`);for(const s of o??[])if(!r.has(s)||!vc(r.get(s),r))throw new l("INVALID_SCHEMA_METRIC",`Custom metric is not registered: ${t.id}.${s}`,{schemaId:t.id,metric:s});if(n===void 0)return;const i=n;if(i===null||typeof i!="object"||Array.isArray(i)||n.whitelist!=="*"&&(!Array.isArray(n.whitelist)||n.whitelist.some(s=>typeof s!="string")))throw new l("INVALID_METRIC_PERMISSIONS",`Metric permissions whitelist must be '*' or an array of strings: ${t.id}`,{schemaId:t.id});for(const s of n.whitelist==="*"?[]:n.whitelist)if(!o?.includes(s))throw new l("INVALID_METRIC_PERMISSION",`Metric is not configured on Schema: ${t.id}.${s}`,{schemaId:t.id,metric:s})},ar=(t,e,r,n)=>{const o=c=>{if(c.schema)return r(c.schema);if(c.from)return o(c.from);throw new l("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")},i=(c,d)=>{const p=c.schema?r(c.schema):d;if(c.operator&&n.has(c.operator)){const f=n.get(c.operator);if(vc(f,n)){const m=Ye(e,p.id)?.metricPermissions;if((p.metrics!==void 0||m!==void 0)&&!p.metrics?.includes(f.name))throw new l("METRIC_NOT_CONFIGURED",`Metric is not configured on Schema: ${p.id}.${f.name}`,{schemaId:p.id,metric:f.name});if(m&&m.whitelist!=="*"&&!m.whitelist.includes(f.name))throw new l("METRIC_PERMISSION_DENIED",`Metric is not included in the metric permissions: ${p.id}.${f.name}`,{schemaId:p.id,metric:f.name})}f.dependencies?.length&&sr({schema:p.id,preds:f.dependencies.map(m=>({pred:m}))},e,r)}c.pred&&typeof c.pred=="object"&&!Array.isArray(c.pred)&&i(c.pred,p);for(const f of Array.isArray(c.pred)?c.pred:[])typeof f!="string"&&i(f,p);a(c.query,p),s(c.args)},s=c=>{if(Re(c)){u(c);return}if(Array.isArray(c)){for(const d of c)s(d);return}if(!(!c||typeof c!="object"||c instanceof Date))for(const d of Object.values(c))s(d)},a=(c,d)=>{if(Re(c)){u(c);return}if(Array.isArray(c)){for(const p of c)a(p,d);return}if(!(!c||typeof c!="object"||c instanceof Date))for(const[p,f]of Object.entries(c)){const m=p==="$expr"&&f&&typeof f=="object"?f.pred:void 0;m&&typeof m=="object"&&!Array.isArray(m)&&i(m,d),a(f,d)}},u=c=>{const d=o(c);Ye(e,d.id);for(const p of[...c.preds??[],...c.groupby??[]])i(p,d);a(c.query,d),c.from&&u(c.from)};u(t)},zc=t=>String(t),Qm=(t,e,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${zc(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=zc(r),o},zi=(t,e)=>`${t}:${String(e)}`,Ym=t=>{const e=t.properties.filter(({type:n})=>n==="ID"),r=e[0];if(e.length!==1||!r)throw new l("RELATION_TARGET_ID_REQUIRED",`Relation target ${t.id} must contain exactly one ID property`,{schemaId:t.id,count:e.length});return r};class vm{#e;#t;#r=new Map;#n=new Map;#o=new Map;#i=!1;constructor(e){this.#e=e,this.#t=Et(e.now??new Date)}load=(e,r)=>{const n=zi(e,r),o=this.#r.get(n);if(o)return Promise.resolve(o);const i=this.#n.get(n);if(i)return i;const s=this.#e.resolveSchema(e),a=oa(s,this.#e.plugins),u=Ym(s);let c,d;const p=new Promise((m,h)=>{c=m,d=h}),f=this.#o.get(e)??{schema:s,idProperty:u,loads:new Map,...a?{latestVersion:{startProperty:a.start.name,asOf:this.#t}}:{}};return f.loads.set(n,{id:r,resolve:m=>c?.(m),reject:m=>d?.(m)}),this.#o.set(e,f),this.#n.set(n,p),this.#s(),p};#s(){this.#i||(this.#i=!0,queueMicrotask(()=>{this.#a()}))}async#a(){this.#i=!1;const e=this.#o;this.#o=new Map,await Promise.all([...e.values()].map(r=>this.#c(r)))}async#c(e){const r={schema:e.schema,idProperty:e.idProperty,ids:[...e.loads.values()].map(({id:n})=>n),...e.latestVersion?{latestVersion:e.latestVersion}:{}};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){if(e.latestVersion&&o.has(zi(e.schema.id,s)))continue;const a=typeof s=="string"?s:typeof s=="number"||typeof s=="boolean"||typeof s=="bigint"?String(s):JSON.stringify(s),u=i._id===a?i:{...i,_id:a};o.set(zi(e.schema.id,s),u)}}for(const[i,s]of e.loads){const a=o.get(i)??Qm(e.schema,e.idProperty,s.id);this.#r.set(i,a),this.#n.delete(i),s.resolve(a)}}catch(n){for(const[o,i]of e.loads)this.#n.delete(o),i.reject(n)}}}const Gm=(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 l("INVALID_ARRAY_RESULT",`Result column ${e.name} contains invalid array JSON`,{property:e.name,cause:n})}},zm=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=Gm(o[i.name],i),u={property:i,requestEntity:n},c=s.normalizeResult?await s.normalizeResult(a,u):a,d=s.hydrateResult;if(!d){o[i.name]=c;return}o[i.name]=i.isArray&&Array.isArray(c)?await Promise.all(c.map(p=>d(p,u))):await d(c,u)}))}))},Wc=5,Wm=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),Km=(t,e)=>{const r=e.properties.find(({type:n})=>n==="ID");return r?t[r.name]:void 0},Jm=(t,e)=>{const r=Fu(e);t._title=t[r.name]??t._id},Xm=(t,e)=>{const r=structuredClone(t);if(!("_id"in r)){const n=Km(r,e);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},Zm=(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})},ey=async(t,e,r)=>{const n=new vm(r);let o=[{rows:t,properties:e,expandEntities:r.expandEntities!==!1}];for(let i=0;o.length>0;i+=1){await Promise.all(o.map(a=>{const u=a.expandEntities&&i<Wc;return zm(a.rows,a.properties,r.semanticTypes,u?n.load:(c,d)=>Promise.resolve(d))}));for(const a of o)if(a.schema)for(const u of a.rows)Jm(u,a.schema);if(i>=Wc)return;const s=new Map;for(const a of o)if(a.expandEntities)for(const u of a.properties){if(u.primal_type!=="entity"&&u.primal_type!=="object"||!u.ref)continue;const c=r.resolveSchema(u.ref);for(const d of a.rows){if(!(u.name in d))continue;const p=d[u.name],f=u.isArray?Array.isArray(p)?p:[p]:[p];for(const[m,h]of f.entries()){if(!Wm(h))continue;const y=Xm(h,c);u.isArray?f[m]=y:d[u.name]=y,Zm(s,c,y,!u.isArray)}u.isArray&&(d[u.name]=f)}}o=[...s.values()]}},Wi=async(t,e,r)=>{const n=t.map(o=>({...o}));return await ey(n,e,r),n},Kc=(t,e)=>{if(!t.latestVersion)return{query:e};const{startProperty:r,asOf:n}=t.latestVersion;return{query:{$and:[e,{[r]:{$lte:n}}]},sort:{[r]:-1}}},Jc=(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")}},Xc=(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=Jc(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)},ty=(t,e)=>{const r=ia(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=Jc(e,t.timeZone);let o=Xc({...n,...r},t.timeZone);if(o.getTime()<=e.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=Xc({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},t.timeZone)}return o},ry=(t,e)=>{const r=t.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(e.getTime()+n.ttlSeconds*1e3)]:[ty(n,e)]);return r.length===0?void 0:new Date(Math.min(...r.map(n=>n.getTime())))},Ki=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(Ki):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,Ki(r)])):t,Zc=t=>Sn("sha256").update(JSON.stringify(Ki(t))).digest("hex"),ny=t=>Zc({namespace:t.namespace,provider:t.provider,connectionId:t.connectionId,...t.dataVersion!==void 0?{dataVersion:t.dataVersion}:{},sql:t.sql,parameters:t.parameters}),oy=(t,e)=>Zc({namespace:t,source:e}),Ji=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(Ji)}:t&&typeof t=="object"?{type:"object",value:Object.entries(t).map(([e,r])=>[e,Ji(r)])}:t,Xi=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(Xi);case"object":return Object.fromEntries(t.value.map(([e,r])=>[e,Xi(r)]))}},iy=t=>JSON.stringify(Ji(t)),sy=t=>{const e=Xi(JSON.parse(t));if(!(!Array.isArray(e)||e.some(r=>!r||typeof r!="object"||Array.isArray(r))))return e},ay=Number.MAX_SAFE_INTEGER;class cy{#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:${ny(e)}`}#o(e,r){return`${this.#t}:source:${oy(e,r)}`}async get(e){const r=await this.#e.get(this.#n(e));if(r!==null)return sy(r)}async set(e,r,n){const o=this.#n(e),i=iy(r),s=n.expiresAt?.getTime(),a=s??ay,u=this.#e.multi();s===void 0?u.set(o,i):u.set(o,i,{PXAT:s});for(const c of new Set(n.sources)){const d=this.#o(e.namespace,c);u.zRemRangeByScore(d,0,Date.now()),u.zAdd(d,{score:a,value:o})}await u.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 uy=async(t={})=>{const e=Bu(t.url?{url:t.url}:{});return e.on("error",()=>{}),await e.connect(),new cy(e,{...t.keyPrefix?{keyPrefix:t.keyPrefix}:{},ownsClient:!0})};function dy(t){if(!t||typeof t!="object")throw new l("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 l("INVALID_QUERY_CACHE_CONFIGURATION","Query cache id must not be empty");if(e.kind!=="redis")throw new l("INVALID_QUERY_CACHE_CONFIGURATION",`Unsupported query cache kind: ${String(e.kind)}`);if(typeof e.url!="string"||e.url.trim().length===0)throw new l("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 l("INVALID_QUERY_CACHE_CONFIGURATION","Redis query cache keyPrefix must not be empty");if(typeof e.namespace!="string"||e.namespace.trim().length===0)throw new l("INVALID_QUERY_CACHE_CONFIGURATION","Query cache namespace must not be empty")}const py=({namespace:t,...e})=>e,ly=async t=>uy({url:t.url,...t.keyPrefix?{keyPrefix:t.keyPrefix}:{}});class fy{create;#e=new Map;constructor(e=ly){this.create=e}async get(e){dy(e);const r=py(e),n=this.#e.get(r.id);if(n){if(!Ro(n.connection,r))throw new l("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 eu=new fy,tu=t=>eu.get(t),my=()=>eu.close(),yy=async({cache:t,source:e})=>{if(typeof e!="string"||e.trim().length===0)throw new l("INVALID_QUERY_CACHE_SOURCE","Query cache source must not be empty");const r=await tu(t);await r.store.invalidateSource(r.namespace,e)},hy=Object.freeze({invalidateSource:yy}),gy=()=>{},Ur=(t,e)=>e.findSource(t.schemaId,t.mappingSource??t.source,t.connectionId),hn=(t,e,r)=>{if(qt(t)){e.push(t.plan);return}if(Ka(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)hn(n,e,r);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const n of Object.values(t))hn(n,e,r)},gn=(t,e,r)=>{if(t.kind==="window"){gn(t.input,e,r);for(const n of t.partitionBy)gn(n,e,r);return}if(t.kind==="operator"){hn(t.query,e,r),t.input&&gn(t.input,e,r);for(const n of t.inputs??[])gn(n,e,r)}},ke=t=>{const e=new Map,r=o=>{e.set(`${o.schemaId}:${o.connectionId??""}:${o.mappingSource??""}:${o.computationId??""}:${o.source}`,o)};if(t.subplans)for(const o of t.subplans)for(const i of ke(o))r(i);else if(t.sourcePlan)for(const o of ke(t.sourcePlan))r(o);else if(t.mappingSourcePlan)for(const o of ke(t.mappingSourcePlan))r(o);else t.source&&r({schemaId:t.schemaId,source:t.source.identity,...t.connectionId?{connectionId:t.connectionId}:{}});for(const o of t.computationSources??[])r({...o,computationId:o.id});for(const o of t.joins??[])if(r({schemaId:o.targetSchemaId,source:o.targetSource.identity,...o.targetConnectionId?{connectionId:o.targetConnectionId}:{}}),o.targetMappingSourcePlan)for(const i of ke(o.targetMappingSourcePlan))r(i);for(const o of t.enrichmentJoins??[])r({schemaId:t.schemaId,source:o.source.identity,...t.source?{mappingSource:t.source.identity}:{},...t.connectionId?{connectionId:t.connectionId}:{}});const n=[];hn(t.query,n,e),hn(t.having,n,e);for(const o of t.projections)gn(o.expression,n,e);for(const o of n)for(const i of ke(o))r(i);return[...e.values()]},mo=t=>{const e=new Map;for(const r of t.flat())e.set(`${r.schemaId}:${r.connectionId??""}:${r.mappingSource??""}:${r.computationId??""}:${r.source}`,r);return[...e.values()]},ru=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})}},wy=(t,e)=>{const r=[];for(const n of t){const o=Ur(n,e),i=o?.mappings?.find(u=>u.mappingType==="property"&&u.propertyId===n.computationId),s=i?.mappingType==="property"?i.value:void 0,a=n.computationId?s?.kind==="sql"?s.freshness:void 0:n.mappingSource?o?.enrichments?.find(({source:u})=>lt(u)===n.source)?.freshness:o?.freshness;if(!a)return;r.push(a)}return r},Zi=async(t,e,r,n=gy)=>{t=nu(t),r.signal?.throwIfAborted();const o=r.cache?wy(e,r.schemaMappings):void 0;if(!r.cache||!o)return n("database"),ru(r.provider,{...t,...r.signal?{signal:r.signal}:{}});const i=await r.provider.getDataVersion?.(),s={namespace:r.cache.namespace,provider:r.provider.kind,...r.connectionId?{connectionId:r.connectionId}:{},sql:t.sql,parameters:t.parameters,...i!==void 0?{dataVersion:i}:{}};try{const u=await r.cache.store.get(s);if(r.signal?.throwIfAborted(),u)return n("cache"),[...u]}catch{r.signal?.throwIfAborted()}n("database");const a=await ru(r.provider,{...t,...r.signal?{signal:r.signal}:{}});try{const u=ry(o,new Date);await r.cache.store.set(s,a,{sources:[...new Set(e.map(({source:c})=>c))],...u?{expiresAt:u}:{}})}catch{}return a},nu=t=>({...t,sql:nm(t.sql)}),Ay=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")},$y=(t,e,r)=>{const n=Ay(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}},ou=async(t,e)=>{if(!Ot(e.permissions,t.schema.id,t.idProperty))throw new l("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(w=>Ot(e.permissions,t.schema.id,w)),n=e.schemaMappings.list(t.schema.id),o=n.find(({connectionId:w})=>w===e.preferredConnectionId)?.connectionId??n[0]?.connectionId,i=o&&e.providerForConnection?e.providerForConnection(o):e.provider,s={version:e.version,schema:t.schema.id,...Kc(t,$y(t.idProperty.name,t.ids,i.maxInListItems)),preds:r.map(w=>({pred:w.name,name:w.name}))},a=Bt(s,e.permissions,e.resolveSchema,!0,new Set,e.plugins),u=await Rt(a,t.schema,{semanticTypes:e.semanticTypes,operators:e.operators,...e.plugins?{plugins:e.plugins}:{},...e.locale?{locale:e.locale}:{},...e.localeRegistry?{localeRegistry:e.localeRegistry}:{},resolveSchema:e.resolveSchema}),c=Me(u,t.schema,e.operators,e.schemaMappings,{resolveSchema:e.resolveSchema,...o?{preferredConnectionId:o}:{},canUsePropertyRowIdentity:(w,E)=>Ot(e.permissions,w.id,E)}),d=new Set(ke(c).map(w=>e.schemaMappings.findSource(w.schemaId,w.source,w.connectionId)?.connectionId).filter(w=>!!w));if(d.size>1)throw new l("CROSS_CONNECTION_ENTITY_HYDRATION_UNSUPPORTED",`Entity hydration cannot span connections: ${[...d].join(", ")}`);const p=[...d][0]??o,f=p&&e.providerForConnection?e.providerForConnection(p):i,m=Oe(c,f,e.operators),h=ke(c),y=e.onCompiled?.(m,u,f,p,h),$=await Zi(m,h,{provider:f,...p?{connectionId:p}:{},schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},y);return oo($,c.rowIdentity)},es=t=>`'${t.replaceAll("'","''")}'`,iu=t=>{const e=[["\\","\\\\"],["\0","\\0"],["\b","\\b"],[" ","\\t"],[`
|
|
5
|
+
`,"\\n"],["\r","\\r"],["","\\Z"],['"','\\"'],["'","\\'"]];let r=t;for(const[n,o]of e)r=r.replaceAll(n,o);return`'${r}'`},wn=(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():es(t.toString());if(typeof t=="string")return e==="mysql"?iu(t):es(t);if(t instanceof Date){const r=e==="clickhouse"||e==="mysql"?t.toISOString().replace("T"," ").replace("Z",""):t.toISOString();return e==="mysql"?iu(r):es(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}`)},Ey=(t,e)=>t.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in e?wn(e[o],"clickhouse"):r}),Iy=(t,e)=>t.replace(/:([1-9]\d*)\b/g,(r,n)=>{const o=Number(n)-1;return o in e?wn(e[o],"oracle"):r}),_y=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="$"){const s=/^\$(\d+)/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a)-1;if(u in e){r+=wn(e[u],"postgresql"),o+=s[0].length-1;continue}}}r+=i}}return r},ts=(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+=wn(e[o],r),o+=1;continue}n+=a}}return n},by=(t,e)=>ts(t,e,"mysql"),rs=(t,e)=>ts(t,e,"snowflake"),Sy=(t,e)=>ts(t,e,"dameng"),Ny=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="["){n="]",r+=i;continue}if(i==="@"){const s=/^@p(\d+)\b/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a);if(u in e){r+=wn(e[u],"sqlserver"),o+=s[0].length-1;continue}}}r+=i}}return r},Ht=(t,e)=>new Error(`Database driver "${t}" is not installed or could not be loaded. Install it with: npm install ${t}`,{cause:e}),qr=t=>{for(const[e,r]of Object.entries({database:t.database,schema:t.schema}))if(r!==void 0&&!r.trim())throw new l("INVALID_TABLE_SCOPE",`Table discovery ${e} must not be empty`)},nt=(t,e)=>{throw new l("UNSUPPORTED_TABLE_SCOPE",`${t.kind} table discovery does not support a ${e} override`)},ht=(t,e)=>Object.entries(t).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1],ve=(t,e)=>{const r=ht(t,e);if(typeof r!="string"||!r)throw new l("INVALID_TABLE_METADATA",`Expected a non-empty metadata field: ${e}`);return r},su=t=>{const e=ve(t,"table_name"),r=ht(t,"table_database"),n=ht(t,"table_schema"),o=ve(t,"table_type").toUpperCase();if(!["BASE TABLE","TABLE","FOREIGN TABLE","EXTERNAL TABLE","EVENT TABLE","VIEW","SYSTEM VIEW","MATERIALIZED VIEW"].includes(o))throw new l("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"}},ns=t=>t.map(su),cr=async(t,e)=>{e.signal?.throwIfAborted(),qr(e);const r=[],n=u=>{const c=t.parameter(r.length,u);return r.push(u),c},o=e.database,i=e.schema;let s;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":i!==void 0&&nt(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&&nt(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&&nt(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&&nt(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 l("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(),ns(a)},yo=t=>{if(qr(t),!t.table.trim())throw new l("INVALID_TABLE_NAME","Table name must not be empty")},ho=(t,e)=>{const r=ht(t,e);return typeof r=="string"?r:""},Ry=t=>{const e=ve(t,"column_type"),r=ht(t,"type_length"),n=ht(t,"type_precision"),o=ht(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},au=t=>{const e=ht(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 l("INVALID_TABLE_METADATA","Invalid primary-key metadata");return{name:ve(t,"column_name"),type:Ry(t),comment:ho(t,"column_comment"),...r!==void 0?{primaryKey:r}:{}}},Oy=(t,e)=>{const r=[],n=c=>{const d=t.parameter(r.length,c);return r.push(c),d},o=n(e.table),{database:i,schema:s}=e;let a,u;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":{s!==void 0&&nt(t,"schema");const c=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${i!==void 0?n(i):"DATABASE()"}`;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_SCHEMA AS table_database, c.TABLE_TYPE AS table_type, c.TABLE_COMMENT AS table_comment FROM information_schema.tables c WHERE ${c}`,u=`SELECT c.COLUMN_NAME AS column_name, c.COLUMN_TYPE AS column_type, c.COLUMN_COMMENT AS column_comment, (c.COLUMN_KEY = 'PRI') AS is_primary_key FROM information_schema.columns c WHERE ${c} ORDER BY c.ORDINAL_POSITION`;break}case"postgresql":{i!==void 0&&nt(t,"database");const c=`c.relname = ${o} AND n.nspname = ${s!==void 0?n(s):"current_schema()"}`;a=`SELECT c.relname AS table_name, current_database() AS table_database, n.nspname AS table_schema, CASE WHEN c.relkind IN ('v', 'm') THEN 'VIEW' ELSE 'TABLE' END AS table_type, obj_description(c.oid, 'pg_class') AS table_comment FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE ${c} AND c.relkind IN ('r', 'v', 'm', 'p', 'f')`,u=`SELECT a.attname AS column_name, format_type(a.atttypid, a.atttypmod) AS column_type, col_description(c.oid, a.attnum) AS column_comment, EXISTS (SELECT 1 FROM pg_catalog.pg_index i WHERE i.indrelid = c.oid AND i.indisprimary AND a.attnum = ANY(i.indkey)) AS is_primary_key FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE ${c} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`;break}case"sqlserver":{const c=i!==void 0?`${t.quoteIdentifier(i)}.`:"",d=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"SCHEMA_NAME()"}`,p=`JOIN ${c}sys.schemas s ON s.name = c.TABLE_SCHEMA JOIN ${c}sys.objects o ON o.schema_id = s.schema_id AND o.name = c.TABLE_NAME `;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_CATALOG AS table_database, c.TABLE_SCHEMA AS table_schema, c.TABLE_TYPE AS table_type, CAST(ep.value AS nvarchar(max)) AS table_comment FROM ${c}INFORMATION_SCHEMA.TABLES c ${p}LEFT JOIN ${c}sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id AND ep.minor_id = 0 AND ep.name = 'MS_Description' WHERE ${d}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, c.CHARACTER_MAXIMUM_LENGTH AS type_length, c.NUMERIC_PRECISION AS type_precision, c.NUMERIC_SCALE AS type_scale, CAST(ep.value AS nvarchar(max)) AS column_comment, CASE WHEN EXISTS (SELECT 1 FROM ${c}sys.indexes i JOIN ${c}sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id WHERE i.object_id = o.object_id AND i.is_primary_key = 1 AND ic.key_ordinal > 0 AND ic.column_id = sc.column_id) THEN 1 ELSE 0 END AS is_primary_key FROM ${c}INFORMATION_SCHEMA.COLUMNS c ${p}JOIN ${c}sys.columns sc ON sc.object_id = o.object_id AND sc.name = c.COLUMN_NAME LEFT JOIN ${c}sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id AND ep.minor_id = sc.column_id AND ep.name = 'MS_Description' WHERE ${d} ORDER BY c.ORDINAL_POSITION`;break}case"snowflake":{const c=`${i!==void 0?`${t.quoteIdentifier(i)}.`:""}INFORMATION_SCHEMA`,d=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"CURRENT_SCHEMA()"}`;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_CATALOG AS table_database, c.TABLE_SCHEMA AS table_schema, c.TABLE_TYPE AS table_type, c.COMMENT AS table_comment FROM ${c}.TABLES c WHERE ${d}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, c.COMMENT AS column_comment, c.CHARACTER_MAXIMUM_LENGTH AS type_length, c.NUMERIC_PRECISION AS type_precision, c.NUMERIC_SCALE AS type_scale FROM ${c}.COLUMNS c WHERE ${d} ORDER BY c.ORDINAL_POSITION`;break}case"oracle":case"dameng":{i!==void 0&&nt(t,"database");const c=`c.TABLE_NAME = ${o} AND c.OWNER = ${s!==void 0?n(s):"SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')"}`;a=`SELECT c.TABLE_NAME AS table_name, c.OWNER AS table_schema, c.TABLE_TYPE AS table_type, c.COMMENTS AS table_comment FROM ALL_TAB_COMMENTS c WHERE ${c}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, CASE WHEN c.DATA_TYPE = 'RAW' THEN c.DATA_LENGTH ELSE c.CHAR_LENGTH END AS type_length, c.DATA_PRECISION AS type_precision, c.DATA_SCALE AS type_scale, cm.COMMENTS AS column_comment, CASE WHEN EXISTS (SELECT 1 FROM ALL_CONS_COLUMNS k JOIN ALL_CONSTRAINTS t ON t.OWNER = k.OWNER AND t.CONSTRAINT_NAME = k.CONSTRAINT_NAME WHERE t.CONSTRAINT_TYPE = 'P' AND k.OWNER = c.OWNER AND k.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END AS is_primary_key FROM ALL_TAB_COLUMNS c LEFT JOIN ALL_COL_COMMENTS cm ON cm.OWNER = c.OWNER AND cm.TABLE_NAME = c.TABLE_NAME AND cm.COLUMN_NAME = c.COLUMN_NAME WHERE ${c} ORDER BY c.COLUMN_ID`;break}case"clickhouse":{s!==void 0&&nt(t,"schema");const c=i!==void 0?n(i):"currentDatabase()";a=`SELECT c.name AS table_name, c.database AS table_database, c.comment AS table_comment, if(c.engine IN ('View', 'MaterializedView', 'LiveView', 'WindowView'), 'VIEW', 'TABLE') AS table_type FROM system.tables c WHERE c.name = ${o} AND c.database = ${c}`,u=`SELECT c.name AS column_name, c.type AS column_type, c.comment AS column_comment, c.is_in_primary_key AS is_primary_key FROM system.columns c WHERE c.table = ${o} AND c.database = ${c} ORDER BY c.position`;break}default:throw new l("UNSUPPORTED_TABLE_DESCRIPTION",`No table description SQL for provider: ${t.kind}`)}return{tableSql:a,columnSql:u,parameters:r}},cu=(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(".")},jr=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},os=async(t,e,r)=>{if(e.includeSample===!1)return r;const n=cu(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 jr(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},Ty=async(t,e)=>{let{database:r,schema:n}=e;if(r===void 0||n===void 0){const[p]=await jr(t,e,"SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!p)throw new l("INVALID_TABLE_METADATA","Databricks current namespace was not returned");r??=ve(p,"table_database"),n??=ve(p,"table_schema")}const o=cu(t,{name:e.table,database:r,schema:n}),i=await jr(t,e,`DESCRIBE TABLE EXTENDED ${o}`),s=[];let a=!0,u=!1,c="",d="table";for(const p of i){const f=ht(p,"col_name"),m=ht(p,"data_type"),h=(f==="# Partition Information"||f==="# Detailed Table Information")&&!m;(f===""||h)&&(a=!1),h&&f==="# Detailed Table Information"&&(u=!0),a?s.push({name:ve(p,"col_name"),type:ve(p,"data_type"),comment:ho(p,"comment")}):u&&f==="Comment"?c=ho(p,"data_type"):u&&f==="Type"&&m==="VIEW"&&(d="view")}if(!s.length)throw new l("INVALID_TABLE_METADATA","Databricks description did not contain columns");return os(t,e,{columns:s,tableInfo:{name:e.table,database:r,schema:n,type:d,comment:c}})},Py=async(t,e)=>{e.database!==void 0&&nt(t,"database"),e.schema!==void 0&&nt(t,"schema");const n=(await jr(t,e,`DESC ${t.quoteIdentifier(e.table)}`)).map(au);if(!n.length)throw new l("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);return os(t,e,{columns:n,tableInfo:{name:e.table,type:"table",comment:""}})},Tt=async(t,e)=>{if(e.signal?.throwIfAborted(),yo(e),t.kind==="databricks")return Ty(t,e);if(t.kind==="maxcompute")return Py(t,e);const{tableSql:r,columnSql:n,parameters:o}=Oy(t,e),i=await jr(t,e,r,o),[s]=i;if(!s)throw new l("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);if(i.length!==1)throw new l("AMBIGUOUS_TABLE",`More than one table matched: ${e.table}`);const a={...su(s),comment:ho(s,"table_comment")},u=(await jr(t,e,n,o)).map(au);return os(t,e,{columns:u,tableInfo:a})},Ly=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}`},Cy=t=>t===null?"Nullable(String)":typeof t=="boolean"?"Bool":typeof t=="number"?"Float64":t instanceof Date?"DateTime64(3)":"String",uu=t=>t instanceof Date?t.toISOString().replace("T"," ").replace("Z",""):t;class Dy{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 Ht("@clickhouse/client",r)});return e({url:Ly(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}:${Cy(r)}}`}displayQuery(e,r){return Ey(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}`,uu(i)]));return(await r.query({query:e.sql,format:"JSONEachRow",query_params:n,...e.signal?{abort_signal:e.signal}:{}})).json()}getTableList(e){return cr(this,e)}describeTable(e){return Tt(this,e)}async runSQL(e){e.signal?.throwIfAborted();const r=await this.#r();if(e.signal?.throwIfAborted(),!r.exec)throw new l("UNSUPPORTED_RAW_SQL","ClickHouse native SQL requires client.exec");const n=await r.exec({query:e.sql,query_params:Object.fromEntries(e.parameters.map((a,u)=>[`p${u}`,uu(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(`
|
|
6
|
+
`).map(a=>{const u=JSON.parse(a);if(typeof u!="object"||u===null||Array.isArray(u))throw new Error("ClickHouse provider expected object rows");return u}):[]}}async close(){const e=this.#t;if(!e)return;await(await e).close(),this.#t=void 0}}const My=t=>[".azuredatabricks.net",".databricks.azure.cn",".databricks.azure.us"].some(e=>t.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]?.endsWith(e)),ky=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??(My(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)}`)},Uy=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 qy{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 Ht("@databricks/sql",r)})).DBSQLClient;if(this.#e)try{await e.connect(ky(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 rs(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=process.env.TZ,i=await r.openSession({...this.#e?.catalog?{initialCatalog:this.#e.catalog}:{},...n?{initialSchema:n}:{}});let s;const a=()=>{s&&s.cancel().catch(()=>{})};e.signal?.addEventListener("abort",a,{once:!0});try{if(e.signal?.throwIfAborted(),o){s=await i.executeStatement(`SET TIME ZONE '${o.replaceAll("'","''")}'`,{ordinalParameters:[]}),e.signal?.aborted&&a();try{e.signal?.throwIfAborted(),await s.finished?.(),e.signal?.throwIfAborted()}finally{const c=s;s=void 0,await c.close()}}s=await i.executeStatement(e.sql,{ordinalParameters:e.parameters.map(Uy)}),e.signal?.aborted&&a(),e.signal?.throwIfAborted(),await s.finished?.(),e.signal?.throwIfAborted();const u=await s.fetchAll();if(e.signal?.throwIfAborted(),!Array.isArray(u))throw new Error("Databricks provider expected an array result");return u}finally{e.signal?.removeEventListener("abort",a);try{s&&await s.close()}finally{await i.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 Tt(this,{...e,...r!==void 0?{database:r}:{},...n!==void 0?{schema:n}:{}})}async getTableList(e){e.signal?.throwIfAborted(),qr(e);const r=c=>this.execute({sql:c,parameters:[],...e.signal?{signal:e.signal}:{}});let n=e.database??this.#e?.catalog,o=e.schema??this.#e?.schema??this.#e?.database;if(n===void 0||o===void 0){const[c]=await r("SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!c)throw new Error("Databricks current namespace was not returned");n??=ve(c,"table_database"),o??=ve(c,"table_schema")}const i=`${this.quoteIdentifier(n)}.${this.quoteIdentifier(o)}`,s=await r(`SHOW TABLES IN ${i}`),a=await r(`SHOW VIEWS IN ${i}`),u=new Map;for(const c of s){const d=ve(c,"tableName");u.set(d,{name:d,database:n,schema:o,type:"table"})}for(const c of a){const d=ve(c,"viewName");u.set(d,{name:d,database:n,schema:o,type:"view"})}return[...u.values()].sort((c,d)=>c.name.localeCompare(d.name))}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}const du=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}`)},jy=t=>{const{host:e,port:r,...n}=t;return{...n,connectString:t.connectString??`${e??"localhost"}:${r??5236}`}};class xy{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={...jy(this.#e),poolAlias:typeof this.#e.poolAlias=="string"?this.#e.poolAlias:`semanticdb-${Br()}`};if(this.#t)return this.#t.createPool(e);const{default:r}=await import("dmdb").catch(n=>{throw Ht("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 Sy(e,r.map(du))}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 cr(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}describeTable(e){return Tt(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(du),{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 we={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 by(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}`}}},Vy={connectionLimit:30,maxIdle:10,idleTimeout:6e4,enableKeepAlive:!0,keepAliveInitialDelay:0};class go{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 Ht("mysql2",r)});return e({...Vy,decimalNumbers:!0,...this.#e})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return we.quoteIdentifier(e)}tableAlias(e,r){return we.tableAlias(e,r)}paginate(e,r,n){return we.paginate(e,r,n)}parameter(e,r){return we.parameter(e,r)}displayQuery(e,r){return we.displayQuery(e,r)}dateBucket(e,r){return we.dateBucket(e,r)}datePart(e,r){return we.datePart(e,r)}dateShift(e,r,n){return we.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=we.datePeriodBoundary?.bind(we);if(!o)throw new Error("MySQL date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return we.aggregateFunction(e,r)}stringify(e){return we.stringify(e)}concat(e){return we.concat(e)}substring(e,r,n){return we.substring(e,r,n)}stringLength(e){return we.stringLength(e)}regex(e,r,n){return we.regex(e,r,n)}arrayContains(e,r){const n=we.arrayContains?.bind(we);if(!n)throw new Error("MySQL-compatible array conditions are unavailable");return n(e,r)}expandArray(e,r,n,o){const i=we.expandArray?.bind(we);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 cr(this,e)}describeTable(e){return Tt(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 Fy extends go{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}`}}}const pu=(t,e="DuckDB")=>{if(t==null)return null;if(t instanceof Date)return $t(t,Oo);if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"||typeof t=="string")return t;if(Buffer.isBuffer(t))return Qu(t);throw new TypeError(`Unsupported ${e} parameter: ${typeof t}`)},xr=t=>`'${t.replaceAll("'","''")}'`;class is{kind="duckdb";supportsHavingAlias=!0;supportsRecursiveCte=!0;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 rs(e,r)}dateBucket(e,r){return`DATE_TRUNC(${xr(r)}, ${e})`}datePart(e,r){return`EXTRACT(${r==="weekday"?"ISODOW":r.toUpperCase()} FROM ${e})`}dateShift(e,r,n){return`(${e} + INTERVAL ${xr(`${n} ${r}`)})`}datePeriodBoundary(e,r,n){const o=this.dateBucket(e,r);return n==="start"?o:`(${o} + INTERVAL ${xr(`1 ${r}`)} - 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`REGEXP_MATCHES(${e}, ${r}${n?`, ${xr(n)}`:""})`}arrayContains(e,r){return`LIST_CONTAINS(${e}, ${r})`}normalizeStringArray(e){const r=`TRY_CAST(${e} AS JSON)`;return`(CASE WHEN ${e} IS NULL THEN []::VARCHAR[] WHEN json_type(${r}) = 'ARRAY' THEN from_json(${r}, '["VARCHAR"]') ELSE [CAST(${e} AS VARCHAR)] END)`}expandArray(e,r,n){return{joinSql:`CROSS JOIN UNNEST(${e}) AS ${this.quoteIdentifier(r)}(${this.quoteIdentifier(n)})`,valueExpression:`${this.quoteIdentifier(r)}.${this.quoteIdentifier(n)}`}}}const lu=t=>{const e={string:"VARCHAR",number:"DOUBLE",boolean:"BOOLEAN",date:"DATE",timestamp:"TIMESTAMP"};if(!Object.hasOwn(e,t))throw new l("INVALID_FILE_IMPORT",`Unsupported column type: ${t}`);return e[t]},fu=t=>{if(!Array.isArray(t)||!t.length)throw new l("INVALID_FILE_IMPORT","columns must not be empty");const e=new Set;for(const r of t){const n=r;if(!n||typeof n.name!="string"||!n.name.trim()||n.name.includes("\0")||e.has(n.name.toLowerCase()))throw new l("INVALID_FILE_IMPORT","Column names must be non-empty and unique");if(n.type===void 0||n.nullable!==void 0&&typeof n.nullable!="boolean")throw new l("INVALID_FILE_IMPORT","Columns require a supported type and optional boolean nullable");lu(n.type),e.add(n.name.toLowerCase())}},By=(t,e)=>{if(t==null||t===""){if(e.nullable===!1)throw new Error("NULL is not allowed");return null}switch(e.type){case"string":if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);break;case"number":{const r=typeof t=="number"?t:typeof t=="string"&&/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(t.trim())?Number(t):Number.NaN;if(Number.isFinite(r))return r;break}case"boolean":if(t===!0||t==="true"||t===1||t==="1")return!0;if(t===!1||t==="false"||t===0||t==="0")return!1;break;case"date":{const r=t instanceof Date?t.toISOString().slice(0,10):t;if(typeof r=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(r)){const n=new Date(`${r}T00:00:00Z`);if(!Number.isNaN(n.getTime())&&n.toISOString().slice(0,10)===r)return r}break}case"timestamp":{if(t instanceof Date&&!Number.isNaN(t.getTime()))return t.toISOString();if(typeof t=="string"&&/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})?$/.test(t)){const r=t.slice(0,10);if(new Date(`${r}T00:00:00Z`).toISOString().slice(0,10)!==r)break;const n=new Date(t.replace(" ","T")+(/(?:Z|[+-]\d{2}:\d{2})$/.test(t)?"":"Z"));if(!Number.isNaN(n.getTime()))return n.toISOString()}break}}throw new Error(`Expected ${e.type}`)},Hy=t=>{if(!t.table.trim()||/[.\0]/.test(t.table)||!t.batchId.trim())throw new l("INVALID_FILE_IMPORT","A non-empty unqualified table name and batchId are required");const e=t.mode??"append";if(!["append","replace-batch","replace"].includes(e))throw new l("INVALID_FILE_IMPORT","Unsupported import mode");fu(t.columns);const r=t.columns.map(o=>({name:o.name,type:o.type,nullable:o.nullable??!0})),n=t.rows.map((o,i)=>{if(t.signal?.throwIfAborted(),Object.keys(o).length!==r.length||r.some(({name:s})=>!Object.hasOwn(o,s)))throw new l("IMPORT_COLUMN_MISMATCH",`Row ${i+1} does not match the dataset columns`);return Object.fromEntries(r.map(s=>{try{return[s.name,By(o[s.name],s)]}catch(a){throw new l("IMPORT_INVALID_VALUE",`Row ${i+1}, column ${s.name}: ${a instanceof Error?a.message:String(a)}`,{row:i+1,column:s.name})}}))});return{columns:r,rows:n,mode:e,hash:Sn("sha256").update(JSON.stringify({columns:r,rows:n})).digest("hex")}},mu=new is,yu=t=>Hr(t,"manifest.json"),hu=(t,e)=>t instanceof Error&&"code"in t&&t.code===e,ss=async t=>{let e;try{e=await Ss(yu(t),"utf8")}catch(r){if(hu(r,"ENOENT"))return{format:1,version:"empty",tables:[]};throw r}try{const r=JSON.parse(e);if(r.format!==1||typeof r.version!="string"||!r.version||!Array.isArray(r.tables))throw new Error("Invalid manifest");const n=new Set;for(const o of r.tables){const i=o;if(typeof i.name!="string"||!i.name.trim()||/[.\0]/.test(i.name)||n.has(i.name.toLowerCase())||!Array.isArray(i.batches)||!i.batches.length)throw new Error("Invalid table");n.add(i.name.toLowerCase()),fu(i.columns);const s=new Set;for(const a of i.batches){const u=a;if(typeof u.id!="string"||!u.id.trim()||s.has(u.id)||!/^[a-f0-9-]{36}\.parquet$/.test(u.file)||!/^[a-f0-9]{64}$/.test(u.hash)||!Number.isSafeInteger(u.rowCount)||u.rowCount<0)throw new Error("Invalid batch");s.add(u.id)}}return r}catch(r){throw new l("INVALID_DATASET_MANIFEST",`Invalid dataset manifest: ${r instanceof Error?r.message:String(r)}`)}},Qy=async(t,e,r)=>{for(const n of r.tables){const o=n.batches.map(i=>xr(Hr(e,i.file))).join(", ");await t.run(`CREATE TEMP VIEW ${mu.quoteIdentifier(n.name)} AS SELECT * FROM read_parquet([${o}])`)}},Yy=async(t,e)=>{const r=Hr(t,`${Br()}.json.tmp`);try{const n=await Rs(r,"wx");try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await Gu(r,yu(t))}finally{await Po(r,{force:!0})}},vy=async(t,e,r)=>{e.signal?.throwIfAborted();const n=Hy(e);t=Es(t),await Ns(t,{recursive:!0});const o=Hr(t,".publish-lock"),i=Date.now();for(;;){e.signal?.throwIfAborted();try{await Ns(o);break}catch(u){if(!hu(u,"EEXIST"))throw u;if(Date.now()-i>=r)throw new l("FILE_IMPORT_BUSY","Dataset publisher is locked; retry later. Inspect .publish-lock after a writer crash.");await Wu(25,void 0,e.signal?{signal:e.signal}:{})}}let s,a=!1;try{const u=await ss(t),c=u.tables.find(E=>E.name.toLowerCase()===e.table.toLowerCase());if(c&&(c.name!==e.table||!Ro(c.columns,n.columns)))throw new l("IMPORT_COLUMN_MISMATCH","Column definitions must match the existing dataset exactly");const d=c?.batches.find(E=>E.id===e.batchId),p={table:e.table,batchId:e.batchId,rowCount:n.rows.length};if(d?.hash===n.hash&&(n.mode!=="replace"||c?.batches.length===1))return{...p,version:u.version,status:"unchanged"};if(d&&n.mode==="append")throw new l("IMPORT_BATCH_CONFLICT","batchId already exists with different data; use replace-batch");const f=`${Br()}.parquet`;s=Hr(t,f);const m=await To.create(":memory:");try{const E=await m.connect();try{const N=n.columns;await E.run(`CREATE TABLE incoming (${N.map(S=>`${mu.quoteIdentifier(S.name)} ${lu(S.type)}`).join(", ")})`);const I=await E.createAppender("incoming");try{for(const S of n.rows){e.signal?.throwIfAborted();for(const D of N){const b=S[D.name];if(b===null)I.appendNull();else if(typeof b=="number")I.appendDouble(b);else if(typeof b=="boolean")I.appendBoolean(b);else if(typeof b=="string")if(D.type==="date"||D.type==="timestamp"){const T=new Date(D.type==="date"?`${b}T00:00:00Z`:b);D.type==="date"?I.appendDate(Yu(Math.floor(T.getTime()/864e5))):I.appendTimestamp(vu(BigInt(T.getTime())*1000n))}else I.appendVarchar(b)}I.endRow()}I.flushSync()}finally{I.closeSync()}await E.run(`COPY incoming TO ${xr(s)} (FORMAT PARQUET)`)}finally{E.closeSync()}}finally{m.closeSync()}const h=await Rs(s,"r");try{await h.sync()}finally{await h.close()}e.signal?.throwIfAborted();const y=n.mode==="replace"?[]:(c?.batches??[]).filter(E=>E.id!==e.batchId),$={name:e.table,columns:n.columns,batches:[...y,{id:e.batchId,file:f,hash:n.hash,rowCount:n.rows.length}]},w=Br();return await Yy(t,{format:1,version:w,tables:[...u.tables.filter(E=>E.name!==e.table),$]}),a=!0,{...p,version:w,status:"imported"}}finally{try{s&&!a&&await Po(s,{force:!0})}finally{await Po(o,{recursive:!0,force:!0})}}};class Gy extends is{#e;#t;#r=!1;#n=new Set;constructor(e){super();const r=e.path,n=e.directory;if(typeof r=="string"==(typeof n=="string")||!(r??n)?.trim())throw new l("INVALID_DUCKDB_CONNECTION","Specify exactly one non-empty DuckDB path or dataset directory");const o=e;if(n!==void 0&&o.readOnly!==void 0||r!==void 0&&o.lockTimeoutMs!==void 0)throw new l("INVALID_DUCKDB_CONNECTION","readOnly applies to files; lockTimeoutMs applies to dataset directories");if(e.lockTimeoutMs!==void 0&&(!Number.isSafeInteger(e.lockTimeoutMs)||e.lockTimeoutMs<0))throw new l("INVALID_DUCKDB_CONNECTION","lockTimeoutMs must be a non-negative safe integer");this.#e=n!==void 0?{...e,directory:Es(n)}:{...e}}async#o(){return this.#t??=To.create(this.#e.path??":memory:",{...this.#e.path!==void 0&&(this.#e.readOnly??!0)?{access_mode:"READ_ONLY"}:{}}).catch(e=>{throw this.#t=void 0,e}),this.#t}#i(e){if(this.#r)return Promise.reject(new l("DUCKDB_CLOSED","DuckDB connection is closed"));const r=e();return this.#n.add(r),r.finally(()=>this.#n.delete(r)).catch(()=>{}),r}#s(e,r){return this.#i(async()=>{e?.throwIfAborted();const o=await(await this.#o()).connect(),i=()=>o.interrupt();e?.addEventListener("abort",i,{once:!0});try{if(e?.throwIfAborted(),this.#e.directory!==void 0){const a=await ss(this.#e.directory);await Qy(o,this.#e.directory,a)}const s=await r(o);return e?.throwIfAborted(),s}catch(s){throw e?.throwIfAborted(),s}finally{e?.removeEventListener("abort",i),o.closeSync()}})}async getDataVersion(){return this.#e.directory!==void 0?(await ss(this.#e.directory)).version:void 0}importRows(e){const r=this.#e.directory;return r===void 0?Promise.reject(new l("UNSUPPORTED_FILE_IMPORT","Managed imports require a DuckDB dataset directory")):this.#i(()=>vy(r,e,this.#e.lockTimeoutMs??1e4))}async execute(e){return(await this.runSQL(e)).rows}runSQL(e){return this.#s(e.signal,async r=>{const n=await r.runAndReadAll(e.sql,e.parameters.map(o=>pu(o)));return{rows:n.returnType===Is.QUERY_RESULT?n.getRowObjectsJS():[],...n.returnType===Is.CHANGED_ROWS?{affectedRows:n.rowsChanged}:{}}})}#a(e){qr(e);const r=e.database;return{sql:`table_catalog = ${r!==void 0?"?":this.#e.directory!==void 0?"'temp'":"current_database()"} AND table_schema = ?`,parameters:[...r!==void 0?[r]:[],e.schema??"main"]}}getTableList(e){const r=this.#a(e);return this.#s(e.signal,async n=>{const o=await n.runAndReadAll(`SELECT table_name, table_catalog AS table_database, table_schema, table_type FROM information_schema.tables WHERE ${r.sql} ORDER BY table_name`,r.parameters);return ns(o.getRowObjectsJS())})}describeTable(e){yo(e);const r=this.#a(e);return this.#s(e.signal,async n=>{const o=await n.runAndReadAll(`SELECT table_name, table_catalog AS table_database, table_schema, table_type FROM information_schema.tables WHERE ${r.sql} AND table_name = ?`,[...r.parameters,e.table]),[i]=ns(o.getRowObjectsJS());if(!i)throw new l("TABLE_NOT_FOUND",`Table was not found: ${e.table}`);const s=[i.database??"",i.schema??"main",i.name],a=await n.runAndReadAll("SELECT c.column_name, c.data_type, c.comment, EXISTS (SELECT 1 FROM duckdb_constraints() k WHERE k.database_name = c.database_name AND k.schema_name = c.schema_name AND k.table_name = c.table_name AND k.constraint_type = 'PRIMARY KEY' AND list_contains(k.constraint_column_names, c.column_name)) AS pk FROM duckdb_columns() c WHERE c.database_name = ? AND c.schema_name = ? AND c.table_name = ? ORDER BY c.column_index",s),u=await n.runAndReadAll("SELECT comment FROM duckdb_tables() WHERE database_name = ? AND schema_name = ? AND table_name = ? UNION ALL SELECT comment FROM duckdb_views() WHERE database_name = ? AND schema_name = ? AND view_name = ?",[...s,...s]);let c;if(e.includeSample!==!1){const p=s.map(f=>this.quoteIdentifier(f)).join(".");try{[c]=(await n.runAndReadAll(`SELECT * FROM ${p} LIMIT 1`)).getRowObjectsJS()}catch{e.signal?.throwIfAborted()}}const d=u.getRowObjectsJS()[0]?.comment;return{tableInfo:{...i,comment:typeof d=="string"?d:""},columns:a.getRowObjectsJS().map(p=>{const f=ve(p,"column_name");return{name:f,type:ve(p,"data_type"),comment:typeof p.comment=="string"?p.comment:"",primaryKey:p.pk===!0,...c&&Object.hasOwn(c,f)?{exampleValue:c[f]}:{}}})}})}async close(){this.#r=!0,await Promise.allSettled([...this.#n]);const e=this.#t;this.#t=void 0,e&&(await e).closeSync()}}class zy extends go{kind="gbase";supportsRecursiveCte=!1;constructor(e={}){super({...e,connection:{port:5258,...e.connection}})}}class Wy{kind="maxcompute";supportsRecursiveCte=!1;#e;#t=!1;constructor(e){this.#e=e.client}quoteIdentifier(e){return we.quoteIdentifier(e)}tableAlias(e,r){return we.tableAlias(e,r)}paginate(e,r,n){return we.paginate(e,r,n)}parameter(e,r){return we.parameter(e,r)}displayQuery(e,r){return we.displayQuery(e,r)}dateBucket(e,r){return we.dateBucket(e,r)}datePart(e,r){return we.datePart(e,r)}dateShift(e,r,n){return we.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=we.datePeriodBoundary?.bind(we);if(!o)throw new Error("MaxCompute date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return we.aggregateFunction(e,r)}stringify(e){return we.stringify(e)}concat(e){return we.concat(e)}substring(e,r,n){return we.substring(e,r,n)}stringLength(e){return we.stringLength(e)}regex(e,r,n){return we.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(),qr(e),this.#e.getTableList){const n=await this.#e.getTableList(e);return e.signal?.throwIfAborted(),n}return e.database!==void 0&&nt(this,"database"),e.schema!==void 0&&nt(this,"schema"),(await this.execute({sql:"SHOW TABLES",parameters:[],...e.signal?{signal:e.signal}:{}})).map(n=>({name:ve(n,"table_name"),type:"table"}))}async close(){this.#t||(await this.#e.close(),this.#t=!0)}async describeTable(e){if(e.signal?.throwIfAborted(),yo(e),!this.#e.describeTable)return Tt(this,e);const r=await this.#e.describeTable(e);return e.signal?.throwIfAborted(),r}}class Ky extends go{kind="mysql";constructor(e={}){super(e)}}const gu=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}`)},Jy=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class Xy{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 Iy(e,r.map(gu))}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 Ht("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 cr(this,e)}describeTable(e){return Tt(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(gu),{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?Jy(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 Zy{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 Ht("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 _y(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}'))`}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 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 cr(this,e)}describeTable(e){return Tt(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 wu=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}`)},eh=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class th{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 Ht("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 rs(e,r.map(wu))}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#i(){if(this.#r)return;const e=await this.#o();this.#n??=new Promise((r,n)=>{e.connect(o=>{if(o){n(o);return}this.#r=!0,r()})});try{await this.#n}catch(r){throw this.#n=void 0,r}}async execute(e){return(await this.#s(e,!1)).rows}async runSQL(e){return this.#s(e,!0)}getTableList(e){return cr(this,e)}describeTable(e){return Tt(this,e)}async#s(e,r){e.signal?.throwIfAborted(),await this.#i(),e.signal?.throwIfAborted();const n=await this.#o();e.signal?.throwIfAborted();const o=e.parameters.map(wu);return new Promise((i,s)=>{const a=e.signal,u={};let c=!1;const d=f=>{c||(c=!0,a?.removeEventListener("abort",p),f())},p=()=>{u.current?.cancel(),a&&d(()=>s(eh(a)))};a?.addEventListener("abort",p,{once:!0}),u.current=n.execute({sqlText:e.sql,binds:o,complete:(f,m,h)=>{if(f){d(()=>s(f));return}if(!(r&&h===void 0)&&!Array.isArray(h)){d(()=>s(new Error("Snowflake provider expected an array result")));return}const y=r?m.getNumUpdatedRows?.():void 0;d(()=>i({rows:h??[],...typeof y=="number"&&y>=0?{affectedRows:y}:{}}))}}),a?.aborted&&p()})}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 rh=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}}},nh=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}`)},oh=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError"),ih=t=>t instanceof Error?t:new Error("SQL Server query failed",{cause:t}),sh=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 ah{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 Ht("mssql",n)}),r=new e.ConnectionPool(rh(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`${sh(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 Ny(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 cr(this,e)}describeTable(e){return Tt(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}`,nh(i))),new Promise((i,s)=>{const a=e.signal;let u=!1;const c=p=>{u||(u=!0,a?.removeEventListener("abort",d),p())},d=()=>{o.cancel(),a&&c(()=>s(oh(a)))};a?.addEventListener("abort",d,{once:!0}),o.query(e.sql).then(p=>{if(!Array.isArray(p.recordset)&&!(r&&p.recordset===void 0)){c(()=>s(new Error("SQL Server provider expected an array result")));return}c(()=>i({rows:p.recordset??[],...p.rowsAffected?{affectedRows:p.rowsAffected.reduce((f,m)=>f+m,0)}:{}}))},p=>c(()=>s(ih(p)))),a?.aborted&&d()})}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}class ch extends go{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 tt=t=>{const{id:e,kind:r,...n}=t;return n},uh=Object.freeze([{kind:"duckdb",create:t=>new Gy(tt(t))},{kind:"mysql",create:t=>new Ky({connection:tt(t)})},{kind:"doris",create:t=>new Fy({connection:tt(t)})},{kind:"gbase",create:t=>new zy({connection:tt(t)})},{kind:"starrocks",create:t=>new ch({connection:tt(t)})},{kind:"maxcompute",create:t=>new Wy(tt(t))},{kind:"postgresql",create:t=>new Zy({connection:tt(t)})},{kind:"clickhouse",create:t=>new Dy(tt(t))},{kind:"databricks",create:t=>new qy({connection:tt(t)})},{kind:"dameng",create:t=>new xy({connection:tt(t)})},{kind:"snowflake",create:t=>new th({connection:tt(t)})},{kind:"sqlserver",create:t=>new ah({connection:tt(t)})},{kind:"oracle",create:t=>new Xy({connection:tt(t)})}]);class Au{#e=new Map;constructor(e=uh){e.forEach(r=>this.register(r))}register(e){if(!e.kind)throw new l("INVALID_PROVIDER","Provider kind must not be empty");if(this.#e.has(e.kind))throw new l("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 l("PROVIDER_NOT_FOUND",`Provider is not registered: ${e.kind}`,{provider:e.kind});return r.create(e)}has(e){return this.#e.has(e)}}const $u=new Au,Eu=(t,e=$u)=>e.create(t);class dh{create;#e=new Map;#t=new Set;#r=[];constructor(e=Eu){this.create=e}get(e){const r=this.#e.get(e.id);if(r&&Ro(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 wo=new Map,ph=t=>{const e=wo.get(t);if(e)return e;const r=new dh(n=>Eu(n,t));return wo.set(t,r),r},An=(t,e=$u)=>ph(e).get(t),lh=async()=>{const t=[...wo.values()];wo.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")},as=(t,e)=>{if(!Number.isSafeInteger(t)||t<=0)throw new l("INVALID_FILE_IMPORT",`${e} must be a positive safe integer`);return t},fh=(t,e="auto")=>{let r;if(e!=="auto"?r=e:t[0]===255&&t[1]===254?r="utf-16le":t[0]===254&&t[1]===255?r="utf-16be":r="utf-8",!["utf-8","gbk","gb18030","utf-16le","utf-16be"].includes(r))throw new l("UNSUPPORTED_CSV_ENCODING",`Unsupported CSV encoding: ${r}`);try{const n=new TextDecoder(r,{fatal:!0}).decode(t);if(n.includes("\0"))throw new Error("CSV contains NUL characters");return{text:n,encoding:r}}catch{throw new l(e==="auto"?"CSV_ENCODING_REQUIRED":"INVALID_CSV_ENCODING",e==="auto"?"CSV is not valid UTF-8/BOM-marked Unicode. Specify csv.encoding (e.g. gbk or gb18030).":`CSV cannot be decoded strictly as ${r}`)}},Iu=t=>{const e=t.value;if(e===null||typeof e!="object"||e instanceof Date)return e;if("formula"in e||"sharedFormula"in e){if(e.result===void 0)throw new l("EXCEL_FORMULA_RESULT_REQUIRED",`Formula at ${t.address} has no saved result; recalculate and save the workbook first`);if(typeof e.result=="object"&&!(e.result instanceof Date))throw new l("INVALID_EXCEL_CELL",`Excel error at ${t.address}`);return e.result}if("richText"in e)return e.richText.map(({text:r})=>r).join("");if("hyperlink"in e)return e.text;throw new l("INVALID_EXCEL_CELL",`Unsupported Excel cell at ${t.address}`)},_u=async t=>{t.signal?.throwIfAborted();const e=as(t.maxBytes??50*1024*1024,"maxBytes"),r=as(t.maxRows??1e5,"maxRows"),n=t.file.format??("path"in t.file?Hu(t.file.path).slice(1).toLowerCase():void 0);if(n!=="csv"&&n!=="xlsx")throw new l("UNSUPPORTED_IMPORT_FILE","Only .xlsx and .csv files are supported");if(n==="csv"&&t.excel||n==="xlsx"&&t.csv)throw new l("INVALID_FILE_IMPORT","Parser options must match the file format");if("path"in t.file&&(await zu(t.file.path)).size>e)throw new l("IMPORT_FILE_TOO_LARGE",`File exceeds ${e} bytes`);const o="path"in t.file?await Ss(t.file.path,{signal:t.signal}):t.file.data;if(o.byteLength>e)throw new l("IMPORT_FILE_TOO_LARGE",`File exceeds ${e} bytes`);let i,s,a;if(n==="csv"){const p=fh(o,t.csv?.encoding);s=p.encoding;const f=t.csv?.delimiter??",";if(![",",";"," ","|"].includes(f))throw new l("INVALID_FILE_IMPORT","Unsupported CSV delimiter");i=Ku(p.text,{delimiter:f,skip_empty_lines:!0,relax_column_count:!1})}else{const p=new Ju.Workbook;await p.xlsx.load(Buffer.from(o));const f=t.excel?.sheet!==void 0?p.getWorksheet(t.excel.sheet):p.worksheets[0];if(!f)throw new l("EXCEL_SHEET_NOT_FOUND","Requested worksheet was not found");a=f.name;const m=as(t.excel?.headerRow??1,"headerRow");if(f.rowCount-m>r)throw new l("IMPORT_ROW_LIMIT",`File exceeds ${r} rows`);const h=f.getRow(m),y=h.cellCount;i=[Array.from({length:y},($,w)=>Iu(h.getCell(w+1)))];for(let $=m+1;$<=f.rowCount;$++){t.signal?.throwIfAborted();const w=f.getRow($);for(let N=1;N<=w.cellCount;N++){const I=w.getCell(N);if(I.isMerged&&I.master.address!==I.address)throw new l("INVALID_EXCEL_CELL",`Merged data cell at ${I.address}; upload a flat table`);if(N>y&&I.value!==null)throw new l("IMPORT_COLUMN_MISMATCH",`Unexpected data column at ${I.address}`)}const E=Array.from({length:y},(N,I)=>Iu(w.getCell(I+1)));E.some(N=>N!==null&&N!=="")&&i.push(E)}}t.signal?.throwIfAborted();const[u,...c]=i;if(!u?.length)throw new l("IMPORT_HEADER_REQUIRED","File must contain a header row");const d=u.map(p=>{if(typeof p!="string"||!p.trim())throw new l("INVALID_IMPORT_HEADER","Column names must be non-empty text");return p.trim()});if(new Set(d.map(p=>p.toLowerCase())).size!==d.length)throw new l("INVALID_IMPORT_HEADER","Duplicate column names are not allowed");if(c.length>r)throw new l("IMPORT_ROW_LIMIT",`File exceeds ${r} rows`);return{format:n,...s?{encoding:s}:{},...a?{sheet:a}:{},columns:d,rows:c.map(p=>Object.fromEntries(d.map((f,m)=>[f,p[m]??null])))}},bu=async()=>{const e=(await Promise.allSettled([lh(),my()])).flatMap(r=>r.status==="rejected"?[r.reason]:[]);if(e.length>0)throw new AggregateError(e,"Failed to close one or more SemanticDB resources")},mh=async t=>{t.signal?.throwIfAborted();const e=An(t.connection,t.providerRegistry);if(!e.importRows)throw new l("UNSUPPORTED_FILE_IMPORT",`Provider does not support managed imports: ${e.kind}`);const r=await _u(t);if(r.columns.length!==t.columns.length||t.columns.some(({name:o})=>!r.columns.includes(o)))throw new l("IMPORT_COLUMN_MISMATCH","File headers must match the dataset columns exactly");return{...await e.importRows({table:t.table,columns:t.columns,rows:r.rows,batchId:t.batchId,...t.mode?{mode:t.mode}:{},...t.signal?{signal:t.signal}:{}}),format:r.format,...r.encoding?{encoding:r.encoding}:{},...r.sheet?{sheet:r.sheet}:{}}},yh=async t=>{if(t.signal?.throwIfAborted(),!t.sql.trim())throw new l("INVALID_SQL","SQL must not be empty");const e=An(t.connection,t.providerRegistry);if(!e.runSQL)throw new l("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},hh=async t=>{t.signal?.throwIfAborted(),qr(t);const e=An(t.connection,t.providerRegistry);if(!e.getTableList)throw new l("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},gh=async t=>{t.signal?.throwIfAborted(),yo(t);const e=An(t.connection,t.providerRegistry);if(!e.describeTable)throw new l("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},wh=Object.freeze({runSQL:yh,getTableList:hh,describeTable:gh,importFile:mh,close:bu}),Ah=t=>{const{name:e,kind:r}=t;switch(r){case"boolean":return{name:e,kind:r,type:bs,sqlType:"BOOLEAN"};case"date":return{name:e,kind:r,type:Oo,sqlType:"TIMESTAMP"};case"number":return{name:e,kind:r,type:_s,sqlType:"DOUBLE"};case"string":return{name:e,kind:r,type:lr,sqlType:"VARCHAR"}}},$h=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="true"?!0:t===0||t==="0"||t==="false"?!1:!!t,Eh=(t,e)=>{if(t==null)return null;switch(e.kind){case"boolean":return $t($h(t),bs);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:$t(r,Oo)}case"number":{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?$t(r,_s):null}case"string":return typeof t=="string"?$t(t,lr):typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?$t(t.toString(),lr):typeof t=="symbol"?$t(t.description??"",lr):typeof t=="function"?$t(t.name,lr):$t(JSON.stringify(t),lr)}};class bo extends is{instance;connection;static async create(){const e=await To.create(":memory:"),r=await e.connect();return new bo(e,r)}constructor(e,r){super(),this.instance=e,this.connection=r}async materialize(e,r,n){const o=r.map(Ah),i=o.map(a=>`${this.quoteIdentifier(a.name)} ${a.sqlType}`).join(", ");await this.connection.run(`CREATE TABLE ${this.quoteIdentifier(e)} (${i})`);const s=await this.connection.createAppender(e);try{for(const a of n){for(const u of o){const c=Eh(a[u.name],u);c===null?s.appendNull():s.appendValue(c,u.type)}s.endRow()}s.flushSync()}finally{s.closeSync()}}async execute(e){e.signal?.throwIfAborted();const r=await this.connection.runAndReadAll(e.sql,e.parameters.map(n=>pu(n,"DuckDB coordinator")));return e.signal?.throwIfAborted(),r.getRowObjectsJS()}close(){return this.connection.closeSync(),this.instance.closeSync(),Promise.resolve()}}const cs="__sdb_total__",Ih="__sdb_total_source__",us=t=>{const e={...t,orderBy:[]};return delete e.pagination,e},_h=t=>{const e={...t};return delete e.limit,delete e.page,e},ds=(t,e)=>({sql:`SELECT ${e.aggregateFunction("count")} AS ${e.quoteIdentifier(cs)} FROM ${e.tableAlias(`(${t.sql})`,Ih)}`,parameters:t.parameters}),Ao=t=>{if(t.length===0)return 0;const e=t[0]??{},r=e[cs]??e[cs.toUpperCase()]??Object.values(e)[0],n=typeof r=="number"?r:Number(r);if(!Number.isSafeInteger(n)||n<0)throw new l("INVALID_TOTAL_RESULT","The total query must return a non-negative safe integer",{total:r});return n},$n="__semanticdb_coordinator__",Su=(t,e)=>{const r=new Set;for(const n of ke(t)){const o=Ur(n,e);if(!o)throw new l("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]},En=(t,e)=>!!t.subplans&&new Set(t.subplans?.flatMap(r=>Su(r,e))).size>1||!!(t.sourcePlan&&En(t.sourcePlan,e)),bh=(t,e)=>({name:t,expression:{kind:"column",property:t,column:t,qualifier:e}}),Sh=(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"},Nu=(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"?Sh(e,n):"string";return{name:n,kind:i}})},Nh=(t,e)=>{const r=t.projections.map(({name:n})=>n);return{schemaId:t.schemaId,source:rt({kind:"table",table:e}),sourceAlias:e,fields:Object.fromEntries([...r,"_id"].map(n=>[n,n])),projections:[...r,"_id"].map(n=>bh(n,e)),...t.columnProperties?{columnProperties:t.columnProperties}:{},groupBy:[],orderBy:[],rowIdentity:{kind:"generated"}}},Rh=(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",ro(i)]:["object",JSON.stringify(i)]:[typeof i,i]}))}))}if(e.rowIdentity.kind==="singleton")return t.map(r=>({...r,_id:"0"}));throw new l("UNSTABLE_FEDERATED_IDENTITY","A federated composition branch must be grouped or aggregate to a singleton row")},Ru=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:no(n,r.names,r.separator,r.nullLabel)}))}return e.rowIdentity.kind==="singleton"?t.map(r=>({...r,_id:"0"})):[...t]},$o=async(t,e)=>{if(!Number.isSafeInteger(e.maxMaterializedRows)||e.maxMaterializedRows<1)throw new l("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:e.maxMaterializedRows});if(t.sourcePlan&&En(t.sourcePlan,e.schemaMappings)){const s=await $o(t.sourcePlan,e),a=await bo.create();try{const u="__federated_source";await a.materialize(u,Nu(t.sourcePlan,s.rows),s.rows);const c={...t,source:rt({kind:"table",table:u})};delete c.sourcePlan,delete c.sourceLogicform,delete c.connectionId;const d=Oe(c,a,e.operators),p=ds(Oe(us(c),a,e.operators),a),f=e.onCompiled({compiled:d,sources:[],connectionId:$n,provider:a,type:"computation",logicform:e.logicform});e.onCompiled({compiled:p,sources:[],connectionId:$n,provider:a,type:"total",logicform:e.logicform})("database");const h=await a.execute({...p,...e.signal?{signal:e.signal}:{}});f("database");const y=await a.execute({...d,...e.signal?{signal:e.signal}:{}});return{rows:Ru(y,t),total:Ao(h),connections:s.connections}}finally{await a.close()}}if(!t.subplans||t.subplans.length<2)throw new l("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=Su(s,e.schemaMappings);if(a.length!==1)throw new l("CROSS_CONNECTION_FRAGMENT_UNSUPPORTED","A federated branch must compile completely on one physical connection",{schemaId:s.schemaId,connectionIds:a});const u=a[0],c=e.providerForConnection(u);r.set(u,c.kind);const d=Oe(s,c,e.operators),p=ke(s),f=e.onCompiled({compiled:d,sources:p,connectionId:u,provider:c,type:"computation",logicform:e.logicform}),m=await Zi(d,p,{provider:c,connectionId:u,schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}},f),h=t.rowPartition?m.map((y,$)=>({...y,_id:String($)})):Rh(m,s);return{child:s,rows:h}})),o=n.reduce((s,a)=>s+a.rows.length,0);if(o>e.maxMaterializedRows)throw new l("FEDERATED_RESULT_LIMIT_EXCEEDED",`Federated execution materialized ${o} rows; maximum is ${e.maxMaterializedRows}`,{materializedRowCount:o,maxMaterializedRows:e.maxMaterializedRows});const i=await bo.create();try{const s=n.flatMap(({rows:y})=>y),a=[];for(const[y,{child:$,rows:w}]of n.entries()){const E=`__federated_branch_${y}`;await i.materialize(E,Nu($,s),w),a.push(Nh($,E))}const u={...t,subplans:a},c=Oe(u,i,e.operators),d=ds(Oe(us(u),i,e.operators),i),p=e.onCompiled({compiled:c,sources:[],connectionId:$n,provider:i,type:"computation",logicform:e.logicform});e.onCompiled({compiled:d,sources:[],connectionId:$n,provider:i,type:"total",logicform:e.logicform})("database");const m=await i.execute({...d,...e.signal?{signal:e.signal}:{}});p("database");const h=await i.execute({...c,...e.signal?{signal:e.signal}:{}});return{rows:Ru(h,t),total:Ao(m),connections:[...r].map(([y,$])=>({connectionId:y,provider:$}))}}finally{await i.close()}},Ou=t=>{const e={...t};return delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,delete e.sample,e},Oh=new Set(["$gt","$gte","$lt","$lte"]),ps=t=>Object.entries(t).flatMap(([e,r])=>e==="$and"&&Array.isArray(r)?r.flatMap(n=>ps(n)):[{[e]:r}]),Th=(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=>!Oh.has(i))))return;const n={};for(const o of["lower","upper"]){const i=o==="lower"?["$gt","$gte"]:["$lt","$lte"],s=r.flatMap(c=>i.flatMap(d=>c[d]===void 0?[]:[{key:d,value:c[d]}]));if(s.some(({value:c})=>typeof c!="string"&&!(c instanceof Date)))return;const u=s.reduce((c,d)=>{if(!c)return d;const p=c.value instanceof Date?c.value.toISOString():c.value,f=d.value instanceof Date?d.value.toISOString():d.value;return p===f?d.key===(o==="lower"?"$gt":"$lt")?d:c:o==="lower"?f>p?d:c:f<p?d:c},void 0);u&&(n[u.key]=u.value)}return n},Tu=(t,e)=>{const r=[...t?ps(t):[],...ps(e)],n=[];for(const i of r){const[s]=Object.entries(i);if(!s)continue;const[a,u]=s,c=n.findIndex(d=>Object.keys(d).length===1&&a in d);if(c>=0){const d=n[c],p=Th(d[a],u);if(p){n[c]={[a]:p};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}},Pu=(t,e,r)=>{if(e.length===0)throw new l("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 l("INVALID_SCHEMA_PARTITION",`Schema ${t.id} partition shard ${n} requires a query and mappingCandidates`);for(const u of o.mappingCandidates)if(typeof u!="string"||!r.findById(t.id,u))throw new l("INVALID_SCHEMA_PARTITION",`Schema ${t.id} partition shard ${n} references unknown mapping ${u}`)}},ls=t=>{const e=t.preds;return!t.groupby?.length&&!!e?.length&&e.every(r=>!r.operator&&typeof r.pred=="string")},Lu=t=>{if(!ls(t)&&(!t.preds?.length||t.preds.some(e=>e.operator!=="$sum")))throw new l("UNSUPPORTED_SCHEMA_PARTITION_AGGREGATE","Schema partition supports $sum PredItems or ungrouped Property projections")},fs=(t,e,r,n,o,i,s)=>{if(Lu(t),s&&Lu(s.logicform),t.limitBy!==void 0||s?.logicform.limitBy!==void 0)throw new l("UNSUPPORTED_SCHEMA_PARTITION_LIMIT_BY","Schema partition does not support limitBy");Pu(e,r,o);const a=[],u=[],c=[];let d,p;for(const[$,w]of r.entries()){const E=Tu(t.query,w.query),N={...t,query:E},I=s?{...s.logicform,query:s.queryForCurrentShard(E)}:void 0;let S;const D=[],b=[];for(const M of w.mappingCandidates){const Y={...i,mappingCandidates:[M]};try{const C=Me(Ou(N),e,n,o,Y),O=I?Me(Ou(I),e,n,o,Y):void 0;S={mappingId:M,current:C,...O?{comparison:O}:{}};break}catch(C){if(!(C instanceof l)||C.code!=="QUERY_NOT_COVERED_BY_DATA_SOURCE")throw C;D.push(`${M}: ${JSON.stringify(C.details?.rejectedMappings??[])}`);const O=C.details?.uncoveredDimensions;b.push(Array.isArray(O)?O.filter(L=>typeof L=="string"):[])}}if(!S){const M=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id,Y=b.length===w.mappingCandidates.length&&b.every(C=>C.length>0)?[...new Set(b.flat())]:[];throw new l("SCHEMA_PARTITION_MAPPING_NOT_FOUND",Y.length>0?s?`Schema\u300C${M}\u300D\u7684\u7B2C${$+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${Y.join("\u3001")}\u3011\u3002`:`Schema\u300C${M}\u300D\u7684\u7B2C${$+1}\u4E2A\u6570\u636E\u5206\u7247\u6CA1\u6709\u6570\u636E\u8868\u80FD\u5B8C\u6574\u8986\u76D6\u7EF4\u5EA6\u3010${Y.join("\u3001")}\u3011\u3002`:s?`Schema\u300C${M}\u300D\u7684\u7B2C${$+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${M}\u300D\u7684\u7B2C${$+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:M,shardIndex:$,...s?{comparison:!0}:{},...Y.length>0?{uncoveredDimensions:Y}:{},reasons:D})}const T={...i,mappingCandidates:[S.mappingId]};d??=Me(N,e,n,o,T),I&&(p??=Me(I,e,n,o,T)),a.push(S.current),S.comparison&&u.push(S.comparison),c.push(S.mappingId)}const f=d,m=ls(t),h=a.length===1?f:m?{...f,subplans:a,rowPartition:!0,rowIdentity:{kind:"generated"}}:{...f,subplans:a,sumPartition:!0},y=p?u.length===1?p:{...p,subplans:u,sumPartition:!0}:void 0;return{current:h,...y?{comparison:y}:{},mappingIds:c}},Ph=t=>{const e=new Map;for(const r of t)for(const n of r){const o=n._id;if(o==null)throw new l("MERGE_BY_ID_REQUIRED","mergeByID requires every row to have an _id");e.set(o,{...e.get(o)??{},...n})}return[...e.values()]},Lh=new Set(["execute","schemas","getSchema","getProperty","signal","locale","now","log","md5","fetch","dayjs","moment","mergeByID","config"]),ms=(t,e)=>!!(t.operator&&e.get(t.operator).kind==="runtime"),Ch=(t,e)=>[...t.preds??[],...t.groupby??[]].some(r=>In(r,e)),In=(t,e)=>ms(t,e)?!0:t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?In(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&In(r,e)),Dh=t=>{const e={...t};return delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,delete e.sample,e},Mh=(t,e,r)=>{const n=Array.isArray(t)?t:[t];if(Array.isArray(t)&&r.length===0&&t.length>1)throw new l("INVALID_RUNTIME_RESULT",`Ungrouped runtime metric ${e} returned multiple rows`);return n.map(o=>{const i=o!==null&&typeof o=="object"&&!Array.isArray(o)?{...o}:{[e]:o};if(!(e in i))throw new l("INVALID_RUNTIME_RESULT",`Runtime metric ${e} did not return its output column`);for(const s of r)if(!(s in i))throw new l("INVALID_RUNTIME_RESULT",`Runtime metric ${e} did not return group key ${s}`);for(const s of Object.keys(i))if(s!==e&&s!=="_id"&&!r.includes(s))throw new l("INVALID_RUNTIME_RESULT",`Runtime metric ${e} returned unexpected column ${s}`);return delete i._id,i})},ys=(t,e)=>JSON.stringify(e.map(r=>t[r])),Cu=(t,e)=>t.map(r=>({...r,_id:ys(r,e)})),Du=(t,e)=>{if(t){for(const[r,n]of Object.entries(t))if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new l("INVALID_HAVING",`${r} must be an array`);for(const o of n)Du(o,e)}else if(!e.has(r))throw new l("INVALID_HAVING",`Having field is not an output: ${r}`)}},kh=async(t,e,r,n)=>{e.signal?.throwIfAborted();const o=e.plugins??[],i=e.locale??"zh-CN",s=zr([...Pe(o).flatMap(k=>k.locales??[]),...e.locales===void 0?[]:"locale"in e.locales?[e.locales]:e.locales]),a=t.version,u=a===void 0||typeof a=="string"&&/^1\./.test(a);u||ga(t);const c=Wo(e.schemas,o,u),d=u?jn(t,c):t;if(!d.schema||d.from)throw new l("UNSUPPORTED_RUNTIME_FORM","Runtime metrics require a physical Schema leaf");const p=e.semanticTypes?ii(e.semanticTypes,o):Mt(o),f=Object.fromEntries(Object.keys(c).map(k=>[k,Bn(Ko(k,c),p,o)])),m=k=>{Ye(e.permissions,k);const g=f[k];if(!g)throw new l("SCHEMA_NOT_FOUND",`Schema not found: ${k}`);return Yc(e.permissions,()=>g,[k]),Gc(g,e.permissions,r),g},h=m(d.schema);ar(d,e.permissions,m,r);const y=Bt(d,e.permissions,m,!0,new Set,o,r),$=new Date,w=await Rt(y,h,{semanticTypes:p,operators:r,plugins:o,locale:i,localeRegistry:s,now:$,resolveSchema:m,canProjectProperty:(k,g)=>Ot(e.permissions,k.id,g)});if(ar(w,e.permissions,m,r),w.sample)throw new l("INVALID_SAMPLE","sample is not supported with runtime metrics");const E=Mr(w,h,m,y);if(w.output?.type==="sql")throw new l("UNSUPPORTED_OUTPUT","SQL output is not available for runtime metrics");for(const k of Object.keys(e.runtimeHelpers??{}))if(Lh.has(k))throw new l("RESERVED_RUNTIME_HELPER",`Runtime helper name is reserved: ${k}`);const N=w.preds,I=N.filter(k=>ms(k,r)),S=N.filter(k=>!ms(k,r));if(I.length===0)throw new l("INVALID_RUNTIME_FORM","No runtime projection found");if((w.groupby??[]).some(k=>In(k,r))||S.some(k=>In(k,r)))throw new l("UNSUPPORTED_RUNTIME_NESTING","Runtime operators must be top-level metrics");const D=(w.groupby??[]).map(({name:k})=>k??"");if((w.groupby??[]).some(({pred:k})=>typeof k!="string"))throw new l("UNSUPPORTED_RUNTIME_GROUPBY","Runtime metrics require direct Property group keys");const b=(w.groupby??[]).map(k=>{const g=ne(h,k.pred,m);return{...g.property,name:k.name??g.property.name,formulaText:en(g.property.formulaText===void 0?g.canonicalName:g.property.formulaText)}}),T=(k,g=h)=>{const A=k.schema?m(k.schema):g,_=typeof k.pred=="string"?(()=>{const P=ne(A,k.pred,m);return en(P.property.formulaText===void 0?P.canonicalName:P.property.formulaText)})():k.pred&&!Array.isArray(k.pred)?T(k.pred,A):void 0;return k.operator?La(r.get(k.operator),{schema:A,executionContext:r.executionContext,..._===void 0?{}:{input:_},inputs:Array.isArray(k.pred)?k.pred.map(P=>T(typeof P=="string"?{pred:P}:P,A)):[],args:k.args??{}}):_===void 0?null:_},M=I.map(k=>{const g=r.get(k.operator??""),A=k.name??"",_=typeof k.pred=="string"?ne(k.schema?m(k.schema):h,k.pred,m).property:void 0,P=g.getOutputProperty?.({semanticTypes:p,name:A,..._?{property:_}:{},args:k.args??{},executionContext:r.executionContext})??{name:A,type:_?.type??"number",primal_type:_?.primal_type??"number",isArray:!1};return{...P,name:A,formulaText:T(k),...P.description?{}:g.description?{description:g.description}:{}}}),Y={...Dh(d),preds:S},{onProgress:C,...O}=e,L=S.length>0?await n(Y,{...O,result_only:!0}):void 0;if(L&&"errorCode"in L)throw new l("RUNTIME_SQL_COMPONENT_FAILED",L.error);const q=[...L?L.schema.properties:b,...M],Q=new Set;for(const k of q){if(!k.name||k.name==="_id"||Q.has(k.name))throw new l("DUPLICATE_OUTPUT_NAME",`Duplicate result column: ${k.name}`);Q.add(k.name)}const j={id:`result:${h.id}:${q.map(k=>`${k.name}:${k.type}`).join("|")}`,name:`${h.name} result`,type:h.type,temporalSemantics:"normal",properties:q.map(Ri)};async function oe(k,g){e.signal?.throwIfAborted();const A=await n(k,{...O,result_only:g?.result_only===!0});if("errorCode"in A)throw new l("RUNTIME_CHILD_EXECUTION_FAILED",A.error);return g?.result_only===!0?A.result:A}const H={...e.runtimeHelpers,execute:oe,mergeByID:Ph,schemas:f,getSchema:m,getProperty:(k,g)=>Ea(m(k),g),...e.signal?{signal:e.signal}:{},locale:i,now:$,log:(...k)=>console.log(...k),md5:k=>Sn("md5").update(k).digest("hex"),fetch:globalThis.fetch,dayjs:he,moment:he},R=[];L&&R.push(Cu(L.result,D));for(const k of I){e.signal?.throwIfAborted();const g=r.get(k.operator??"");if(g.kind!=="runtime")throw new l("INVALID_RUNTIME_FORM","Runtime projection is not a runtime operator");const A={...e,...e.runtimeConfig,...k,result_only:!0,pred:k,locale:i,...e.signal?{signal:e.signal}:{}},_={...H,config:A},P=await g.run(E,h,A,_);e.signal?.throwIfAborted();const B=Mh(P,k.name??"",D),X=new Set;for(const Z of B){const V=ys(Z,D);if(X.has(V))throw new l("DUPLICATE_RUNTIME_GROUP",`Runtime metric ${k.name} returned a duplicate group`);X.add(V)}R.push(Cu(B,D))}Du(w.having,Q);const x=Object.entries(w.sort??{}).map(([k,g])=>{const A=g;if(!Q.has(k)||A!==1&&A!==-1)throw new l("INVALID_SORT",`Invalid sort field or direction: ${k}`);return{name:k,direction:g===1?"ASC":"DESC"}}),F=D.map(k=>({name:k,expression:{kind:"column",property:k,column:k}})),G=w.limitBy===void 0?void 0:{count:w.limitBy,partitionBy:D.slice(0,-1),orderBy:x.length>0?x:[{name:D[D.length-1],direction:"ASC"}]},ee={groupBy:F,...w.having?{having:w.having}:{},...G?{groupLimit:G}:{},orderBy:x,...w.limit===void 0?{}:{pagination:w.limit>0&&w.limit<1?{kind:"ratio",page:w.page,ratio:w.limit}:{kind:"rows",page:w.page,pageSize:w.limit}}},{pagination:ue,...Ee}=ee,Ge=dn(R,Ee).length,Ze=dn(R,ee),ze=await Wi(Ze,q,{now:$,semanticTypes:p,plugins:o,resolveSchema:m,expandEntities:e.result_only!==!0,fetchEntities:async k=>{const{schema:g,idProperty:A,ids:_}=k,P=await n({version:w.version,schema:g.id,...Kc(k,{[A.name]:{$in:_}}),preds:g.properties.filter(B=>Ot(e.permissions,g.id,B)).map(B=>({pred:B.name,name:B.name}))},{...O,result_only:!0});if("errorCode"in P)throw new l("RUNTIME_ENTITY_FETCH_FAILED",P.error);return P.result}}),v=oo(ze.map(({_id:k,...g})=>g),D.length>0?{kind:"group",names:D,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"}),Ae=new Map;for(const k of v){const g=String(k._id);Ae.set(g,(Ae.get(g)??0)+1)}const Le=v.map(k=>Ae.get(String(k._id))===1?k:{...k,_id:ys(k,D)}),$e={source:{schemaId:h.id,schemaName:h.name,physicalTable:L?.lineage.source.physicalTable??"",provider:"runtime"},outputs:[...L?.lineage.outputs??[],...M.map(k=>({name:k.name,sources:[],transformations:[I.find(g=>g.name===k.name)?.operator??"runtime"]}))],filters:L?.lineage.filters??[]},We={result:Le,total:Ge,schema:j,normedLogicform:E,sqls:L?.sqls??[],lineage:$e,...w.output&&w.output.type!=="data"?await(async()=>{const k=kn(w.output?.type??"",o);return k?{output:await k.handle({rows:Le,logicform:E,schema:j})}:{}})():{}};return await e.onProgress?.({stage:"result",result:Le,partialResult:We}),We},Uh=t=>t instanceof Date?t.getTime():t,qh=(t,e,r)=>{for(const n of r){const o=a=>{if(!n.comparable||a===null||a===void 0)return Uh(a);const u=n.comparable.values.indexOf(typeof a=="string"||typeof a=="number"?String(a):"");return u<0?null:n.comparable.direction*u},i=o(t[n.name]),s=o(e[n.name]);if(i!==s){if(i==null)return 1;if(s==null)return-1;if(i<s)return n.direction==="ASC"?-1:1;if(i>s)return n.direction==="ASC"?1:-1}}return 0},Mu=(t,e,r)=>{const n=new Map;for(const u of t){const c=u._id;if(typeof c!="string"&&typeof c!="number")throw new l("INVALID_SAMPLE_ID","Sampled entity row must have a scalar ID");const d=`${typeof c}:${String(c)}`;n.has(d)||n.set(d,u)}const o=[...n.entries()],i=o.length,s=Math.min(e,i);for(let u=0;u<s;u+=1){const c=Vu(u,i),d=o[u],p=o[c];if(!d||!p)throw new l("INVALID_SAMPLE","Sample index is out of range");o[u]=p,o[c]=d}const a=o.slice(0,s).map(([,u])=>u);return r.length>0&&a.sort((u,c)=>qh(u,c,r)),{rows:a,total:i}},ku=(t,e,r)=>{if(!r)return t;const{minFactor:n=.1,maxFactor:o=1.5}=r===!0?{}:r,i=new Set(["_id",...e.groupBy.map(({name:a})=>a)]);e.rowIdentity.kind==="property"&&(i.add(e.rowIdentity.column),i.add(e.rowIdentity.internalName));const s=(e.columnProperties??[]).filter(a=>a.primal_type==="number"&&!a.isArray&&a.type!=="ID"&&!a.ref&&!i.has(a.name)).map(({name:a})=>a);return t.map(a=>{const u={...a};for(const c of s){const d=a[c];if(typeof d!="number"&&typeof d!="bigint"&&!(typeof d=="string"&&d.trim()!==""))continue;const p=Number(d);if(!Number.isFinite(p))continue;const f=n===o?n:n+Math.random()*(o-n),m=p*f;if(!Number.isFinite(m))throw new l("RANDOM_DATA_OVERFLOW",`randomData overflow in column ${c}`);u[c]=m}return u})},Uu=(t,e)=>[...Pe(t).flatMap(r=>r.locales??[]),...e===void 0?[]:"locale"in e?[e]:e],Eo=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}:{}}),qu=t=>t instanceof Error?t:new Error(String(t)),jh=(t,e="zh-CN",r)=>t instanceof l?t.localizedMessage(e,r):t.message,xh=(t,e,r={},n="zh-CN",o)=>{const i=qu(t);return{errorCode:"100",error:jh(i,n,o),result:[],...r.schema?{schema:r.schema}:{},normedLogicform:r.normedLogicform??e,sqls:r.sqls??[],...r.lineage?{lineage:r.lineage}:{}}},Vh=(t,e,r)=>{const n=e.projections.map(({name:c})=>c),o=new Map((e.columnProperties??[]).map(c=>[c.name,c])),i=[],s=(c,d)=>{const p=r.parameter(i.length,d);i.push(d);const f=o.get(c)?.type;return f&&(f==="date"||f==="timestamp")&&r.castValue?r.castValue(p,f):p},a=c=>`SELECT ${n.map(d=>`${s(d,c[d])} AS ${r.quoteIdentifier(d)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""}`;return{sql:t.length>0?t.map(a).join(" UNION ALL "):`SELECT ${n.map(c=>`NULL AS ${r.quoteIdentifier(c)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""} WHERE 1 = 0`,parameters:i}},Fh=(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),...ke(r)];for(const i of o){const s=Ur(i,e);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},Bh=async(t,e,r)=>{await t?.({...e,partialResult:r})},Hh=(t,e,r,n,o,i,s=r,a,u=[])=>({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:u,sql:t.sql,parameters:[...t.parameters],displaySql:e.displayQuery(t.sql,t.parameters)}),hs=(t,e)=>{if(e.connectionId)for(const r of ke(t)){const n=Ur(r,e.schemaMappings);if(!n)throw new l("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 l("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})}},ju=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 gs(o))e.add(i)};return r(t),[...e]},gs=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...gs(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:gs(r))]:e},ws=async(t,e)=>{const r=e.locale??"zh-CN",n=e.localeRegistry??zr(Uu(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&&ga(t);const u=a?jn(t,e.schemas):t,c=e.schemaMappings.definitions(),d=ju(u),p=[...new Set(c.filter(({schemaId:g})=>d.includes(g)).map(({connectionId:g})=>g))],f=e.connectionId??(p.length===1?p[0]:void 0)??e.provider.kind,m=a?$a(e.schemas,c,f,d):c,h=m.length===c.length?e.schemaMappings:new Dt(m,e.schemaMappings.plugins.filter(g=>!hr.includes(g))),y={...e,locale:r,localeRegistry:n,schemaMappings:h,schemas:Wo(e.schemas,o,a)},$=Rn.now(),w=y.semanticTypes===void 0?Mt(o):y.semanticTypesResolved?y.semanticTypes:ii(y.semanticTypes,o);let E=y.operators??at(o);if(y.operators&&!y.operatorsResolved)for(const g of o)for(const A of g.operators??[])if(E.has(A.name)){if(E.get(A.name)!==A)throw new l("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${A.name}`,{operator:A.name,plugin:g.name})}else E.register(A);const N=y.schemaMappings,I=g=>ke(g).some(A=>Aa(Ur(A,N))),S=new Date,D=new Map,b=new Map;let T={};const M=[],Y=new WeakMap,C=g=>{const A=new Map;for(const _ of g){const P=Ur(_,N);if(!P)continue;const B=It(P);A.set(JSON.stringify([P.schemaId,P.connectionId,B]),{schemaId:P.schemaId,mappingId:B,connectionId:P.connectionId,source:lt(P.source)})}return[...A.values()]},O=(g,A,_,P=A,B=y.provider,X=y.connectionId,Z)=>{const V=M.length;M.push(Hh(nu(g),B,A,Mr(_,R(_),H),y.locale??"zh-CN",n,P,X,C(Z))),T={...T,sqls:[...M]};const z=K=>{M[V]={...M[V],executionSource:K},T={...T,sqls:[...M]}};return Y.set(g,z),z},L=(g,A)=>Zi(g,A,y,Y.get(g)),q=async(g,A={})=>{T={...T,...A},await Bh(y.onProgress,g,T)},Q=new Set,j=g=>{const A=Bn(Ko(g,y.schemas),w,o);return Q.has(g)||(Yc(y.permissions,()=>A,[g]),Gc(A,y.permissions,E),Q.add(g)),A},oe=new Map,H=g=>{const A=oe.get(g);return A||(Ye(y.permissions,g),j(g))},R=g=>{if(g.schema)return H(g.schema);if(g.from)return R(g.from);throw new l("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},x=g=>{if(g.schema)return j(g.schema);if(g.from)return x(g.from);throw new l("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},F=async()=>{const g=Object.values(y.schemas).filter(K=>K.is_calendar===!0);if(g.length!==1)return Object.freeze({});const A=g[0];if(!A)return Object.freeze({});const _=N.list(A.id),P=_.find(({connectionId:K})=>K===y.connectionId)??_[0];if(!P)throw new l("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${A.id}`,{schemaId:A.id});if(Aa(P))return Object.freeze({calendar:Object.freeze([])});const B=y.providerForConnection?.(P.connectionId)??y.provider,{onProgress:X,executionContext:Z,...V}=y,z=await ws({version:"2.0",schema:A.id,limit:-1},{...V,provider:B,connectionId:P.connectionId,operators:E,operatorsResolved:!0,executionContext:Object.freeze({})});return M.push(...z.sqls.map(K=>({...K,type:"semantic-resolution",explain:n.translate(y.locale??"zh-CN","sql.semanticResolution")}))),Object.freeze({calendar:Object.freeze(z.result.map(({_id:K,...ie})=>Object.freeze(ie)))})},G=e.executionContext??await F();E=E.withExecutionContext(G);const ee=new Map,ue={semanticTypes:w,plugins:o,preplannedPartitions:ee,authorizeLogicform:g=>ar(g,y.permissions,H,E),authorizeComputationInput:(g,A)=>{sr({schema:g.id,preds:[{pred:A}]},y.permissions,H,o);const _=ne(g,A,H);for(const P of _.relations)if(Ye(y.permissions,P.targetSchema.id)?.rowPermissions!==void 0)throw new l("COMPUTATION_RELATED_ROW_PERMISSIONS_UNSUPPORTED",`Computation input ${A} requires related row permissions; use a permission-filtered source Mapping`,{schemaId:P.targetSchema.id,reference:A})},resolveSchema:H,...y.connectionId?{preferredConnectionId:y.connectionId}:{},canUsePropertyRowIdentity:(g,A)=>Ot(y.permissions,g.id,A)},Ee=async(g,A)=>{const _=await v(g,R(g));return ee.set(JSON.stringify(g),_),cc(_,A)},Ge=async(g,A,_)=>{const P=`${g.id}:${A.id}:${_.toISOString()}`,B=D.get(P);if(B)return B;const X=(async()=>{const Z=Pe(o).find(re=>re.createTimeWatermarkLogicform)?.createTimeWatermarkLogicform;if(!Z)return;const V=Z({logicform:u,rootSchema:g,rootProperty:A,requestedUpperBound:_,now:S,...y.timeWatermark?{defaultPolicy:y.timeWatermark}:{},resolveSchema:H,inferPropertyPath:(re,pe,de)=>Vc(re,pe,de,H)}),z=Bt(V,y.permissions,H,!1,new Set,o),K=await Rt(z,g,{semanticTypes:w,operators:E,plugins:o,now:S,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,resolveFromSchema:Ee}),ie=Me(K,g,E,N,ue);if(I(ie))return;let me;if(En(ie,N)){const re=y.providerForConnection;if(!re)throw new l("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated timeWatermark resolution requires a provider resolver");me=(await $o(ie,{logicform:K,operators:E,schemaMappings:N,providerForConnection:re,maxMaterializedRows:y.federation?.maxMaterializedRows??1e5,...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:({compiled:de,sources:ye,logicform:Ce,provider:De,connectionId:Ke})=>O(de,"semantic-resolution",Ce,"time-watermark",De,Ke,ye)})).rows}else{hs(ie,y);const re=Oe(ie,y.provider,E),pe=ke(ie);O(re,"semantic-resolution",K,"time-watermark",y.provider,y.connectionId,pe),me=await L(re,pe)}const W=me[0]?.__timeWatermark__??Object.values(me[0]??{})[0];if(W==null||!(W instanceof Date)&&typeof W!="string"&&typeof W!="number")return;const J=W instanceof Date?W:new Date(W);return Number.isNaN(J.getTime())?void 0:J})();return D.set(P,X),X},Ze=async(g,A,_)=>{const P=JSON.stringify([g.id,A,_??null]),B=b.get(P);if(B)return B;const X=(async()=>{const Z={version:"2.0",schema:g.id,..._?{query:_}:{},preds:[{name:"__autoCaseMin__",operator:"$min",pred:A},{name:"__autoCaseMax__",operator:"$max",pred:A},{name:"__autoCaseCount__",operator:"$count",pred:A}]},V=await Rt(Z,g,{semanticTypes:w,operators:E,plugins:o,now:S,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,resolveFromSchema:Ee}),z=Me(V,g,E,N,ue);if(I(z))return{empty:!0};let K;if(En(z,N)){const ye=y.providerForConnection;if(!ye)throw new l("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated automatic bucket resolution requires a provider resolver");K=(await $o(z,{logicform:V,operators:E,schemaMappings:N,providerForConnection:ye,maxMaterializedRows:y.federation?.maxMaterializedRows??1e5,...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:({compiled:De,sources:Ke,logicform:ut,provider:gt,connectionId:He})=>O(De,"semantic-resolution",ut,"auto-case",gt,He,Ke)})).rows}else{hs(z,y);const ye=Oe(z,y.provider,E),Ce=ke(z);O(ye,"semantic-resolution",V,"auto-case",y.provider,y.connectionId,Ce),K=await L(ye,Ce)}const ie=K[0],me=ie?.__autoCaseMin__,W=ie?.__autoCaseMax__,J=ie?.__autoCaseCount__;if(me==null||W===null||W===void 0||J===null||J===void 0||Number(J)===0)return{empty:!0};const re=Number(me),pe=Number(W),de=Number(J);if(!Number.isFinite(re)||!Number.isFinite(pe)||!Number.isSafeInteger(de)||de<0)throw new l("INVALID_AUTO_CASE_STATS","Automatic bucket statistics must contain finite min/max and a non-negative integer count",{min:me,max:W,count:J});return{min:re,max:pe,count:de}})();return b.set(P,X),X},ze=async(g,A,_)=>{if(!A.partition||y.partitionDisabledSchemaIds?.includes(A.id)||!g.schema||g.from)return;if(y.partitionStack?.includes(A.id))throw new l("RECURSIVE_SCHEMA_PARTITION",`Schema ${A.id} partition called itself without a pinned mapping`);const P=[...y.partitionStack??[],A.id],B=await A.partition(Mr(g,A,H,_),{dayjs:he,moment:he,schemas:Object.fromEntries(Object.keys(y.schemas).map(Z=>[Z,j(Z)])),schemaMappings:N.definitions(),execute:async(Z,V)=>{const z=Z.schema,K=V?.mappingId;if(K&&!z)throw new l("PARTITION_MAPPING_SCHEMA_REQUIRED","A pinned partition query requires a physical Schema");const ie=K&&z?N.findById(z,K):void 0;if(K&&!ie)throw new l("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${z}:${K}`);const me=ie?new Dt([...N.definitions().filter(({schemaId:ye})=>ye!==z),ie],o):N,W=ie?.connectionId??y.connectionId,J=ie?y.providerForConnection?.(ie.connectionId)??(ie.connectionId===y.connectionId?y.provider:void 0):y.provider;if(!J)throw new l("DATABASE_CONNECTION_ROUTER_REQUIRED",`Pinned mapping ${K} requires a provider for ${W}`);const{onProgress:re,...pe}=y,de=await ws(Z,{...pe,schemaMappings:me,provider:J,...W?{connectionId:W}:{},partitionStack:P,...z&&ie?{partitionDisabledSchemaIds:[...y.partitionDisabledSchemaIds??[],z]}:{},operators:E,operatorsResolved:!0,semanticTypes:w,semanticTypesResolved:!0});return M.push(...de.sqls.map(ye=>({...ye,type:"semantic-resolution",explain:n.translate(r,"sql.semanticResolution")}))),T={...T,sqls:[...M]},de}}),X=B;if(typeof X!="object"||X===null||!Array.isArray(X.shards))throw new l("INVALID_SCHEMA_PARTITION",`Schema ${A.id} partition must return shards`);return Pu(A,B.shards,N),Promise.all(B.shards.map(async Z=>{const V=await Rt({version:g.version,schema:A.id,query:Z.query,preds:[]},A,{semanticTypes:w,operators:E,plugins:o,now:S,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,resolveFromSchema:Ee,requestTimeWatermark:Ge,requestAutoCaseBounds:Ze});if(!V.query)throw new l("INVALID_SCHEMA_PARTITION",`Schema ${A.id} partition shard query normalized to empty`);return{...Z,query:V.query}}))},v=async(g,A,_,P,B)=>{const X={...ue,...B?{semanticPreds:B}:{}},Z=await ze(g,A,P);if(!Z)return Me(g,A,E,N,X);if(ls(g)||g.preds?.every(({operator:K})=>K==="$sum"))return fs(g,A,Z,E,N,X).current;if(!g.preds?.some(K=>E.isComponent(K)))throw new l("UNSUPPORTED_SCHEMA_PARTITION_AGGREGATE","Schema partition supports $sum PredItems or ungrouped Property projections");for(const K of Z)for(const ie of K.mappingCandidates){const me={...g,query:Tu(g.query,K.query)};try{return Me(me,A,E,N,{...X,mappingCandidates:[ie]})}catch(W){if(!(W instanceof l)||W.code!=="QUERY_NOT_COVERED_BY_DATA_SOURCE")throw W;const J=N.findById(A.id,ie);if(!J)continue;const re={...J,...J.mappings?{mappings:J.mappings.map(de=>{if(de.mappingType!=="property")return de;const{granularity:ye,...Ce}=de;return Ce})}:{}},pe=new Dt([...N.definitions().filter(({schemaId:de})=>de!==A.id),re],o);return Me(me,A,E,pe,{...X,mappingCandidates:[ie]})}}const z=A.name&&A.name!==A.id?`${A.name}(${A.id})`:A.id;throw new l("SCHEMA_PARTITION_MAPPING_NOT_FOUND",`Schema\u300C${z}\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:A.id,schemaLabel:z,component:!0})},Ae=new WeakMap,Le=async g=>{for(const A of g){if("logicform"in A&&A.partitionQuery&&A.partitionCurrentLogicform){const _=R(A.partitionCurrentLogicform),P=await ze(A.partitionCurrentLogicform,_);if(P){const B=fs(A.partitionCurrentLogicform,_,P,E,N,ue,{logicform:A.logicform,queryForCurrentShard:A.partitionQuery});Ae.set(A.logicform,B.comparison)}}if("components"in A)for(const _ of A.components.filter(mt)){if(!_.comparisonOf||!_.partitionQuery)continue;const P=A.components.filter(mt).find(({name:V})=>V===_.comparisonOf);if(!P)throw new l("INVALID_COMPONENT_COMPARISON",`Comparison component ${_.name} has no current component ${_.comparisonOf}`);const B=R(P.logicform),X=await ze(P.logicform,B);if(!X)continue;const Z=fs(P.logicform,B,X,E,N,ue,{logicform:_.logicform,queryForCurrentShard:_.partitionQuery});Ae.set(P.logicform,Z.current),Ae.set(_.logicform,Z.comparison)}}},$e=new WeakSet,We=new WeakMap,k=Sm({createUnits:(g,A,_,P)=>{const B=Im(g,A,_,E,H,P,r,n.translator(r)),X=new Map,Z=V=>{V.schema&&V.query&&X.set(V.schema,new Set([...X.get(V.schema)??[],JSON.stringify(V.query)])),V.from&&Z(V.from)};Z(g);for(const V of B??[]){const z=A.projections.findIndex(({name:me})=>me===V.outputName)-A.groupBy.length,K=g.preds?.[z];if(!K?.operator||E.isBuiltin(K.operator))continue;const ie="logicform"in V?[V.logicform]:V.components.filter(mt).map(({logicform:me})=>me);for(const me of ie)$e.add(me),We.set(me,X)}return B},resolveSchema:R,prepareUnits:Le,replanSource:(g,A,_,P)=>(ee.set(JSON.stringify(_),P),Me(g,A,E,N,ue)),prepareQuery:async g=>{const A=R(g.logicform);ar(g.logicform,y.permissions,H,E);const _=$e.has(g.logicform);_&&sr(g.logicform,y.permissions,H,o,We.get(g.logicform));const P=g.prepare||_?await Rt(Bt(g.logicform,y.permissions,H,!_,new Set,o,E),A,{semanticTypes:w,operators:E,plugins:o,now:S,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,resolveFromSchema:Ee,canProjectProperty:(B,X)=>Ot(y.permissions,B.id,X),requestTimeWatermark:Ge}):g.logicform;return ar(P,y.permissions,H,E),{logicform:P,schema:A,plan:Ae.get(g.logicform)??await v(P,A,void 0,void 0,g.semanticPreds)}}});try{y.signal?.throwIfAborted(),xi(u),await q({stage:"started",logicform:u});const g=R(u);await q({stage:"validated",schema:g}),ar(u,y.permissions,H,E);const A=Bt(u,y.permissions,H,!0,new Set,o,E);let _;const P=await Rt(A,g,{semanticTypes:w,operators:E,plugins:o,now:S,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,resolveFromSchema:Ee,canProjectProperty:(U,te)=>Ot(y.permissions,U.id,te),requestTimeWatermark:Ge,requestAutoCaseBounds:Ze,onTimeRangeResolved:U=>{_=U}});E=E.withExecutionContext(Object.freeze({...G,...G.timeRange?{}:_?{timeRange:_}:{}})),ar(P,y.permissions,H,E);const B=Mr(P,g,H,A);await q({stage:"normalized",normedLogicform:B},{normedLogicform:B});const X=async U=>{if(Re(U)){await X(U.from),await X(U.query),await X(U.preds);const te=JSON.stringify(U);!ee.has(te)&&U.schema&&!U.from&&H(U.schema).partition&&ee.set(te,await v(U,H(U.schema)));return}if(Array.isArray(U)){for(const te of U)await X(te);return}if(!(typeof U!="object"||U===null||U instanceof Date))for(const te of Object.values(U))await X(te)};await X(P.from),await X(P.query),await X(P.preds);const Z={...P};delete Z.sample;const V=await v(Z,g,void 0,A),z=P.sample;if(z&&(g.type!=="entity"||V.rowIdentity.kind!=="property"||V.groupBy.length>0||V.groupLimit))throw new l("INVALID_SAMPLE","sample requires detail rows with a stable entity ID");const K=V.orderBy,{pagination:ie,...me}=V,W=await k.resolvePlan(P,z?{...me,orderBy:[]}:V,g),J=En(W,N);J||hs(W,y);const re=W.columnProperties??[],pe=ac(W,g);oe.set(pe.id,pe),await q({stage:"planned",plan:W},{schema:pe});const de=Xa(W,g,y.provider,E,y.providerForConnection,H);if(await q({stage:"lineage",lineage:de},{lineage:de}),a&&I(W)){const U=[];await q({stage:"compiled",sqls:[]},{sqls:[]}),await q({stage:"result",result:U},{result:U,total:0}),await q({stage:"completed",durationMs:Rn.now()-$});const te=P.output?kn(P.output.type,o):void 0;return{result:U,total:0,schema:pe,normedLogicform:B,sqls:[],lineage:de,...te?{output:await te.handle({rows:U,logicform:B,schema:pe})}:{}}}if(J){const U=y.providerForConnection;if(!U)throw new l("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated execution requires a provider resolver for every physical connection");const te=await $o(W,{logicform:B,operators:E,schemaMappings:N,providerForConnection:U,maxMaterializedRows:y.federation?.maxMaterializedRows??1e5,...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:({compiled:je,sources:_e,type:Qe,logicform:wt,provider:Ue,connectionId:et})=>O(je,Qe,wt,Qe,Ue,et,_e)});await q({stage:"compiled",sqls:[...M]},{sqls:[...M]}),await q({stage:"executing",provider:"duckdb",connectionId:$n}),await q({stage:"hydrating"});const ae=te.connections.length===1?te.connections[0]?.connectionId:void 0,le=z?Mu(te.rows,P.limit,K):te,be=await Wi(ku(le.rows,W,P.randomData),re,{now:S,expandEntities:y.result_only!==!0,semanticTypes:w,plugins:o,resolveSchema:H,fetchEntities:je=>ou(je,{version:P.version,operators:E,schemaMappings:N,semanticTypes:w,plugins:o,...y.locale?{locale:y.locale}:{},localeRegistry:n,resolveSchema:H,...y.permissions?{permissions:y.permissions}:{},provider:y.provider,providerForConnection:U,...ae?{preferredConnectionId:ae}:{},...y.cache?{cache:y.cache}:{},...y.signal?{signal:y.signal}:{},onCompiled:(_e,Qe,wt,Ue,et)=>O(_e,"semantic-resolution",Qe,"entity-expansion",wt,Ue,et)})}),Se=oo(be,W.rowIdentity);return await q({stage:"result",result:Se},{result:Se,total:le.total,sqls:[...M]}),await q({stage:"completed",durationMs:Rn.now()-$}),{result:Se,total:le.total,schema:pe,normedLogicform:B,sqls:[...M],lineage:de}}const ye=k.getUnits(P,W,g),Ce=(U,te)=>mo([...U.map(({prepared:ae})=>ae.sources),...U.length===0&&te.groupBy.length>0?[ke(te)]:[]]),De=async(U,te)=>{const ae=te&&U.logicform.schema===te.id?te:R(U.logicform),le=await k.prepareQuery(U),be=le.logicform,Se=le.plan,je=k.getUnits(be,le.plan,ae,U.logicform);if(je){if(je.length!==1)throw new Error("A generated component must produce exactly one execution unit");const _e=je[0];if("logicform"in _e){const Ue=await De(_e,ae),et=Ue.component.mapResult,st=U.mapResult;return{...Ue,component:{...U,logicform:Ue.component.logicform,...et||st?{mapResult:Qt=>{const dr=et?.(Qt)??[...Qt];return st?.(dr)??[...dr]}}:{}}}}if("mergeRow"in _e)throw new l("UNSUPPORTED_NESTED_JS_COMPONENT","A JavaScript composite metric cannot currently be nested as a generated component");const Qe=await Promise.all(_e.components.filter(mt).map(async Ue=>({name:Ue.name,prepared:await De(Eo(Ue)),...Ue.groupKeyShifts?{groupKeyShifts:Ue.groupKeyShifts}:{},...Ue.joinKeys?{joinKeys:Ue.joinKeys}:{}}))),wt=to(_e,Qe.map(({name:Ue,prepared:et,...st})=>({name:Ue,plan:et.plan,...st})),Se,_e.outputName,y.provider,E);return{component:{...U,logicform:be},plan:Se,compiled:wt,sources:Ce(Qe,Se)}}return{component:{...U,logicform:be},plan:Se,compiled:Oe(Se,y.provider,E),sources:ke(Se)}},Ke=async(U,te)=>{const ae=k.getUnits(U,te,R(U));if(!ae)return{compiled:Oe(te,y.provider,E),sources:ke(te)};const le=await Promise.all(ae.map(async be=>{if("logicform"in be){const _e=await De(be);return{plan:_e.plan,compiled:_e.compiled,outputs:_e.plan.projections.map(({name:Qe})=>Qe).filter(Qe=>!te.groupBy.some(wt=>wt.name===Qe))}}if("mergeRow"in be)throw new l("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const Se=await Promise.all(be.components.filter(mt).map(async _e=>{const Qe=await De(Eo(_e));return{name:_e.name,plan:Qe.plan,..._e.joinKeys?{joinKeys:_e.joinKeys}:{},..._e.groupKeyShifts?{groupKeyShifts:_e.groupKeyShifts}:{}}})),je=to(be,Se,te,be.outputName,y.provider,E);return{plan:te,compiled:je,outputs:[be.outputName,...be.components.map(_e=>_e.name)]}}));return{compiled:Mi(le,te,y.provider,E),sources:mo(le.map(({plan:be})=>ke(be)))}},ut=new WeakMap,gt=(U,te)=>{const ae={...U,preds:[]};return delete ae.having,delete ae.sort,delete ae.limit,delete ae.limitBy,delete ae.page,delete ae.sample,De({kind:"query",logicform:ae},te)},He=async U=>{if(!U.sourcePlan||!U.sourceLogicform)return Oe(U,y.provider,E);const te=x(U.sourceLogicform),ae=k.getUnits(U.sourceLogicform,U.sourcePlan,te);if(ae?.some(_e=>"mergeRow"in _e)){const _e=ut.get(U.sourcePlan);if(_e){const Ie={...U};delete Ie.sourcePlan,delete Ie.sourceLogicform;const At=Oe({...Ie,source:rt({kind:"sql",sql:_e.sql})},y.provider,E,_e.parameters.length);return{sql:At.sql,parameters:[..._e.parameters,...At.parameters]}}const Qe=await Promise.all(ae.map(async Ie=>{if("logicform"in Ie)return{kind:"query",unit:Ie,prepared:await De(Ie,te)};const At=await Promise.all(Ie.components.filter(mt).map(async Ne=>({input:Ne,prepared:await De(Eo(Ne),te)})));if("mergeRow"in Ie){const Ne=At.map(({prepared:pr})=>pr);return At.length===0&&U.sourcePlan?.groupBy.length&&Ne.push(await gt(U.sourceLogicform,te)),{kind:"js",unit:Ie,components:Ne}}return{kind:"component",unit:Ie,components:At,compiled:to(Ie,At.map(({input:Ne,prepared:pr})=>({name:Ne.name,plan:pr.plan,...Ne.joinKeys?{joinKeys:Ne.joinKeys}:{},...Ne.groupKeyShifts?{groupKeyShifts:Ne.groupKeyShifts}:{}})),U.sourcePlan,Ie.outputName,y.provider,E)}})),wt=U.sourcePlan.groupBy.map(({name:Ie})=>Ie),Ue=await Promise.all(Qe.map(async Ie=>{if(Ie.kind==="query"){O(Ie.prepared.compiled,"computation",Ie.prepared.component.logicform,"computation",y.provider,y.connectionId,Ie.prepared.sources);const Ne=await L(Ie.prepared.compiled,Ie.prepared.sources);return Ie.unit.mapResult?.(Ne)??Ne}if(Ie.kind==="component"){const Ne=Ce(Ie.components,U.sourcePlan);return O(Ie.compiled,"computation",U.sourceLogicform,"computation",y.provider,y.connectionId,Ne),L(Ie.compiled,Ne)}const At=await Promise.all(Ie.components.map(async Ne=>{O(Ne.compiled,"computation",Ne.component.logicform,"computation",y.provider,y.connectionId,Ne.sources);const pr=await L(Ne.compiled,Ne.sources);return Ne.component.mapResult?.(pr)??pr}));return Promise.all(Sc(At,wt,Ie.unit).map(async Ne=>({...Ne,[Ie.unit.outputName]:await Ie.unit.mergeRow(Ne)})))})),et=dn(Ue,U.sourcePlan),st=y.federation?.maxMaterializedRows??1e5;if(!Number.isSafeInteger(st)||st<1)throw new l("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:st});if(et.length>st)throw new l("MATERIALIZED_RESULT_LIMIT_EXCEEDED",`Nested component materialized ${et.length} rows; maximum is ${st}`,{materializedRowCount:et.length,maxMaterializedRows:st});const Qt=Vh(et,U.sourcePlan,y.provider);ut.set(U.sourcePlan,Qt);const dr={...U};delete dr.sourcePlan,delete dr.sourceLogicform;const As=Oe({...dr,source:rt({kind:"sql",sql:Qt.sql})},y.provider,E,Qt.parameters.length);return{sql:As.sql,parameters:[...Qt.parameters,...As.parameters]}}const le=await Ke(U.sourceLogicform,U.sourcePlan),be={...U};delete be.sourcePlan,delete be.sourceLogicform;const Se={...be,source:rt({kind:"sql",sql:le.compiled.sql})},je=Oe(Se,y.provider,E,le.compiled.parameters.length);return{sql:je.sql,parameters:[...le.compiled.parameters,...je.parameters]}},Ve=ye?await Promise.all(ye.map(async U=>{if("logicform"in U)return{kind:"query",unit:U,...await De(U)};const te=await Promise.all(U.components.filter(mt).map(async le=>({name:le.name,prepared:await De(Eo(le)),...le.groupKeyShifts?{groupKeyShifts:le.groupKeyShifts}:{},...le.joinKeys?{joinKeys:le.joinKeys}:{}})));if("mergeRow"in U){const le=te.map(({prepared:be})=>be);return te.length===0&&W.groupBy.length>0&&le.push(await gt(P)),{kind:"js",unit:U,components:le}}const ae=te.map(({name:le,prepared:be,...Se})=>({name:le,plan:be.plan,...Se}));return{kind:"component",unit:U,plan:W,compiled:to(U,ae,W,U.outputName,y.provider,E),sources:Ce(te,W)}})):void 0,Te=Ve&&Fh(Ve,N,W)?Ve.map(U=>{const te=new Set(W.groupBy.map(({name:le})=>le));if(U.kind==="query")return{plan:U.plan,compiled:U.compiled,outputs:U.plan.projections.map(({name:le})=>le).filter(le=>!te.has(le))};const ae=U.unit.outputName;if(!ae)throw new l("INVALID_COMPONENT_PLAN","Component output projection is missing");return{plan:U.plan,compiled:U.compiled,outputs:[ae,...U.unit.components.map(le=>le.name)]}}):void 0,Fe=Te?Mi(Te,W,y.provider,E):void 0,fe=Ve?void 0:await He(W),qe=ke(W),Je=W.sourcePlan&&ut.has(W.sourcePlan)?[]:qe,Pt=Fe?mo([...Ve.map(U=>U.sources),qe]):void 0,Lt=Fe?mo([...Ve.map(U=>U.sources),Je]):void 0,Ct=us(W),ot=W.pagination&&(Fe||fe)?ds(Te?Mi(Te,Ct,y.provider,E):await He(Ct),y.provider):void 0;if(Fe)O(Fe,"computation",B,"computation",y.provider,y.connectionId,Lt);else if(Ve)for(const U of Ve)if(U.kind==="js")for(const te of U.components)O(te.compiled,"computation",te.component.logicform,"computation",y.provider,y.connectionId,te.sources);else O(U.compiled,"computation",B,"computation",y.provider,y.connectionId,U.sources);else O(fe,"computation",B,"computation",y.provider,y.connectionId,Je);ot&&O(ot,"total",_h(B),"total",y.provider,y.connectionId,Lt??Je),await q({stage:"compiled",sqls:[...M]},{sqls:[...M]}),await q({stage:"executing",provider:y.provider.kind});const ur=Fe?await(async()=>{const U=Pt,[te,ae]=await Promise.all([L(Fe,U),ot?L(ot,U):Promise.resolve(void 0)]);return{rows:te,total:ae?Ao(ae):te.length}})():Ve?await(async()=>{const U=await Promise.all(Ve.map(async ae=>{if(ae.kind==="js"){const be=await Promise.all(ae.components.map(async Se=>{const je=await L(Se.compiled,Se.sources);return Se.component.mapResult?.(je)??je}));return Promise.all(Sc(be,W.groupBy.map(({name:Se})=>Se),ae.unit).map(async Se=>{const je=await ae.unit.mergeRow(Se);return{...Se,[ae.unit.outputName]:je}}))}const le=await L(ae.compiled,ae.sources);return ae.kind==="query"?ae.unit.mapResult?.(le)??le:le})),te=dn(U,W);return{rows:te,total:W.pagination?dn(U,Ct).length:te.length}})():await(async()=>{const U=qe,[te,ae]=await Promise.all([L(fe,U),ot?L(ot,U):Promise.resolve(void 0)]);return{rows:te,total:ae?Ao(ae):te.length}})(),{rows:bn,total:it}=z?Mu(ur.rows,P.limit,K):ur;await q({stage:"hydrating"});const So=await Wi(ku(bn,W,P.randomData),re,{now:S,expandEntities:y.result_only!==!0,semanticTypes:w,plugins:o,resolveSchema:H,fetchEntities:U=>ou(U,{version:P.version,operators:E,schemaMappings:N,semanticTypes:w,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:(te,ae,le,be,Se)=>O(te,"semantic-resolution",ae,"entity-expansion",le,be,Se)})}),dt=oo(So,W.rowIdentity);return await q({stage:"result",result:dt},{result:dt,total:it,sqls:[...M]}),await q({stage:"completed",durationMs:Rn.now()-$}),{result:dt,total:it,schema:pe,normedLogicform:B,sqls:[...M],lineage:de,...P.output?await(async()=>{const U=kn(P.output?.type??"",o);return U?{output:await U.handle({rows:dt,logicform:B,schema:pe})}:{}})():{}}}catch(g){const A=qu(g);try{await q({stage:"failed",error:A})}catch{}throw A}},xu=async(t,e)=>{let r={};const n=e.locale??"zh-CN",o=zr(Uu(e.plugins,e.locales));try{const i=at(e.plugins),s=e.operators===void 0?[]:Array.isArray(e.operators)?e.operators:[e.operators],a=new Vr(s),u=new Set(a.definitions().map(({name:O})=>O)),c=s.length===0?i:new Vr([...i.definitions().filter(({name:O})=>!u.has(O)),...a.definitions()],Object.freeze({}),i.definitions().filter(({name:O})=>i.isBuiltin(O)&&!u.has(O))),d=t.version,p=d===void 0||typeof d=="string"&&/^1\./.test(d),f=p?jn(t,e.schemas):t;if(Ch(f,c))return await kh(t,e,c,xu);const m=e.connections??[],h=e.schemaMappings??[];if(m.length===0)throw new l("DATABASE_CONNECTION_REQUIRED","At least one database connection is required");const y=new Map;for(const O of m){if(O.id.trim().length===0)throw new l("INVALID_DATABASE_CONNECTION","Database connection id must not be empty");if(y.has(O.id))throw new l("DATABASE_CONNECTION_ALREADY_REGISTERED",`Database connection id is duplicated: ${O.id}`,{connectionId:O.id});y.set(O.id,O)}const $=ju(t),w=[...new Set(h.filter(({schemaId:O})=>$.includes(O)).map(({connectionId:O})=>O))],E=m.length===1?m[0]?.id:w.length===1?w[0]:void 0,N=p?$a(e.schemas,h,E,$,m.map(({id:O})=>O)):h,I=new Dt(N,e.plugins),S=$.flatMap(O=>I.list(O)).map(({connectionId:O})=>O)[0];if(!S)throw new l("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain at least one physical Schema leaf");const D=O=>{const L=y.get(O);if(!L)throw new l("DATABASE_CONNECTION_NOT_FOUND",`Database connection is not registered: ${O}`,{connectionId:O});return An(L,e.providerRegistry)},b=D(S),T=e.semanticTypes===void 0?Mt(e.plugins):ii(e.semanticTypes,e.plugins??[]),{cache:M,...Y}=e,C=M?await tu(M):void 0;return await ws(t,{...Y,schemaMappings:I,locale:n,localeRegistry:o,provider:b,providerForConnection:D,operators:c,operatorsResolved:!0,semanticTypes:T,semanticTypesResolved:!0,connectionId:S,...C?{cache:C}:{},onProgress:async O=>{r=O.partialResult,await e.onProgress?.(O)}})}catch(i){return xh(i,t,r,n,o)}},Qh=Object.freeze({execute:xu,close:bu});export{wh as DBConnector,ko as LocaleRegistry,Qh as Logicform,Vr as OperatorRegistry,Za as PlannerSemanticRegistry,Au as ProviderRegistry,hy as QueryCacheManager,Dt as SchemaMappingRegistry,l as SemanticDBError,ti as SemanticTypeRegistry,Wa as builtinOperators,ei as builtinSemanticTypes,zr as createLocaleRegistry,at as createOperatorRegistry,ec as createPlannerSemanticRegistry,Mt as createSemanticTypeRegistry,Ln as defaultLocaleRegistry,Ys as enUS,sl as fromYiAskSchemaMapping,Gt as getLogicformPropertyReferences,il as getSupportedDimensions,Np as isDimensionInLogicform,_u as readImportFile,za as resolveOperator,Bn as resolveSchema,lt as sourceIdentity,ba as validateResolvedSchema,vs as zhCN};
|