semanticdb-v2 2.0.0-alpha.5 → 2.0.0-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +272 -7
- package/dist/cache/redis-query-cache.esm.js +1 -1
- package/dist/cache/redis-query-cache.js +1 -1
- package/dist/cache/types.d.ts +2 -0
- package/dist/executor/connection-registry.d.ts +1 -12
- package/dist/executor/execute-query.d.ts +6 -1
- package/dist/executor/federated-execution.d.ts +37 -0
- package/dist/executor/fetch-entities.d.ts +3 -1
- package/dist/executor/result-hydrator/types.d.ts +2 -0
- package/dist/executor/total.d.ts +11 -0
- package/dist/executor/types.d.ts +33 -4
- package/dist/index.d.ts +9 -7
- package/dist/logicform-types.d.ts +44 -12
- package/dist/normalizer/core.d.ts +9 -0
- package/dist/normalizer/pred-expression.d.ts +6 -0
- package/dist/operators/builtins/query-expression.d.ts +3 -0
- package/dist/operators/index.d.ts +1 -1
- package/dist/operators/types.d.ts +39 -8
- package/dist/physical/clickhouse-provider.d.ts +20 -2
- package/dist/physical/connection-registry.d.ts +13 -0
- package/dist/physical/connection.d.ts +57 -15
- package/dist/physical/dameng-provider.d.ts +66 -0
- package/dist/physical/databricks-provider.d.ts +88 -0
- package/dist/physical/db-connector.d.ts +23 -0
- package/dist/physical/display-query.d.ts +3 -0
- package/dist/physical/doris-provider.d.ts +2 -1
- package/dist/physical/duckdb-coordinator-provider.d.ts +37 -0
- package/dist/physical/gbase-provider.d.ts +11 -0
- package/dist/physical/index.d.ts +24 -9
- package/dist/physical/load-driver.d.ts +1 -0
- package/dist/physical/maxcompute-provider.d.ts +44 -0
- package/dist/physical/mysql-protocol-provider.d.ts +24 -6
- package/dist/physical/mysql-provider.d.ts +2 -1
- package/dist/physical/oracle-provider.d.ts +20 -4
- package/dist/physical/postgresql-provider.d.ts +23 -4
- package/dist/physical/provider.d.ts +57 -1
- package/dist/physical/snowflake-provider.d.ts +19 -3
- package/dist/physical/sqlserver-provider.d.ts +69 -0
- package/dist/physical/starrocks-provider.d.ts +2 -1
- package/dist/physical/table-description.d.ts +5 -0
- package/dist/physical/table-discovery.d.ts +10 -0
- package/dist/planner/build-lineage.d.ts +1 -1
- package/dist/planner/create-logical-plan.d.ts +7 -0
- package/dist/planner/index.d.ts +4 -2
- package/dist/planner/mapping-granularity.d.ts +7 -0
- package/dist/planner/rewrite-nested-components.d.ts +8 -0
- package/dist/planner/select-schema-mapping.d.ts +16 -2
- package/dist/planner/semantics/index.d.ts +0 -4
- package/dist/planner/semantics/periods.d.ts +13 -0
- package/dist/planner/semantics/registry-defaults.d.ts +2 -1
- package/dist/planner/types.d.ts +71 -34
- package/dist/plugins/hierarchy/index.d.ts +1 -1
- package/dist/plugins/hierarchy/mapping-granularity.d.ts +4 -0
- package/dist/plugins/hierarchy/types.d.ts +17 -0
- package/dist/plugins/index.d.ts +10 -1
- package/dist/{planner/semantics → plugins}/observation/classification.d.ts +1 -1
- package/dist/plugins/observation/index.d.ts +17 -0
- package/dist/{planner/semantics → plugins}/observation/operator-policy.d.ts +2 -3
- package/dist/{planner/semantics → plugins}/observation/periods.d.ts +2 -3
- package/dist/{planner/semantics → plugins}/observation/rule.d.ts +1 -1
- package/dist/{planner/semantics → plugins}/observation/types.d.ts +1 -1
- package/dist/plugins/property-hierarchy/index.d.ts +11 -0
- package/dist/plugins/recursive/index.d.ts +26 -0
- package/dist/plugins/temporal/index.d.ts +13 -0
- package/dist/plugins/types.d.ts +165 -1
- package/dist/plugins/validity/classification.d.ts +5 -0
- package/dist/{planner/semantics → plugins}/validity/index.d.ts +9 -0
- package/dist/{planner/semantics → plugins}/validity/periods.d.ts +2 -3
- package/dist/{planner/semantics → plugins}/validity/query-policy.d.ts +1 -2
- package/dist/{planner/semantics → plugins}/validity/rule.d.ts +1 -1
- package/dist/plugins/validity/semantic-types.d.ts +3 -0
- package/dist/schema-mappings/freshness.d.ts +1 -1
- package/dist/schema-mappings/granularity.d.ts +5 -0
- package/dist/schema-mappings/index.d.ts +2 -1
- package/dist/schema-mappings/registry.d.ts +5 -3
- package/dist/schema-mappings/types.d.ts +43 -0
- package/dist/schema-mappings/yiask.d.ts +6 -2
- package/dist/semantic-types/index.d.ts +5 -3
- package/dist/semantic-types/registry.d.ts +2 -0
- package/dist/semantic-types/resolve-schema.d.ts +1 -1
- package/dist/semantic-types/types.d.ts +0 -14
- package/dist/semantic-types/validate-resolved-schema.d.ts +2 -5
- package/dist/semanticdb.esm.js +5 -3
- package/dist/semanticdb.js +5 -3
- package/package.json +46 -5
- package/dist/planner/semantics/annual-periods.d.ts +0 -11
- package/dist/planner/semantics/lifecycle/classification.d.ts +0 -5
- package/dist/planner/semantics/lifecycle/index.d.ts +0 -3
- package/dist/planner/semantics/lifecycle/query-policy.d.ts +0 -2
- package/dist/planner/semantics/lifecycle/rule.d.ts +0 -2
- package/dist/planner/semantics/observation/index.d.ts +0 -6
- package/dist/planner/semantics/validity/classification.d.ts +0 -14
- package/dist/semantic-types/builtins/end-date.d.ts +0 -2
- package/dist/semantic-types/builtins/start-date.d.ts +0 -2
package/dist/semanticdb.esm.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
import{performance as Wr}from"node:perf_hooks";import J from"dayjs";import dt from"dayjs/plugin/isoWeek.js";import pt from"dayjs/plugin/quarterOfYear.js";import{randomUUID as oi}from"node:crypto";import ii from"dayjs/plugin/customParseFormat.js";import{getNameProperty as si}from"semanticdb-core";import{isDeepStrictEqual as ai}from"node:util";import{createClient as ci}from"@clickhouse/client";import{createPool as ui}from"mysql2/promise";import di from"mysql2";import zr from"oracledb";import{Pool as pi}from"pg";import li from"snowflake-sdk";const x=e=>typeof e=="string",Ke=()=>{let e,t;const r=new Promise((n,o)=>{e=n,t=o});return r.resolve=e,r.reject=t,r},Kr=e=>e==null?"":""+e,fi=(e,t,r)=>{e.forEach(n=>{t[n]&&(r[n]=t[n])})},mi=/###/g,Jr=e=>e&&e.indexOf("###")>-1?e.replace(mi,"."):e,Zr=e=>!e||x(e),Je=(e,t,r)=>{const n=x(t)?t.split("."):t;let o=0;for(;o<n.length-1;){if(Zr(e))return{};const i=Jr(n[o]);!e[i]&&r&&(e[i]=new r),Object.prototype.hasOwnProperty.call(e,i)?e=e[i]:e={},++o}return Zr(e)?{}:{obj:e,k:Jr(n[o])}},Xr=(e,t,r)=>{const{obj:n,k:o}=Je(e,t,Object);if(n!==void 0||t.length===1){n[o]=r;return}let i=t[t.length-1],s=t.slice(0,t.length-1),a=Je(e,s,Object);for(;a.obj===void 0&&s.length;)i=`${s[s.length-1]}.${i}`,s=s.slice(0,s.length-1),a=Je(e,s,Object),a?.obj&&typeof a.obj[`${a.k}.${i}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${i}`]=r},yi=(e,t,r,n)=>{const{obj:o,k:i}=Je(e,t,Object);o[i]=o[i]||[],o[i].push(r)},lt=(e,t)=>{const{obj:r,k:n}=Je(e,t);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},hi=(e,t,r)=>{const n=lt(e,r);return n!==void 0?n:lt(t,r)},en=(e,t,r)=>{for(const n in t)n!=="__proto__"&&n!=="constructor"&&(n in e?x(e[n])||e[n]instanceof String||x(t[n])||t[n]instanceof String?r&&(e[n]=t[n]):en(e[n],t[n],r):e[n]=t[n]);return e},Pe=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var gi={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const $i=e=>x(e)?e.replace(/[&<>"'\/]/g,t=>gi[t]):e;class wi{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const r=this.regExpMap.get(t);if(r!==void 0)return r;const n=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,n),this.regExpQueue.push(t),n}}const Ai=[" ",",","?","!",";"],Ei=new wi(20),_i=(e,t,r)=>{t=t||"",r=r||"";const n=Ai.filter(s=>t.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=Ei.getRegExp(`(${n.map(s=>s==="?"?"\\?":s).join("|")})`);let i=!o.test(e);if(!i){const s=e.indexOf(r);s>0&&!o.test(e.substring(0,s))&&(i=!0)}return i},Ht=(e,t,r=".")=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;const n=t.split(r);let o=e;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},Ze=e=>e?.replace(/_/g,"-"),Si={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console?.[e]?.apply?.(console,t)}};class Bt{constructor(t,r={}){this.init(t,r)}init(t,r={}){this.prefix=r.prefix||"i18next:",this.logger=t||Si,this.options=r,this.debug=r.debug}log(...t){return this.forward(t,"log","",!0)}warn(...t){return this.forward(t,"warn","",!0)}error(...t){return this.forward(t,"error","")}deprecate(...t){return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}forward(t,r,n,o){return o&&!this.debug?null:(x(t[0])&&(t[0]=`${n}${this.prefix} ${t[0]}`),this.logger[r](t))}create(t){return new Bt(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t=t||this.options,t.prefix=t.prefix||this.prefix,new Bt(this.logger,t)}}var me=new Bt;class ft{constructor(){this.observers={}}on(t,r){return t.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(t,r){if(this.observers[t]){if(!r){delete this.observers[t];return}this.observers[t].delete(r)}}emit(t,...r){this.observers[t]&&Array.from(this.observers[t].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,[t,...r])})}}class tn extends ft{constructor(t,r={ns:["translation"],defaultNS:"translation"}){super(),this.data=t||{},this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const r=this.options.ns.indexOf(t);r>-1&&this.options.ns.splice(r,1)}getResource(t,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;t.indexOf(".")>-1?a=t.split("."):(a=[t,r],n&&(Array.isArray(n)?a.push(...n):x(n)&&i?a.push(...n.split(i)):a.push(n)));const c=lt(this.data,a);return!c&&!r&&!n&&t.indexOf(".")>-1&&(t=a[0],r=a[1],n=a.slice(2).join(".")),c||!s||!x(n)?c:Ht(this.data?.[t]?.[r],n,i)}addResource(t,r,n,o,i={silent:!1}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let a=[t,r];n&&(a=a.concat(s?n.split(s):n)),t.indexOf(".")>-1&&(a=t.split("."),o=r,r=a[1]),this.addNamespaces(r),Xr(this.data,a,o),i.silent||this.emit("added",t,r,n,o)}addResources(t,r,n,o={silent:!1}){for(const i in n)(x(n[i])||Array.isArray(n[i]))&&this.addResource(t,r,i,n[i],{silent:!0});o.silent||this.emit("added",t,r,n)}addResourceBundle(t,r,n,o,i,s={silent:!1,skipCopy:!1}){let a=[t,r];t.indexOf(".")>-1&&(a=t.split("."),o=n,n=r,r=a[1]),this.addNamespaces(r);let c=lt(this.data,a)||{};s.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?en(c,n,i):c={...c,...n},Xr(this.data,a,c),s.silent||this.emit("added",t,r,n)}removeResourceBundle(t,r){this.hasResourceBundle(t,r)&&delete this.data[t][r],this.removeNamespaces(r),this.emit("removed",t,r)}hasResourceBundle(t,r){return this.getResource(t,r)!==void 0}getResourceBundle(t,r){return r||(r=this.options.defaultNS),this.getResource(t,r)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const r=this.getDataByLanguage(t);return!!(r&&Object.keys(r)||[]).find(o=>r[o]&&Object.keys(r[o]).length>0)}toJSON(){return this.data}}var rn={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,r,n,o){return e.forEach(i=>{t=this.processors[i]?.process(t,r,n,o)??t}),t}};const nn=Symbol("i18next/PATH_KEY");function Ii(){const e=[],t=Object.create(null);let r;return t.get=(n,o)=>(r?.revoke?.(),o===nn?e:(e.push(o),r=Proxy.revocable(n,t),r.proxy)),Proxy.revocable(Object.create(null),t).proxy}function je(e,t){const{[nn]:r}=e(Ii()),n=t?.keySeparator??".",o=t?.nsSeparator??":";if(r.length>1&&o){const i=t?.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 on={},Gt=e=>!x(e)&&typeof e!="boolean"&&typeof e!="number";class Ft extends ft{constructor(t,r={}){super(),fi(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=me.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t,r={interpolation:{}}){const n={...r};if(t==null)return!1;const o=this.resolve(t,n);if(o?.res===void 0)return!1;const i=Gt(o.res);return!(n.returnObjects===!1&&i)}extractFromKey(t,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&&t.indexOf(n)>-1,a=!this.options.userDefinedKeySeparator&&!r.keySeparator&&!this.options.userDefinedNsSeparator&&!r.nsSeparator&&!_i(t,n,o);if(s&&!a){const c=t.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:t,namespaces:x(i)?[i]:i};const u=t.split(n);(n!==o||n===o&&this.options.ns.indexOf(u[0])>-1)&&(i=u.shift()),t=u.join(o)}return{key:t,namespaces:x(i)?[i]:i}}translate(t,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={}),t==null)return"";typeof t=="function"&&(t=je(t,{...this.options,...o})),Array.isArray(t)||(t=[String(t)]),t=t.map(V=>typeof V=="function"?je(V,{...this.options,...o}):String(V));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(t[t.length-1],o),u=c[c.length-1];let d=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;d===void 0&&(d=":");const l=o.lng||this.language,f=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l?.toLowerCase()==="cimode")return f?i?{res:`${u}${d}${a}`,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:u,usedParams:this.getUsedParamsDetails(o)}:`${u}${d}${a}`:i?{res:a,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:u,usedParams:this.getUsedParamsDetails(o)}:a;const m=this.resolve(t,o);let y=m?.res;const g=m?.usedKey||a,_=m?.exactUsedKey||a,R=["[object Number]","[object Function]","[object RegExp]"],$=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,E=!this.i18nFormat||this.i18nFormat.handleAsObject,h=o.count!==void 0&&!x(o.count),S=Ft.hasDefaultValue(o),N=h?this.pluralResolver.getSuffix(l,o.count,o):"",k=o.ordinal&&h?this.pluralResolver.getSuffix(l,o.count,{ordinal:!1}):"",j=h&&!o.ordinal&&o.count===0,v=j&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${N}`]||o[`defaultValue${k}`]||o.defaultValue;let K=y;E&&!y&&S&&(K=v);const D=Gt(K),L=Object.prototype.toString.apply(K);if(E&&K&&D&&R.indexOf(L)<0&&!(x($)&&Array.isArray(K))){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const V=this.options.returnedObjectHandler?this.options.returnedObjectHandler(g,K,{...o,ns:c}):`key '${a} (${this.language})' returned an object instead of string.`;return i?(m.res=V,m.usedParams=this.getUsedParamsDetails(o),m):V}if(s){const V=Array.isArray(K),q=V?[]:{},re=V?_:g;for(const W in K)if(Object.prototype.hasOwnProperty.call(K,W)){const Z=`${re}${s}${W}`;S&&!y?q[W]=this.translate(Z,{...o,defaultValue:Gt(v)?v[W]:void 0,joinArrays:!1,ns:c}):q[W]=this.translate(Z,{...o,joinArrays:!1,ns:c}),q[W]===Z&&(q[W]=K[W])}y=q}}else if(E&&x($)&&Array.isArray(y))y=y.join($),y&&(y=this.extendTranslation(y,t,o,n));else{let V=!1,q=!1;!this.isValidLookup(y)&&S&&(V=!0,y=v),this.isValidLookup(y)||(q=!0,y=a);const W=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&q?void 0:y,Z=S&&v!==y&&this.options.updateMissing;if(q||V||Z){if(this.logger.log(Z?"updateKey":"missingKey",l,u,a,Z?v:y),s){const Q=this.resolve(a,{...o,keySeparator:!1});Q&&Q.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 ne=[];const X=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&X&&X[0])for(let Q=0;Q<X.length;Q++)ne.push(X[Q]);else this.options.saveMissingTo==="all"?ne=this.languageUtils.toResolveHierarchy(o.lng||this.language):ne.push(o.lng||this.language);const ce=(Q,w,A)=>{const I=S&&A!==y?A:W;this.options.missingKeyHandler?this.options.missingKeyHandler(Q,u,w,I,Z,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(Q,u,w,I,Z,o),this.emit("missingKey",Q,u,w,y)};this.options.saveMissing&&(this.options.saveMissingPlurals&&h?ne.forEach(Q=>{const w=this.pluralResolver.getSuffixes(Q,o);j&&o[`defaultValue${this.options.pluralSeparator}zero`]&&w.indexOf(`${this.options.pluralSeparator}zero`)<0&&w.push(`${this.options.pluralSeparator}zero`),w.forEach(A=>{ce([Q],a+A,o[`defaultValue${A}`]||v)})}):ce(ne,a,v))}y=this.extendTranslation(y,t,o,m,n),q&&y===a&&this.options.appendNamespaceToMissingKey&&(y=`${u}${d}${a}`),(q||V)&&this.options.parseMissingKeyHandler&&(y=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${d}${a}`:a,V?y:void 0,o))}return i?(m.res=y,m.usedParams=this.getUsedParamsDetails(o),m):y}extendTranslation(t,r,n,o,i){if(this.i18nFormat?.parse)t=this.i18nFormat.parse(t,{...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=x(t)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let u;if(c){const l=t.match(this.interpolator.nestingRegexp);u=l&&l.length}let d=n.replace&&!x(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(d={...this.options.interpolation.defaultVariables,...d}),t=this.interpolator.interpolate(t,d,n.lng||this.language||o.usedLng,n),c){const l=t.match(this.interpolator.nestingRegexp),f=l&&l.length;u<f&&(n.nest=!1)}!n.lng&&o&&o.res&&(n.lng=this.language||o.usedLng),n.nest!==!1&&(t=this.interpolator.nest(t,(...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=x(s)?[s]:s;return t!=null&&a?.length&&n.applyPostProcessor!==!1&&(t=rn.handle(a,t,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...o,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),t}resolve(t,r={}){let n,o,i,s,a;return x(t)&&(t=[t]),Array.isArray(t)&&(t=t.map(c=>typeof c=="function"?je(c,{...this.options,...r}):c)),t.forEach(c=>{if(this.isValidLookup(n))return;const u=this.extractFromKey(c,r),d=u.key;o=d;let l=u.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));const f=r.count!==void 0&&!x(r.count),m=f&&!r.ordinal&&r.count===0,y=r.context!==void 0&&(x(r.context)||typeof r.context=="number")&&r.context!=="",g=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);l.forEach(_=>{this.isValidLookup(n)||(a=_,!on[`${g[0]}-${_}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(on[`${g[0]}-${_}`]=!0,this.logger.warn(`key "${o}" for languages "${g.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),g.forEach(R=>{if(this.isValidLookup(n))return;s=R;const $=[d];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys($,d,R,_,r);else{let h;f&&(h=this.pluralResolver.getSuffix(R,r.count,r));const S=`${this.options.pluralSeparator}zero`,N=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(r.ordinal&&h.indexOf(N)===0&&$.push(d+h.replace(N,this.options.pluralSeparator)),$.push(d+h),m&&$.push(d+S)),y){const k=`${d}${this.options.contextSeparator||"_"}${r.context}`;$.push(k),f&&(r.ordinal&&h.indexOf(N)===0&&$.push(k+h.replace(N,this.options.pluralSeparator)),$.push(k+h),m&&$.push(k+S))}}let E;for(;E=$.pop();)this.isValidLookup(n)||(i=E,n=this.getResource(R,_,E,r))}))})}),{res:n,usedKey:o,exactUsedKey:i,usedLng:s,usedNS:a}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,r,n,o={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(t,r,n,o):this.resourceStore.getResource(t,r,n,o)}getUsedParamsDetails(t={}){const r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=t.replace&&!x(t.replace);let o=n?t.replace:t;if(n&&typeof t.count<"u"&&(o.count=t.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(t){const r="defaultValue";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&r===n.substring(0,r.length)&&t[n]!==void 0)return!0;return!1}}class sn{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=me.create("languageUtils")}getScriptPartFromCode(t){if(t=Ze(t),!t||t.indexOf("-")<0)return null;const r=t.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}getLanguagePartFromCode(t){if(t=Ze(t),!t||t.indexOf("-")<0)return t;const r=t.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(t){if(x(t)&&t.indexOf("-")>-1){let r;try{r=Intl.getCanonicalLocales(t)[0]}catch{}return r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r||(this.options.lowerCaseLng?t.toLowerCase():t)}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let r;return t.forEach(n=>{if(r)return;const o=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(o))&&(r=o)}),!r&&this.options.supportedLngs&&t.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(t,r){if(!t)return[];if(typeof t=="function"&&(t=t(r)),x(t)&&(t=[t]),Array.isArray(t))return t;if(!r)return t.default||[];let n=t[r];return n||(n=t[this.getScriptPartFromCode(r)]),n||(n=t[this.formatLanguageCode(r)]),n||(n=t[this.getLanguagePartFromCode(r)]),n||(n=t.default),n||[]}toResolveHierarchy(t,r){const n=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],t),o=[],i=s=>{s&&(this.isSupportedCode(s)?o.push(s):this.logger.warn(`rejecting language code not found in supportedLngs: ${s}`))};return x(t)&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&i(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&i(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&i(this.getLanguagePartFromCode(t))):x(t)&&i(this.formatLanguageCode(t)),n.forEach(s=>{o.indexOf(s)<0&&i(this.formatLanguageCode(s))}),o}}const an={zero:0,one:1,two:2,few:3,many:4,other:5},cn={select:e=>e===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Ri{constructor(t,r={}){this.languageUtils=t,this.options=r,this.logger=me.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(t,r={}){const n=Ze(t==="dev"?"en":t),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!"),cn;if(!t.match(/-|_/))return cn;const c=this.languageUtils.getLanguagePartFromCode(t);s=this.getRule(c,r)}return this.pluralRulesCache[i]=s,s}needsPlural(t,r={}){let n=this.getRule(t,r);return n||(n=this.getRule("dev",r)),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(t,r,n={}){return this.getSuffixes(t,n).map(o=>`${r}${o}`)}getSuffixes(t,r={}){let n=this.getRule(t,r);return n||(n=this.getRule("dev",r)),n?n.resolvedOptions().pluralCategories.sort((o,i)=>an[o]-an[i]).map(o=>`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${o}`):[]}getSuffix(t,r,n={}){const o=this.getRule(t,n);return o?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${o.select(r)}`:(this.logger.warn(`no plural rule found for: ${t}`),this.getSuffix("dev",r,n))}}const un=(e,t,r,n=".",o=!0)=>{let i=hi(e,t,r);return!i&&o&&x(r)&&(i=Ht(e,r,n),i===void 0&&(i=Ht(t,r,n))),i},Wt=e=>e.replace(/\$/g,"$$$$");class dn{constructor(t={}){this.logger=me.create("interpolator"),this.options=t,this.format=t?.interpolation?.format||(r=>r),this.init(t)}init(t={}){t.interpolation||(t.interpolation={escapeValue:!0});const{escape:r,escapeValue:n,useRawValueToEscape:o,prefix:i,prefixEscaped:s,suffix:a,suffixEscaped:c,formatSeparator:u,unescapeSuffix:d,unescapePrefix:l,nestingPrefix:f,nestingPrefixEscaped:m,nestingSuffix:y,nestingSuffixEscaped:g,nestingOptionsSeparator:_,maxReplaces:R,alwaysFormat:$}=t.interpolation;this.escape=r!==void 0?r:$i,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=i?Pe(i):s||"{{",this.suffix=a?Pe(a):c||"}}",this.formatSeparator=u||",",this.unescapePrefix=d?"":l||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=f?Pe(f):m||Pe("$t("),this.nestingSuffix=y?Pe(y):g||Pe(")"),this.nestingOptionsSeparator=_||",",this.maxReplaces=R||1e3,this.alwaysFormat=$!==void 0?$:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(r,n)=>r?.source===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(t,r,n,o){let i,s,a;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=m=>{if(m.indexOf(this.formatSeparator)<0){const R=un(r,c,m,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(R,void 0,n,{...o,...r,interpolationkey:m}):R}const y=m.split(this.formatSeparator),g=y.shift().trim(),_=y.join(this.formatSeparator).trim();return this.format(un(r,c,g,this.options.keySeparator,this.options.ignoreJSONStructure),_,n,{...o,...r,interpolationkey:g})};this.resetRegExp();const d=o?.missingInterpolationHandler||this.options.missingInterpolationHandler,l=o?.interpolation?.skipOnVariables!==void 0?o.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:m=>Wt(m)},{regex:this.regexp,safeValue:m=>this.escapeValue?Wt(this.escape(m)):Wt(m)}].forEach(m=>{for(a=0;i=m.regex.exec(t);){const y=i[1].trim();if(s=u(y),s===void 0)if(typeof d=="function"){const _=d(t,i,o);s=x(_)?_:""}else if(o&&Object.prototype.hasOwnProperty.call(o,y))s="";else if(l){s=i[0];continue}else this.logger.warn(`missed to pass in variable ${y} for interpolating ${t}`),s="";else!x(s)&&!this.useRawValueToEscape&&(s=Kr(s));const g=m.safeValue(s);if(t=t.replace(i[0],g),l?(m.regex.lastIndex+=s.length,m.regex.lastIndex-=i[0].length):m.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),t}nest(t,r,n={}){let o,i,s;const a=(c,u)=>{const d=this.nestingOptionsSeparator;if(c.indexOf(d)<0)return c;const l=c.split(new RegExp(`${Pe(d)}[ ]*{`));let f=`{${l[1]}`;c=l[0],f=this.interpolate(f,s);const m=f.match(/'/g),y=f.match(/"/g);((m?.length??0)%2===0&&!y||(y?.length??0)%2!==0)&&(f=f.replace(/'/g,'"'));try{s=JSON.parse(f),u&&(s={...u,...s})}catch(g){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,g),`${c}${d}${f}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,c};for(;o=this.nestingRegexp.exec(t);){let c=[];s={...n},s=s.replace&&!x(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(d=>d.trim()).filter(Boolean),o[1]=o[1].slice(0,u)),i=r(a.call(this,o[1].trim(),s),s),i&&o[0]===t&&!x(i))return i;x(i)||(i=Kr(i)),i||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${t}`),i=""),c.length&&(i=c.reduce((d,l)=>this.format(d,l,n.lng,{...n,interpolationkey:o[1].trim()}),i.trim())),t=t.replace(o[0],i),this.regexp.lastIndex=0}return t}}const Oi=e=>{let t=e.toLowerCase().trim();const r={};if(e.indexOf("(")>-1){const n=e.split("(");t=n[0].toLowerCase().trim();const o=n[1].substring(0,n[1].length-1);t==="currency"&&o.indexOf(":")<0?r.currency||(r.currency=o.trim()):t==="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,""),d=a.trim();r[d]||(r[d]=u),u==="false"&&(r[d]=!1),u==="true"&&(r[d]=!0),isNaN(u)||(r[d]=parseInt(u,10))}})}return{formatName:t,formatOptions:r}},pn=e=>{const t={};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=t[s];return a||(a=e(Ze(n),o),t[s]=a),a(r)}},bi=e=>(t,r,n)=>e(Ze(r),n)(t);class Ni{constructor(t={}){this.logger=me.create("formatter"),this.options=t,this.init(t)}init(t,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?pn:bi;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(t,r){this.formats[t.toLowerCase().trim()]=r}addCached(t,r){this.formats[t.toLowerCase().trim()]=pn(r)}format(t,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:d}=Oi(c);if(this.formats[u]){let l=a;try{const f=o?.formatParams?.[o.interpolationkey]||{},m=f.locale||f.lng||o.locale||o.lng||n;l=this.formats[u](a,m,{...d,...o,...f})}catch(f){this.logger.warn(f)}return l}else this.logger.warn(`there was no format function for ${u}`);return a},t)}}const Pi=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class Ti extends ft{constructor(t,r,n,o={}){super(),this.backend=t,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=me.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(t,r,n,o){const i={},s={},a={},c={};return t.forEach(u=>{let d=!0;r.forEach(l=>{const f=`${u}|${l}`;!n.reload&&this.store.hasResourceBundle(u,l)?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),c[l]===void 0&&(c[l]=!0)))}),d||(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(t,r,n){const o=t.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[t]=r?-1:2,r&&n&&(this.state[t]=0);const a={};this.queue.forEach(c=>{yi(c.loaded,[i],s),Pi(c,t),r&&c.errors.push(r),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(u=>{a[u]||(a[u]={});const d=c.loaded[u];d.length&&d.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(t,r,n,o=0,i=this.retryTimeout,s){if(!t.length)return s(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:r,fcName:n,tried:o,wait:i,callback:s});return}this.readingCalls++;const a=(u,d)=>{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&&d&&o<this.maxRetries){setTimeout(()=>{this.read.call(this,t,r,n,o+1,i*2,s)},i);return}s(u,d)},c=this.backend[n].bind(this.backend);if(c.length===2){try{const u=c(t,r);u&&typeof u.then=="function"?u.then(d=>a(null,d)).catch(a):a(null,u)}catch(u){a(u)}return}return c(t,r,a)}prepareLoading(t,r,n={},o){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),o&&o();x(t)&&(t=this.languageUtils.toResolveHierarchy(t)),x(r)&&(r=[r]);const i=this.queueLoad(t,r,n,o);if(!i.toLoad.length)return i.pending.length||o(),null;i.toLoad.forEach(s=>{this.loadOne(s)})}load(t,r,n){this.prepareLoading(t,r,{},n)}reload(t,r,n){this.prepareLoading(t,r,{reload:!0},n)}loadOne(t,r=""){const n=t.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(t,s,a)})}saveMissing(t,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 d;u.length===5?d=u(t,r,n,o,c):d=u(t,r,n,o),d&&typeof d.then=="function"?d.then(l=>a(null,l)).catch(a):a(null,d)}catch(d){a(d)}else u(t,r,n,o,a,c)}!t||!t[0]||this.store.addResource(t[0],r,n,o)}}}const zt=()=>({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:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),x(e[1])&&(t.defaultValue=e[1]),x(e[2])&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const r=e[3]||e[2];Object.keys(r).forEach(n=>{t[n]=r[n]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),ln=e=>(x(e.ns)&&(e.ns=[e.ns]),x(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),x(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),typeof e.initImmediate=="boolean"&&(e.initAsync=e.initImmediate),e),mt=()=>{},Li=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(r=>{typeof e[r]=="function"&&(e[r]=e[r].bind(e))})},fn="__i18next_supportNoticeShown",Di=()=>!!(typeof globalThis<"u"&&globalThis[fn]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),Ci=()=>{typeof globalThis<"u"&&(globalThis[fn]=!0)},qi=e=>!!(e?.modules?.backend?.name?.indexOf("Locize")>0||e?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||e?.options?.backend?.backends&&e.options.backend.backends.some(t=>t?.name?.indexOf("Locize")>0||t?.constructor?.name?.indexOf("Locize")>0)||e?.options?.backend?.projectId||e?.options?.backend?.backendOptions&&e.options.backend.backendOptions.some(t=>t?.projectId));class ut extends ft{constructor(t={},r){if(super(),this.options=ln(t),this.services={},this.logger=me,this.modules={external:[]},Li(this),r&&!this.isInitialized&&!t.isClone){if(!this.options.initAsync)return this.init(t,r),this;setTimeout(()=>{this.init(t,r)},0)}}init(t={},r){this.isInitializing=!0,typeof t=="function"&&(r=t,t={}),t.defaultNS==null&&t.ns&&(x(t.ns)?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));const n=zt();this.options={...n,...this.options,...ln(t)},this.options.interpolation={...n.interpolation,...this.options.interpolation},t.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=t.keySeparator),t.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=t.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!qi(this)&&!Di()&&(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}"),Ci());const o=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?me.init(o(this.modules.logger),this.options):me.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=Ni;const d=new sn(this.options);this.store=new tn(this.options.resources,this.options);const l=this.services;l.logger=me,l.resourceStore=this.store,l.languageUtils=d,l.pluralResolver=new Ri(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"),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 dn(this.options),l.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},l.backendConnector=new Ti(o(this.modules.backend),l.resourceStore,l,this.options),l.backendConnector.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.languageDetector&&(l.languageDetector=o(this.modules.languageDetector),l.languageDetector.init&&l.languageDetector.init(l,this.options.detection,this.options)),this.modules.i18nFormat&&(l.i18nFormat=o(this.modules.i18nFormat),l.i18nFormat.init&&l.i18nFormat.init(this)),this.translator=new Ft(this.services,this.options),this.translator.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.external.forEach(m=>{m.init&&m.init(this)})}if(this.format=this.options.interpolation.format,r||(r=mt),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]=(...d)=>this.store[u](...d)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...d)=>(this.store[u](...d),this)});const a=Ke(),c=()=>{const u=(d,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(d,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(t,r=mt){let n=r;const o=x(t)?t:this.language;if(typeof t=="function"&&(n=t),!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(t,r,n){const o=Ke();return typeof t=="function"&&(n=t,t=void 0),typeof r=="function"&&(n=r,r=void 0),t||(t=this.languages),r||(r=this.options.ns),n||(n=mt),this.services.backendConnector.reload(t,r,i=>{o.resolve(),n(i)}),o}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&rn.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-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(t)<0&&this.store.hasLanguageSomeTranslations(t)&&(this.resolvedLanguage=t,this.languages.unshift(t))}}changeLanguage(t,r){this.isLanguageChangingTo=t;const n=Ke();this.emit("languageChanging",t);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===t&&(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=>{!t&&!a&&this.services.languageDetector&&(a=[]);const c=x(a)?a:a&&a[0],u=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(x(a)?[a]:a);u&&(this.language||o(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,d=>{i(d,u)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?s(this.services.languageDetector.detect()):!t&&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(t),n}getFixedT(t,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=je(c.keyPrefix,u));const d=this.options.keySeparator||".";let l;return c.keyPrefix&&Array.isArray(i)?l=i.map(f=>(typeof f=="function"&&(f=je(f,u)),`${c.keyPrefix}${d}${f}`)):(typeof i=="function"&&(i=je(i,u)),l=c.keyPrefix?`${c.keyPrefix}${d}${i}`:i),this.t(l,c)};return x(t)?o.lng=t:o.lngs=t,o.ns=r,o.keyPrefix=n,o}t(...t){return this.translator?.translate(...t)}exists(...t){return this.translator?.exists(...t)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t,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,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||s(n,t)&&(!o||s(i,t)))}loadNamespaces(t,r){const n=Ke();return this.options.ns?(x(t)&&(t=[t]),t.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(t,r){const n=Ke();x(t)&&(t=[t]);const o=this.options.preload||[],i=t.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(t){if(t||(t=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!t)return"rtl";try{const o=new Intl.Locale(t);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 sn(zt());return t.toLowerCase().indexOf("-latn")>1?"ltr":r.indexOf(n.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(t={},r){const n=new ut(t,r);return n.createInstance=ut.createInstance,n}cloneInstance(t={},r=mt){const n=t.forkResourceStore;n&&delete t.forkResourceStore;const o={...this.options,...t,isClone:!0},i=new ut(o);if((t.debug!==void 0||t.prefix!==void 0)&&(i.logger=i.logger.clone(t)),["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((d,l)=>(d[l]={...c[u][l]},d),c[u]),c),{});i.store=new tn(a,o),i.services.resourceStore=i.store}if(t.interpolation){const c={...zt().interpolation,...this.options.interpolation,...t.interpolation},u={...o,interpolation:c};i.services.interpolator=new dn(u)}return i.translator=new Ft(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 ie=ut.createInstance(),Ui=ie.createInstance;ie.dir,ie.init,ie.loadResources,ie.reloadResources,ie.use,ie.changeLanguage,ie.getFixedT,ie.t,ie.exists,ie.setDefaultNamespace,ie.hasLoadedNamespace,ie.loadNamespaces,ie.loadLanguages;const mn={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.$hierarchyLevel":"{operandName}{levelSuffix} level","operator.$least":"Least of {inputNames}","operator.$greatest":"Greatest of {inputNames}","operator.$dateBucket":"{operandName} by {granularity}","operator.$periodBoundary.start":"{operandName} at period start","operator.$periodBoundary.end":"{operandName} at period end","operator.$periodValue.start":"{operandName} at period start","operator.$periodValue.end":"{operandName} at period end","operator.$periodShift":"{operandName} {comparison} baseline","operator.$periodGrowth":"{operandName} {comparison} growth","operator.$periodDifference":"{operandName} {comparison} difference","operator.$averagePerPeriod":"Average {operandName} per {granularity}","operator.$newly":"New {operandName}","operator.$shareOfTotal":"{operandName} share of total","component.numerator":"{outputName} numerator","component.denominator":"{outputName} denominator","component.current":"{outputName} current","component.previous":"{outputName} previous","component.start":"{outputName} start","component.end":"{outputName} end","period.comparison":"period-over-period","period.current":"current-period","period.yearOverYear":"year-over-year","period.monthOverMonth":"month-over-month","period.weekOverWeek":"week-over-week","time.granularity.second":"second","time.granularity.minute":"minute","time.granularity.hour":"hour","time.granularity.day":"day","time.granularity.week":"week","time.granularity.month":"month","time.granularity.quarter":"quarter","time.granularity.year":"year","time.granularity.period":"period","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal requires a property","sql.timeWatermark":"Resolve time watermark to keep year-over-year and period-over-period comparison ranges consistent","sql.entityExpansion":"Expand entities to obtain more information","sql.computation":"Numeric computation","sql.semanticResolution":"Semantic resolution"}},yn={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.$hierarchyLevel":"{operandName}{level}\u5C42\u7EA7","operator.$least":"{inputNames}\u4E2D\u7684\u6700\u65E9\u503C","operator.$greatest":"{inputNames}\u4E2D\u7684\u6700\u665A\u503C","operator.$dateBucket":"{operandName}\uFF08\u6309{granularity}\uFF09","operator.$periodBoundary.start":"{operandName}\u671F\u521D","operator.$periodBoundary.end":"{operandName}\u671F\u672B","operator.$periodValue.start":"{operandName}\u671F\u521D\u503C","operator.$periodValue.end":"{operandName}\u671F\u672B\u503C","operator.$periodShift":"{operandName}{comparison}\u57FA\u671F\u503C","operator.$periodGrowth":"{operandName}{comparison}\u589E\u957F\u7387","operator.$periodDifference":"{operandName}{comparison}\u5DEE\u503C","operator.$averagePerPeriod":"{operandName}{granularity}\u5747\u503C","operator.$newly":"\u65B0\u589E{operandName}","operator.$shareOfTotal":"{operandName}\u5360\u6BD4","component.numerator":"{outputName}\u5206\u5B50","component.denominator":"{outputName}\u5206\u6BCD","component.current":"{outputName}\u672C\u671F","component.previous":"{outputName}\u4E0A\u671F","component.start":"{outputName}\u5F00\u59CB","component.end":"{outputName}\u7ED3\u675F","period.comparison":"\u540C\u671F","period.current":"\u672C\u671F","period.yearOverYear":"\u540C\u6BD4","period.monthOverMonth":"\u73AF\u6BD4","period.weekOverWeek":"\u5468\u73AF\u6BD4","time.granularity.second":"\u79D2","time.granularity.minute":"\u5206\u949F","time.granularity.hour":"\u5C0F\u65F6","time.granularity.day":"\u65E5","time.granularity.week":"\u5468","time.granularity.month":"\u6708","time.granularity.quarter":"\u5B63\u5EA6","time.granularity.year":"\u5E74","time.granularity.period":"\u5468\u671F","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal\u9700\u8981pred\u53C2\u6570","sql.timeWatermark":"\u8BA1\u7B97\u6570\u636E\u6700\u540E\u65F6\u95F4\uFF0C\u4ECE\u800C\u4FDD\u8BC1\u540C\u6BD4\u3001\u73AF\u6BD4\u7684\u6BD4\u8F83\u533A\u95F4\u4E00\u81F4","sql.entityExpansion":"\u5B9E\u4F53\u5C55\u5F00\uFF0C\u7528\u4E8E\u83B7\u5F97\u66F4\u591A\u4FE1\u606F","sql.computation":"\u6570\u503C\u8BA1\u7B97","sql.semanticResolution":"\u8BED\u4E49\u89E3\u6790"}},ji=[yn,mn],Xe=e=>e.trim().toLowerCase(),ki=e=>e?"locale"in e?[e]:e:[],Mi=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.locale=="string"&&t.locale.trim().length>0&&typeof t.messages=="object"&&t.messages!==null&&!Array.isArray(t.messages)};class Kt{definitions=new Map;i18n;constructor(t){this.i18n=Ui(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(ji),this.register(t)}register(t){for(const r of ki(t)){const n=r;if(!Mi(n))throw new TypeError("Locale definition must have a non-empty locale");const o=n,i=this.definitions.get(Xe(o.locale)),s={locale:o.locale,messages:Object.freeze({...i?.messages,...o.messages})};this.definitions.set(Xe(o.locale),s),this.i18n.addResourceBundle(o.locale,"translation",s.messages,!0,!0)}return this}resolve(t="zh-CN"){const r=this.definitions.get(Xe(t));if(r)return r;const n=Xe(t).split("-")[0];return[...this.definitions.entries()].find(([i])=>i.split("-")[0]===n)?.[1]??this.definitions.get("zh-cn")}has(t){return this.definitions.has(Xe(t))}translate(t,r,n,o){const i=this.resolve(t);return this.i18n.t(r,{lng:i.locale,defaultValue:n??r,...o??{}})}translator(t="zh-CN"){return(r,n,o)=>this.translate(t,r,n,o)}}const yt=e=>new Kt(e),ht=new Kt;class p extends Error{code;details;constructor(t,r,n){super(r),this.code=t,this.details=n,this.name="SemanticDBError"}localizedMessage(t="zh-CN",r=ht){if(this.code==="PRED_PROPERTY_REQUIRED"&&this.message==="$shareOfTotal requires a property")return r.translate(t,"error.PRED_PROPERTY_REQUIRED.$shareOfTotal",this.message,this.details);if(this.code==="PROPERTY_NOT_FOUND"&&t.toLowerCase().startsWith("en")){const n=this.details?.schemaId,o=this.details?.schemaName,i=this.details?.property,s=this.details?.propertyName;if(typeof n=="string"&&typeof o=="string"&&typeof i=="string"&&typeof s=="string")return`Property not found in Schema: ${o}(${n}): ${s}`}return this.message}}J.extend(dt),J.extend(pt);const xi=new Set(["year","quarter","month","week"]),Jt=e=>e.format("YYYY-MM-DD HH:mm:ss"),Zt=(e,t)=>e.operator&&t(e.operator).kind==="aggregate"?!0:(e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)?Zt(e.pred,t):!1)||Array.isArray(e.pred)&&e.pred.some(r=>typeof r!="string"&&Zt(r,t)),gt=(e,t,r)=>{if(e.kind==="window"||e.kind==="cumulative")throw new p("ACCUMULATE_WINDOW_UNSUPPORTED","$accumulate cannot contain another window expression");if(e.kind==="ordinal-decode")return{...e,input:gt(e.input,t,r)};if(e.kind==="ordinal-encode")return{kind:"cumulative",function:"sum",input:e,...r};if(e.kind!=="operator")return{kind:"cumulative",function:"sum",input:e,...r};const n=t.getOperator(e.operator);if(n.kind==="component")throw new p("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain component operator ${e.operator}`);if(n.kind==="aggregate"){if(e.operator==="$avg"){const s={...e,operator:"$sum"},a={...e,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"}[e.operator];if(!i)throw new p("ACCUMULATE_OPERATOR_UNSUPPORTED",`Aggregate operator ${e.operator} does not declare cumulative semantics`);return{kind:"cumulative",function:i,input:e,...r}}if(n.kind!=="scalar")throw new p("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain ${e.operator}`);return{...e,...e.input?{input:gt(e.input,t,r)}:{},...e.inputs?{inputs:e.inputs.map(o=>gt(o,t,r))}:{}}},Vi=e=>{if(!e.input||e.inputs.length>0||e.pred.query)throw new p("INVALID_ACCUMULATE_INPUT","$accumulate requires exactly one nested pred and does not accept pred.query");if(e.inputProperty?.comparable&&e.input.kind!=="ordinal-decode")throw new p("ACCUMULATE_COMPARABLE_OPERATOR_REQUIRED","$accumulate over a comparable category requires an explicit $min or $max metric");const t=e.args.partitionBy??[],r=e.args.orderBy;if(!Array.isArray(t)||t.some(o=>typeof o!="string"))throw new p("INVALID_ACCUMULATE_ARGS","$accumulate partitionBy must be an array of groupby names");if(!Array.isArray(r)||r.length===0)throw new p("INVALID_ACCUMULATE_ARGS","$accumulate requires a non-empty args.orderBy array");const n=r.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw new p("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require pred and optional direction");const{pred:i,direction:s="asc",...a}=o;if(typeof i!="string"||s!=="asc"&&s!=="desc"||Object.keys(a).length>0)throw new p("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require only a string pred and asc/desc direction");return{expression:e.resolveKey(i),direction:s==="asc"?"ASC":"DESC"}});return gt(e.input,e,{partitionBy:t.map(o=>e.resolveKey(String(o))),orderBy:n})},vi=e=>{if(e.groupByNames.length===0)return;if(typeof e.pred.pred!="object"||Array.isArray(e.pred.pred)||!Zt(e.pred.pred,e.getOperator))throw new p("ACCUMULATE_AGGREGATE_REQUIRED","$accumulate over a grouped physical relation requires an aggregate expression");const t=e.pred.args?.partitionBy,r=e.pred.args?.orderBy;if(t!==void 0&&!Array.isArray(t)||!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=[...t??[],...r.map(i=>i.pred)];if(n.some(i=>typeof i!="string"))return;const o=n.map(i=>e.resolveGroupName(String(i)));if(o.length!==e.groupByNames.length||new Set(o).size!==e.groupByNames.length||e.groupByNames.some(i=>!o.includes(i)))throw new p("INCOMPLETE_ACCUMULATE_DIMENSIONS","$accumulate partitionBy and orderBy must cover every groupby item exactly once",{expected:e.groupByNames,received:o})},Bi=(e,t,r)=>{if(e.from||e.having)throw new p("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period currently requires a physical LogicForm without from or having");if((e.preds?.length??0)!==t.length)throw new p("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period cannot currently be mixed with non-period projections");const n=e.query&&Object.entries(e.query).find(([,h])=>{if(typeof h!="object"||h===null||Array.isArray(h))return!1;const S=h;return typeof S.$gte=="string"&&typeof S.$lte=="string"});if(!n)throw new p("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires one bounded date query identifying the target period");const[o,i]=n,s=i,a=J(String(s.$gte)),c=J(String(s.$lte));if(!a.isValid()||!c.isValid())throw new p("ACCUMULATE_PERIOD_QUERY_REQUIRED","Target date range is invalid");const u=t.map(h=>{if(!h.name)throw new p("MISSING_PRED_NAME","$accumulate args.period requires normalized names");return h.name}),d=r==="week"?a.startOf("isoWeek"):a.startOf(r),l={...e.query,[o]:{...s,$gte:Jt(d)}},f=new Set([...(e.groupby??[]).map(({name:h})=>h),...(e.preds??[]).map(({name:h})=>h)]),m=h=>{let S=h;for(;f.has(S);)S=`_${S}`;return f.add(S),S},y=m("__accumulate_period"),g=t.map((h,S)=>m(`__accumulate_metric_${S}`)),_=(e.groupby??[]).map(({name:h})=>String(h)),R=r==="year"||r==="quarter"?"month":"day",$={version:e.version,...e.schema?{schema:e.schema}:{},query:l,groupby:[...e.groupby??[],{operator:"$dateBucket",pred:o,args:{granularity:R},name:y}],preds:t.map((h,S)=>({...h.pred,name:g[S]??`__accumulate_metric_${S}`}))},E={version:e.version,from:$,preds:[..._.map(h=>({pred:h,name:h})),{pred:y,name:y},...t.map((h,S)=>({operator:"$accumulate",pred:g[S]??`__accumulate_metric_${S}`,args:{partitionBy:_,orderBy:[{pred:y,direction:"asc"}]},name:u[S]??`accumulate_${S}`}))]};return{version:e.version,from:E,query:{[y]:{$gte:Jt(a),$lte:Jt(c)}},preds:[..._.map(h=>({pred:h,name:h})),...u.map(h=>({pred:h,name:h}))],...e.sort?{sort:e.sort}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.page!==void 0?{page:e.page}:{},...e.output?{output:e.output}:{},...e.representation?{representation:e.representation}:{}}},Fi={name:"$accumulate",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`Cumulative ${e}`:`${e}\u7D2F\u8BA1\u503C`,kind:"logical",normalizePred({pred:e}){const t=e.args?.period;if(t!==void 0&&(typeof t!="string"||!xi.has(t)))throw new p("INVALID_ACCUMULATE_ARGS","$accumulate args.period must be year, quarter, month, or week");if(t!==void 0&&(e.args?.partitionBy!==void 0||e.args?.orderBy!==void 0))throw new p("INVALID_ACCUMULATE_ARGS","$accumulate args.period cannot be combined with partitionBy or orderBy");return e},planExpression:Vi,validatePlan:vi,rewriteLogicform({logicform:e,schema:t}){const r=(e.preds??[]).filter(s=>s.operator==="$accumulate"&&s.args?.period!==void 0);if(r.length===0)return;const n=r[0]?.args?.period;if(r.some(s=>s.args?.period!==n))throw new p("ACCUMULATE_PERIOD_UNSUPPORTED","All $accumulate args.period projections in one LogicForm must use the same period");const o=new Set(Object.keys(e.query??{}));if(t.properties.filter(s=>s.primal_type==="date"&&o.has(s.name)).length!==1)throw new p("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires exactly one queried date property");return Bi(e,r,n)},getOutputProperty({name:e,inputProperty:t}){return t?{...t,name:e,isArray:!1}:{name:e,type:"number",primal_type:"number",isArray:!1}}},Yi={name:"$abs",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`Absolute ${e}`:`${e}\u7EDD\u5BF9\u503C`,kind:"scalar",toSQL({expression:e}){if(!e)throw new p("PRED_PROPERTY_REQUIRED","$abs requires a pred");return`ABS(${e})`},getOutputProperty({name:e,inputProperty:t}){if(!t)throw new p("PRED_PROPERTY_REQUIRED","$abs requires a pred");return{...t,name:e,isArray:!1}}},ke=(e,t,r,n=r)=>{const o=t.expressions??[];if(o.length<r||o.length>n)throw new p("INVALID_OPERATOR_COMPONENTS",`${e} requires ${r===n?String(r):`${r}-${n}`} pred inputs`);return o},$t=e=>({name:e,type:"number",primal_type:"number",isArray:!1}),Qi={name:"$add",defaultName:({operandName:e,inputNames:t,locale:r})=>r.toLowerCase().startsWith("en")?t.length>0?t.join(" plus "):`Sum of ${e}`:t.length>0?t.join("\u52A0"):`${e}\u6C42\u548C`,kind:"scalar",requiresProperty:!1,toSQL(e){return`(${ke("$add",e,2,Number.POSITIVE_INFINITY).join(" + ")})`},getOutputProperty({name:e,inputProperties:t}){const r=t?.[0];return r?{...r,name:e,isArray:!1}:$t(e)}},Y=e=>structuredClone(e),Hi=(e,t)=>{const r=t[e];if(!r)throw new p("SCHEMA_NOT_FOUND",`Schema not found: ${e}`,{schemaId:e});if("_id"in r||"_sid"in r)throw new p("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported",{schemaId:e});if("sid"in r)throw new p("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid",{schemaId:e});if(r.id!==e)throw new p("SCHEMA_ID_MISMATCH",`Schema registry key ${e} does not match schema.id ${r.id}`,{registryKey:e,schemaId:r.id});return r},Gi=(e,t)=>{const r=e.properties.find(n=>n.id===t)??e.properties.find(n=>n.name===t);if(!r)throw new p("PROPERTY_NOT_FOUND",`Property not found in ${e.id}: ${t}`,{schemaId:e.id,property:t});return r},Wi=e=>{const t=e.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(t))},hn=(e,t)=>e.properties.some(r=>r!==t&&r.id===t.name)?t.id:t.name,zi=(e,t)=>e.properties.flatMap(r=>[...t.startsWith(`${r.id}_`)?[{property:r,prefix:r.id}]:[],...r.name!==r.id&&t.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)),z=(e,t,r)=>{const n=e.properties.find(o=>o.id===t)??e.properties.find(o=>o.name===t);if(n)return{canonicalName:hn(e,n),canonicalId:n.id,schema:e,property:n,relations:[]};for(const{property:o,prefix:i}of zi(e,t)){if(o.primal_type!=="entity"&&o.primal_type!=="object"||!o.ref)continue;if(!r)throw new p("SCHEMA_RESOLVER_REQUIRED",`Resolving property path ${t} requires a Schema resolver`);const s=r(o.ref),a=z(s,t.slice(i.length+1),r);return{canonicalName:`${hn(e,o)}_${a.canonicalName}`,canonicalId:`${o.id}_${a.canonicalId}`,schema:a.schema,property:a.property,relations:[{sourceSchema:e,property:o,targetSchema:s},...a.relations]}}throw new p("PROPERTY_NOT_FOUND",`\u5728 Schema\uFF1A${e.name}(${e.id})\u4E2D\u672A\u627E\u5230\u5C5E\u6027: ${t}`,{schemaId:e.id,schemaName:e.name,property:t,propertyName:t})},Xt=(e,t)=>e.name===t||e.id===t,Ki=(e,t,r)=>{const n=new Set,o=[e];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=>Xt(a,i.hierarchy?.up??"")):[],...r.properties.filter(a=>a.hierarchy?.down!==void 0&&Xt(i,a.hierarchy.down))];if(s.some(a=>Xt(t,a.name)))return!0;o.push(...s)}return!1},gn=(e,t,r,n)=>{if(e.operator||typeof e.pred!="string"||t.length===0)return!1;let o;try{o=z(r,e.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:t.some(i=>{if(i.operator||typeof i.pred!="string")return!1;let s;try{s=z(r,i.pred,n)}catch{return!1}if(s.property.isArray)return!1;if(s.relations.length===0&&o.relations.length===0)return Ki(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})},Ji=({source:e,properties:t})=>{const r=e.hierarchy;if(!Array.isArray(r))return r===void 0?{}:{hierarchy:r};let n=e.hierarchy_property;if(typeof n!="string"||n.length===0){const s=t.filter(({type:c})=>c==="ID");if(s.length!==1)throw new p("LEGACY_HIERARCHY_ID_PROPERTY_REQUIRED","Legacy Schema hierarchy without hierarchy_property must contain exactly one ID property",{idPropertyCount:s.length});const a=s[0];n=a?.id??a?.name}const o=r.map(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return;const a=s;if(!(typeof a.name!="string"||!Number.isInteger(a.code_length)))return{name:a.name,...Array.isArray(a.syno)?{syno:a.syno}:{},codeLength:a.code_length}});if(o.some(s=>s===void 0))return{};const i=r[0];return{hierarchy:{property:n,storage:i?.use_full_length===!0?"zero-padded":"compact",levels:o}}},Zi=e=>{if(!e.hierarchy)return;const t=e.properties.find(({name:r})=>r===e.hierarchy?.property);if(!t)throw new p("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${e.hierarchy.property}`,{schemaId:e.id,property:e.hierarchy.property});return t},Xi=(e,t,r)=>{const n=z(e,t,r);if(n.property.primal_type!=="entity"&&n.property.primal_type!=="object")return{schema:n.schema,reference:n.canonicalName,relation:!1};if(n.property.isArray)throw new p("ARRAY_HIERARCHY_RELATION_UNSUPPORTED",`$hierarchyLevel cannot group an array relation: ${n.canonicalName}`);if(!n.property.ref||!r)throw new p("SCHEMA_RESOLVER_REQUIRED",`$hierarchyLevel requires a Schema resolver for relation ${n.canonicalName}`);return{schema:r(n.property.ref),reference:n.canonicalName,relation:!0}},es={name:"$hierarchyLevel",defaultName:({operandName:e,args:t,locale:r})=>{const n=typeof t.level=="string"?t.level:"";return r.toLowerCase().startsWith("en")?`${e}${n?` ${n}`:""} level`:`${e}${n}\u5C42\u7EA7`},kind:"scalar",planInput({reference:e,args:t,schema:r,resolveSchema:n}){const o=Object.keys(t).filter(m=>m!=="level");if(o.length>0||typeof t.level!="string"||t.level.length===0)throw new p("INVALID_HIERARCHY_LEVEL_ARGS","$hierarchyLevel args must contain exactly one non-empty level string",{unsupportedArgs:o});const i=Xi(r,e,n),s=i.schema.hierarchy;if(!s)throw new p("SCHEMA_HIERARCHY_REQUIRED",`Schema ${i.schema.id} does not declare hierarchy`,{schemaId:i.schema.id});const a=i.schema.properties.find(({name:m})=>m===s.property);if(!a)throw new p("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${s.property}`);if(!i.relation&&a.name!==z(r,e,n).property.name)throw new p("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${a.name}`);let c=0;const u=s.levels.find(m=>(c+=m.codeLength,m.name===t.level||m.syno?.includes(t.level)));if(!u)throw new p("HIERARCHY_LEVEL_NOT_FOUND",`Schema ${i.schema.id} does not declare hierarchy level: ${t.level}`,{schemaId:i.schema.id,level:t.level});const d=s.levels.reduce((m,y)=>m+y.codeLength,0),l=i.schema.properties.filter(({type:m})=>m==="ID");return{reference:i.relation&&l.length===1&&l[0]?.name===a.name?i.reference:i.relation?`${i.reference}_${a.name}`:i.reference,args:{level:u.name,codeLength:c,totalLength:d,storage:s.storage}}},toSQL({expression:e,args:t,sql:r}){if(!e)throw new Error("$hierarchyLevel requires a hierarchy pred");const n=t.codeLength,o=t.totalLength,i=t.storage;if(!Number.isInteger(n)||!Number.isInteger(o)||Number(n)<=0||Number(o)<Number(n)||i!=="compact"&&i!=="zero-padded")throw new p("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const s=r.substring(e,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:e}){return{name:e,type:"string",primal_type:"string",isArray:!1}}},ts={keys:["hierarchy"],resolve(e,t){if("hierarchy_property"in e)throw new p("LEGACY_HIERARCHY_PROPERTY_NOT_ALLOWED","Schema hierarchy must declare hierarchy.property instead of hierarchy_property");const r=e.hierarchy;if(r===void 0)return{};if(typeof r!="object"||r===null||Array.isArray(r))throw new p("INVALID_HIERARCHY","Schema hierarchy must be an object containing property, levels, and optional storage");const n=r,o=Object.keys(n).filter(f=>f!=="property"&&f!=="storage"&&f!=="levels");if(o.length>0)throw new p("UNSUPPORTED_HIERARCHY_FIELD","Schema hierarchy only supports property, storage, and levels",{unsupportedKeys:o});const i=n.property===void 0?(()=>{const f=t.filter(m=>m.type==="ID");if(f.length!==1)throw new p("HIERARCHY_ID_PROPERTY_REQUIRED","Schema hierarchy.property may be omitted only when the Schema has exactly one ID Property",{idPropertyCount:f.length});return f[0]})():void 0;if(n.property!==void 0&&(typeof n.property!="string"||n.property.length===0))throw new p("HIERARCHY_PROPERTY_REQUIRED","Schema hierarchy.property must be a non-empty property name or id when provided");const s=i??t.find(f=>f.name===n.property||f.id===n.property);if(!s)throw new p("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${n.property}`,{property:n.property});if(s.primal_type!=="string")throw new p("INVALID_HIERARCHY_PROPERTY",`Hierarchy property ${s.name} must have primal_type string`,{property:s.name,primal_type:s.primal_type});const a=n.storage??"compact";if(a!=="compact"&&a!=="zero-padded")throw new p("INVALID_HIERARCHY_STORAGE","Schema hierarchy.storage must be compact or zero-padded");if(!Array.isArray(n.levels)||n.levels.length===0)throw new p("HIERARCHY_LEVELS_REQUIRED","Schema hierarchy.levels must be a non-empty array");const c=new Set,u=new Set,d=n.levels.map((f,m)=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new p("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} must be an object`);const y=f,g=Object.keys(y).filter(R=>R!=="name"&&R!=="syno"&&R!=="codeLength");if(g.length>0)throw new p("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${m} only supports name, syno, and codeLength`,{unsupportedKeys:g});if(typeof y.name!="string"||y.name.length===0)throw new p("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} name must not be empty`);if(c.has(y.name)||u.has(y.name))throw new p("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level name: ${y.name}`);if(!Number.isInteger(y.codeLength)||Number(y.codeLength)<=0)throw new p("INVALID_HIERARCHY_CODE_LENGTH",`Hierarchy level ${y.name} codeLength must be a positive integer`);if(y.syno!==void 0&&(!Array.isArray(y.syno)||y.syno.some(R=>typeof R!="string"||R.length===0)))throw new p("INVALID_HIERARCHY_SYNONYMS",`Hierarchy level ${y.name} syno must contain only non-empty strings`);const _=y.syno??[];for(const R of _){if(R===y.name||c.has(R)||u.has(R))throw new p("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${R}`);u.add(R)}return c.add(y.name),{name:y.name,..._.length>0?{syno:[..._]}:{},codeLength:Number(y.codeLength)}});return{hierarchy:{property:s.name,storage:a,levels:d}}}},rs=Object.freeze({name:"hierarchy",schemaMetadata:ts,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:Ji,resolveEntityFilterProperty:Zi,operators:[es]}),$n=Object.freeze([rs]),wt=(e=[])=>{const t=[...$n,...e],r=new Set,n=new Set,o=new Set;for(const i of t){if(!i.name)throw new p("INVALID_PLUGIN","Plugin name must not be empty");if(r.has(i.name))throw new p("PLUGIN_ALREADY_REGISTERED",`Plugin is already registered: ${i.name}`,{plugin:i.name});r.add(i.name);for(const s of[...i.schemaMetadata?.keys??[],...i.legacySchemaKeys??[]]){if(!s)throw new p("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(n.has(s))throw new p("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${s}`,{key:s,plugin:i.name});n.add(s)}for(const s of i.operators??[]){if(o.has(s.name))throw new p("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${s.name}`,{operator:s.name,plugin:i.name});o.add(s.name)}}return Object.freeze(t)},er=e=>typeof e=="string"&&e.length>0&&e!=="placeholder"||typeof e=="number"&&Number.isSafeInteger(e),ns=e=>{const t=e.properties.filter(({type:r})=>r==="ID");if(t.length!==1)throw new p("ENTITY_ID_PROPERTY_REQUIRED",`Schema ${e.id} must contain exactly one ID property to use entity_id`,{schemaId:e.id,idPropertyCount:t.length});return t[0]},tr=(e,t=[])=>{for(const r of wt(t)){const n=r.resolveEntityFilterProperty?.(e);if(n)return n}return ns(e)},rr=e=>{if(e.name)return e.name;throw new p("MISSING_PRED_NAME","A normalized groupby PredItem must have a name")},nr=e=>typeof e.pred=="string"?e.pred:void 0,os=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),is={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},ss={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},or=(e,t,r)=>{const n=t.toLowerCase().startsWith("en"),o=e.time;if(!os(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}${is[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${ss[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};J.extend(dt),J.extend(pt);const as=["second","minute","hour","day","week","month","quarter","year"],cs=new Set(as),ir=["year","quarter","month","week","day","hour","minute","second"],wn=e=>Object.prototype.toString.call(e)==="[object Object]",_e=e=>{throw new p("INVALID_PERIOD_SHIFT_ARGS",e)},us=e=>{const t=e.time;wn(t)||_e("$periodShift requires args.time");const r=t;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!cs.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&_e("Relative period shift time requires only granularity and an integer offset"),r;const o=Object.entries(r);(o.length===0||o.some(([a,c])=>!ir.includes(a)||!Number.isInteger(c)))&&_e("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&_e("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 d=r[a];d!==void 0&&(Number(d)<c||Number(d)>u)&&_e(`Invalid absolute period shift ${a}: ${JSON.stringify(d)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&_e("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&_e("Absolute period shift day requires month"),r},An=(e,t,r)=>t==="month"?e.month(r-1):t==="day"?e.date(r):t==="week"?e.isoWeek(r):t==="quarter"?e.quarter(r):e.set(t,r),ds=(e,t)=>{if("granularity"in t){const n=t.granularity==="week"?"week":t.granularity;return e.add(t.offset,n)}let r=e;for(const n of ir){const o=t[n];typeof o=="number"&&(r=An(r,n,o))}return r},sr=(e,t)=>e instanceof Date?t.toDate():typeof e!="string"?e:t.format(e.includes(":")?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"),ps=(e,t,r,n,o)=>(e.groupby??[]).filter(i=>{const s=nr(i);return s?z(t,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:rr(i),granularity:a,offset:c}}),ar=(e,t,r)=>{if(Array.isArray(e))return e.map(i=>ar(i,t,r));if(wn(e))return Object.fromEntries(Object.entries(e).map(([i,s])=>[i,ar(s,t,r)]));if(!(e instanceof Date)&&typeof e!="string")return e;const n=J(e);if(!n.isValid())return e;const o=ds(n,t);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,sr(e,o)},ls=(e,t,r,n,o)=>{const i=new Set,s=c=>Object.fromEntries(Object.entries(c).map(([u,d])=>{if((u==="$and"||u==="$or")&&Array.isArray(d))return[u,d.map(f=>s(f))];const l=z(t,u,r);return l.property.primal_type!=="date"?[u,d]:(i.add(l.canonicalName),[u,ar(d,n,o)])})),a=s(e);if(i.size===0||o.shiftedValues===0)throw new p("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a concrete date condition in the LogicForm query");if(i.size>1)throw new p("AMBIGUOUS_PERIOD_SHIFT_TIME","$periodShift query contains more than one date property",{properties:[...i]});return a},Te=e=>{const t=e.filter(r=>r!==void 0);if(t.length!==0)return t.length===1?t[0]:{$and:t}},Se=e=>[...e.query?[e.query]:[],...e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)?Se(e.pred):[],...Array.isArray(e.pred)?e.pred.flatMap(r=>typeof r=="string"?[]:Se(r)):[]],fs=(e,t,r)=>{if(!(e instanceof Date)&&typeof e!="string")return e;const n=J(e);if(!n.isValid())return e;if("granularity"in t)return sr(e,n.add(-t.offset,t.granularity));if(!r.originalAnchor)return e;let o=n;for(const i of ir)if(t[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=An(o,i,s)}return sr(e,o)},cr=({logicform:e,pred:t,outputName:r,schema:n,resolveSchema:o})=>{const i=t.pred;(!i||typeof i!="object"||Array.isArray(i))&&_e("$periodShift pred must be a nested metric");const s=us(t.args??{}),a={shiftedValues:0},c=Te([e.query,...Se(t)]);if(!c)throw new p("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const u=ls(c,n,o,s,a),d=Y(i);d.name=r,delete d.query;const l=Y(e);l.query=u,l.preds=[d],delete l.having,delete l.sort,delete l.limit,delete l.page;const f=new Set((e.groupby??[]).filter(m=>{const y=nr(m);return y?z(n,y,o).property.primal_type==="date":!1}).map(rr));return{kind:"query",logicform:l,groupKeyShifts:ps(e,n,o,s,a),mapResult:m=>m.map(y=>{const g={...y};for(const _ of f)g[_]=fs(g[_],s,a);return g})}},ms={name:"$periodShift",defaultName:({operandName:e,args:t,locale:r,t:n})=>{const o=or(t,r,n),i=r.toLowerCase().startsWith("en")?`${e} ${o} baseline`:`${e}${o}\u57FA\u671F\u503C`;return n?.("operator.$periodShift",i,{operandName:e,comparison:o})??i},kind:"component",createComponent:cr,getOutputProperty({name:e,inputProperty:t}){if(!t)throw new Error("$periodShift requires a nested metric");return{...t,name:e,isArray:!1}}},ys=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date),At=e=>typeof e=="string"||typeof e=="number"||e instanceof Date,En=(e,t)=>{const r=e.properties.find(({type:n})=>n==="timestamp");if(!r)throw new p("TIMESTAMP_PROPERTY_REQUIRED",`${t} requires a timestamp property in the Schema`);return r},_n=(e,t)=>{if(At(e)){t.start??=e,t.end??=e;return}if(!ys(e))return;const r=e.$eq;At(r)&&(t.start??=r,t.end??=r);const n=e.$gte??e.$gt,o=e.$lte??e.$lt;At(n)&&(t.start??=n),At(o)&&(t.end??=o);for(const i of["$and","$or"]){const s=e[i];if(Array.isArray(s))for(const a of s)_n(a,t)}},hs=(e,t,r,n)=>{const o=En(t,n),i=new Set,s={},a=(l,f)=>{for(const[m,y]of Object.entries(l)){if((m==="$and"||m==="$or")&&Array.isArray(y)){for(const _ of y)a(_,f||m==="$or");continue}if(m.startsWith("$"))continue;const g=z(t,m,r);if(g.property.type==="timestamp"){if(f)throw new p("AMBIGUOUS_TIME_QUERY",`${n} does not support timestamp conditions inside $or`);i.add(g.canonicalName),_n(y,s)}}};if(a(e,!1),i.size!==1)throw new p(i.size===0?"TIME_QUERY_REQUIRED":"AMBIGUOUS_TIME_QUERY",`${n} requires a concrete condition on the Schema timestamp property`);const c=[...i][0];if(!c||c!==o.name)throw new p("AMBIGUOUS_TIME_QUERY",`${n} requires the Schema timestamp property: ${o.name}`);const u=l=>{const f=[];for(const[m,y]of Object.entries(l)){if((m==="$and"||m==="$or")&&Array.isArray(y)){const g=y.map(_=>u(_)).filter(_=>_!==void 0);g.length>0&&f.push([m,g]);continue}!m.startsWith("$")&&z(t,m,r).property.type==="timestamp"||f.push([m,y])}return f.length>0?Object.fromEntries(f):void 0},d=u(e);return{property:o,propertyName:c,...s.start!==void 0?{start:s.start}:{},...s.end!==void 0?{end:s.end}:{},...d?{queryWithoutTime:d}:{}}},Sn=(e,t,r,n,o)=>{const i=Te([e,...Se(t)]);if(!i)throw new p("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return hs(i,r,n,o)},In=(e,t,r)=>Te([e,{[t]:r}]),gs=new Set(["day","week","month","quarter","year"]),$s={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},ws=e=>{if(typeof e!="string"||!gs.has(e))throw new p("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return e},Rn=e=>{const t=Y(e);return delete t.having,delete t.sort,delete t.limit,delete t.page,t},ur=e=>{const t=Y(e);return delete t.query,t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&(t.pred=ur(t.pred)),Array.isArray(t.pred)&&(t.pred=t.pred.map(r=>typeof r=="string"?r:ur(r))),t},As={name:"$averagePerPeriod",defaultName:({operandName:e,args:t,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${e} per ${typeof t.granularity=="string"?t.granularity:"period"}`:`${e}${$s[String(t.granularity)]??"\u5468\u671F"}\u5747\u503C`,kind:"component",createComponent({logicform:e,pred:t,schema:r,outputName:n,t:o}){if(!t.pred||typeof t.pred!="object"||Array.isArray(t.pred))throw new p("INVALID_AVERAGE_PER_PERIOD_INPUT","$averagePerPeriod pred must be a nested metric");const i=ws(t.args?.granularity),s=En(r,"$averagePerPeriod"),a=ur(t.pred),c=Te([e.query,...Se(t)]),u=Rn(e);u.preds=[{...a,name:"__avg_period_num__"}],c&&(u.query=c);const d=Rn(e);d.preds=[{operator:"$countDistinct",pred:{operator:"$dateBucket",pred:s.name,args:{granularity:i},name:"__avg_period_bucket__"},name:"__avg_period_den__"}],c&&(d.query=c);const l=o("component.numerator",`${n}\u5206\u5B50`,{outputName:n}),f=o("component.denominator",`${n}\u5206\u6BCD`,{outputName:n});return{components:[{name:l,logicform:u},{name:f,logicform:d}],expression:`${l} / NULLIF(${f}, 0)`}},getOutputProperty({name:e,inputProperty:t}){if(!t)throw new Error("$averagePerPeriod requires a nested metric");return{...t,name:e,isArray:!1}}},Es={name:"$avg",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`Average ${e}`:`\u5E73\u5747${e}`,kind:"aggregate",toSQL(e){const{column:t,sql:r}=e;if(!t)throw new Error("$avg requires a column");return r.aggregateFunction("avg",t)},getOutputProperty({name:e,property:t,inputProperty:r}){const n=t??r;if(!n)throw new Error("$avg requires a property");return{name:e,type:n.type,primal_type:n.primal_type,isArray:!1}}},_s=e=>{if(e.mode!=="auto")return;const t=e.buckets;if(!Number.isInteger(t)||t<2||t>100)throw new p("INVALID_CASE_ARGS","$case auto mode requires args.buckets to be an integer between 2 and 100");if(Object.hasOwn(e,"cases"))throw new p("INVALID_CASE_ARGS","$case auto mode cannot define args.cases");for(const r of["min","max"])if(e[r]!==void 0&&typeof e[r]!="number"||e[r]!==void 0&&!Number.isFinite(e[r]))throw new p("INVALID_CASE_ARGS",`$case auto mode ${r} must be finite number`);if(e.min===void 0!=(e.max===void 0))throw new p("INVALID_CASE_ARGS","$case auto mode requires both min and max");return t},Ss=e=>{if(!Array.isArray(e)||e.length===0)throw new p("INVALID_CASE_ARGS","$case requires a non-empty args.cases array");return e.map(t=>{if(typeof t!="object"||t===null||!("when"in t)||!("then"in t))throw new p("INVALID_CASE_ARGS","Each $case item requires when and then");const r=t;return{when:r.when,then:r.then}})},Is={name:"$case",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`${e} category`:`${e}\u5206\u7C7B`,kind:"scalar",toSQL({expression:e,args:t,sql:r}){if(!e)throw new p("PRED_PROPERTY_REQUIRED","$case requires a pred");const n=_s(t);if(n!==void 0){const s=t.min===void 0?`MIN(${e}) OVER ()`:r.value(t.min),a=t.max===void 0?`MAX(${e}) OVER ()`:r.value(t.max),c=`(${a} - ${s})`,u=Array.from({length:n-1},(d,l)=>{const f=`${s} + ${c} * ${l+1} / ${n}`;return`WHEN ${e} < ${f} THEN ${r.value(l)}`});return`CASE WHEN ${s} = ${a} THEN ${r.value(0)} ${u.join(" ")} ELSE ${r.value(n-1)} END`}const o=Ss(t.cases).map(({when:s,then:a})=>`WHEN ${r.condition(e,s)} THEN ${r.value(a)}`),i=Object.hasOwn(t,"default")?` ELSE ${r.value(t.default)}`:"";return`CASE ${o.join(" ")}${i} END`},getOutputProperty({name:e}){return{name:e,type:"category",primal_type:"string",isArray:!1}}},Rs={name:"$concat",defaultName:({operandName:e,inputNames:t,locale:r})=>r.toLowerCase().startsWith("en")?t.length>0?`Combined ${t.join(" and ")}`:`Combined ${e}`:t.length>0?`${t.join("\u4E0E")}\u62FC\u63A5\u503C`:`${e}\u62FC\u63A5\u503C`,kind:"scalar",requiresProperty:!1,toSQL(e){return e.sql.concat(ke("$concat",e,1,Number.POSITIVE_INFINITY))},getOutputProperty({name:e}){return{name:e,type:"string",primal_type:"string",isArray:!1}}},Os={name:"$count",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?e==="rows"?"Row count":`${e} count`:e==="\u6570\u636E\u884C"?"\u884C\u6570":`${e}\u6570\u91CF`,kind:"aggregate",requiresProperty:!1,toSQL(e){const{column:t,sql:r}=e;return r.aggregateFunction("count",t)},getOutputProperty({name:e}){return{name:e,type:"int",primal_type:"number",isArray:!1}}},bs={name:"$countDistinct",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`Distinct ${e} count`:`${e}\u53BB\u91CD\u8BA1\u6570`,kind:"aggregate",toSQL(e){const{column:t,sql:r}=e;if(!t)throw new Error("$countDistinct requires a column");return r.aggregateFunction("count",`DISTINCT ${t}`)},getOutputProperty({name:e}){return{name:e,type:"int",primal_type:"number",isArray:!1}}},Ns=new Set(["hour","day","week","month","quarter","year"]),Ps={hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},On=e=>{if(typeof e!="string"||!Ns.has(e))throw new p("INVALID_DATE_BUCKET_ARGS","$dateBucket args.granularity must be hour, day, week, month, quarter, or year");return e},Ts={name:"$dateBucket",defaultName:({operandName:e,args:t,locale:r})=>r.toLowerCase().startsWith("en")?`${e} by ${typeof t.granularity=="string"?t.granularity:"time"}`:`${e}\uFF08\u6309${Ps[String(t.granularity)]??"\u65F6\u95F4"}\uFF09`,kind:"scalar",toSQL({expression:e,args:t,sql:r}){if(!e)throw new Error("$dateBucket requires a date pred");return r.dateBucket(e,On(t.granularity))},getOutputProperty({name:e,inputProperty:t,args:r}){if(!t||t.primal_type!=="date")throw new p("DATE_BUCKET_DATE_REQUIRED","$dateBucket requires a date-valued pred");const n=On(r.granularity);return{...t,name:e,type:"date",primal_type:"date",isArray:!1,granularity:n}}},Ls={name:"$divide",defaultName:({operandName:e,inputNames:t,locale:r})=>r.toLowerCase().startsWith("en")?t.length>=2?`${t[0]} divided by ${t[1]}`:`${e} ratio`:t.length>=2?`${t[0]}\u9664\u4EE5${t[1]}`:`${e}\u6BD4\u503C`,kind:"scalar",requiresProperty:!1,toSQL(e){const[t,r]=ke("$divide",e,2);return`(${t} / NULLIF(${r}, 0))`},getOutputProperty({name:e}){return $t(e)}},Ds=e=>{if(!(!e.inputProperty?.comparable||!e.input))return{kind:"ordinal-decode",comparable:e.inputProperty.comparable,input:{kind:"operator",operator:"$max",args:e.args,...e.pred.query?{query:e.planQuery(e.pred.query)}:{},input:{kind:"ordinal-encode",input:e.input,comparable:e.inputProperty.comparable}}}},Cs={name:"$max",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`Maximum ${e}`:`${e}\u6700\u5927\u503C`,kind:"aggregate",planExpression:Ds,toSQL(e){const{column:t,sql:r}=e;if(!t)throw new Error("$max requires a column");return r.aggregateFunction("max",t)},getOutputProperty({name:e,property:t,inputProperty:r}){const n=t??r;if(!n)throw new Error("$max requires a property");return{name:e,type:n.type,primal_type:n.primal_type,isArray:!1,...n.granularity?{granularity:n.granularity}:{},...n.comparable?{comparable:n.comparable}:{}}}},qs=e=>{if(!(!e.inputProperty?.comparable||!e.input))return{kind:"ordinal-decode",comparable:e.inputProperty.comparable,input:{kind:"operator",operator:"$min",args:e.args,...e.pred.query?{query:e.planQuery(e.pred.query)}:{},input:{kind:"ordinal-encode",input:e.input,comparable:e.inputProperty.comparable}}}},Us={name:"$min",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`Minimum ${e}`:`${e}\u6700\u5C0F\u503C`,kind:"aggregate",planExpression:qs,toSQL(e){const{column:t,sql:r}=e;if(!t)throw new Error("$min requires a column");return r.aggregateFunction("min",t)},getOutputProperty({name:e,property:t,inputProperty:r}){const n=t??r;if(!n)throw new Error("$min requires a property");return{name:e,type:n.type,primal_type:n.primal_type,isArray:!1,...n.granularity?{granularity:n.granularity}:{},...n.comparable?{comparable:n.comparable}:{}}}},js={name:"$multiply",defaultName:({operandName:e,inputNames:t,locale:r})=>r.toLowerCase().startsWith("en")?t.length>0?t.join(" times "):`Product of ${e}`:t.length>0?t.join("\u4E58\u4EE5"):`${e}\u4E58\u79EF`,kind:"scalar",requiresProperty:!1,toSQL(e){return`(${ke("$multiply",e,2,Number.POSITIVE_INFINITY).join(" * ")})`},getOutputProperty({name:e}){return $t(e)}},ks=e=>{const t=Y(e);return delete t.having,delete t.sort,delete t.limit,delete t.page,t},dr=e=>{const t=Y(e);return delete t.query,t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&(t.pred=dr(t.pred)),Array.isArray(t.pred)&&(t.pred=t.pred.map(r=>typeof r=="string"?r:dr(r))),t},Ms={name:"$newly",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`New ${e}`:`\u65B0\u589E${e}`,kind:"component",createComponent({logicform:e,pred:t,schema:r,resolveSchema:n,outputName:o,t:i}){if(!t.pred||typeof t.pred!="object"||Array.isArray(t.pred))throw new p("INVALID_NEWLY_INPUT","$newly pred must be a nested metric");if((e.groupby??[]).some(l=>{const f=nr(l);return f?z(r,f,n).property.type==="timestamp":!1}))throw new p("NEWLY_TIME_GROUPBY_UNSUPPORTED","$newly does not support grouping by the timestamp property");const s=Sn(e.query,t,r,n,"$newly");if(s.start===void 0||s.end===void 0)throw new p("NEWLY_RANGE_REQUIRED","$newly requires both start and end timestamp bounds");const a=dr(t.pred),c=(l,f)=>{const m=ks(e);return m.query=In(s.queryWithoutTime,s.propertyName,{$lte:l}),m.preds=[{...a,name:f}],m},u=i("component.end",`${o}\u7ED3\u675F`,{outputName:o}),d=i("component.start",`${o}\u5F00\u59CB`,{outputName:o});return{components:[{name:u,logicform:c(s.end,"__newly_end__")},{name:d,logicform:c(s.start,"__newly_start__")}],expression:`${u} - COALESCE(${d}, 0)`}},getOutputProperty({name:e,inputProperty:t}){if(!t)throw new Error("$newly requires a nested metric");return{...t,name:e,isArray:!1}}},xs=e=>{const t=Y(e);return delete t.having,delete t.sort,delete t.limit,delete t.page,t},pr=e=>{const t=Y(e);return delete t.query,t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&(t.pred=pr(t.pred)),Array.isArray(t.pred)&&(t.pred=t.pred.map(r=>typeof r=="string"?r:pr(r))),t},Vs={name:"$periodValue",defaultName:({operandName:e,args:t,locale:r})=>r.toLowerCase().startsWith("en")?`${e} at period ${t.boundary==="start"?"start":"end"}`:`${e}${t.boundary==="start"?"\u671F\u521D\u503C":"\u671F\u672B\u503C"}`,kind:"component",observationPolicy({pred:e}){const t=e.args?.boundary;if(t!=="start"&&t!=="end")throw new p("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:t});return{boundary:t,implicit:!1}},createComponent({logicform:e,pred:t,outputName:r,schema:n,resolveSchema:o}){if(!t.pred||typeof t.pred!="object"||Array.isArray(t.pred))throw new p("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");const i=t.args?.boundary;if(i!=="start"&&i!=="end")throw new p("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end");const s=Sn(e.query,t,n,o,"$periodValue"),a=i==="start"?s.start:s.end;if(a===void 0)throw new p("PERIOD_BOUNDARY_RANGE_REQUIRED",`$periodValue cannot resolve the ${i} of the timestamp query`);const c={version:e.version,schema:n.id,query:{[s.propertyName]:{$lte:a}},preds:[{operator:"$max",pred:s.propertyName,name:"__period_boundary_date__"}]},u=xs(e);return u.query=In(s.queryWithoutTime,s.propertyName,c),u.preds=[{...pr(t.pred),name:r}],{kind:"query",logicform:u}},getOutputProperty({name:e,inputProperty:t}){if(!t)throw new Error("$periodValue requires a nested metric");return{...t,name:e,isArray:!1}}},vs=e=>{const t=Y(e);return delete t.having,delete t.sort,delete t.limit,delete t.page,t},Bs=({logicform:e,pred:t,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!t.pred||typeof t.pred!="object"||Array.isArray(t.pred))throw new Error("$periodDifference pred must be a nested metric");const a=Y(t.pred);a.name="__period_diff_current__";const c=vs(e);c.preds=[a];const u=Te([e.query,...Se(t)]);u&&(c.query=u);const d={pred:Y(t.pred),...t.args?{args:t.args}:{}},l=cr({logicform:e,pred:d,outputName:"__period_diff_prev__",schema:i,resolveSchema:s});if(!("logicform"in l))throw new Error("$periodDifference period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:c},{name:m,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${f} - ${m}`}},Fs={name:"$periodDifference",defaultName:({operandName:e,args:t,locale:r,t:n})=>{const o=or(t,r,n),i=r.toLowerCase().startsWith("en")?`${e} ${o} difference`:`${e}${o}\u5DEE\u503C`;return n?.("operator.$periodDifference",i,{operandName:e,comparison:o})??i},kind:"component",createComponent:Bs,getOutputProperty({name:e,inputProperty:t}){if(!t)throw new Error("$periodDifference requires a nested metric");return{...t,name:e,isArray:!1}}},Ys=e=>{const t=Y(e);return delete t.having,delete t.sort,delete t.limit,delete t.page,t},Qs=({logicform:e,pred:t,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!t.pred||typeof t.pred!="object"||Array.isArray(t.pred))throw new Error("$periodGrowth pred must be a nested metric");const a=Y(t.pred);a.name="__period_growth_current__";const c=Ys(e);c.preds=[a];const u=Te([e.query,...Se(t)]);u&&(c.query=u);const d={pred:Y(t.pred),...t.args?{args:t.args}:{}},l=cr({logicform:e,pred:d,outputName:"__period_growth_prev__",schema:i,resolveSchema:s});if(!("logicform"in l))throw new Error("$periodGrowth period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:c},{name:m,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${f} / NULLIF(ABS(${m}), 0) - 1`}},Hs={name:"$periodGrowth",defaultName:({operandName:e,args:t,locale:r,t:n})=>{const o=or(t,r,n),i=r.toLowerCase().startsWith("en")?`${e} ${o} growth`:`${e}${o}\u589E\u957F\u7387`;return n?.("operator.$periodGrowth",i,{operandName:e,comparison:o})??i},kind:"component",createComponent:Qs,getOutputProperty({name:e}){return{name:e,type:"percentage",primal_type:"number",isArray:!1}}},Gs={name:"$sum",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`Total ${e}`:`\u603B${e}`,kind:"aggregate",toSQL(e){const{column:t,sql:r}=e;if(!t)throw new Error("$sum requires a column");return r.aggregateFunction("sum",t)},getOutputProperty({name:e,property:t,inputProperty:r}){const n=t??r;if(!n)throw new Error("$sum requires a property");return{name:e,type:n.type,primal_type:n.primal_type,isArray:!1}}},Ws={name:"$subtract",defaultName:({operandName:e,inputNames:t,locale:r})=>r.toLowerCase().startsWith("en")?t.length>=2?`${t[0]} minus ${t[1]}`:`${e} difference`:t.length>=2?`${t[0]}\u51CF\u53BB${t[1]}`:`${e}\u5DEE\u503C`,kind:"scalar",requiresProperty:!1,toSQL(e){const[t,r]=ke("$subtract",e,2);return`(${t} - ${r})`},getOutputProperty({name:e,inputProperties:t}){const r=t?.[0];return r?{...r,name:e,isArray:!1}:$t(e)}},bn=e=>{const t=Y(e);return delete t.having,delete t.sort,delete t.limit,delete t.page,t},lr=e=>{const t=Y(e);return delete t.query,t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&(t.pred=lr(t.pred)),Array.isArray(t.pred)&&(t.pred=t.pred.map(r=>typeof r=="string"?r:lr(r))),t},zs={name:"$shareOfTotal",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`${e} share of total`:`${e}\u5360\u6BD4`,kind:"component",createComponent({logicform:e,pred:t,outputName:r,t:n}){if(!t.pred||typeof t.pred!="object"||Array.isArray(t.pred))throw new p("INVALID_SHARE_OF_TOTAL_INPUT","$shareOfTotal pred must be a nested metric");const o=t.args?.dimension;if(o!==void 0&&typeof o!="string")throw new p("INVALID_SHARE_OF_TOTAL_ARGS","$shareOfTotal args.dimension must be a groupby pred or output name");const i=e.groupby??[],s=o===void 0?i.length-1:i.findIndex(y=>typeof y.pred=="string"&&y.pred===o||rr(y)===o);if(o!==void 0&&s<0)throw new p("SHARE_OF_TOTAL_DIMENSION_NOT_FOUND",`$shareOfTotal dimension is not grouped: ${o}`);const a=i.filter((y,g)=>g!==s),c=lr(t.pred),u=bn(e);u.preds=[{...c,name:"__share_numerator__"}];const d=Te([e.query,...Se(t)]);d&&(u.query=d);const l=bn(e);l.groupby=a,l.preds=[{...c,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:u},{name:m,logicform:l}],expression:`${f} / NULLIF(${m}, 0)`}},getOutputProperty({name:e}){return{name:e,type:"percentage",primal_type:"number",isArray:!1}}},Ks={name:"$substring",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`${e} substring`:`${e}\u5B50\u4E32`,kind:"scalar",toSQL({expression:e,args:t,sql:r}){if(!e)throw new p("PRED_PROPERTY_REQUIRED","$substring requires a pred");const{start:n,length:o}=t;if(!Number.isInteger(n)||Number(n)<0||!Number.isInteger(o)||Number(o)<1)throw new p("INVALID_SUBSTRING_ARGS","$substring requires a non-negative integer start and a positive integer length");return r.substring(e,Number(n)+1,Number(o))},getOutputProperty({name:e}){return{name:e,type:"string",primal_type:"string",isArray:!1}}},Nn=(e,t,r,n="$sql")=>{if(typeof e!="string"||e.trim().length===0)throw new p("INVALID_SQL_ARGS",`${n} requires a non-empty args.sql expression`);let o="",i=0,s;for(let a=0;a<e.length;a+=1){const c=e[a];if(!c)continue;if(s){o+=c,c===s&&(e[a+1]===s?(o+=s,a+=1):s=void 0);continue}if(c==="'"||c==='"'||c==="`"){s=c,o+=c;continue}const u=e.slice(a,a+2);if(c===";"||u==="--"||u==="/*")throw new p("INVALID_SQL_EXPRESSION",`${n} accepts one expression and does not allow statements or SQL comments`);if(c==="?"){if(i>=t.length)throw new p("INVALID_SQL_PARAMETERS",`${n} contains more placeholders than args.parameters values`);o+=r(t[i]),i+=1;continue}o+=c}if(s)throw new p("INVALID_SQL_EXPRESSION",`${n} contains an unterminated quote`);if(i!==t.length)throw new p("INVALID_SQL_PARAMETERS",`${n} args.parameters contains more values than SQL placeholders`);return o},Js=new Set(["boolean","date","number","entity","object","string"]),Zs=e=>{if(e===void 0)return[];if(!Array.isArray(e))throw new p("INVALID_SQL_ARGS","$sql args.parameters must be an array");return e},Xs=(e,t)=>{const r=t.type,n=t.primal_type;if(typeof r!="string"||r.length===0||!Js.has(n))throw new p("INVALID_SQL_OUTPUT","$sql requires args.type and a valid args.primal_type");if(t.isArray!==void 0&&typeof t.isArray!="boolean")throw new p("INVALID_SQL_OUTPUT","$sql args.isArray must be boolean");if(t.ref!==void 0&&typeof t.ref!="string")throw new p("INVALID_SQL_OUTPUT","$sql args.ref must be a Schema id");return{name:e,type:r,primal_type:n==="object"?"entity":n,isArray:t.isArray===!0,...typeof t.ref=="string"?{ref:t.ref}:{}}},ea={name:"$sql",defaultName:({locale:e})=>e.toLowerCase().startsWith("en")?"Calculated value":"\u8BA1\u7B97\u503C",kind:"scalar",requiresProperty:!1,toSQL({args:e,expression:t,expressions:r,sql:n}){if(t||r&&r.length>0)throw new p("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return Nn(e.sql,Zs(e.parameters),o=>n.value(o))},getOutputProperty({name:e,args:t,inputProperty:r,inputProperties:n}){if(r||n&&n.length>0)throw new p("INVALID_SQL_INPUT","$sql does not accept pred; put the expression in args.sql");return Xs(e,t)}},ta=e=>{const t=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}t.add(o)}};return r(e),[...t]},ra=e=>typeof e.pred!="string"?e:{...e,pred:{operator:"$sum",pred:e.pred,name:`${e.pred}\u5408\u8BA1`}},Et=(e,t)=>{if(e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred))return e.pred.operator&&t?.(e.pred.operator).kind==="component"?e.pred:Et(e.pred,t);if(Array.isArray(e.pred)){for(const r of e.pred)if(typeof r!="string"){const n=Et(r,t);if(n)return n}}},na=(e,t,r)=>{const n=`__rank_component_${t.name??"value"}__`,o=c=>c===r?n:Array.isArray(c)?c.map(o):!c||typeof c!="object"?c:Object.fromEntries(Object.entries(c).map(([u,d])=>[u,o(d)])),i=Y(e);i.preds=[{...Y(r),name:n}],delete i.having,delete i.sort,delete i.limit,delete i.limitBy,delete i.page,delete i.output,delete i.representation;const s=Y(e);s.from=i;const a=[];for(const c of e.groupby??[]){const u=c.name??(typeof c.pred=="string"?c.pred:void 0);u&&a.push({pred:u,name:u})}return s.preds=[...a,...(e.preds??[]).map(c=>o(c))],delete s.groupby,s},oa=(e,t,r)=>{const n=e.preds;if(n.filter(d=>d.operator==="$rank"&&d.query).length!==1)throw new p("AMBIGUOUS_RANK_TARGET","A LogicForm without groupby must contain exactly one $rank pred.query target");const i=ta(r),[s]=i;if(i.length!==1||!s)throw new p("AMBIGUOUS_RANK_DIMENSION","$rank pred.query must reference exactly one property when groupby is omitted",{properties:i});const a=Y(e);a.groupby=[{pred:s,name:s}],a.preds=n.map(d=>{if(d.name!==t.name)return d;const l={...d};return delete l.query,ra(l)}),delete a.sort,delete a.limit,delete a.limitBy,delete a.page,delete a.output,delete a.representation;const c=n.map(({name:d})=>d).filter(d=>!!d),u=Y(e);return u.from=a,u.query=r,u.preds=[{pred:s,name:s},...c.map(d=>({pred:d,name:d}))],delete u.groupby,delete u.having,delete u.entity_id,delete u.propertyResolve,u},ia={name:"$rank",defaultName:({operandName:e,locale:t})=>t.toLowerCase().startsWith("en")?`${e} rank`:`${e}\u6392\u540D`,kind:"window",windowFunction:"rank",rewriteLogicform({logicform:e,getOperator:t}){const r=e.groupby?.length?e.preds?.map(o=>Et(o,t)).find(Boolean):void 0;if(r){const o=e.preds?.find(i=>Et(i,t)===r);if(o)return na(e,o,r)}if(e.groupby?.length)return;const n=e.preds?.find(o=>o.operator==="$rank"&&o.query);return n?.query?oa(e,n,n.query):void 0},validatePlan({pred:e,groupByNames:t}){if(!e.pred||Array.isArray(e.pred))throw new p("INVALID_WINDOW_OPERATOR_INPUT","$rank requires exactly one pred");if(t.length===0&&!e.query&&typeof e.pred!="string")throw new p("RANK_GROUPBY_OR_TARGET_REQUIRED","$rank requires groupby or a pred.query target used to infer the ranking dimension")},getOutputProperty({name:e}){return{name:e,type:"int",primal_type:"number",isArray:!1}}},sa={name:"$rowNumber",defaultName:({locale:e})=>e.toLowerCase().startsWith("en")?"Row number":"\u884C\u53F7",kind:"window",windowFunction:"rowNumber",getOutputProperty({name:e}){return{name:e,type:"int",primal_type:"number",isArray:!1}}},aa=new Set(["string","number","boolean","date","entity","object"]),fr=e=>{if(e==="timestamp"||e==="date")return{type:e,primal_type:"date"};if(typeof e=="string"&&aa.has(e))return{type:e,primal_type:e};throw new p("INVALID_CONSTANT_TYPE","$constant args.type must be timestamp, date, string, number, boolean, entity, or object")},ca={name:"$constant",defaultName:({locale:e})=>e.toLowerCase().startsWith("en")?"Constant":"\u5E38\u91CF",kind:"scalar",requiresProperty:!1,normalizePred({pred:e}){if(e.pred!==void 0)throw new p("INVALID_CONSTANT_INPUT","$constant does not accept pred");return fr(e.args?.type),e},toSQL({args:e,sql:t}){return fr(e.type),t.value(e.value,e.type)},getOutputProperty({name:e,args:t}){return{name:e,...fr(t.type),isArray:!1}}},ua={name:"$periodBoundary",defaultName:({operandName:e,args:t,locale:r})=>r.toLowerCase().startsWith("en")?`${e} at period ${t.boundary==="start"?"start":"end"}`:`${e}${t.boundary==="start"?"\u671F\u521D":"\u671F\u672B"}`,kind:"scalar",toSQL({expression:e,args:t,sql:r}){if(!e)throw new p("PRED_PROPERTY_REQUIRED","$periodBoundary requires pred");const n=t.boundary;if(n!=="start"&&n!=="end")throw new p("INVALID_PERIOD_BOUNDARY_ARGS","$periodBoundary args.boundary must be start or end");const o=t.granularity;if(typeof o!="string")throw new p("END_OF_PERIOD_GRANULARITY_REQUIRED","$periodBoundary requires the input Property granularity");const i=r.dateBucket(e,o);return r.datePeriodBoundary?r.datePeriodBoundary(e,o,n):n==="start"?i:r.dateShift(r.dateShift(i,o,1),"second",-1)},planExpression({input:e,inputProperty:t,args:r}){if(!e)return;const n=t?.granularity??r.granularity;return{kind:"operator",operator:"$periodBoundary",input:e,args:{...r,granularity:n}}},normalizePred({pred:e,schema:t}){if(!e.pred||Array.isArray(e.pred))throw new p("INVALID_PERIOD_BOUNDARY_INPUT","$periodBoundary requires one pred");if(typeof e.pred=="string"){const r=t.properties.find(({id:n,name:o})=>n===e.pred||o===e.pred);return{...e,args:{...e.args,granularity:r?.granularity}}}return e},getOutputProperty({name:e,inputProperty:t,args:r}){if(!t||t.primal_type!=="date")throw new p("PERIOD_BOUNDARY_DATE_REQUIRED","$periodBoundary requires a date-valued pred");const n=t.granularity??r.granularity;if(typeof n!="string")throw new p("END_OF_PERIOD_GRANULARITY_REQUIRED","$periodBoundary requires the input Property granularity");return{...t,name:e,granularity:n,isArray:!1}}},Pn="__scalarExtremumInputs",mr=e=>{if(e.schema)return e.schema;if(e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred))return mr(e.pred);if(Array.isArray(e.pred)){const t=[...new Set(e.pred.flatMap(r=>typeof r=="string"?[]:mr(r)??[]))];if(t.length===1)return t[0]}},da=e=>{const t=Y(e);return delete t.from,delete t.having,delete t.sort,delete t.limit,delete t.limitBy,delete t.page,delete t.representation,delete t.output,t},pa=(e,t)=>{if(t.args?.[Pn]===!0||!Array.isArray(t.pred))return;if(e.preds?.length!==1)throw new p("SCALAR_EXTREMUM_SINGLE_PROJECTION_REQUIRED",`${t.operator} with multiple pred inputs must be the only LogicForm projection`);const r=t.pred.map((o,i)=>{const s=typeof o=="string"?{pred:o}:Y(o),a=s.name??`__scalar_extremum_input_${i}__`,c=s.schema??mr(s);return{...s,name:a,...c?{schema:c}:{}}}),n=da(e);return n.preds=r,{version:e.version,from:n,preds:[{operator:t.operator,pred:r.map(({name:o})=>o),...t.name?{name:t.name}:{},args:{...t.args,[Pn]:!0}}],...e.having?{having:e.having}:{},...e.sort?{sort:e.sort}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.page!==void 0?{page:e.page}:{},...e.output?{output:e.output}:{},...e.representation?{representation:e.representation}:{}}},la=(e,t)=>{const r=e==="$least"?"MIN":"MAX",n=t.map(o=>`SELECT ${o} AS value`).join(" UNION ALL ");return`(SELECT ${r}(value) FROM (${n}) AS __scalar_extremum_values)`},fa=(e,t,r)=>{const[n,...o]=r??[];if(!n)throw new p("INVALID_OPERATOR_INPUTS",`${e} requires pred inputs`);if(o.some(({primal_type:i})=>i!==n.primal_type))throw new p("INCOMPATIBLE_OPERATOR_INPUTS",`${e} pred inputs must have the same primal type`);return{...n,name:t,isArray:!1}},Tn=e=>({name:e,defaultName:({inputNames:t,locale:r})=>r.toLowerCase().startsWith("en")?`${e==="$least"?"Least":"Greatest"} of ${t.join(", ")}`:`${t.join("\u3001")}\u4E2D\u7684${e==="$least"?"\u6700\u65E9\u503C":"\u6700\u665A\u503C"}`,kind:"scalar",requiresProperty:!1,normalizePred({pred:t}){if(!Array.isArray(t.pred)||t.pred.length<2)throw new p("INVALID_OPERATOR_INPUTS",`${e} requires at least two pred inputs`);return t},rewriteLogicform({logicform:t}){const r=t.preds?.[0];return r?.operator===e?pa(t,r):void 0},toSQL(t){const r=ke(e,t,2,Number.POSITIVE_INFINITY);return t.sql.scalarExtremum?.(e==="$least"?"least":"greatest",r)??la(e,r)},getOutputProperty({name:t,inputProperties:r}){return fa(e,t,r)}}),ma=Tn("$least"),ya=Tn("$greatest"),Ln=Object.freeze([Fi,Gs,Os,bs,Es,Us,Cs,ms,Hs,Fs,As,Vs,Ms,Qi,Ws,js,Ls,Yi,zs,Is,Rs,Ks,Ts,ea,ia,sa,ca,ua,ma,ya]),ha={name:"boolean",primalType:"boolean",hydrateResult(e){return typeof e=="number"?e===1:e}},ga={name:"category",primalType:"string"},$a={name:"currency",primalType:"number"},wa={name:"date",primalType:"date"},Aa={name:"duration",primalType:"number"},Ea={name:"end_date",primalType:"date"},Dn=(e,{property:t,requestEntity:r})=>!t.ref||e===void 0||e===null||typeof e=="object"&&!Array.isArray(e)?e:r(t.ref,e),_a={name:"object",primalType:"object",hydrateResult:Dn},Sa={name:"entity",primalType:"entity",hydrateResult:Dn},Ia={name:"file",primalType:"string"},Ra={name:"humanName",primalType:"string"},Oa={name:"ID",primalType:"string"},ba={name:"image",primalType:"string"},Na={name:"int",primalType:"number"},Pa={name:"name",primalType:"string"},Ta={name:"number",primalType:"number"},La={name:"order",primalType:"number"},Da={name:"percentage",primalType:"number"},Ca={name:"start_date",primalType:"date"},qa={name:"string",primalType:"string"},Ua={name:"timestamp",primalType:"date"},yr=Object.freeze([Oa,qa,Pa,Ra,ga,ba,Ia,Ta,Na,$a,Da,Aa,La,ha,Ua,wa,Ca,Ea,Sa,_a]),ja=(e,t,r)=>{if(typeof e=="function")return e;if(typeof e!="string"||e.trim().length===0)return;const n=new Function(`return (${e})`)();if(typeof n!="function")throw new TypeError(`Operator ${r} ${t} must resolve to a function`);return n},Cn=e=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("Operator definition must be an object");const t=e,r=t.name,n=typeof r=="string"?r:"",o=t.type,i=new Set(["defaultName","getOutputProperty","planInput","normalizePred","planExpression","observationPolicy","validatePlan","rewriteLogicform","requiresPerPeriodEvaluation","toSQL","evaluate","createComponent"]),s=Object.fromEntries(Object.entries(t).filter(([a])=>!i.has(a)));s.name=r;for(const a of i){const c=ja(t[a],a,n);c&&(s[a]=c)}if(!s.getOutputProperty&&typeof o=="string"){const a=yr.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 qn{#e=new Map;constructor(t=[]){for(const r of t)this.register(r)}register(t){const r=Cn(t);if(!r.name)throw new p("INVALID_OPERATOR","Operator name must not be empty");if(typeof r.defaultName!="function")throw new p("INVALID_OPERATOR",`Operator must implement defaultName: ${r.name}`);if(this.#e.has(r.name))throw new p("OPERATOR_ALREADY_REGISTERED",`Operator is already registered: ${r.name}`,{operator:r.name});const n=r;if(!(n.kind==="scalar"&&(typeof n.toSQL=="function"||typeof n.evaluate=="function")||n.kind==="aggregate"&&typeof n.toSQL=="function"||n.kind==="component"&&typeof n.createComponent=="function"||n.kind==="window"&&typeof n.windowFunction=="string"||n.kind==="logical"&&typeof n.planExpression=="function"))throw new p("INVALID_OPERATOR",`Operator kind and implementation do not match: ${r.name}`);return this.#e.set(r.name,r),this}get(t){const r=this.#e.get(t);if(!r)throw new p("OPERATOR_NOT_FOUND",`Operator is not registered: ${t}`,{operator:t});return r}requiresPerPeriodEvaluation(t,r){return this.get(t).requiresPerPeriodEvaluation?.(r)??!1}has(t){return this.#e.has(t)}definitions(){return[...this.#e.values()]}}const ka=Object.freeze([...Ln,...$n.flatMap(({operators:e})=>e??[])]),Ie=(e=[])=>new qn([...Ln,...wt(e).flatMap(({operators:t})=>t??[])]),Ma=(e,t)=>{const r=Gi(e,t);return{schemaId:e.id,propertyId:r.id,propertyName:r.name,physicalColumn:r.udf?.sql??r.id}},Un=(e,t,r)=>{const n=e.fieldReferences?.[r];return n?{schemaId:n.schemaId,propertyId:n.propertyId??n.column,propertyName:n.property,physicalColumn:n.sql??n.column}:Ma(t,r)},et=(e,t,r,n)=>{if(e.kind==="column")return{sources:[{schemaId:e.schemaId??r.id,propertyId:e.propertyId??e.column,propertyName:e.property,physicalColumn:e.column}],transformations:["projection"]};if(e.kind==="property-sql")return{sources:[{schemaId:e.schemaId,propertyId:e.propertyId,propertyName:e.property,physicalColumn:e.sql}],transformations:["property-sql"]};if(e.kind==="array-element")return{sources:[{schemaId:e.schemaId,propertyId:e.property,propertyName:e.property,physicalColumn:e.property}],transformations:["array-expand"]};if(e.kind==="window"){const c=[e.input,...e.partitionBy].map(u=>et(u,t,r,n));return{sources:c.flatMap(({sources:u})=>u),transformations:[...c.flatMap(({transformations:u})=>u).filter(u=>u!=="projection"),`window:${e.function}`]}}if(e.kind==="cumulative"){const c=[e.input,...e.partitionBy,...e.orderBy.map(({expression:u})=>u)].map(u=>et(u,t,r,n));return{sources:c.flatMap(({sources:u})=>u),transformations:[...c.flatMap(({transformations:u})=>u).filter(u=>u!=="projection"),`window:cumulative:${e.function}`]}}if(e.kind==="ordinal-encode"||e.kind==="ordinal-decode"){const c=et(e.input,t,r,n);return{sources:c.sources,transformations:[...c.transformations.filter(u=>u!=="projection"),`ordinal:${e.kind==="ordinal-encode"?"encode":"decode"}`]}}const o=[...e.input?[e.input]:[],...e.inputs??[]].map(c=>et(c,t,r,n)),i={sources:o.flatMap(({sources:c})=>c),transformations:o.flatMap(({transformations:c})=>c)},s=n.get(e.operator),a=new Set([...e.property?[e.property]:[],...s.dependencies??[],..._t(e.query)]);return{sources:[...i.sources,...[...a].filter(c=>!i.sources.some(u=>u.propertyName===c)).map(c=>Un(t,r,c))],transformations:[...i.transformations.filter(c=>c!=="projection"),`operator:${e.operator}`]}};function _t(e){if(!e)return[];const t=[];for(const[r,n]of Object.entries(e))if((r==="$and"||r==="$or")&&Array.isArray(n))for(const o of n)typeof o=="object"&&o!==null&&!Array.isArray(o)&&t.push(..._t(o));else r.startsWith("$")||t.push(r);return t}const we=e=>e.kind==="window"?[...we(e.input),...e.partitionBy.flatMap(we)]:e.kind==="cumulative"?[...we(e.input),...e.partitionBy.flatMap(we),...e.orderBy.flatMap(({expression:t})=>we(t))]:e.kind==="ordinal-encode"||e.kind==="ordinal-decode"?we(e.input):e.kind==="operator"?[..._t(e.query),...e.input?we(e.input):[],...(e.inputs??[]).flatMap(we)]:[],jn=(e,t,r,n=Ie())=>{if(e.subplans){const o=e.subplans.map(i=>jn(i,t,r,n));return{source:{schemaId:t.id,schemaName:t.name,physicalTable:o.map(({source:i})=>i.physicalTable).join(", "),provider:r.kind},outputs:e.projections.map(({name:i})=>{const s=o.flatMap(({outputs:a})=>a.filter(c=>c.name===i));return{name:i,sources:s.flatMap(({sources:a})=>a),transformations:[...new Set([...s.flatMap(({transformations:a})=>a),"compose"])]}}),filters:o.flatMap(({filters:i})=>i)}}return{source:{schemaId:t.id,schemaName:t.name,physicalTable:e.source,provider:r.kind},outputs:e.projections.map(o=>({name:o.name,...et(o.expression,e,t,n)})),filters:[...new Set([..._t(e.query),...e.projections.flatMap(({expression:o})=>we(o))])].map(o=>Un(e,t,o))}},ye=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.version=="string"&&(typeof e.schema=="string"||typeof e.from=="object"),xa=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,kn=e=>{const t=xa.exec(e);if(!t)return;const r=Number(t[1]),n=Number(t[2]),o=Number(t[3]??0);if(!(r>23||n>59||o>59))return{hour:r,minute:n,second:o}},Va=e=>{const t=e.freshness;if(t){if(t.mode==="ttl"){if(!Number.isInteger(t.ttlSeconds)||t.ttlSeconds<=0)throw new p("INVALID_SOURCE_FRESHNESS","TTL freshness requires a positive integer ttlSeconds");return}if(t.mode==="daily"){if(!kn(t.expireAt))throw new p("INVALID_SOURCE_FRESHNESS","Daily freshness expireAt must use HH:mm or HH:mm:ss");if(t.timeZone)try{new Intl.DateTimeFormat("en-US",{timeZone:t.timeZone}).format()}catch{throw new p("INVALID_SOURCE_FRESHNESS",`Invalid freshness timeZone: ${t.timeZone}`)}}}};class hr{#e=new Map;constructor(t=[]){for(const r of t)this.register(r)}register(t){if(!t.schemaId)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping schemaId must not be empty");if(!t.source)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping source must not be empty");if(t.sourceSql!==void 0&&t.sourceSql.trim().length===0)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping sourceSql must not be empty");if(t.id!==void 0&&!t.id)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping id must not be empty");if(t.connectionId.trim().length===0)throw new p("INVALID_SCHEMA_MAPPING","Schema mapping connectionId must not be empty");if(t.priority!==void 0&&!Number.isFinite(t.priority))throw new p("INVALID_SCHEMA_MAPPING","Schema mapping priority must be finite");for(const o of t.mappings??[]){if(o.mappingType==="property"&&(!o.sourceColumn||!o.propertyTarget?.length))throw new p("INVALID_SCHEMA_MAPPING","Schema mapping property items require sourceColumn and propertyTarget");if(o.mappingType==="predItem"&&(!o.sourceColumn||!o.predItem?.operator||typeof o.predItem.pred!="string"))throw new p("INVALID_SCHEMA_MAPPING","Schema mapping PredItem items require sourceColumn and predItem operator/pred")}Va(t);const r=this.#e.get(t.schemaId)??[],n=t.id??t.source;if(r.some(o=>(o.id??o.source)===n||o.source===t.source))throw new p("SCHEMA_MAPPING_ALREADY_REGISTERED",`Schema mapping is already registered: ${t.schemaId}:${n}`,{schemaId:t.schemaId,mappingId:n});return this.#e.set(t.schemaId,[...r,t]),this}get(t){const r=this.list(t);if(r.length===1)return r[0];const n=r.filter(o=>(o.mappings??[]).length===0);if(n.length===1)return n[0];throw new p("SCHEMA_MAPPING_AMBIGUOUS",`Schema ${t} has multiple mappings and requires LogicForm-based selection`,{schemaId:t,mappingIds:r.map(o=>o.id??o.source)})}list(t){const r=this.#e.get(t);if(!r||r.length===0)throw new p("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${t}`,{schemaId:t});return r}findSource(t,r){return this.#e.get(t)?.find(n=>n.source===r)}}const va=e=>{if(e.tablePath?.trim())return e.tablePath;const t=[e.physicalDatabase,e.physicalSchema,e.physicalTable].filter(r=>!!r?.trim());if(t.length>0)return t.join(".");if(e.sourceSql?.trim())return e.sourceSql;throw new p("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping ${e.id} has no physical source`)},Ba=e=>{if(!e.schemaSid||!e.datasourceSid)throw new p("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping requires schemaSid and datasourceSid");if(e.enabled===!1)throw new p("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping is disabled: ${e.id}`);const t=[];for(const r of e.mappings){if(r.mappingType==="property"){if(!r.sourceColumn||!r.propertyTarget?.length)continue;t.push(r);continue}r.mappingType==="predItem"&&(!r.sourceColumn||!r.predItem?.operator||typeof r.predItem.pred!="string"||t.push(r))}return{id:String(e.id),schemaId:e.schemaSid,connectionId:e.datasourceSid,source:va(e),...e.sourceSql?{sourceSql:e.sourceSql}:{},mappings:t}},Fa=(e,t)=>!!(e&&t?.temporalSemantics==="snapshot"&&e.type!=="timestamp"),gr="$periodValue",Ya=(e,t)=>{const r=t?.observationPolicy?.({pred:e});if(r)return{operator:gr,...r};if(t?.kind==="aggregate")throw new p("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${gr}; ${t.name} describes a time range`,{operator:t.name});return{operator:gr,boundary:"end",implicit:!0}},Qa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),St=(e,t,r)=>{const n=e instanceof Date?e.getTime():typeof e=="string"||typeof e=="number"?new Date(e).getTime():Number.NaN;if(Number.isNaN(n))throw new p(`${r.codePrefix}_PERIOD_INVALID_BOUND`,`${r.label} period ${t} must be a date`,{owner:t,value:e});return n},Re=(e,t=2)=>String(e).padStart(t,"0"),Mn=e=>`${Re(e.getFullYear(),4)}-${Re(e.getMonth()+1)}-${Re(e.getDate())} ${Re(e.getHours())}:${Re(e.getMinutes())}:${Re(e.getSeconds())}.`+Re(e.getMilliseconds(),3),Ha=(e,t)=>{if(!Qa(e)){const a=St(e,"point",t);return{lower:a,upper:a}}const r=e.$eq;if(r!==void 0){const a=St(r,"$eq",t);return{lower:a,upper:a}}const n=e.$gte??e.$gt,o=e.$lte??e.$lt;if(n===void 0||o===void 0)throw new p(`${t.codePrefix}_PERIOD_BOUNDS_REQUIRED`,`${t.label} period grouping requires both a lower and an upper time bound`);const i=St(n,e.$gte!==void 0?"$gte":"$gt",t)+(e.$gte===void 0?1:0),s=St(o,e.$lte!==void 0?"$lte":"$lt",t)-(e.$lte===void 0?1:0);if(i>s)throw new p(`${t.codePrefix}_PERIOD_INVALID_RANGE`,`${t.label} period grouping requires the lower bound to precede the upper bound`,{lower:n,upper:o});return{lower:i,upper:s}},xn=(e,t)=>{const{lower:r,upper:n}=Ha(e,t),o=new Date(r).getFullYear(),i=new Date(n).getFullYear();if(i-o+1>1e4)throw new p(`${t.codePrefix}_PERIOD_LIMIT_EXCEEDED`,`${t.label} period grouping cannot generate more than 10000 periods`);return Array.from({length:i-o+1},(s,a)=>{const c=o+a,u=new Date(c,0,1,0,0,0,0),d=new Date(Math.min(new Date(c,11,31,23,59,59,999).getTime(),n));return{label:`${Re(c,4)}-01-01 00:00:00.000`,start:Mn(u),end:Mn(d)}})},Ga=(e,t)=>e.groupby?.find(r=>typeof r.pred=="string"&&r.pred===t.name),Wa=(e,t)=>e&&Object.fromEntries(Object.entries(e).filter(([r])=>r!==t.name)),za=(e,t)=>{if(t.temporalSemantics!=="snapshot")return;const r=t.properties.find(({type:d})=>d==="timestamp");if(!r)return;const n=Ga(e,r),o=e.preds??[],i=o.filter(({operator:d})=>d==="$periodValue");if(!n||i.length===0)return;if(n.operator!=="$dateBucket"||n.args?.granularity!=="year")throw new p("OBSERVATION_PERIOD_GRANULARITY_UNSUPPORTED","Grouped observation period values currently require $dateBucket with year granularity",{property:r.name});if(i.length!==o.length)throw new p("OBSERVATION_PERIOD_METRICS_REQUIRED","A grouped observation query cannot mix $periodValue with ordinary projections");const s=i.map(d=>{const l=d.args?.boundary;if(l!=="start"&&l!=="end")throw new p("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:l});if(!d.pred||typeof d.pred!="object"||Array.isArray(d.pred))throw new p("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");return{pred:d,effectivePred:{...d.pred,...d.name?{name:d.name}:{}}}});if(new Set(i.map(({args:d})=>d?.boundary)).size!==1)throw new p("OBSERVATION_PERIOD_BOUNDARY_MISMATCH","Grouped observation metrics in one query must use the same period boundary");const c=i[0]?.args?.boundary,u=e.query?.[r.name];if(u===void 0)throw new p("OBSERVATION_PERIOD_BOUNDS_REQUIRED",`Grouped observation values on ${r.name} require a bounded query`,{property:r.name});return{group:n,timestamp:r,boundary:c,metrics:s,periods:xn(u,{codePrefix:"OBSERVATION",label:"Observation"}).map(d=>({label:d.label,asOf:d[c]}))}},Ka={name:"observation",resolveProjection({pred:e,schema:t,sourceProperty:r,outputProperty:n,operator:o}){if(!r||!Fa(r,t))return;const i=r,s=Ya(e,o);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:s.boundary,sourceProperty:i.name}}}}},It=(e,t)=>{const r=e.filter(n=>n.type===t);return r.length===1?r[0]:void 0},tt=e=>{if(e.type!=="entity"||e.temporalSemantics==="snapshot")return;const t=It(e.properties,"ID"),r=It(e.properties,"timestamp"),n=It(e.properties,"start_date"),o=It(e.properties,"end_date");return t&&r&&n&&o?{id:t,timestamp:r,start:n,end:o}:void 0},Ja=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Za=e=>Ja(e)?e.$lte??e.$lt??e.$eq:e,Vn=(e,t)=>{if(!e)return e;const r=Object.fromEntries(Object.entries(e).map(([a,c])=>[a,(a==="$and"||a==="$or")&&Array.isArray(c)?c.map(u=>Vn(u,t)):c])),n=Object.entries(e).find(([a])=>a===t.timestamp.name);if(!n)return r;const[,o]=n,i=Za(o);if(i===void 0)throw new p("VALIDITY_POINT_IN_TIME_REQUIRED",`Valid-time query on ${t.timestamp.name} requires an upper bound or a point in time`,{property:t.timestamp.name});return{...Object.fromEntries(Object.entries(r).filter(([a])=>a!==t.timestamp.name)),[t.start.name]:e[t.start.name]??{$lte:i},[t.end.name]:e[t.end.name]??{$or:[{$exists:!1},{$gt:i}]}}},vn=(e,t)=>e.groupby?.find(r=>typeof r.pred=="string"&&r.pred===t.timestamp.name),Xa=(e,t)=>vn(e,t)!==void 0,ec=(e,t)=>e&&Object.fromEntries(Object.entries(e).filter(([n])=>n!==t.timestamp.name)),tc=(e,t)=>{const r=vn(e,t);if(!r)return;if(r.operator!=="$dateBucket"||r.args?.granularity!=="year")throw new p("VALIDITY_PERIOD_GRANULARITY_UNSUPPORTED","Valid-time period grouping currently requires $dateBucket with year granularity",{property:t.timestamp.name});const n=e.query?.[t.timestamp.name];if(n===void 0)throw new p("VALIDITY_PERIOD_BOUNDS_REQUIRED",`Valid-time period grouping on ${t.timestamp.name} requires a bounded query`,{property:t.timestamp.name});return{group:r,granularity:"year",periods:xn(n,{codePrefix:"VALIDITY",label:"Valid-time"}).map(({label:o,end:i})=>({label:o,asOf:i}))}},Bn=(e,t)=>!!(e&&Object.entries(e).some(([r,n])=>t.has(r)||(r==="$and"||r==="$or")&&Array.isArray(n)&&n.some(o=>typeof o=="object"&&o!==null&&Bn(o,t)))),rc={name:"validity",resolveQuery({logicform:e,schema:t,query:r}){const n=tt(t);if(!n)return r;if(Xa(e,n))return ec(r,n);const i=Bn(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:new Date().toISOString()}};return Vn(i,n)},resolveProjection({schema:e,outputProperty:t}){if(tt(e))return{outputProperty:{...t,temporal:{kind:"validity"}}}}};class Fn{#e=new Map;constructor(t=[]){for(const r of t)this.register(r)}register(t){if(!t.name)throw new p("INVALID_SEMANTIC_RULE","Semantic rule name must not be empty");if(this.#e.has(t.name))throw new p("SEMANTIC_RULE_ALREADY_REGISTERED",`Semantic rule is already registered: ${t.name}`,{rule:t.name});return this.#e.set(t.name,t),this}resolveProjection(t){return[...this.#e.values()].reduce((r,n)=>n.resolveProjection?.({...t,outputProperty:r})?.outputProperty??r,t.outputProperty)}resolveQuery(t){return[...this.#e.values()].reduce((r,n)=>n.resolveQuery?.({...t,...r?{query:r}:{}})??r,t.query)}rules(){return[...this.#e.values()]}}const Yn=()=>new Fn([Ka,rc]),Qn=e=>e.id??e.source,Rt=(e,t)=>{if(e===t)return!0;if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((o,i)=>Rt(o,t[i]));if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const r=Object.entries(e),n=t;return r.length===Object.keys(n).length&&r.every(([o,i])=>Object.prototype.hasOwnProperty.call(n,o)&&Rt(i,n[o]))},Me=e=>{if(!e)return[];const t=[];for(const[r,n]of Object.entries(e))if(n!==void 0){if(r==="$or")return;if(r==="$and"){if(!Array.isArray(n))return;for(const o of n){const i=Me(o);if(!i)return;t.push(...i)}continue}if(r.startsWith("$"))return;t.push({property:r,condition:n})}return t},$r=(e,t,r)=>{if(!e)return;const n={};for(const[o,i]of Object.entries(e))if(i!==void 0){if(o==="$and"&&Array.isArray(i)){const s=i.map(a=>$r(a,t,r)).filter(a=>a!==void 0);s.length>0&&(n[o]=s);continue}o!=="$or"&&t.some(s=>Ot(r,s.property,o)&&Rt(s.condition,i))||(n[o]=i)}return Object.keys(n).length>0?n:void 0},Le=(e,t)=>e.properties.find(({id:r,name:n})=>r===t||n===t),Ot=(e,t,r)=>t===r||Le(e,t)?.id===Le(e,r)?.id&&Le(e,t)!==void 0&&Le(e,r)!==void 0,ue=(e,t,r)=>{const n=Le(t,r);return n?(e.mappings??[]).find(i=>i.mappingType==="property"&&i.propertyTarget?.some(s=>Ot(t,s,r)))?.sourceColumn??((e.mappings??[]).some(i=>i.mappingType==="property")?void 0:n.id):void 0},wr=(e,t,r)=>!(e.mappings??[]).some(n=>n.mappingType==="property")||ue(e,t,r)!==void 0,Hn=(e,t,r)=>{if(!e||!(t.mappings??[]).some(i=>i.mappingType==="property"))return;const n=Me(e);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:i})=>!wr(t,r,i));return o?`query property is not available: ${o.property}`:void 0},bt=e=>[...typeof e.pred=="string"?[e.pred]:e.pred&&!Array.isArray(e.pred)?bt(e.pred):[],...Array.isArray(e.pred)?e.pred.flatMap(t=>typeof t=="string"?[t]:bt(t)):[]],nc=(e,t,r,n,o)=>{if(e.match.schema!==void 0&&e.match.schema!==n)return!1;const i=typeof t.pred=="string"?Le(r,t.pred):void 0,s=Le(r,e.match.pred),a=typeof t.pred=="string"&&Ot(r,t.pred,e.match.pred)&&!!(i&&s);if(t.operator!==e.match.operator||!a||Array.isArray(t.pred)||t.args&&Object.keys(t.args).length>0)return!1;const c=Me(e.match.query);return c!==void 0&&c.every(u=>o.some(d=>Ot(r,d.property,u.property)&&Rt(d.condition,u.condition)))},oc=(e,t,r)=>{const n=(r.mappings??[]).flatMap(l=>{if(l.mappingType!=="predItem"||!l.sourceColumn||!l.predItem||!l.predItem.operator||typeof l.predItem.pred!="string")return[];const f=l.predItem,m=f.operator,y=f.pred;return!m||typeof y!="string"?[]:[{match:{operator:m,pred:y,...f.schema?{schema:f.schema}:{},...f.query?{query:f.query}:{}},column:l.sourceColumn}]}),o=(r.mappings??[]).some(l=>l.mappingType==="property");if(n.length===0&&!o)return{mapping:r,logicform:e,predRewrites:[],priority:r.priority??0,specificity:0};const i=Me(e.query);if(!i&&n.length>0)return"query contains $or or another unsupported logical expression";const s=Y(e),a=[],c=[];for(const[l,f]of(e.preds??[]).entries()){const m=Me(f.query);if(!m&&n.length>0)return`PredItem ${l} query contains an unsupported logical expression`;if(n.length>0){const g=[...i??[],...m??[]],_=n.filter(h=>nc(h,f,t,f.schema??t.id,g));if(_.length===0)return`PredItem ${l} is not mapped`;if(_.length>1)return`PredItem ${l} matches multiple mapping rules`;const R=_[0],$=Me(R.match.query)??[];c.push(...$);const E=s.preds?.[l];if(E){const h=$r(E.query,$,t);h?E.query=h:delete E.query}a.push({predIndex:l,column:R.column});continue}const y=bt(f).find(g=>!wr(r,t,g));if(y)return`PredItem ${l} property is not available: ${y}`}const u=$r(s.query,c,t);u?s.query=u:delete s.query;const d=Hn(s.query,r,t);if(d)return d;for(const[l,f]of(s.preds??[]).entries()){const m=Hn(f.query,r,t);if(m)return`PredItem ${l} ${m}`}for(const l of s.groupby??[]){const m=bt(l).find(y=>!wr(r,t,y));if(m)return`groupby property is not available: ${m}`}return{mapping:r,logicform:s,predRewrites:a,priority:r.priority??0,specificity:a.length}},ic=(e,t,r)=>{const n=[],o=[];for(const a of r.list(t.id)){const c=oc(e,t,a);typeof c=="string"?o.push({mappingId:Qn(a),reason:c}):n.push(c)}if(n.length===0){const a=t.name&&t.name!==t.id?`${t.name}(${t.id})`:t.id;throw new p("QUERY_NOT_COVERED_BY_DATA_SOURCE",`Schema\u300C${a}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u4E0D\u652F\u6301\u6B64\u95EE\u9898\u3002\u5982\u9700\u652F\u6301\uFF0C\u9700\u8981\u63A5\u5165\u660E\u7EC6\u5C42\u6570\u636E\uFF0C\u8BF7\u8054\u7CFB\u6570\u636E\u7BA1\u7406\u5458\u3002`,{schemaId:t.id,requiredDataLayer:"detail",rejectedMappings:o})}n.sort((a,c)=>c.priority-a.priority||c.specificity-a.specificity);const i=n[0],s=n.filter(({priority:a,specificity:c})=>a===i.priority&&c===i.specificity);if(s.length>1)throw new p("SCHEMA_MAPPING_AMBIGUOUS",`Multiple Schema mappings cover the LogicForm for ${t.id}`,{schemaId:t.id,mappingIds:s.map(({mapping:a})=>Qn(a))});return i},sc=(e,t)=>`result:${e}:${t.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,Gn=(e,t)=>{const r=(e.columnProperties??[]).map(n=>({...n,id:n.name}));return{id:sc(e.schemaId,e.columnProperties??[]),name:`${t.name} result`,type:t.type,temporalSemantics:"normal",properties:r}},Wn=(e,t)=>({...Gn(e,t),id:t.id,name:t.name,type:t.type}),Ar=e=>{if(!e.name)throw new p("MISSING_PRED_NAME","Planner requires every normalized PredItem to have a name");return e.name},ac=(e,t,r)=>{const n=new Set(r),o=(i,s)=>{if(!(ye(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"].includes(a)||o(c,a)});return}if(!(s&&["args","$exists","$regex","$contains"].includes(s))&&(typeof i!="string"||!n.has(i)))throw new p("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${t} does not contain value: ${JSON.stringify(i)}`,{property:t,value:i})}};o(e)},cc=(e,t,r)=>{if(!t.udf)return{};const o=t.udf.sql.includes("$TS")?e.properties.find(({type:i})=>i==="timestamp")?.id:void 0;return{sql:t.udf.sql,...o?{timestampColumn:o}:{},...o&&r?{timestampQualifier:r}:{}}},zn=e=>e.sql?{kind:"property-sql",schemaId:e.schemaId,property:e.property,propertyId:e.column,sql:e.sql,qualifier:e.qualifier,...e.timestampColumn?{timestampColumn:e.timestampColumn}:{},...e.timestampQualifier?{timestampQualifier:e.timestampQualifier}:{}}:{kind:"column",...e},Kn=(e,t,r={})=>({name:e,type:t.type,primal_type:t.primal_type,isArray:t.isArray,...t.ref?{ref:t.ref}:{},...t.comparable?{comparable:t.comparable}:{},...r}),rt=(e,t,r,n,o,i,s,a,c="projection")=>{const u=Ar(e);if(c==="groupby"&&e.query)throw new p("GROUPBY_QUERY_NOT_ALLOWED","A groupby expression cannot define pred.query");if(!e.operator){if(typeof e.pred!="string")throw new p("PRED_PROPERTY_REQUIRED","A projection must reference a property");const $=r(e.pred);return{expression:zn($.field),outputProperty:Kn($.reference,$.property),sourceProperty:$.property,sourceField:$.field}}const d=t.get(e.operator);if(c==="groupby"&&d.kind!=="scalar")throw new p("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${e.operator} cannot be used in groupby`,{operator:e.operator});if(c==="groupby"&&!d.toSQL)throw new p("JAVASCRIPT_OPERATOR_NOT_ALLOWED_IN_GROUPBY",`JavaScript-only operator ${e.operator} cannot be used in groupby`,{operator:e.operator});if(d.planInput&&typeof e.pred!="string")throw new p("OPERATOR_DIRECT_PROPERTY_REQUIRED",`${e.operator} requires a direct property pred`);const l=d.planInput&&typeof e.pred=="string"?d.planInput({reference:e.pred,args:e.args??{},schema:s,...a?{resolveSchema:a}:{}}):void 0,f=l?.reference??e.pred,m=l?.args??e.args??{},y=f&&typeof f=="object"&&!Array.isArray(f)?rt(f,t,r,n,o,i,s,a,c):typeof f=="string"?rt({pred:f,name:f},t,r,n,o,i,s,a,c):void 0,g=Array.isArray(f)?f.map($=>rt(typeof $=="string"?{pred:$,name:$}:$,t,r,n,o,i,s,a,c)):[];if(d.requiresProperty!==!1&&!y&&g.length===0)throw new p("PRED_PROPERTY_REQUIRED",`${e.operator} requires a property`);const _=u,R=d.getOutputProperty?.({name:_,...y?.sourceProperty?{property:y.sourceProperty}:{},...y?{inputProperty:{...y.outputProperty,name:_}}:{},...g.length>0?{inputProperties:g.map(({outputProperty:$})=>$)}:{},args:m})??(y?Kn(_,y.outputProperty,{isArray:!1}):{name:_,type:"number",primal_type:"number",isArray:!1});if(d.planExpression){const $=d.planExpression({pred:e,...y?{input:y.expression,inputProperty:y.outputProperty}:{},inputs:g.map(({expression:E})=>E),args:m,resolveKey:o,getOperator:E=>t.get(E),planQuery:i});if($)return{expression:$,outputProperty:R,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}}if(d.kind==="window"){if(!y||g.length>0||e.query)throw new p("INVALID_WINDOW_OPERATOR_INPUT",`${e.operator} requires exactly one nested pred and does not accept pred.query`);const $=e.args?.direction??"desc";if($!=="asc"&&$!=="desc")throw new p("INVALID_WINDOW_ARGS",`${e.operator} direction must be asc or desc`);const E=e.args?.partitionBy??[];if(!Array.isArray(E)||E.some(h=>typeof h!="string"))throw new p("INVALID_WINDOW_ARGS",`${e.operator} partitionBy must be an array of groupby names`);return{expression:{kind:"window",function:d.windowFunction,input:y.expression,partitionBy:E.map(h=>n(String(h))),direction:$==="asc"?"ASC":"DESC"},outputProperty:R}}return{expression:{kind:"operator",operator:e.operator,args:m,...e.query?{query:i(e.query)}:{},...y?{input:y.expression}:{},...g.length>0?{inputs:g.map(({expression:$})=>$)}:{},...y?.sourceProperty?{property:y.sourceProperty.name,column:y.sourceProperty.id}:{},...y?.sourceField?{qualifier:y.sourceField.qualifier,schemaId:y.sourceField.schemaId}:{}},outputProperty:R,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}},uc=(e,t,r,n,o,i,s,a,c,u,d,l=e)=>{const f=Ar(e),m=typeof e.pred=="string"?e.pred:void 0,y=!u||!m?r:$=>{const E=r($);return $===m?{...E,field:{...E.field,column:u}}:E},g=d?{...e,operator:d}:e,_=rt(g,t,y,n,o,i,s,a),R=c?.resolveProjection({pred:l,schema:s,..._.sourceProperty?{sourceProperty:_.sourceProperty}:{},outputProperty:{..._.outputProperty,name:f},...l.operator?{operator:t.get(l.operator)}:{}})??{..._.outputProperty,name:f};return{name:f,expression:_.expression,outputProperty:R}},dc=e=>{const t=new Set;for(const r of e){if(r.name==="_id")throw new p("RESERVED_OUTPUT_NAME","Output name _id is reserved for executor-owned row identity");if(t.has(r.name))throw new p("DUPLICATE_OUTPUT_NAME",`Duplicate output name: ${r.name}`);t.add(r.name)}},Er=(e,t,r)=>{if(!e.schema||e.schema===t.id)return t;const n=r.resolveSchema?.(e.schema);if(!n)throw new p("SCHEMA_RESOLVER_REQUIRED",`Cannot plan nested LogicForm schema without a schema resolver: ${e.schema}`,{schemaId:e.schema});return n},pc=(e,t,r,n,o,i)=>{if(t.length<2)throw new p("COMPOSITION_REQUIRES_MULTIPLE_BRANCHES","A cross-Schema plan requires at least two branches");const s=t.map(g=>he(g,Er(g,r,i),n,o,i)),a=s[0]?.groupBy.map(({name:g})=>g)??[];for(const g of s){const _=g.groupBy.map(({name:R})=>R);if(_.length!==a.length||_.some((R,$)=>R!==a[$]))throw new p("INCOMPATIBLE_COMPOSITION_GROUPBY","All composed LogicForm objects must have the same groupby output names in the same order",{expected:a,received:_});if(g.rowIdentity.kind!==(a.length>0?"group":"singleton"))throw new p("UNSTABLE_COMPOSITION_IDENTITY","Composed LogicForm objects must be grouped or aggregate to a singleton row")}const c=[],u=[],d=new Map;s.forEach((g,_)=>{g.projections.forEach((R,$)=>{const E=a.includes(R.name),h=d.get(R.name);if(h!==void 0&&!E)throw new p("DUPLICATE_COMPOSITION_OUTPUT",`Composed LogicForm objects produce the same output: ${R.name}`,{name:R.name,childIndexes:[h,_]});if(h!==void 0)return;d.set(R.name,_),c.push({name:R.name,expression:{kind:"column",property:R.name,column:R.name}});const S=g.columnProperties?.[$];S&&u.push(S)})});const l=new Set(c.map(({name:g})=>g)),f=Object.entries(e.sort??{}).map(([g,_])=>{if(!l.has(g))throw new p("INVALID_SORT",`Sort field is not an output: ${g}`);const R=u.find($=>$.name===g);return{name:g,direction:_===1?"ASC":"DESC",...R?.comparable?{comparable:R.comparable}:{},...R?.comparable?{expression:{kind:"column",property:g,column:g}}:{}}}),m=e.limitBy===void 0||a.length<2?void 0:{count:e.limitBy,partitionBy:a.slice(0,-1),orderBy:f.length>0?f:(()=>{const g=a.at(-1)??"",_=u.find(R=>R.name===g);return[{name:g,direction:"ASC",..._?.comparable?{comparable:_.comparable}:{}}]})()},y=e.limitBy!==void 0&&a.length<2?{kind:"rows",page:1,pageSize:e.limitBy}:void 0;return{schemaId:r.id,source:"",subplans:s,fields:Object.fromEntries(c.map(({name:g})=>[g,g])),projections:c,columnProperties:u,groupBy:c.filter(({name:g})=>a.includes(g)),orderBy:f,rowIdentity:a.length>0?{kind:"group",names:a,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"},...m?{groupLimit:m}:{},...y?{pagination:y}:{}}},he=(e,t,r=Ie(),n=new hr,o={})=>{const i=[...new Set((e.preds??[]).map(w=>w.schema).filter(w=>!!(w&&w!==t.id)))];if(i.length>0){const w=e.propertyResolve??{},A=[t.id,...i].map(I=>({...e,schema:I,preds:(e.preds??[]).filter(b=>(b.schema??t.id)===I).map(({schema:b,...T})=>T),...I===t.id||!e.query?{}:{query:Object.fromEntries(Object.entries(e.query).map(([b,T])=>{let P=b;try{P=z(t,b,o.resolveSchema).canonicalName}catch{}return[w[I]?.[b]??w[I]?.[P]??b,T]}))},...I!==t.id&&e.groupby?{groupby:e.groupby.map(b=>({...b,...typeof b.pred=="string"?{pred:w[I]?.[b.pred]??(()=>{try{return w[I]?.[z(t,b.pred,o.resolveSchema).canonicalName]??b.pred}catch{return b.pred}})()}:{}}))}:{}}));return pc(e,A,t,r,n,o)}for(const w of e.preds??[]){if(!w.operator)continue;const A=r.get(w.operator).rewriteLogicform?.({logicform:e,schema:t,getOperator:I=>r.get(I)});if(A)return he(A,t,r,n,o)}const s=o.semanticRegistry??Yn();if(e.from){const w=Er(e.from,t,o),A=he(e.from,w,r,n,o),I=Wn(A,t),b={...e};delete b.from,b.schema??=I.id;const T=he(b,I,r,n,o),P=new Set(T.projections.map(({name:U})=>U)),O=A.rowIdentity.kind==="group"&&A.rowIdentity.names.every(U=>P.has(U))||A.rowIdentity.kind==="singleton"?A.rowIdentity:{kind:"generated"};return{...T,source:A.source,sourcePlan:A,sourceLogicform:e.from,rowIdentity:O}}if(!e.schema)throw new p("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const a=ic(e,t,n);e=a.logicform;const c=new Map(a.predRewrites.map(({predIndex:w,column:A})=>[w,A])),u=tt(t),d=u?tc(e,u):void 0,l=za(e,t),f=s.resolveQuery({logicform:e,schema:t,...e.query?{query:e.query}:{}}),m=l?Wa(f,l.timestamp):f,y=t.id,g=new Map,_=new Map,R=new Map,$=w=>{const A=z(t,w,o.resolveSchema);let I=y;const b=[];for(const P of A.relations){b.push(P.property.name);const O=b.join("_"),U=O;if(!g.has(O)){const M=P.targetSchema.properties.filter(({type:Ee})=>Ee==="ID"),[C]=M;if(M.length!==1||!C)throw new p(P.targetSchema.temporalSemantics==="snapshot"?"SNAPSHOT_JOIN_REQUIRES_ID_AND_TIMESTAMP":"RELATION_TARGET_ID_REQUIRED",P.targetSchema.temporalSemantics==="snapshot"?`Snapshot Schema ${P.targetSchema.id} requires an ID Property when joined`:`Relation target ${P.targetSchema.id} must contain exactly one ID property`,{schemaId:P.targetSchema.id,count:M.length});const B=P.sourceSchema.id===t.id?a.mapping:n.get(P.sourceSchema.id),F=n.get(P.targetSchema.id),oe=ue(B,P.sourceSchema,P.property.name)??P.property.id,H=ue(F,P.targetSchema,C.name)??C.id,G=P.sourceSchema.properties.find(({type:Ee})=>Ee==="timestamp"),se=P.targetSchema.properties.find(({type:Ee})=>Ee==="timestamp"),pe=tt(P.targetSchema),le=G?ue(B,P.sourceSchema,G.name)??G.id:void 0,Ne=se?ue(F,P.targetSchema,se.name)??se.id:void 0;if(P.targetSchema.temporalSemantics==="snapshot"){if(!se)throw new p("SNAPSHOT_JOIN_REQUIRES_ID_AND_TIMESTAMP",`Snapshot Schema ${P.targetSchema.id} requires an ID and timestamp Property when joined`,{schemaId:P.targetSchema.id});if(!G)throw new p("SNAPSHOT_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Snapshot Schema ${P.targetSchema.id} cannot join from a Schema without a timestamp Property`,{schemaId:P.sourceSchema.id});const Ee=["second","minute","hour","day","week","month","quarter","year"],Yt=G.granularity??"day",Qt=se.granularity??"day";if(Ee.indexOf(Yt)>Ee.indexOf(Qt))throw new p("SNAPSHOT_JOIN_GRANULARITY_TOO_COARSE",`Cannot join ${P.targetSchema.id} snapshot granularity ${Qt} to coarser source granularity ${Yt}`,{sourceSchemaId:P.sourceSchema.id,targetSchemaId:P.targetSchema.id,sourceGranularity:Yt,targetGranularity:Qt})}if(pe&&!G)throw new p("VALIDITY_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Valid-time Schema ${P.targetSchema.id} cannot join from a Schema without a timestamp Property`,{schemaId:P.sourceSchema.id});const Ue=P.property.isArray?O:void 0;Ue&&!_.has(Ue)&&_.set(Ue,{path:Ue,sourceAlias:I,sourceColumn:oe,...P.property.udf?{sourceSql:P.property.udf.sql,...le?{sourceTimestampColumn:le}:{}}:{},alias:`__array_${O}`}),g.set(O,{kind:"left",path:O,sourceAlias:I,sourceColumn:oe,...P.property.udf?{sourceSql:P.property.udf.sql,...le?{sourceTimestampColumn:le}:{}}:{},targetSchemaId:P.targetSchema.id,targetSource:F.source,...F.sourceSql?{targetSourceSql:F.sourceSql}:{},targetAlias:U,targetColumn:H,...Ue?{sourceArrayExpansionPath:Ue}:{},...C.udf?{targetSql:C.udf.sql,...Ne?{targetTimestampColumn:Ne}:{}}:{},...P.targetSchema.temporalSemantics==="snapshot"&&le?{sourceTimestampColumn:le,sourceTimestampGranularity:G?.granularity??"day"}:{},...P.targetSchema.temporalSemantics==="snapshot"&&Ne?{targetTimestampColumn:Ne,targetTimestampGranularity:se?.granularity??"day"}:{},...pe&&le?{sourceTimestampColumn:le,targetValidityStartColumn:ue(F,P.targetSchema,pe.start.name)??pe.start.id,targetValidityEndColumn:ue(F,P.targetSchema,pe.end.name)??pe.end.id}:{}})}I=U}const T={schemaId:A.schema.id,property:A.property.name,propertyId:A.property.id,column:A.relations.length===0?ue(a.mapping,t,A.canonicalName)??A.property.id:A.property.id,qualifier:I,...A.property.isArray?{isArray:!0}:{},...A.property.comparable?{comparable:A.property.comparable}:{},...cc(A.relations.length>0?t:A.schema,A.property,A.relations.length>0?y:I)};return R.set(A.canonicalName,T),{reference:A.canonicalName,schema:A.schema,property:A.property,field:T}},E=w=>{if(w)for(const[A,I]of Object.entries(w))if((A==="$and"||A==="$or")&&Array.isArray(I))for(const b of I)typeof b=="object"&&b!==null&&!Array.isArray(b)&&E(b);else A.startsWith("$")||$(A)},h=w=>{if(ye(w)){const A=Er(w,t,o),I=he(w,A,r,n,o);if(I.projections.length!==1)throw new p("SUBQUERY_SINGLE_COLUMN_REQUIRED",`Query LogicForm must output exactly one column, received ${I.projections.length}`,{schemaId:w.schema,projectionCount:I.projections.length});return{kind:"logicform-subquery",plan:I}}return Array.isArray(w)?w.map(h):typeof w!="object"||w===null||w instanceof Date?w:Object.fromEntries(Object.entries(w).map(([A,I])=>[A,h(I)]))},S=(w,A)=>{if(typeof A!="object"||A===null||Array.isArray(A))throw new p("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const I=A,b=$(w),T=typeof I.schema=="string"?I.schema:b.property.ref??b.schema.id,P=T===t.id?t:o.resolveSchema?.(T);if(!P)throw new p("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${T}`);const O=P.properties.find(({id:C,name:B})=>C===I.idProperty||B===I.idProperty),U=P.properties.find(({id:C,name:B})=>C===I.parentProperty||B===I.parentProperty);if(!O)throw new p("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive ID property not found: ${String(I.idProperty)}`);if(!U)throw new p("RECURSIVE_PARENT_PROPERTY_REQUIRED",`$recursive parent property not found: ${String(I.parentProperty)}`);if(!Array.isArray(I.roots)||typeof I.includeSelf!="boolean")throw new p("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const M=n.get(T);return{kind:"recursive-query",schemaId:T,source:M.source,...M.sourceSql?{sourceSql:M.sourceSql}:{},idColumn:O.id,parentColumn:U.id,roots:I.roots,includeSelf:I.includeSelf}},N=w=>Object.fromEntries(Object.entries(w).map(([A,I])=>{if((A==="$and"||A==="$or")&&Array.isArray(I))return[A,I.map(T=>N(T))];if(typeof I=="object"&&I!==null&&!Array.isArray(I)&&Object.prototype.hasOwnProperty.call(I,"$recursive"))return[A,{$recursive:S(A,I.$recursive)}];const b=A.startsWith("$")?void 0:$(A).property.comparable;return[A,b?{kind:"ordinal-query",comparable:b,condition:h(I)}:h(I)]})),k=w=>{const A=b=>{if(!b||typeof b!="object")return!1;if(Array.isArray(b))return b.some(A);const T=b;return Object.prototype.hasOwnProperty.call(T,"$and")||Object.values(T).some(A)};if(A(w))return w;const I=new Set(Object.keys(w).flatMap(b=>{if(b.startsWith("$"))return[];const T=z(t,b,o.resolveSchema);return T.relations.length===1&&T.property.type==="ID"?[T.relations[0]?.property.name]:[]}));return Object.fromEntries(Object.entries(w).map(([b,T])=>{if(b==="$and"||b==="$or")return Array.isArray(T)?[b,T.map(H=>typeof H=="object"&&H!==null&&!Array.isArray(H)?k(H):H)]:[b,T];if(b.startsWith("$"))return[b,T];const P=z(t,b,o.resolveSchema);if(P.relations.length===0)return[b,T];if(P.property.udf?.sql.includes("$TS")===!0||P.relations.some(({property:H})=>H.udf?.sql.includes("$TS")===!0))return[b,T];const U=P.relations.map(({property:H})=>H.name).join("_");if(g.has(U))return[b,T];const[M]=P.relations;if(!M)return[b,T];if(I.has(M.property.name))return[b,T];const C=M.property.name,B=P.canonicalName.slice(C.length+1),F=M.targetSchema.properties.find(({type:H})=>H==="ID");if(!F)throw new p("RELATION_TARGET_ID_REQUIRED",`Relation target ${M.targetSchema.id} must contain an ID property`,{schemaId:M.targetSchema.id});if(P.relations.length===1&&P.property.id===F.id)return[M.property.id,T];const oe={version:e.version,schema:M.targetSchema.id,query:B?{[B]:T}:{},preds:[{pred:F.name,name:F.name}]};return[M.property.id,{$in:oe}]}))},j=(e.groupby??[]).map(w=>{const A=Ar(w);if(w.operator==="$case"&&w.args?.mode==="auto"&&(w.args.min===void 0||w.args.max===void 0))throw new p("AUTO_CASE_GROUPBY_REQUIRES_BOUNDS","$case auto mode in groupby requires explicit args.min and args.max");const I=rt(w,r,$,v,K,N,t,o.resolveSchema,"groupby");let b=I.expression;if(d?.group===w&&(b={kind:"column",schemaId:t.id,property:u?.timestamp.name??A,...u?.timestamp.id?{propertyId:u.timestamp.id}:{},column:"__period_start",qualifier:"__validity_periods"}),l?.group===w&&(b={kind:"column",schemaId:t.id,property:l.timestamp.name,propertyId:l.timestamp.id,column:"__period_start",qualifier:"__observation_periods"}),I.sourceProperty?.isArray&&I.sourceField){const T=`groupby:${A}`;_.set(T,{path:T,sourceAlias:I.sourceField.qualifier,sourceColumn:I.sourceField.column,...I.sourceField.sql?{sourceSql:I.sourceField.sql,...I.sourceField.timestampColumn?{sourceTimestampColumn:I.sourceField.timestampColumn}:{}}:{},alias:`__array_group_${_.size}`}),b={kind:"array-element",schemaId:I.sourceField.schemaId,property:I.sourceProperty.name,expansionPath:T}}return{name:A,expression:b,outputProperty:{...I.outputProperty,name:A,isArray:!1}}});function v(w){const A=(e.groupby??[]).findIndex(b=>typeof b.pred=="string"&&b.pred===w||b.name===w),I=A>=0?j[A]:void 0;if(!I)throw new p("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${w}`);return I.expression}function K(w){const A=(e.groupby??[]).findIndex(b=>typeof b.pred=="string"&&b.pred===w||b.name===w),I=A>=0?j[A]:void 0;return I?I.expression:zn($(w).field)}const D=w=>{w.operator&&r.get(w.operator).validatePlan?.({pred:w,groupByNames:j.map(({name:A})=>A),resolveGroupName:A=>{const I=(e.groupby??[]).findIndex(b=>b.name===A||typeof b.pred=="string"&&b.pred===A);return I>=0?j[I]?.name:void 0},getOperator:A=>r.get(A)}),w.pred&&typeof w.pred=="object"&&!Array.isArray(w.pred)&&D(w.pred);for(const A of Array.isArray(w.pred)?w.pred:[])D(typeof A=="string"?{pred:A}:A)};for(const w of e.preds??[])D(w);const L=[...j,...(e.preds??[]).map((w,A)=>{const b=l?.metrics.find(T=>T.pred===w)?.effectivePred??w;return uc(b,r,$,v,K,N,t,o.resolveSchema,s,c.get(A),gn(b,e.groupby??[],t,o.resolveSchema)?"$min":void 0,w)})],V=w=>Object.fromEntries(Object.entries(w).map(([A,I])=>{if((A==="$and"||A==="$or")&&Array.isArray(I))return[A,I.map(T=>V(T))];const b=L.find(({name:T})=>T===A)?.outputProperty.comparable;return b&&ac(I,A,b.values),[A,b?{kind:"ordinal-query",comparable:b,condition:h(I)}:h(I)]})),q=m?k(m):void 0;E(q);const re=w=>{E(w.query),w.pred&&typeof w.pred=="object"&&!Array.isArray(w.pred)&&re(w.pred);for(const A of Array.isArray(w.pred)?w.pred:[])re(typeof A=="string"?{pred:A}:A)};for(const w of e.preds??[])re(w);if(L.length===0)throw new p("EMPTY_PROJECTION","LogicForm must contain preds or groupby");dc(L);const W=new Set(L.map(({name:w})=>w)),Z=j.length>0?{kind:"group",names:j.map(({name:w})=>w),separator:"_",nullLabel:"\u7A7A\u503C"}:L.every(({expression:w})=>w.kind==="column")||L.some(({expression:w})=>w.kind==="property-sql"&&t.properties.some(({id:A,type:I})=>I==="ID"&&A===w.propertyId))?(()=>{const w=t.properties.find(({type:A})=>A==="ID");return w&&(o.canUsePropertyRowIdentity?.(t,w)??!0)?{kind:"property",column:w.id,internalName:"_id"}:{kind:"generated"}})():{kind:"singleton"},ne=Object.entries(e.sort??{}).map(([w,A])=>{if(!W.has(w))throw new p("INVALID_SORT",`Sort field is not an output: ${w}`);const I=L.find(b=>b.name===w);return{name:w,direction:A===1?"ASC":"DESC",...I?.outputProperty.comparable?{comparable:I.outputProperty.comparable,expression:I.expression}:{}}}),X=e.limit===void 0?void 0:e.limit>0&&e.limit<1?{kind:"ratio",page:e.page??1,ratio:e.limit}:{kind:"rows",page:e.page??1,pageSize:e.limit},ce=e.limitBy===void 0?void 0:{count:e.limitBy,partitionBy:j.slice(0,-1).map(({name:w})=>w),orderBy:ne.length>0?ne:(()=>{const w=j.at(-1);return[{name:w?.name??"",direction:"ASC",...w?.outputProperty.comparable?{comparable:w.outputProperty.comparable,expression:w.expression}:{}}]})()},Q=R.size===0&&g.size===0&&_.size===0&&!q&&j.length===0&&L.length>0&&L.every(({expression:w})=>w.kind==="operator"&&w.operator==="$constant");return{schemaId:t.id,source:Q?"":a.mapping.source,...!Q&&a.mapping.sourceSql?{sourceSql:a.mapping.sourceSql}:{},mappingId:a.mapping.id??a.mapping.source,sourceAlias:y,fields:{...Wi(t),...Object.fromEntries(t.properties.flatMap(w=>{const A=ue(a.mapping,t,w.name);return A?[[w.name,A],[w.id,A]]:[]}))},fieldReferences:Object.fromEntries(R),joins:[...g.values()],arrayExpansions:[..._.values()],...d&&u?{validityPeriods:{alias:"__validity_periods",labelColumn:"__period_start",asOfColumn:"__as_of",sourceAlias:y,startColumn:ue(a.mapping,t,u.start.name)??u.start.id,endColumn:ue(a.mapping,t,u.end.name)??u.end.id,periods:d.periods}}:{},...l?{observationPeriods:{alias:"__observation_periods",labelColumn:"__period_start",asOfColumn:"__as_of",sourceAlias:y,lookupAlias:"__observation_lookup",timestampColumn:ue(a.mapping,t,l.timestamp.name)??l.timestamp.id,periods:l.periods}}:{},projections:L.map(({name:w,expression:A})=>({name:w,expression:A})),columnProperties:L.map(({outputProperty:w})=>w),groupBy:j.map(({name:w,expression:A})=>({name:w,expression:A})),...q?{query:N(q)}:{},...e.having?{having:V(e.having)}:{},orderBy:ne,rowIdentity:Q?{kind:"singleton"}:Z,...X?{pagination:X}:{},...ce?{groupLimit:ce}:{}}},nt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.kind==="logicform-subquery"&&typeof e.plan=="object"&&e.plan!==null,Jn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.kind==="recursive-query",lc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.kind==="ordinal-query";class fc{provider;parameterOffset;values=[];constructor(t,r=0){this.provider=t,this.parameterOffset=r}add(t){const r=this.parameterOffset+this.values.length;return this.values.push(t),this.provider.parameter(r,t)}get nextParameterOffset(){return this.parameterOffset+this.values.length}append(t){this.values.push(...t)}}const mc=(e,t)=>{const r=t.split(".");if(r.some(n=>n.length===0))throw new p("INVALID_SOURCE",`Invalid physical source: ${t}`);return r.map(n=>e.quoteIdentifier(n)).join(".")},_r=(e,t,r)=>r===void 0?mc(e,t):`(${r.trim().replace(/;+\s*$/,"")})`,ot=(e,t,r,n,o)=>{const i=Nn(e,[],String,`Property ${t} udf.sql`);if(!i.includes("$TS"))return i;if(!n)throw new p("PROPERTY_UDF_TIMESTAMP_REQUIRED",`Property ${t} udf.sql uses $TS but its evaluation context has no timestamp Property`,{property:t});const s=(o?`${r.quoteIdentifier(o)}.`:"")+r.quoteIdentifier(n);return i.replace(/\$TS/g,s)},ge=(e,t,r,n=!1,o,i,s,a)=>{const c=(u,d)=>n&&d?`${t.quoteIdentifier(d)}.${t.quoteIdentifier(u)}`:t.quoteIdentifier(u);switch(e.kind){case"array-element":if(!a)throw new p("ARRAY_EXPANSION_UNAVAILABLE","Array expansion compiler is unavailable");return a(e.expansionPath);case"column":return c(e.column,e.qualifier);case"property-sql":return ot(e.sql,e.property,t,e.timestampColumn,n?e.timestampQualifier??e.qualifier:void 0);case"window":{if(ae(e.input,r))throw new p("UNSUPPORTED_MIXED_OPERATOR","Window operators cannot consume a JavaScript operator");const u=e.partitionBy.length>0?`PARTITION BY ${e.partitionBy.map(f=>ge(f,t,r,n,o,i,s,a)).join(", ")} `:"",d=ge(e.input,t,r,n,o,i,s,a);return`${e.function==="rank"?"RANK":"ROW_NUMBER"}() OVER (${u}ORDER BY ${d} ${e.direction})`}case"cumulative":{if(ae(e.input,r))throw new p("UNSUPPORTED_MIXED_OPERATOR","Cumulative expressions cannot consume a JavaScript operator");const u=ge(e.input,t,r,n,o,i,s,a),d=e.partitionBy.length>0?`PARTITION BY ${e.partitionBy.map(f=>ge(f,t,r,n,o,i,s,a)).join(", ")} `:"",l=e.orderBy.map(f=>`${ge(f.expression,t,r,n,o,i,s,a)} ${f.direction}`).join(", ");return`${t.aggregateFunction(e.function,u)} OVER (${d}ORDER BY ${l} ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`}case"ordinal-encode":{if(!i)throw new p("SQL_BINDER_UNAVAILABLE","Ordinal encoding requires a value binder");return`CASE ${e.comparable.values.map((d,l)=>`WHEN ${ge(e.input,t,r,n,o,i,s,a)} = ${i(d)} THEN ${e.comparable.direction*l}`).join(" ")} END`}case"ordinal-decode":{if(!i)throw new p("SQL_BINDER_UNAVAILABLE","Ordinal decoding requires a value binder");return`CASE ${e.comparable.values.map((d,l)=>`WHEN ${ge(e.input,t,r,n,o,i,s,a)} = ${e.comparable.direction*l} THEN ${i(d)}`).join(" ")} END`}case"operator":{const u=r.get(e.operator);if(u.kind==="component")throw new p("COMPONENT_OPERATOR_REQUIRES_EXECUTOR",`${e.operator} must be compiled through the executor component pipeline`);if(u.toSQL&&(e.input&&ae(e.input,r)||e.inputs?.some(f=>ae(f,r))))throw new p("UNSUPPORTED_MIXED_OPERATOR",`${e.operator} cannot consume a JavaScript operator in SQL`);let d=e.input?ge(e.input,t,r,n,o,i,s,a):e.column?c(e.column,e.qualifier):void 0;const l=e.inputs?.map(f=>ge(f,t,r,n,o,i,s,a));if(e.query&&Object.keys(e.query).length>0){if(u.kind!=="aggregate")throw new p("OPERATOR_QUERY_REQUIRES_AGGREGATION",`Pred query is only supported by aggregation operators: ${e.operator}`);if(!o)throw new p("INVALID_OPERATOR_QUERY","Operator query compiler is unavailable");d=`CASE WHEN ${o(e.query)} THEN ${d??"1"} END`}if(u.requiresProperty!==!1&&!d)throw new p("PRED_PROPERTY_REQUIRED",`${e.operator} requires a column`);return u.toSQL?u.toSQL({sql:{aggregateFunction:t.aggregateFunction.bind(t),quoteIdentifier:t.quoteIdentifier.bind(t),concat:t.concat.bind(t),substring:t.substring.bind(t),dateBucket:t.dateBucket.bind(t),dateShift:t.dateShift.bind(t),...t.datePeriodBoundary?{datePeriodBoundary:t.datePeriodBoundary.bind(t)}:{},...t.scalarExtremum?{scalarExtremum:t.scalarExtremum.bind(t)}:{},value:(f,m)=>{if(!i)throw new p("SQL_BINDER_UNAVAILABLE","SQL value binder is unavailable");const y=i(f);return m&&t.castValue?t.castValue(y,m):y},condition:(f,m)=>{if(!s)throw new p("SQL_CONDITION_UNAVAILABLE","SQL condition compiler is unavailable");return s(f,m)}},...d?{expression:d,column:d}:{},...l?{expressions:l}:{},args:e.args}):d??"NULL"}}},ae=(e,t)=>e.kind==="window"?ae(e.input,t)||e.partitionBy.some(r=>ae(r,t)):e.kind==="cumulative"?ae(e.input,t)||e.partitionBy.some(r=>ae(r,t))||e.orderBy.some(r=>ae(r.expression,t)):e.kind==="ordinal-encode"||e.kind==="ordinal-decode"?ae(e.input,t):e.kind==="operator"&&(!t.get(e.operator).toSQL&&!!t.get(e.operator).evaluate||(e.input?ae(e.input,t):!1)||(e.inputs?.some(r=>ae(r,t))??!1)),yc=(e,t)=>e.sourceSql?ot(e.sourceSql,e.sourceColumn,t,e.sourceTimestampColumn,e.sourceAlias):`${t.quoteIdentifier(e.sourceAlias)}.${t.quoteIdentifier(e.sourceColumn)}`,Zn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).some(t=>t.startsWith("$")),hc=(e,t,r)=>{if(!r.supportsRecursiveCte)throw new p("RECURSIVE_QUERY_UNSUPPORTED",`Provider ${r.kind} does not support recursive queries`);if(e.roots.length===0)return"(SELECT NULL WHERE 1 = 0)";const n=r.quoteIdentifier("__recursive_tree__"),o=r.quoteIdentifier("__recursive_id__"),i=r.quoteIdentifier("__recursive_node__"),s=r.quoteIdentifier("__recursive_child__"),a=r.quoteIdentifier(e.idColumn),c=r.quoteIdentifier(e.parentColumn),u=_r(r,e.source,e.sourceSql),d=()=>e.roots.map(y=>t.add(y)).join(", "),l=(y,g=!1)=>e.roots.length===1?`${y} ${g?"<>":"="} ${d()}`:`${y} ${g?"NOT IN":"IN"} (${d()})`,f=`${i}.${a}`,m=e.includeSelf?l(f):`${l(`${i}.${c}`)} AND ${l(f,!0)}`;return`(WITH RECURSIVE ${n}(${o}) AS ( SELECT ${f} FROM ${r.tableAlias(u,"__recursive_node__")} WHERE ${m} UNION SELECT ${s}.${a} FROM ${r.tableAlias(u,"__recursive_child__")} JOIN ${n} ON ${s}.${c} = ${n}.${o}) SELECT DISTINCT ${o} FROM ${n})`},it=(e,t,r,n,o,i,s)=>{if(t==="$recursive"){if(!Jn(r))throw new p("INVALID_RECURSIVE_QUERY","$recursive query was not planned");return`${e} IN ${hc(r,n,o)}`}if(t==="$eq"&&r===null)return`${e} IS NULL`;if(t==="$ne"&&r===null)return`${e} IS NOT NULL`;const c={$eq:"=",$ne:"<>",$gt:">",$gte:">=",$lt:"<",$lte:"<="}[t];if(c){const u=nt(r)?`(${i(r)})`:n.add(r);return`${e} ${c} ${u}`}if(t==="$in"||t==="$nin"){const u=t==="$in"?"IN":"NOT IN";if(nt(r))return`${e} ${u} (${i(r)})`;if(!Array.isArray(r))throw new p("INVALID_QUERY_VALUE",`${t} requires an array or query LogicForm`);if(r.length===0)return t==="$in"?"0 = 1":"1 = 1";const d=r.filter(nt);if(d.length>0){if(d.length!==r.length)throw new p("MIXED_SUBQUERY_VALUES",`${t} cannot mix query LogicForm objects and literal values`);return`${e} ${u} (${d.map(i).join(" UNION ALL ")})`}const l=r.map(f=>n.add(f)).join(", ");return`${e} ${u} (${l})`}if(nt(r))throw new p("UNSUPPORTED_SUBQUERY_OPERATOR",`Query LogicForm is not supported by ${t}`);if(t==="$exists")return`${e} IS ${r?"NOT ":""}NULL`;if(t==="$contains")return`${e} LIKE ${n.add(`%${String(r)}%`)}`;if(t==="$regex"){if(typeof r!="string"||s!==void 0&&typeof s!="string")throw new p("INVALID_QUERY_VALUE","$regex requires a string pattern and args.options must be a string");return o.regex(e,n.add(r),s)}throw new p("UNSUPPORTED_QUERY_OPERATOR",`Unsupported query operator: ${t}`)},Nt=(e,t,r,n,o)=>{if(lc(t)){const c=()=>`CASE ${t.comparable.values.map((f,m)=>`WHEN ${e} = ${r.add(f)} THEN ${t.comparable.direction*m}`).join(" ")} END`,u=new Set(["$gt","$gte","$lt","$lte"]),d=l=>typeof l!="object"||l===null||Array.isArray(l)?Nt(e,l,r,n,o):Object.entries(l).filter(([f])=>f!=="args").map(([f,m])=>(f==="$and"||f==="$or")&&Array.isArray(m)?`(${m.map(d).join(f==="$and"?" AND ":" OR ")})`:u.has(f)?it(c(),f,t.comparable.direction*t.comparable.values.indexOf(String(m)),r,n,o):it(e,f,m,r,n,o)).join(" AND ");return d(t.condition)}if(Array.isArray(t))return it(e,"$in",t,r,n,o);if(!Zn(t))return it(e,"$eq",t,r,n,o);const i=[],s=t.args;if(s!==void 0){if(typeof s!="object"||s===null||Array.isArray(s))throw new p("INVALID_QUERY_VALUE","Query args.options must be a string");const c=s.options;if(c!==void 0&&typeof c!="string")throw new p("INVALID_QUERY_VALUE","Query args.options must be a string")}const a=s?.options;for(const[c,u]of Object.entries(t))if(c==="$and"||c==="$or"){if(!Array.isArray(u))throw new p("INVALID_QUERY_VALUE",`${c} requires an array`);const d=u.map(l=>Nt(e,l,r,n,o));i.push(`(${d.join(c==="$and"?" AND ":" OR ")})`)}else c!=="args"&&i.push(it(e,c,u,r,n,o,c==="$regex"?a:void 0));if(i.length===0)throw new p("EMPTY_QUERY_CONDITION","Query condition contains no operators");return i.join(" AND ")},Xn=(e,t,r,n)=>{if(!n.arrayContains)throw new p("ARRAY_CONDITION_UNSUPPORTED",`Provider ${n.kind} does not support array conditions`);const o=n.arrayContains.bind(n),i=a=>o(e,r.add(a));if(Array.isArray(t))return`(${t.map(i).join(" OR ")})`;if(!Zn(t))return i(t);const s=[];for(const[a,c]of Object.entries(t))if(a==="$and"||a==="$or"){if(!Array.isArray(c))throw new p("INVALID_QUERY_VALUE",`${a} requires an array`);const u=c.map(d=>Xn(e,d,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 p("INVALID_QUERY_VALUE",`${a} requires an array`);const u=c.map(i),d=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 ")})`:`(${d})`)}else if(a==="$exists")s.push(`${e} IS ${c?"NOT ":""}NULL`);else if(a!=="args")throw new p("UNSUPPORTED_ARRAY_QUERY_OPERATOR",`Unsupported array query operator: ${a}`);if(s.length===0)throw new p("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},xe=(e,t,r,n,o,i)=>{const s=[];for(const[a,c]of Object.entries(e)){if(a==="$and"||a==="$or"){if(!Array.isArray(c))throw new p("INVALID_QUERY_VALUE",`${a} requires an array`);const d=c.map(l=>{if(typeof l!="object"||l===null||Array.isArray(l))throw new p("INVALID_QUERY_VALUE",`${a} items must be query objects`);return xe(l,t,r,n,o,i)});s.push(`(${d.join(a==="$and"?" AND ":" OR ")})`);continue}const u=t(a);s.push(r(a)?Xn(u,c,n,o):Nt(u,c,n,o,i))}return s.join(" AND ")},Pt=(e,t,r,n,o)=>e.orderBy.map(i=>{const s=t.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,f)=>`WHEN ${u} = ${r.add(l)} THEN ${c.direction*f}`).join(" ")} END`:a} ${i.direction}`}).join(", "),Sr=(e,t)=>{let r=e;for(;t.has(r);)r=`_${r}`;return r},eo=(e,t,r,n)=>t.concat(e.flatMap((o,i)=>[...i>0?[`'${r.replaceAll("'","''")}'`]:[],`CASE WHEN ${o} IS NULL THEN '${n.replaceAll("'","''")}' ELSE ${t.stringify(o)} END`])),gc=(e,t,r,n,o)=>{const i=new Set(t.projections.map(({name:j})=>j)),s="__sdb_page_source",a="__sdb_page",c=n.quoteIdentifier(s),u=n.quoteIdentifier(a),d=Sr("__sdb_row_number",i),l=Sr("__sdb_total_rows",i),f=n.quoteIdentifier(d),m=n.quoteIdentifier(l),y=Pt(t,n,o,c),g=y?`ORDER BY ${y}`:"",_=`CEIL(${m} * ${r.ratio})`,R=r.page-1,$=r.page,h=[...t.projections.map(({name:j})=>j),...t.rowIdentity.kind==="property"?[t.rowIdentity.internalName]:[],...t.rowIdentity.kind==="group"?["_id"]:[]].map(j=>`${u}.${n.quoteIdentifier(j)}`).join(", "),S=Pt(t,n,o,u),N=`SELECT ${c}.*, ROW_NUMBER() OVER (${g}) AS ${f}, COUNT(*) OVER () AS ${m} FROM ${n.tableAlias(`(${e})`,s)}`;let k=`SELECT ${h} FROM ${n.tableAlias(`(${N})`,a)} WHERE ${u}.${f} > ${R} * ${_} AND ${u}.${f} <= ${$} * ${_}`;return S&&(k+=` ORDER BY ${S}`),k},to=(e,t,r,n)=>{const o=t.groupLimit;if(!o)return e;const i="__sdb_limit_by_source",s="__sdb_limit_by_ranked",a=r.quoteIdentifier(i),c=r.quoteIdentifier(s),u=new Set(t.projections.map(({name:$})=>$)),d=Sr("__sdb_limit_by_row_number",u),l=r.quoteIdentifier(d),f=o.partitionBy.map($=>`${a}.${r.quoteIdentifier($)}`).join(", "),m=o.orderBy.map(({name:$,direction:E,comparable:h})=>{const S=`${a}.${r.quoteIdentifier($)}`;return`${h?`CASE ${h.values.map((k,j)=>`WHEN ${S} = ${n.add(k)} THEN ${h.direction*j}`).join(" ")} END`:S} ${E}`}).join(", "),g=[...t.projections.map(({name:$})=>$),...t.rowIdentity.kind==="property"?[t.rowIdentity.internalName]:[],...t.rowIdentity.kind==="group"?["_id"]:[]].map($=>`${c}.${r.quoteIdentifier($)}`).join(", "),_=`PARTITION BY ${f} ORDER BY ${m}`,R=`SELECT ${a}.*, ROW_NUMBER() OVER (${_}) AS ${l} FROM ${r.tableAlias(`(${e})`,i)}`;return`SELECT ${g} FROM ${r.tableAlias(`(${R})`,s)} WHERE ${c}.${l} <= ${o.count}`},fe=(e,t,r=Ie(),n=0)=>{const o=new fc(t,n);if(e.subplans){const h=e.projections.map(({name:v})=>v),S=e.subplans.map((v,K)=>{const D=fe(v,t,r,o.nextParameterOffset);o.append(D.parameters);const L=`__composition_child_${K}`,V=t.quoteIdentifier(L),q=new Set(v.projections.map(({name:re})=>re));return{aliasName:L,alias:V,available:q,sql:D.sql}}),N=S[0];if(!N)throw new p("INVALID_COMPOSITION","Composition has no children");const k=h.map(v=>`${(S.find(D=>D.available.has(v))??N).alias}.${t.quoteIdentifier(v)} AS ${t.quoteIdentifier(v)}`);e.rowIdentity.kind==="group"&&k.push(`${N.alias}.${t.quoteIdentifier("_id")} AS ${t.quoteIdentifier("_id")}`);let j=`SELECT ${k.join(", ")} FROM ${t.tableAlias(`(${N.sql})`,N.aliasName)}`;for(const v of S.slice(1))j+=` LEFT JOIN ${t.tableAlias(`(${v.sql})`,v.aliasName)}`,j+=e.rowIdentity.kind==="group"?` ON ${N.alias}.${t.quoteIdentifier("_id")} = ${v.alias}.${t.quoteIdentifier("_id")}`:" ON 1 = 1";return e.groupLimit&&(j=to(j,e,t,o)),e.orderBy.length>0&&(j+=` ORDER BY ${Pt(e,t,o)}`),e.pagination?.kind==="rows"&&(j=t.paginate(j,e.pagination.pageSize,0)),{sql:j,parameters:o.values}}const i=h=>{if(h.plan.projections.some(({expression:N})=>ae(N,r)))throw new p("JAVASCRIPT_OPERATOR_IN_SUBQUERY","A query LogicForm cannot use a JavaScript-only operator");const S=fe(h.plan.rowIdentity.kind==="property"||h.plan.rowIdentity.kind==="group"?{...h.plan,rowIdentity:{kind:"generated"}}:h.plan,t,r,o.nextParameterOffset);return o.append(S.parameters),S.sql},s=(e.joins?.length??0)>0,a=(e.arrayExpansions?.length??0)>0,c=s||a||e.sourcePlan!==void 0||e.sourceSql!==void 0||e.validityPeriods!==void 0||e.observationPeriods!==void 0,u=new Map,d=(e.arrayExpansions??[]).map(h=>{if(!t.expandArray)throw new p("ARRAY_EXPANSION_UNSUPPORTED",`Provider ${t.kind} does not support array expansion`);const S=t.expandArray(yc(h,t),h.alias,"value");return u.set(h.path,S.valueExpression),S}),l=h=>{const S=e.fieldReferences?.[h];if(S?.sql)return ot(S.sql,S.property,t,S.timestampColumn,c?S.timestampQualifier??S.qualifier:void 0);if(S&&c)return`${t.quoteIdentifier(S.qualifier)}.${t.quoteIdentifier(S.column)}`;const N=e.fields[h];if(!N)throw new p("PROPERTY_NOT_FOUND",`Query property not found: ${h}`);return t.quoteIdentifier(N)},f=h=>ge(h,t,r,c,S=>xe(S,l,N=>e.fieldReferences?.[N]?.isArray===!0,o,t,i),S=>o.add(S),(S,N)=>Nt(S,N,o,t,i),S=>{const N=u.get(S);if(!N)throw new p("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${S}`);return N}),m=e.projections.map(h=>`${f(h.expression)} AS ${t.quoteIdentifier(h.name)}`),y=e.rowIdentity.kind==="property"?`${c&&e.sourceAlias?`${t.quoteIdentifier(e.sourceAlias)}.`:""}${t.quoteIdentifier(e.rowIdentity.column)} AS ${t.quoteIdentifier(e.rowIdentity.internalName)}`:e.rowIdentity.kind==="group"?(()=>{const h=e.rowIdentity.names.map(S=>{const N=e.groupBy.find(k=>k.name===S)??e.projections.find(k=>k.name===S);if(!N)throw new p("GROUP_IDENTITY_OUTPUT_NOT_FOUND",`Group identity output not found: ${S}`);return f(N.expression)});return`${eo(h,t,e.rowIdentity.separator,e.rowIdentity.nullLabel)} AS ${t.quoteIdentifier("_id")}`})():void 0,g=[...m,...y?[y]:[]].join(", "),_=e.sourcePlan?(()=>{const h=fe(e.sourcePlan,t,r,o.nextParameterOffset);return o.append(h.parameters),`(${h.sql})`})():e.source?_r(t,e.source,e.sourceSql):"",R=c&&e.sourceAlias?t.tableAlias(_,e.sourceAlias):_;let $=`SELECT ${g}`;if(e.validityPeriods){const h=e.validityPeriods,S=h.periods.map(({label:V,asOf:q},re)=>{const W=o.add(V),Z=o.add(q);return re===0?`SELECT ${W} AS ${t.quoteIdentifier(h.labelColumn)}, ${Z} AS ${t.quoteIdentifier(h.asOfColumn)}`:`SELECT ${W}, ${Z}`}).join(" UNION ALL "),N=t.tableAlias(`(${S})`,h.alias),k=t.tableAlias(_,h.sourceAlias),j=t.quoteIdentifier(h.alias),v=t.quoteIdentifier(h.sourceAlias),K=`${j}.${t.quoteIdentifier(h.asOfColumn)}`,D=`${v}.${t.quoteIdentifier(h.startColumn)}`,L=`${v}.${t.quoteIdentifier(h.endColumn)}`;$+=` FROM ${N} LEFT JOIN ${k} ON ${D} <= ${K} AND (${L} > ${K} OR ${L} IS NULL)`,e.query&&Object.keys(e.query).length>0&&($+=` AND ${xe(e.query,l,V=>e.fieldReferences?.[V]?.isArray===!0,o,t,i)}`)}else if(e.observationPeriods){const h=e.observationPeriods,S=h.periods.map(({label:W,asOf:Z},ne)=>{const X=o.add(W),ce=o.add(Z);return ne===0?`SELECT ${X} AS ${t.quoteIdentifier(h.labelColumn)}, ${ce} AS ${t.quoteIdentifier(h.asOfColumn)}`:`SELECT ${X}, ${ce}`}).join(" UNION ALL "),N=t.tableAlias(`(${S})`,h.alias),k=t.tableAlias(_,h.sourceAlias),j=t.tableAlias(_,h.lookupAlias),v=t.quoteIdentifier(h.alias),K=t.quoteIdentifier(h.sourceAlias),D=t.quoteIdentifier(h.lookupAlias),L=`${v}.${t.quoteIdentifier(h.asOfColumn)}`,V=`${K}.${t.quoteIdentifier(h.timestampColumn)}`,q=`${D}.${t.quoteIdentifier(h.timestampColumn)}`,re=`SELECT ${t.aggregateFunction("max",q)} FROM ${j} WHERE ${q} <= ${L}`;$+=` FROM ${N} LEFT JOIN ${k} ON ${V} = (${re})`,e.query&&Object.keys(e.query).length>0&&($+=` AND ${xe(e.query,l,W=>e.fieldReferences?.[W]?.isArray===!0,o,t,i)}`)}else R&&($+=` FROM ${R}`);for(const h of d)$+=` ${h.joinSql}`;for(const h of e.joins??[]){$+=` LEFT JOIN ${t.tableAlias(_r(t,h.targetSource,h.targetSourceSql),h.targetAlias)}`;const S=h.sourceArrayExpansionPath?u.get(h.sourceArrayExpansionPath):h.sourceSql?ot(h.sourceSql,h.sourceColumn,t,h.sourceTimestampColumn,h.sourceAlias):`${t.quoteIdentifier(h.sourceAlias)}.${t.quoteIdentifier(h.sourceColumn)}`,N=h.targetSql?ot(h.targetSql,h.targetColumn,t,h.targetTimestampColumn,h.targetAlias):`${t.quoteIdentifier(h.targetAlias)}.${t.quoteIdentifier(h.targetColumn)}`;if(!S)throw new p("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${h.path}`);if($+=` ON ${S} = ${N}`,h.sourceTimestampColumn&&h.targetTimestampColumn&&h.sourceTimestampGranularity&&h.targetTimestampGranularity){const k=`${t.quoteIdentifier(h.sourceAlias)}.${t.quoteIdentifier(h.sourceTimestampColumn)}`,j=`${t.quoteIdentifier(h.targetAlias)}.${t.quoteIdentifier(h.targetTimestampColumn)}`;$+=` AND ${t.dateBucket(k,h.sourceTimestampGranularity)} = ${t.dateBucket(j,h.targetTimestampGranularity)}`}if(h.sourceTimestampColumn&&h.targetValidityStartColumn&&h.targetValidityEndColumn){const k=`${t.quoteIdentifier(h.sourceAlias)}.${t.quoteIdentifier(h.sourceTimestampColumn)}`,j=`${t.quoteIdentifier(h.targetAlias)}.${t.quoteIdentifier(h.targetValidityStartColumn)}`,v=`${t.quoteIdentifier(h.targetAlias)}.${t.quoteIdentifier(h.targetValidityEndColumn)}`;$+=` AND ${j} <= ${k} AND (${v} > ${k} OR ${v} IS NULL)`}}const E=[];if(!e.validityPeriods&&!e.observationPeriods&&e.query&&Object.keys(e.query).length>0&&E.push(xe(e.query,l,h=>e.fieldReferences?.[h]?.isArray===!0,o,t,i)),E.length>0&&($+=` WHERE ${E.join(" AND ")}`),e.groupBy.length>0){const h=e.groupBy.map(N=>f(N.expression)),S=e.rowIdentity.kind==="group"?[eo(h,t,e.rowIdentity.separator,e.rowIdentity.nullLabel)]:[];$+=` GROUP BY ${[...h,...S].join(", ")}`}if(e.having&&Object.keys(e.having).length>0){const h=S=>{const N=e.projections.find(k=>k.name===S);if(!N)throw new p("INVALID_HAVING",`Having field is not an output: ${S}`);return t.supportsHavingAlias===!1?f(N.expression):t.quoteIdentifier(S)};$+=` HAVING ${xe(e.having,h,()=>!1,o,t,i)}`}if(e.groupLimit&&($=to($,e,t,o)),e.pagination?.kind==="ratio")$=gc($,e,e.pagination,t,o);else if(e.orderBy.length>0&&($+=` ORDER BY ${Pt(e,t,o,void 0,f)}`),e.pagination?.kind==="rows"){const h=(e.pagination.page-1)*e.pagination.pageSize;$=t.paginate($,e.pagination.pageSize,h)}return{sql:$,parameters:o.values}},$c=(e,t)=>{const r=Object.keys(t).sort((f,m)=>m.length-f.length),n=[];let o=0;for(;o<e.length;){const f=e[o];if(f&&/\s/.test(f)){o+=1;continue}if(f&&/[()+\-*/,]/.test(f)){n.push(f),o+=1;continue}const m=e.slice(o).match(/^\d+(?:\.\d+)?/);if(m?.[0]){n.push(m[0]),o+=m[0].length;continue}const y=r.find(_=>e.startsWith(_,o));if(y){n.push(y),o+=y.length;continue}const g=e.slice(o).match(/^[A-Za-z_$][\w$]*/);if(g?.[0]){n.push(g[0]),o+=g[0].length;continue}n.push(f??""),o+=1}let i=0;const s=()=>n[i],a=()=>n[i++],c=()=>{const f=a();if(!f)throw new Error("Component expression is incomplete");if(f==="("){const y=d();if(a()!==")")throw new Error("Component expression has an unclosed parenthesis");return`(${y})`}if(/^\d/.test(f))return f;if(!t[f]&&!/^[A-Za-z_$][\w$]*$/.test(f))throw new Error(`Invalid component expression token: ${f}`);if(s()==="("){a();const y=[];if(s()!==")")for(;y.push(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()}(${y.join(", ")})`}const m=t[f];if(!m)throw new Error(`Unknown component in expression: ${f}`);return m},u=()=>{let f=c();for(;s()==="*"||s()==="/";)f=`${f} ${a()} ${c()}`;return f},d=()=>{let f=u();for(;s()==="+"||s()==="-";)f=`${f} ${a()} ${u()}`;return f},l=d();if(i!==n.length)throw new Error(`Unexpected component expression token: ${s()}`);return l},wc=e=>`__sdb_cte_${e}`,ro=e=>{const t=e.projections[e.groupBy.length];if(!t)throw new Error("CTE component must produce one metric projection");return t.name},Ac=(e,t)=>e?.find(r=>r.name===t),Ec=(e,t,r)=>r===0?e:t.kind==="postgresql"?e.replace(/\$(\d+)/g,(n,o)=>`$${Number(o)+r}`):t.kind==="oracle"?e.replace(/:(\d+)/g,(n,o)=>`:${Number(o)+r}`):t.kind==="clickhouse"?e.replace(/\{p(\d+):([^}]+)\}/g,(n,o,i)=>`{p${Number(o)+r}:${i}}`):e,no=(e,t,r,n=Ie())=>{if(e.length===0)throw new Error("CTE query combination requires at least one unit");let o=0;const i=e.map(($,E)=>{const h={...$.compiled,sql:Ec($.compiled.sql,r,o)};return o+=$.compiled.parameters.length,{...$,compiled:h,alias:`__sdb_exec_${E}`}}),s=i.map(({alias:$,compiled:E})=>`${r.quoteIdentifier($)} AS (${E.sql})`),a=i[0],c=r.quoteIdentifier(a.alias),u=t.groupBy.map(({name:$})=>$),d=t.orderBy??[],l=t.rowIdentity.kind==="group",f=r.quoteIdentifier("__sdb_exec_keys");if(l){const $=E=>[...u.map(h=>`${E}.${r.quoteIdentifier(h)}`),`${E}.${r.quoteIdentifier("_id")}`].join(", ");s.push(`${f} AS (${i.map(({alias:E})=>`SELECT ${$(r.quoteIdentifier(E))} FROM ${r.quoteIdentifier(E)}`).join(" UNION ")})`)}const m=l?f:c,y=[...u,...e.flatMap(({outputs:$})=>$)],g=y.filter(($,E,h)=>h.indexOf($)===E).map($=>{if(u.includes($))return`${m}.${r.quoteIdentifier($)} AS ${r.quoteIdentifier($)}`;const E=i.find(({outputs:S})=>S.includes($));if(!E)throw new Error(`CTE execution unit does not expose output projection: ${$}`);return`${r.quoteIdentifier(E.alias)}.${r.quoteIdentifier($)} AS ${r.quoteIdentifier($)}`});l&&g.push(`${m}.${r.quoteIdentifier("_id")} AS ${r.quoteIdentifier("_id")}`);let _=`SELECT ${g.join(", ")} FROM ${m}`;for(const $ of l?i:i.slice(1)){const E=r.quoteIdentifier($.alias);_+=` LEFT JOIN ${E}`,_+=l?` ON ${m}.${r.quoteIdentifier("_id")} = ${E}.${r.quoteIdentifier("_id")}`:" ON 1 = 1"}if(!!(t.having&&Object.keys(t.having).length>0||d.length>0||t.pagination||t.groupLimit)){const $={schemaId:t.schemaId,source:"__sdb_cte_result_source",sourceSql:_,sourceAlias:"__sdb_cte_result",fields:Object.fromEntries(y.map(h=>[h,h])),projections:y.map(h=>({name:h,expression:{kind:"column",property:h,column:h}})),groupBy:[],...t.having&&Object.keys(t.having).length>0?{query:t.having}:{},orderBy:d.map(({name:h,direction:S,comparable:N})=>({name:h,direction:S,...N?{comparable:N}:{}})),...t.pagination?{pagination:t.pagination}:{},...t.groupLimit?{groupLimit:t.groupLimit}:{},rowIdentity:{kind:"generated"}},E=fe($,r,n,o);return{sql:`WITH ${s.join(", ")} ${E.sql}`,parameters:[...i.flatMap(({compiled:h})=>h.parameters),...E.parameters]}}return{sql:`WITH ${s.join(", ")} ${_}`,parameters:i.flatMap(({compiled:$})=>$.parameters)}},Ir=(e,t,r,n,o,i)=>{const s=[];let a=0;for(const $ of t){const E=fe($.plan,o,i,a);a+=E.parameters.length,s.push({input:$,sql:E,alias:wc($.name)})}const c=s.map(({sql:$,alias:E})=>`${o.quoteIdentifier(E)} AS (${$.sql})`).join(", "),u=s[0];if(!u)throw new Error("CTE calculation requires a current component");const d=o.quoteIdentifier(u.alias),l=r.groupBy.map(({name:$})=>$),f=l.map($=>`${d}.${o.quoteIdentifier($)} AS ${o.quoteIdentifier($)}`);let m="";for(const $ of s.slice(1)){const E=o.quoteIdentifier($.alias),h=$.input.plan.groupBy.map(({name:k})=>k),N=($.input.joinKeys??l.filter(k=>h.includes(k))).map(k=>{const j=Ac($.input.groupKeyShifts,k),v=j?o.dateShift(`${E}.${o.quoteIdentifier(k)}`,j.granularity,j.offset):`${E}.${o.quoteIdentifier(k)}`;return`${d}.${o.quoteIdentifier(k)} = ${v}`});m+=` LEFT JOIN ${E} ON ${N.length>0?N.join(" AND "):"1 = 1"}`}const y=Object.fromEntries(s.map(({input:$,alias:E})=>[$.name,`${o.quoteIdentifier(E)}.${o.quoteIdentifier(ro($.plan))}`])),g=$c(e.expression,y),_=[...f,...r.rowIdentity.kind==="group"?[`${d}.${o.quoteIdentifier("_id")} AS ${o.quoteIdentifier("_id")}`]:[],...s.map(({input:$,alias:E})=>`${`${o.quoteIdentifier(E)}.${o.quoteIdentifier(ro($.plan))}`} AS ${o.quoteIdentifier($.name)}`),`${g} AS ${o.quoteIdentifier(n)}`].join(", ");let R=`WITH ${c} SELECT ${_} FROM ${d}`;return R+=m,{sql:R,parameters:s.flatMap(({sql:$})=>$.parameters)}},_c=e=>{if(typeof e!="string"||!/\bSELECT\b/i.test(e))return e;try{let t=e;const r=io(e).length*2+2;for(let n=0;n<r;n+=1){const o=Sc(t);if(o===t)return t;t=o}return t}catch{return e}},Sc=e=>{const t=io(e),r=Ic(e,t);if(r!==e)return r;const n=[];for(const i of t){const s=so(e,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?xc(e.slice(i.fromStart+4,i.close)):null;if(a){n.push({start:i.open,end:i.close+1,value:a});continue}if(!s||s.some(g=>g.trim()==="*"))continue;const c=kc(Rc(e.slice(i.fromStart,i.close),i,t)),u=Oc(e,i),d=bc(e,i);if(d&&Nc(u,d))continue;let l=s.filter(g=>{const _=ao(g);if(!_||_==="_id")return!0;const R=new RegExp(`(^|[^\\w$])${Rr(_)}([^\\w$]|$)`,"i");return R.test(c)||R.test(u)}),f=!0;for(;f;){f=!1;const g=po(l.join(" ")),_=s.filter(R=>{if(l.includes(R))return!1;const $=ao(R);return $?new RegExp(`(^|[^\\w$])${Rr($)}([^\\w$]|$)`,"i").test(g):!1});_.length>0&&(l=s.filter(R=>l.includes(R)||_.includes(R)),f=!0)}if(l.length===s.length)continue;const m=e.slice(i.selectEnd,i.fromStart),y=l.length===0&&Mc(e,i)&&!/(^|[^\w$])\*([^\w$]|$)/.test(u)&&!/^\s*(?:DISTINCT|ALL|TOP|SQL_)\b/i.test(m)&&!/\b(?:UNION|INTERSECT|EXCEPT)\b/i.test(c);l.length===0&&!y||n.push({start:i.selectEnd,end:i.fromStart,value:m.match(/^\s*/)[0]+(y?"1":l.map(g=>g.trim()).join(", "))+m.match(/\s*$/)[0]})}n.sort((i,s)=>s.start-i.start);let o=e;for(const i of n)o=o.slice(0,i.start)+i.value+o.slice(i.end);return o},Ic=(e,t)=>{const r=/^\s*SELECT\b/i.exec(e);if(!r)return e;const n=r.index+r[0].length,o=oo(e,"FROM",n);if(o===-1||!so(e,n,o)?.every(jc))return e;const s=t.find(f=>f.open>o&&e.slice(o+4,f.open).trim().length===0);if(!s||!/^\s*1\s*$/.test(e.slice(s.selectEnd,s.fromStart)))return e;const a=t.filter(f=>f.open>s.fromStart&&f.close<s.close).sort((f,m)=>m.close-m.open-(f.close-f.open))[0];if(!a||e.slice(s.fromStart+4,a.open).trim().length>0)return e;const c=e.slice(a.close+1,s.close);if(/\b(?:GROUP|HAVING|ORDER|LIMIT|OFFSET|UNION|INTERSECT|EXCEPT)\b/i.test(c))return e;const u=qc.exec(c)?.[1],d=Uc.exec(e.slice(s.close+1));if(!u||!d||co(u)!==co(d[1]))return e;const l=/;(\s*)$/.exec(e)?.[0]??"";return e.slice(0,s.open)+e.slice(a.open,s.close)+l},Rc=(e,t,r)=>Pc(e,r.filter(n=>n.open>t.open&&n.close<t.close).map(n=>({start:n.open-t.fromStart,end:n.close-t.fromStart+1}))),Oc=(e,t)=>{const r=e.slice(0,t.open)+" ".repeat(t.close-t.open+1)+e.slice(t.close+1);return po(r)},bc=(e,t)=>e.slice(t.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${Ae})(?=\\s|$)`,"i"))?.[1]??null,Nc=(e,t)=>new RegExp(`(^|[^\\w$])${Rr(t)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(e),Pc=(e,t)=>{if(!t.length)return e;const r=e.split("");for(const n of t)for(let o=Math.max(0,n.start);o<Math.min(r.length,n.end);o+=1)r[o]=" ";return r.join("")},oo=(e,t,r)=>{let n=0,o=0,i="",s="";for(let a=r;a<e.length;a+=1){const c=e[a],u=e[a+1];if(s==="--"){c===`
|
|
2
|
-
`&&(s="");continue}if(s==="/*"){
|
|
3
|
-
`&&(o="");continue}if(o==="/*"){s==="*"&&a==="/"&&(o="",i+=1);continue}if(n){s===n&&e[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=e.slice(c.open+1,i),d=/^\s*SELECT\b/i.exec(u);if(!d)continue;const l=c.open+1+d.index,f=oo(e,"FROM",l+6);f===-1||f>=i||t.push({open:c.open,close:i,selectEnd:l+6,fromStart:f})}return t},so=(e,t,r)=>{const n=e.slice(t,r),o=[];let i=0,s=0,a=0,c="";for(let u=0;u<n.length;u+=1){const d=n[u];if(c){d===c&&n[u-1]!=="\\"&&(c="");continue}if(d==="`"||d==='"'||d==="'"){c=d;continue}d==="("?s+=1:d===")"?s-=1:d==="["?a+=1:d==="]"?a-=1:d===","&&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)},ao=e=>e.trim().match(/\bAS\s+(`[^`]+`|"[^"]+"|[A-Za-z_][\w$]*)\s*$/i)?.[1]?.replace(/^`|`$/g,"").replace(/^"|"$/g,"")??null,Ae='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',Tc=new RegExp(`\\s+AS\\s+${Ae}\\s*$`,"i"),Lc=new RegExp(`\\bAS\\s+${Ae}`,"gi"),Dc=new RegExp(`(?:${Ae}\\s*\\.\\s*)+${Ae}`,"g"),Cc=new RegExp(`^${Ae}(?:\\s*\\.\\s*${Ae})*$`),qc=new RegExp(`^\\s*(?:AS\\s+)?(${Ae})\\s+WHERE\\b`,"i"),Uc=new RegExp(`^\\s*(?:AS\\s+)?(${Ae})\\s*;?\\s*$`,"i"),co=e=>e.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),jc=e=>{const t=e.replace(Tc,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(t)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(t)},uo=(e,t)=>e.replace(t,r=>" ".repeat(r.length)),po=e=>uo(e,Lc),kc=e=>uo(e,Dc),Mc=(e,t)=>/\b(?:FROM|JOIN)\s*$/i.test(e.slice(0,t.open)),xc=e=>{const t=e.trim();return Cc.test(t)?t:null},Rr=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Or=(e,t)=>{if(e.kind!=="operator")return!1;const r=t.get(e.operator);return!r.toSQL&&!!r.evaluate||(e.input?Or(e.input,t):!1)||(e.inputs?.some(n=>Or(n,t))??!1)},lo=(e,t,r,n)=>{if(e.kind!=="operator")return t[r];const o=n.get(e.operator),i=e.input?lo(e.input,t,r,n):t[r];return o.evaluate?Promise.resolve(i).then(s=>o.evaluate?.({input:s,args:e.args})):i},Tt=async(e,t,r)=>{const n=t.filter(({expression:o})=>Or(o,r));return n.length===0?[...e]:Promise.all(e.map(async o=>{const i={...o};for(const s of n)i[s.name]=await lo(s.expression,i,s.name,r);return i}))},br=e=>e==null?"\u7A7A\u503C":typeof e=="object"?"_id"in e?String(e._id):"id"in e?String(e.id):JSON.stringify(e):String(e),fo=(e,t,r="_",n="\u7A7A\u503C")=>t.map(o=>e[o]===null||e[o]===void 0?n:br(e[o])).join(r),mo=(e,t)=>e.map(r=>{if(t.kind==="property"){const{[t.internalName]:n,...o}=r;return{...o,_id:String(n)}}return t.kind==="group"?{...r,_id:r._id===void 0?fo(r,t.names,t.separator,t.nullLabel):br(r._id)}:{...r,_id:t.kind==="singleton"?"0":oi()}}),Vc=e=>{const t=Y(e);return delete t.having,delete t.sort,delete t.limit,delete t.page,t},st=(e,t)=>e.operator&&t.get(e.operator).kind==="component"?!0:!!e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&st(e.pred,t)||Array.isArray(e.pred)&&e.pred.some(r=>typeof r!="string"&&st(r,t)),Nr=(e,t,r,n,o,i,s="zh-CN",a=ht.translator(s))=>{const c=e.preds??[],u=c.map((m,y)=>({pred:m,index:y,definition:m.operator?n.get(m.operator):void 0})).filter(({pred:m,definition:y})=>y?.kind==="component"&&!(t.observationPeriods&&m.operator==="$periodValue"));if(u.length===0&&t.sourcePlan||u.length===0)return;for(const m of c)if((!m.operator||n.get(m.operator).kind!=="component")&&(m.pred&&typeof m.pred=="object"&&!Array.isArray(m.pred)&&st(m.pred,n)||Array.isArray(m.pred)&&m.pred.some(y=>typeof y!="string"&&st(y,n))))throw new p("UNSUPPORTED_COMPONENT_NESTING","A component operator must currently be the top-level projection operator");const d=[],l=c.filter((m,y)=>!u.some(g=>g.index===y));if(l.length>0){const m=Vc(e);m.preds=l,d.push({kind:"query",logicform:m})}const f=e.groupby?.length??0;for(const{pred:m,index:y,definition:g}of u){const _=g?.createComponent;if(!_)continue;const R=t.projections[f+y]?.name;if(!R)throw new p("INVALID_COMPONENT_PLAN","Component output projection is missing");const $=i?.preds?.[y],E=_({logicform:e,pred:$??m,outputName:R,locale:s,t:a,schema:r,resolveSchema:o,...i?{sourceLogicform:i}:{}});if("logicform"in E&&(E.logicform.preds??[]).some(h=>st(h,n)))throw new p("UNSUPPORTED_COMPONENT_NESTING","Nested component operators are not supported yet");d.push("components"in E?{...E,outputName:R}:E)}return d},$e=e=>e instanceof Date?e.getTime():e,vc=(e,t,r,n)=>{const o=$e(e),i=$e(r);switch(t){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=>$e(s)===o);case"$nin":return Array.isArray(r)&&r.every(s=>$e(s)!==o);case"$exists":return r?e!=null:e==null;case"$contains":return String(e).includes(String(r));case"$regex":return typeof r=="string"&&new RegExp(r,n).test(String(e));default:throw new p("UNSUPPORTED_QUERY_OPERATOR",`Unsupported having operator: ${t}`)}},yo=(e,t)=>{if(!t||typeof t!="object"||Array.isArray(t))return $e(e)===$e(t);const r=Object.entries(t),n=t.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=>yo(e,c));return i==="$and"?a.every(Boolean):a.some(Boolean)}return vc(e,i,s,typeof o=="string"?o:void 0)})},ho=(e,t)=>Object.entries(t).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>ho(e,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return yo(e[r],n)}),go=(e,t)=>t.length===0?"0":e._id===void 0?fo(e,t):br(e._id),$o=(e,t)=>{const r=new Map;for(const n of e)for(const o of n){const i=go(o,t);r.set(i,{...r.get(i)??{},...o})}return[...r.values()]},Bc=(e,t)=>{const r=t.groupBy.map(({name:o})=>o);let n=$o(e,r);if(t.having&&(n=n.filter(o=>ho(o,t.having))),t.groupLimit){const o=t.groupLimit,i=new Map;for(const s of n){const a=go(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 d=$e(a[u.name]),l=$e(c[u.name]);if(d!==l)return d==null?u.direction==="ASC"?-1:1:l==null?u.direction==="ASC"?1:-1:(d<l?-1:1)*(u.direction==="ASC"?1:-1)}return 0}).slice(0,o.count))}if(t.orderBy.length>0&&n.sort((o,i)=>{for(const s of t.orderBy){const a=$e(o[s.name]),c=$e(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}),t.pagination?.kind==="rows"){const o=(t.pagination.page-1)*t.pagination.pageSize;n=n.slice(o,o+t.pagination.pageSize)}else if(t.pagination?.kind==="ratio"){const o=Math.ceil(n.length*t.pagination.ratio),i=(t.pagination.page-1)*o;n=n.slice(i,i+o)}return n},wo=(e,t,r)=>{if(!e.schema||e.schema===t.id)return t;const n=r.resolveSchema?.(e.schema);if(!n)throw new p("SCHEMA_RESOLVER_REQUIRED",`Cannot normalize nested LogicForm schema without a schema resolver: ${e.schema}`,{schemaId:e.schema});return n},Lt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fc={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},Ve=(e,t)=>{if(e===null)return t?"null":"\u7A7A\u503C";if(typeof e=="string"||typeof e=="number")return String(e);if(typeof e=="boolean")return t?String(e):e?"\u662F":"\u5426";if(Array.isArray(e))return e.map(n=>Ve(n,t)).join(t?", ":"\u3001");if(!Lt(e))return t?"the specified condition":"\u6307\u5B9A\u6761\u4EF6";if(Array.isArray(e.roots))return e.roots.map(n=>Ve(n,t)).join(t?", ":"\u3001");if(e.root!==void 0)return Ve(e.root,t);const r=["year","quarter","month","week","day","hour","minute","second"].filter(n=>e[n]!==void 0).map(n=>t?`${n} ${String(e[n])}`:`${String(e[n])}${Fc[n]??""}`);return r.length>0?r.join(t?", ":""):t?"the specified condition":"\u6307\u5B9A\u6761\u4EF6"},Dt=(e,t,r)=>e.filter(Boolean).join(r?t==="$and"?" and ":" or ":t==="$and"?"\u4E14":"\u6216"),Ao=(e,t,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",$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",$regex:"\u5339\u914D",$recursive:"\u5C5E\u4E8E"})[e];if(!s)return;const a=e==="$in"?n?"":"\u4E4B\u4E00":e==="$nin"?n?"":"\u4E2D\u7684\u4EFB\u4E00\u9879":e==="$recursive"?n?" or a descendant":"\u53CA\u5176\u4E0B\u7EA7":"";return n?`${t} ${s} ${r}${a}`:`${t}${s}${r}${a}`},Eo=(e,t,r)=>{if(!Lt(t)||Object.keys(t).every(o=>!o.startsWith("$")))return Ao("$eq",e,Ve(t,r),r)??"";const n=[];for(const[o,i]of Object.entries(t))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Dt(i.map(s=>Eo(e,s,r)),o,r));else if(o==="$exists")n.push(r?`${e} ${i?"exists":"does not exist"}`:`${i?"\u6709":"\u65E0"}${e}`);else if(o!=="args"){const s=o==="$regex"&&Lt(i)?Ve(i.pattern,r):Ve(i,r),a=Ao(o,e,s,r);a&&n.push(a)}return Dt(n,"$and",r)},_o=(e,t="zh-CN")=>{const r=t.toLowerCase().startsWith("en"),n=[];for(const[o,i]of Object.entries(e))(o==="$and"||o==="$or")&&Array.isArray(i)?n.push(Dt(i.map(s=>Lt(s)?_o(s,t):""),o,r)):i!==void 0&&n.push(Eo(o,i,r));return Dt(n,"$and",r)},Yc=(e,t,r,n)=>e==="$count"&&!t?"operator.$count.rows":["$add","$multiply","$concat"].includes(e)&&r.length===0?`operator.${e}.empty`:["$subtract","$divide"].includes(e)&&r.length<2?`operator.${e}.fallback`:e==="$periodBoundary"||e==="$periodValue"?`operator.${e}.${n.boundary==="start"?"start":"end"}`:`operator.${e}`,ve=(e,t,r={})=>{if(e.name!==void 0){if(typeof e.name!="string"||e.name.length===0)throw new p("INVALID_PRED_NAME","PredItem name must be a non-empty string");return e.name}const n=r.locale??"zh-CN",o=r.localeRegistry??ht,i=o.resolve(n).locale.toLowerCase().startsWith("en"),s=o.translator(n),a=Array.isArray(e.pred)?e.pred.map(m=>typeof m=="string"?m:ve(m,t,r)):[],c=typeof e.pred=="string"?e.pred:e.pred&&!Array.isArray(e.pred)?ve(e.pred,t,r):void 0,u=c??(a.length>0?a.join(i?", ":"\u3001"):s("operator.rows",i?"rows":"\u6570\u636E\u884C")),d=e.args??{},l=e.operator?(()=>{const m=t.get(e.operator).defaultName({operandName:u,...c?{inputName:c}:{},inputNames:a,args:d,locale:n,t:s});if(typeof m!="string"||m.length===0)throw new p("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${e.operator}`,{operator:e.operator});const y=typeof d.granularity=="string"?s(`time.granularity.${d.granularity}`,d.granularity):s("time.granularity.period","\u5468\u671F"),g=i?e.operator==="$concat"?" and ":e.operator==="$multiply"?" times ":" plus ":e.operator==="$concat"?"\u4E0E":e.operator==="$multiply"?"\u4E58\u4EE5":"\u52A0";return["$periodShift","$periodGrowth","$periodDifference"].includes(e.operator)?m:s(Yc(e.operator,!!c||a.length>0,a,d),m,{...d,operandName:u,inputName:c??"",inputNames:a.join(g),input0:a[0]??"",input1:a[1]??"",granularity:y,level:typeof d.level=="string"?d.level:"",levelSuffix:typeof d.level=="string"&&d.level.length>0?` ${d.level}`:""})})():u;if(typeof l!="string"||l.length===0)throw new p("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${e.operator}`,{operator:e.operator});if(!e.query)return l;const f=_o(e.query,n);return f?i?`${l} where ${f}`:`${f}\u7684${l}`:l};class So{#e=new Map;constructor(t=[]){for(const r of t)this.register(r)}register(t){if(!t.name)throw new p("INVALID_SEMANTIC_TYPE","Semantic type name must not be empty");if(this.#e.has(t.name))throw new p("SEMANTIC_TYPE_ALREADY_REGISTERED",`Semantic type is already registered: ${t.name}`,{type:t.name});return this.#e.set(t.name,t),this}get(t){const r=this.#e.get(t);if(!r)throw new p("SEMANTIC_TYPE_NOT_FOUND",`Semantic type is not registered: ${t}`,{type:t});return r}requiresPerPeriodEvaluation(t){return t.property?this.get(t.property.type).requiresPerPeriodEvaluation?.({...t,property:t.property})??!1:!1}}const Qc=e=>{const t=new Set,r=new Set;for(const n of e){if(!n.name)throw new p("INVALID_PROPERTY_NAME","Property name must not be empty");if(!n.id)throw new p("INVALID_PROPERTY_ID",`Property ${n.name} physical id must not be empty`);if(t.has(n.name))throw new p("DUPLICATE_PROPERTY_NAME",`Duplicate property name: ${n.name}`,{property:n.name});if(r.has(n.id))throw new p("DUPLICATE_PROPERTY_ID",`Duplicate property physical id: ${n.id}`,{propertyId:n.id});t.add(n.name),r.add(n.id)}},Io=(e,t={})=>{Qc(e);const r=e.filter(({type:n})=>n==="timestamp");if(r.length>1)throw new p("MULTIPLE_TIMESTAMP_PROPERTIES","A Schema can declare at most one timestamp Property",{properties:r.map(({name:n})=>n)});if(t.temporalSemantics==="snapshot"&&r.length===0)throw new p("SNAPSHOT_TIMESTAMP_REQUIRED","A snapshot Schema must declare exactly one timestamp Property",{schemaId:t.schemaId})},Hc=new Set(["second","minute","hour","day","week","month","quarter","year"]),Ro=(e,t)=>{if(e===void 0)return;if(typeof e!="object"||e===null||Array.isArray(e))throw new p("INVALID_TIME_WATERMARK",`${t} timeWatermark must be an object`);const r=e,n=Object.keys(r);if(!(r.type==="database_latest"&&n.length===1)&&!(r.type==="now_offset"&&n.every(o=>o==="type"||o==="offset")&&Number.isInteger(r.offset)))throw new p("INVALID_TIME_WATERMARK",`${t} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:t,timeWatermark:e})},Gc=(e,t)=>{if(Ro(e.timeWatermark,`Property ${e.name}`),"_id"in e||"_sid"in e)throw new p("LEGACY_PROPERTY_ID_NOT_ALLOWED",`Property ${e.name} must use id instead of _id; _sid is not supported`,{property:e.name});if("sid"in e)throw new p("PROPERTY_SID_NOT_ALLOWED",`Property ${e.name} must not declare sid`,{property:e.name});const r=e;if(r.is_comparable!==void 0||r.comparable_order!==void 0)throw new p("LEGACY_COMPARABLE_NOT_ALLOWED",`Property ${e.name} must use comparable instead of is_comparable/comparable_order`,{property:e.name});if(e.udf!==void 0){const a=e.udf;if(typeof a!="object"||a===null||Array.isArray(a))throw new p("INVALID_PROPERTY_UDF",`Property ${e.name} udf must be an object containing only sql`,{property:e.name});const c=a,u=Object.keys(c).filter(d=>d!=="sql");if(u.length>0)throw new p("UNSUPPORTED_PROPERTY_UDF",`Property ${e.name} udf only supports sql`,{property:e.name,unsupportedKeys:u});if(typeof c.sql!="string"||c.sql.trim().length===0)throw new p("INVALID_PROPERTY_UDF",`Property ${e.name} udf.sql must be a non-empty string`,{property:e.name})}const n=t.get(e.type),o=e.primal_type==="object"?"entity":e.primal_type;if(o!==void 0&&o!==n.primalType)throw new p("PRIMAL_TYPE_MISMATCH",`Property ${e.name} declares primal_type ${e.primal_type}, but ${e.type} requires ${n.primalType}`,{property:e.name,type:e.type,declared:e.primal_type,expected:n.primalType});if(e.isArray!==void 0&&typeof e.isArray!="boolean")throw new p("INVALID_IS_ARRAY",`Property ${e.name} isArray must be a boolean`,{property:e.name,isArray:e.isArray});if(e.level!==void 0&&(typeof e.level!="string"||e.level.trim().length===0))throw new p("INVALID_PROPERTY_LEVEL",`Property ${e.name} level must be a non-empty string`,{property:e.name,level:e.level});if("is_observation"in e)throw new p("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED",`Property ${e.name} must use Schema temporalSemantics; is_observation is not supported`,{property:e.name});if(e.comparable!==void 0){const a=e.comparable;if(typeof a!="object"||a===null||Array.isArray(a))throw new p("INVALID_COMPARABLE_CATEGORY",`Property ${e.name} comparable must contain values and direction`);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 p("INVALID_COMPARABLE_CATEGORY",`Property ${e.name} comparable requires unique string values and direction 1 or -1`,{property:e.name,comparable:a});if(e.type!=="category"||e.isArray===!0)throw new p("COMPARABLE_CATEGORY_REQUIRED",`Property ${e.name} comparable is only supported by scalar category properties`,{property:e.name,type:e.type})}const i={...e,id:e.id??e.name,primal_type:n.primalType,isArray:e.isArray??!1,is_dynamic:e.udf?.sql!==void 0,...n.primalType==="date"?{granularity:e.granularity??"day"}:{}};if(i.timeWatermark&&i.primal_type!=="date")throw new p("TIME_WATERMARK_DATE_PROPERTY_REQUIRED",`Property ${i.name} timeWatermark is only supported by date Properties`,{property:i.name});if(n.primalType==="entity"||n.primalType==="object"){if(typeof i.ref!="string"||i.ref.length===0)throw new p("PROPERTY_REF_REQUIRED",`Entity property ${i.name} must declare ref`,{property:i.name,type:i.type})}else if(i.ref!==void 0)throw new p("PROPERTY_REF_NOT_ALLOWED",`Property ${i.name} cannot declare ref unless its primal_type is entity`,{property:i.name,type:i.type});if(i.level!==void 0&&i.primal_type!=="entity"&&i.primal_type!=="object")throw new p("PROPERTY_LEVEL_REQUIRES_ENTITY",`Property ${i.name} level requires an entity relation`,{property:i.name,type:i.type});if(n.primalType==="date"||e.type==="duration"){if(i.granularity!==void 0&&!Hc.has(i.granularity))throw new p("INVALID_GRANULARITY",`Property ${i.name} has unsupported granularity: ${i.granularity}`,{property:i.name,granularity:i.granularity})}else if(i.granularity!==void 0)throw new p("GRANULARITY_NOT_ALLOWED",`Property ${i.name} cannot declare granularity unless its type supports it`,{property:i.name,type:i.type});return n.validateProperty?.(i),i},Wc=e=>{const t=(o,i,s)=>{if(i===void 0)return;if(typeof i!="string"||i.length===0)throw new p("INVALID_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy.${s} must be a non-empty Property name or id`,{property:o.name,direction:s,reference:i});const a=e.find(c=>c.id===i)??e.find(c=>c.name===i);if(!a)throw new p("PROPERTY_HIERARCHY_TARGET_NOT_FOUND",`Property ${o.name} hierarchy.${s} does not exist: ${i}`,{property:o.name,direction:s,reference:i});if(a===o)throw new p("PROPERTY_HIERARCHY_CYCLE",`Property ${o.name} cannot point to itself in hierarchy.${s}`,{property:o.name,direction:s});return a.name},r=e.map(o=>{if(o.hierarchy===void 0)return o;const i=o.hierarchy;if(typeof i!="object"||i===null||Array.isArray(i))throw new p("INVALID_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy must be an object containing up and/or down`,{property:o.name,hierarchy:i});const s=i,a=Object.keys(s).filter(d=>d!=="up"&&d!=="down");if(a.length>0)throw new p("UNSUPPORTED_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy only supports up and down`,{property:o.name,unsupported:a});const c=t(o,s.up,"up"),u=t(o,s.down,"down");return{...o,hierarchy:{...c?{up:c}:{},...u?{down:u}:{}}}}),n=new Map(r.map(o=>[o.name,o]));for(const o of r)for(const i of["up","down"]){const s=new Set;let a=o;for(;a?.hierarchy?.[i];){if(s.has(a.name))throw new p("PROPERTY_HIERARCHY_CYCLE",`Property hierarchy.${i} contains a cycle at ${a.name}`,{property:o.name,direction:i,cycleAt:a.name});s.add(a.name),a=n.get(a.hierarchy[i])}}return r},Oo=(e,t,r=[])=>{Ro(e.timeWatermark,`Schema ${e.id}`);const n=wt(r);if("_id"in e||"_sid"in e)throw new p("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported");if("sid"in e)throw new p("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid");if("is_snapshot"in e||"is_observation"in e)throw new p("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED","Schema must use temporalSemantics instead of is_snapshot/is_observation",{schemaId:e.id});const o=e.temporalSemantics??"normal";if(o!=="normal"&&o!=="snapshot")throw new p("INVALID_TEMPORAL_SEMANTICS","Schema temporalSemantics must be normal or snapshot",{schemaId:e.id,temporalSemantics:o});const i=o;if(!e.id)throw new p("INVALID_SCHEMA_ID","Schema id must not be empty");let s=e.properties.map(g=>Gc(g,t));s=Wc(s);const a=s.filter(({type:g})=>g==="ID"),c=s.filter(({type:g})=>g==="start_date"),u=s.filter(({type:g})=>g==="end_date");if(e.type==="entity"&&!s.some(({type:g})=>g==="timestamp")&&e.temporalSemantics!=="snapshot"&&a.length===1&&c.length===1&&u.length===1&&!s.some(({name:g})=>g==="\u65E5\u671F")){const g=c[0];g&&(s=[...s,{id:"__chatbi__timestamp__placeholder__",name:"\u65E5\u671F",type:"timestamp",primal_type:"date",isArray:!1,is_dynamic:!0,is_supplementary:!0,udf:{sql:g.id}}])}Io(s,{temporalSemantics:i,schemaId:e.id});const d=n.flatMap(g=>g.schemaMetadata?[g.schemaMetadata]:[]);let l={};for(const g of d)l={...l,...g.resolve(e,s)};const f=e.parentProperty===void 0?void 0:s.find(({id:g,name:_})=>g===e.parentProperty||_===e.parentProperty);if(e.parentProperty!==void 0&&!f)throw new p("RECURSIVE_PARENT_PROPERTY_REQUIRED",`Schema parentProperty does not exist: ${e.parentProperty}`,{schemaId:e.id,property:e.parentProperty});const m=new Set(n.flatMap(g=>[...g.schemaMetadata?.keys??[],...g.legacySchemaKeys??[]]));return{...Object.fromEntries(Object.entries(e).filter(([g])=>g!=="parentProperty"&&!m.has(g))),temporalSemantics:i,properties:s,...l,...f?{parentProperty:f.name}:{}}};J.extend(ii),J.extend(dt),J.extend(pt);const zc="YYYY-MM-DD HH:mm:ss",Kc=new Set(["YTD","QTD","MTD","WTD","DTD"]),Jc=new Set(["$eq","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),Ct=["second","minute","hour","day","week","month","quarter","year"],Be=e=>Object.prototype.toString.call(e)==="[object Object]",Pr=e=>!Be(e)||"$gte"in e||"$gt"in e||"$lte"in e||"$lt"in e||"$or"in e||"$ne"in e?!1:typeof e.granularity=="string"&&Ct.includes(e.granularity)&&typeof e.offset=="number"||Ct.some(t=>t in e),Fe=e=>J(e).format(zc),Zc=(e,t)=>Ct.find(r=>r in e||t!==void 0),Xc=(e,t,r)=>t==="month"?e.month(r-1):t==="day"?e.date(r):t==="week"?e.isoWeek(r):t==="quarter"?e.quarter(r):e.set(t,r),bo=(e,t)=>{const r=typeof e.granularity=="string"?e.granularity:void 0,n=r?{[r]:e.offset}:void 0,o=r??Zc(e,void 0)??"day";let i=J(t).millisecond(0);for(const a of[...Ct].reverse()){const c=e[a];typeof c=="number"&&(i=Xc(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:Fe(i.startOf(s)),$lte:Fe(i.endOf(s))}},eu=(e,t)=>{const r=J(t),o={DTD:()=>r.startOf("day"),WTD:()=>r.startOf("isoWeek"),MTD:()=>r.startOf("month"),QTD:()=>r.startOf("quarter"),YTD:()=>r.startOf("year")}[e];return{$gte:Fe(o()),$lte:Fe(r.endOf("day"))}},Tr=async(e,t)=>{const r=J(String(e.$lte)),n=await t.requestTimeWatermark(r.toDate());if(!n)return e;const o=t.property.granularity??"day",i=o==="week"?"isoWeek":o,s=J(n).endOf(i),a=J(String(e.$gte));if(a.isValid()&&s.isBefore(a))return e;const c=s.isBefore(r)?s:r;return{...e,$lte:Fe(c)}},Lr=async(e,t)=>ye(e)?e:e instanceof Date||typeof e=="string"&&J(e).isValid()?Fe(e):typeof e=="string"&&Kc.has(e)?Tr(eu(e,t.now),t):Pr(e)?Tr(bo(e,t.now),t):e,No=async(e,t,r)=>{if(e==="$and"||e==="$or")return Array.isArray(t)?Promise.all(t.map(o=>qt(o,r))):t;if(Array.isArray(t))return Promise.all(t.map(o=>Lr(o,r)));const n=await Lr(t,r);return e==="$eq"&&Be(n)&&"$gte"in n&&"$lte"in n?n:e==="$gte"||e==="$gt"?Be(n)&&"$gte"in n?n.$gte:n:(e==="$lte"||e==="$lt")&&Be(n)&&"$lte"in n?n.$lte:n},qt=async(e,t)=>{if(ye(e))return e;if(Array.isArray(e))return Promise.all(e.map(o=>qt(o,t)));if(!Be(e))return Lr(e,t);if("$options"in e)throw new p("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");if("$offset"in e)throw new p("UNSUPPORTED_DATE_VALUE","The legacy {$offset: ...} date form is not supported; use { granularity, offset }");if(("granularity"in e||"offset"in e)&&(!Pr(e)||!Number.isInteger(e.offset)))throw new p("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(Pr(e))return Tr(bo(e,t.now),t);const r=Object.entries(e);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await No("$eq",r[0][1],t);if(Be(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)n[o]=Jc.has(o)?await No(o,i,t):await qt(i,t);return n},tu=(e,t)=>t.property.primal_type==="date"?qt(e,t):e,Po=()=>new So(yr),ru=/^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,nu=e=>{if(typeof e!="string")return!1;const t=ru.exec(e);if(!t)return!1;const r=Number(t[1]),n=Number(t[2]),o=Number(t[3]??0);return r!==2?r>2:n>0||o>0?!0:t[4]===void 0},Dr=e=>{if(!nu(e.version))throw new p("UNSUPPORTED_LOGICFORM_VERSION",`This library only supports LogicForm version 2.0 or later; received ${JSON.stringify(e.version)}`,{minimumVersion:"2.0",receivedVersion:e.version})},To=(e,t)=>Object.entries(e).some(([r,n])=>t.has(r)?!0:r!=="$and"&&r!=="$or"||!Array.isArray(n)?!1:n.some(o=>typeof o=="object"&&o!==null&&!Array.isArray(o)&&To(o,t))),Lo=(e,t,r,n=[])=>{if(t===void 0||t==="placeholder")return e;if(!er(t))throw new p("INVALID_ENTITY_ID","entity_id must be a non-empty string or a safe integer");const o=tr(r,n);return e&&To(e,new Set([o.name,o.id]))?e:{[o.name]:t,...e??{}}},ou=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.schema=="string"&&typeof e.query=="object"&&e.query!==null&&!Array.isArray(e.query),iu=e=>{if(!ye(e))return!1;const t=e;return t.groupby!==void 0||t.preds!==void 0||t.from!==void 0||t.having!==void 0||t.sort!==void 0||t.limit!==void 0||t.limitBy!==void 0||t.page!==void 0},Cr=async(e,t)=>{if(ye(e)){if(!t.normalizeNestedLogicform)throw new p("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");return t.normalizeNestedLogicform(e)}return Array.isArray(e)?Promise.all(e.map(r=>Cr(r,t))):typeof e!="object"||e===null||e instanceof Date?e:Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,n])=>[r,await Cr(n,t)])))},Do=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>Do(o,t))]:[`${t}_${r}`,n])),su=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return e;const t=Object.entries(e),[r]=t;return t.length===1&&r?.[0]==="$eq"?r[1]:e},Co=async(e,t,r,n)=>{const o=u=>{if(Array.isArray(u)){u.forEach(o);return}if(typeof u!="object"||u===null||ye(u))return;const d=u;if("$options"in d)throw new p("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");Object.values(d).forEach(o)};o(e);const i=n.semanticTypes.get(r.type),s={schema:t,property:r,now:n.now??new Date,requestTimeWatermark:u=>n.requestTimeWatermark?.(t,r,u)??Promise.resolve(void 0)},a=await tu(Y(e),s),c=i.normalizeQuery?i.normalizeQuery(a,s):a;if(r.comparable){const u=new Set(r.comparable.values),d=(l,f)=>{if(!(ye(l)||l===null)){if(Array.isArray(l)){l.forEach(m=>d(m,f));return}if(typeof l=="object"){Object.entries(l).forEach(([m,y])=>{["args","$exists","$regex","$contains"].includes(m)||d(y,m)});return}if(!(f&&["args","$exists","$regex","$contains"].includes(f))&&(typeof l!="string"||!u.has(l)))throw new p("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${r.name} does not contain value: ${JSON.stringify(l)}`,{property:r.name,value:l})}};d(c)}return c},au=async(e,t,r,n)=>{const o=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{root:e},i=typeof o.schema=="string"?o.schema:r.ref??t.id,s=i===t.id?t:n.resolveSchema?.(i);if(!s)throw new p("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${i}`);const a=o.idProperty??o.id_property,c=s.properties.filter(({type:y})=>y==="ID"),u=a===void 0?c.length===1?c[0]:void 0:s.properties.find(({id:y,name:g})=>y===a||g===a);if(!u||a===void 0&&c.length!==1)throw new p("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive Schema ${i} must have exactly one ID property or idProperty`);const d=Array.isArray(o.roots),l=d?o.roots:o.root===void 0?[]:[o.root];if(!d&&l.length===0||l.some(y=>y===void 0))throw new p("RECURSIVE_ROOT_REQUIRED","$recursive requires root or roots");const f=await Promise.all(l.map(y=>Co(y,s,u,n))),m=o.parentProperty??o.parent_property??s.parentProperty??"pid";if(typeof m!="string"||m.length===0)throw new p("RECURSIVE_PARENT_PROPERTY_REQUIRED","$recursive parentProperty must be a string");if(o.includeSelf!==void 0&&typeof o.includeSelf!="boolean"||o.include_self!==void 0&&typeof o.include_self!="boolean")throw new p("INVALID_RECURSIVE_QUERY","$recursive includeSelf must be boolean");return{schema:i,roots:f,includeSelf:o.includeSelf??o.include_self??!0,idProperty:u.name,parentProperty:m}},qr=async(e,t,r)=>{const n={};for(const[o,i]of Object.entries(e)){if(o==="$and"||o==="$or"){if(!Array.isArray(i))throw new p("INVALID_QUERY_VALUE",`${o} requires an array`);n[o]=await Promise.all(i.map(async u=>{if(typeof u!="object"||u===null||Array.isArray(u))throw new p("INVALID_QUERY_VALUE",`${o} items must be query objects`);return qr(u,t,r)}));continue}const s=z(t,o,r.resolveSchema);if(iu(i)&&(s.property.primal_type==="entity"||s.property.primal_type==="object")&&s.property.ref){if(i.schema!==s.property.ref)throw new p("RELATION_SCHEMA_MISMATCH",`Relation ${s.canonicalName} references ${s.property.ref}, not ${i.schema??"undefined"}`);if(!r.normalizeNestedLogicform)throw new p("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");const u=await r.normalizeNestedLogicform(i);n[s.canonicalName]={$in:u};continue}if(ou(i)){if(i.version!==void 0&&Dr(i),s.property.primal_type!=="entity"&&s.property.primal_type!=="object")throw new p("INVALID_RELATION_QUERY",`Relation query ${o} must resolve to an entity property`);if(!s.property.ref)throw new p("INVALID_RELATION_QUERY",`Nested LogicForm query requires an object property: ${s.canonicalName}`);if(i.schema!==s.property.ref)throw new p("RELATION_SCHEMA_MISMATCH",`Relation ${s.canonicalName} references ${s.property.ref}, not ${i.schema}`);const u=r.resolveSchema?.(i.schema);if(!u)throw new p("SCHEMA_RESOLVER_REQUIRED",`Nested relation query requires Schema ${i.schema}`);const d=Lo(i.query,i.entity_id,u,r.plugins),l=await qr(d,u,r);Object.assign(n,Do(l,s.canonicalName));continue}if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.prototype.hasOwnProperty.call(i,"$recursive")){const u=i;if(Object.keys(u).filter(l=>l!=="$recursive").length>0)throw new p("INVALID_RECURSIVE_QUERY","$recursive cannot be combined with other field operators");n[s.canonicalName]={$recursive:await au(u.$recursive,s.schema,s.property,r)};continue}const a=await Cr(i,r),c=await Co(a,s.schema,s.property,r);n[s.canonicalName]=su(c)}return n},qo=async(e,t,r)=>{if(!e)return;const n=await qr(e,t,r);return Object.keys(n).length===0?void 0:n},cu=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},uu=e=>{if(e.args===void 0||Object.keys(e.args).length>0)return e;const{args:t,...r}=e;return r},Ut=async(e,t,r)=>{if("components"in e)throw new p("PRED_COMPONENTS_NOT_ALLOWED","PredItem components is not supported; use a pred array for multiple inputs");const n=r.operators,o={...r.locale?{locale:r.locale}:{},...r.localeRegistry?{localeRegistry:r.localeRegistry}:{}};if(!n)throw new Error("Normalizer operator registry is not initialized");if(e.name!==void 0&&(typeof e.name!="string"||e.name.length===0))throw new p("INVALID_PRED_NAME","PredItem name must be a non-empty string");if(e.name==="_id")throw new p("RESERVED_OUTPUT_NAME","PredItem name _id is reserved for executor-owned row identity");if(e.args!==void 0&&!cu(e.args))throw new p("INVALID_OPERATOR_ARGS","Pred args must be a plain object");const i=e.schema===void 0||e.schema===t.id?t:r.resolveSchema?.(e.schema);if(!i)throw new p("SCHEMA_RESOLVER_REQUIRED",`Cross-Schema pred requires Schema ${e.schema}`);const s=await qo(e.query,i,r),a=Array.isArray(e.pred)?await Promise.all(e.pred.map(f=>Ut(typeof f=="string"?{pred:f}:f,i,r))):void 0,{query:c,...u}=e,d={...u,...s?{query:s}:{},...a?{pred:a}:{}},l=f=>{const m=f.operator?n.get(f.operator).normalizePred?.({pred:f,schema:i})??f:f;return uu(m)};if(typeof e.pred=="string"){const f=z(i,e.pred,r.resolveSchema),m={...d,pred:f.canonicalName};return l({...m,name:m.name??ve(m,n,o)})}if(e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)){const f={...d,pred:await Ut(e.pred,i,r)};return l({...f,name:f.name??ve(f,n,o)})}if(a)return l({...d,name:d.name??ve(d,n,o)});if(e.pred!==void 0)throw new p("UNSUPPORTED_PRED","A pred must be a property name or nested pred");return l({...d,name:d.name??ve(d,n,o)})},Uo=(e,t,r)=>Promise.all((e??[]).map(n=>Ut(n,t,r))),du=(e,t,r)=>Uo(e??[],t,r),Ye=(e,t)=>{throw new p("INVALID_PAGINATION",e,t)},pu=e=>{"skip"in e&&Ye("skip has been removed; use the 1-based page field",{skip:e.skip});const t=e.groupby?.length??0;e.limitBy!==void 0&&((!Number.isInteger(e.limitBy)||e.limitBy<=0)&&Ye("limitBy must be a positive integer",{limitBy:e.limitBy}),t<2&&(e.limit=e.limitBy,delete e.limitBy));const{limit:r,page:n}=e;if(r===void 0){n!==void 0&&Ye("page requires limit",{page:n});return}if((!Number.isFinite(r)||r<0&&r!==-1||r>1&&!Number.isInteger(r))&&Ye("limit must be -1, a non-negative integer, or a ratio between 0 and 1",{limit:r}),r===-1){n!==void 0&&Ye("page cannot be used with unlimited results",{limit:r,page:n}),delete e.limit;return}n!==void 0&&(!Number.isInteger(n)||n<1)&&Ye("page must be a positive integer starting from 1",{page:n}),e.page=n??1},lu=e=>e.property.name,jo=(e,t,r,n,o=new Set)=>{if(o.has(e.id))return;const i=new Set(o).add(e.id),s=e.properties.find(a=>a.id===t||a.name===t);if(s)return s.name;if(n==="timestamp"){const a=e.properties.find(c=>c.type==="timestamp");if(a)return a.name}for(const a of e.properties){if(!a.ref||a.primal_type!=="entity"&&a.primal_type!=="object")continue;const c=r?.(a.ref);if(!c)continue;const u=jo(c,t,r,n,i);if(u)return`${a.name}_${u}`}},ko=(e,t,r,n)=>{try{const o=z(e,t,n);return jo(r,lu(o),n,o.property.type)}catch{return}},fu=(e,t,r)=>{const n=[...new Set((e.preds??[]).map(s=>s.schema).filter(s=>!!(s&&s!==t.id)))];if(n.length===0)return e;const o={};for(const[s,a]of Object.entries(e.propertyResolve??{})){const c=r.resolveSchema?.(s),u={};for(const[d,l]of Object.entries(a))try{const f=z(t,d,r.resolveSchema),m=c?z(c,l,r.resolveSchema):void 0;u[f.canonicalName]=m?.canonicalName??l}catch{u[d]=l}o[s]=u}const i=[...(e.groupby??[]).map(s=>s.pred),...Object.keys(e.query??{}).filter(s=>s!=="$and"&&s!=="$or")];for(const s of i){if(typeof s!="string")continue;let a;try{a=z(t,s,r.resolveSchema)}catch{continue}for(const c of n){const u=r.resolveSchema?.(c),d=u&&ko(t,s,u,r.resolveSchema);d&&d!==a.canonicalName&&(o[c]={...o[c]??{},[a.canonicalName]:d})}}return Object.keys(o).length>0?{...e,propertyResolve:o}:e},mu=e=>{if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new p("INVALID_PROPERTY_RESOLVE","propertyResolve must be an object");for(const[t,r]of Object.entries(e)){if(typeof r!="object"||r===null||Array.isArray(r))throw new p("INVALID_PROPERTY_RESOLVE",`propertyResolve.${t} must be an object`);for(const[n,o]of Object.entries(r))if(typeof o!="string"||o.length===0)throw new p("INVALID_PROPERTY_RESOLVE",`propertyResolve.${t}.${n} must be a non-empty string`)}}},yu=async(e,t,r)=>{if(!e)return;const n=wo(e,t,r);return Qe(e,n,r)},Qe=async(e,t,r)=>{if(r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:yt(r.locales)},...r.operators?{}:{operators:Ie(r.plugins)}},Dr(e),mu(e.propertyResolve),e.output&&e.output.type!=="data"&&e.output.type!=="sql")throw new p("UNSUPPORTED_OUTPUT",`Output type is not supported: ${e.output.type}`);const o=Y(e),i={...r,normalizeNestedLogicform:async y=>{const g=wo(y,t,r);return Qe(y,g,r)}};pu(o);const s=await yu(o.from,t,i),a=s&&r.resolveFromSchema?r.resolveFromSchema(s,t):t,c=await qo(Lo(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;let d=await Uo(u,a,i),l=await du(o.groupby,a,i);const f=l.filter(y=>gn(y,l,a,r.resolveSchema));if(f.length>0){const y=new Set(f.map(({name:g})=>g));l=l.filter(({name:g})=>!y.has(g)),d=[...d,...f]}return o.preds=d,l.length>0?o.groupby=l:delete o.groupby,s?o.from=s:delete o.from,c?o.query=c:delete o.query,fu(o,a,i)},Ur=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Oe=(e,t)=>{if(e){if(!Ur(e,t))throw new p("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${t}`,{schemaId:t});return e[t]}},De=(e,t,r)=>{const n=Oe(e,t)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},He=(e,t,r)=>{if(!De(e,t.id,r))throw new p("COLUMN_PERMISSION_DENIED",`Property is not included in the column permissions: ${t.id}.${r.name}`,{schemaId:t.id,property:r.name,propertyId:r.id})},jr=(e,t,r,n)=>{const o=z(t,e,n);for(const i of o.relations)Oe(r,i.targetSchema.id),He(r,i.sourceSchema,i.property);He(r,o.schema,o.property)},Mo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.schema=="string"&&typeof e.query=="object"&&e.query!==null&&!Array.isArray(e.query),hu=(e,t,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||!Ur(e,"$recursive"))return;const o=e.$recursive,i=typeof o=="object"&&o!==null&&!Array.isArray(o)?o:{},s=typeof i.schema=="string"?i.schema:t.property.ref??t.schema.id,a=n(s);if(Oe(r,s)?.rowPermissions!==void 0)throw new p("RECURSIVE_ROW_PERMISSION_UNSUPPORTED",`$recursive cannot safely apply row permissions for Schema ${s}`,{schemaId:s});const u=i.idProperty??i.id_property,d=u===void 0?a.properties.find(({type:m})=>m==="ID"):a.properties.find(({id:m,name:y})=>m===u||y===u),l=i.parentProperty??i.parent_property??a.parentProperty??"pid",f=a.properties.find(({id:m,name:y})=>m===l||y===l);d&&He(r,a,d),f&&He(r,a,f)},kr=(e,t,r,n)=>{if(ye(e)){Mt(e,t,r,n);return}if(Array.isArray(e)){for(const o of e)kr(o,t,r,n);return}if(!(typeof e!="object"||e===null||e instanceof Date))for(const o of Object.values(e))kr(o,t,r,n)},jt=(e,t,r,n,o)=>{if(e)for(const[i,s]of Object.entries(e)){if(i==="$and"||i==="$or"){if(Array.isArray(s))for(const c of s)jt(c,t,r,n,o);continue}const a=z(t,i,n);if(jr(i,t,r,n),hu(s,a,r,n),Mo(s)){if(a.property.ref!==s.schema)continue;const c=n(s.schema);Oe(r,c.id),er(s.entity_id)&&He(r,c,tr(c,o)),jt(s.query,c,r,n,o);continue}kr(s,r,n,o)}},kt=(e,t,r,n,o)=>{const i=e.schema?n(e.schema):t;e.schema&&Oe(r,e.schema),typeof e.pred=="string"?jr(e.pred,i,r,n):e.pred&&!Array.isArray(e.pred)&&kt(e.pred,i,r,n,o);for(const s of Array.isArray(e.pred)?e.pred:[])typeof s=="string"?jr(s,i,r,n):kt(s,i,r,n,o);jt(e.query,i,r,n,o)},Mt=(e,t,r,n=[])=>{if(!e.schema){if(e.from){Mt(e.from,t,r,n);return}throw new p("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const o=r(e.schema);if(Oe(t,o.id),er(e.entity_id)&&He(t,o,tr(o,n)),e.from){Mt(e.from,t,r,n);return}jt(e.query,o,t,r,n);for(const i of e.preds??[])kt(i,o,t,r,n);for(const i of e.groupby??[])kt(i,o,t,r,n)},xt=(e,t)=>{if(Array.isArray(e))return e.map(o=>xt(o,t));if(typeof e!="object"||e===null||e instanceof Date)return e;const r=Object.entries(e).map(([o,i])=>[o,xt(i,t)]),n=Object.fromEntries(r);return Mo(e)&&!Ur(e,"version")&&(n.version=t),n},gu=(e,t,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 d of u)o(d,a);else c.startsWith("$")||n.push(z(a,c,r))},i=(s,a)=>{const c=s.schema?r(s.schema):a;typeof s.pred=="string"?n.push(z(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(z(c,u,r)):i(u,c);o(s.query,c)};o(e.query,t);for(const s of e.preds??[])i(s,t);for(const s of e.groupby??[])i(s,t);return n},$u=(e,t,r)=>{if(!e.schema)return[];const n=r(e.schema),o=new Set,i=[];for(const s of gu(e,n,r)){if(s.relations.length===0)continue;let a=-1;if(s.relations.forEach(({targetSchema:l},f)=>{t[l.id]?.rowPermissions!==void 0&&(a=f)}),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 d={};for(const l of[...c].reverse())d={[l.property.name]:{schema:l.targetSchema.id,query:d}};i.push(d)}return i},Ge=(e,t,r,n,o,i)=>ye(e)?Ce(e,t,r,n,o,i):Array.isArray(e)?e.map(s=>Ge(s,t,r,n,o,i)):typeof e!="object"||e===null||e instanceof Date?e:Object.fromEntries(Object.entries(e).map(([s,a])=>[s,Ge(a,t,r,n,o,i)])),Mr=(e,t,r,n,o,i)=>({...e,...e.query?{query:Ge(e.query,t,r,n,o,i)}:{},...e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)?{pred:Mr(e.pred,t,r,n,o,i)}:{},...Array.isArray(e.pred)?{pred:e.pred.map(s=>typeof s=="string"?s:Mr(s,t,r,n,o,i))}:{}}),Ce=(e,t,r,n=!0,o=new Set,i=[])=>{if(!t)return Y(e);if(!e.schema){const m=Y(e);return m.from&&(m.from=Ce(m.from,t,r,n,new Set,i)),m}n&&Mt(e,t,r,i);const s=Oe(t,e.schema),a=o.has(e.schema),c=new Set(o).add(e.schema),u=Y(e);u.query&&(u.query=Ge(u.query,t,r,n,new Set,i)),u.preds&&(u.preds=u.preds.map(m=>Mr(m,t,r,n,new Set,i))),u.from&&(u.from=Ce(u.from,t,r,n,new Set,i));const d=a||e.from?void 0:s?.rowPermissions,l=(e.from?[]:$u(e,t,r)).map(m=>Ge(xt(m,e.version),t,r,!1,c,i));d&&l.push(Ge(xt(Y(d),e.version),t,r,!1,c,i));const f=[u.query,...l].filter(m=>m!==void 0&&Object.keys(m).length>0);return f.length===1?u.query=f[0]:f.length>1?u.query={$and:f}:delete u.query,u},wu=(e,t)=>{if(e)for(const[r,n]of Object.entries(e)){const o=t(r),i=n.columnPermissions?.whitelist;if(i&&(!Array.isArray(i)||i.some(s=>typeof s!="string")))throw new p("INVALID_COLUMN_PERMISSIONS",`Column permissions whitelist must be an array of strings: ${r}`,{schemaId:r});for(const s of i??[])if(!o.properties.some(({id:a,name:c})=>a===s||c===s))throw new p("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${r}.${s}`,{schemaId:r,property:s})}},xo=(e,t)=>{const r=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(e),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")}},Vo=(e,t)=>{const r=Date.UTC(e.year,e.month-1,e.day,e.hour,e.minute,e.second);let n=r;for(let o=0;o<3;o+=1){const i=xo(new Date(n),t),s=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second);n+=r-s}return new Date(n)},Au=(e,t)=>{const r=kn(e.expireAt);if(!r)throw new Error(`Invalid daily expiration time: ${e.expireAt}`);if(!e.timeZone){const i=new Date(t);return i.setHours(r.hour,r.minute,r.second,0),i.getTime()<=t.getTime()&&i.setDate(i.getDate()+1),i}const n=xo(t,e.timeZone);let o=Vo({...n,...r},e.timeZone);if(o.getTime()<=t.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=Vo({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},e.timeZone)}return o},Eu=(e,t)=>{const r=e.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(t.getTime()+n.ttlSeconds*1e3)]:[Au(n,t)]);return r.length===0?void 0:new Date(Math.min(...r.map(n=>n.getTime())))},at=(e,t,r)=>{if(nt(e)){t.push(e.plan);return}if(Jn(e)){r.set(`${e.schemaId}:${e.source}`,{schemaId:e.schemaId,source:e.source});return}if(Array.isArray(e)){for(const n of e)at(n,t,r);return}if(!(typeof e!="object"||e===null||e instanceof Date))for(const n of Object.values(e))at(n,t,r)},ct=(e,t,r)=>{if(e.kind==="window"){ct(e.input,t,r);for(const n of e.partitionBy)ct(n,t,r);return}if(e.kind==="operator"){at(e.query,t,r),e.input&&ct(e.input,t,r);for(const n of e.inputs??[])ct(n,t,r)}},de=e=>{const t=new Map,r=o=>{t.set(`${o.schemaId}:${o.source}`,o)};if(e.subplans)for(const o of e.subplans)for(const i of de(o))r(i);else if(e.sourcePlan)for(const o of de(e.sourcePlan))r(o);else e.source&&r({schemaId:e.schemaId,source:e.source});for(const o of e.joins??[])r({schemaId:o.targetSchemaId,source:o.targetSource});const n=[];at(e.query,n,t),at(e.having,n,t);for(const o of e.projections)ct(o.expression,n,t);for(const o of n)for(const i of de(o))r(i);return[...t.values()]},Vt=e=>{const t=new Map;for(const r of e.flat())t.set(`${r.schemaId}:${r.source}`,r);return[...t.values()]},vo=async(e,t)=>{try{return await e.execute(t)}catch(r){const n=r instanceof Error?r.message:String(r),o=`${e.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})}},_u=(e,t)=>{const r=[];for(const n of e){const o=t.findSource(n.schemaId,n.source);if(!o?.freshness)return;r.push(o.freshness)}return r},We=async(e,t,r)=>{e=Bo(e),r.signal?.throwIfAborted();const n=r.cache?_u(t,r.schemaMappings):void 0;if(!r.cache||!n)return vo(r.provider,{...e,...r.signal?{signal:r.signal}:{}});const o={namespace:r.cache.namespace,provider:r.provider.kind,sql:e.sql,parameters:e.parameters};try{const s=await r.cache.store.get(o);if(r.signal?.throwIfAborted(),s)return[...s]}catch{r.signal?.throwIfAborted()}const i=await vo(r.provider,{...e,...r.signal?{signal:r.signal}:{}});try{const s=Eu(n,new Date);await r.cache.store.set(o,i,{sources:[...new Set(t.map(({source:a})=>a))],...s?{expiresAt:s}:{}})}catch{}return i},Bo=e=>({...e,sql:_c(e.sql)}),Su=e=>{if(e.every(t=>typeof t=="string"))return[...e];if(e.every(t=>typeof t=="number"))return[...e];if(e.every(t=>typeof t=="boolean"))return[...e];throw new TypeError("Entity IDs must have one scalar type")},Iu=(e,t,r)=>{const n=Su(t);if(!r||n.length<=r)return{[e]:{$in:n}};const o=[];for(let i=0;i<n.length;i+=r)o.push({[e]:{$in:n.slice(i,i+r)}});return{$or:o}},Ru=async(e,t)=>{if(!De(t.permissions,e.schema.id,e.idProperty))throw new p("COLUMN_PERMISSION_DENIED",`Entity hydration requires the ID property in the column permissions: ${e.schema.id}.${e.idProperty.name}`,{schemaId:e.schema.id,property:e.idProperty.name});const r=e.schema.properties.filter(u=>De(t.permissions,e.schema.id,u)),n={version:t.version,schema:e.schema.id,query:Iu(e.idProperty.name,e.ids,t.provider.maxInListItems),preds:r.map(u=>({pred:u.name,name:u.name}))},o=Ce(n,t.permissions,t.resolveSchema,!0,new Set,t.plugins),i=await Qe(o,e.schema,{semanticTypes:t.semanticTypes,operators:t.operators,...t.plugins?{plugins:t.plugins}:{},...t.locale?{locale:t.locale}:{},...t.localeRegistry?{localeRegistry:t.localeRegistry}:{},resolveSchema:t.resolveSchema}),s=he(i,e.schema,t.operators,t.schemaMappings,{resolveSchema:t.resolveSchema,canUsePropertyRowIdentity:(u,d)=>De(t.permissions,u.id,d)}),a=fe(s,t.provider,t.operators);t.onCompiled?.(a,i);const c=await We(a,de(s),{provider:t.provider,schemaMappings:t.schemaMappings,...t.cache?{cache:t.cache}:{},...t.signal?{signal:t.signal}:{}});return mo(c,s.rowIdentity)},Fo=e=>String(e),Ou=(e,t,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${Fo(r)}\u300D\u7684\u5B9E\u4F53`,o={};for(const i of e.properties)i.id===t.id?o[i.name]=r:i.isArray?o[i.name]=[]:o[i.name]=i.primal_type==="string"?n:null;return o._id=Fo(r),o},Yo=(e,t)=>`${e}:${String(t)}`,bu=e=>{const t=e.properties.filter(({type:n})=>n==="ID"),r=t[0];if(t.length!==1||!r)throw new p("RELATION_TARGET_ID_REQUIRED",`Relation target ${e.id} must contain exactly one ID property`,{schemaId:e.id,count:t.length});return r};class Nu{#e;#r=new Map;#t=new Map;#n=new Map;#o=!1;constructor(t){this.#e=t}load=(t,r)=>{const n=Yo(t,r),o=this.#r.get(n);if(o)return Promise.resolve(o);const i=this.#t.get(n);if(i)return i;const s=this.#e.resolveSchema(t);if(tt(s))throw new p("VALIDITY_ENTITY_HYDRATION_REQUIRES_TIME",`Cannot hydrate valid-time entity ${t} by ID without the source row's timestamp; use a relation path to select its as-of properties`,{schemaId:t});const a=bu(s);let c,u;const d=new Promise((f,m)=>{c=f,u=m}),l=this.#n.get(t)??{schema:s,idProperty:a,loads:new Map};return l.loads.set(n,{id:r,resolve:f=>c?.(f),reject:f=>u?.(f)}),this.#n.set(t,l),this.#t.set(n,d),this.#i(),d};#i(){this.#o||(this.#o=!0,queueMicrotask(()=>{this.#s()}))}async#s(){this.#o=!1;const t=this.#n;this.#n=new Map,await Promise.all([...t.values()].map(r=>this.#a(r)))}async#a(t){const r={schema:t.schema,idProperty:t.idProperty,ids:[...t.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[t.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(Yo(t.schema.id,s),c)}}for(const[i,s]of t.loads){const a=o.get(i)??Ou(t.schema,t.idProperty,s.id);this.#r.set(i,a),this.#t.delete(i),s.resolve(a)}}catch(n){for(const[o,i]of t.loads)this.#t.delete(o),i.reject(n)}}}const Pu=(e,t)=>{if(!t.isArray||typeof e!="string")return e;const r=e.trim();if(!r.startsWith("[")||!r.endsWith("]"))return e;try{const n=JSON.parse(r);if(!Array.isArray(n))throw new Error("JSON result is not an array");return n}catch(n){throw new p("INVALID_ARRAY_RESULT",`Result column ${t.name} contains invalid array JSON`,{property:t.name,cause:n})}},Tu=async(e,t,r,n)=>{await Promise.all(e.map(async o=>{await Promise.all(t.map(async i=>{if(!(i.name in o))return;const s=Pu(o[i.name],i),a=r.get(i.type).hydrateResult;if(!a){o[i.name]=s;return}o[i.name]=i.isArray&&Array.isArray(s)?await Promise.all(s.map(c=>a(c,{property:i,requestEntity:n}))):await a(s,{property:i,requestEntity:n})}))}))},Qo=5,Lu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date),Du=(e,t)=>{const r=t.properties.find(({type:n})=>n==="ID");return r?e[r.name]:void 0},Cu=(e,t)=>{const r=si(t);e._title=e[r.name]??e._id},qu=(e,t)=>{const r=structuredClone(e);if(!("_id"in r)){const n=Du(r,t);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},Uu=(e,t,r,n)=>{const o=`${t.id}:${n?"recursive":"leaf"}`,i=e.get(o);if(i){i.rows.push(r);return}e.set(o,{rows:[r],properties:t.properties,schema:t,expandEntities:n})},ju=async(e,t,r)=>{const n=new Nu(r);let o=[{rows:e,properties:t,expandEntities:!0}];for(let i=0;o.length>0;i+=1){await Promise.all(o.map(a=>{const c=a.expandEntities&&i<Qo;return Tu(a.rows,a.properties,r.semanticTypes,c?n.load:(u,d)=>Promise.resolve(d))}));for(const a of o)if(a.schema)for(const c of a.rows)Cu(c,a.schema);if(i>=Qo)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 d of a.rows){if(!(c.name in d))continue;const l=d[c.name],f=c.isArray?Array.isArray(l)?l:[l]:[l];for(const[m,y]of f.entries()){if(!Lu(y))continue;const g=qu(y,u);c.isArray?f[m]=g:d[c.name]=g,Uu(s,u,g,!c.isArray)}c.isArray&&(d[c.name]=f)}}o=[...s.values()]}},ku=async(e,t,r)=>{const n=e.map(o=>({...o}));return await ju(n,t,r),n},xr=e=>`'${e.replaceAll("'","''")}'`,vt=(e,t)=>{if(e==null)return"NULL";if(typeof e=="boolean")return e?"TRUE":"FALSE";if(typeof e=="number")return String(e);if(typeof e=="bigint")return xr(e.toString());if(typeof e=="string")return xr(e);if(e instanceof Date){const r=t==="clickhouse"?e.toISOString().replace("T"," ").replace("Z",""):e.toISOString();return xr(r)}if(Buffer.isBuffer(e)){const r=e.toString("hex");return t==="oracle"?`HEXTORAW('${r}')`:t==="postgresql"?`decode('${r}', 'hex')`:t==="snowflake"?`TO_BINARY('${r}', 'HEX')`:`unhex('${r}')`}throw new TypeError(`Unsupported ${t} display parameter type: ${typeof e}`)},Mu=(e,t)=>e.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in t?vt(t[o],"clickhouse"):r}),xu=(e,t)=>e.replace(/:([1-9]\d*)\b/g,(r,n)=>{const o=Number(n)-1;return o in t?vt(t[o],"oracle"):r}),Vu=(e,t)=>{let r="",n;for(let o=0;o<e.length;o+=1){const i=e[o];if(i){if(n){r+=i,i===n&&(e[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(e.slice(o)),a=s?.[1];if(s&&a){const c=Number(a)-1;if(c in t){r+=vt(t[c],"postgresql"),o+=s[0].length-1;continue}}}r+=i}}return r},vu=(e,t)=>{let r="",n=0,o;for(let i=0;i<e.length;i+=1){const s=e[i];if(s){if(o){r+=s,s===o&&(e[i+1]===o?(r+=o,i+=1):o=void 0);continue}if(s==="'"||s==='"'||s==="`"){o=s,r+=s;continue}if(s==="?"&&n<t.length){r+=vt(t[n],"snowflake"),n+=1;continue}r+=s}}return r},Bu=e=>{if(e.url!==void 0)return e.url;const t=e.host??"localhost";if(/^[a-z][a-z\d+.-]*:\/\//iu.test(t)){if(e.port===void 0)return t;const n=new URL(t);return n.port=String(e.port),n.toString()}return`http://${t}:${e.port??8123}`},Fu=e=>e===null?"Nullable(String)":typeof e=="boolean"?"Bool":typeof e=="number"?"Float64":e instanceof Date?"DateTime64(3)":"String",Yu=e=>e instanceof Date?e.toISOString().replace("T"," ").replace("Z",""):e;class Qu{kind="clickhouse";client;constructor(t={}){this.client=t.client??ci({url:Bu(t),username:t.username??t.user??"default",password:t.password??"",database:t.database??"default"})}quoteIdentifier(t){return`\`${t.replaceAll("`","``")}\``}tableAlias(t,r){return`${t} AS ${this.quoteIdentifier(r)}`}paginate(t,r,n){return`${t} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(t,r){return`{p${t}:${Fu(r)}}`}displayQuery(t,r){return Mu(t,r)}dateBucket(t,r){if(r==="second")return`toDateTime64(${t}, 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}(${t})`}dateShift(t,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}, ${t})`}castValue(t,r){return r==="timestamp"?`toDateTime(${t})`:r==="date"?`toDate(${t})`:t}scalarExtremum(t,r){const n=`[${r.map(s=>`toNullable(${s})`).join(", ")}]`,o=`arrayFilter(value -> isNotNull(value), ${n})`;return`if(arrayExists(value -> isNotNull(value), ${n}), ${t==="least"?"arrayMin":"arrayMax"}(${o}), NULL)`}aggregateFunction(t,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(t))throw new Error(`Unsupported ClickHouse aggregate function: ${t}`);return`${t.toUpperCase()}(${r})`}stringify(t){return`toString(${t})`}concat(t){return`concat(${t.join(", ")})`}substring(t,r,n){return`substring(${t}, ${r}, ${n})`}regex(t,r,n){if(n&&n!=="i")throw new Error(`Unsupported ClickHouse regex options: ${n}`);const o=n==="i"?`concat('(?i)', ${r})`:r;return`match(${t}, ${o})`}arrayContains(t,r){return`has(${t}, ${r})`}expandArray(t,r,n){const o=this.quoteIdentifier(r);return{joinSql:`ARRAY JOIN ${t} AS ${o}`,valueExpression:o}}async execute(t){t.signal?.throwIfAborted();const r=Object.fromEntries(t.parameters.map((o,i)=>[`p${i}`,Yu(o)]));return(await this.client.query({query:t.sql,format:"JSONEachRow",query_params:r,...t.signal?{abort_signal:t.signal}:{}})).json()}async close(){await this.client.close()}}const te={quoteIdentifier(e){return`\`${e.replaceAll("`","``")}\``},tableAlias(e,t){return`${e} AS ${this.quoteIdentifier(t)}`},paginate(e,t,r){return`${e} LIMIT ${t}${r>0?` OFFSET ${r}`:""}`},parameter(e,t){return"?"},displayQuery(e,t){return di.format(e,[...t])},dateBucket(e,t){const r={hour:"%Y-%m-%d %H:00:00",day:"%Y-%m-%d",month:"%Y-%m-01",year:"%Y-01-01"};if(t==="week")return`DATE_SUB(DATE(${e}), INTERVAL WEEKDAY(${e}) DAY)`;if(t==="quarter")return`MAKEDATE(YEAR(${e}), 1) + INTERVAL (QUARTER(${e}) - 1) QUARTER`;const n=r[t];if(!n)throw new Error(`Unsupported MySQL-compatible date level: ${t}`);return`DATE_FORMAT(${e}, '${n}')`},dateShift(e,t,r){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(t)||!Number.isInteger(r))throw new Error(`Unsupported MySQL-compatible date shift: ${t}/${r}`);return`DATE_ADD(${e}, INTERVAL ${r} ${t.toUpperCase()})`},datePeriodBoundary(e,t,r){if(r==="start")return this.dateBucket(e,t);switch(t){case"hour":return`DATE_FORMAT(${e}, '%Y-%m-%d %H:59:59')`;case"day":return`TIMESTAMP(DATE(${e}), '23:59:59')`;case"month":return`TIMESTAMP(LAST_DAY(${e}), '23:59:59')`;case"year":return`CONCAT(YEAR(${e}), '-12-31 23:59:59')`;default:return this.dateShift(this.dateShift(this.dateBucket(e,t),t,1),"second",-1)}},aggregateFunction(e,t="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported MySQL-compatible aggregate function: ${e}`);return`${e.toUpperCase()}(${t})`},stringify(e){return`CAST(${e} AS CHAR)`},concat(e){return`CONCAT(${e.join(", ")})`},substring(e,t,r){return`SUBSTRING(${e}, ${t}, ${r})`},regex(e,t,r){if(r&&r!=="i")throw new Error(`Unsupported MySQL-compatible regex options: ${r}`);return r==="i"?`LOWER(${e}) REGEXP LOWER(${t})`:`${e} REGEXP ${t}`},arrayContains(e,t){return`JSON_OVERLAPS(${e}, JSON_ARRAY(${t}))`},expandArray(e,t,r){const n=this.quoteIdentifier(t),o=this.quoteIdentifier(r);return{joinSql:`CROSS JOIN JSON_TABLE(CASE WHEN JSON_TYPE(${e}) = 'ARRAY' THEN ${e} ELSE JSON_ARRAY() END, '$[*]' COLUMNS (${o} JSON PATH '$')) AS ${n}`,valueExpression:`${n}.${o}`}}},Hu={connectionLimit:30,maxIdle:10,idleTimeout:6e4,enableKeepAlive:!0,keepAliveInitialDelay:0};class Vr{supportsRecursiveCte=!0;pool;constructor(t={}){this.pool=t.pool??ui({...Hu,decimalNumbers:!0,...t.connection})}quoteIdentifier(t){return te.quoteIdentifier(t)}tableAlias(t,r){return te.tableAlias(t,r)}paginate(t,r,n){return te.paginate(t,r,n)}parameter(t,r){return te.parameter(t,r)}displayQuery(t,r){return te.displayQuery(t,r)}dateBucket(t,r){return te.dateBucket(t,r)}dateShift(t,r,n){return te.dateShift(t,r,n)}datePeriodBoundary(t,r,n){const o=te.datePeriodBoundary?.bind(te);if(!o)throw new Error("MySQL date period boundary renderer is unavailable");return o(t,r,n)}aggregateFunction(t,r){return te.aggregateFunction(t,r)}stringify(t){return te.stringify(t)}concat(t){return te.concat(t)}substring(t,r,n){return te.substring(t,r,n)}regex(t,r,n){return te.regex(t,r,n)}arrayContains(t,r){const n=te.arrayContains?.bind(te);if(!n)throw new Error("MySQL-compatible array conditions are unavailable");return n(t,r)}expandArray(t,r,n){const o=te.expandArray?.bind(te);if(!o)throw new Error("MySQL-compatible array expansion is unavailable");return o(t,r,n)}async execute(t){t.signal?.throwIfAborted();const[r]=await this.pool.execute(t.sql,t.parameters);if(!Array.isArray(r))throw new Error(`${this.kind} provider expected an array result`);return r}async close(){await this.pool.end()}}class Gu extends Vr{kind="doris";constructor(t={}){super(t)}}class Wu extends Vr{kind="mysql";constructor(t={}){super(t)}}const Ho=e=>{if(e==null)return null;if(typeof e=="bigint")return e.toString();if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e instanceof Date||Buffer.isBuffer(e))return e;throw new TypeError(`Unsupported Oracle parameter type: ${typeof e}`)},zu=e=>e.reason instanceof Error?e.reason:new DOMException("The operation was aborted","AbortError");class Ku{kind="oracle";supportsHavingAlias=!1;maxInListItems=1e3;#e;#r;#t;constructor(t={}){this.#e=t.connection??{},this.#r=t.driver??{createPool:r=>zr.createPool(r)},this.#t=t.pool?Promise.resolve(t.pool):void 0}quoteIdentifier(t){return`"${t.replaceAll('"','""')}"`}tableAlias(t,r){return`${t} ${this.quoteIdentifier(r)}`}paginate(t,r,n){return n>0?`${t} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`:`${t} FETCH FIRST ${r} ROWS ONLY`}parameter(t,r){return`:${t+1}`}displayQuery(t,r){return xu(t,r.map(Ho))}dateBucket(t,r){const n={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(r in n))throw new Error(`Unsupported Oracle date level: ${r}`);const o=n[r];return o?`TRUNC(${t}, '${o}')`:`TRUNC(${t})`}dateShift(t,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(${t}, ${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`(${t} + NUMTODSINTERVAL(${n*a.multiplier}, '${a.unit}'))`}aggregateFunction(t,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(t))throw new Error(`Unsupported Oracle aggregate function: ${t}`);return`${t.toUpperCase()}(${r})`}stringify(t){return`TO_CHAR(${t})`}concat(t){return`(${t.join(" || ")})`}substring(t,r,n){return`SUBSTR(${t}, ${r}, ${n})`}regex(t,r,n){if(n&&n!=="i")throw new Error(`Unsupported Oracle regex options: ${n}`);return`REGEXP_LIKE(${t}, ${r}${n?", 'i'":""})`}arrayContains(t,r){return`JSON_EXISTS(${t}, '$?(@ == $value)' PASSING ${r} AS "value")`}expandArray(t,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS APPLY JSON_TABLE(${t}, '$[*]' COLUMNS (${i} VARCHAR2(4000) PATH '$')) ${o}`,valueExpression:`${o}.${i}`}}async#n(){this.#t??=this.#r.createPool(this.#e);try{return await this.#t}catch(t){throw this.#t=void 0,t}}async execute(t){t.signal?.throwIfAborted();const r=await this.#n();t.signal?.throwIfAborted();const n=await r.getConnection(),o=t.signal,i=()=>{n.break().catch(()=>{})};o?.addEventListener("abort",i,{once:!0});try{const s=await n.execute(t.sql,t.parameters.map(Ho),{outFormat:zr.OUT_FORMAT_OBJECT});if(o?.throwIfAborted(),!Array.isArray(s.rows))throw new Error("Oracle provider expected an array result");return s.rows}catch(s){throw o?.aborted?zu(o):s}finally{o?.removeEventListener("abort",i),await n.close()}}async close(){const t=this.#t;if(!t)return;await(await t).close(0),this.#t=void 0}}class Ju{kind="postgresql";supportsHavingAlias=!1;supportsRecursiveCte=!0;pool;constructor(t={}){this.pool=t.pool??new pi(t.connection)}quoteIdentifier(t){return`"${t.replaceAll('"','""')}"`}tableAlias(t,r){return`${t} AS ${this.quoteIdentifier(r)}`}paginate(t,r,n){return`${t} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(t,r){return`$${t+1}`}displayQuery(t,r){return Vu(t,r)}dateBucket(t,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported PostgreSQL date level: ${r}`);return`DATE_TRUNC('${r}', ${t})`}dateShift(t,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`(${t} + (${n} * INTERVAL '1 ${r}'))`}aggregateFunction(t,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(t))throw new Error(`Unsupported PostgreSQL aggregate function: ${t}`);return`${t.toUpperCase()}(${r})`}stringify(t){return`CAST(${t} AS TEXT)`}concat(t){return`CONCAT(${t.join(", ")})`}substring(t,r,n){return`SUBSTRING(${t} FROM ${r} FOR ${n})`}regex(t,r,n){if(n&&n!=="i")throw new Error(`Unsupported PostgreSQL regex options: ${n}`);return`${t} ${n==="i"?"~*":"~"} ${r}`}arrayContains(t,r){return`${r} = ANY(${t})`}expandArray(t,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS JOIN LATERAL unnest(${t}) AS ${o}(${i})`,valueExpression:`${o}.${i}`}}async execute(t){t.signal?.throwIfAborted();const r=await this.pool.query(t.sql,[...t.parameters]);if(t.signal?.throwIfAborted(),!Array.isArray(r.rows))throw new Error("PostgreSQL provider expected an array result");return r.rows}async close(){await this.pool.end()}}const Go=e=>{if(e==null)return null;if(e instanceof Date)return e.toISOString();if(typeof e=="bigint")return e.toString();if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;throw new TypeError(`Unsupported Snowflake parameter type: ${typeof e}`)},Zu=e=>e.reason instanceof Error?e.reason:new DOMException("The operation was aborted","AbortError");class Xu{kind="snowflake";#e;#r=!1;#t;constructor(t={}){this.#e=t.client??li.createConnection(t.connection??{})}quoteIdentifier(t){return`"${t.replaceAll('"','""')}"`}tableAlias(t,r){return`${t} AS ${this.quoteIdentifier(r)}`}paginate(t,r,n){return`${t} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(t,r){return"?"}displayQuery(t,r){return vu(t,r.map(Go))}dateBucket(t,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Snowflake date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${t})`}dateShift(t,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}, ${t})`}aggregateFunction(t,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(t))throw new Error(`Unsupported Snowflake aggregate function: ${t}`);return`${t.toUpperCase()}(${r})`}stringify(t){return`TO_VARCHAR(${t})`}concat(t){return`CONCAT(${t.join(", ")})`}substring(t,r,n){return`SUBSTRING(${t}, ${r}, ${n})`}regex(t,r,n){if(n&&n!=="i")throw new Error(`Unsupported Snowflake regex options: ${n}`);return n?`REGEXP_INSTR(${t}, ${r}, 1, 1, 0, '${n}') > 0`:`REGEXP_INSTR(${t}, ${r}) > 0`}arrayContains(t,r){return`ARRAY_CONTAINS(${r}::VARIANT, ${t})`}expandArray(t,r,n){const o=this.quoteIdentifier(r);return{joinSql:`, LATERAL FLATTEN(INPUT => ${t}) ${o}`,valueExpression:`${o}.VALUE`}}async#n(){if(!this.#r){this.#t??=new Promise((t,r)=>{this.#e.connect(n=>{if(n){r(n);return}this.#r=!0,t()})});try{await this.#t}catch(t){throw this.#t=void 0,t}}}async execute(t){t.signal?.throwIfAborted(),await this.#n(),t.signal?.throwIfAborted();const r=t.parameters.map(Go);return new Promise((n,o)=>{const i=t.signal,s={};let a=!1;const c=d=>{a||(a=!0,i?.removeEventListener("abort",u),d())},u=()=>{s.current?.cancel(),i&&c(()=>o(Zu(i)))};i?.addEventListener("abort",u,{once:!0}),s.current=this.#e.execute({sqlText:t.sql,binds:r,complete:(d,l,f)=>{if(d){c(()=>o(d));return}if(!Array.isArray(f)){c(()=>o(new Error("Snowflake provider expected an array result")));return}c(()=>n(f))}}),i?.aborted&&u()})}async close(){this.#r&&await new Promise((t,r)=>{this.#e.destroy(n=>{if(n){r(n);return}this.#r=!1,this.#t=void 0,t()})})}}class ed extends Vr{kind="starrocks";constructor(t={}){super(t)}}const td=e=>{switch(e.kind){case"mysql":{const{id:t,kind:r,...n}=e;return new Wu({connection:n})}case"doris":{const{id:t,kind:r,...n}=e;return new Gu({connection:n})}case"starrocks":{const{id:t,kind:r,...n}=e;return new ed({connection:n})}case"postgresql":{const{id:t,kind:r,...n}=e;return new Ju({connection:n})}case"clickhouse":{const{id:t,kind:r,...n}=e;return new Qu(n)}case"snowflake":{const{id:t,kind:r,...n}=e;return new Xu({connection:n})}case"oracle":{const{id:t,kind:r,...n}=e;return new Ku({connection:n})}}};class rd{create;#e=new Map;constructor(t=td){this.create=t}get(t){const r=this.#e.get(t.id);if(r){if(!ai(r.connection,t))throw new p("DATABASE_CONNECTION_CONFIGURATION_MISMATCH",`Database connection configuration changed for id: ${t.id}`,{connectionId:t.id});return r.provider}const n=this.create(t);return this.#e.set(t.id,{connection:t,provider:n}),n}async close(){const t=[...this.#e.values()].map(({provider:o})=>o);this.#e.clear();const r=await Promise.allSettled(t.map(async o=>o.close())),n=[];for(const o of r)o.status==="rejected"&&n.push(o.reason);if(n.length>0)throw new AggregateError(n,"Failed to close one or more database connections")}}const Wo=new rd,nd=e=>Wo.get(e),od=async()=>Wo.close(),id=new Set(["$sply","$splm","$splq","$splw","$yoy","$mom","$qoq","$wow","$yoyd","$momd","$qoqd","$wowd","$percentage"]),zo=e=>!ee(e)||!Array.isArray(e.properties)?[]:e.properties.filter(ee),ze=(e,t,r)=>{const n=(o,i,s)=>{const u=zo(r[o]).map(y=>{const g=typeof y.id=="string"?y.id:void 0,_=typeof y.name=="string"?y.name:void 0,$=[g,_].filter(E=>!!E&&(i===E||i.startsWith(`${E}_`))).sort((E,h)=>h.length-E.length)[0];return $?{property:y,key:$}:void 0}).filter(y=>!!y).sort((y,g)=>g.key.length-y.key.length)[0];if(!u)return;const d=String(u.property.id??u.property.name),l=i===u.key?"":i.slice(u.key.length+1);if(!l)return d;const f=typeof u.property.ref=="string"?u.property.ref:void 0;if(!f||s.has(f))return;const m=n(f,l,new Set(s).add(f));return m?`${d}_${m}`:void 0};return n(e,t,new Set([e]))},vr=(e,t,r)=>{const n=zo(r[e]).filter(o=>typeof o.id=="string").sort((o,i)=>String(i.id).length-String(o.id).length).find(o=>t===o.id||t.startsWith(`${String(o.id)}_`));if(!(!n||typeof n.id!="string")){if(t===n.id)return n.id;if(typeof n.ref=="string")return vr(n.ref,t.slice(n.id.length+1),r)}},Ko=e=>Object.keys(e).filter(t=>t!=="$and"&&t!=="$or"),ee=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jo=e=>{if(!ee(e))return e;if(ee(e.$offset)){const t=Object.entries(e.$offset),r=t[0];if(t.length===1&&r&&Number.isInteger(r[1]))return{granularity:r[0],offset:r[1]}}return e},sd=(e,t)=>{const n=e&&({$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"}[e]??e),o={...t};return e==="$sply"||e==="$yoy"||e==="$yoyd"?o.time??={granularity:"year",offset:-1}:e==="$splm"||e==="$mom"||e==="$momd"?o.time??={granularity:"month",offset:-1}:e==="$splq"||e==="$qoq"||e==="$qoqd"?o.time??={granularity:"quarter",offset:-1}:e==="$splw"||e==="$wow"||e==="$wowd"?o.time??={granularity:"week",offset:-1}:e==="$dailyavg"?o.granularity??="day":e==="$weeklyavg"?o.granularity??="week":e==="$monthlyavg"?o.granularity??="month":e==="$startOfPeriod"?o.boundary??="start":e==="$endOfPeriod"&&(o.boundary??="end"),{...n?{operator:n}:{},args:o}},be=e=>{if(Array.isArray(e))return e.map(be);if(!ee(e))return e;const t=Jo(e);if(t!==e)return t;const r=e,n={};for(const[i,s]of Object.entries(r))i==="skip"||i==="_snapshot"||i==="_snapshots"||(n[i]=be(s));if(typeof r.version=="string"&&/^1\./.test(r.version)&&(n.version="2.0"),Array.isArray(r.groupby)){const i=r.groupby;n.groupby=i.map(s=>{if(!ee(s))return s;const{_id:a,level:c,...u}=s,d={...u,...u.pred===void 0&&typeof a=="string"?{pred:a}:{}};return typeof c=="string"&&(d.operator="$dateBucket",d.args={...ee(d.args)?d.args:{},granularity:c}),d})}const o=r.skip;if(typeof o=="number"&&Number.isInteger(o)&&o>=0){const i=r.limit;o===0?delete n.skip:typeof i=="number"&&Number.isInteger(i)&&i>0&&o%i===0?n.page=o/i+1:n.skip=o}else o!==void 0&&(n.skip=be(o));if(r.operator&&typeof r.operator=="string"){const i=sd(r.operator,ee(n.args)?n.args:{});i.operator&&(n.operator=i.operator),n.args=i.args,id.has(r.operator)&&typeof n.pred=="string"&&(n.pred={operator:"$sum",pred:n.pred})}return r.params!==void 0&&n.args===void 0&&(n.args=Array.isArray(r.params)?{values:be(r.params)}:be(r.params)),r.inputs!==void 0&&n.pred===void 0&&Array.isArray(r.inputs)&&(n.pred=r.inputs.map(be),ee(n.args)&&delete n.args.inputs),r.pred===void 0&&typeof r.operator=="string"&&r.operator==="$sql"&&typeof r.sql=="string"&&(n.args={...ee(n.args)?n.args:{},sql:r.sql},delete n.sql),r.$options!==void 0&&n.$regex!==void 0&&(n.args={...ee(n.args)?n.args:{},options:r.$options},delete n.$options),r.query&&ee(r.query)&&(n.query=ad(r.query)),n},ad=e=>{const t=be(e);for(const[r,n]of Object.entries(t))t[r]=Jo(n);return t},Zo=(e,t)=>{const r=ee(e)?e:void 0,n=be(e);if(!ee(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],Zo(o)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),t?cd(n,t):n},cd=(e,t)=>{const r=e;if(!Array.isArray(r.preds))return e;const n=r.preds,o=typeof r.schema=="string"?r.schema:void 0;if(!o)return e;const i=new Set([o]);for(const c of n)ee(c)&&typeof c.schema=="string"&&i.add(c.schema);if(i.size<2)return e;if(!t)throw new Error("Cannot migrate cross-Schema LogicForm without Schema metadata for field alignment");const s=Array.isArray(r.groupby)?r.groupby.map(c=>ee(c)&&typeof c.pred=="string"?ze(o,c.pred,t):void 0):[];for(const c of i)if(Array.isArray(r.groupby)&&r.groupby.map((u,d)=>{if(!ee(u)||typeof u.pred!="string")return u;const l=c===o?ze(c,u.pred,t):ze(c,vr(o,s[d]??"",t)??u.pred,t);if(!l)return u;const f=l.split("_").at(-1)??u.pred;return{...u,pred:l,name:f}}),ee(r.query))for(const u of Ko(r.query)){const d=ze(o,u,t);if(!(c===o?d:ze(c,(d&&vr(o,d,t))??u,t))&&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(!ee(c)||typeof c.pred!="string")return c;const d=s[u];return d?{...c,pred:d}:c})),ee(r.query)){const c=r.query,u=Ko(c).map(d=>[ze(o,d,t)??d,c[d]]);a.query=Object.fromEntries(u)}return a},ud=e=>{const t=(r,n)=>{if(Array.isArray(r)){r.forEach((o,i)=>t(o,`${n}[${i}]`));return}if(ee(r))for(const[o,i]of Object.entries(r)){if(["is_snapshot","is_observation","_snapshot","_snapshots","$options","params","inputs"].includes(o))throw new p("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);if(o==="_id"&&(n.endsWith(".groupby")||n.includes(".groupby[")))throw new p("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);t(i,`${n}.${o}`)}};t(e,"$")},Br=e=>{if(Array.isArray(e))return e.map(Br).filter(n=>n!==void 0);if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return e;const t=Object.entries(e),r=t.filter(([,n])=>n!==null).map(([n,o])=>[n,Br(o)]).filter(([,n])=>n!==void 0);if(!(t.length>0&&r.length===0))return Object.fromEntries(r)},dd=e=>{if(e.comparable!=null)return e.comparable;if(e.is_comparable!==!0||e.isArray===!0||e.type!=="string"&&e.type!=="category"||!Array.isArray(e.constraints?.enum))return;const r=e.constraints.enum.map(n=>Array.isArray(n)?n[0]:n);if(!(r.length===0||r.some(n=>typeof n!="string")))return{values:[...new Set(r)],direction:e.comparable_order===-1?-1:1}},pd=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return e;const t=e;if(t.sql!=null)return Object.keys(t).every(r=>r==="sql")?e:{sql:t.sql}},ld=(e,t=[],r=!0)=>{const n=wt(t),o={},i=new Set(n.flatMap(s=>[...s.schemaMetadata?.keys??[],...s.legacySchemaKeys??[]]));for(const[s,a]of Object.entries(e)){const c=Br(a),u=c,l=(Array.isArray(u.properties)?u.properties:[]).some(E=>E.is_observation===!0)||u.is_observation===!0,f=u.is_snapshot===!0,m=typeof c.id=="string"&&c.id.length>0?c.id:r&&typeof c._id=="string"&&c._id.length>0?c._id:c.id,{properties:y}=c,g=Object.fromEntries(Object.entries(c).filter(([E])=>(r?!["_id","_sid","sid","is_observation","is_snapshot"].includes(E):E!=="properties")&&E!=="properties"&&!i.has(E))),_=y.map(E=>{const h=E,S=typeof h.id=="string"&&h.id.length>0?h.id:r&&typeof h._id=="string"&&h._id.length>0?h._id:h.id,{udf:N,...k}=h,j=dd(h),v=pd(N),K=j!==void 0&&h.comparable==null?"category":h.type==="object"?"entity":h.type;return{...r?Object.fromEntries(Object.entries(k).filter(([L])=>!["_id","_sid","sid","is_observation","is_comparable","comparable_order"].includes(L))):k,type:K,...h.primal_type==="object"?{primal_type:"entity"}:{},...S!==void 0?{id:S}:{},...v!==void 0?{udf:v}:{},...j!==void 0?{comparable:j}:{}}});let R={};for(const E of n)for(const h of E.schemaMetadata?.keys??[])c[h]!==void 0&&(R={...R,[h]:c[h]});for(const E of n)R={...R,...E.normalizeLegacySchema?.({source:c,properties:_})};const $={...g,...m!==void 0?{id:m}:{},properties:_,...r&&(f||l)?{temporalSemantics:"snapshot"}:{},...R};o[s]=$}return o};J.extend(dt),J.extend(pt);const Fr=e=>({kind:"query",logicform:e.logicform,...e.prepare!==void 0?{prepare:e.prepare}:{},...e.mapResult?{mapResult:e.mapResult}:{},...e.groupKeyShifts?{groupKeyShifts:e.groupKeyShifts}:{}}),Xo=e=>e instanceof Error?e:new Error(String(e)),fd=(e,t="zh-CN",r)=>e instanceof p?e.localizedMessage(t,r):e.message,md=(e,t,r={},n="zh-CN",o)=>{const i=Xo(e);return{errorCode:"100",error:fd(i,n,o),result:[],...r.schema?{schema:r.schema}:{},normedLogicform:r.normedLogicform??t,sqls:r.sqls??[],...r.provider?{provider:r.provider}:{},...r.lineage?{lineage:r.lineage}:{}}},yd=(e,t,r)=>{if(e.length<2||e.some(i=>i.kind==="js"||i.kind==="query"&&i.unit.mapResult))return!1;const n=new Set,o=[...e.flatMap(({sources:i})=>i),...de(r)];for(const i of o){const s=t.findSource(i.schemaId,i.source);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},hd=async(e,t,r)=>{await e?.({...t,partialResult:r})},gd=(e,t,r,n,o,i,s=r)=>({type:r,explain:i.translate(o,s==="time-watermark"?"sql.timeWatermark":s==="entity-expansion"?"sql.entityExpansion":s==="computation"?"sql.computation":"sql.semanticResolution"),logicform:n,sql:e.sql,parameters:[...e.parameters],displaySql:t.displayQuery(e.sql,e.parameters)}),ei=(e,t)=>{if(t.connectionId)for(const r of de(e)){const n=t.schemaMappings.findSource(r.schemaId,r.source);if(!n)throw new p("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${r.schemaId}:${r.source}`,{schemaId:r.schemaId,source:r.source});if(n.connectionId!==t.connectionId)throw new p("CROSS_CONNECTION_QUERY_UNSUPPORTED",`One physical query cannot use multiple database connections: ${t.connectionId}, ${n.connectionId}`,{schemaId:r.schemaId,source:r.source,connectionId:n.connectionId})}},$d=e=>{const t=new Set,r=n=>{n.schema&&t.add(n.schema),n.from&&r(n.from)};return r(e),[...t]},wd="YYYY-MM-DD HH:mm:ss",ti=(e,t)=>J(e).endOf(t==="week"?"isoWeek":t).toDate(),Yr=e=>J(e).format(wd),Ad=(e,t)=>{const r=e??{type:"database_latest"};if(r.type==="database_latest"||Number.isInteger(r.offset))return r;throw new p("INVALID_TIME_WATERMARK",`${t} timeWatermark must be database_latest or now_offset with an integer offset`,{owner:t,timeWatermark:e})},Qr=e=>{const t=e.schema?[e.schema]:[];return e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)?[...t,...Qr(e.pred)]:Array.isArray(e.pred)?[...t,...e.pred.flatMap(r=>typeof r=="string"?[]:Qr(r))]:t},Ed=async(e,t)=>{const r=t.locale??"zh-CN",n=t.localeRegistry??yt(t.locales),o=t.plugins??[],i=e.version,s=typeof i=="string"&&(/^2\./.test(i)||/^[3-9]\d*\./.test(i)),a=i===void 0||typeof i=="string"&&/^1\./.test(i);s&&ud(e);const c=a?Zo(e,t.schemas):e,u={...t,locale:r,localeRegistry:n,schemas:ld(t.schemas,o,a)},d=Wr.now(),l=u.semanticTypes??Po(),f=u.operators??Ie(o);if(u.operators)for(const D of o)for(const L of D.operators??[])if(f.has(L.name)){if(f.get(L.name)!==L)throw new p("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${L.name}`,{operator:L.name,plugin:D.name})}else f.register(L);const m=u.schemaMappings,y=new Date,g=new Map;let _={provider:u.provider.kind};const R=[],$=(D,L,V,q=L)=>{R.push(gd(Bo(D),u.provider,L,V,u.locale??"zh-CN",n,q)),_={..._,sqls:[...R]}},E=async(D,L={})=>{_={..._,...L},await hd(u.onProgress,D,_)},h=D=>Oo(Hi(D,u.schemas),l,o),S=new Map,N=D=>{const L=S.get(D);return L||(Oe(u.permissions,D),h(D))},k=D=>{if(D.schema)return N(D.schema);if(D.from)return k(D.from);throw new p("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},j={resolveSchema:N,canUsePropertyRowIdentity:(D,L)=>De(u.permissions,D.id,L)},v=(D,L)=>{const V=Wn(he(D,k(D),f,m,j),L);return S.set(V.id,V),V},K=async(D,L,V)=>{const q=`${D.id}:${L.id}:${V.toISOString()}`,re=g.get(q);if(re)return re;const W=(async()=>{const Z=[...new Set((c.preds??[]).flatMap(Qr).filter(O=>O!==D.id))],ne=[{schema:D,property:L}];for(const O of Z){const U=N(O),M=c.propertyResolve?.[O],C=M?.[L.id]??M?.[L.name]??ko(D,L.name,U,N);if(!C)throw new p("TIME_WATERMARK_PROPERTY_RESOLVE_REQUIRED",`Cross-Schema timeWatermark requires propertyResolve for ${O}.${L.name}`,{schemaId:O,property:L.name});const B=U.properties.find(({id:F,name:oe})=>F===C||oe===C);if(!B||B.primal_type!=="date")throw new p("TIME_WATERMARK_PROPERTY_REQUIRED",`timeWatermark Property is not a date Property: ${O}.${C}`,{schemaId:O,property:C});ne.push({schema:U,property:B})}const X=ne.map(({schema:O,property:U})=>{const M=Ad(U.timeWatermark??O.timeWatermark??u.timeWatermark,`${O.id}.${U.id}`);if(M.type==="now_offset"){const C=ti(J(y).add(M.offset,"day").toDate(),U.granularity??"day");return{operator:"$constant",args:{value:Yr(C),type:"timestamp"},name:`${O.name}\u6570\u636E\u65F6\u95F4`}}return{operator:"$periodBoundary",args:{boundary:"end"},pred:{operator:"$max",pred:U.name,schema:O.id},name:`${O.name}\u6700\u65B0\u65F6\u95F4`}});X.some(({operator:O})=>O==="$periodBoundary")&&X.push({operator:"$constant",args:{value:Yr(ti(y,L.granularity??"day")),type:"timestamp"},name:"\u73B0\u5728"}),X.push({operator:"$constant",args:{value:Yr(V),type:"timestamp"},name:"\u63D0\u95EE\u65F6\u95F4\u4E0A\u754C"});const ce={version:c.version,schema:D.id,preds:[{name:"__timeWatermark__",operator:"$least",pred:X}]},Q=Ce(ce,u.permissions,N,!1,new Set,o),w=await Qe(Q,D,{semanticTypes:l,operators:f,plugins:o,now:y,...u.locale?{locale:u.locale}:{},localeRegistry:n,resolveSchema:N,resolveFromSchema:v}),A=he(w,D,f,m,j);ei(A,u);const I=fe(A,u.provider,f);$(I,"semantic-resolution",w,"time-watermark");const b=await We(I,de(A),u),T=b[0]?.__timeWatermark__??Object.values(b[0]??{})[0];if(T==null||!(T instanceof Date)&&typeof T!="string"&&typeof T!="number")return;const P=T instanceof Date?T:new Date(T);return Number.isNaN(P.getTime())?void 0:P})();return g.set(q,W),W};try{u.signal?.throwIfAborted(),Dr(c),await E({stage:"started",logicform:c}),wu(u.permissions,h);const D=k(c);await E({stage:"validated",schema:D});const L=Ce(c,u.permissions,N,!0,new Set,o),V=await Qe(L,D,{semanticTypes:l,operators:f,plugins:o,now:y,...u.locale?{locale:u.locale}:{},localeRegistry:n,resolveSchema:N,resolveFromSchema:v,canProjectProperty:(O,U)=>De(u.permissions,O.id,U),requestTimeWatermark:K});await E({stage:"normalized",normedLogicform:V},{normedLogicform:V});const q=he(V,D,f,m,j);ei(q,u);const re=q.columnProperties??[],W=Gn(q,D);S.set(W.id,W),await E({stage:"planned",plan:q},{schema:W});const Z=jn(q,D,u.provider,f);await E({stage:"lineage",lineage:Z},{lineage:Z});const ne=Nr(V,q,D,f,N,void 0,r,n.translator(r)),X=async O=>{const U=k(O.logicform),M=O.prepare?await Qe(Ce(O.logicform,u.permissions,N,!0,new Set,o),U,{semanticTypes:l,operators:f,plugins:o,now:y,...u.locale?{locale:u.locale}:{},localeRegistry:n,resolveSchema:N,resolveFromSchema:v,canProjectProperty:(F,oe)=>De(u.permissions,F.id,oe),requestTimeWatermark:K}):O.logicform,C=he(M,U,f,m,j),B=Nr(M,C,U,f,N,O.logicform,r,n.translator(r));if(B){if(B.length!==1)throw new Error("A generated component must produce exactly one execution unit");const F=B[0];if("logicform"in F){const G=await X(F),se=G.component.mapResult,pe=O.mapResult;return{...G,component:{...O,logicform:G.component.logicform,...se||pe?{mapResult:le=>{const Ne=se?.(le)??[...le];return pe?.(Ne)??[...Ne]}}:{}}}}if("mergeRow"in F)throw new p("UNSUPPORTED_NESTED_JS_COMPONENT","A JavaScript composite metric cannot currently be nested as a generated component");const oe=await Promise.all(F.components.map(async G=>({name:G.name,prepared:await X(Fr(G)),...G.groupKeyShifts?{groupKeyShifts:G.groupKeyShifts}:{},...G.joinKeys?{joinKeys:G.joinKeys}:{}}))),H=Ir(F,oe.map(({name:G,prepared:se,...pe})=>({name:G,plan:se.plan,...pe})),C,F.outputName,u.provider,f);return{component:{...O,logicform:M},plan:C,compiled:H,sources:Vt(oe.map(({prepared:G})=>G.sources))}}return{component:{...O,logicform:M},plan:C,compiled:fe(C,u.provider,f),sources:de(C)}},ce=async(O,U)=>{const M=Nr(O,U,k(O),f,N,void 0,r,n.translator(r));if(!M)return{compiled:fe(U,u.provider,f),sources:de(U)};const C=await Promise.all(M.map(async B=>{if("logicform"in B){const H=await X(B);return{plan:H.plan,compiled:H.compiled,outputs:H.plan.projections.map(({name:G})=>G).filter(G=>!U.groupBy.some(se=>se.name===G))}}if("mergeRow"in B)throw new p("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const F=await Promise.all(B.components.map(async H=>{const G=await X(Fr(H));return{name:H.name,plan:G.plan,...H.joinKeys?{joinKeys:H.joinKeys}:{},...H.groupKeyShifts?{groupKeyShifts:H.groupKeyShifts}:{}}})),oe=Ir(B,F,U,B.outputName,u.provider,f);return{plan:U,compiled:oe,outputs:[B.outputName,...B.components.map(H=>H.name)]}}));return{compiled:no(C,U,u.provider,f),sources:Vt(C.map(({plan:B})=>de(B)))}},Q=ne?await Promise.all(ne.map(async O=>{if("logicform"in O)return{kind:"query",unit:O,...await X(O)};const U=await Promise.all(O.components.map(async C=>({name:C.name,prepared:await X(Fr(C)),...C.groupKeyShifts?{groupKeyShifts:C.groupKeyShifts}:{},...C.joinKeys?{joinKeys:C.joinKeys}:{}})));if("mergeRow"in O)return{kind:"js",unit:O,components:U.map(({prepared:C})=>C)};const M=U.map(({name:C,prepared:B,...F})=>({name:C,plan:B.plan,...F}));return{kind:"component",unit:O,plan:q,compiled:Ir(O,M,q,O.outputName,u.provider,f),sources:Vt(U.map(({prepared:C})=>C.sources))}})):void 0,w=Q&&yd(Q,m,q)?no(Q.map(O=>{const U=new Set(q.groupBy.map(({name:C})=>C));if(O.kind==="query")return{plan:O.plan,compiled:O.compiled,outputs:O.plan.projections.map(({name:C})=>C).filter(C=>!U.has(C))};const M=O.unit.outputName;if(!M)throw new p("INVALID_COMPONENT_PLAN","Component output projection is missing");return{plan:O.plan,compiled:O.compiled,outputs:[M,...O.unit.components.map(C=>C.name)]}}),q,u.provider,f):void 0,A=Q?void 0:await(async()=>{if(!q.sourcePlan||!q.sourceLogicform)return fe(q,u.provider,f);const O=await ce(q.sourceLogicform,q.sourcePlan),U={...q};delete U.sourcePlan,delete U.sourceLogicform;const M={...U,sourceSql:O.compiled.sql,source:q.source},C=fe(M,u.provider,f,O.compiled.parameters.length);return{sql:C.sql,parameters:[...O.compiled.parameters,...C.parameters]}})();if(w)$(w,"computation",V);else if(Q)for(const O of Q)if(O.kind==="js")for(const U of O.components)$(U.compiled,"computation",U.component.logicform);else $(O.compiled,"computation",V);else $(A,"computation",V);await E({stage:"compiled",sqls:[...R]},{sqls:[...R]}),await E({stage:"executing",provider:u.provider.kind});const I=w?await(async()=>{const O=await We(w,Vt([...Q.map(M=>M.sources),de(q)]),u);return await Tt(O,q.projections,f)})():Q?Bc(await Promise.all(Q.map(async O=>{if(O.kind==="js"){const C=await Promise.all(O.components.map(async B=>{const F=await We(B.compiled,B.sources,u),oe=await Tt(F,B.plan.projections,f);return B.component.mapResult?.(oe)??oe}));return Promise.all($o(C,q.groupBy.map(({name:B})=>B)).map(async B=>{const F=await O.unit.mergeRow(B);return{...B,[O.unit.outputName]:F}}))}const U=await We(O.compiled,O.sources,u),M=O.kind==="query"?await Tt(U,O.plan.projections,f):U;return O.kind==="query"?O.unit.mapResult?.(M)??M:M})),q):await(async()=>{const O=await We(A,de(q),u);return Tt(O,q.projections,f)})();await E({stage:"hydrating"});const b=await ku(I,re,{semanticTypes:l,resolveSchema:N,fetchEntities:O=>Ru(O,{version:V.version,operators:f,schemaMappings:m,semanticTypes:l,plugins:o,...u.locale?{locale:u.locale}:{},localeRegistry:n,resolveSchema:N,...u.permissions?{permissions:u.permissions}:{},provider:u.provider,...u.cache?{cache:u.cache}:{},...u.signal?{signal:u.signal}:{},onCompiled:(U,M)=>$(U,"semantic-resolution",M,"entity-expansion")})}),T=mo(b,q.rowIdentity);return await E({stage:"result",result:T},{result:T,sqls:[...R]}),await E({stage:"completed",durationMs:Wr.now()-d}),{result:T,schema:W,normedLogicform:V,sqls:[...R],lineage:Z,provider:u.provider.kind}}catch(D){const L=Xo(D);try{await E({stage:"failed",error:L})}catch{}throw L}},_d=async(e,t)=>{let r={};const n=t.locale??"zh-CN",o=yt(t.locales);try{if(t.connections.length===0)throw new p("DATABASE_CONNECTION_REQUIRED","At least one database connection is required");const i=new Map;for(const m of t.connections){if(m.id.trim().length===0)throw new p("INVALID_DATABASE_CONNECTION","Database connection id must not be empty");if(i.has(m.id))throw new p("DATABASE_CONNECTION_ALREADY_REGISTERED",`Database connection id is duplicated: ${m.id}`,{connectionId:m.id});i.set(m.id,m)}const s=new hr(t.schemaMappings),a=new Set;for(const m of $d(e))for(const y of s.list(m))a.add(y.connectionId);if(a.size>1)throw new p("CROSS_CONNECTION_QUERY_UNSUPPORTED",`One LogicForm cannot compile into SQL for multiple database connections: ${[...a].join(", ")}`,{connectionIds:[...a]});const[c]=a;if(!c)throw new p("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain at least one physical Schema leaf");const u=i.get(c);if(!u)throw new p("DATABASE_CONNECTION_NOT_FOUND",`Database connection is not registered: ${c}`,{connectionId:c});const d=nd(u);r={provider:d.kind};const l=Ie(t.plugins),f=t.operators===void 0?[]:Array.isArray(t.operators)?t.operators:[t.operators];for(const m of f)l.register(m);return await Ed(e,{...t,schemaMappings:s,locale:n,localeRegistry:o,provider:d,operators:l,connectionId:u.id,onProgress:async m=>{r=m.partialResult,await t.onProgress?.(m)}})}catch(i){return md(i,e,r,n,o)}},ri="semanticdb_calendar_dates",Hr="semanticdb_calendar_relations",qe={dates:"__sdb_calendar_dates",relations:"__sdb_calendar_relations"},Gr=e=>`${typeof e}:${String(e)}`,Sd=(e,t)=>{const r=typeof e=="number"?e:Number(e),n=typeof t=="number"?t:Number(t);return Number.isFinite(r)&&Number.isFinite(n)?r-n:String(e).localeCompare(String(t))},ni=(e,t,r)=>{const n=r.filter(c=>c.calendar===t.calendar&&c.grain===t.grain&&c.relation===t.relation&&(t.key===void 0||c.key===t.key)),o=new Map(n.map(c=>[Gr(c.sourceDateId),c])),i=e.flatMap(c=>{const u=o.get(Gr(c))?.targetDateId;return u==null?[]:[u]}),s=[...new Map(i.map(c=>[Gr(c),c])).values()].sort(Sd),a=[];for(const c of s){const u=a[a.length-1];if(u&&typeof u.end=="number"&&typeof c=="number"&&c===u.end+1)u.end=c;else if(u&&String(u.end).match(/^\d{8}$/)&&String(c).match(/^\d{8}$/)){const d=Number(u.end),l=Number(c),f=new Date(Date.UTC(Math.floor(d/1e4),Math.floor(d/100)%100-1,d%100));f.setUTCDate(f.getUTCDate()+1);const m=new Date(Date.UTC(Math.floor(l/1e4),Math.floor(l/100)%100-1,l%100));if(f.getTime()===m.getTime()){u.end=c;continue}a.push({start:c,end:c})}else a.push({start:c,end:c})}return{dateIds:s,ranges:a}},Id=async(e,t,r)=>ni(e,t,await r.loadRelations(e,t)),Rd=(e,t)=>e.filter(r=>Object.entries(t).every(([n,o])=>r[n]===o)).map(r=>r.dateId),Od=["source_date_id","target_date_id","calendar","grain","relation","relation_key"];class bd{provider;constructor(t){this.provider=t}async loadRelations(t,r){if(t.length===0)return[];const n=[...t,r.calendar,r.grain,r.relation];r.key!==void 0&&n.push(r.key);const o=t.map((u,d)=>this.provider.parameter(d,u)),i=u=>this.provider.parameter(u,n[u]),s=u=>this.provider.quoteIdentifier(u),a=[`${s("source_date_id")} IN (${o.join(", ")})`,`${s("calendar")} = ${i(t.length)}`,`${s("grain")} = ${i(t.length+1)}`,`${s("relation")} = ${i(t.length+2)}`];return r.key!==void 0&&a.push(`${s("relation_key")} = ${i(t.length+3)}`),(await this.provider.execute({sql:`SELECT ${Od.map(s).join(", ")} FROM ${s(Hr)} WHERE ${a.join(" AND ")}`,parameters:n})).map(u=>({sourceDateId:u.source_date_id,targetDateId:u.target_date_id,calendar:String(u.calendar),grain:String(u.grain),relation:String(u.relation),...typeof u.relation_key=="string"||typeof u.relation_key=="number"?{key:String(u.relation_key)}:{}}))}}const Nd={[qe.dates]:{id:qe.dates,name:qe.dates,type:"entity",source:ri,properties:[{id:"date_id",name:"date_id",type:"id",primal_type:"string"},{id:"calendar",name:"calendar",type:"string",primal_type:"string"},{id:"grain",name:"grain",type:"string",primal_type:"string"},{id:"period_key",name:"period_key",type:"string",primal_type:"string"},{id:"relative_day",name:"relative_day",type:"int",primal_type:"number"}]},[qe.relations]:{id:qe.relations,name:qe.relations,type:"entity",source:Hr,properties:[{id:"source_date_id",name:"source_date_id",type:"string",primal_type:"string"},{id:"target_date_id",name:"target_date_id",type:"string",primal_type:"string"},{id:"calendar",name:"calendar",type:"string",primal_type:"string"},{id:"grain",name:"grain",type:"string",primal_type:"string"},{id:"relation",name:"relation",type:"string",primal_type:"string"},{id:"relation_key",name:"relation_key",type:"string",primal_type:"string"}]}},Pd=Object.freeze({execute:_d,close:od});export{ri as CALENDAR_DATES_TABLE,Hr as CALENDAR_RELATIONS_TABLE,qe as CALENDAR_SYSTEM_SCHEMA_IDS,Kt as LocaleRegistry,Pd as Logicform,qn as OperatorRegistry,Fn as PlannerSemanticRegistry,bd as ProviderCalendarRelationStore,hr as SchemaMappingRegistry,p as SemanticDBError,So as SemanticTypeRegistry,ka as builtinOperators,yr as builtinSemanticTypes,Nd as calendarSystemSchemas,yt as createLocaleRegistry,Ie as createOperatorRegistry,Yn as createPlannerSemanticRegistry,Po as createSemanticTypeRegistry,ht as defaultLocaleRegistry,mn as enUS,Ba as fromYiAskSchemaMapping,ni as resolveCalendarPeriod,Id as resolveCalendarPeriodFromStore,Cn as resolveOperator,Oo as resolveSchema,Rd as selectCalendarDates,Io as validateResolvedSchema,yn as zhCN};
|
|
1
|
+
import{performance as Xr}from"node:perf_hooks";import ue from"dayjs";import Mt from"dayjs/plugin/isoWeek.js";import ar from"dayjs/plugin/quarterOfYear.js";import Do from"dayjs/plugin/customParseFormat.js";import{randomUUID as Co}from"node:crypto";import{getNameProperty as wa}from"semanticdb-core";import{isDeepStrictEqual as Ea}from"node:util";import{DuckDBInstance as _a,VARCHAR as mt,DOUBLE as ko,TIMESTAMP as Zr,BOOLEAN as Uo,jsToDuckDBValue as Be,blobValue as Sa}from"@duckdb/node-api";const V=t=>typeof t=="string",qt=()=>{let t,e;const r=new Promise((n,o)=>{t=n,e=o});return r.resolve=t,r.reject=e,r},Mo=t=>t==null?"":""+t,Ia=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},ba=/###/g,qo=t=>t&&t.indexOf("###")>-1?t.replace(ba,"."):t,jo=t=>!t||V(t),jt=(t,e,r)=>{const n=V(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if(jo(t))return{};const i=qo(n[o]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++o}return jo(t)?{}:{obj:t,k:qo(n[o])}},xo=(t,e,r)=>{const{obj:n,k:o}=jt(t,e,Object);if(n!==void 0||e.length===1){n[o]=r;return}let i=e[e.length-1],s=e.slice(0,e.length-1),a=jt(t,s,Object);for(;a.obj===void 0&&s.length;)i=`${s[s.length-1]}.${i}`,s=s.slice(0,s.length-1),a=jt(t,s,Object),a?.obj&&typeof a.obj[`${a.k}.${i}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${i}`]=r},Ra=(t,e,r,n)=>{const{obj:o,k:i}=jt(t,e,Object);o[i]=o[i]||[],o[i].push(r)},cr=(t,e)=>{const{obj:r,k:n}=jt(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},Na=(t,e,r)=>{const n=cr(t,r);return n!==void 0?n:cr(e,r)},Bo=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(n in t?V(t[n])||t[n]instanceof String||V(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):Bo(t[n],e[n],r):t[n]=e[n]);return t},Ze=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Oa={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const Ta=t=>V(t)?t.replace(/[&<>"'\/]/g,e=>Oa[e]):t;class Pa{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 La=[" ",",","?","!",";"],Da=new Pa(20),Ca=(t,e,r)=>{e=e||"",r=r||"";const n=La.filter(s=>e.indexOf(s)<0&&r.indexOf(s)<0);if(n.length===0)return!0;const o=Da.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},en=(t,e,r=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const n=e.split(r);let o=t;for(let i=0;i<n.length;){if(!o||typeof o!="object")return;let s,a="";for(let u=i;u<n.length;++u)if(u!==i&&(a+=r),a+=n[u],s=o[a],s!==void 0){if(["string","number","boolean"].indexOf(typeof s)>-1&&u<n.length-1)continue;i+=u-i+1;break}o=s}return o},xt=t=>t?.replace(/_/g,"-"),ka={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class Wr{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||ka,this.options=r,this.debug=r.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,r,n,o){return o&&!this.debug?null:(V(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new Wr(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Wr(this.logger,e)}}var ke=new Wr;class ur{constructor(){this.observers={}}on(e,r){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const o=this.observers[n].get(r)||0;this.observers[n].set(r,o+1)}),this}off(e,r){if(this.observers[e]){if(!r){delete this.observers[e];return}this.observers[e].delete(r)}}emit(e,...r){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([o,i])=>{for(let s=0;s<i;s++)o(...r)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([o,i])=>{for(let s=0;s<i;s++)o.apply(o,[e,...r])})}}class Vo extends ur{constructor(e,r={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const r=this.options.ns.indexOf(e);r>-1&&this.options.ns.splice(r,1)}getResource(e,r,n,o={}){const i=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,s=o.ignoreJSONStructure!==void 0?o.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.indexOf(".")>-1?a=e.split("."):(a=[e,r],n&&(Array.isArray(n)?a.push(...n):V(n)&&i?a.push(...n.split(i)):a.push(n)));const u=cr(this.data,a);return!u&&!r&&!n&&e.indexOf(".")>-1&&(e=a[0],r=a[1],n=a.slice(2).join(".")),u||!s||!V(n)?u:en(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),xo(this.data,a,o),i.silent||this.emit("added",e,r,n,o)}addResources(e,r,n,o={silent:!1}){for(const i in n)(V(n[i])||Array.isArray(n[i]))&&this.addResource(e,r,i,n[i],{silent:!0});o.silent||this.emit("added",e,r,n)}addResourceBundle(e,r,n,o,i,s={silent:!1,skipCopy:!1}){let a=[e,r];e.indexOf(".")>-1&&(a=e.split("."),o=n,n=r,r=a[1]),this.addNamespaces(r);let u=cr(this.data,a)||{};s.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?Bo(u,n,i):u={...u,...n},xo(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 vo={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 Fo=Symbol("i18next/PATH_KEY");function Ua(){const t=[],e=Object.create(null);let r;return e.get=(n,o)=>(r?.revoke?.(),o===Fo?t:(t.push(o),r=Proxy.revocable(n,e),r.proxy)),Proxy.revocable(Object.create(null),e).proxy}function yt(t,e){const{[Fo]:r}=t(Ua()),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 Yo={},tn=t=>!V(t)&&typeof t!="boolean"&&typeof t!="number";class zr extends ur{constructor(e,r={}){super(),Ia(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=ke.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&&!Ca(e,n,o);if(s&&!a){const u=e.match(this.interpolator.nestingRegexp);if(u&&u.length>0)return{key:e,namespaces:V(i)?[i]:i};const c=e.split(n);(n!==o||n===o&&this.options.ns.indexOf(c[0])>-1)&&(i=c.shift()),e=c.join(o)}return{key:e,namespaces:V(i)?[i]:i}}translate(e,r,n){let o=typeof r=="object"?{...r}:r;if(typeof o!="object"&&this.options.overloadTranslationOptionHandler&&(o=this.options.overloadTranslationOptionHandler(arguments)),typeof o=="object"&&(o={...o}),o||(o={}),e==null)return"";typeof e=="function"&&(e=yt(e,{...this.options,...o})),Array.isArray(e)||(e=[String(e)]),e=e.map(k=>typeof k=="function"?yt(k,{...this.options,...o}):String(k));const i=o.returnDetails!==void 0?o.returnDetails:this.options.returnDetails,s=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,{key:a,namespaces:u}=this.extractFromKey(e[e.length-1],o),c=u[u.length-1];let p=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;p===void 0&&(p=":");const l=o.lng||this.language,f=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l?.toLowerCase()==="cimode")return f?i?{res:`${c}${p}${a}`,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:`${c}${p}${a}`:i?{res:a,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:c,usedParams:this.getUsedParamsDetails(o)}:a;const m=this.resolve(e,o);let y=m?.res;const h=m?.usedKey||a,g=m?.exactUsedKey||a,A=["[object Number]","[object Function]","[object RegExp]"],w=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,E=o.count!==void 0&&!V(o.count),$=zr.hasDefaultValue(o),R=E?this.pluralResolver.getSuffix(l,o.count,o):"",O=o.ordinal&&E?this.pluralResolver.getSuffix(l,o.count,{ordinal:!1}):"",D=E&&!o.ordinal&&o.count===0,M=D&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${R}`]||o[`defaultValue${O}`]||o.defaultValue;let z=y;S&&!y&&$&&(z=M);const q=tn(z),v=Object.prototype.toString.apply(z);if(S&&z&&q&&A.indexOf(v)<0&&!(V(w)&&Array.isArray(z))){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const k=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,z,{...o,ns:u}):`key '${a} (${this.language})' returned an object instead of string.`;return i?(m.res=k,m.usedParams=this.getUsedParamsDetails(o),m):k}if(s){const k=Array.isArray(z),H=k?[]:{},ae=k?g:h;for(const te in z)if(Object.prototype.hasOwnProperty.call(z,te)){const fe=`${ae}${s}${te}`;$&&!y?H[te]=this.translate(fe,{...o,defaultValue:tn(M)?M[te]:void 0,joinArrays:!1,ns:u}):H[te]=this.translate(fe,{...o,joinArrays:!1,ns:u}),H[te]===fe&&(H[te]=z[te])}y=H}}else if(S&&V(w)&&Array.isArray(y))y=y.join(w),y&&(y=this.extendTranslation(y,e,o,n));else{let k=!1,H=!1;!this.isValidLookup(y)&&$&&(k=!0,y=M),this.isValidLookup(y)||(H=!0,y=a);const te=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&H?void 0:y,fe=$&&M!==y&&this.options.updateMissing;if(H||k||fe){if(this.logger.log(fe?"updateKey":"missingKey",l,c,a,fe?M:y),s){const j=this.resolve(a,{...o,keySeparator:!1});j&&j.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let C=[];const F=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&F&&F[0])for(let j=0;j<F.length;j++)C.push(F[j]);else this.options.saveMissingTo==="all"?C=this.languageUtils.toResolveHierarchy(o.lng||this.language):C.push(o.lng||this.language);const Z=(j,le,_)=>{const I=$&&_!==y?_:te;this.options.missingKeyHandler?this.options.missingKeyHandler(j,c,le,I,fe,o):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(j,c,le,I,fe,o),this.emit("missingKey",j,c,le,y)};this.options.saveMissing&&(this.options.saveMissingPlurals&&E?C.forEach(j=>{const le=this.pluralResolver.getSuffixes(j,o);D&&o[`defaultValue${this.options.pluralSeparator}zero`]&&le.indexOf(`${this.options.pluralSeparator}zero`)<0&&le.push(`${this.options.pluralSeparator}zero`),le.forEach(_=>{Z([j],a+_,o[`defaultValue${_}`]||M)})}):Z(C,a,M))}y=this.extendTranslation(y,e,o,m,n),H&&y===a&&this.options.appendNamespaceToMissingKey&&(y=`${c}${p}${a}`),(H||k)&&this.options.parseMissingKeyHandler&&(y=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${p}${a}`:a,k?y:void 0,o))}return i?(m.res=y,m.usedParams=this.getUsedParamsDetails(o),m):y}extendTranslation(e,r,n,o,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||o.usedLng,o.usedNS,o.usedKey,{resolved:o});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const u=V(e)&&(n?.interpolation?.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let c;if(u){const l=e.match(this.interpolator.nestingRegexp);c=l&&l.length}let p=n.replace&&!V(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),e=this.interpolator.interpolate(e,p,n.lng||this.language||o.usedLng,n),u){const l=e.match(this.interpolator.nestingRegexp),f=l&&l.length;c<f&&(n.nest=!1)}!n.lng&&o&&o.res&&(n.lng=this.language||o.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...l)=>i?.[0]===l[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${l[0]} in key: ${r[0]}`),null):this.translate(...l,r),n)),n.interpolation&&this.interpolator.reset()}const s=n.postProcess||this.options.postProcess,a=V(s)?[s]:s;return e!=null&&a?.length&&n.applyPostProcessor!==!1&&(e=vo.handle(a,e,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...o,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,r={}){let n,o,i,s,a;return V(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(u=>typeof u=="function"?yt(u,{...this.options,...r}):u)),e.forEach(u=>{if(this.isValidLookup(n))return;const c=this.extractFromKey(u,r),p=c.key;o=p;let l=c.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));const f=r.count!==void 0&&!V(r.count),m=f&&!r.ordinal&&r.count===0,y=r.context!==void 0&&(V(r.context)||typeof r.context=="number")&&r.context!=="",h=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);l.forEach(g=>{this.isValidLookup(n)||(a=g,!Yo[`${h[0]}-${g}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(Yo[`${h[0]}-${g}`]=!0,this.logger.warn(`key "${o}" for languages "${h.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),h.forEach(A=>{if(this.isValidLookup(n))return;s=A;const w=[p];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(w,p,A,g,r);else{let E;f&&(E=this.pluralResolver.getSuffix(A,r.count,r));const $=`${this.options.pluralSeparator}zero`,R=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(r.ordinal&&E.indexOf(R)===0&&w.push(p+E.replace(R,this.options.pluralSeparator)),w.push(p+E),m&&w.push(p+$)),y){const O=`${p}${this.options.contextSeparator||"_"}${r.context}`;w.push(O),f&&(r.ordinal&&E.indexOf(R)===0&&w.push(O+E.replace(R,this.options.pluralSeparator)),w.push(O+E),m&&w.push(O+$))}}let S;for(;S=w.pop();)this.isValidLookup(n)||(i=S,n=this.getResource(A,g,S,r))}))})}),{res:n,usedKey:o,exactUsedKey:i,usedLng:s,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,r,n,o={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,r,n,o):this.resourceStore.getResource(e,r,n,o)}getUsedParamsDetails(e={}){const r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!V(e.replace);let o=n?e.replace:e;if(n&&typeof e.count<"u"&&(o.count=e.count),this.options.interpolation.defaultVariables&&(o={...this.options.interpolation.defaultVariables,...o}),!n){o={...o};for(const i of r)delete o[i]}return o}static hasDefaultValue(e){const r="defaultValue";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&r===n.substring(0,r.length)&&e[n]!==void 0)return!0;return!1}}class Ho{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=ke.create("languageUtils")}getScriptPartFromCode(e){if(e=xt(e),!e||e.indexOf("-")<0)return null;const r=e.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}getLanguagePartFromCode(e){if(e=xt(e),!e||e.indexOf("-")<0)return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(V(e)&&e.indexOf("-")>-1){let r;try{r=Intl.getCanonicalLocales(e)[0]}catch{}return r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let r;return e.forEach(n=>{if(r)return;const o=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(o))&&(r=o)}),!r&&this.options.supportedLngs&&e.forEach(n=>{if(r)return;const o=this.getScriptPartFromCode(n);if(this.isSupportedCode(o))return r=o;const i=this.getLanguagePartFromCode(n);if(this.isSupportedCode(i))return r=i;r=this.options.supportedLngs.find(s=>{if(s===i)return s;if(!(s.indexOf("-")<0&&i.indexOf("-")<0)&&(s.indexOf("-")>0&&i.indexOf("-")<0&&s.substring(0,s.indexOf("-"))===i||s.indexOf(i)===0&&i.length>1))return s})}),r||(r=this.getFallbackCodes(this.options.fallbackLng)[0]),r}getFallbackCodes(e,r){if(!e)return[];if(typeof e=="function"&&(e=e(r)),V(e)&&(e=[e]),Array.isArray(e))return e;if(!r)return e.default||[];let n=e[r];return n||(n=e[this.getScriptPartFromCode(r)]),n||(n=e[this.formatLanguageCode(r)]),n||(n=e[this.getLanguagePartFromCode(r)]),n||(n=e.default),n||[]}toResolveHierarchy(e,r){const n=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],e),o=[],i=s=>{s&&(this.isSupportedCode(s)?o.push(s):this.logger.warn(`rejecting language code not found in supportedLngs: ${s}`))};return V(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&i(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&i(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&i(this.getLanguagePartFromCode(e))):V(e)&&i(this.formatLanguageCode(e)),n.forEach(s=>{o.indexOf(s)<0&&i(this.formatLanguageCode(s))}),o}}const Qo={zero:0,one:1,two:2,few:3,many:4,other:5},Go={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Ma{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=ke.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=xt(e==="dev"?"en":e),o=r.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:n,type:o});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let s;try{s=new Intl.PluralRules(n,{type:o})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Go;if(!e.match(/-|_/))return Go;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)=>Qo[o]-Qo[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 Wo=(t,e,r,n=".",o=!0)=>{let i=Na(t,e,r);return!i&&o&&V(r)&&(i=en(t,r,n),i===void 0&&(i=en(e,r,n))),i},rn=t=>t.replace(/\$/g,"$$$$");class zo{constructor(e={}){this.logger=ke.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(r=>r),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:r,escapeValue:n,useRawValueToEscape:o,prefix:i,prefixEscaped:s,suffix:a,suffixEscaped:u,formatSeparator:c,unescapeSuffix:p,unescapePrefix:l,nestingPrefix:f,nestingPrefixEscaped:m,nestingSuffix:y,nestingSuffixEscaped:h,nestingOptionsSeparator:g,maxReplaces:A,alwaysFormat:w}=e.interpolation;this.escape=r!==void 0?r:Ta,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=i?Ze(i):s||"{{",this.suffix=a?Ze(a):u||"}}",this.formatSeparator=c||",",this.unescapePrefix=p?"":l||"-",this.unescapeSuffix=this.unescapePrefix?"":p||"",this.nestingPrefix=f?Ze(f):m||Ze("$t("),this.nestingSuffix=y?Ze(y):h||Ze(")"),this.nestingOptionsSeparator=g||",",this.maxReplaces=A||1e3,this.alwaysFormat=w!==void 0?w:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(r,n)=>r?.source===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,r,n,o){let i,s,a;const u=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=m=>{if(m.indexOf(this.formatSeparator)<0){const A=Wo(r,u,m,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(A,void 0,n,{...o,...r,interpolationkey:m}):A}const y=m.split(this.formatSeparator),h=y.shift().trim(),g=y.join(this.formatSeparator).trim();return this.format(Wo(r,u,h,this.options.keySeparator,this.options.ignoreJSONStructure),g,n,{...o,...r,interpolationkey:h})};this.resetRegExp();const p=o?.missingInterpolationHandler||this.options.missingInterpolationHandler,l=o?.interpolation?.skipOnVariables!==void 0?o.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:m=>rn(m)},{regex:this.regexp,safeValue:m=>this.escapeValue?rn(this.escape(m)):rn(m)}].forEach(m=>{for(a=0;i=m.regex.exec(e);){const y=i[1].trim();if(s=c(y),s===void 0)if(typeof p=="function"){const g=p(e,i,o);s=V(g)?g:""}else if(o&&Object.prototype.hasOwnProperty.call(o,y))s="";else if(l){s=i[0];continue}else this.logger.warn(`missed to pass in variable ${y} for interpolating ${e}`),s="";else!V(s)&&!this.useRawValueToEscape&&(s=Mo(s));const h=m.safeValue(s);if(e=e.replace(i[0],h),l?(m.regex.lastIndex+=s.length,m.regex.lastIndex-=i[0].length):m.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,r,n={}){let o,i,s;const a=(u,c)=>{const p=this.nestingOptionsSeparator;if(u.indexOf(p)<0)return u;const l=u.split(new RegExp(`${Ze(p)}[ ]*{`));let f=`{${l[1]}`;u=l[0],f=this.interpolate(f,s);const m=f.match(/'/g),y=f.match(/"/g);((m?.length??0)%2===0&&!y||(y?.length??0)%2!==0)&&(f=f.replace(/'/g,'"'));try{s=JSON.parse(f),c&&(s={...c,...s})}catch(h){return this.logger.warn(`failed parsing options string in nesting for key ${u}`,h),`${u}${p}${f}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,u};for(;o=this.nestingRegexp.exec(e);){let u=[];s={...n},s=s.replace&&!V(s.replace)?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;const c=/{.*}/.test(o[1])?o[1].lastIndexOf("}")+1:o[1].indexOf(this.formatSeparator);if(c!==-1&&(u=o[1].slice(c).split(this.formatSeparator).map(p=>p.trim()).filter(Boolean),o[1]=o[1].slice(0,c)),i=r(a.call(this,o[1].trim(),s),s),i&&o[0]===e&&!V(i))return i;V(i)||(i=Mo(i)),i||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${e}`),i=""),u.length&&(i=u.reduce((p,l)=>this.format(p,l,n.lng,{...n,interpolationkey:o[1].trim()}),i.trim())),e=e.replace(o[0],i),this.regexp.lastIndex=0}return e}}const qa=t=>{let e=t.toLowerCase().trim();const r={};if(t.indexOf("(")>-1){const n=t.split("(");e=n[0].toLowerCase().trim();const o=n[1].substring(0,n[1].length-1);e==="currency"&&o.indexOf(":")<0?r.currency||(r.currency=o.trim()):e==="relativetime"&&o.indexOf(":")<0?r.range||(r.range=o.trim()):o.split(";").forEach(s=>{if(s){const[a,...u]=s.split(":"),c=u.join(":").trim().replace(/^'+|'+$/g,""),p=a.trim();r[p]||(r[p]=c),c==="false"&&(r[p]=!1),c==="true"&&(r[p]=!0),isNaN(c)||(r[p]=parseInt(c,10))}})}return{formatName:e,formatOptions:r}},Ko=t=>{const e={};return(r,n,o)=>{let i=o;o&&o.interpolationkey&&o.formatParams&&o.formatParams[o.interpolationkey]&&o[o.interpolationkey]&&(i={...i,[o.interpolationkey]:void 0});const s=n+JSON.stringify(i);let a=e[s];return a||(a=t(xt(n),o),e[s]=a),a(r)}},ja=t=>(e,r,n)=>t(xt(r),n)(e);class xa{constructor(e={}){this.logger=ke.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?Ko:ja;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()]=Ko(r)}format(e,r,n,o={}){const i=r.split(this.formatSeparator);if(i.length>1&&i[0].indexOf("(")>1&&i[0].indexOf(")")<0&&i.find(a=>a.indexOf(")")>-1)){const a=i.findIndex(u=>u.indexOf(")")>-1);i[0]=[i[0],...i.splice(1,a)].join(this.formatSeparator)}return i.reduce((a,u)=>{const{formatName:c,formatOptions:p}=qa(u);if(this.formats[c]){let l=a;try{const f=o?.formatParams?.[o.interpolationkey]||{},m=f.locale||f.lng||o.locale||o.lng||n;l=this.formats[c](a,m,{...p,...o,...f})}catch(f){this.logger.warn(f)}return l}else this.logger.warn(`there was no format function for ${c}`);return a},e)}}const Ba=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Va extends ur{constructor(e,r,n,o={}){super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=ke.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=o.maxParallelReads||10,this.readingCalls=0,this.maxRetries=o.maxRetries>=0?o.maxRetries:5,this.retryTimeout=o.retryTimeout>=1?o.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,o.backend,o)}queueLoad(e,r,n,o){const i={},s={},a={},u={};return e.forEach(c=>{let p=!0;r.forEach(l=>{const f=`${c}|${l}`;!n.reload&&this.store.hasResourceBundle(c,l)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?s[f]===void 0&&(s[f]=!0):(this.state[f]=1,p=!1,s[f]===void 0&&(s[f]=!0),i[f]===void 0&&(i[f]=!0),u[l]===void 0&&(u[l]=!0)))}),p||(a[c]=!0)}),(Object.keys(i).length||Object.keys(s).length)&&this.queue.push({pending:s,pendingCount:Object.keys(s).length,loaded:{},errors:[],callback:o}),{toLoad:Object.keys(i),pending:Object.keys(s),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(u)}}loaded(e,r,n){const o=e.split("|"),i=o[0],s=o[1];r&&this.emit("failedLoading",i,s,r),!r&&n&&this.store.addResourceBundle(i,s,n,void 0,void 0,{skipCopy:!0}),this.state[e]=r?-1:2,r&&n&&(this.state[e]=0);const a={};this.queue.forEach(u=>{Ra(u.loaded,[i],s),Ba(u,e),r&&u.errors.push(r),u.pendingCount===0&&!u.done&&(Object.keys(u.loaded).forEach(c=>{a[c]||(a[c]={});const p=u.loaded[c];p.length&&p.forEach(l=>{a[c][l]===void 0&&(a[c][l]=!0)})}),u.done=!0,u.errors.length?u.callback(u.errors):u.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(u=>!u.done)}read(e,r,n,o=0,i=this.retryTimeout,s){if(!e.length)return s(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:r,fcName:n,tried:o,wait:i,callback:s});return}this.readingCalls++;const a=(c,p)=>{if(this.readingCalls--,this.waitingReads.length>0){const l=this.waitingReads.shift();this.read(l.lng,l.ns,l.fcName,l.tried,l.wait,l.callback)}if(c&&p&&o<this.maxRetries){setTimeout(()=>{this.read.call(this,e,r,n,o+1,i*2,s)},i);return}s(c,p)},u=this.backend[n].bind(this.backend);if(u.length===2){try{const c=u(e,r);c&&typeof c.then=="function"?c.then(p=>a(null,p)).catch(a):a(null,c)}catch(c){a(c)}return}return u(e,r,a)}prepareLoading(e,r,n={},o){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),o&&o();V(e)&&(e=this.languageUtils.toResolveHierarchy(e)),V(r)&&(r=[r]);const i=this.queueLoad(e,r,n,o);if(!i.toLoad.length)return i.pending.length||o(),null;i.toLoad.forEach(s=>{this.loadOne(s)})}load(e,r,n){this.prepareLoading(e,r,{},n)}reload(e,r,n){this.prepareLoading(e,r,{reload:!0},n)}loadOne(e,r=""){const n=e.split("|"),o=n[0],i=n[1];this.read(o,i,"read",void 0,void 0,(s,a)=>{s&&this.logger.warn(`${r}loading namespace ${i} for language ${o} failed`,s),!s&&a&&this.logger.log(`${r}loaded namespace ${i} for language ${o}`,a),this.loaded(e,s,a)})}saveMissing(e,r,n,o,i,s={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(r)){this.logger.warn(`did not save key "${n}" as the namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if(this.backend?.create){const u={...s,isUpdate:i},c=this.backend.create.bind(this.backend);if(c.length<6)try{let p;c.length===5?p=c(e,r,n,o,u):p=c(e,r,n,o),p&&typeof p.then=="function"?p.then(l=>a(null,l)).catch(a):a(null,p)}catch(p){a(p)}else c(e,r,n,o,a,u)}!e||!e[0]||this.store.addResource(e[0],r,n,o)}}}const nn=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),V(t[1])&&(e.defaultValue=t[1]),V(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const r=t[3]||t[2];Object.keys(r).forEach(n=>{e[n]=r[n]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),Jo=t=>(V(t.ns)&&(t.ns=[t.ns]),V(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),V(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs?.indexOf?.("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),typeof t.initImmediate=="boolean"&&(t.initAsync=t.initImmediate),t),dr=()=>{},va=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})},Xo="__i18next_supportNoticeShown",Fa=()=>!!(typeof globalThis<"u"&&globalThis[Xo]||typeof process<"u"&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&process.env&&process.env.NODE_ENV==="production"),Ya=()=>{typeof globalThis<"u"&&(globalThis[Xo]=!0)},Ha=t=>!!(t?.modules?.backend?.name?.indexOf("Locize")>0||t?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||t?.options?.backend?.backends&&t.options.backend.backends.some(e=>e?.name?.indexOf("Locize")>0||e?.constructor?.name?.indexOf("Locize")>0)||t?.options?.backend?.projectId||t?.options?.backend?.backendOptions&&t.options.backend.backendOptions.some(e=>e?.projectId));class sr extends ur{constructor(e={},r){if(super(),this.options=Jo(e),this.services={},this.logger=ke,this.modules={external:[]},va(this),r&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,r),this;setTimeout(()=>{this.init(e,r)},0)}}init(e={},r){this.isInitializing=!0,typeof e=="function"&&(r=e,e={}),e.defaultNS==null&&e.ns&&(V(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const n=nn();this.options={...n,...this.options,...Jo(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&&!Ha(this)&&!Fa()&&(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}"),Ya());const o=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?ke.init(o(this.modules.logger),this.options):ke.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=xa;const p=new Ho(this.options);this.store=new Vo(this.options.resources,this.options);const l=this.services;l.logger=ke,l.resourceStore=this.store,l.languageUtils=p,l.pluralResolver=new Ma(p,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),c&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(l.formatter=o(c),l.formatter.init&&l.formatter.init(l,this.options),this.options.interpolation.format=l.formatter.format.bind(l.formatter)),l.interpolator=new zo(this.options),l.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},l.backendConnector=new Va(o(this.modules.backend),l.resourceStore,l,this.options),l.backendConnector.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.languageDetector&&(l.languageDetector=o(this.modules.languageDetector),l.languageDetector.init&&l.languageDetector.init(l,this.options.detection,this.options)),this.modules.i18nFormat&&(l.i18nFormat=o(this.modules.i18nFormat),l.i18nFormat.init&&l.i18nFormat.init(this)),this.translator=new zr(this.services,this.options),this.translator.on("*",(m,...y)=>{this.emit(m,...y)}),this.modules.external.forEach(m=>{m.init&&m.init(this)})}if(this.format=this.options.interpolation.format,r||(r=dr),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...p)=>this.store[c](...p)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...p)=>(this.store[c](...p),this)});const a=qt(),u=()=>{const c=(p,l)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(l),r(p,l)};if(this.languages&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?u():setTimeout(u,0),a}loadResources(e,r=dr){let n=r;const o=V(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(o?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const i=[],s=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(c=>{c!=="cimode"&&i.indexOf(c)<0&&i.push(c)})};o?s(o):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>s(u)),this.options.preload?.forEach?.(a=>s(a)),this.services.backendConnector.load(i,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(a)})}else n(null)}reloadResources(e,r,n){const o=qt();return typeof e=="function"&&(n=e,e=void 0),typeof r=="function"&&(n=r,r=void 0),e||(e=this.languages),r||(r=this.options.ns),n||(n=dr),this.services.backendConnector.reload(e,r,i=>{o.resolve(),n(i)}),o}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&vo.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-1)){for(let r=0;r<this.languages.length;r++){const n=this.languages[r];if(!(["cimode","dev"].indexOf(n)>-1)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,r){this.isLanguageChangingTo=e;const n=qt();this.emit("languageChanging",e);const o=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},i=(a,u)=>{u?this.isLanguageChangingTo===e&&(o(u),this.translator.changeLanguage(u),this.isLanguageChangingTo=void 0,this.emit("languageChanged",u),this.logger.log("languageChanged",u)):this.isLanguageChangingTo=void 0,n.resolve((...c)=>this.t(...c)),r&&r(a,(...c)=>this.t(...c))},s=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const u=V(a)?a:a&&a[0],c=this.store.hasLanguageSomeTranslations(u)?u:this.services.languageUtils.getBestMatchFromCodes(V(a)?[a]:a);c&&(this.language||o(c),this.translator.language||this.translator.changeLanguage(c),this.services.languageDetector?.cacheUserLanguage?.(c)),this.loadResources(c,p=>{i(p,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?s(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(s):this.services.languageDetector.detect(s):s(e),n}getFixedT(e,r,n){const o=(i,s,...a)=>{let u;typeof s!="object"?u=this.options.overloadTranslationOptionHandler([i,s].concat(a)):u={...s},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs,u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||n||o.keyPrefix);const c={...this.options,...u};typeof u.keyPrefix=="function"&&(u.keyPrefix=yt(u.keyPrefix,c));const p=this.options.keySeparator||".";let l;return u.keyPrefix&&Array.isArray(i)?l=i.map(f=>(typeof f=="function"&&(f=yt(f,c)),`${u.keyPrefix}${p}${f}`)):(typeof i=="function"&&(i=yt(i,c)),l=u.keyPrefix?`${u.keyPrefix}${p}${i}`:i),this.t(l,u)};return V(e)?o.lng=e:o.lngs=e,o.ns=r,o.keyPrefix=n,o}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,r={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=r.lng||this.resolvedLanguage||this.languages[0],o=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const s=(a,u)=>{const c=this.services.backendConnector.state[`${a}|${u}`];return c===-1||c===0||c===2};if(r.precheck){const a=r.precheck(this,s);if(a!==void 0)return a}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||s(n,e)&&(!o||s(i,e)))}loadNamespaces(e,r){const n=qt();return this.options.ns?(V(e)&&(e=[e]),e.forEach(o=>{this.options.ns.indexOf(o)<0&&this.options.ns.push(o)}),this.loadResources(o=>{n.resolve(),r&&r(o)}),n):(r&&r(),Promise.resolve())}loadLanguages(e,r){const n=qt();V(e)&&(e=[e]);const o=this.options.preload||[],i=e.filter(s=>o.indexOf(s)<0&&this.services.languageUtils.isSupportedCode(s));return i.length?(this.options.preload=o.concat(i),this.loadResources(s=>{n.resolve(),r&&r(s)}),n):(r&&r(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const o=new Intl.Locale(e);if(o&&o.getTextInfo){const i=o.getTextInfo();if(i&&i.direction)return i.direction}}catch{}const r=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=this.services?.languageUtils||new Ho(nn());return e.toLowerCase().indexOf("-latn")>1?"ltr":r.indexOf(n.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},r){const n=new sr(e,r);return n.createInstance=sr.createInstance,n}cloneInstance(e={},r=dr){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const o={...this.options,...e,isClone:!0},i=new sr(o);if((e.debug!==void 0||e.prefix!==void 0)&&(i.logger=i.logger.clone(e)),["store","services","language"].forEach(a=>{i[a]=this[a]}),i.services={...this.services},i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},n){const a=Object.keys(this.store.data).reduce((u,c)=>(u[c]={...this.store.data[c]},u[c]=Object.keys(u[c]).reduce((p,l)=>(p[l]={...u[c][l]},p),u[c]),u),{});i.store=new Vo(a,o),i.services.resourceStore=i.store}if(e.interpolation){const u={...nn().interpolation,...this.options.interpolation,...e.interpolation},c={...o,interpolation:u};i.services.interpolator=new zo(c)}return i.translator=new zr(i.services,o),i.translator.on("*",(a,...u)=>{i.emit(a,...u)}),i.init(o,r),i.translator.options=o,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const _e=sr.createInstance(),Qa=_e.createInstance;_e.dir,_e.init,_e.loadResources,_e.reloadResources,_e.use,_e.changeLanguage,_e.getFixedT,_e.t,_e.exists,_e.setDefaultNamespace,_e.hasLoadedNamespace,_e.loadNamespaces,_e.loadLanguages;const Zo={locale:"en-US",messages:{"operator.rows":"rows","operator.$sum":"Total {operandName}","operator.$avg":"Average {operandName}","operator.$min":"Minimum {operandName}","operator.$max":"Maximum {operandName}","operator.$count":"{operandName} count","operator.$count.rows":"Row count","operator.$countDistinct":"Distinct {operandName} count","operator.$add":"{inputNames}","operator.$add.empty":"Sum of {operandName}","operator.$subtract":"{input0} minus {input1}","operator.$subtract.fallback":"{operandName} difference","operator.$multiply":"{inputNames}","operator.$multiply.empty":"Product of {operandName}","operator.$divide":"{input0} divided by {input1}","operator.$divide.fallback":"{operandName} ratio","operator.$concat":"Combined {inputNames}","operator.$concat.empty":"Combined {operandName}","operator.$abs":"Absolute {operandName}","operator.$substring":"{operandName} substring","operator.$case":"{operandName} category","operator.$constant":"Constant","operator.$sql":"Calculated value","operator.$rowNumber":"Row number","operator.$rank":"{operandName} rank","operator.$accumulate":"Cumulative {operandName}","operator.$least":"Least of {inputNames}","operator.$greatest":"Greatest of {inputNames}","operator.$dateBucket":"{operandName} by {granularity}","operator.$periodBoundary.start":"{operandName} at period start","operator.$periodBoundary.end":"{operandName} at period end","operator.$periodValue.start":"{operandName} at period start","operator.$periodValue.end":"{operandName} at period end","operator.$periodShift":"{operandName} {comparison} baseline","operator.$periodGrowth":"{operandName} {comparison} growth","operator.$periodDifference":"{operandName} {comparison} difference","operator.$averagePerPeriod":"Average {operandName} per {granularity}","operator.$newly":"New {operandName}","operator.$shareOfTotal":"{operandName} share of total","component.numerator":"{outputName} numerator","component.denominator":"{outputName} denominator","component.current":"{outputName} current","component.previous":"{outputName} previous","component.start":"{outputName} start","component.end":"{outputName} end","period.comparison":"period-over-period","period.current":"current-period","period.yearOverYear":"year-over-year","period.monthOverMonth":"month-over-month","period.weekOverWeek":"week-over-week","time.granularity.second":"second","time.granularity.minute":"minute","time.granularity.hour":"hour","time.granularity.day":"day","time.granularity.week":"week","time.granularity.month":"month","time.granularity.quarter":"quarter","time.granularity.year":"year","time.granularity.period":"period","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal requires a property","sql.timeWatermark":"Resolve time watermark to keep year-over-year and period-over-period comparison ranges consistent","sql.autoCase":"Resolve automatic bucket boundaries","sql.entityExpansion":"Expand entities to obtain more information","sql.computation":"Numeric computation","sql.total":"Count result rows before pagination","sql.semanticResolution":"Semantic resolution"}},ei={locale:"zh-CN",messages:{"operator.rows":"\u6570\u636E\u884C","operator.$sum":"\u603B{operandName}","operator.$avg":"\u5E73\u5747{operandName}","operator.$min":"{operandName}\u6700\u5C0F\u503C","operator.$max":"{operandName}\u6700\u5927\u503C","operator.$count":"{operandName}\u6570\u91CF","operator.$count.rows":"\u884C\u6570","operator.$countDistinct":"{operandName}\u53BB\u91CD\u8BA1\u6570","operator.$add":"{inputNames}","operator.$add.empty":"{operandName}\u6C42\u548C","operator.$subtract":"{input0}\u51CF\u53BB{input1}","operator.$subtract.fallback":"{operandName}\u5DEE\u503C","operator.$multiply":"{inputNames}","operator.$multiply.empty":"{operandName}\u4E58\u79EF","operator.$divide":"{input0}\u9664\u4EE5{input1}","operator.$divide.fallback":"{operandName}\u6BD4\u503C","operator.$concat":"{inputNames}\u62FC\u63A5\u503C","operator.$concat.empty":"{operandName}\u62FC\u63A5\u503C","operator.$abs":"{operandName}\u7EDD\u5BF9\u503C","operator.$substring":"{operandName}\u5B50\u4E32","operator.$case":"{operandName}\u5206\u7C7B","operator.$constant":"\u5E38\u91CF","operator.$sql":"\u8BA1\u7B97\u503C","operator.$rowNumber":"\u884C\u53F7","operator.$rank":"{operandName}\u6392\u540D","operator.$accumulate":"{operandName}\u7D2F\u8BA1\u503C","operator.$least":"{inputNames}\u4E2D\u7684\u6700\u65E9\u503C","operator.$greatest":"{inputNames}\u4E2D\u7684\u6700\u665A\u503C","operator.$dateBucket":"{operandName}\uFF08\u6309{granularity}\uFF09","operator.$periodBoundary.start":"{operandName}\u671F\u521D","operator.$periodBoundary.end":"{operandName}\u671F\u672B","operator.$periodValue.start":"{operandName}\u671F\u521D\u503C","operator.$periodValue.end":"{operandName}\u671F\u672B\u503C","operator.$periodShift":"{operandName}{comparison}\u57FA\u671F\u503C","operator.$periodGrowth":"{operandName}{comparison}\u589E\u957F\u7387","operator.$periodDifference":"{operandName}{comparison}\u5DEE\u503C","operator.$averagePerPeriod":"{operandName}{granularity}\u5747\u503C","operator.$newly":"\u65B0\u589E{operandName}","operator.$shareOfTotal":"{operandName}\u5360\u6BD4","component.numerator":"{outputName}\u5206\u5B50","component.denominator":"{outputName}\u5206\u6BCD","component.current":"{outputName}\u672C\u671F","component.previous":"{outputName}\u4E0A\u671F","component.start":"{outputName}\u5F00\u59CB","component.end":"{outputName}\u7ED3\u675F","period.comparison":"\u540C\u671F","period.current":"\u672C\u671F","period.yearOverYear":"\u540C\u6BD4","period.monthOverMonth":"\u73AF\u6BD4","period.weekOverWeek":"\u5468\u73AF\u6BD4","time.granularity.second":"\u79D2","time.granularity.minute":"\u5206\u949F","time.granularity.hour":"\u5C0F\u65F6","time.granularity.day":"\u65E5","time.granularity.week":"\u5468","time.granularity.month":"\u6708","time.granularity.quarter":"\u5B63\u5EA6","time.granularity.year":"\u5E74","time.granularity.period":"\u5468\u671F","error.PRED_PROPERTY_REQUIRED.$shareOfTotal":"$shareOfTotal\u9700\u8981pred\u53C2\u6570","sql.timeWatermark":"\u8BA1\u7B97\u6570\u636E\u6700\u540E\u65F6\u95F4\uFF0C\u4ECE\u800C\u4FDD\u8BC1\u540C\u6BD4\u3001\u73AF\u6BD4\u7684\u6BD4\u8F83\u533A\u95F4\u4E00\u81F4","sql.autoCase":"\u8BA1\u7B97\u81EA\u52A8\u5206\u6BB5\u8FB9\u754C","sql.entityExpansion":"\u5B9E\u4F53\u5C55\u5F00\uFF0C\u7528\u4E8E\u83B7\u5F97\u66F4\u591A\u4FE1\u606F","sql.computation":"\u6570\u503C\u8BA1\u7B97","sql.total":"\u8BA1\u7B97\u5206\u9875\u524D\u7684\u7ED3\u679C\u603B\u6570","sql.semanticResolution":"\u8BED\u4E49\u89E3\u6790"}},Ga=[ei,Zo],Bt=t=>t.trim().toLowerCase(),Wa=t=>t?"locale"in t?[t]:t:[],za=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 on{definitions=new Map;i18n;constructor(e){this.i18n=Qa(),this.i18n.init({initAsync:!1,fallbackLng:"zh-CN",defaultNS:"translation",keySeparator:!1,showSupportNotice:!1,interpolation:{escapeValue:!1,prefix:"{",suffix:"}"}}),this.register(Ga),this.register(e)}register(e){for(const r of Wa(e)){const n=r;if(!za(n))throw new TypeError("Locale definition must have a non-empty locale");const o=n,i=this.definitions.get(Bt(o.locale)),s={locale:o.locale,messages:Object.freeze({...i?.messages,...o.messages})};this.definitions.set(Bt(o.locale),s),this.i18n.addResourceBundle(o.locale,"translation",s.messages,!0,!0)}return this}resolve(e="zh-CN"){const r=this.definitions.get(Bt(e));if(r)return r;const n=Bt(e).split("-")[0];return[...this.definitions.entries()].find(([i])=>i.split("-")[0]===n)?.[1]??this.definitions.get("zh-cn")}has(e){return this.definitions.has(Bt(e))}translate(e,r,n,o){const i=this.resolve(e);return this.i18n.t(r,{lng:i.locale,defaultValue:n??r,...o??{}})}translator(e="zh-CN"){return(r,n,o)=>this.translate(e,r,n,o)}}const lr=t=>new on(t),pr=new on;class d extends Error{code;details;constructor(e,r,n){super(r),this.code=e,this.details=n,this.name="SemanticDBError"}localizedMessage(e="zh-CN",r=pr){if(this.code==="PRED_PROPERTY_REQUIRED"&&this.message==="$shareOfTotal requires a property")return r.translate(e,"error.PRED_PROPERTY_REQUIRED.$shareOfTotal",this.message,this.details);if(this.code==="PROPERTY_NOT_FOUND"&&e.toLowerCase().startsWith("en")){const n=this.details?.schemaId,o=this.details?.schemaName,i=this.details?.property,s=this.details?.propertyName;if(typeof n=="string"&&typeof o=="string"&&typeof i=="string"&&typeof s=="string")return`Property not found in Schema: ${o}(${n}): ${s}`}return this.message}}ue.extend(Mt),ue.extend(ar);const Ka=new Set(["year","quarter","month","week"]),sn=t=>t.format("YYYY-MM-DD HH:mm:ss"),an=(t,e)=>t.operator&&e(t.operator).kind==="aggregate"?!0:(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?an(t.pred,e):!1)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&an(r,e)),fr=(t,e,r)=>{if(t.kind==="window"||t.kind==="cumulative")throw new d("ACCUMULATE_WINDOW_UNSUPPORTED","$accumulate cannot contain another window expression");if(t.kind==="ordinal-decode")return{...t,input:fr(t.input,e,r)};if(t.kind==="ordinal-encode")return{kind:"cumulative",function:"sum",input:t,...r};if(t.kind!=="operator")return{kind:"cumulative",function:"sum",input:t,...r};const n=e.getOperator(t.operator);if(n.kind==="component")throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain component operator ${t.operator}`);if(n.kind==="aggregate"){if(t.operator==="$avg"){const s={...t,operator:"$sum"},a={...t,operator:"$count"};return{kind:"operator",operator:"$divide",args:{},inputs:[{kind:"cumulative",function:"sum",input:s,...r},{kind:"cumulative",function:"sum",input:a,...r}]}}const i={$sum:"sum",$count:"sum",$min:"min",$max:"max"}[t.operator];if(!i)throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`Aggregate operator ${t.operator} does not declare cumulative semantics`);return{kind:"cumulative",function:i,input:t,...r}}if(n.kind!=="scalar")throw new d("ACCUMULATE_OPERATOR_UNSUPPORTED",`$accumulate cannot contain ${t.operator}`);return{...t,...t.input?{input:fr(t.input,e,r)}:{},...t.inputs?{inputs:t.inputs.map(o=>fr(o,e,r))}:{}}},Ja=t=>{if(!t.input||t.inputs.length>0||t.pred.query)throw new d("INVALID_ACCUMULATE_INPUT","$accumulate requires exactly one nested pred and does not accept pred.query");if(t.inputProperty?.comparable&&t.input.kind!=="ordinal-decode")throw new d("ACCUMULATE_COMPARABLE_OPERATOR_REQUIRED","$accumulate over a comparable category requires an explicit $min or $max metric");const e=t.args.partitionBy??[],r=t.args.orderBy;if(!Array.isArray(e)||e.some(o=>typeof o!="string"))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate partitionBy must be an array of groupby names");if(!Array.isArray(r)||r.length===0)throw new d("INVALID_ACCUMULATE_ARGS","$accumulate requires a non-empty args.orderBy array");const n=r.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw new d("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require pred and optional direction");const{pred:i,direction:s="asc",...a}=o;if(typeof i!="string"||s!=="asc"&&s!=="desc"||Object.keys(a).length>0)throw new d("INVALID_ACCUMULATE_ARGS","$accumulate orderBy items require only a string pred and asc/desc direction");return{expression:t.resolveKey(i),direction:s==="asc"?"ASC":"DESC"}});return fr(t.input,t,{partitionBy:e.map(o=>t.resolveKey(String(o))),orderBy:n})},Xa=t=>{if(t.groupByNames.length===0)return;if(typeof t.pred.pred!="object"||Array.isArray(t.pred.pred)||!an(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})},Za=(t,e,r)=>{if(t.from||t.having)throw new d("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period currently requires a physical LogicForm without from or having");if((t.preds?.length??0)!==e.length)throw new d("ACCUMULATE_PERIOD_UNSUPPORTED","$accumulate args.period cannot currently be mixed with non-period projections");const n=t.query&&Object.entries(t.query).find(([,E])=>{if(typeof E!="object"||E===null||Array.isArray(E))return!1;const $=E;return typeof $.$gte=="string"&&typeof $.$lte=="string"});if(!n)throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","$accumulate args.period requires one bounded date query identifying the target period");const[o,i]=n,s=i,a=ue(String(s.$gte)),u=ue(String(s.$lte));if(!a.isValid()||!u.isValid())throw new d("ACCUMULATE_PERIOD_QUERY_REQUIRED","Target date range is invalid");const c=e.map(E=>{if(!E.name)throw new d("MISSING_PRED_NAME","$accumulate args.period requires normalized names");return E.name}),p=r==="week"?a.startOf("isoWeek"):a.startOf(r),l={...t.query,[o]:{...s,$gte:sn(p)}},f=new Set([...(t.groupby??[]).map(({name:E})=>E),...(t.preds??[]).map(({name:E})=>E)]),m=E=>{let $=E;for(;f.has($);)$=`_${$}`;return f.add($),$},y=m("__accumulate_period"),h=e.map((E,$)=>m(`__accumulate_metric_${$}`)),g=(t.groupby??[]).map(({name:E})=>String(E)),A=r==="year"||r==="quarter"?"month":"day",w={version:t.version,...t.schema?{schema:t.schema}:{},query:l,groupby:[...t.groupby??[],{operator:"$dateBucket",pred:o,args:{granularity:A},name:y}],preds:e.map((E,$)=>({...E.pred,name:h[$]??`__accumulate_metric_${$}`}))},S={version:t.version,from:w,preds:[...g.map(E=>({pred:E,name:E})),{pred:y,name:y},...e.map((E,$)=>({operator:"$accumulate",pred:h[$]??`__accumulate_metric_${$}`,args:{partitionBy:g,orderBy:[{pred:y,direction:"asc"}]},name:c[$]??`accumulate_${$}`}))]};return{version:t.version,from:S,query:{[y]:{$gte:sn(a),$lte:sn(u)}},preds:[...g.map(E=>({pred:E,name:E})),...c.map(E=>({pred:E,name:E}))],...t.sort?{sort:t.sort}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.page!==void 0?{page:t.page}:{},...t.output?{output:t.output}:{},...t.representation?{representation:t.representation}:{}}},ec={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"||!Ka.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:Ja,validatePlan:Xa,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 Za(t,r,n)},getOutputProperty({name:t,inputProperty:e}){return e?{...e,name:t,isArray:!1}:{name:t,type:"number",primal_type:"number",isArray:!1}}},tc={name:"$abs",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Absolute ${t}`:`${t}\u7EDD\u5BF9\u503C`,kind:"scalar",toSQL({expression:t}){if(!t)throw new d("PRED_PROPERTY_REQUIRED","$abs requires a pred");return`ABS(${t})`},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new d("PRED_PROPERTY_REQUIRED","$abs requires a pred");return{...e,name:t,isArray:!1}}},ht=(t,e,r,n=r)=>{const o=e.expressions??[];if(o.length<r||o.length>n)throw new d("INVALID_OPERATOR_COMPONENTS",`${t} requires ${r===n?String(r):`${r}-${n}`} pred inputs`);return o},mr=t=>({name:t,type:"number",primal_type:"number",isArray:!1}),rc={name:"$add",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?e.join(" plus "):`Sum of ${t}`:e.length>0?e.join("\u52A0"):`${t}\u6C42\u548C`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$add.empty":"operator.$add",kind:"scalar",requiresProperty:!1,toSQL(t){return`(${ht("$add",t,2,Number.POSITIVE_INFINITY).join(" + ")})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:mr(t)}},ne=t=>structuredClone(t),nc=(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},oc=(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},ic=t=>{const e=t.properties.flatMap(r=>[[r.name,r.id],[r.id,r.id]]);return Object.freeze(Object.fromEntries(e))},ti=(t,e)=>t.properties.some(r=>r!==e&&r.id===e.name)?e.id:e.name,sc=(t,e)=>t.properties.flatMap(r=>[...e.startsWith(`${r.id}_`)?[{property:r,prefix:r.id}]:[],...r.name!==r.id&&e.startsWith(`${r.name}_`)?[{property:r,prefix:r.name}]:[]]).sort((r,n)=>n.prefix.length-r.prefix.length||(n.prefix===n.property.id?1:0)-(r.prefix===r.property.id?1:0)),de=(t,e,r)=>{const n=t.properties.find(o=>o.id===e)??t.properties.find(o=>o.name===e);if(n)return{canonicalName:ti(t,n),canonicalId:n.id,schema:t,property:n,relations:[]};for(const{property:o,prefix:i}of sc(t,e)){if(o.primal_type!=="entity"&&o.primal_type!=="object"||!o.ref)continue;if(!r)throw new d("SCHEMA_RESOLVER_REQUIRED",`Resolving property path ${e} requires a Schema resolver`);const s=r(o.ref),a=de(s,e.slice(i.length+1),r);return{canonicalName:`${ti(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})},cn=(t,e)=>t.name===e||t.id===e,ac=(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=>cn(a,i.hierarchy?.up??"")):[],...r.properties.filter(a=>a.hierarchy?.down!==void 0&&cn(i,a.hierarchy.down))];if(s.some(a=>cn(e,a.name)))return!0;o.push(...s)}return!1},ri=(t,e,r,n)=>{if(t.operator||typeof t.pred!="string"||e.length===0)return!1;let o;try{o=de(r,t.pred,n)}catch{return!1}return o.property.isArray||o.property.primal_type==="entity"||o.property.primal_type==="object"||o.relations.some(({property:i})=>i.isArray)?!1:e.some(i=>{if(i.operator||typeof i.pred!="string")return!1;let s;try{s=de(r,i.pred,n)}catch{return!1}if(s.property.isArray)return!1;if(s.relations.length===0&&o.relations.length===0)return ac(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})},cc=({source:t,properties:e})=>{const r=t.hierarchy;if(!Array.isArray(r))return r===void 0?{}:{hierarchy:r};let n=t.hierarchy_property;if(typeof n!="string"||n.length===0){const s=e.filter(({type:u})=>u==="ID");if(s.length!==1)throw new d("LEGACY_HIERARCHY_ID_PROPERTY_REQUIRED","Legacy Schema hierarchy without hierarchy_property must contain exactly one ID property",{idPropertyCount:s.length});const a=s[0];n=a?.id??a?.name}const o=r.map(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return;const a=s;if(!(typeof a.name!="string"||!Number.isInteger(a.code_length)))return{name:a.name,...Array.isArray(a.syno)?{syno:a.syno}:{},codeLength:a.code_length}});if(o.some(s=>s===void 0))return{};const i=r[0];return{hierarchy:{property:n,storage:i?.use_full_length===!0?"zero-padded":"compact",levels:o}}},uc=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},dc=(t,e,r)=>{const n=de(t,e,r);if(n.property.primal_type!=="entity"&&n.property.primal_type!=="object")return{schema:n.schema,reference:n.canonicalName,relation:!1};if(n.property.isArray)throw new d("ARRAY_HIERARCHY_RELATION_UNSUPPORTED",`$hierarchyLevel cannot group an array relation: ${n.canonicalName}`);if(!n.property.ref||!r)throw new d("SCHEMA_RESOLVER_REQUIRED",`$hierarchyLevel requires a Schema resolver for relation ${n.canonicalName}`);return{schema:r(n.property.ref),reference:n.canonicalName,relation:!0}},lc={name:"$hierarchyLevel",defaultName:({operandName:t,args:e,locale:r})=>{const n=typeof e.level=="string"?e.level:"";return r.toLowerCase().startsWith("en")?`${t}${n?` ${n}`:""} level`:`${t}${n}\u5C42\u7EA7`},kind:"scalar",planInput({reference:t,args:e,schema:r,resolveSchema:n}){const o=Object.keys(e).filter(y=>y!=="level");if(o.length>0||e.level!==void 0&&(typeof e.level!="string"||e.level.length===0))throw new d("INVALID_HIERARCHY_LEVEL_ARGS","$hierarchyLevel args may contain only one non-empty level string",{unsupportedArgs:o});const i=dc(r,t,n),s=i.schema.hierarchy;if(!s)throw new d("SCHEMA_HIERARCHY_REQUIRED",`Schema ${i.schema.id} does not declare hierarchy`,{schemaId:i.schema.id});const a=i.schema.properties.find(({name:y})=>y===s.property);if(!a)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${s.property}`);if(!i.relation&&a.name!==de(r,t,n).property.name)throw new d("HIERARCHY_PROPERTY_REQUIRED",`$hierarchyLevel pred must be an object relation or hierarchy property ${a.name}`);const u=s.levels.reduce((y,h)=>y+h.codeLength,0),c=i.schema.properties.filter(({type:y})=>y==="ID"),l=i.relation&&c.length===1&&c[0]?.name===a.name?i.reference:i.relation?`${i.reference}_${a.name}`:i.reference;if(e.level===void 0){let y=0;return{reference:l,args:{levels:s.levels.map(({name:h,codeLength:g})=>(y+=g,{name:h,codeLength:y})),totalLength:u,storage:s.storage}}}let f=0;const m=s.levels.find(y=>(f+=y.codeLength,y.name===e.level||y.syno?.includes(e.level)));if(!m)throw new d("HIERARCHY_LEVEL_NOT_FOUND",`Schema ${i.schema.id} does not declare hierarchy level: ${e.level}`,{schemaId:i.schema.id,level:e.level});return{reference:l,args:{level:m.name,codeLength:f,totalLength:u,storage:s.storage}}},toSQL({expression:t,args:e,sql:r}){if(!t)throw new Error("$hierarchyLevel requires a hierarchy pred");if(Array.isArray(e.levels)){const u=e.levels.filter(y=>typeof y=="object"&&y!==null&&!Array.isArray(y)&&typeof y.name=="string"&&Number.isInteger(y.codeLength)),c=e.totalLength,p=e.storage;if(u.length!==e.levels.length||u.length===0||!Number.isInteger(c)||Number(c)<=0||u.some(({name:y,codeLength:h},g)=>y.length===0||h<=0||h>Number(c)||g>0&&h<=Number(u[g-1]?.codeLength))||u.at(-1)?.codeLength!==c||p!=="compact"&&p!=="zero-padded")throw new d("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const l=`WHEN ${t} IS NULL THEN NULL`;if(p==="compact"){const y=r.stringLength(t),h=u.map(g=>`WHEN ${y} = ${g.codeLength} THEN ${r.value(g.name)}`);return`(CASE ${l} ${h.join(" ")} ELSE NULL END)`}const f=u.slice(0,-1).map(y=>{const h=Number(c)-y.codeLength;return`WHEN ${r.substring(t,y.codeLength+1,h)} = ${r.value("0".repeat(h))} THEN ${r.value(y.name)}`}),m=u.at(-1);return`(CASE ${l} ${f.join(" ")} ELSE ${r.value(m?.name)} END)`}const n=e.codeLength,o=e.totalLength,i=e.storage;if(!Number.isInteger(n)||!Number.isInteger(o)||Number(n)<=0||Number(o)<Number(n)||i!=="compact"&&i!=="zero-padded")throw new d("INVALID_HIERARCHY_LEVEL_PLAN","$hierarchyLevel must be resolved by the planner before SQL compilation");const s=r.substring(t,1,Number(n)),a=Number(o)-Number(n);return i==="zero-padded"&&a>0?r.concat([s,r.value("0".repeat(a))]):s},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},gt=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=t;return Object.keys(e).length===2&&e.kind==="hierarchy"&&typeof e.level=="string"&&e.level.trim().length>0},$t=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),un=(t,e,{schema:r,resolveSchema:n})=>{if(typeof e!="string")return;const o=t.primal_type==="entity"||t.primal_type==="object"?t.ref?n?.(t.ref).hierarchy:void 0:r.hierarchy?.property===t.name?r.hierarchy:void 0,i=o?.levels.find(s=>s.name===e||s.syno?.includes(e));if(!(!o||!i))return{name:i.name,index:o.levels.indexOf(i)}},yr=(t,{schema:e,mapping:r})=>r.mappings?.find(n=>n.mappingType==="property"&&n.propertyTarget?.some(o=>$t(e,o)?.id===t.id)),ni=(t,e,r)=>{const n=$t(r.schema,t);if(!n)return`hierarchy property is not available: ${t}`;const o=un(n,e,r);if(!o)return`hierarchy level is not available: ${String(e)}`;const i=yr(n,r);if(!gt(i?.granularity))return;const s=un(n,i.granularity.level,r);return s&&s.index>=o.index?void 0:`hierarchy dimension ${t} requires ${o.name}, but source has ${s?.name}`},pc=(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=ni(i.pred,i.args.level,e);if(u)return u}else{const u=$t(e.schema,i.pred),c=u&&yr(u,e);if(gt(c?.granularity))return`$hierarchyLevel without args.level is not covered by hierarchy-grained source: ${i.pred}`}const a=Array.isArray(i.pred)?i.pred:i.pred===void 0?[]:[i.pred];for(const u of a){if(typeof u=="string")continue;const c=r(u);if(c)return c}},n=i=>{if(i){for(const[s,a]of Object.entries(i))if(a!==void 0){if(s==="$and"||s==="$or"){if(!Array.isArray(a))continue;for(const u of a){const c=n(u);if(c)return c}}else if(s==="$expr"){if(typeof a!="object"||a===null||Array.isArray(a))continue;const u=a.pred;if(typeof u!="object"||u===null||Array.isArray(u))continue;const c=r(u);if(c)return c}else if(!s.startsWith("$")){const u=$t(e.schema,s),c=u&&yr(u,e);if(gt(c?.granularity))return`query on hierarchy-grained property requires an explicit $hierarchyLevel: ${s}`}}}},o=n(t.query);if(o)return o;for(const i of t.preds??[]){const s=r(i);if(s)return s}for(const i of t.groupby??[])if(typeof i.pred=="string"){if(i.operator==="$hierarchyLevel"){const s=ni(i.pred,i.args?.level,e);if(s)return s}else if(i.operator===void 0){const s=$t(e.schema,i.pred),a=s&&yr(s,e);if(gt(a?.granularity))return`raw groupby is not covered by hierarchy-grained source: ${i.pred}`}}},fc={kind:"hierarchy",isGranularity:gt,validateItem(t,e){const r=t.granularity;if(gt(r))return t.propertyTarget?.every(n=>{const o=$t(e.schema,n);return o!==void 0&&un(o,r.level,e)!==void 0})?void 0:"physical hierarchy granularity requires a mapped hierarchy Property and level"},candidateReason:pc,supportsGroupby:t=>t.operator==="$hierarchyLevel"},mc={keys:["hierarchy"],resolve(t,e){for(const f of e)if(f.level!==void 0){if(typeof f.level!="string"||f.level.trim().length===0)throw new d("INVALID_PROPERTY_LEVEL",`Property ${f.name} level must be a non-empty string`,{property:f.name,level:f.level});if(f.primal_type!=="entity"&&f.primal_type!=="object")throw new d("PROPERTY_LEVEL_REQUIRES_ENTITY",`Property ${f.name} level requires an entity relation`,{property:f.name,type:f.type})}if("hierarchy_property"in t)throw new d("LEGACY_HIERARCHY_PROPERTY_NOT_ALLOWED","Schema hierarchy must declare hierarchy.property instead of hierarchy_property");const r=t.hierarchy;if(r===void 0)return{};if(typeof r!="object"||r===null||Array.isArray(r))throw new d("INVALID_HIERARCHY","Schema hierarchy must be an object containing property, levels, and optional storage");const n=r,o=Object.keys(n).filter(f=>f!=="property"&&f!=="storage"&&f!=="levels");if(o.length>0)throw new d("UNSUPPORTED_HIERARCHY_FIELD","Schema hierarchy only supports property, storage, and levels",{unsupportedKeys:o});const i=n.property===void 0?(()=>{const f=e.filter(m=>m.type==="ID");if(f.length!==1)throw new d("HIERARCHY_ID_PROPERTY_REQUIRED","Schema hierarchy.property may be omitted only when the Schema has exactly one ID Property",{idPropertyCount:f.length});return f[0]})():void 0;if(n.property!==void 0&&(typeof n.property!="string"||n.property.length===0))throw new d("HIERARCHY_PROPERTY_REQUIRED","Schema hierarchy.property must be a non-empty property name or id when provided");const s=i??e.find(f=>f.name===n.property||f.id===n.property);if(!s)throw new d("HIERARCHY_PROPERTY_NOT_FOUND",`Schema hierarchy.property does not exist: ${n.property}`,{property:n.property});if(s.primal_type!=="string")throw new d("INVALID_HIERARCHY_PROPERTY",`Hierarchy property ${s.name} must have primal_type string`,{property:s.name,primal_type:s.primal_type});const a=n.storage??"compact";if(a!=="compact"&&a!=="zero-padded")throw new d("INVALID_HIERARCHY_STORAGE","Schema hierarchy.storage must be compact or zero-padded");if(!Array.isArray(n.levels)||n.levels.length===0)throw new d("HIERARCHY_LEVELS_REQUIRED","Schema hierarchy.levels must be a non-empty array");const u=new Set,c=new Set,p=n.levels.map((f,m)=>{if(typeof f!="object"||f===null||Array.isArray(f))throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} must be an object`);const y=f,h=Object.keys(y).filter(A=>A!=="name"&&A!=="syno"&&A!=="codeLength");if(h.length>0)throw new d("UNSUPPORTED_HIERARCHY_LEVEL_FIELD",`Hierarchy level ${m} only supports name, syno, and codeLength`,{unsupportedKeys:h});if(typeof y.name!="string"||y.name.length===0)throw new d("INVALID_HIERARCHY_LEVEL",`Hierarchy level ${m} name must not be empty`);if(u.has(y.name)||c.has(y.name))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level name: ${y.name}`);if(!Number.isInteger(y.codeLength)||Number(y.codeLength)<=0)throw new d("INVALID_HIERARCHY_CODE_LENGTH",`Hierarchy level ${y.name} codeLength must be a positive integer`);if(y.syno!==void 0&&(!Array.isArray(y.syno)||y.syno.some(A=>typeof A!="string"||A.length===0)))throw new d("INVALID_HIERARCHY_SYNONYMS",`Hierarchy level ${y.name} syno must contain only non-empty strings`);const g=y.syno??[];for(const A of g){if(A===y.name||u.has(A)||c.has(A))throw new d("DUPLICATE_HIERARCHY_LEVEL",`Duplicate hierarchy level alias: ${A}`);c.add(A)}return u.add(y.name),{name:y.name,...g.length>0?{syno:[...g]}:{},codeLength:Number(y.codeLength)}});return{hierarchy:{property:s.name,storage:a,levels:p}}}},yc=Object.freeze({name:"hierarchy",schemaMetadata:mc,legacySchemaKeys:["hierarchy_property"],normalizeLegacySchema:cc,resolveEntityFilterProperty:uc,operators:[lc],mappingGranularity:fc}),hc=(t,e)=>!!(t&&e?.temporalSemantics==="snapshot"&&t.type!=="timestamp"),dn="$periodValue",gc=(t,e)=>{const r=e?.periodBoundaryPolicy?.({pred:t});if(r)return{operator:dn,...r};if(e?.kind==="aggregate")throw new d("OBSERVATION_REQUIRES_PERIOD_BOUNDARY",`Observation metrics must use ${dn}; ${e.name} describes a time range`,{operator:e.name});return{operator:dn,boundary:"end",implicit:!0}},$c={name:"observation",resolveProjection({pred:t,schema:e,sourceProperty:r,outputProperty:n,operator:o}){if(!r||!hc(r,e))return;const i=gc(t,o);return{outputProperty:{...n,temporal:{kind:"period-boundary",boundary:i.boundary,sourceProperty:r.name}}}}},Ac=new Set(["second","minute","hour","day","week","month","quarter","year"]),oi=t=>typeof t=="string"&&Ac.has(t),wc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),hr=(t,e,r)=>{const n=t instanceof Date?t.getTime():typeof t=="string"||typeof t=="number"?new Date(t).getTime():Number.NaN;if(Number.isNaN(n))throw new d(`${r.codePrefix}_PERIOD_INVALID_BOUND`,`${r.label} period ${e} must be a date`,{owner:e,value:t});return n},et=(t,e=2)=>String(t).padStart(e,"0"),ln=t=>`${et(t.getFullYear(),4)}-${et(t.getMonth()+1)}-${et(t.getDate())} ${et(t.getHours())}:${et(t.getMinutes())}:${et(t.getSeconds())}.`+et(t.getMilliseconds(),3),Ec=(t,e)=>{if(!wc(t)){const a=hr(t,"point",e);return{lower:a,upper:a}}const r=t.$eq;if(r!==void 0){const a=hr(r,"$eq",e);return{lower:a,upper:a}}const n=t.$gte??t.$gt,o=t.$lte??t.$lt;if(n===void 0||o===void 0)throw new d(`${e.codePrefix}_PERIOD_BOUNDS_REQUIRED`,`${e.label} period grouping requires both a lower and an upper time bound`);const i=hr(n,t.$gte!==void 0?"$gte":"$gt",e)+(t.$gte===void 0?1:0),s=hr(o,t.$lte!==void 0?"$lte":"$lt",e)-(t.$lte===void 0?1:0);if(i>s)throw new d(`${e.codePrefix}_PERIOD_INVALID_RANGE`,`${e.label} period grouping requires the lower bound to precede the upper bound`,{lower:n,upper:o});return{lower:i,upper:s}},_c=(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},Sc=(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},ii=(t,e,r)=>{const{lower:n,upper:o}=Ec(t,r),i=[];let s=_c(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=Sc(s,e),u=new Date(Math.min(a.getTime()-1,o));i.push({label:ln(s),start:ln(s),end:ln(u)}),s=a}return i},Ic=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.name),bc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.name)),Rc=(t,e)=>{if(e.temporalSemantics!=="snapshot")return;const r=e.properties.find(({type:l})=>l==="timestamp");if(!r)return;const n=Ic(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"||!oi(s))throw new d("OBSERVATION_PERIOD_GRANULARITY_UNSUPPORTED","Grouped observation period values require $dateBucket with a supported time granularity",{property:r.name});if(i.length!==o.length)throw new d("OBSERVATION_PERIOD_METRICS_REQUIRED","A grouped observation query cannot mix $periodValue with ordinary projections");const a=i.map(l=>{const f=l.args?.boundary;if(f!=="start"&&f!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:f});if(!l.pred||typeof l.pred!="object"||Array.isArray(l.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");return{pred:l,effectivePred:{...l.pred,...l.name?{name:l.name}:{}}}});if(new Set(i.map(({args:l})=>l?.boundary)).size!==1)throw new d("OBSERVATION_PERIOD_BOUNDARY_MISMATCH","Grouped observation metrics in one query must use the same period boundary");const c=i[0]?.args?.boundary,p=t.query?.[r.name];if(p===void 0)throw new d("OBSERVATION_PERIOD_BOUNDS_REQUIRED",`Grouped observation values on ${r.name} require a bounded query`,{property:r.name});return{group:n,timestamp:r,boundary:c,metrics:a,periods:ii(p,s,{codePrefix:"OBSERVATION",label:"Observation"}).map(l=>({label:l.label,asOf:l[c]}))}},si=["second","minute","hour","day","week","month","quarter","year"],Nc=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:[$c],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(si.indexOf(o)>si.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=Rc(t,e);if(r)return{group:r.group,property:r.timestamp,periods:r.periods,source:{kind:"latest",timestamp:r.timestamp},rewriteQuery:n=>bc(n,r.timestamp),rewritePred:n=>r.metrics.find(o=>o.pred===n)?.effectivePred??n}}}}),Vt=(t,e)=>typeof e=="string"?t.properties.find(({id:r,name:n})=>r===e||n===e):void 0,Oc={name:"$recursive",validateCondition(t){if(Object.keys(t).some(e=>e!=="$recursive"))throw new d("INVALID_RECURSIVE_QUERY","$recursive cannot be combined with other field operators")},async normalize(t,e){const r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{root:t},n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=n===e.schema.id?e.schema:e.resolveSchema?.(n);if(!o)throw new d("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=r.idProperty??r.id_property,s=o.properties.filter(({type:f})=>f==="ID"),a=i===void 0?s.length===1?s[0]:void 0:Vt(o,i);if(!a||i===void 0&&s.length!==1)throw new d("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive Schema ${n} must have exactly one ID property or idProperty`);const u=Array.isArray(r.roots),c=u?r.roots:r.root===void 0?[]:[r.root];if(!u&&c.length===0||c.some(f=>f===void 0))throw new d("RECURSIVE_ROOT_REQUIRED","$recursive requires root or roots");const p=await Promise.all(c.map(f=>e.normalizeValue(f,o,a))),l=r.parentProperty??r.parent_property??o.parentProperty??"pid";if(typeof l!="string"||l.length===0)throw new d("RECURSIVE_PARENT_PROPERTY_REQUIRED","$recursive parentProperty must be a string");if(r.includeSelf!==void 0&&typeof r.includeSelf!="boolean"||r.include_self!==void 0&&typeof r.include_self!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive includeSelf must be boolean");return{schema:n,roots:p,includeSelf:r.includeSelf??r.include_self??!0,idProperty:a.name,parentProperty:l}},authorize(t,e){const r=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=e.resolveSchema(n);if(e.assertSchemaAllowed(n),e.hasRowPermissions(n))throw new d("RECURSIVE_ROW_PERMISSION_UNSUPPORTED",`$recursive cannot safely apply row permissions for Schema ${n}`,{schemaId:n});const i=r.idProperty??r.id_property,s=i===void 0?o.properties.find(({type:c})=>c==="ID"):Vt(o,i),a=r.parentProperty??r.parent_property??o.parentProperty??"pid",u=Vt(o,a);s&&e.assertPropertyAllowed(o,s),u&&e.assertPropertyAllowed(o,u)},plan(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const r=t,n=typeof r.schema=="string"?r.schema:e.property.ref??e.schema.id,o=n===e.schema.id?e.schema:e.resolveSchema?.(n);if(!o)throw new d("SCHEMA_RESOLVER_REQUIRED",`$recursive requires Schema ${n}`);const i=Vt(o,r.idProperty),s=Vt(o,r.parentProperty);if(!i)throw new d("RECURSIVE_ID_PROPERTY_REQUIRED",`$recursive ID property not found: ${String(r.idProperty)}`);if(!s)throw new d("RECURSIVE_PARENT_PROPERTY_REQUIRED",`$recursive parent property not found: ${String(r.parentProperty)}`);if(!Array.isArray(r.roots)||typeof r.includeSelf!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive must be normalized before planning");const a=e.resolveMapping(n,e.connectionId);return{value:{schemaId:n,connectionId:a.connectionId,source:a.source,...a.sourceSql?{sourceSql:a.sourceSql}:{},idColumn:i.id,parentColumn:s.id,roots:r.roots,includeSelf:r.includeSelf},sources:[{schemaId:n,source:a.source,...a.connectionId?{connectionId:a.connectionId}:{}}]}},compile(t,{field:e,provider:r,bind:n,renderSource:o}){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_RECURSIVE_QUERY","$recursive query was not planned");const i=t;if(typeof i.source!="string"||typeof i.idColumn!="string"||typeof i.parentColumn!="string"||!Array.isArray(i.roots)||typeof i.includeSelf!="boolean")throw new d("INVALID_RECURSIVE_QUERY","$recursive query was not planned");if(!r.supportsRecursiveCte)throw new d("RECURSIVE_QUERY_UNSUPPORTED",`Provider ${r.kind} does not support recursive queries`);const s=Array.isArray(i.roots)?i.roots:[];if(s.length===0)return`${e} IN (SELECT NULL WHERE 1 = 0)`;const a=r.quoteIdentifier("__recursive_tree__"),u=r.quoteIdentifier("__recursive_id__"),c=r.quoteIdentifier("__recursive_node__"),p=r.quoteIdentifier("__recursive_child__"),l=r.quoteIdentifier(i.idColumn),f=r.quoteIdentifier(i.parentColumn),m=o(i.source,typeof i.sourceSql=="string"?i.sourceSql:void 0),y=()=>s.map(E=>n(E)).join(", "),h=(E,$=!1)=>s.length===1?`${E} ${$?"<>":"="} ${y()}`:`${E} ${$?"NOT IN":"IN"} (${y()})`,g=`${c}.${l}`,A=i.includeSelf?h(g):`${h(`${c}.${f}`)} AND ${h(g,!0)}`,w=r.recursiveCteUnion??"UNION",S=`(WITH RECURSIVE ${a}(${u}) AS ( SELECT ${g} FROM ${r.tableAlias(m,"__recursive_node__")} WHERE ${A} ${w} SELECT ${p}.${l} FROM ${r.tableAlias(m,"__recursive_child__")} JOIN ${a} ON ${p}.${f} = ${a}.${u}) SELECT DISTINCT ${u} FROM ${a})`;return`${e} IN ${S}`}},Tc=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:[Oc]});ue.extend(Mt);const pn=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...pn(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:pn(r))]:e},ai=(t,e)=>ue(t).endOf(e==="week"?"isoWeek":e).toDate(),fn=t=>ue(t).format("YYYY-MM-DD HH:mm:ss"),Pc=(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})},ci=(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})},Lc=Object.freeze({name:"temporal",schemaMetadata:{keys:["timeWatermark"],resolve(t){return ci(t.timeWatermark,`Schema ${t.id}`),{...t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}}},propertyMetadata:{keys:["timeWatermark"],resolve(t,e){if(ci(t.timeWatermark,`Property ${t.name}`),t.timeWatermark&&e.primal_type!=="date")throw new d("TIME_WATERMARK_DATE_PROPERTY_REQUIRED",`Property ${e.name} timeWatermark is only supported by date Properties`,{property:e.name});return t.timeWatermark?{timeWatermark:t.timeWatermark}:{}}},createTimeWatermarkLogicform({logicform:t,rootSchema:e,rootProperty:r,requestedUpperBound:n,now:o,defaultPolicy:i,resolveSchema:s,inferPropertyPath:a}){const u=[...new Set((t.preds??[]).flatMap(pn).filter(l=>l!==e.id))],c=[{schema:e,property:r}];for(const l of u){const f=s(l),m=t.propertyResolve?.[l],y=m?.[r.id]??m?.[r.name]??a(e,r.name,f);if(!y)throw new d("TIME_WATERMARK_PROPERTY_RESOLVE_REQUIRED",`Cross-Schema timeWatermark requires propertyResolve for ${l}.${r.name}`,{schemaId:l,property:r.name});const h=f.properties.find(({id:g,name:A})=>g===y||A===y);if(!h||h.primal_type!=="date")throw new d("TIME_WATERMARK_PROPERTY_REQUIRED",`timeWatermark Property is not a date Property: ${l}.${y}`,{schemaId:l,property:y});c.push({schema:f,property:h})}const p=c.map(({schema:l,property:f})=>{const m=Pc(f.timeWatermark??l.timeWatermark??i,`${l.id}.${f.id}`);if(m.type==="now_offset"){const y=ai(ue(o).add(m.offset,"day").toDate(),f.granularity??"day");return{operator:"$constant",args:{value:fn(y),type:"timestamp"},name:`${l.name}\u6570\u636E\u65F6\u95F4`}}return{operator:"$periodBoundary",args:{boundary:"end"},pred:{operator:"$max",pred:f.name,schema:l.id},name:`${l.name}\u6700\u65B0\u65F6\u95F4`}});return p.some(({operator:l})=>l==="$periodBoundary")&&p.push({operator:"$constant",args:{value:fn(ai(o,r.granularity??"day")),type:"timestamp"},name:"\u73B0\u5728"}),p.push({operator:"$constant",args:{value:fn(n),type:"timestamp"},name:"\u63D0\u95EE\u65F6\u95F4\u4E0A\u754C"}),{version:t.version,schema:e.id,preds:[{name:"__timeWatermark__",operator:"$least",pred:p}]}}}),gr=(t,e)=>{const r=t.filter(n=>n.type===e);return r.length===1?r[0]:void 0},vt=t=>{if(t.type!=="entity"||t.temporalSemantics==="snapshot")return;const e=gr(t.properties,"ID"),r=gr(t.properties,"timestamp"),n=gr(t.properties,"start_date"),o=gr(t.properties,"end_date");return e&&r&&n&&o?{id:e,timestamp:r,start:n,end:o}:void 0},ui=(t,e)=>t.groupby?.find(r=>typeof r.pred=="string"&&r.pred===e.timestamp.name),Dc=(t,e)=>ui(t,e)!==void 0,Cc=(t,e)=>t&&Object.fromEntries(Object.entries(t).filter(([r])=>r!==e.timestamp.name)),kc=(t,e)=>{const r=ui(t,e);if(!r)return;const n=r.args?.granularity;if(r.operator!=="$dateBucket"||!oi(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:ii(o,n,{codePrefix:"VALIDITY",label:"Valid-time"}).map(({label:i,end:s})=>({label:i,asOf:s}))}},Uc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Mc=t=>Uc(t)?t.$lte??t.$lt??t.$eq:t,di=(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=>di(c,e)):u])),n=Object.entries(t).find(([a])=>a===e.timestamp.name);if(!n)return r;const[,o]=n,i=Mc(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}]}}},li=(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&&li(o,e)))),qc={name:"validity",resolveQuery({logicform:t,schema:e,query:r}){const n=vt(e);if(!n)return r;if(Dc(t,n))return Cc(r,n);const i=li(r,new Set([n.timestamp.name,n.start.name,n.end.name]))?r:{...r,[n.timestamp.name]:{$lte:new Date().toISOString()}};return di(i,n)},resolveProjection({schema:t,outputProperty:e}){if(vt(t))return{outputProperty:{...e,temporal:{kind:"validity"}}}}},jc={name:"start_date",primalType:"date"},xc={name:"end_date",primalType:"date"},Bc=Object.freeze({name:"validity",semanticTypes:[jc,xc],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:[qc],intervalSemantics:{resolve:vt},relationSemantics:{plan({sourceSchema:t,targetSchema:e}){const r=vt(e);if(!r)return;const n=t.properties.find(({type:o})=>o==="timestamp");if(!n)throw new d("VALIDITY_JOIN_SOURCE_TIMESTAMP_REQUIRED",`Valid-time Schema ${e.id} cannot join from a Schema without a timestamp Property`,{schemaId:t.id});return{kind:"point-in-interval",point:n,start:r.start,end:r.end}}},plannerPeriod:{resolve(t,e){const r=vt(e);if(!r)return;const n=kc(t,r);return n?{group:n.group,property:r.timestamp,periods:n.periods,source:{kind:"interval",start:r.start,end:r.end}}:void 0}}}),pi=(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},Vc=Object.freeze({name:"property-hierarchy",propertyMetadata:{keys:["hierarchy"],resolve:()=>({}),resolveAll(t,e){const r=t.map((o,i)=>{const s=e[i]?.hierarchy;if(s===void 0)return o;if(typeof s!="object"||s===null||Array.isArray(s))throw new d("INVALID_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy must be an object containing up and/or down`,{property:o.name,hierarchy:s});const a=s,u=Object.keys(a).filter(l=>l!=="up"&&l!=="down");if(u.length>0)throw new d("UNSUPPORTED_PROPERTY_HIERARCHY",`Property ${o.name} hierarchy only supports up and down`,{property:o.name,unsupported:u});const c=pi(t,o,a.up,"up"),p=pi(t,o,a.down,"down");return{...o,hierarchy:{...c?{up:c}:{},...p?{down:p}:{}}}}),n=new Map(r.map(o=>[o.name,o]));for(const o of r)for(const i of["up","down"]){const s=new Set;let a=o;for(;a?.hierarchy?.[i];){if(s.has(a.name))throw new d("PROPERTY_HIERARCHY_CYCLE",`Property hierarchy.${i} contains a cycle at ${a.name}`,{property:o.name,direction:i,cycleAt:a.name});s.add(a.name),a=n.get(a.hierarchy[i])}}return r}}}),fi=Object.freeze([yc,Tc,Lc,Nc,Bc,Vc]),me=(t=[])=>{const e=[...fi,...t],r=new Set,n=new Set,o=new Set,i=new Set,s=new Set,a=new Set,u=new Set,c=new Set,p=new Set;for(const l of e){if(!l.name)throw new d("INVALID_PLUGIN","Plugin name must not be empty");if(r.has(l.name))throw new d("PLUGIN_ALREADY_REGISTERED",`Plugin is already registered: ${l.name}`,{plugin:l.name});r.add(l.name);for(const m of[...l.schemaMetadata?.keys??[],...l.legacySchemaKeys??[]]){if(!m)throw new d("INVALID_PLUGIN_METADATA_KEY","Plugin metadata key must not be empty");if(n.has(m))throw new d("PLUGIN_METADATA_KEY_ALREADY_REGISTERED",`Plugin Schema metadata key is already registered: ${m}`,{key:m,plugin:l.name});n.add(m)}for(const m of l.propertyMetadata?.keys??[]){if(!m)throw new d("INVALID_PLUGIN_PROPERTY_METADATA_KEY","Plugin Property metadata key must not be empty");if(o.has(m))throw new d("PLUGIN_PROPERTY_METADATA_KEY_ALREADY_REGISTERED",`Plugin Property metadata key is already registered: ${m}`,{key:m,plugin:l.name});o.add(m)}for(const m of l.operators??[]){if(i.has(m.name))throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${m.name}`,{operator:m.name,plugin:l.name});i.add(m.name)}for(const m of l.semanticTypes??[]){if(s.has(m.name))throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${m.name}`,{semanticType:m.name,plugin:l.name});s.add(m.name)}for(const m of l.plannerSemantics??[]){if(!m.name||a.has(m.name))throw new d("PLUGIN_SEMANTIC_RULE_ALREADY_REGISTERED",`Plugin Planner semantic rule must be non-empty and unique: ${m.name}`,{rule:m.name,plugin:l.name});a.add(m.name)}for(const m of l.queryOperators??[]){if(!m.name||u.has(m.name))throw new d("PLUGIN_QUERY_OPERATOR_ALREADY_REGISTERED",`Plugin Query Operator must be non-empty and unique: ${m.name}`,{operator:m.name,plugin:l.name});u.add(m.name)}for(const m of l.outputHandlers??[]){if(!m.type||c.has(m.type))throw new d("PLUGIN_OUTPUT_HANDLER_ALREADY_REGISTERED",`Plugin output handler type must be non-empty and unique: ${m.type}`,{type:m.type,plugin:l.name});c.add(m.type)}const f=l.mappingGranularity;if(f){if(!f.kind||p.has(f.kind))throw new d("PLUGIN_GRANULARITY_ALREADY_REGISTERED",`Plugin physical granularity kind must be non-empty and unique: ${f.kind}`);p.add(f.kind)}}return Object.freeze(e)},At=(t,e=[])=>me(e).flatMap(r=>r.queryOperators??[]).find(r=>r.name===t),mi=(t,e=[])=>me(e).flatMap(r=>r.outputHandlers??[]).find(r=>r.type===t),mn=(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},yi=(t,e=[])=>mn("interval semantics",me(e).flatMap(r=>{const n=r.intervalSemantics?.resolve(t);return n?[{plugin:r.name,value:n}]:[]})),vc=(t,e,r=[])=>mn("relation semantics",me(r).flatMap(n=>{const o=n.relationSemantics?.plan({sourceSchema:t,targetSchema:e});return o?[{plugin:n.name,value:o}]:[]})),Fc=(t,e,r=[])=>mn("planner period semantics",me(r).flatMap(n=>{const o=n.plannerPeriod?.resolve(t,e);return o?[{plugin:n.name,value:o}]:[]})),yn=t=>typeof t=="string"&&t.length>0&&t!=="placeholder"||typeof t=="number"&&Number.isSafeInteger(t),Yc=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 me(e)){const n=r.resolveEntityFilterProperty?.(t);if(n)return n}return Yc(t)},gn=t=>{if(t.name)return t.name;throw new d("MISSING_PRED_NAME","A normalized groupby PredItem must have a name")},$n=t=>typeof t.pred=="string"?t.pred:void 0,Hc=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Qc={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Gc={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},An=(t,e,r)=>{const n=e.toLowerCase().startsWith("en"),o=t.time;if(!Hc(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}${Qc[o.granularity]??"\u671F"}`}const i=Object.entries(o).map(([s,a])=>n?`${s} ${String(a)}`:`${String(a)}${Gc[s]??s}`).join(n?", ":"");return n?`compared with ${i}`:`\u5BF9\u6BD4${i}`};ue.extend(Mt),ue.extend(ar);const Wc=["second","minute","hour","day","week","month","quarter","year"],zc=new Set(Wc),wn=["year","quarter","month","week","day","hour","minute","second"],hi=t=>Object.prototype.toString.call(t)==="[object Object]",We=t=>{throw new d("INVALID_PERIOD_SHIFT_ARGS",t)},Kc=t=>{const e=t.time;hi(e)||We("$periodShift requires args.time");const r=e;if("granularity"in r||"offset"in r)return(typeof r.granularity!="string"||!zc.has(r.granularity)||!Number.isInteger(r.offset)||Object.keys(r).some(a=>a!=="granularity"&&a!=="offset"))&&We("Relative period shift time requires only granularity and an integer offset"),r;const o=Object.entries(r);(o.length===0||o.some(([a,u])=>!wn.includes(a)||!Number.isInteger(u)))&&We("Absolute period shift time requires integer calendar components"),typeof r.year!="number"&&We("Absolute period shift time requires year");const i={quarter:[1,4],month:[1,12],week:[1,53],day:[1,31],hour:[0,23],minute:[0,59],second:[0,59]};for(const[a,[u,c]]of Object.entries(i)){const p=r[a];p!==void 0&&(Number(p)<u||Number(p)>c)&&We(`Invalid absolute period shift ${a}: ${JSON.stringify(p)}`)}return["quarter","month","week"].filter(a=>a in r).length>1&&We("Absolute period shift time cannot mix quarter, month, and week"),"day"in r&&!("month"in r)&&We("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),Jc=(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},En=(t,e)=>t instanceof Date?e.toDate():typeof t!="string"?t:e.format(t.includes(":")?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"),Xc=(t,e,r,n,o)=>(t.groupby??[]).filter(i=>{const s=$n(i);return s?de(e,s,r).property.primal_type==="date":!1}).map(i=>{const s=i.operator==="$dateBucket"?i.args?.granularity:void 0,a="granularity"in n?n.granularity:s??"day",u="granularity"in n?-n.offset:o.originalAnchor&&o.shiftedAnchor?o.originalAnchor.diff(o.shiftedAnchor,a):0;return{name:gn(i),granularity:a,offset:u}}),_n=(t,e,r)=>{if(Array.isArray(t))return t.map(i=>_n(i,e,r));if(hi(t))return Object.fromEntries(Object.entries(t).map(([i,s])=>[i,_n(s,e,r)]));if(!(t instanceof Date)&&typeof t!="string")return t;const n=ue(t);if(!n.isValid())return t;const o=Jc(n,e);return r.originalAnchor??=n,r.shiftedAnchor??=o,r.shiftedValues+=1,En(t,o)},Zc=(t,e,r,n,o)=>{const i=new Set,s=u=>Object.fromEntries(Object.entries(u).map(([c,p])=>{if((c==="$and"||c==="$or")&&Array.isArray(p))return[c,p.map(f=>s(f))];const l=de(e,c,r);return l.property.primal_type!=="date"?[c,p]:(i.add(l.canonicalName),[c,_n(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},tt=t=>{const e=t.filter(r=>r!==void 0);if(e.length!==0)return e.length===1?e[0]:{$and:e}},ze=t=>[...t.query?[t.query]:[],...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?ze(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(r=>typeof r=="string"?[]:ze(r)):[]],eu=(t,e,r)=>{if(!(t instanceof Date)&&typeof t!="string")return t;const n=ue(t);if(!n.isValid())return t;if("granularity"in e)return En(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 En(t,o)},Sn=({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o})=>{const i=e.pred;(!i||typeof i!="object"||Array.isArray(i))&&We("$periodShift pred must be a nested metric");const s=Kc(e.args??{}),a={shiftedValues:0},u=tt([t.query,...ze(e)]);if(!u)throw new d("PERIOD_SHIFT_TIME_QUERY_REQUIRED","$periodShift requires a date condition in the LogicForm query");const c=Zc(u,n,o,s,a),p=ne(i);p.name=r,delete p.query;const l=ne(t);l.query=c,l.preds=[p],delete l.having,delete l.sort,delete l.limit,delete l.page;const f=new Set((t.groupby??[]).filter(m=>{const y=$n(m);return y?de(n,y,o).property.primal_type==="date":!1}).map(gn));return{kind:"query",logicform:l,groupKeyShifts:Xc(t,n,o,s,a),mapResult:m=>m.map(y=>{const h={...y};for(const g of f)h[g]=eu(h[g],s,a);return h})}},tu={name:"$periodShift",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=An(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} baseline`:`${t}${o}\u57FA\u671F\u503C`;return n?.("operator.$periodShift",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:Sn,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodShift requires a nested metric");return{...e,name:t,isArray:!1}}},ru=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),$r=t=>typeof t=="string"||typeof t=="number"||t instanceof Date,$i=(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},Ai=(t,e)=>{if($r(t)){e.start??=t,e.end??=t;return}if(!ru(t))return;const r=t.$eq;$r(r)&&(e.start??=r,e.end??=r);const n=t.$gte??t.$gt,o=t.$lte??t.$lt;$r(n)&&(e.start??=n),$r(o)&&(e.end??=o);for(const i of["$and","$or"]){const s=t[i];if(Array.isArray(s))for(const a of s)Ai(a,e)}},nu=(t,e,r,n)=>{const o=$i(e,n),i=new Set,s={},a=(l,f)=>{for(const[m,y]of Object.entries(l)){if((m==="$and"||m==="$or")&&Array.isArray(y)){for(const g of y)a(g,f||m==="$or");continue}if(m.startsWith("$"))continue;const h=de(e,m,r);if(h.property.type==="timestamp"){if(f)throw new d("AMBIGUOUS_TIME_QUERY",`${n} does not support timestamp conditions inside $or`);i.add(h.canonicalName),Ai(y,s)}}};if(a(t,!1),i.size!==1)throw new d(i.size===0?"TIME_QUERY_REQUIRED":"AMBIGUOUS_TIME_QUERY",`${n} requires a concrete condition on the Schema timestamp property`);const u=[...i][0];if(!u||u!==o.name)throw new d("AMBIGUOUS_TIME_QUERY",`${n} requires the Schema timestamp property: ${o.name}`);const c=l=>{const f=[];for(const[m,y]of Object.entries(l)){if((m==="$and"||m==="$or")&&Array.isArray(y)){const h=y.map(g=>c(g)).filter(g=>g!==void 0);h.length>0&&f.push([m,h]);continue}!m.startsWith("$")&&de(e,m,r).property.type==="timestamp"||f.push([m,y])}return f.length>0?Object.fromEntries(f):void 0},p=c(t);return{property:o,propertyName:u,...s.start!==void 0?{start:s.start}:{},...s.end!==void 0?{end:s.end}:{},...p?{queryWithoutTime:p}:{}}},wi=(t,e,r,n,o)=>{const i=tt([t,...ze(e)]);if(!i)throw new d("TIME_QUERY_REQUIRED",`${o} requires a timestamp query`);return nu(i,r,n,o)},Ei=(t,e,r)=>tt([t,{[e]:r}]),ou=new Set(["day","week","month","quarter","year"]),iu={day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},su=t=>{if(typeof t!="string"||!ou.has(t))throw new d("INVALID_AVERAGE_PER_PERIOD_ARGS","$averagePerPeriod args.granularity must be day, week, month, quarter, or year");return t},_i=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},In=t=>{const e=ne(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=In(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:In(r))),e},au={name:"$averagePerPeriod",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`Average ${t} per ${typeof e.granularity=="string"?e.granularity:"period"}`:`${t}${iu[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=su(e.args?.granularity),s=$i(r,"$averagePerPeriod"),a=In(e.pred),u=tt([t.query,...ze(e)]),c=_i(t);c.preds=[{...a,name:"__avg_period_num__"}],u&&(c.query=u);const p=_i(t);p.preds=[{operator:"$countDistinct",pred:{operator:"$dateBucket",pred:s.name,args:{granularity:i},name:"__avg_period_bucket__"},name:"__avg_period_den__"}],u&&(p.query=u);const l=o("component.numerator",`${n}\u5206\u5B50`,{outputName:n}),f=o("component.denominator",`${n}\u5206\u6BCD`,{outputName:n});return{components:[{name:l,logicform:c},{name:f,logicform:p}],expression:`${l} / NULLIF(${f}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$averagePerPeriod requires a nested metric");return{...e,name:t,isArray:!1}}},cu={name:"$avg",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Average ${t}`:`\u5E73\u5747${t}`,kind:"aggregate",toSQL(t){const{column:e,sql:r}=t;if(!e)throw new Error("$avg requires a column");return r.aggregateFunction("avg",e)},getOutputProperty({name:t,property:e,inputProperty:r}){const n=e??r;if(!n)throw new Error("$avg requires a property");return{name:t,type:n.type,primal_type:n.primal_type,isArray:!1}}},wt=t=>{throw new d("INVALID_CASE_ARGS",t)},uu=t=>{if(t.mode!=="auto")return;Object.hasOwn(t,"cases")&&wt("$case auto mode cannot define args.cases"),t.empty!==void 0&&typeof t.empty!="boolean"&&wt("$case auto mode args.empty must be boolean");const e=t.buckets;e!==void 0&&(!Number.isInteger(e)||e<2||e>100)&&wt("$case auto mode args.buckets must be an integer between 2 and 100");const r=t.count;if(r!==void 0&&(!Number.isSafeInteger(r)||r<0)&&wt("$case auto mode args.count must be a non-negative safe integer"),t.empty===!0)return{empty:!0};for(const o of["min","max"])(typeof t[o]!="number"||!Number.isFinite(t[o]))&&wt(`$case auto mode requires resolved finite args.${o}`);t.min>t.max&&wt("$case auto mode args.min cannot be greater than args.max");const n=e===void 0?r===void 0?10:Math.min(12,Math.max(5,Math.ceil(Math.log2(Math.max(r,1))+1))):e;return{empty:!1,minimum:t.min,maximum:t.max,targetBuckets:n}},du=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},Ar=t=>{const e=Number(t.toPrecision(15));return Object.is(e,-0)?0:e},bn=t=>String(Ar(t)),lu=(t,e,r)=>{if(t===e)return[t,e];const n=du((e-t)/r),o=Ar(Math.floor(t/n)*n),i=Ar(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:Ar(o+n*u))},pu=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}})},fu={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=uu(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(bn(a))} END`;const c=lu(a,u,n.targetBuckets),p=c.slice(0,-1).map((f,m)=>{const y=c[m+1],h=m===c.length-2?"]":")";return`[${bn(f)}, ${bn(y)}${h}`}),l=p.slice(0,-1).map((f,m)=>`WHEN ${t} < ${r.value(c[m+1])} THEN ${r.value(f)}`);return`CASE WHEN ${t} IS NULL THEN ${s} ${l.join(" ")} ELSE ${r.value(p.at(-1))} END`}const o=pu(e.cases).map(({when:s,then:a})=>`WHEN ${r.condition(t,s)} THEN ${r.value(a)}`),i=Object.hasOwn(e,"default")?` ELSE ${r.value(e.default)}`:"";return`CASE ${o.join(" ")}${i} END`},getOutputProperty({name:t}){return{name:t,type:"category",primal_type:"string",isArray:!1}}},mu={name:"$concat",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?`Combined ${e.join(" and ")}`:`Combined ${t}`:e.length>0?`${e.join("\u4E0E")}\u62FC\u63A5\u503C`:`${t}\u62FC\u63A5\u503C`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$concat.empty":"operator.$concat",kind:"scalar",requiresProperty:!1,toSQL(t){return t.sql.concat(ht("$concat",t,1,Number.POSITIVE_INFINITY))},getOutputProperty({name:t}){return{name:t,type:"string",primal_type:"string",isArray:!1}}},yu={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}}},hu={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}}},gu=new Set(["second","minute","hour","day","week","month","quarter","year"]),$u={second:"\u79D2",minute:"\u5206\u949F",hour:"\u5C0F\u65F6",day:"\u65E5",week:"\u5468",month:"\u6708",quarter:"\u5B63\u5EA6",year:"\u5E74"},Si=t=>{if(typeof t!="string"||!gu.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},Au={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${$u[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,Si(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=Si(r.granularity);return{...e,name:t,type:"date",primal_type:"date",isArray:!1,granularity:n}}},wu={name:"$divide",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>=2?`${e[0]} divided by ${e[1]}`:`${t} ratio`:e.length>=2?`${e[0]}\u9664\u4EE5${e[1]}`:`${t}\u6BD4\u503C`,defaultNameKey:({inputNames:t})=>t.length<2?"operator.$divide.fallback":"operator.$divide",kind:"scalar",requiresProperty:!1,toSQL(t){const[e,r]=ht("$divide",t,2);return`(${e} / NULLIF(${r}, 0))`},getOutputProperty({name:t}){return mr(t)}},Eu=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}}}},_u={name:"$max",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Maximum ${t}`:`${t}\u6700\u5927\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Eu,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}:{}}}},Su=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}}}},Iu={name:"$min",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`Minimum ${t}`:`${t}\u6700\u5C0F\u503C`,kind:"aggregate",supportsGroupedSourceRollup:!0,planExpression:Su,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}:{}}}},bu={name:"$multiply",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>0?e.join(" times "):`Product of ${t}`:e.length>0?e.join("\u4E58\u4EE5"):`${t}\u4E58\u79EF`,defaultNameKey:({inputNames:t})=>t.length===0?"operator.$multiply.empty":"operator.$multiply",kind:"scalar",requiresProperty:!1,toSQL(t){return`(${ht("$multiply",t,2,Number.POSITIVE_INFINITY).join(" * ")})`},getOutputProperty({name:t}){return mr(t)}},Ru=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Rn=t=>{const e=ne(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Rn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Rn(r))),e},Nu={name:"$newly",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`New ${t}`:`\u65B0\u589E${t}`,kind:"component",createComponent({logicform:t,pred:e,schema:r,resolveSchema:n,outputName:o,t:i}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_NEWLY_INPUT","$newly pred must be a nested metric");if((t.groupby??[]).some(l=>{const f=$n(l);return f?de(r,f,n).property.type==="timestamp":!1}))throw new d("NEWLY_TIME_GROUPBY_UNSUPPORTED","$newly does not support grouping by the timestamp property");const s=wi(t.query,e,r,n,"$newly");if(s.start===void 0||s.end===void 0)throw new d("NEWLY_RANGE_REQUIRED","$newly requires both start and end timestamp bounds");const a=Rn(e.pred),u=(l,f)=>{const m=Ru(t);return m.query=Ei(s.queryWithoutTime,s.propertyName,{$lte:l}),m.preds=[{...a,name:f}],m},c=i("component.end",`${o}\u7ED3\u675F`,{outputName:o}),p=i("component.start",`${o}\u5F00\u59CB`,{outputName:o});return{components:[{name:c,logicform:u(s.end,"__newly_end__")},{name:p,logicform:u(s.start,"__newly_start__")}],expression:`${c} - COALESCE(${p}, 0)`}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$newly requires a nested metric");return{...e,name:t,isArray:!1}}},Ou=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Nn=t=>{const e=ne(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=Nn(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:Nn(r))),e},Tu={name:"$periodValue",defaultName:({operandName:t,args:e,locale:r})=>r.toLowerCase().startsWith("en")?`${t} at period ${e.boundary==="start"?"start":"end"}`:`${t}${e.boundary==="start"?"\u671F\u521D\u503C":"\u671F\u672B\u503C"}`,defaultNameKey:({args:t})=>`operator.$periodValue.${t.boundary==="start"?"start":"end"}`,kind:"component",skipComponentExecution:({plan:t})=>t.periodSource?.match.kind==="latest",periodBoundaryPolicy({pred:t}){const e=t.args?.boundary;if(e!=="start"&&e!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end",{boundary:e});return{boundary:e,implicit:!1}},createComponent({logicform:t,pred:e,outputName:r,schema:n,resolveSchema:o}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_PERIOD_BOUNDARY_INPUT","$periodValue pred must be a nested metric");const i=e.args?.boundary;if(i!=="start"&&i!=="end")throw new d("INVALID_PERIOD_BOUNDARY_ARGS","$periodValue args.boundary must be start or end");const s=wi(t.query,e,n,o,"$periodValue"),a=i==="start"?s.start:s.end;if(a===void 0)throw new d("PERIOD_BOUNDARY_RANGE_REQUIRED",`$periodValue cannot resolve the ${i} of the timestamp query`);const u={version:t.version,schema:n.id,query:{[s.propertyName]:{$lte:a}},preds:[{operator:"$max",pred:s.propertyName,name:"__period_boundary_date__"}]},c=Ou(t);return c.query=Ei(s.queryWithoutTime,s.propertyName,u),c.preds=[{...Nn(e.pred),name:r}],{kind:"query",logicform:c}},getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodValue requires a nested metric");return{...e,name:t,isArray:!1}}},Pu=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},Lu=({logicform:t,pred:e,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new Error("$periodDifference pred must be a nested metric");const a=ne(e.pred);a.name="__period_diff_current__";const u=Pu(t);u.preds=[a];const c=tt([t.query,...ze(e)]);c&&(u.query=c);const p={pred:ne(e.pred),...e.args?{args:e.args}:{}},l=Sn({logicform:t,pred:p,outputName:"__period_diff_prev__",schema:i,resolveSchema:s});if(!("logicform"in l))throw new Error("$periodDifference period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:u},{name:m,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${f} - ${m}`}},Du={name:"$periodDifference",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=An(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} difference`:`${t}${o}\u5DEE\u503C`;return n?.("operator.$periodDifference",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:Lu,getOutputProperty({name:t,inputProperty:e}){if(!e)throw new Error("$periodDifference requires a nested metric");return{...e,name:t,isArray:!1}}},Cu=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},ku=({logicform:t,pred:e,outputName:r,locale:n,t:o,schema:i,resolveSchema:s})=>{if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new Error("$periodGrowth pred must be a nested metric");const a=ne(e.pred);a.name="__period_growth_current__";const u=Cu(t);u.preds=[a];const c=tt([t.query,...ze(e)]);c&&(u.query=c);const p={pred:ne(e.pred),...e.args?{args:e.args}:{}},l=Sn({logicform:t,pred:p,outputName:"__period_growth_prev__",schema:i,resolveSchema:s});if(!("logicform"in l))throw new Error("$periodGrowth period shift must produce a query component");const f=o("component.current",`${r}\u672C\u671F`,{outputName:r}),m=o("component.previous",`${r}\u4E0A\u671F`,{outputName:r});return{components:[{name:f,logicform:u},{name:m,logicform:l.logicform,...l.groupKeyShifts?{groupKeyShifts:l.groupKeyShifts}:{}}],expression:`${f} / NULLIF(ABS(${m}), 0) - 1`}},Uu={name:"$periodGrowth",defaultNameIsLocalized:!0,defaultName:({operandName:t,args:e,locale:r,t:n})=>{const o=An(e,r,n),i=r.toLowerCase().startsWith("en")?`${t} ${o} growth`:`${t}${o}\u589E\u957F\u7387`;return n?.("operator.$periodGrowth",i,{operandName:t,comparison:o})??i},kind:"component",createComponent:ku,getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},Mu={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}}},qu={name:"$subtract",defaultName:({operandName:t,inputNames:e,locale:r})=>r.toLowerCase().startsWith("en")?e.length>=2?`${e[0]} minus ${e[1]}`:`${t} difference`:e.length>=2?`${e[0]}\u51CF\u53BB${e[1]}`:`${t}\u5DEE\u503C`,defaultNameKey:({inputNames:t})=>t.length<2?"operator.$subtract.fallback":"operator.$subtract",kind:"scalar",requiresProperty:!1,toSQL(t){const[e,r]=ht("$subtract",t,2);if(t.args.nullAsZero!==void 0&&typeof t.args.nullAsZero!="boolean")throw new d("INVALID_SUBTRACT_ARGS","$subtract args.nullAsZero must be boolean");return t.args.nullAsZero===!0?`(COALESCE(${e}, 0) - COALESCE(${r}, 0))`:`(${e} - ${r})`},getOutputProperty({name:t,inputProperties:e}){const r=e?.[0];return r?{...r,name:t,isArray:!1}:mr(t)}},Ii=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},On=t=>{const e=ne(t);return delete e.query,e.pred&&typeof e.pred=="object"&&!Array.isArray(e.pred)&&(e.pred=On(e.pred)),Array.isArray(e.pred)&&(e.pred=e.pred.map(r=>typeof r=="string"?r:On(r))),e},ju={name:"$shareOfTotal",defaultName:({operandName:t,locale:e})=>e.toLowerCase().startsWith("en")?`${t} share of total`:`${t}\u5360\u6BD4`,kind:"component",createComponent({logicform:t,pred:e,outputName:r,t:n}){if(!e.pred||typeof e.pred!="object"||Array.isArray(e.pred))throw new d("INVALID_SHARE_OF_TOTAL_INPUT","$shareOfTotal pred must be a nested metric");const o=e.args?.dimension;if(o!==void 0&&typeof o!="string")throw new d("INVALID_SHARE_OF_TOTAL_ARGS","$shareOfTotal args.dimension must be a groupby pred or output name");const i=t.groupby??[],s=o===void 0?i.length-1:i.findIndex(y=>typeof y.pred=="string"&&y.pred===o||gn(y)===o);if(o!==void 0&&s<0)throw new d("SHARE_OF_TOTAL_DIMENSION_NOT_FOUND",`$shareOfTotal dimension is not grouped: ${o}`);const a=i.filter((y,h)=>h!==s),u=On(e.pred),c=Ii(t);c.preds=[{...u,name:"__share_numerator__"}];const p=tt([t.query,...ze(e)]);p&&(c.query=p);const l=Ii(t);l.groupby=a,l.preds=[{...u,name:"__share_denominator__"}];const f=n("component.numerator",`${r}\u5206\u5B50`,{outputName:r}),m=n("component.denominator",`${r}\u5206\u6BCD`,{outputName:r});return{components:[{name:f,logicform:c},{name:m,logicform:l}],expression:`${f} / NULLIF(${m}, 0)`}},getOutputProperty({name:t}){return{name:t,type:"percentage",primal_type:"number",isArray:!1}}},xu={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}}},bi=(t,e,r,n="$sql")=>{if(typeof t!="string"||t.trim().length===0)throw new d("INVALID_SQL_ARGS",`${n} requires a non-empty args.sql expression`);let o="",i=0,s;for(let a=0;a<t.length;a+=1){const u=t[a];if(!u)continue;if(s){o+=u,u===s&&(t[a+1]===s?(o+=s,a+=1):s=void 0);continue}if(u==="'"||u==='"'||u==="`"){s=u,o+=u;continue}const c=t.slice(a,a+2);if(u===";"||c==="--"||c==="/*")throw new d("INVALID_SQL_EXPRESSION",`${n} accepts one expression and does not allow statements or SQL comments`);if(u==="?"){if(i>=e.length)throw new d("INVALID_SQL_PARAMETERS",`${n} contains more placeholders than args.parameters values`);o+=r(e[i]),i+=1;continue}o+=u}if(s)throw new d("INVALID_SQL_EXPRESSION",`${n} contains an unterminated quote`);if(i!==e.length)throw new d("INVALID_SQL_PARAMETERS",`${n} args.parameters contains more values than SQL placeholders`);return o},Bu=new Set(["boolean","date","number","entity","object","string"]),Vu=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},vu=(t,e)=>{const r=e.type,n=e.primal_type;if(typeof r!="string"||r.length===0||!Bu.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}:{}}},Fu={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 bi(t.sql,Vu(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 vu(t,e)}},Yu=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]},Hu=t=>typeof t.pred!="string"?t:{...t,pred:{operator:"$sum",pred:t.pred,name:`${t.pred}\u5408\u8BA1`}},Qu=(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=Yu(r),[s]=i;if(i.length!==1||!s)throw new d("AMBIGUOUS_RANK_DIMENSION","$rank pred.query must reference exactly one property when groupby is omitted",{properties:i});const a=ne(t);a.groupby=[{pred:s,name:s}],a.preds=n.map(p=>{if(p.name!==e.name)return p;const l={...p};return delete l.query,Hu(l)}),delete a.sort,delete a.limit,delete a.limitBy,delete a.page,delete a.output,delete a.representation;const u=n.map(({name:p})=>p).filter(p=>!!p),c=ne(t);return c.from=a,c.query=r,c.preds=[{pred:s,name:s},...u.map(p=>({pred:p,name:p}))],delete c.groupby,delete c.having,delete c.entity_id,delete c.propertyResolve,c},Gu={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?Qu(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}}},Wu={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}}},zu=new Set(["string","number","boolean","date","entity","object"]),Tn=t=>{if(t==="timestamp"||t==="date")return{type:t,primal_type:"date"};if(typeof t=="string"&&zu.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")},Ku={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 Tn(t.args?.type),t},toSQL({args:t,sql:e}){return Tn(t.type),e.value(t.value,t.type)},getOutputProperty({name:t,args:e}){return{name:t,...Tn(e.type),isArray:!1}}},Ju={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}}},Ri="__scalarExtremumInputs",Pn=t=>{if(t.schema)return t.schema;if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred))return Pn(t.pred);if(Array.isArray(t.pred)){const e=[...new Set(t.pred.flatMap(r=>typeof r=="string"?[]:Pn(r)??[]))];if(e.length===1)return e[0]}},Xu=t=>{const e=ne(t);return delete e.from,delete e.having,delete e.sort,delete e.limit,delete e.limitBy,delete e.page,delete e.representation,delete e.output,e},Zu=(t,e)=>{if(e.args?.[Ri]===!0||!Array.isArray(e.pred))return;if(t.preds?.length!==1)throw new d("SCALAR_EXTREMUM_SINGLE_PROJECTION_REQUIRED",`${e.operator} with multiple pred inputs must be the only LogicForm projection`);const r=e.pred.map((o,i)=>{const s=typeof o=="string"?{pred:o}:ne(o),a=s.name??`__scalar_extremum_input_${i}__`,u=s.schema??Pn(s);return{...s,name:a,...u?{schema:u}:{}}}),n=Xu(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,[Ri]:!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}:{}}},ed=(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)`},td=(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}},Ni=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?Zu(e,r):void 0},toSQL(e){const r=ht(t,e,2,Number.POSITIVE_INFINITY);return e.sql.scalarExtremum?.(t==="$least"?"least":"greatest",r)??ed(t,r)},getOutputProperty({name:e,inputProperties:r}){return td(t,e,r)}}),rd=Ni("$least"),nd=Ni("$greatest"),Ln={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"}},od={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}}},id=t=>({name:`$${t}`,defaultName:({operandName:e,locale:r})=>r.toLowerCase().startsWith("en")?`${e} ${Ln[t].en}`:`${e}${Ln[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}}}),sd=Object.freeze(Object.keys(Ln).map(id)),Oi=Object.freeze([ec,Mu,yu,hu,cu,Iu,_u,tu,Uu,Du,au,Tu,Nu,rc,qu,bu,wu,tc,ju,fu,mu,xu,Au,Fu,Gu,Wu,Ku,Ju,rd,nd,od,...sd]),ad={name:"boolean",primalType:"boolean",hydrateResult(t){return typeof t=="number"?t===1:t}},cd={name:"category",primalType:"string"},ud={name:"currency",primalType:"number"},dd={name:"date",primalType:"date"},ld={name:"duration",primalType:"number"},Ti=(t,{property:e,requestEntity:r})=>!e.ref||t===void 0||t===null||typeof t=="object"&&!Array.isArray(t)?t:r(e.ref,t),pd={name:"object",primalType:"object",hydrateResult:Ti},fd={name:"entity",primalType:"entity",hydrateResult:Ti},md={name:"file",primalType:"string"},yd={name:"humanName",primalType:"string"},hd={name:"ID",primalType:"string"},gd={name:"image",primalType:"string"},$d={name:"int",primalType:"number"},Ad={name:"name",primalType:"string"},wd={name:"number",primalType:"number"},Ed={name:"order",primalType:"number"},_d={name:"percentage",primalType:"number"},Sd={name:"string",primalType:"string"},Id={name:"timestamp",primalType:"date"},Dn=Object.freeze([hd,Sd,Ad,yd,cd,gd,md,wd,$d,ud,_d,ld,Ed,ad,Id,dd,fd,pd]),bd=(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},Pi=t=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError("Operator definition must be an object");const e=t,r=e.name,n=typeof r=="string"?r:"",o=e.type,i=new Set(["defaultName","getOutputProperty","planInput","normalizePred","planExpression","periodBoundaryPolicy","validatePlan","rewriteLogicform","requiresPerPeriodEvaluation","toSQL","evaluate","createComponent"]),s=Object.fromEntries(Object.entries(e).filter(([a])=>!i.has(a)));s.name=r;for(const a of i){const u=bd(e[a],a,n);u&&(s[a]=u)}if(!s.getOutputProperty&&typeof o=="string"){const a=Dn.find(({name:u})=>u===o);if(!a)throw new TypeError(`Semantic type is not registered: ${o}`);s.getOutputProperty=()=>({name:n,type:o,primal_type:a.primalType,isArray:!1})}return s};class wr{#e=new Map;constructor(e=[]){for(const r of e)this.register(r)}register(e){const r=Pi(e);if(!r.name)throw new d("INVALID_OPERATOR","Operator name must not be empty");if(typeof r.defaultName!="function")throw new d("INVALID_OPERATOR",`Operator must implement defaultName: ${r.name}`);if(this.#e.has(r.name))throw new d("OPERATOR_ALREADY_REGISTERED",`Operator is already registered: ${r.name}`,{operator:r.name});const n=r;if(!(n.kind==="scalar"&&(typeof n.toSQL=="function"||typeof n.evaluate=="function")||n.kind==="aggregate"&&typeof n.toSQL=="function"||n.kind==="component"&&typeof n.createComponent=="function"||n.kind==="window"&&typeof n.windowFunction=="string"||n.kind==="logical"&&typeof n.planExpression=="function"))throw new d("INVALID_OPERATOR",`Operator kind and implementation do not match: ${r.name}`);return this.#e.set(r.name,r),this}get(e){const r=this.#e.get(e);if(!r)throw new d("OPERATOR_NOT_FOUND",`Operator is not registered: ${e}`,{operator:e});return r}requiresPerPeriodEvaluation(e,r){return this.get(e).requiresPerPeriodEvaluation?.(r)??!1}has(e){return this.#e.has(e)}definitions(){return[...this.#e.values()]}}const Rd=Object.freeze([...Oi,...fi.flatMap(({operators:t})=>t??[])]),Le=(t=[])=>new wr([...Oi,...me(t).flatMap(({operators:e})=>e??[])]),Et=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="logicform-subquery"&&typeof t.plan=="object"&&t.plan!==null,Li=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="query-operator"&&typeof t.operator=="string",Nd=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="ordinal-query",Di=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.kind==="expression-query",Od=(t,e)=>{const r=oc(t,e);return{schemaId:t.id,propertyId:r.id,propertyName:r.name,physicalColumn:r.udf?.sql??r.id}},Ci=(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}:Od(e,r)},Ft=(t,e,r,n)=>{if(t.kind==="column")return{sources:[{schemaId:t.schemaId??r.id,propertyId:t.propertyId??t.column,propertyName:t.property,physicalColumn:t.column}],transformations:["projection"]};if(t.kind==="property-sql")return{sources:[{schemaId:t.schemaId,propertyId:t.propertyId,propertyName:t.property,physicalColumn:t.sql}],transformations:["property-sql"]};if(t.kind==="array-element")return{sources:[{schemaId:t.schemaId,propertyId:t.property,propertyName:t.property,physicalColumn:t.property}],transformations:["array-expand"]};if(t.kind==="window"){const u=[t.input,...t.partitionBy].map(c=>Ft(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:${t.function}`]}}if(t.kind==="cumulative"){const u=[t.input,...t.partitionBy,...t.orderBy.map(({expression:c})=>c)].map(c=>Ft(c,e,r,n));return{sources:u.flatMap(({sources:c})=>c),transformations:[...u.flatMap(({transformations:c})=>c).filter(c=>c!=="projection"),`window:cumulative:${t.function}`]}}if(t.kind==="ordinal-encode"||t.kind==="ordinal-decode"){const u=Ft(t.input,e,r,n);return{sources:u.sources,transformations:[...u.transformations.filter(c=>c!=="projection"),`ordinal:${t.kind==="ordinal-encode"?"encode":"decode"}`]}}const o=[...t.input?[t.input]:[],...t.inputs??[]].map(u=>Ft(u,e,r,n)),i={sources:o.flatMap(({sources:u})=>u),transformations:o.flatMap(({transformations:u})=>u)},s=n.get(t.operator),a=new Set([...t.property?[t.property]:[],...s.dependencies??[],...Er(t.query)]);return{sources:[...i.sources,...[...a].filter(u=>!i.sources.some(c=>c.propertyName===u)).map(u=>Ci(e,r,u))],transformations:[...i.transformations.filter(u=>u!=="projection"),`operator:${t.operator}`]}};function Er(t){if(!t)return[];const e=[];for(const[r,n]of Object.entries(t))if((r==="$and"||r==="$or")&&Array.isArray(n))for(const o of n)typeof o=="object"&&o!==null&&!Array.isArray(o)&&e.push(...Er(o));else r==="$expr"&&Di(n)?e.push(...n.properties):r.startsWith("$")||e.push(r);return e}const Ve=t=>t.kind==="window"?[...Ve(t.input),...t.partitionBy.flatMap(Ve)]:t.kind==="cumulative"?[...Ve(t.input),...t.partitionBy.flatMap(Ve),...t.orderBy.flatMap(({expression:e})=>Ve(e))]:t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?Ve(t.input):t.kind==="operator"?[...Er(t.query),...t.input?Ve(t.input):[],...(t.inputs??[]).flatMap(Ve)]:[],ki=(t,e,r,n=Le(),o)=>{if(t.subplans){const s=t.subplans.map(u=>ki(u,e,r,n,o)),a=new Map;for(const u of s){u.source.connectionId&&a.set(u.source.connectionId,u.source.provider);for(const c of u.source.connections??[])a.set(c.connectionId,c.provider)}return{source:{schemaId:e.id,schemaName:e.name,physicalTable:s.map(({source:u})=>u.physicalTable).join(", "),provider:r.kind,connections:[...a].map(([u,c])=>({connectionId:u,provider:c}))},outputs:t.projections.map(({name:u})=>{const c=s.flatMap(({outputs:p})=>p.filter(l=>l.name===u));return{name:u,sources:c.flatMap(({sources:p})=>p),transformations:[...new Set([...c.flatMap(({transformations:p})=>p),"compose"])]}}),filters:s.flatMap(({filters:u})=>u)}}const i=t.connectionId&&o?o(t.connectionId):r;return{source:{schemaId:e.id,schemaName:e.name,physicalTable:[t.source,...(t.enrichmentJoins??[]).map(({source:s})=>s)].filter(Boolean).join(", "),provider:i.kind,...t.connectionId?{connectionId:t.connectionId}:{}},outputs:t.projections.map(s=>({name:s.name,...Ft(s.expression,t,e,n)})),filters:[...new Set([...Er(t.query),...t.projections.flatMap(({expression:s})=>Ve(s))])].map(s=>Ci(t,e,s))}},Se=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.version=="string"&&(typeof t.schema=="string"||typeof t.from=="object"),Td=/^(\d{2}):(\d{2})(?::(\d{2}))?$/,Ui=t=>{const e=Td.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}},Mi=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(!Ui(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}`)}}}},Pd=new Set(["second","minute","hour","day","week","month","quarter","year"]),Cn=t=>typeof t=="string"&&Pd.has(t),kn=(t,e=me())=>Cn(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 Un{#e=new Map;plugins;constructor(e=[],r=[]){this.plugins=me(r);for(const n of e)this.register(n)}register(e){for(const s of this.plugins){const a=s.schemaMapping?.validate?.(e);if(a)throw new d("INVALID_SCHEMA_MAPPING_PLUGIN",`Schema mapping is rejected by plugin ${s.name}: ${a}`,{plugin:s.name,reason:a})}if(!e.schemaId)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping schemaId must not be empty");if(!e.source)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping source must not be empty");if(e.sourceSql!==void 0&&e.sourceSql.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping sourceSql must not be empty");if(e.id!==void 0&&!e.id)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping id must not be empty");if(e.connectionId.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping connectionId must not be empty");if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping priority must be finite");if("dimensions"in e)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping dimensions is removed; declare time granularity on property mapping items");const r=new Set,n=new Set;for(const s of e.enrichments??[]){if(!s.id||r.has(s.id))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment ids must be non-empty and unique");if(!s.source||s.source===e.source||n.has(s.source))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment sources must be non-empty and unique");if(s.sourceSql!==void 0&&s.sourceSql.trim().length===0)throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichment sourceSql must not be empty");if(s.on.length===0||s.on.some(({baseColumn:a,targetColumn:u})=>!a||!u))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping enrichments require non-empty baseColumn/targetColumn keys");if(s.temporal?.kind==="point"&&!s.temporal.pointColumn)throw new d("INVALID_SCHEMA_MAPPING","Point-in-time Schema mapping enrichments require pointColumn");Mi(s),r.add(s.id),n.add(s.source)}for(const s of e.mappings??[]){if(s.granularity!==void 0&&(s.mappingType!=="property"||!kn(s.granularity,this.plugins)))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping granularity requires a property item and a supported physical granularity");if(s.mappingType==="property"&&(!s.sourceColumn||!s.propertyTarget?.length))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping property items require sourceColumn and propertyTarget");if(s.mappingType==="predItem"&&(!s.sourceColumn||!s.predItem?.operator||typeof s.predItem.pred!="string"))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping PredItem items require sourceColumn and predItem operator/pred");if(s.sourceRef!==void 0&&(s.mappingType!=="property"||!r.has(s.sourceRef)))throw new d("INVALID_SCHEMA_MAPPING","Schema mapping sourceRef requires a property item and a registered enrichment id")}Mi(e);const o=this.#e.get(e.schemaId)??[],i=e.id??e.source;if(o.some(s=>s.connectionId===e.connectionId&&((s.id??s.source)===i||s.source===e.source)))throw new d("SCHEMA_MAPPING_ALREADY_REGISTERED",`Schema mapping is already registered: ${e.schemaId}:${e.connectionId}:${i}`,{schemaId:e.schemaId,connectionId:e.connectionId,mappingId:i});return this.#e.set(e.schemaId,[...o,e]),this}get(e,r){const n=this.list(e),o=r===void 0?n:n.filter(s=>s.connectionId===r);if(o.length===0)throw new d("SCHEMA_MAPPING_CONNECTION_NOT_FOUND",`Schema ${e} has no mapping on connection ${r}`,{schemaId:e,connectionId:r});if(o.length===1)return o[0];const i=o.filter(s=>(s.mappings??[]).length===0);if(i.length===1)return i[0];throw new d("SCHEMA_MAPPING_AMBIGUOUS",r===void 0?`Schema ${e} has multiple mappings and requires LogicForm-based selection`:`Schema ${e} has multiple mappings on connection ${r} and requires LogicForm-based selection`,{schemaId:e,...r===void 0?{}:{connectionId:r},mappingIds:o.map(s=>s.id??s.source)})}list(e){const r=this.#e.get(e);if(!r||r.length===0)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${e}`,{schemaId:e});return r}findSource(e,r,n){return this.#e.get(e)?.find(o=>o.source===r&&(n===void 0||o.connectionId===n))}}const Ld=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`)},Dd=(t,e=[])=>{const r=me(e);if(!t.schemaSid||!t.datasourceSid)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping requires schemaSid and datasourceSid");if(t.enabled===!1)throw new d("INVALID_SCHEMA_MAPPING",`YiAsk Schema mapping is disabled: ${t.id}`);if("dimensions"in t)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping dimensions is removed; set granularity on property items");const n=[];for(const o of t.mappings){if(o.granularity!==void 0&&(o.mappingType!=="property"||!kn(o.granularity,r)))throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires a property item and a supported physical granularity");if(o.mappingType==="property"){if(!o.sourceColumn||!o.propertyTarget?.length){if(o.granularity!==void 0)throw new d("INVALID_SCHEMA_MAPPING","YiAsk Schema mapping granularity requires sourceColumn and propertyTarget");continue}n.push(o);continue}o.mappingType==="predItem"&&(!o.sourceColumn||!o.predItem?.operator||typeof o.predItem.pred!="string"||n.push(o))}return{id:String(t.id),schemaId:t.schemaSid,connectionId:t.datasourceSid,source:Ld(t),...t.sourceSql?{sourceSql:t.sourceSql}:{},...t.enrichments?{enrichments:t.enrichments}:{},mappings:n}};class qi{#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 ji=(t=[])=>new qi([...me(t).flatMap(e=>e.plannerSemantics??[])]);ue.extend(Do),ue.extend(Mt),ue.extend(ar);const _t=["second","minute","hour","day","week","month","quarter","year"],Cd=new Set(["$second","$minute","$hour","$day","$week","$month","$quarter","$year"]),kd="YYYY-MM-DD HH:mm:ss",St=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),Ud=(t,e)=>t==="week"?e==="week":e==="week"?_t.indexOf(t)<=_t.indexOf("day"):_t.indexOf(t)<=_t.indexOf(e),xi=(t,e,r)=>{if(typeof t!="string")return"second";const n=ue(t,kd,!0);if(!n.isValid())return"second";for(const o of[..._t].reverse()){const i=o==="week"?n.startOf("isoWeek"):n.startOf(o),s=o==="week"?n.endOf("isoWeek"):n.endOf(o),a=e==="lower"?r?i:s:r?s:i;if(n.isSame(a.millisecond(0),"second"))return o}return"second"},Bi=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])=>Cd.has(r)?[r.slice(1)]:r==="$weekday"?["day"]:r==="$and"||r==="$or"?Array.isArray(n)?n.flatMap(Bi):["second"]:r==="$gte"||r==="$gt"?[xi(n,"lower",r==="$gte")]:r==="$lte"||r==="$lt"?[xi(n,"upper",r==="$lte")]:["second"])},Md=(t,e,r)=>{if(e.primal_type==="date"){if(t.operator){const n=r.get(t.operator).groupedSourceTimeGranularity?.({pred:t,property:e});if(n&&_t.includes(n))return n}return e.granularity??"day"}},qd=(t,e,r,n,o=me(),i=Le(o))=>{const s=r.mappings??[],a=s.filter(g=>g.granularity!==void 0),u={schema:e,mapping:r,...n?{resolveSchema:n}:{}};if(a.some(g=>!kn(g.granularity,o)))return"physical granularity is not supported by the active plugins";if(a.find(g=>Cn(g.granularity)&&!g.propertyTarget?.every(A=>St(e,A)?.primal_type==="date")))return"physical time granularity requires mapped date Properties";for(const g of a)for(const A of o){const w=A.mappingGranularity;if(!w||!w.isGranularity(g.granularity))continue;const S=w.validateItem?.(g,u);if(S)return S}if(!(a.length>0))return;const l=g=>s.find(A=>A.mappingType==="property"&&A.propertyTarget?.some(w=>St(e,w)?.id===g.id)),f=(g,A,w="filterOrGroup")=>{const S=St(e,g);if(!S)return`property is not available: ${g}`;const E=l(S);if(!E&&!(w==="operand"&&s.some($=>$.mappingType==="predItem"&&typeof $.predItem?.pred=="string"&&St(e,$.predItem.pred)?.id===S.id)))return`property is not available on grouped source: ${g}`;if(w==="filterOrGroup"&&S.primal_type==="number"&&S.type!=="category"&&S.type!=="ID")return`measure cannot be used as a grouped source dimension: ${g}`;if(S.primal_type==="date"&&(!E?.granularity||!Cn(E.granularity)||!Ud(E.granularity,A??S.granularity??"day")))return`time dimension ${g} is too coarse for ${A}`};function m(g){if(g)for(const[A,w]of Object.entries(g)){if(w===void 0)continue;if(A==="$and"||A==="$or"){if(!Array.isArray(w))return"unsupported dimension query";for(const $ of w){const R=m($);if(R)return R}continue}if(A==="$expr"){if(typeof w!="object"||w===null||Array.isArray(w))return"unsupported expression query";const $=w.pred;if(typeof $!="object"||$===null||Array.isArray($))return"unsupported expression query";const R=y($);if(R)return R;continue}if(A.startsWith("$"))return"unsupported dimension query";const S=St(e,A);if(!S)return`dimension property is not available: ${A}`;const E=S.primal_type==="date"?Bi(w):[void 0];for(const $ of E){const R=f(A,$);if(R)return R}}}function y(g){const A=m(g.query);if(A)return A;const w=Array.isArray(g.pred)?g.pred:g.pred===void 0?[]:[g.pred];for(const S of w){const E=typeof S=="string"?f(S,void 0,"operand"):y(S);if(E)return E}}const h=m(t.query);if(h)return h;if(!t.preds?.length)return"grouped source requires an aggregating PredItem";for(const g of t.preds){const A=y(g);if(A)return A;if(typeof g.pred!="string"||!g.operator||!i.get(g.operator).supportsGroupedSourceRollup)return`PredItem ${g.operator??"(projection)"} cannot be rolled up from a grouped source`}for(const g of t.groupby??[]){if(typeof g.pred!="string")return"computed groupby is not covered by the grouped source";const A=St(e,g.pred);if(!A)return`groupby property is not available: ${g.pred}`;if(g.operator!==void 0&&!i.get(g.operator).supportsGroupedSourceGroupby&&!o.some(S=>S.mappingGranularity?.supportsGroupby?.(g)))return`computed groupby is not covered: ${g.pred}`;const w=f(g.pred,Md(g,A,i));if(w)return w}for(const g of o){const A=g.mappingGranularity?.candidateReason?.(t,u);if(A)return A}};function Yt(t){return[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?Yt(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:Yt(e)):[]]}const Mn=t=>t.id??t.source,_r=(t,e)=>{if(t===e)return!0;if(t instanceof Date||e instanceof Date)return t instanceof Date&&e instanceof Date&&t.getTime()===e.getTime();if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((o,i)=>_r(o,e[i]));if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const r=Object.entries(t),n=e;return r.length===Object.keys(n).length&&r.every(([o,i])=>Object.prototype.hasOwnProperty.call(n,o)&&_r(i,n[o]))},It=t=>{if(!t)return[];const e=[];for(const[r,n]of Object.entries(t))if(n!==void 0){if(r==="$or")return;if(r==="$and"){if(!Array.isArray(n))return;for(const o of n){const i=It(o);if(!i)return;e.push(...i)}continue}if(r==="$expr"){if(typeof n!="object"||n===null||Array.isArray(n))return;const o=n.pred;if(typeof o!="object"||o===null||Array.isArray(o))return;const i=Yt(o);if(i.length===0)return;e.push(...i.map(s=>({property:s,condition:{$expr:n}})));continue}if(r.startsWith("$"))return;e.push({property:r,condition:n})}return e},qn=(t,e,r)=>{if(!t)return;const n={};for(const[o,i]of Object.entries(t))if(i!==void 0){if(o==="$and"&&Array.isArray(i)){const s=i.map(a=>qn(a,e,r)).filter(a=>a!==void 0);s.length>0&&(n[o]=s);continue}o!=="$or"&&e.some(s=>Sr(r,s.property,o)&&_r(s.condition,i))||(n[o]=i)}return Object.keys(n).length>0?n:void 0},rt=(t,e)=>t.properties.find(({id:r,name:n})=>r===e||n===e),Sr=(t,e,r)=>e===r||rt(t,e)?.id===rt(t,r)?.id&&rt(t,e)!==void 0&&rt(t,r)!==void 0,Ie=(t,e,r)=>Ir(t,e,r)?.column,Ir=(t,e,r)=>{const n=rt(e,r);if(!n)return;const o=(t.mappings??[]).find(i=>i.mappingType==="property"&&i.propertyTarget?.some(s=>Sr(e,s,r)));return o?.sourceColumn?{column:o.sourceColumn,...o.sourceRef?{sourceRef:o.sourceRef}:{}}:(t.mappings??[]).some(i=>i.mappingType==="property")?void 0:{column:n.id}},jn=(t,e,r)=>!(t.mappings??[]).some(n=>n.mappingType==="property")||Ie(t,e,r)!==void 0,Vi=(t,e,r)=>{if(!t||!(e.mappings??[]).some(i=>i.mappingType==="property"))return;const n=It(t);if(!n)return"query contains an unsupported logical expression";const o=n.find(({property:i})=>!jn(e,r,i));return o?`query property is not available: ${o.property}`:void 0},jd=(t,e,r,n,o)=>{if(t.match.schema!==void 0&&t.match.schema!==n)return!1;const i=typeof e.pred=="string"?rt(r,e.pred):void 0,s=rt(r,t.match.pred),a=typeof e.pred=="string"&&Sr(r,e.pred,t.match.pred)&&!!(i&&s);if(e.operator!==t.match.operator||!a||Array.isArray(e.pred)||e.args&&Object.keys(e.args).length>0)return!1;const u=It(t.match.query);return u!==void 0&&u.every(c=>o.some(p=>Sr(r,p.property,c.property)&&_r(p.condition,c.condition)))},xd=(t,e,r,n,o,i=Le(o))=>{const s=(r.mappings??[]).flatMap(g=>{if(g.mappingType!=="predItem"||!g.sourceColumn||!g.predItem||!g.predItem.operator||typeof g.predItem.pred!="string")return[];const A=g.predItem,w=A.operator,S=A.pred;return!w||typeof S!="string"?[]:[{match:{operator:w,pred:S,...A.schema?{schema:A.schema}:{},...A.query?{query:A.query}:{}},column:g.sourceColumn}]}),a=(r.mappings??[]).some(g=>g.mappingType==="property");if(s.length===0&&!a){const g={schema:e,mapping:r,...n?{resolveSchema:n}:{}};for(const A of o??[]){const w=A.schemaMapping?.candidateReason?.(t,g);if(w)return w}return{mapping:r,logicform:t,predRewrites:[],priority:r.priority??0,specificity:0}}const u=It(t.query);if(!u&&s.length>0)return"query contains $or or another unsupported logical expression";const c=ne(t),p=[],l=[];for(const[g,A]of(t.preds??[]).entries()){const w=It(A.query);if(!w&&s.length>0)return`PredItem ${g} query contains an unsupported logical expression`;if(s.length>0){const E=[...u??[],...w??[]],$=s.filter(M=>jd(M,A,e,A.schema??e.id,E));if($.length===0)return`PredItem ${g} is not mapped`;if($.length>1)return`PredItem ${g} matches multiple mapping rules`;const R=$[0],O=It(R.match.query)??[];l.push(...O);const D=c.preds?.[g];if(D){const M=qn(D.query,O,e);M?D.query=M:delete D.query}p.push({predIndex:g,column:R.column});continue}const S=Yt(A).find(E=>!jn(r,e,E));if(S)return`PredItem ${g} property is not available: ${S}`}const f=qn(c.query,l,e);f?c.query=f:delete c.query;const m=Vi(c.query,r,e);if(m)return m;for(const[g,A]of(c.preds??[]).entries()){const w=Vi(A.query,r,e);if(w)return`PredItem ${g} ${w}`}for(const g of c.groupby??[]){const w=Yt(g).find(S=>!jn(r,e,S));if(w)return`groupby property is not available: ${w}`}const y=qd(c,e,r,n,o,i);if(y)return y;const h={schema:e,mapping:r,...n?{resolveSchema:n}:{}};for(const g of o??[]){const A=g.schemaMapping?.candidateReason?.(c,h);if(A)return A}return{mapping:r,logicform:c,predRewrites:p,priority:r.priority??0,specificity:p.length}},Bd=(t,e,r,n={})=>{const o=n.plugins?me(n.plugins):r.plugins,i=n.operators??Le(n.plugins),s=[],a=[];for(const l of r.list(e.id)){const f=xd(t,e,l,n.resolveSchema,o,i);typeof f=="string"?a.push({mappingId:Mn(l),reason:f}):s.push(f)}if(s.length===0){const l=e.name&&e.name!==e.id?`${e.name}(${e.id})`:e.id;throw new d("QUERY_NOT_COVERED_BY_DATA_SOURCE",`Schema\u300C${l}\u300D\u5F53\u524D\u63A5\u5165\u7684\u6570\u636E\u4E0D\u652F\u6301\u6B64\u95EE\u9898\u3002\u5982\u9700\u652F\u6301\uFF0C\u9700\u8981\u63A5\u5165\u660E\u7EC6\u5C42\u6570\u636E\uFF0C\u8BF7\u8054\u7CFB\u6570\u636E\u7BA1\u7406\u5458\u3002`,{schemaId:e.id,requiredDataLayer:"detail",rejectedMappings:a})}const u=n.preferredConnectionId===void 0?[]:s.filter(({mapping:l})=>l.connectionId===n.preferredConnectionId),p=(u.length>0?u:s).reduce((l,f)=>f.priority>l.priority||f.priority===l.priority&&f.specificity>l.specificity?f:l);for(const l of s){if(l===p)continue;let f;u.length>0&&l.mapping.connectionId!==n.preferredConnectionId?f=`connection ${l.mapping.connectionId} does not match preferred connection ${n.preferredConnectionId}`:l.priority<p.priority?f=`priority ${l.priority} is lower than selected priority ${p.priority}`:l.specificity<p.specificity?f=`specificity ${l.specificity} is lower than selected specificity ${p.specificity}`:f="priority and specificity tie; an earlier registered mapping was selected",a.push({mappingId:Mn(l.mapping),reason:f})}return{mapping:p.mapping,logicform:p.logicform,predRewrites:p.predRewrites,selection:{schemaId:e.id,selectedMappingId:Mn(p.mapping),rejectedMappings:a}}},Ht=(t,e)=>!!(t.operator&&e.get(t.operator).kind==="component"),Qt=(t,e)=>Ht(t,e)?!0:t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Qt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Qt(r,e)),vi=(t,e)=>t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?Qt(t.pred,e):Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&Qt(r,e)),Fi=t=>t.name??(typeof t.pred=="string"?t.pred:void 0),Vd=(t,e)=>{const r=t.preds??[];if(!r.some(m=>!Ht(m,e)&&vi(m,e)))return;const n=new Set([...r.map(({name:m})=>m).filter(m=>!!m),...(t.groupby??[]).map(Fi).filter(m=>!!m)]);let o=0;const i=()=>{let m;do m=`__nested_component_input_${o}__`,o+=1;while(n.has(m));return n.add(m),m},s=[],a=m=>{const y=i();return s.push(typeof m=="string"?{pred:m,name:y}:{...ne(m),name:y}),y},u=m=>{if(m.query)throw new d("UNSUPPORTED_COMPONENT_NESTING","An operator above a component cannot define pred.query; apply the query inside a materialized input");const y=ne(m);return Array.isArray(m.pred)?y.pred=m.pred.map(h=>typeof h=="string"||!Qt(h,e)||Ht(h,e)?a(h):u(h)):m.pred&&typeof m.pred=="object"&&(y.pred=Ht(m.pred,e)?a(m.pred):u(m.pred)),y},c=r.map(m=>{const y=m.name;if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every projection to have a name");return!Ht(m,e)&&vi(m,e)?{...u(m),name:y}:(s.push({...ne(m),name:y}),{pred:y,name:y})}),p=ne(t);p.preds=s,delete p.having,delete p.sort,delete p.limit,delete p.limitBy,delete p.page,delete p.output,delete p.representation;const l=(t.groupby??[]).map(m=>{const y=Fi(m);if(!y)throw new d("MISSING_PRED_NAME","Nested component rewrite requires every groupby projection to have a name");return{pred:y,name:y}}),f=ne(t);return f.from=p,f.preds=[...l,...c],delete f.query,delete f.groupby,delete f.entity_id,delete f.propertyResolve,f},vd=(t,e)=>`result:${t}:${e.map(({name:r,type:n,primal_type:o})=>`${r}:${n}:${o}`).join("|")}`,Yi=(t,e)=>{const r=(t.columnProperties??[]).map(n=>({...n,id:n.name}));return{id:vd(t.schemaId,t.columnProperties??[]),name:`${e.name} result`,type:e.type,temporalSemantics:"normal",properties:r}},Hi=(t,e)=>({...Yi(t,e),id:e.id,name:e.name,type:e.type}),xn=t=>{if(!t.name)throw new d("MISSING_PRED_NAME","Planner requires every normalized PredItem to have a name");return t.name},br=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?br(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:br(e)):[]],Bn=(t,e)=>({...t,...typeof t.pred=="string"?{pred:e(t.pred)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:Bn(t.pred,e)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(r=>typeof r=="string"?e(r):Bn(r,e))}:{}}),Qi=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(o=>Qi(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:Bn(o,e)}]}return[r.startsWith("$")?r:e(r),n]})),Vn=(t,e,r)=>{const n=new Set(r),o=(i,s)=>{if(!(Se(i)||i===null)){if(Array.isArray(i)){i.forEach(a=>o(a,s));return}if(typeof i=="object"){Object.entries(i).forEach(([a,u])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(a)||o(u,a)});return}if(!(s&&["$exists","$regex","$contains","$startsWith","$length"].includes(s))&&(typeof i!="string"||!n.has(i)))throw new d("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${e} does not contain value: ${JSON.stringify(i)}`,{property:e,value:i})}};o(t)},Gi=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>{if((r==="$and"||r==="$or")&&Array.isArray(n))return[r,n.map(i=>Gi(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&&Vn(n,r,o.values),[r,o?{kind:"ordinal-query",comparable:o,condition:n}:n]})),Fd=(t,e,r)=>{if(!e.udf)return{};const o=e.udf.sql.includes("$TS")?t.properties.find(({type:i})=>i==="timestamp")?.id:void 0;return{sql:e.udf.sql,...o?{timestampColumn:o}:{},...o&&r?{timestampQualifier:r}:{}}},Wi=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},zi=(t,e,r={})=>({name:t,type:e.type,primal_type:e.primal_type,isArray:e.isArray,...e.description!==void 0?{description:e.description}:{},...e.ref?{ref:e.ref}:{},...e.comparable?{comparable:e.comparable}:{},...r}),bt=(t,e,r,n,o,i,s,a,u="projection")=>{const c=xn(t);if(u==="groupby"&&t.query)throw new d("GROUPBY_QUERY_NOT_ALLOWED","A groupby expression cannot define pred.query");if(!t.operator){if(typeof t.pred!="string")throw new d("PRED_PROPERTY_REQUIRED","A projection must reference a property");const E=r(t.pred);return{expression:Wi(E.field),outputProperty:zi(E.reference,E.property),sourceProperty:E.property,sourceField:E.field}}const p=e.get(t.operator);if(u==="groupby"&&p.kind!=="scalar")throw new d("OPERATOR_NOT_ALLOWED_IN_GROUPBY",`Operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(u==="groupby"&&!p.toSQL)throw new d("JAVASCRIPT_OPERATOR_NOT_ALLOWED_IN_GROUPBY",`JavaScript-only operator ${t.operator} cannot be used in groupby`,{operator:t.operator});if(p.planInput&&typeof t.pred!="string")throw new d("OPERATOR_DIRECT_PROPERTY_REQUIRED",`${t.operator} requires a direct property pred`);const l=p.planInput&&typeof t.pred=="string"?p.planInput({reference:t.pred,args:t.args??{},schema:s,...a?{resolveSchema:a}:{}}):void 0,f=l?.reference??t.pred,m=l?.args??t.args??{},y=f&&typeof f=="object"&&!Array.isArray(f)?bt(f,e,r,n,o,i,s,a,u):typeof f=="string"?bt({pred:f,name:f},e,r,n,o,i,s,a,u):void 0,h=Array.isArray(f)?f.map(E=>bt(typeof E=="string"?{pred:E,name:E}:E,e,r,n,o,i,s,a,u)):[];if(p.requiresProperty!==!1&&!y&&h.length===0)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a property`);const g=c,A=p.getOutputProperty?.({name:g,...y?.sourceProperty?{property:y.sourceProperty}:{},...y?{inputProperty:{...y.outputProperty,name:g}}:{},...h.length>0?{inputProperties:h.map(({outputProperty:E})=>E)}:{},args:m}),w=A?.description??p.description??y?.outputProperty.description,S={...A??(y?zi(g,y.outputProperty,{isArray:!1}):{name:g,type:"number",primal_type:"number",isArray:!1}),...w!==void 0?{description:w}:{}};if(p.planExpression){const E=p.planExpression({pred:t,...y?{input:y.expression,inputProperty:y.outputProperty}:{},inputs:h.map(({expression:$})=>$),args:m,resolveKey:o,getOperator:$=>e.get($),planQuery:i});if(E)return{expression:E,outputProperty:S,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}}if(p.kind==="window"){if(!y||h.length>0||t.query)throw new d("INVALID_WINDOW_OPERATOR_INPUT",`${t.operator} requires exactly one nested pred and does not accept pred.query`);const E=t.args?.direction??"desc";if(E!=="asc"&&E!=="desc")throw new d("INVALID_WINDOW_ARGS",`${t.operator} direction must be asc or desc`);const $=t.args?.partitionBy??[];if(!Array.isArray($)||$.some(R=>typeof R!="string"))throw new d("INVALID_WINDOW_ARGS",`${t.operator} partitionBy must be an array of groupby names`);return{expression:{kind:"window",function:p.windowFunction,input:y.expression,partitionBy:$.map(R=>n(String(R))),direction:E==="asc"?"ASC":"DESC"},outputProperty:S}}return{expression:{kind:"operator",operator:t.operator,args:m,...t.query?{query:i(t.query)}:{},...y?{input:y.expression}:{},...h.length>0?{inputs:h.map(({expression:E})=>E)}:{},...y?.sourceProperty?{property:y.sourceProperty.name,column:y.sourceProperty.id}:{},...y?.sourceField?{qualifier:y.sourceField.qualifier,schemaId:y.sourceField.schemaId}:{}},outputProperty:S,...y?.sourceProperty?{sourceProperty:y.sourceProperty}:{},...y?.sourceField?{sourceField:y.sourceField}:{}}},Yd=(t,e,r,n,o,i,s,a,u,c,p,l=t)=>{const f=xn(t),m=typeof t.pred=="string"?t.pred:void 0,y=!c||!m?r:w=>{const S=r(w);return w===m?{...S,field:{...S.field,column:c}}:S},h=p?{...t,operator:p}:t,g=bt(h,e,y,n,o,i,s,a),A=u?.resolveProjection({pred:l,schema:s,...g.sourceProperty?{sourceProperty:g.sourceProperty}:{},outputProperty:{...g.outputProperty,name:f},...l.operator?{operator:e.get(l.operator)}:{}})??{...g.outputProperty,name:f};return{name:f,expression:g.expression,outputProperty:A}},Hd=t=>{const e=new Set;for(const r of t){if(r.name==="_id")throw new d("RESERVED_OUTPUT_NAME","Output name _id is reserved for executor-owned row identity");if(e.has(r.name))throw new d("DUPLICATE_OUTPUT_NAME",`Duplicate output name: ${r.name}`);e.add(r.name)}},vn=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cannot plan nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n},Qd=(t,e,r,n,o,i)=>{if(e.length<2)throw new d("COMPOSITION_REQUIRES_MULTIPLE_BRANCHES","A cross-Schema plan requires at least two branches");const s=e.map(h=>Oe(h,vn(h,r,i),n,o,i)),a=s[0]?.groupBy.map(({name:h})=>h)??[];for(const h of s){const g=h.groupBy.map(({name:A})=>A);if(g.length!==a.length||g.some((A,w)=>A!==a[w]))throw new d("INCOMPATIBLE_COMPOSITION_GROUPBY","All composed LogicForm objects must have the same groupby output names in the same order",{expected:a,received:g});if(h.rowIdentity.kind!==(a.length>0?"group":"singleton"))throw new d("UNSTABLE_COMPOSITION_IDENTITY","Composed LogicForm objects must be grouped or aggregate to a singleton row")}const u=[],c=[],p=new Map;s.forEach((h,g)=>{h.projections.forEach((A,w)=>{const S=a.includes(A.name),E=p.get(A.name);if(E!==void 0&&!S)throw new d("DUPLICATE_COMPOSITION_OUTPUT",`Composed LogicForm objects produce the same output: ${A.name}`,{name:A.name,childIndexes:[E,g]});if(E!==void 0)return;p.set(A.name,g),u.push({name:A.name,expression:{kind:"column",property:A.name,column:A.name}});const $=h.columnProperties?.[w];$&&c.push($)})});const l=new Set(u.map(({name:h})=>h)),f=Object.entries(t.sort??{}).map(([h,g])=>{if(!l.has(h))throw new d("INVALID_SORT",`Sort field is not an output: ${h}`);const A=c.find(w=>w.name===h);return{name:h,direction:g===1?"ASC":"DESC",...A?.comparable?{comparable:A.comparable}:{},...A?.comparable?{expression:{kind:"column",property:h,column:h}}:{}}}),m=t.limitBy===void 0||a.length<2?void 0:{count:t.limitBy,partitionBy:a.slice(0,-1),orderBy:f.length>0?f:(()=>{const h=a.at(-1)??"",g=c.find(A=>A.name===h);return[{name:h,direction:"ASC",...g?.comparable?{comparable:g.comparable}:{}}]})()},y=t.limitBy!==void 0&&a.length<2?{kind:"rows",page:1,pageSize:t.limitBy}:t.limit===void 0?void 0:t.limit>0&&t.limit<1?{kind:"ratio",page:t.page??1,ratio:t.limit}:{kind:"rows",page:t.page??1,pageSize:t.limit};return{schemaId:r.id,source:"",subplans:s,fields:Object.fromEntries(u.map(({name:h})=>[h,h])),projections:u,columnProperties:c,groupBy:u.filter(({name:h})=>a.includes(h)),...t.having?{having:Gi(t.having,c)}:{},orderBy:f,rowIdentity:a.length>0?{kind:"group",names:a,separator:"_",nullLabel:"\u7A7A\u503C"}:{kind:"singleton"},...m?{groupLimit:m}:{},...y?{pagination:y}:{}}},Oe=(t,e,r=Le(),n=new Un,o={})=>{const i=[...new Set((t.preds??[]).map(_=>_.schema).filter(_=>!!(_&&_!==e.id)))];if(i.length>0){const _=t.propertyResolve??{},I=[e.id,...i].map(b=>{const{having:T,sort:P,limit:Y,limitBy:K,page:re,...L}=t,ee=J=>{let B=J;try{B=de(e,J,o.resolveSchema).canonicalName}catch{}return _[b]?.[J]??_[b]?.[B]??J};return{...L,schema:b,preds:(t.preds??[]).filter(J=>(J.schema??e.id)===b).map(({schema:J,...B})=>B),...b===e.id||!t.query?{}:{query:Qi(t.query,ee)},...b!==e.id&&t.groupby?{groupby:t.groupby.map(J=>({...J,...typeof J.pred=="string"?{pred:ee(J.pred)}:{}}))}:{}}});return Qd(t,I,e,r,n,o)}const s=Vd(t,r);if(s)return Oe(s,e,r,n,o);for(const _ of t.preds??[]){if(!_.operator)continue;const I=r.get(_.operator).rewriteLogicform?.({logicform:t,schema:e,getOperator:b=>r.get(b)});if(I)return Oe(I,e,r,n,o)}const a=o.semanticRegistry??ji(o.plugins);if(t.from){const _=vn(t.from,e,o),I=Oe(t.from,_,r,n,o),b=Hi(I,e),T={...t};delete T.from,T.schema??=b.id;const P=Oe(T,b,r,n,o),Y=new Set(P.projections.map(({name:B})=>B)),K=I.rowIdentity.kind==="group"&&I.rowIdentity.names.every(B=>Y.has(B))||I.rowIdentity.kind==="singleton"?I.rowIdentity:{kind:"generated"},re=I.groupBy.map(({name:B})=>B).filter(B=>Y.has(B)),L=re.at(-1),ee=I.columnProperties?.find(B=>B.name===L),J=t.limitBy!==void 0&&re.length>0?{count:t.limitBy,partitionBy:re.slice(0,-1),orderBy:P.orderBy.length>0?P.orderBy:re.slice(-1).map(B=>({name:B,direction:"ASC",...ee?.comparable?{comparable:ee.comparable}:{}}))}:void 0;return{...P,source:I.source,sourcePlan:I,sourceLogicform:t.from,rowIdentity:K,...J?{groupLimit:J}:{}}}if(!t.schema)throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema");const u=Bd(t,e,n,{operators:r,...o.plugins?{plugins:o.plugins}:{},...o.preferredConnectionId?{preferredConnectionId:o.preferredConnectionId}:{},...o.resolveSchema?{resolveSchema:o.resolveSchema}:{}});o.onSchemaMappingSelection?.(u.selection),t=u.logicform;const c=new Map(u.predRewrites.map(({predIndex:_,column:I})=>[_,I])),p=yi(e,o.plugins),l=Fc(t,e,o.plugins),f=a.resolveQuery({logicform:t,schema:e,...t.query?{query:t.query}:{}}),m=l?.rewriteQuery?l.rewriteQuery(f):f,y=e.id,h=new Map,g=new Map,A=new Map,w=new Map,S=_=>{const I=g.get(_);if(I)return I.alias;const b=u.mapping.enrichments?.find(Y=>Y.id===_);if(!b)throw new d("SCHEMA_MAPPING_ENRICHMENT_NOT_FOUND",`Schema mapping enrichment is not registered: ${_}`,{schemaId:e.id,mappingId:u.mapping.id,enrichmentId:_});const T=`__enrichment_${_}`,P=b.temporal?(()=>{if(!p)throw new d("POINT_ENRICHMENT_REQUIRES_INTERVAL",`Point enrichment ${_} requires an entity with interval semantics`,{schemaId:e.id,enrichmentId:_});const Y=Ir(u.mapping,e,p.start.name),K=Ir(u.mapping,e,p.end.name);if(!Y||!K)throw new d("POINT_ENRICHMENT_INTERVAL_COLUMNS_REQUIRED",`Point enrichment ${_} requires mapped interval boundary columns`,{schemaId:e.id,enrichmentId:_});if(Y.sourceRef||K.sourceRef)throw new d("POINT_ENRICHMENT_INTERVAL_MUST_USE_BASE_SOURCE",`Point enrichment ${_} requires interval boundaries on the base source`,{schemaId:e.id,enrichmentId:_});return{kind:"point-in-interval",pointSide:"target",pointColumn:b.temporal.pointColumn,intervalSide:"source",startColumn:Y.column,endColumn:K.column}})():void 0;return g.set(_,{kind:"enrichment-left",id:_,source:b.source,...b.sourceSql?{sourceSql:b.sourceSql}:{},alias:T,baseAlias:y,keys:b.on,...P?{temporalCondition:P}:{}}),T},E=_=>{const I=de(e,_,o.resolveSchema);let b=y,T=u.mapping;const P=[];for(const L of I.relations){P.push(L.property.name);const ee=P.join("_"),J=ee,B=n.get(L.targetSchema.id,u.mapping.connectionId);if(T=B,!h.has(ee)){const ye=L.targetSchema.properties.filter(({type:Q})=>Q==="ID"),[ce]=ye;if(ye.length!==1||!ce)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${L.targetSchema.id} must contain exactly one ID property`,{schemaId:L.targetSchema.id,count:ye.length});const De=L.sourceSchema.id===e.id?u.mapping:n.get(L.sourceSchema.id,u.mapping.connectionId),lt=Ie(De,L.sourceSchema,L.property.name)??L.property.id,pt=Ie(B,L.targetSchema,ce.name)??ce.id,Je=L.sourceSchema.properties.find(({type:Q})=>Q==="timestamp"),Qe=L.targetSchema.properties.find(({type:Q})=>Q==="timestamp"),we=vc(L.sourceSchema,L.targetSchema,o.plugins),N=Je?Ie(De,L.sourceSchema,Je.name)??Je.id:void 0,x=Qe?Ie(B,L.targetSchema,Qe.name)??Qe.id:void 0,G=we?.kind==="date-bucket-equal"?{kind:"date-bucket-equal",sourceColumn:Ie(De,L.sourceSchema,we.sourceTimestamp.name)??we.sourceTimestamp.id,targetColumn:Ie(B,L.targetSchema,we.targetTimestamp.name)??we.targetTimestamp.id,sourceGranularity:we.sourceTimestamp.granularity??"day",targetGranularity:we.targetTimestamp.granularity??"day"}:we?.kind==="point-in-interval"?{kind:"point-in-interval",pointSide:"source",pointColumn:Ie(De,L.sourceSchema,we.point.name)??we.point.id,intervalSide:"target",startColumn:Ie(B,L.targetSchema,we.start.name)??we.start.id,endColumn:Ie(B,L.targetSchema,we.end.name)??we.end.id}:void 0,U=L.property.isArray?ee:void 0;U&&!A.has(U)&&A.set(U,{path:U,sourceAlias:b,sourceColumn:lt,...L.property.udf?{sourceSql:L.property.udf.sql,...N?{sourceTimestampColumn:N}:{}}:{},alias:`__array_${ee}`}),h.set(ee,{kind:"left",path:ee,sourceAlias:b,sourceColumn:lt,...L.property.udf?{sourceSql:L.property.udf.sql,...N?{sourceTimestampColumn:N}:{}}:{},targetSchemaId:L.targetSchema.id,targetConnectionId:B.connectionId,targetSource:B.source,...B.sourceSql?{targetSourceSql:B.sourceSql}:{},targetAlias:J,targetColumn:pt,...U?{sourceArrayExpansionPath:U}:{},...ce.udf?{targetSql:ce.udf.sql,...x?{targetTimestampColumn:x}:{}}:{},...G?{temporalCondition:G}:{}})}b=J}const Y=Ir(T,I.schema,I.property.name);if(I.relations.length>0&&Y?.sourceRef)throw new d("RELATION_MAPPING_ENRICHMENT_UNSUPPORTED",`Related property ${I.canonicalName} cannot be sourced from a mapping enrichment`,{schemaId:I.schema.id,property:I.property.name});const K=Y?.sourceRef?S(Y.sourceRef):b,re={schemaId:I.schema.id,property:I.property.name,propertyId:I.property.id,column:Y?.column??I.property.id,qualifier:K,...I.property.isArray?{isArray:!0}:{},...I.property.comparable?{comparable:I.property.comparable}:{},...Fd(I.relations.length>0?e:I.schema,I.property,y)};return w.set(I.canonicalName,re),{reference:I.canonicalName,schema:I.schema,property:I.property,field:re}},$=_=>{if(_)for(const[I,b]of Object.entries(_))if((I==="$and"||I==="$or")&&Array.isArray(b))for(const T of b)typeof T=="object"&&T!==null&&!Array.isArray(T)&&$(T);else if(I==="$expr"&&typeof b=="object"&&b!==null&&!Array.isArray(b)){const T=b.pred;typeof T=="object"&&T!==null&&!Array.isArray(T)&&br(T).forEach(E)}else I.startsWith("$")||E(I)},R=_=>{if(Se(_)){const I=vn(_,e,o),b=Oe(_,I,r,n,o);if(b.projections.length!==1)throw new d("SUBQUERY_SINGLE_COLUMN_REQUIRED",`Query LogicForm must output exactly one column, received ${b.projections.length}`,{schemaId:_.schema,projectionCount:b.projections.length});return{kind:"logicform-subquery",plan:b}}return Array.isArray(_)?_.map(R):typeof _!="object"||_===null||_ instanceof Date?_:Object.fromEntries(Object.entries(_).map(([I,b])=>[I,R(b)]))},O=_=>Object.fromEntries(Object.entries(_).map(([I,b])=>{if((I==="$and"||I==="$or")&&Array.isArray(b))return[I,b.map(P=>O(P))];if(I==="$expr"){if(typeof b!="object"||b===null||Array.isArray(b))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const P=b;if(typeof P.pred!="object"||P.pred===null||Array.isArray(P.pred)||!Object.prototype.hasOwnProperty.call(P,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must be normalized before planning");const Y=P.pred,K=bt(Y,r,E,z,q,O,e,o.resolveSchema,"groupby");if(K.outputProperty.isArray)throw new d("ARRAY_EXPRESSION_QUERY_UNSUPPORTED","$expr must produce a scalar value");const re=R(P.condition);return K.outputProperty.comparable&&Vn(re,Y.name??Y.operator??"$expr",K.outputProperty.comparable.values),[I,{kind:"expression-query",expression:K.expression,condition:K.outputProperty.comparable?{kind:"ordinal-query",comparable:K.outputProperty.comparable,condition:re}:re,properties:br(Y)}]}if(typeof b=="object"&&b!==null&&!Array.isArray(b)){const Y=Object.entries(b).find(([K])=>At(K,o.plugins));if(Y){const[K,re]=Y,L=At(K,o.plugins);if(!L)throw new Error(`Query Operator disappeared: ${K}`);const ee=E(I),J=L.plan(re,{schema:ee.schema,property:ee.property,connectionId:u.mapping.connectionId,...o.resolveSchema?{resolveSchema:o.resolveSchema}:{},resolveMapping:(B,ye)=>n.get(B,ye)});return[I,{[K]:{kind:"query-operator",operator:K,value:J.value,definition:L,...J.sources?{sources:J.sources}:{}}}]}}const T=I.startsWith("$")?void 0:E(I).property.comparable;return[I,T?{kind:"ordinal-query",comparable:T,condition:R(b)}:R(b)]})),D=_=>{const I=T=>{if(!T||typeof T!="object")return!1;if(Array.isArray(T))return T.some(I);const P=T;return Object.prototype.hasOwnProperty.call(P,"$and")||Object.values(P).some(I)};if(I(_))return _;const b=new Set(Object.keys(_).flatMap(T=>{if(T.startsWith("$"))return[];const P=de(e,T,o.resolveSchema);return P.relations.length===1&&P.property.type==="ID"?[P.relations[0]?.property.name]:[]}));return Object.fromEntries(Object.entries(_).map(([T,P])=>{if(T==="$and"||T==="$or")return Array.isArray(P)?[T,P.map(ce=>typeof ce=="object"&&ce!==null&&!Array.isArray(ce)?D(ce):ce)]:[T,P];if(T.startsWith("$"))return[T,P];const Y=de(e,T,o.resolveSchema);if(Y.relations.length===0)return[T,P];if(Y.property.udf?.sql.includes("$TS")===!0||Y.relations.some(({property:ce})=>ce.udf?.sql.includes("$TS")===!0))return[T,P];const re=Y.relations.map(({property:ce})=>ce.name).join("_");if(h.has(re))return[T,P];const[L]=Y.relations;if(!L)return[T,P];if(b.has(L.property.name))return[T,P];const ee=L.property.name,J=Y.canonicalName.slice(ee.length+1),B=L.targetSchema.properties.find(({type:ce})=>ce==="ID");if(!B)throw new d("RELATION_TARGET_ID_REQUIRED",`Relation target ${L.targetSchema.id} must contain an ID property`,{schemaId:L.targetSchema.id});if(Y.relations.length===1&&Y.property.id===B.id)return[L.property.id,P];const ye={version:t.version,schema:L.targetSchema.id,query:J?{[J]:P}:{},preds:[{pred:B.name,name:B.name}]};return[L.property.id,{$in:ye}]}))},M=(t.groupby??[]).map(_=>{const I=xn(_);_.operator&&r.get(_.operator).validateGroupby?.({pred:_});const b=bt(_,r,E,z,q,O,e,o.resolveSchema,"groupby");let T=b.expression;if(l?.group===_&&(T={kind:"column",schemaId:e.id,property:l.property.name,propertyId:l.property.id,column:"__period_start",qualifier:"__periods"}),b.sourceProperty?.isArray&&b.sourceField){const P=`groupby:${I}`;A.set(P,{path:P,sourceAlias:b.sourceField.qualifier,sourceColumn:b.sourceField.column,...b.sourceField.sql?{sourceSql:b.sourceField.sql,...b.sourceField.timestampColumn?{sourceTimestampColumn:b.sourceField.timestampColumn}:{}}:{},alias:`__array_group_${A.size}`}),T={kind:"array-element",schemaId:b.sourceField.schemaId,property:b.sourceProperty.name,expansionPath:P}}return{name:I,expression:T,outputProperty:{...b.outputProperty,name:I,isArray:!1}}});function z(_){const I=(t.groupby??[]).findIndex(T=>typeof T.pred=="string"&&T.pred===_||T.name===_),b=I>=0?M[I]:void 0;if(!b)throw new d("WINDOW_PARTITION_NOT_GROUPED",`Window partition must reference a groupby item: ${_}`);return b.expression}function q(_){const I=(t.groupby??[]).findIndex(T=>typeof T.pred=="string"&&T.pred===_||T.name===_),b=I>=0?M[I]:void 0;return b?b.expression:Wi(E(_).field)}const v=_=>{_.operator&&r.get(_.operator).validatePlan?.({pred:_,groupByNames:M.map(({name:I})=>I),resolveGroupName:I=>{const b=(t.groupby??[]).findIndex(T=>T.name===I||typeof T.pred=="string"&&T.pred===I);return b>=0?M[b]?.name:void 0},getOperator:I=>r.get(I)}),_.pred&&typeof _.pred=="object"&&!Array.isArray(_.pred)&&v(_.pred);for(const I of Array.isArray(_.pred)?_.pred:[])v(typeof I=="string"?{pred:I}:I)};for(const _ of t.preds??[])v(_);const k=[...M,...(t.preds??[]).map((_,I)=>{const b=l?.rewritePred?.(_)??_;return Yd(b,r,E,z,q,O,e,o.resolveSchema,a,c.get(I),ri(b,t.groupby??[],e,o.resolveSchema)?"$min":void 0,_)})],H=_=>Object.fromEntries(Object.entries(_).map(([I,b])=>{if((I==="$and"||I==="$or")&&Array.isArray(b))return[I,b.map(P=>H(P))];if(I==="$expr")throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names");const T=k.find(({name:P})=>P===I)?.outputProperty.comparable;return T&&Vn(b,I,T.values),[I,T?{kind:"ordinal-query",comparable:T,condition:R(b)}:R(b)]})),ae=m?D(m):void 0;$(ae);const te=_=>{$(_.query),_.pred&&typeof _.pred=="object"&&!Array.isArray(_.pred)&&te(_.pred);for(const I of Array.isArray(_.pred)?_.pred:[])te(typeof I=="string"?{pred:I}:I)};for(const _ of t.preds??[])te(_);if(k.length===0)throw new d("EMPTY_PROJECTION","LogicForm must contain preds or groupby");Hd(k);const fe=new Set(k.map(({name:_})=>_)),C=M.length>0?{kind:"group",names:M.map(({name:_})=>_),separator:"_",nullLabel:"\u7A7A\u503C"}:k.every(({expression:_})=>_.kind==="column"||_.kind==="property-sql")||k.some(({expression:_})=>_.kind==="property-sql"&&e.properties.some(({id:I,type:b})=>b==="ID"&&I===_.propertyId))?(()=>{const _=e.properties.find(({type:I})=>I==="ID");return _&&(o.canUsePropertyRowIdentity?.(e,_)??!0)?{kind:"property",column:_.id,internalName:"_id"}:{kind:"generated"}})():{kind:"singleton"},F=Object.entries(t.sort??{}).map(([_,I])=>{if(!fe.has(_))throw new d("INVALID_SORT",`Sort field is not an output: ${_}`);const b=k.find(T=>T.name===_);return{name:_,direction:I===1?"ASC":"DESC",...b?.outputProperty.comparable?{comparable:b.outputProperty.comparable,expression:b.expression}:{}}}),Z=t.limit===void 0?void 0:t.limit>0&&t.limit<1?{kind:"ratio",page:t.page??1,ratio:t.limit}:{kind:"rows",page:t.page??1,pageSize:t.limit},j=t.limitBy===void 0?void 0:{count:t.limitBy,partitionBy:M.slice(0,-1).map(({name:_})=>_),orderBy:F.length>0?F:(()=>{const _=M.at(-1);return[{name:_?.name??"",direction:"ASC",..._?.outputProperty.comparable?{comparable:_.outputProperty.comparable,expression:_.expression}:{}}]})()},le=w.size===0&&h.size===0&&g.size===0&&A.size===0&&!ae&&M.length===0&&k.length>0&&k.every(({expression:_})=>_.kind==="operator"&&_.operator==="$constant");return{schemaId:e.id,source:le?"":u.mapping.source,...le?{}:{connectionId:u.mapping.connectionId},...!le&&u.mapping.sourceSql?{sourceSql:u.mapping.sourceSql}:{},mappingId:u.mapping.id??u.mapping.source,sourceAlias:y,fields:{...ic(e),...Object.fromEntries(e.properties.flatMap(_=>{const I=Ie(u.mapping,e,_.name);return I?[[_.name,I],[_.id,I]]:[]}))},fieldReferences:Object.fromEntries(w),joins:[...h.values()],enrichmentJoins:[...g.values()],arrayExpansions:[...A.values()],...l?{periodSource:{alias:"__periods",labelColumn:"__period_start",asOfColumn:"__as_of",sourceAlias:y,periods:l.periods,match:l.source.kind==="interval"?{kind:"interval",startColumn:Ie(u.mapping,e,l.source.start.name)??l.source.start.id,endColumn:Ie(u.mapping,e,l.source.end.name)??l.source.end.id}:{kind:"latest",lookupAlias:"__period_lookup",timestampColumn:Ie(u.mapping,e,l.source.timestamp.name)??l.source.timestamp.id}}}:{},projections:k.map(({name:_,expression:I})=>({name:_,expression:I})),columnProperties:k.map(({outputProperty:_})=>_),groupBy:M.map(({name:_,expression:I})=>({name:_,expression:I})),...ae?{query:O(ae)}:{},...t.having?{having:H(t.having)}:{},orderBy:F,rowIdentity:le?{kind:"singleton"}:C,...Z?{pagination:Z}:{},...j?{groupLimit:j}:{}}};class Gd{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 Wd=(t,e)=>{const r=e.split(".");if(r.some(n=>n.length===0))throw new d("INVALID_SOURCE",`Invalid physical source: ${e}`);return r.map(n=>t.quoteIdentifier(n)).join(".")},Rr=(t,e,r)=>r===void 0?Wd(t,e):`(${r.trim().replace(/;+\s*$/,"")})`,Gt=(t,e,r,n,o)=>{const i=bi(t,[],String,`Property ${e} udf.sql`);if(!i.includes("$TS"))return i;if(!n)throw new d("PROPERTY_UDF_TIMESTAMP_REQUIRED",`Property ${e} udf.sql uses $TS but its evaluation context has no timestamp Property`,{property:e});const s=(o?`${r.quoteIdentifier(o)}.`:"")+r.quoteIdentifier(n);return i.replace(/\$TS/g,s)},Ue=(t,e,r,n=!1,o,i,s,a)=>{const u=(c,p)=>n&&p?`${e.quoteIdentifier(p)}.${e.quoteIdentifier(c)}`:e.quoteIdentifier(c);switch(t.kind){case"array-element":if(!a)throw new d("ARRAY_EXPANSION_UNAVAILABLE","Array expansion compiler is unavailable");return a(t.expansionPath);case"column":return u(t.column,t.qualifier);case"property-sql":return Gt(t.sql,t.property,e,t.timestampColumn,n?t.timestampQualifier??t.qualifier:void 0);case"window":{if(be(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Window operators cannot consume a JavaScript operator");const c=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>Ue(f,e,r,n,o,i,s,a)).join(", ")} `:"",p=Ue(t.input,e,r,n,o,i,s,a);return`${t.function==="rank"?"RANK":"ROW_NUMBER"}() OVER (${c}ORDER BY ${p} ${t.direction})`}case"cumulative":{if(be(t.input,r))throw new d("UNSUPPORTED_MIXED_OPERATOR","Cumulative expressions cannot consume a JavaScript operator");const c=Ue(t.input,e,r,n,o,i,s,a),p=t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map(f=>Ue(f,e,r,n,o,i,s,a)).join(", ")} `:"",l=t.orderBy.map(f=>`${Ue(f.expression,e,r,n,o,i,s,a)} ${f.direction}`).join(", ");return`${e.aggregateFunction(t.function,c)} OVER (${p}ORDER BY ${l} ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`}case"ordinal-encode":{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","Ordinal encoding requires a value binder");return`CASE ${t.comparable.values.map((p,l)=>`WHEN ${Ue(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 ${Ue(t.input,e,r,n,o,i,s,a)} = ${t.comparable.direction*l} THEN ${i(p)}`).join(" ")} END`}case"operator":{const c=r.get(t.operator);if(c.kind==="component")throw new d("COMPONENT_OPERATOR_REQUIRES_EXECUTOR",`${t.operator} must be compiled through the executor component pipeline`);if(c.toSQL&&(t.input&&be(t.input,r)||t.inputs?.some(f=>be(f,r))))throw new d("UNSUPPORTED_MIXED_OPERATOR",`${t.operator} cannot consume a JavaScript operator in SQL`);let p=t.input?Ue(t.input,e,r,n,o,i,s,a):t.column?u(t.column,t.qualifier):void 0;const l=t.inputs?.map(f=>Ue(f,e,r,n,o,i,s,a));if(t.query&&Object.keys(t.query).length>0){if(c.kind!=="aggregate")throw new d("OPERATOR_QUERY_REQUIRES_AGGREGATION",`Pred query is only supported by aggregation operators: ${t.operator}`);if(!o)throw new d("INVALID_OPERATOR_QUERY","Operator query compiler is unavailable");p=`CASE WHEN ${o(t.query)} THEN ${p??"1"} END`}if(c.requiresProperty!==!1&&!p)throw new d("PRED_PROPERTY_REQUIRED",`${t.operator} requires a column`);return c.toSQL?c.toSQL({sql:{aggregateFunction:e.aggregateFunction.bind(e),quoteIdentifier:e.quoteIdentifier.bind(e),concat:e.concat.bind(e),substring:e.substring.bind(e),stringLength:e.stringLength.bind(e),datePart:e.datePart.bind(e),dateBucket:e.dateBucket.bind(e),dateShift:e.dateShift.bind(e),...e.datePeriodBoundary?{datePeriodBoundary:e.datePeriodBoundary.bind(e)}:{},...e.scalarExtremum?{scalarExtremum:e.scalarExtremum.bind(e)}:{},value:(f,m)=>{if(!i)throw new d("SQL_BINDER_UNAVAILABLE","SQL value binder is unavailable");const y=i(f);return m&&e.castValue?e.castValue(y,m):y},condition:(f,m)=>{if(!s)throw new d("SQL_CONDITION_UNAVAILABLE","SQL condition compiler is unavailable");return s(f,m)}},...p?{expression:p,column:p}:{},...l?{expressions:l}:{},args:t.args}):p??"NULL"}}},be=(t,e)=>t.kind==="window"?be(t.input,e)||t.partitionBy.some(r=>be(r,e)):t.kind==="cumulative"?be(t.input,e)||t.partitionBy.some(r=>be(r,e))||t.orderBy.some(r=>be(r.expression,e)):t.kind==="ordinal-encode"||t.kind==="ordinal-decode"?be(t.input,e):t.kind==="operator"&&(!e.get(t.operator).toSQL&&!!e.get(t.operator).evaluate||(t.input?be(t.input,e):!1)||(t.inputs?.some(r=>be(r,e))??!1)),zd=(t,e)=>t.sourceSql?Gt(t.sourceSql,t.sourceColumn,e,t.sourceTimestampColumn,t.sourceAlias):`${e.quoteIdentifier(t.sourceAlias)}.${e.quoteIdentifier(t.sourceColumn)}`,Ki=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).some(e=>e.startsWith("$")),Ji={$second:"second",$minute:"minute",$hour:"hour",$weekday:"weekday",$day:"day",$week:"week",$month:"month",$quarter:"quarter",$year:"year"},Wt=(t,e,r,n,o,i,s,a)=>{if(Li(r)){if(r.operator!==e)throw new d("INVALID_PLUGIN_QUERY",`Query Operator plan does not match ${e}`);const l=r.definition??s(e);if(!l)throw new d("UNSUPPORTED_QUERY_OPERATOR",`Query Operator is not registered: ${e}`);return l.compile(r.value,{field:t,provider:o,bind:f=>n.add(f),renderSource:(f,m)=>Rr(o,f,m)})}if(s(e))throw new d("INVALID_PLUGIN_QUERY",`${e} query was not planned`,{operator:e});if(e==="$eq"&&r===null)return`${t} IS NULL`;if(e==="$ne"&&r===null)return`${t} IS NOT NULL`;const p={$eq:"=",$ne:"<>",$gt:">",$gte:">=",$lt:"<",$lte:"<="}[e];if(p){const l=Et(r)?`(${i(r)})`:n.add(r);return`${t} ${p} ${l}`}if(e==="$in"||e==="$nin"){const l=e==="$in"?"IN":"NOT IN";if(Et(r))return`${t} ${l} (${i(r)})`;if(!Array.isArray(r))throw new d("INVALID_QUERY_VALUE",`${e} requires an array or query LogicForm`);if(r.length===0)return e==="$in"?"0 = 1":"1 = 1";const f=r.filter(Et);if(f.length>0){if(f.length!==r.length)throw new d("MIXED_SUBQUERY_VALUES",`${e} cannot mix query LogicForm objects and literal values`);return`${t} ${l} (${f.map(i).join(" UNION ALL ")})`}const m=r.map(y=>n.add(y)).join(", ");return`${t} ${l} (${m})`}if(Et(r))throw new d("UNSUPPORTED_SUBQUERY_OPERATOR",`Query LogicForm is not supported by ${e}`);if(e==="$exists")return`${t} IS ${r?"NOT ":""}NULL`;if(e==="$contains")return`${t} LIKE ${n.add(`%${String(r)}%`)}`;if(e==="$startsWith"){if(typeof r!="string")throw new d("INVALID_QUERY_VALUE","$startsWith requires a string");return`${t} LIKE ${n.add(`${r}%`)}`}if(e==="$regex"){if(typeof r!="string"||a!==void 0&&typeof a!="string")throw new d("INVALID_QUERY_VALUE","$regex requires a string pattern and args.options must be a string");return o.regex(t,n.add(r),a)}throw new d("UNSUPPORTED_QUERY_OPERATOR",`Unsupported query operator: ${e}`)},Fn=(t,e)=>{if(!(typeof t=="number"&&Number.isFinite(t))){if(Array.isArray(t)){if(t.every(r=>typeof r=="number"&&Number.isFinite(r)))return;throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}if(typeof t=="object"&&t!==null&&!Et(t)){for(const[r,n]of Object.entries(t)){if(!r.startsWith("$"))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`);if(r==="$and"||r==="$or"){if(!Array.isArray(n))throw new d("INVALID_QUERY_VALUE",`${r} requires an array`);n.forEach(o=>Fn(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`)}},nt=(t,e,r,n,o,i)=>{if(Nd(e)){const c=()=>`CASE ${e.comparable.values.map((m,y)=>`WHEN ${t} = ${r.add(m)} THEN ${e.comparable.direction*y}`).join(" ")} END`,p=new Set(["$gt","$gte","$lt","$lte"]),l=f=>typeof f!="object"||f===null||Array.isArray(f)?nt(t,f,r,n,o,i):Object.entries(f).filter(([m])=>m!=="args").map(([m,y])=>(m==="$and"||m==="$or")&&Array.isArray(y)?`(${y.map(l).join(m==="$and"?" AND ":" OR ")})`:p.has(m)?Wt(c(),m,e.comparable.direction*e.comparable.values.indexOf(String(y)),r,n,o,i):Wt(t,m,y,r,n,o,i)).join(" AND ");return l(e.condition)}if(Array.isArray(e))return Wt(t,"$in",e,r,n,o,i);if(!Ki(e))return Wt(t,"$eq",e,r,n,o,i);const s=[],a=e.args;if(a!==void 0){if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_QUERY_VALUE","Query args.options must be a string");const c=a.options;if(c!==void 0&&typeof c!="string")throw new d("INVALID_QUERY_VALUE","Query args.options must be a string")}const u=a?.options;for(const[c,p]of Object.entries(e))if(c==="$and"||c==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${c} requires an array`);const l=p.map(f=>nt(t,f,r,n,o,i));s.push(`(${l.join(c==="$and"?" AND ":" OR ")})`)}else Ji[c]?(Fn(p,c),s.push(nt(n.datePart(t,Ji[c]),p,r,n,o,i))):c==="$length"?(Fn(p,"$length"),s.push(nt(n.stringLength(t),p,r,n,o,i))):c!=="args"&&s.push(Wt(t,c,p,r,n,o,i,c==="$regex"?u:void 0));if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},Xi=(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(!Ki(e))return i(e);const s=[];for(const[a,u]of Object.entries(e))if(a==="$and"||a==="$or"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(p=>Xi(t,p,r,n));s.push(`(${c.join(a==="$and"?" AND ":" OR ")})`)}else if(a==="$eq")s.push(i(u));else if(a==="$ne")s.push(`NOT (${i(u)})`);else if(a==="$in"||a==="$nin"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);const c=u.map(i),p=c.length===0?a==="$in"?"0 = 1":"1 = 1":c.join(a==="$in"?" OR ":" AND NOT ");s.push(a==="$nin"&&c.length>0?`NOT (${c.join(" OR ")})`:`(${p})`)}else if(a==="$exists")s.push(`${t} IS ${u?"NOT ":""}NULL`);else if(a!=="args")throw new d("UNSUPPORTED_ARRAY_QUERY_OPERATOR",`Unsupported array query operator: ${a}`);if(s.length===0)throw new d("EMPTY_QUERY_CONDITION","Query condition contains no operators");return s.join(" AND ")},Rt=(t,e,r,n,o,i,s,a)=>{const u=[];for(const[c,p]of Object.entries(t)){if(c==="$and"||c==="$or"){if(!Array.isArray(p))throw new d("INVALID_QUERY_VALUE",`${c} requires an array`);const f=p.map(m=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_QUERY_VALUE",`${c} items must be query objects`);return Rt(m,e,r,n,o,i,s,a)});u.push(`(${f.join(c==="$and"?" AND ":" OR ")})`);continue}if(c==="$expr"){if(!Di(p))throw new d("INVALID_EXPRESSION_QUERY","$expr query was not planned");u.push(nt(s(p.expression),p.condition,n,o,i,a));continue}const l=e(c);u.push(r(c)?Xi(l,p,n,o):nt(l,p,n,o,i,a))}return u.join(" AND ")},Nr=(t,e,r,n,o)=>t.orderBy.map(i=>{const s=e.quoteIdentifier(i.name),a=`${n?`${n}.`:""}${s}`,u=i.comparable,c=!n&&o&&i.expression?o(i.expression):a;return`${u?`CASE ${u.values.map((l,f)=>`WHEN ${c} = ${r.add(l)} THEN ${u.direction*f}`).join(" ")} END`:a} ${i.direction}`}).join(", "),Yn=(t,e)=>{let r=t;for(;e.has(r);)r=`_${r}`;return r},Zi=(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`])),es=(t,e,r,n,o)=>{const i=new Set(e.projections.map(({name:D})=>D)),s="__sdb_page_source",a="__sdb_page",u=n.quoteIdentifier(s),c=n.quoteIdentifier(a),p=Yn("__sdb_row_number",i),l=Yn("__sdb_total_rows",i),f=n.quoteIdentifier(p),m=n.quoteIdentifier(l),y=Nr(e,n,o,u),h=y?`ORDER BY ${y}`:"",g=`CEIL(${m} * ${r.ratio})`,A=r.page-1,w=r.page,E=[...e.projections.map(({name:D})=>D),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(D=>`${c}.${n.quoteIdentifier(D)}`).join(", "),$=Nr(e,n,o,c),R=`SELECT ${u}.*, ROW_NUMBER() OVER (${h}) AS ${f}, COUNT(*) OVER () AS ${m} FROM ${n.tableAlias(`(${t})`,s)}`;let O=`SELECT ${E} FROM ${n.tableAlias(`(${R})`,a)} WHERE ${c}.${f} > ${A} * ${g} AND ${c}.${f} <= ${w} * ${g}`;return $&&(O+=` ORDER BY ${$}`),O},ts=(t,e,r,n)=>{const o=e.groupLimit;if(!o)return t;const i="__sdb_limit_by_source",s="__sdb_limit_by_ranked",a=r.quoteIdentifier(i),u=r.quoteIdentifier(s),c=new Set(e.projections.map(({name:w})=>w)),p=Yn("__sdb_limit_by_row_number",c),l=r.quoteIdentifier(p),f=o.partitionBy.map(w=>`${a}.${r.quoteIdentifier(w)}`).join(", "),m=o.orderBy.map(({name:w,direction:S,comparable:E})=>{const $=`${a}.${r.quoteIdentifier(w)}`;return`${E?`CASE ${E.values.map((O,D)=>`WHEN ${$} = ${n.add(O)} THEN ${E.direction*D}`).join(" ")} END`:$} ${S}`}).join(", "),h=[...e.projections.map(({name:w})=>w),...e.rowIdentity.kind==="property"?[e.rowIdentity.internalName]:[],...e.rowIdentity.kind==="group"?["_id"]:[]].map(w=>`${u}.${r.quoteIdentifier(w)}`).join(", "),g=`PARTITION BY ${f} ORDER BY ${m}`,A=`SELECT ${a}.*, ROW_NUMBER() OVER (${g}) AS ${l} FROM ${r.tableAlias(`(${t})`,i)}`;return`SELECT ${h} FROM ${r.tableAlias(`(${A})`,s)} WHERE ${u}.${l} <= ${o.count}`},he=(t,e,r=Le(),n=0)=>{const o=new Gd(e,n),i=$=>At($);if(t.subplans){const $=t.projections.map(({name:v})=>v),R=new Set(t.groupBy.map(({name:v})=>v)),O=t.subplans.map((v,k)=>{const H=he(v,e,r,o.nextParameterOffset);o.append(H.parameters);const ae=`__composition_child_${k}`,te=e.quoteIdentifier(ae),fe=new Set(v.projections.map(({name:C})=>C));return{aliasName:ae,alias:te,available:fe,sql:H.sql}}),D=O[0];if(!D)throw new d("INVALID_COMPOSITION","Composition has no children");const M=$.map(v=>{const k=O.filter(te=>te.available.has(v)),H=k[0]??D;return`${R.has(v)&&k.length>1?`COALESCE(${k.map(te=>`${te.alias}.${e.quoteIdentifier(v)}`).join(", ")})`:`${H.alias}.${e.quoteIdentifier(v)}`} AS ${e.quoteIdentifier(v)}`}),z=O.map(v=>`${v.alias} AS (${v.sql})`);let q;if(t.rowIdentity.kind==="group"){const k=e.quoteIdentifier("__composition_keys"),H=e.quoteIdentifier("_id");z.push(`${k} AS (${O.map(ae=>`SELECT ${H} FROM ${ae.alias}`).join(" UNION ")})`),M.push(`${k}.${H} AS ${H}`),q=`WITH ${z.join(", ")} SELECT ${M.join(", ")} FROM ${k}`;for(const ae of O)q+=` LEFT JOIN ${ae.alias} ON ${k}.${H} = ${ae.alias}.${H}`}else{q=`WITH ${z.join(", ")} SELECT ${M.join(", ")} FROM ${D.alias}`;for(const v of O.slice(1))q+=` LEFT JOIN ${v.alias} ON 1 = 1`}if(t.having&&Object.keys(t.having).length>0){const v="__composition_having",k=e.quoteIdentifier(v),H=new Set($),ae=Rt(t.having,te=>{if(!H.has(te))throw new d("INVALID_HAVING",`Having field is not an output: ${te}`);return`${k}.${e.quoteIdentifier(te)}`},()=>!1,o,e,()=>{throw new d("SUBQUERY_IN_COMPOSITION_HAVING_UNSUPPORTED","A composed result having condition cannot contain a LogicForm subquery")},()=>{throw new d("EXPRESSION_QUERY_NOT_ALLOWED_IN_HAVING","$expr is only supported in query; having references projected output names")},i);q=`SELECT ${k}.* FROM ${e.tableAlias(`(${q})`,v)} WHERE ${ae}`}if(t.groupLimit&&(q=ts(q,t,e,o)),t.pagination?.kind==="ratio")q=es(q,t,t.pagination,e,o);else if(t.orderBy.length>0&&(q+=` ORDER BY ${Nr(t,e,o)}`),t.pagination?.kind==="rows"){const v=(t.pagination.page-1)*t.pagination.pageSize;q=e.paginate(q,t.pagination.pageSize,v)}return{sql:q,parameters:o.values}}const s=$=>{if($.plan.projections.some(({expression:O})=>be(O,r)))throw new d("JAVASCRIPT_OPERATOR_IN_SUBQUERY","A query LogicForm cannot use a JavaScript-only operator");const R=he($.plan.rowIdentity.kind==="property"||$.plan.rowIdentity.kind==="group"?{...$.plan,rowIdentity:{kind:"generated"}}:$.plan,e,r,o.nextParameterOffset);return o.append(R.parameters),R.sql},a=(t.joins?.length??0)>0||(t.enrichmentJoins?.length??0)>0,u=(t.arrayExpansions?.length??0)>0,c=a||u||t.sourcePlan!==void 0||t.sourceSql!==void 0||t.periodSource!==void 0,p=new Map,l=(t.arrayExpansions??[]).map($=>{if(!e.expandArray)throw new d("ARRAY_EXPANSION_UNSUPPORTED",`Provider ${e.kind} does not support array expansion`);const R=e.expandArray(zd($,e),$.alias,"value");return p.set($.path,R.valueExpression),R}),f=$=>{const R=t.fieldReferences?.[$];if(R?.sql)return Gt(R.sql,R.property,e,R.timestampColumn,c?R.timestampQualifier??R.qualifier:void 0);if(R&&c)return`${e.quoteIdentifier(R.qualifier)}.${e.quoteIdentifier(R.column)}`;const O=t.fields[$];if(!O)throw new d("PROPERTY_NOT_FOUND",`Query property not found: ${$}`);return e.quoteIdentifier(O)},m=$=>Ue($,e,r,c,R=>Rt(R,f,O=>t.fieldReferences?.[O]?.isArray===!0,o,e,s,m,i),R=>o.add(R),(R,O)=>nt(R,O,o,e,s,i),R=>{const O=p.get(R);if(!O)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${R}`);return O}),y=t.projections.map($=>`${m($.expression)} AS ${e.quoteIdentifier($.name)}`),h=t.rowIdentity.kind==="property"?`${c&&t.sourceAlias?`${e.quoteIdentifier(t.sourceAlias)}.`:""}${e.quoteIdentifier(t.rowIdentity.column)} AS ${e.quoteIdentifier(t.rowIdentity.internalName)}`:t.rowIdentity.kind==="group"?(()=>{const $=t.rowIdentity.names.map(R=>{const O=t.groupBy.find(D=>D.name===R)??t.projections.find(D=>D.name===R);if(!O)throw new d("GROUP_IDENTITY_OUTPUT_NOT_FOUND",`Group identity output not found: ${R}`);return m(O.expression)});return`${Zi($,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)} AS ${e.quoteIdentifier("_id")}`})():void 0,g=[...y,...h?[h]:[]].join(", "),A=t.sourcePlan?(()=>{const $=he(t.sourcePlan,e,r,o.nextParameterOffset);return o.append($.parameters),`(${$.sql})`})():t.source?Rr(e,t.source,t.sourceSql):"",w=c&&t.sourceAlias?e.tableAlias(A,t.sourceAlias):A;let S=`SELECT ${g}`;if(t.periodSource){const $=t.periodSource,R=$.periods.map(({label:k,asOf:H},ae)=>{const te=o.add(k),fe=o.add(H);return ae===0?`SELECT ${te} AS ${e.quoteIdentifier($.labelColumn)}, ${fe} AS ${e.quoteIdentifier($.asOfColumn)}`:`SELECT ${te}, ${fe}`}).join(" UNION ALL "),O=e.tableAlias(`(${R})`,$.alias),D=e.tableAlias(A,$.sourceAlias),M=e.quoteIdentifier($.alias),z=e.quoteIdentifier($.sourceAlias),q=`${M}.${e.quoteIdentifier($.asOfColumn)}`,v=$.match.kind==="interval"?(()=>{const k=`${z}.${e.quoteIdentifier($.match.startColumn)}`,H=`${z}.${e.quoteIdentifier($.match.endColumn)}`;return`${k} <= ${q} AND (${H} > ${q} OR ${H} IS NULL)`})():(()=>{const k=e.tableAlias(A,$.match.lookupAlias),H=e.quoteIdentifier($.match.lookupAlias),ae=`${z}.${e.quoteIdentifier($.match.timestampColumn)}`,te=`${H}.${e.quoteIdentifier($.match.timestampColumn)}`,fe=`SELECT ${e.aggregateFunction("max",te)} FROM ${k} WHERE ${te} <= ${q}`;return`${ae} = (${fe})`})();S+=` FROM ${O} LEFT JOIN ${D} ON ${v}`,t.query&&Object.keys(t.query).length>0&&(S+=` AND ${Rt(t.query,f,k=>t.fieldReferences?.[k]?.isArray===!0,o,e,s,m,i)}`)}else w&&(S+=` FROM ${w}`);for(const $ of l)S+=` ${$.joinSql}`;for(const $ of t.enrichmentJoins??[]){const R=e.quoteIdentifier($.alias),O=e.quoteIdentifier($.baseAlias);S+=` LEFT JOIN ${e.tableAlias(Rr(e,$.source,$.sourceSql),$.alias)}`;const D=$.keys.map(({baseColumn:M,targetColumn:z})=>`${O}.${e.quoteIdentifier(M)} = ${R}.${e.quoteIdentifier(z)}`);if($.temporalCondition?.kind==="point-in-interval"){const M=H=>H==="source"?O:R,z=`${M($.temporalCondition.pointSide)}.${e.quoteIdentifier($.temporalCondition.pointColumn)}`,q=M($.temporalCondition.intervalSide),v=`${q}.${e.quoteIdentifier($.temporalCondition.startColumn)}`,k=`${q}.${e.quoteIdentifier($.temporalCondition.endColumn)}`;D.push(`${v} <= ${z}`),D.push(`(${k} > ${z} OR ${k} IS NULL)`)}S+=` ON ${D.join(" AND ")}`}for(const $ of t.joins??[]){S+=` LEFT JOIN ${e.tableAlias(Rr(e,$.targetSource,$.targetSourceSql),$.targetAlias)}`;const R=$.sourceArrayExpansionPath?p.get($.sourceArrayExpansionPath):$.sourceSql?Gt($.sourceSql,$.sourceColumn,e,$.sourceTimestampColumn,$.sourceAlias):`${e.quoteIdentifier($.sourceAlias)}.${e.quoteIdentifier($.sourceColumn)}`,O=$.targetSql?Gt($.targetSql,$.targetColumn,e,$.targetTimestampColumn,$.targetAlias):`${e.quoteIdentifier($.targetAlias)}.${e.quoteIdentifier($.targetColumn)}`;if(!R)throw new d("ARRAY_EXPANSION_NOT_FOUND",`Array expansion not found: ${$.path}`);if(S+=` ON ${R} = ${O}`,$.temporalCondition?.kind==="date-bucket-equal"){const D=`${e.quoteIdentifier($.sourceAlias)}.${e.quoteIdentifier($.temporalCondition.sourceColumn)}`,M=`${e.quoteIdentifier($.targetAlias)}.${e.quoteIdentifier($.temporalCondition.targetColumn)}`;S+=` AND ${e.dateBucket(D,$.temporalCondition.sourceGranularity)} = ${e.dateBucket(M,$.temporalCondition.targetGranularity)}`}else if($.temporalCondition?.kind==="point-in-interval"){const D=k=>k==="source"?e.quoteIdentifier($.sourceAlias):e.quoteIdentifier($.targetAlias),M=`${D($.temporalCondition.pointSide)}.${e.quoteIdentifier($.temporalCondition.pointColumn)}`,z=D($.temporalCondition.intervalSide),q=`${z}.${e.quoteIdentifier($.temporalCondition.startColumn)}`,v=`${z}.${e.quoteIdentifier($.temporalCondition.endColumn)}`;S+=` AND ${q} <= ${M} AND (${v} > ${M} OR ${v} IS NULL)`}}const E=[];if(!t.periodSource&&t.query&&Object.keys(t.query).length>0&&E.push(Rt(t.query,f,$=>t.fieldReferences?.[$]?.isArray===!0,o,e,s,m,i)),E.length>0&&(S+=` WHERE ${E.join(" AND ")}`),t.groupBy.length>0){const $=t.groupBy.map(O=>m(O.expression)),R=t.rowIdentity.kind==="group"?[Zi($,e,t.rowIdentity.separator,t.rowIdentity.nullLabel)]:[];S+=` GROUP BY ${[...$,...R].join(", ")}`}if(t.having&&Object.keys(t.having).length>0){const $=R=>{const O=t.projections.find(D=>D.name===R);if(!O)throw new d("INVALID_HAVING",`Having field is not an output: ${R}`);return e.supportsHavingAlias===!1?m(O.expression):e.quoteIdentifier(R)};S+=` HAVING ${Rt(t.having,$,()=>!1,o,e,s,m,i)}`}if(t.groupLimit&&(S=ts(S,t,e,o)),t.pagination?.kind==="ratio")S=es(S,t,t.pagination,e,o);else if(t.orderBy.length>0&&(S+=` ORDER BY ${Nr(t,e,o,void 0,m)}`),t.pagination?.kind==="rows"){const $=(t.pagination.page-1)*t.pagination.pageSize;S=e.paginate(S,t.pagination.pageSize,$)}return{sql:S,parameters:o.values}},Kd=(t,e)=>{const r=Object.keys(e).sort((f,m)=>m.length-f.length),n=[];let o=0;for(;o<t.length;){const f=t[o];if(f&&/\s/.test(f)){o+=1;continue}if(f&&/[()+\-*/,]/.test(f)){n.push(f),o+=1;continue}const m=t.slice(o).match(/^\d+(?:\.\d+)?/);if(m?.[0]){n.push(m[0]),o+=m[0].length;continue}const y=r.find(g=>t.startsWith(g,o));if(y){n.push(y),o+=y.length;continue}const h=t.slice(o).match(/^[A-Za-z_$][\w$]*/);if(h?.[0]){n.push(h[0]),o+=h[0].length;continue}n.push(f??""),o+=1}let i=0;const s=()=>n[i],a=()=>n[i++],u=()=>{const f=a();if(!f)throw new Error("Component expression is incomplete");if(f==="("){const y=p();if(a()!==")")throw new Error("Component expression has an unclosed parenthesis");return`(${y})`}if(/^\d/.test(f))return f;if(!e[f]&&!/^[A-Za-z_$][\w$]*$/.test(f))throw new Error(`Invalid component expression token: ${f}`);if(s()==="("){a();const y=[];if(s()!==")")for(;y.push(p()),s()===",";)a();if(a()!==")")throw new Error("Component expression has an unclosed function call");if(!["ABS","NULLIF","COALESCE"].includes(f.toUpperCase()))throw new Error(`Unsupported component expression function: ${f}`);return`${f.toUpperCase()}(${y.join(", ")})`}const m=e[f];if(!m)throw new Error(`Unknown component in expression: ${f}`);return m},c=()=>{let f=u();for(;s()==="*"||s()==="/";)f=`${f} ${a()} ${u()}`;return f},p=()=>{let f=c();for(;s()==="+"||s()==="-";)f=`${f} ${a()} ${c()}`;return f},l=p();if(i!==n.length)throw new Error(`Unexpected component expression token: ${s()}`);return l},Jd=t=>`__sdb_cte_${t}`,rs=t=>{const e=t.projections[t.groupBy.length];if(!e)throw new Error("CTE component must produce one metric projection");return e.name},Xd=(t,e)=>t?.find(r=>r.name===e),Zd=(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,Hn=(t,e,r,n=Le())=>{if(t.length===0)throw new Error("CTE query combination requires at least one unit");let o=0;const i=t.map((w,S)=>{const E={...w.compiled,sql:Zd(w.compiled.sql,r,o)};return o+=w.compiled.parameters.length,{...w,compiled:E,alias:`__sdb_exec_${S}`}}),s=i.map(({alias:w,compiled:S})=>`${r.quoteIdentifier(w)} AS (${S.sql})`),a=i[0],u=r.quoteIdentifier(a.alias),c=e.groupBy.map(({name:w})=>w),p=e.orderBy??[],l=e.rowIdentity.kind==="group",f=r.quoteIdentifier("__sdb_exec_keys");if(l){const w=S=>[...c.map(E=>`${S}.${r.quoteIdentifier(E)}`),`${S}.${r.quoteIdentifier("_id")}`].join(", ");s.push(`${f} AS (${i.map(({alias:S})=>`SELECT ${w(r.quoteIdentifier(S))} FROM ${r.quoteIdentifier(S)}`).join(" UNION ")})`)}const m=l?f:u,y=[...c,...t.flatMap(({outputs:w})=>w)],h=y.filter((w,S,E)=>E.indexOf(w)===S).map(w=>{if(c.includes(w))return`${m}.${r.quoteIdentifier(w)} AS ${r.quoteIdentifier(w)}`;const S=i.find(({outputs:$})=>$.includes(w));if(!S)throw new Error(`CTE execution unit does not expose output projection: ${w}`);return`${r.quoteIdentifier(S.alias)}.${r.quoteIdentifier(w)} AS ${r.quoteIdentifier(w)}`});l&&h.push(`${m}.${r.quoteIdentifier("_id")} AS ${r.quoteIdentifier("_id")}`);let g=`SELECT ${h.join(", ")} FROM ${m}`;for(const w of l?i:i.slice(1)){const S=r.quoteIdentifier(w.alias);g+=` LEFT JOIN ${S}`,g+=l?` ON ${m}.${r.quoteIdentifier("_id")} = ${S}.${r.quoteIdentifier("_id")}`:" ON 1 = 1"}if(!!(e.having&&Object.keys(e.having).length>0||p.length>0||e.pagination||e.groupLimit)){const w={schemaId:e.schemaId,source:"__sdb_cte_result_source",sourceSql:g,sourceAlias:"__sdb_cte_result",fields:Object.fromEntries(y.map(E=>[E,E])),projections:y.map(E=>({name:E,expression:{kind:"column",property:E,column:E}})),groupBy:[],...e.having&&Object.keys(e.having).length>0?{query:e.having}:{},orderBy:p.map(({name:E,direction:$,comparable:R})=>({name:E,direction:$,...R?{comparable:R}:{}})),...e.pagination?{pagination:e.pagination}:{},...e.groupLimit?{groupLimit:e.groupLimit}:{},rowIdentity:{kind:"generated"}},S=he(w,r,n,o);return{sql:`WITH ${s.join(", ")} ${S.sql}`,parameters:[...i.flatMap(({compiled:E})=>E.parameters),...S.parameters]}}return{sql:`WITH ${s.join(", ")} ${g}`,parameters:i.flatMap(({compiled:w})=>w.parameters)}},Or=(t,e,r,n,o,i)=>{const s=[];let a=0;for(const w of e){const S=he(w.plan,o,i,a);a+=S.parameters.length,s.push({input:w,sql:S,alias:Jd(w.name)})}const u=s.map(({sql:w,alias:S})=>`${o.quoteIdentifier(S)} AS (${w.sql})`).join(", "),c=s[0];if(!c)throw new Error("CTE calculation requires a current component");const p=o.quoteIdentifier(c.alias),l=r.groupBy.map(({name:w})=>w),f=l.map(w=>`${p}.${o.quoteIdentifier(w)} AS ${o.quoteIdentifier(w)}`);let m="";for(const w of s.slice(1)){const S=o.quoteIdentifier(w.alias),E=w.input.plan.groupBy.map(({name:O})=>O),R=(w.input.joinKeys??l.filter(O=>E.includes(O))).map(O=>{const D=Xd(w.input.groupKeyShifts,O),M=D?o.dateShift(`${S}.${o.quoteIdentifier(O)}`,D.granularity,D.offset):`${S}.${o.quoteIdentifier(O)}`;return`${p}.${o.quoteIdentifier(O)} = ${M}`});m+=` LEFT JOIN ${S} ON ${R.length>0?R.join(" AND "):"1 = 1"}`}const y=Object.fromEntries(s.map(({input:w,alias:S})=>[w.name,`${o.quoteIdentifier(S)}.${o.quoteIdentifier(rs(w.plan))}`])),h=Kd(t.expression,y),g=[...f,...r.rowIdentity.kind==="group"?[`${p}.${o.quoteIdentifier("_id")} AS ${o.quoteIdentifier("_id")}`]:[],...s.map(({input:w,alias:S})=>`${`${o.quoteIdentifier(S)}.${o.quoteIdentifier(rs(w.plan))}`} AS ${o.quoteIdentifier(w.name)}`),`${h} AS ${o.quoteIdentifier(n)}`].join(", ");let A=`WITH ${u} SELECT ${g} FROM ${p}`;return A+=m,{sql:A,parameters:s.flatMap(({sql:w})=>w.parameters)}},el=t=>{if(typeof t!="string"||!/\bSELECT\b/i.test(t))return t;try{let e=t;const r=os(t).length*2+2;for(let n=0;n<r;n+=1){const o=tl(e);if(o===e)return e;e=o}return e}catch{return t}},tl=t=>{const e=os(t),r=rl(t,e);if(r!==t)return r;const n=[];for(const i of e){const s=is(t,i.selectEnd,i.fromStart),a=s?.length===1&&s[0]?.trim()==="*"?gl(t.slice(i.fromStart+4,i.close)):null;if(a){n.push({start:i.open,end:i.close+1,value:a});continue}if(!s||s.some(h=>h.trim()==="*"))continue;const u=yl(nl(t.slice(i.fromStart,i.close),i,e)),c=ol(t,i),p=il(t,i);if(p&&sl(c,p))continue;let l=s.filter(h=>{const g=ss(h);if(!g||g==="_id")return!0;const A=new RegExp(`(^|[^\\w$])${Qn(g)}([^\\w$]|$)`,"i");return A.test(u)||A.test(c)}),f=!0;for(;f;){f=!1;const h=us(l.join(" ")),g=s.filter(A=>{if(l.includes(A))return!1;const w=ss(A);return w?new RegExp(`(^|[^\\w$])${Qn(w)}([^\\w$]|$)`,"i").test(h):!1});g.length>0&&(l=s.filter(A=>l.includes(A)||g.includes(A)),f=!0)}if(l.length===s.length)continue;const m=t.slice(i.selectEnd,i.fromStart),y=l.length===0&&hl(t,i)&&!/(^|[^\w$])\*([^\w$]|$)/.test(c)&&!/^\s*(?:DISTINCT|ALL|TOP|SQL_)\b/i.test(m)&&!/\b(?:UNION|INTERSECT|EXCEPT)\b/i.test(u);l.length===0&&!y||n.push({start:i.selectEnd,end:i.fromStart,value:m.match(/^\s*/)[0]+(y?"1":l.map(h=>h.trim()).join(", "))+m.match(/\s*$/)[0]})}n.sort((i,s)=>s.start-i.start);let o=t;for(const i of n)o=o.slice(0,i.start)+i.value+o.slice(i.end);return o},rl=(t,e)=>{const r=/^\s*SELECT\b/i.exec(t);if(!r)return t;const n=r.index+r[0].length,o=ns(t,"FROM",n);if(o===-1||!is(t,n,o)?.every(ml))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=pl.exec(u)?.[1],p=fl.exec(t.slice(s.close+1));if(!c||!p||as(c)!==as(p[1]))return t;const l=/;(\s*)$/.exec(t)?.[0]??"";return t.slice(0,s.open)+t.slice(a.open,s.close)+l},nl=(t,e,r)=>al(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}))),ol=(t,e)=>{const r=t.slice(0,e.open)+" ".repeat(e.close-e.open+1)+t.slice(e.close+1);return us(r)},il=(t,e)=>t.slice(e.close+1).match(new RegExp(`^\\s*(?:AS\\s+)?(${ve})(?=\\s|$)`,"i"))?.[1]??null,sl=(t,e)=>new RegExp(`(^|[^\\w$])${Qn(e)}\\s*\\.\\s*\\*([^\\w$]|$)`,"i").test(t),al=(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("")},ns=(t,e,r)=>{let n=0,o=0,i="",s="";for(let a=r;a<t.length;a+=1){const u=t[a],c=t[a+1];if(s==="--"){u===`
|
|
2
|
+
`&&(s="");continue}if(s==="/*"){u==="*"&&c==="/"&&(s="",a+=1);continue}if(i){u===i&&t[a-1]!=="\\"&&(i="");continue}if(u==="-"&&c==="-"){s="--",a+=1;continue}if(u==="/"&&c==="*"){s="/*",a+=1;continue}if(u==="`"||u==='"'||u==="'"){i=u;continue}if(u==="("){n+=1;continue}if(u===")"){n-=1;continue}if(u==="["){o+=1;continue}if(u==="]"){o-=1;continue}if(n===0&&o===0&&new RegExp(`^${e}\\b`,"i").test(t.slice(a)))return a}return-1},os=t=>{const e=[],r=[];let n="",o="";for(let i=0;i<t.length;i+=1){const s=t[i],a=t[i+1];if(o==="--"){s===`
|
|
3
|
+
`&&(o="");continue}if(o==="/*"){s==="*"&&a==="/"&&(o="",i+=1);continue}if(n){s===n&&t[i-1]!=="\\"&&(n="");continue}if(s==="-"&&a==="-"){o="--",i+=1;continue}if(s==="/"&&a==="*"){o="/*",i+=1;continue}if(s==="`"||s==='"'||s==="'"){n=s;continue}if(s==="("){r.push({open:i});continue}if(s!==")")continue;const u=r.pop();if(!u)continue;const c=t.slice(u.open+1,i),p=/^\s*SELECT\b/i.exec(c);if(!p)continue;const l=u.open+1+p.index,f=ns(t,"FROM",l+6);f===-1||f>=i||e.push({open:u.open,close:i,selectEnd:l+6,fromStart:f})}return e},is=(t,e,r)=>{const n=t.slice(e,r),o=[];let i=0,s=0,a=0,u="";for(let c=0;c<n.length;c+=1){const p=n[c];if(u){p===u&&n[c-1]!=="\\"&&(u="");continue}if(p==="`"||p==='"'||p==="'"){u=p;continue}p==="("?s+=1:p===")"?s-=1:p==="["?a+=1:p==="]"?a-=1:p===","&&s===0&&a===0&&(o.push(n.slice(i,c)),i=c+1)}return u||s!==0||a!==0?null:(o.push(n.slice(i)),o)},ss=t=>t.trim().match(/\bAS\s+(`[^`]+`|"[^"]+"|[A-Za-z_][\w$]*)\s*$/i)?.[1]?.replace(/^`|`$/g,"").replace(/^"|"$/g,"")??null,ve='(?:`(?:``|[^`])+`|"(?:""|[^"])+"|[A-Za-z_][\\w$]*)',cl=new RegExp(`\\s+AS\\s+${ve}\\s*$`,"i"),ul=new RegExp(`\\bAS\\s+${ve}`,"gi"),dl=new RegExp(`(?:${ve}\\s*\\.\\s*)+${ve}`,"g"),ll=new RegExp(`^${ve}(?:\\s*\\.\\s*${ve})*$`),pl=new RegExp(`^\\s*(?:AS\\s+)?(${ve})\\s+WHERE\\b`,"i"),fl=new RegExp(`^\\s*(?:AS\\s+)?(${ve})\\s*;?\\s*$`,"i"),as=t=>t.replace(/^`|`$/g,"").replace(/^"|"$/g,"").toLowerCase(),ml=t=>{const e=t.replace(cl,"").trim();return/^(?:NULL|TRUE|FALSE|[-+]?\d+(?:\.\d+)?|'(?:''|[^'])*')$/i.test(e)||/^COUNT\s*\(\s*(?:\*|1)\s*\)$/i.test(e)},cs=(t,e)=>t.replace(e,r=>" ".repeat(r.length)),us=t=>cs(t,ul),yl=t=>cs(t,dl),hl=(t,e)=>/\b(?:FROM|JOIN)\s*$/i.test(t.slice(0,e.open)),gl=t=>{const e=t.trim();return ll.test(e)?e:null},Qn=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Gn=(t,e)=>{if(t.kind!=="operator")return!1;const r=e.get(t.operator);return!r.toSQL&&!!r.evaluate||(t.input?Gn(t.input,e):!1)||(t.inputs?.some(n=>Gn(n,e))??!1)},ds=(t,e,r,n)=>{if(t.kind!=="operator")return e[r];const o=n.get(t.operator),i=t.input?ds(t.input,e,r,n):e[r];return o.evaluate?Promise.resolve(i).then(s=>o.evaluate?.({input:s,args:t.args})):i},ot=async(t,e,r)=>{const n=e.filter(({expression:o})=>Gn(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 ds(s.expression,i,s.name,r);return i}))},Tr=t=>t==null?"\u7A7A\u503C":typeof t=="object"?"_id"in t?String(t._id):"id"in t?String(t.id):JSON.stringify(t):String(t),Wn=(t,e,r="_",n="\u7A7A\u503C")=>e.map(o=>t[o]===null||t[o]===void 0?n:Tr(t[o])).join(r),zn=(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?Wn(r,e.names,e.separator,e.nullLabel):Tr(r._id)}:{...r,_id:e.kind==="singleton"?"0":Co()}}),$l=t=>{const e=ne(t);return delete e.having,delete e.sort,delete e.limit,delete e.page,e},zt=(t,e)=>t.operator&&e.get(t.operator).kind==="component"?!0:!!t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&zt(t.pred,e)||Array.isArray(t.pred)&&t.pred.some(r=>typeof r!="string"&&zt(r,e)),Pr=(t,e,r,n,o,i,s="zh-CN",a=pr.translator(s))=>{const u=t.preds??[],c=u.map((m,y)=>({pred:m,index:y,definition:m.operator?n.get(m.operator):void 0})).filter(({definition:m})=>m?.kind==="component"&&!m.skipComponentExecution?.({plan:e}));if(c.length===0&&e.sourcePlan||c.length===0)return;for(const m of u)if((!m.operator||n.get(m.operator).kind!=="component")&&(m.pred&&typeof m.pred=="object"&&!Array.isArray(m.pred)&&zt(m.pred,n)||Array.isArray(m.pred)&&m.pred.some(y=>typeof y!="string"&&zt(y,n))))throw new d("UNSUPPORTED_COMPONENT_NESTING","A component operator must currently be the top-level projection operator");const p=[],l=u.filter((m,y)=>!c.some(h=>h.index===y));if(l.length>0){const m=$l(t);m.preds=l,p.push({kind:"query",logicform:m})}const f=t.groupby?.length??0;for(const{pred:m,index:y,definition:h}of c){const g=h?.createComponent;if(!g)continue;const A=e.projections[f+y]?.name;if(!A)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");const w=i?.preds?.[y],S=g({logicform:t,pred:w??m,outputName:A,locale:s,t:a,schema:r,resolveSchema:o,...i?{sourceLogicform:i}:{}});if("logicform"in S&&(S.logicform.preds??[]).some(E=>zt(E,n)))throw new d("UNSUPPORTED_COMPONENT_NESTING","Nested component operators are not supported yet");p.push("components"in S?{...S,outputName:A}:S)}return p},Me=t=>t instanceof Date?t.getTime():t,Al=(t,e,r,n)=>{const o=Me(t),i=Me(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=>Me(s)===o);case"$nin":return Array.isArray(r)&&r.every(s=>Me(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}`)}},Kn=(t,e)=>{if(!e||typeof e!="object"||Array.isArray(e))return Me(t)===Me(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=>Kn(t,u));return i==="$and"?a.every(Boolean):a.some(Boolean)}return i==="$length"?typeof t=="string"&&Kn(t.length,s):Al(t,i,s,typeof o=="string"?o:void 0)})},ls=(t,e)=>Object.entries(e).every(([r,n])=>{if(r==="$and"||r==="$or"){if(!Array.isArray(n))return!1;const o=n.map(i=>ls(t,i));return r==="$and"?o.every(Boolean):o.some(Boolean)}return Kn(t[r],n)}),ps=(t,e)=>e.length===0?"0":t._id===void 0?Wn(t,e):Tr(t._id),Jn=(t,e)=>{const r=new Map;for(const n of t)for(const o of n){const i=ps(o,e);r.set(i,{...r.get(i)??{},...o})}return[...r.values()]},Xn=(t,e)=>{const r=e.groupBy.map(({name:o})=>o);let n=Jn(t,r);if(e.having&&(n=n.filter(o=>ls(o,e.having))),e.groupLimit){const o=e.groupLimit,i=new Map;for(const s of n){const a=ps(s,o.partitionBy);i.set(a,[...i.get(a)??[],s])}n=[...i.values()].flatMap(s=>s.sort((a,u)=>{for(const c of o.orderBy){const p=Me(a[c.name]),l=Me(u[c.name]);if(p!==l)return p==null?c.direction==="ASC"?-1:1:l==null?c.direction==="ASC"?1:-1:(p<l?-1:1)*(c.direction==="ASC"?1:-1)}return 0}).slice(0,o.count))}if(e.orderBy.length>0&&n.sort((o,i)=>{for(const s of e.orderBy){const a=Me(o[s.name]),u=Me(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},fs=(t,e,r)=>{if(!t.schema||t.schema===e.id)return e;const n=r.resolveSchema?.(t.schema);if(!n)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cannot normalize nested LogicForm schema without a schema resolver: ${t.schema}`,{schemaId:t.schema});return n};class Zn{#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 wl=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)}},ms=t=>{wl(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)})},El=new Set(["second","minute","hour","day","week","month","quarter","year"]),_l=(t,e)=>{if("_id"in t||"_sid"in t)throw new d("LEGACY_PROPERTY_ID_NOT_ALLOWED",`Property ${t.name} must use id instead of _id; _sid is not supported`,{property:t.name});if("sid"in t)throw new d("PROPERTY_SID_NOT_ALLOWED",`Property ${t.name} must not declare sid`,{property:t.name});const r=t;if(r.is_comparable!==void 0||r.comparable_order!==void 0)throw new d("LEGACY_COMPARABLE_NOT_ALLOWED",`Property ${t.name} must use comparable instead of is_comparable/comparable_order`,{property:t.name});if(t.udf!==void 0){const a=t.udf;if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_PROPERTY_UDF",`Property ${t.name} udf must be an object containing only sql`,{property:t.name});const u=a,c=Object.keys(u).filter(p=>p!=="sql");if(c.length>0)throw new d("UNSUPPORTED_PROPERTY_UDF",`Property ${t.name} udf only supports sql`,{property:t.name,unsupportedKeys:c});if(typeof u.sql!="string"||u.sql.trim().length===0)throw new d("INVALID_PROPERTY_UDF",`Property ${t.name} udf.sql must be a non-empty string`,{property:t.name})}const n=e.get(t.type),o=t.primal_type==="object"?"entity":t.primal_type;if(o!==void 0&&o!==n.primalType)throw new d("PRIMAL_TYPE_MISMATCH",`Property ${t.name} declares primal_type ${t.primal_type}, but ${t.type} requires ${n.primalType}`,{property:t.name,type:t.type,declared:t.primal_type,expected:n.primalType});if(t.isArray!==void 0&&typeof t.isArray!="boolean")throw new d("INVALID_IS_ARRAY",`Property ${t.name} isArray must be a boolean`,{property:t.name,isArray:t.isArray});if("is_observation"in t)throw new d("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED",`Property ${t.name} must use Schema temporalSemantics; is_observation is not supported`,{property:t.name});if(t.comparable!==void 0){const a=t.comparable;if(typeof a!="object"||a===null||Array.isArray(a))throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable must contain values and direction`);const u=a;if(Object.keys(u).some(c=>c!=="values"&&c!=="direction")||!Array.isArray(u.values)||u.values.length===0||u.values.some(c=>typeof c!="string")||new Set(u.values).size!==u.values.length||u.direction!==1&&u.direction!==-1)throw new d("INVALID_COMPARABLE_CATEGORY",`Property ${t.name} comparable requires unique string values and direction 1 or -1`,{property:t.name,comparable:a});if(t.type!=="category"||t.isArray===!0)throw new d("COMPARABLE_CATEGORY_REQUIRED",`Property ${t.name} comparable is only supported by scalar category properties`,{property:t.name,type:t.type})}const i={...t,id:t.id??t.name,primal_type:n.primalType,isArray:t.isArray??!1,is_dynamic:t.udf?.sql!==void 0,...n.primalType==="date"?{granularity:t.granularity??"day"}:{}};if(n.primalType==="entity"||n.primalType==="object"){if(typeof i.ref!="string"||i.ref.length===0)throw new d("PROPERTY_REF_REQUIRED",`Entity property ${i.name} must declare ref`,{property:i.name,type:i.type})}else if(i.ref!==void 0)throw new d("PROPERTY_REF_NOT_ALLOWED",`Property ${i.name} cannot declare ref unless its primal_type is entity`,{property:i.name,type:i.type});if(n.primalType==="date"||t.type==="duration"){if(i.granularity!==void 0&&!El.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},ys=(t,e,r=[])=>{const n=me(r),o=n.reduce((m,y)=>y.prepareSchema?.(m)??m,t);if("_id"in o||"_sid"in o)throw new d("LEGACY_SCHEMA_ID_NOT_ALLOWED","Schema must use id instead of _id; _sid is not supported");if("sid"in o)throw new d("SCHEMA_SID_NOT_ALLOWED","Schema must not declare sid");if("is_snapshot"in o||"is_observation"in o)throw new d("LEGACY_TEMPORAL_SEMANTICS_NOT_ALLOWED","Schema must use temporalSemantics instead of is_snapshot/is_observation",{schemaId:o.id});if(!o.id)throw new d("INVALID_SCHEMA_ID","Schema id must not be empty");const i=n.flatMap(m=>m.propertyMetadata?[m.propertyMetadata]:[]),s=new Set(i.flatMap(({keys:m})=>m));let a=o.properties.map(m=>{const y=Object.fromEntries(Object.entries(m).filter(([g])=>!s.has(g))),h=_l(y,e);return i.reduce((g,A)=>({...g,...A.resolve(m,g,o)}),h)});for(const m of i)a=[...m.resolveAll?.(a,o.properties,o)??a];ms(a);const u=n.flatMap(m=>m.schemaMetadata?[m.schemaMetadata]:[]);let c={};for(const m of u)c={...c,...m.resolve(o,a)};const p=new Set(n.flatMap(m=>[...m.schemaMetadata?.keys??[],...m.legacySchemaKeys??[]])),f={...Object.fromEntries(Object.entries(o).filter(([m])=>!p.has(m))),properties:a,...c};for(const m of n)m.validateResolvedSchema?.(f);return f};ue.extend(Do),ue.extend(Mt),ue.extend(ar);const Sl="YYYY-MM-DD HH:mm:ss",Il=new Set(["YTD","QTD","MTD","WTD","DTD"]),hs=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$nin","$and","$or"]),bl=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),Lr=["second","minute","hour","day","week","month","quarter","year"],it=t=>Object.prototype.toString.call(t)==="[object Object]",gs=(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(it(t)){const n=Object.entries(t);if(n.length===0||n.some(([o])=>!hs.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=>gs(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`)},eo=t=>!it(t)||"$gte"in t||"$gt"in t||"$lte"in t||"$lt"in t||"$or"in t||"$ne"in t?!1:typeof t.granularity=="string"&&Lr.includes(t.granularity)&&typeof t.offset=="number"||Lr.some(e=>e in t),Nt=t=>ue(t).format(Sl),Rl=(t,e)=>Lr.find(r=>r in t||e!==void 0),Nl=(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),$s=(t,e)=>{const r=typeof t.granularity=="string"?t.granularity:void 0,n=r?{[r]:t.offset}:void 0,o=r??Rl(t,void 0)??"day";let i=ue(e).millisecond(0);for(const a of[...Lr].reverse()){const u=t[a];typeof u=="number"&&(i=Nl(i,a,u));const c=n?.[a];typeof c=="number"&&c!==0&&(i=i.add(c,a))}const s=o==="week"?"isoWeek":o;return{$gte:Nt(i.startOf(s)),$lte:Nt(i.endOf(s))}},Ol=(t,e)=>{const r=ue(e),o={DTD:()=>r.startOf("day"),WTD:()=>r.startOf("isoWeek"),MTD:()=>r.startOf("month"),QTD:()=>r.startOf("quarter"),YTD:()=>r.startOf("year")}[t];return{$gte:Nt(o()),$lte:Nt(r.endOf("day"))}},to=async(t,e)=>{const r=ue(String(t.$lte)),n=await e.requestTimeWatermark(r.toDate());if(!n)return t;const o=e.property.granularity??"day",i=o==="week"?"isoWeek":o,s=ue(n).endOf(i),a=ue(String(t.$gte));if(a.isValid()&&s.isBefore(a))return t;const u=s.isBefore(r)?s:r;return{...t,$lte:Nt(u)}},ro=async(t,e)=>Se(t)?t:t instanceof Date||typeof t=="string"&&ue(t).isValid()?Nt(t):typeof t=="string"&&Il.has(t)?to(Ol(t,e.now),e):eo(t)?to($s(t,e.now),e):t,As=async(t,e,r)=>{if(t==="$and"||t==="$or")return Array.isArray(e)?Promise.all(e.map(o=>Dr(o,r))):e;if(Array.isArray(e))return Promise.all(e.map(o=>ro(o,r)));const n=await ro(e,r);return t==="$eq"&&it(n)&&"$gte"in n&&"$lte"in n?n:t==="$gte"||t==="$gt"?it(n)&&"$gte"in n?n.$gte:n:(t==="$lte"||t==="$lt")&&it(n)&&"$lte"in n?n.$lte:n},Dr=async(t,e)=>{if(Se(t))return t;if(Array.isArray(t))return Promise.all(t.map(o=>Dr(o,e)));if(!it(t))return ro(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)&&(!eo(t)||!Number.isInteger(t.offset)))throw new d("INVALID_DATE_VALUE","Relative date values require one granularity and an integer offset");if(eo(t))return to($s(t,e.now),e);const r=Object.entries(t);if(r.length===1&&r[0]?.[0]==="$eq"){const o=await As("$eq",r[0][1],e);if(it(o)&&"$gte"in o&&"$lte"in o)return o}const n={};for(const[o,i]of r)bl.has(o)&&gs(i,o),n[o]=hs.has(o)?await As(o,i,e):await Dr(i,e);return n},Tl=(t,e)=>e.property.primal_type==="date"?Dr(t,e):t,no=(t=[])=>new Zn([...Dn,...me(t).flatMap(({semanticTypes:e})=>e??[])]),ws=(t,e)=>{const r=new Zn(t.definitions());for(const n of me(e))for(const o of n.semanticTypes??[])if(!r.has(o.name))r.register(o);else if(r.get(o.name)!==o)throw new d("PLUGIN_SEMANTIC_TYPE_ALREADY_REGISTERED",`Plugin SemanticType is already registered: ${o.name}`,{semanticType:o.name,plugin:n.name});return r},Pl=/^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Ll=t=>{if(typeof t!="string")return!1;const e=Pl.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},oo=t=>{if(!Ll(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})},Es=(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)&&Es(o,e))),_s=(t,e,r,n=[])=>{if(e===void 0||e==="placeholder")return t;if(!yn(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&&Es(t,new Set([o.name,o.id]))?t:{[o.name]:e,...t??{}}},Ot=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Dl={year:"\u5E74",quarter:"\u5B63\u5EA6",month:"\u6708",week:"\u5468",day:"\u65E5",hour:"\u65F6",minute:"\u5206",second:"\u79D2"},Ss={$second:{zh:"\u79D2",en:"second"},$minute:{zh:"\u5206\u949F",en:"minute"},$hour:{zh:"\u5C0F\u65F6",en:"hour"},$weekday:{zh:"\u661F\u671F",en:"weekday"},$day:{zh:"\u65E5",en:"day of month"},$week:{zh:"\u5468",en:"week"},$month:{zh:"\u6708",en:"month"},$quarter:{zh:"\u5B63\u5EA6",en:"quarter"},$year:{zh:"\u5E74",en:"year"}},Tt=(t,e)=>{if(t===null)return e?"null":"\u7A7A\u503C";if(typeof t=="string"||typeof t=="number")return String(t);if(typeof t=="boolean")return e?String(t):t?"\u662F":"\u5426";if(Array.isArray(t))return t.map(n=>Tt(n,e)).join(e?", ":"\u3001");if(!Ot(t))return e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6";if(Array.isArray(t.roots))return t.roots.map(n=>Tt(n,e)).join(e?", ":"\u3001");if(t.root!==void 0)return Tt(t.root,e);const r=["year","quarter","month","week","day","hour","minute","second"].filter(n=>t[n]!==void 0).map(n=>e?`${n} ${String(t[n])}`:`${String(t[n])}${Dl[n]??""}`);return r.length>0?r.join(e?", ":""):e?"the specified condition":"\u6307\u5B9A\u6761\u4EF6"},Cr=(t,e,r)=>t.filter(Boolean).join(r?e==="$and"?" and ":" or ":e==="$and"?"\u4E14":"\u6216"),Is=(t,e,r,n)=>{const s=(n?{$eq:"is",$ne:"is not",$gt:"is greater than",$gte:"is at least",$lt:"is less than",$lte:"is at most",$in:"is one of",$nin:"is none of",$contains:"contains",$startsWith:"starts with",$regex:"matches",$recursive:"is"}:{$eq:"\u4E3A",$ne:"\u4E0D\u4E3A",$gt:"\u5927\u4E8E",$gte:"\u5927\u4E8E\u7B49\u4E8E",$lt:"\u5C0F\u4E8E",$lte:"\u5C0F\u4E8E\u7B49\u4E8E",$in:"\u4E3A",$nin:"\u4E0D\u4E3A",$contains:"\u5305\u542B",$startsWith:"\u4EE5",$regex:"\u5339\u914D",$recursive:"\u5C5E\u4E8E"})[t];if(!s)return;const a=t==="$startsWith"?n?"":"\u5F00\u5934":t==="$in"?n?"":"\u4E4B\u4E00":t==="$nin"?n?"":"\u4E2D\u7684\u4EFB\u4E00\u9879":t==="$recursive"?n?" or a descendant":"\u53CA\u5176\u4E0B\u7EA7":"";return n?`${e} ${s} ${r}${a}`:`${e}${s}${r}${a}`},Kt=(t,e,r)=>{if(!Ot(e)||Object.keys(e).every(o=>!o.startsWith("$")))return Is("$eq",t,Tt(e,r),r)??"";const n=[];for(const[o,i]of Object.entries(e))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Cr(i.map(s=>Kt(t,s,r)),o,r));else if(o==="$exists")n.push(r?`${t} ${i?"exists":"does not exist"}`:`${i?"\u6709":"\u65E0"}${t}`);else if(Ss[o]){const s=Ss[o];n.push(Kt(r?`${t} ${s.en}`:`${t}\u7684${s.zh}`,i,r))}else if(o==="$length")n.push(Kt(r?`${t} length`:`${t}\u957F\u5EA6`,i,r));else if(o!=="args"){const s=o==="$regex"&&Ot(i)?Tt(i.pattern,r):Tt(i,r),a=Is(o,t,s,r);a&&n.push(a)}return Cr(n,"$and",r)},bs=(t,e="zh-CN")=>{const r=e.toLowerCase().startsWith("en"),n=[];for(const[o,i]of Object.entries(t))if((o==="$and"||o==="$or")&&Array.isArray(i))n.push(Cr(i.map(s=>Ot(s)?bs(s,e):""),o,r));else if(o==="$expr"&&Ot(i)){const s=i.pred,a=Ot(s)&&typeof s.name=="string"?s.name:r?"expression":"\u8868\u8FBE\u5F0F";i.condition!==void 0&&n.push(Kt(a,i.condition,r))}else i!==void 0&&n.push(Kt(o,i,r));return Cr(n,"$and",r)},Pt=(t,e,r={})=>{if(t.name!==void 0){if(typeof t.name!="string"||t.name.length===0)throw new d("INVALID_PRED_NAME","PredItem name must be a non-empty string");return t.name}const n=r.locale??"zh-CN",o=r.localeRegistry??pr,i=o.resolve(n).locale.toLowerCase().startsWith("en"),s=o.translator(n),a=Array.isArray(t.pred)?t.pred.map(m=>typeof m=="string"?m:Pt(m,e,r)):[],u=typeof t.pred=="string"?t.pred:t.pred&&!Array.isArray(t.pred)?Pt(t.pred,e,r):void 0,c=u??(a.length>0?a.join(i?", ":"\u3001"):s("operator.rows",i?"rows":"\u6570\u636E\u884C")),p=t.args??{},l=t.operator?(()=>{const m=e.get(t.operator),y={operandName:c,...u?{inputName:u}:{},inputNames:a,args:p,locale:n,t:s},h=m.defaultName(y);if(typeof h!="string"||h.length===0)throw new d("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});const g=typeof p.granularity=="string"?s(`time.granularity.${p.granularity}`,p.granularity):s("time.granularity.period","\u5468\u671F"),A=i?t.operator==="$concat"?" and ":t.operator==="$multiply"?" times ":" plus ":t.operator==="$concat"?"\u4E0E":t.operator==="$multiply"?"\u4E58\u4EE5":"\u52A0";if(m.defaultNameIsLocalized)return h;const w=typeof m.defaultNameKey=="function"?m.defaultNameKey(y):m.defaultNameKey??`operator.${t.operator}`;return s(w,h,{...p,operandName:c,inputName:u??"",inputNames:a.join(A),input0:a[0]??"",input1:a[1]??"",granularity:g})})():c;if(typeof l!="string"||l.length===0)throw new d("INVALID_PRED_NAME",`Operator defaultName must return a non-empty name: ${t.operator}`,{operator:t.operator});if(!t.query)return l;const f=bs(t.query,n);return f?i?`${l} where ${f}`:`${f}\u7684${l}`:l},Cl=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},kl=t=>{if(t.args===void 0||Object.keys(t.args).length>0)return t;const{args:e,...r}=t;return r},Ul=async(t,e,r)=>{if(t.operator!=="$case"||t.args?.mode!=="auto"||t.args.min!==void 0||t.args.max!==void 0||t.args.empty===!0)return t;if(typeof t.pred!="string")throw new d("AUTO_CASE_PROPERTY_REQUIRED","$case auto mode requires a direct property pred when bounds are not explicit");if(!r.requestAutoCaseBounds)return t;const n=await r.requestAutoCaseBounds(e,t.pred,r.autoCaseQuery);return{...t,args:{...t.args,...n}}},Jt=async(t,e,r,n)=>{if("components"in t)throw new d("PRED_COMPONENTS_NOT_ALLOWED","PredItem components is not supported; use a pred array for multiple inputs");const o=r.operators,i={...r.locale?{locale:r.locale}:{},...r.localeRegistry?{localeRegistry:r.localeRegistry}:{}};if(!o)throw new Error("Normalizer operator registry is not initialized");if(t.name!==void 0&&(typeof t.name!="string"||t.name.length===0))throw new d("INVALID_PRED_NAME","PredItem name must be a non-empty string");if(t.name==="_id")throw new d("RESERVED_OUTPUT_NAME","PredItem name _id is reserved for executor-owned row identity");if(t.args!==void 0&&!Cl(t.args))throw new d("INVALID_OPERATOR_ARGS","Pred args must be a plain object");const s=t.schema===void 0||t.schema===e.id?e:r.resolveSchema?.(t.schema);if(!s)throw new d("SCHEMA_RESOLVER_REQUIRED",`Cross-Schema pred requires Schema ${t.schema}`);const a=await n(t.query,s,r),u=Array.isArray(t.pred)?await Promise.all(t.pred.map(m=>Jt(typeof m=="string"?{pred:m}:m,s,r,n))):void 0,{query:c,...p}=t,l={...p,...a?{query:a}:{},...u?{pred:u}:{}},f=async m=>{const y=await Ul(m,s,r),h=y.operator?o.get(y.operator).normalizePred?.({pred:y,schema:s})??y:y;return kl(h)};if(typeof t.pred=="string"){const m=de(s,t.pred,r.resolveSchema),y={...l,pred:m.canonicalName};return f({...y,name:y.name??Pt(y,o,i)})}if(t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)){const m={...l,pred:await Jt(t.pred,s,r,n)};return f({...m,name:m.name??Pt(m,o,i)})}if(u)return f({...l,name:l.name??Pt(l,o,i)});if(t.pred!==void 0)throw new d("UNSUPPORTED_PRED","A pred must be a property name or nested pred");return f({...l,name:l.name??Pt(l,o,i)})},Ml=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),ql=t=>{if(!Se(t))return!1;const e=t;return e.groupby!==void 0||e.preds!==void 0||e.from!==void 0||e.having!==void 0||e.sort!==void 0||e.limit!==void 0||e.limitBy!==void 0||e.page!==void 0},kr=async(t,e)=>{if(Se(t)){if(!e.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");return e.normalizeNestedLogicform(t)}return Array.isArray(t)?Promise.all(t.map(r=>kr(r,e))):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(await Promise.all(Object.entries(t).map(async([r,n])=>[r,await kr(n,e)])))},Rs=(t,e)=>Object.fromEntries(Object.entries(t).map(([r,n])=>(r==="$and"||r==="$or")&&Array.isArray(n)?[r,n.map(o=>Rs(o,e))]:[`${e}_${r}`,n])),io=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},Ns=new Set(["$second","$minute","$hour","$weekday","$day","$week","$month","$quarter","$year"]),so=new Set([...Ns,"$length"]),Ur=t=>Array.isArray(t)?t.some(Ur):typeof t!="object"||t===null||Se(t)?!1:Object.entries(t).some(([e,r])=>so.has(e)||Ur(r)),Os=(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&&!Se(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=>Os(o,e))}else if(r==="$in"||r==="$nin"){if(!Array.isArray(n)||n.some(o=>typeof o!="number"||!Number.isFinite(o)))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}else if(typeof n!="number"||!Number.isFinite(n))throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}return}throw new d("INVALID_QUERY_VALUE",`${e} requires numeric conditions`)}},Mr=(t,e)=>{if(t.schema!==void 0)throw new d("EXPRESSION_QUERY_SCHEMA_NOT_ALLOWED","$expr.pred is scoped to the query Schema and cannot define schema");if(t.query)throw new d("EXPRESSION_QUERY_PRED_QUERY_NOT_ALLOWED","$expr.pred cannot define pred.query");if(t.operator){if(!e.operators)throw new Error("Normalizer operator registry is not initialized");const r=e.operators.get(t.operator);if(r.kind!=="scalar"||!r.toSQL)throw new d("OPERATOR_NOT_ALLOWED_IN_EXPRESSION_QUERY",`Operator ${t.operator} cannot be used in $expr`,{operator:t.operator})}t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)&&Mr(t.pred,e);for(const r of Array.isArray(t.pred)?t.pred:[])typeof r!="string"&&Mr(r,e)},Ts=async(t,e,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))throw new d("INVALID_EXPRESSION_QUERY","$expr must be an object");const n=t,o=Object.keys(n).filter(u=>u!=="pred"&&u!=="condition");if(o.length>0||!Object.prototype.hasOwnProperty.call(n,"condition"))throw new d("INVALID_EXPRESSION_QUERY","$expr must contain exactly pred and condition",{unsupported:o});if(typeof n.pred!="object"||n.pred===null||Array.isArray(n.pred))throw new d("INVALID_EXPRESSION_QUERY","$expr.pred must be a pred expression");const i=n.pred;if(!i.operator)throw new d("EXPRESSION_QUERY_OPERATOR_REQUIRED","$expr.pred must define a scalar operator");if(!r.operators)throw new Error("Normalizer operator registry is not initialized");Mr(i,r);const s=await Jt(i,e,r,()=>Promise.resolve(void 0));Mr(s,r);const a=io(await kr(n.condition,r));return so.has(s.operator)&&Os(a,s.operator),{pred:s,condition:a}},Ps=async(t,e,r,n)=>{if(typeof e!="object"||e===null||Array.isArray(e)||Se(e))return{[t]:e};const o={},i=[];for(const[s,a]of Object.entries(e))so.has(s)?i.push({$expr:await Ts({pred:{operator:s,pred:t},condition:a},r,n)}):(s==="$and"||s==="$or")&&Array.isArray(a)&&a.some(Ur)?i.push({[s]:await Promise.all(a.map(u=>Ps(t,u,r,n)))}):o[s]=a;return Object.keys(o).length>0&&i.unshift({[t]:io(o)}),i.length===1?i[0]??{}:{$and:i}},ao=t=>Array.isArray(t)?t.some(ao):typeof t!="object"||t===null||Se(t)?!1:Object.entries(t).some(([e,r])=>Ns.has(e)||ao(r)),Ls=async(t,e,r,n)=>{const o=c=>{if(Array.isArray(c)){c.forEach(o);return}if(typeof c!="object"||c===null||Se(c))return;const p=c;if("$options"in p)throw new d("UNSUPPORTED_QUERY_OPERATOR","$options is a LogicForm 1.x field; use args.options in LogicForm 2.0");Object.values(p).forEach(o)};if(o(t),r.primal_type!=="date"&&ao(t))throw new d("INVALID_DATE_PART_QUERY",`Date-part query Operators require a date Property: ${r.name}`,{property:r.name});const i=n.semanticTypes.get(r.type),s={schema:e,property:r,now:n.now??new Date,requestTimeWatermark:c=>n.requestTimeWatermark?.(e,r,c)??Promise.resolve(void 0)},a=await Tl(ne(t),s),u=i.normalizeQuery?i.normalizeQuery(a,s):a;if(r.comparable){const c=new Set(r.comparable.values),p=(l,f)=>{if(!(Se(l)||l===null)){if(Array.isArray(l)){l.forEach(m=>p(m,f));return}if(typeof l=="object"){Object.entries(l).forEach(([m,y])=>{["args","$exists","$regex","$contains","$startsWith","$length"].includes(m)||p(y,m)});return}if(!(f&&["$exists","$regex","$contains","$startsWith","$length"].includes(f))&&(typeof l!="string"||!c.has(l)))throw new d("COMPARABLE_VALUE_NOT_FOUND",`Comparable category ${r.name} does not contain value: ${JSON.stringify(l)}`,{property:r.name,value:l})}};p(u)}return u},co=async(t,e,r)=>{const n={},o=[],i=[],s=a=>{const u=Object.entries(a);if(u.length===1&&u[0]?.[0]==="$and"&&Array.isArray(u[0][1]))for(const c of u[0][1])s(c);else u.length===1&&u[0]?.[0]==="$expr"?o.push(a):u.every(([c])=>!c.startsWith("$"))?Object.assign(n,a):i.push(a)};for(const[a,u]of Object.entries(t)){if(a==="$and"||a==="$or"){if(!Array.isArray(u))throw new d("INVALID_QUERY_VALUE",`${a} requires an array`);n[a]=await Promise.all(u.map(async m=>{if(typeof m!="object"||m===null||Array.isArray(m))throw new d("INVALID_QUERY_VALUE",`${a} items must be query objects`);return co(m,e,r)}));continue}if(a==="$expr"){o.push({$expr:await Ts(u,e,r)});continue}const c=de(e,a,r.resolveSchema);if(ql(u)&&(c.property.primal_type==="entity"||c.property.primal_type==="object")&&c.property.ref){if(u.schema!==c.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${c.canonicalName} references ${c.property.ref}, not ${u.schema??"undefined"}`);if(!r.normalizeNestedLogicform)throw new d("LOGICFORM_NORMALIZER_UNAVAILABLE","Nested query LogicForm must be normalized through normalizeLogicform");const m=await r.normalizeNestedLogicform(u);n[c.canonicalName]={$in:m};continue}if(Ml(u)){if(u.version!==void 0&&oo(u),c.property.primal_type!=="entity"&&c.property.primal_type!=="object")throw new d("INVALID_RELATION_QUERY",`Relation query ${a} must resolve to an entity property`);if(!c.property.ref)throw new d("INVALID_RELATION_QUERY",`Nested LogicForm query requires an object property: ${c.canonicalName}`);if(u.schema!==c.property.ref)throw new d("RELATION_SCHEMA_MISMATCH",`Relation ${c.canonicalName} references ${c.property.ref}, not ${u.schema}`);const m=r.resolveSchema?.(u.schema);if(!m)throw new d("SCHEMA_RESOLVER_REQUIRED",`Nested relation query requires Schema ${u.schema}`);const y=_s(u.query,u.entity_id,m,r.plugins),h=await co(y,m,r);Object.assign(n,Rs(h,c.canonicalName));continue}if(typeof u=="object"&&u!==null&&!Array.isArray(u)){const m=u,y=Object.entries(m).filter(([h])=>At(h,r.plugins));if(y.length>0){const[h]=y,g=h?At(h[0],r.plugins):void 0;if(g?.validateCondition?.(m),!h||y.length!==1||Object.keys(m).length!==1)throw new d("INVALID_PLUGIN_QUERY","A plugin Query Operator cannot be combined with other field operators");const[A,w]=h;if(!g)throw new Error(`Query Operator disappeared: ${A}`);n[c.canonicalName]={[A]:await g.normalize(w,{schema:c.schema,property:c.property,...r.resolveSchema?{resolveSchema:r.resolveSchema}:{},normalizeValue:(S,E,$)=>Ls(S,E,$,r)})};continue}}const p=await kr(u,r),l=await Ls(p,c.schema,c.property,r),f=io(l);if(Ur(f)){s(await Ps(c.canonicalName,f,e,r));continue}n[c.canonicalName]=f}if(i.length>0){const a=Array.isArray(n.$and)?n.$and:[];n.$and=[...a,...i]}if(o.length===1)n.$expr=o[0]?.$expr;else if(o.length>1){const a=Array.isArray(n.$and)?n.$and:[];n.$and=[...a,...o]}return n},Ds=async(t,e,r)=>{if(!t)return;const n=await co(t,e,r);return Object.keys(n).length===0?void 0:n},Cs=(t,e,r)=>Promise.all((t??[]).map(n=>Jt(n,e,r,Ds))),jl=(t,e,r)=>Cs(t??[],e,r),Lt=(t,e)=>{throw new d("INVALID_PAGINATION",t,e)},xl=t=>{"skip"in t&&Lt("skip has been removed; use the 1-based page field",{skip:t.skip});const e=t.groupby?.length??0;t.limitBy!==void 0&&((!Number.isInteger(t.limitBy)||t.limitBy<=0)&&Lt("limitBy must be a positive integer",{limitBy:t.limitBy}),e<2&&(t.limit=t.limitBy,delete t.limitBy));const{limit:r,page:n}=t;if(r===void 0){n!==void 0&&Lt("page requires limit",{page:n});return}if((!Number.isFinite(r)||r<0&&r!==-1||r>1&&!Number.isInteger(r))&&Lt("limit must be -1, a non-negative integer, or a ratio between 0 and 1",{limit:r}),r===-1){n!==void 0&&Lt("page cannot be used with unlimited results",{limit:r,page:n}),delete t.limit;return}n!==void 0&&(!Number.isInteger(n)||n<1)&&Lt("page must be a positive integer starting from 1",{page:n}),t.page=n??1},Bl=t=>t.property.name,ks=(t,e,r,n,o=new Set)=>{if(o.has(t.id))return;const i=new Set(o).add(t.id),s=t.properties.find(a=>a.id===e||a.name===e);if(s)return s.name;if(n==="timestamp"){const a=t.properties.find(u=>u.type==="timestamp");if(a)return a.name}for(const a of t.properties){if(!a.ref||a.primal_type!=="entity"&&a.primal_type!=="object")continue;const u=r?.(a.ref);if(!u)continue;const c=ks(u,e,r,n,i);if(c)return`${a.name}_${c}`}},Us=(t,e,r,n)=>{try{const o=de(t,e,n);return ks(r,Bl(o),n,o.property.type)}catch{return}},uo=t=>[...typeof t.pred=="string"?[t.pred]:t.pred&&!Array.isArray(t.pred)?uo(t.pred):[],...Array.isArray(t.pred)?t.pred.flatMap(e=>typeof e=="string"?[e]:uo(e)):[]],Ms=t=>t?Object.entries(t).flatMap(([e,r])=>{if((e==="$and"||e==="$or")&&Array.isArray(r))return r.flatMap(n=>Ms(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)?uo(n):[]}return e.startsWith("$")?[]:[e]}):[],Vl=(t,e,r)=>{const n=[...new Set((t.preds??[]).map(s=>s.schema).filter(s=>!!(s&&s!==e.id)))];if(n.length===0)return t;const o={};for(const[s,a]of Object.entries(t.propertyResolve??{})){const u=r.resolveSchema?.(s),c={};for(const[p,l]of Object.entries(a))try{const f=de(e,p,r.resolveSchema),m=u?de(u,l,r.resolveSchema):void 0;c[f.canonicalName]=m?.canonicalName??l}catch{c[p]=l}o[s]=c}const i=[...(t.groupby??[]).map(s=>s.pred),...Ms(t.query)];for(const s of i){if(typeof s!="string")continue;let a;try{a=de(e,s,r.resolveSchema)}catch{continue}for(const u of n){const c=r.resolveSchema?.(u),p=c&&Us(e,s,c,r.resolveSchema);p&&p!==a.canonicalName&&(o[u]={...o[u]??{},[a.canonicalName]:p})}}return Object.keys(o).length>0?{...t,propertyResolve:o}:t},vl=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`)}}},Fl=async(t,e,r)=>{if(!t)return;const n=fs(t,e,r);return st(t,n,r)},st=async(t,e,r)=>{if(r={...r,...r.localeRegistry?{localeRegistry:r.localeRegistry}:{localeRegistry:lr([...me(r.plugins).flatMap(h=>h.locales??[]),...r.locales===void 0?[]:"locale"in r.locales?[r.locales]:r.locales])},...r.operators?{}:{operators:Le(r.plugins)}},oo(t),vl(t.propertyResolve),t.output&&t.output.type!=="data"&&t.output.type!=="sql"&&!mi(t.output.type,r.plugins))throw new d("UNSUPPORTED_OUTPUT",`Output type is not supported: ${t.output.type}`);const o=ne(t),i={...r,normalizeNestedLogicform:async h=>{const g=fs(h,e,r);return st(h,g,r)}};xl(o);const s=await Fl(o.from,e,i),a=s&&r.resolveFromSchema?r.resolveFromSchema(s,e):e,u=await Ds(_s(o.query,o.entity_id,a,r.plugins),a,i),c=o.preds===void 0&&o.groupby===void 0?a.properties.filter(h=>r.canProjectProperty?.(a,h)??!0).map(h=>({pred:h.name,name:h.name})):o.preds,p={...i,...u?{autoCaseQuery:u}:{}};let l=await Cs(c,a,p),f=await jl(o.groupby,a,p);const m=f.filter(h=>ri(h,f,a,r.resolveSchema));if(m.length>0){const h=new Set(m.map(({name:g})=>g));f=f.filter(({name:g})=>!h.has(g)),l=[...l,...m]}return o.preds=l,f.length>0?o.groupby=f:delete o.groupby,s?o.from=s:delete o.from,u?o.query=u:delete o.query,Vl(o,a,i)},qs=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Fe=(t,e)=>{if(t){if(!qs(t,e))throw new d("TABLE_PERMISSION_DENIED",`Schema is not included in the table permissions: ${e}`,{schemaId:e});return t[e]}},at=(t,e,r)=>{const n=Fe(t,e)?.columnPermissions?.whitelist;return!n||n.includes(r.name)||n.includes(r.id)},Xt=(t,e,r)=>{if(!at(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})},lo=(t,e,r,n)=>{const o=de(e,t,n);for(const i of o.relations)Fe(r,i.targetSchema.id),Xt(r,i.sourceSchema,i.property);Xt(r,o.schema,o.property)},js=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.schema=="string"&&typeof t.query=="object"&&t.query!==null&&!Array.isArray(t.query),qr=(t,e,r,n)=>{if(Se(t)){xr(t,e,r,n);return}if(Array.isArray(t)){for(const o of t)qr(o,e,r,n);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const o of Object.values(t))qr(o,e,r,n)};function Zt(t,e,r,n,o){const i=t.schema?n(t.schema):e;t.schema&&Fe(r,t.schema),typeof t.pred=="string"?lo(t.pred,i,r,n):t.pred&&!Array.isArray(t.pred)&&Zt(t.pred,i,r,n,o);for(const s of Array.isArray(t.pred)?t.pred:[])typeof s=="string"?lo(s,i,r,n):Zt(s,i,r,n,o);jr(t.query,i,r,n,o)}const jr=(t,e,r,n,o)=>{if(t)for(const[i,s]of Object.entries(t)){if(i==="$and"||i==="$or"){if(Array.isArray(s))for(const u of s)jr(u,e,r,n,o);continue}if(i==="$expr"){if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const u=s.pred;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Zt(u,e,r,n,o),qr(s.condition,r,n,o)}continue}const a=de(e,i,n);if(lo(i,e,r,n),typeof s=="object"&&s!==null&&!Array.isArray(s))for(const[u,c]of Object.entries(s))At(u,o)?.authorize?.(c,{schema:a.schema,property:a.property,resolveSchema:n,assertSchemaAllowed:p=>{Fe(r,p)},assertPropertyAllowed:(p,l)=>Xt(r,p,l),hasRowPermissions:p=>Fe(r,p)?.rowPermissions!==void 0});if(js(s)){if(a.property.ref!==s.schema)continue;const u=n(s.schema);Fe(r,u.id),yn(s.entity_id)&&Xt(r,u,hn(u,o)),jr(s.query,u,r,n,o);continue}qr(s,r,n,o)}},xr=(t,e,r,n=[])=>{if(!t.schema){if(t.from){xr(t.from,e,r,n);return}throw new d("LOGICFORM_SCHEMA_REQUIRED","A physical LogicForm must define schema")}const o=r(t.schema);if(Fe(e,o.id),yn(t.entity_id)&&Xt(e,o,hn(o,n)),t.from){xr(t.from,e,r,n);return}jr(t.query,o,e,r,n);for(const i of t.preds??[])Zt(i,o,e,r,n);for(const i of t.groupby??[])Zt(i,o,e,r,n)},Br=(t,e)=>{if(Array.isArray(t))return t.map(o=>Br(o,e));if(typeof t!="object"||t===null||t instanceof Date)return t;const r=Object.entries(t).map(([o,i])=>[o,Br(i,e)]),n=Object.fromEntries(r);return js(t)&&!qs(t,"version")&&(n.version=e),n},Yl=(t,e,r)=>{const n=[],o=(s,a)=>{if(s)for(const[u,c]of Object.entries(s))if((u==="$and"||u==="$or")&&Array.isArray(c))for(const p of c)o(p,a);else if(u==="$expr"&&typeof c=="object"&&c!==null&&!Array.isArray(c)){const p=c.pred;typeof p=="object"&&p!==null&&!Array.isArray(p)&&i(p,a)}else u.startsWith("$")||n.push(de(a,u,r))},i=(s,a)=>{const u=s.schema?r(s.schema):a;typeof s.pred=="string"?n.push(de(u,s.pred,r)):s.pred&&!Array.isArray(s.pred)&&i(s.pred,u);for(const c of Array.isArray(s.pred)?s.pred:[])typeof c=="string"?n.push(de(u,c,r)):i(c,u);o(s.query,u)};o(t.query,e);for(const s of t.preds??[])i(s,e);for(const s of t.groupby??[])i(s,e);return n},Hl=(t,e,r)=>{if(!t.schema)return[];const n=r(t.schema),o=new Set,i=[];for(const s of Yl(t,n,r)){if(s.relations.length===0)continue;let a=-1;if(s.relations.forEach(({targetSchema:l},f)=>{e[l.id]?.rowPermissions!==void 0&&(a=f)}),a<0)continue;const u=s.relations.slice(0,a+1),c=u.map(({property:l})=>l.name).join("_");if(o.has(c))continue;o.add(c);let p={};for(const l of[...u].reverse())p={[l.property.name]:{schema:l.targetSchema.id,query:p}};i.push(p)}return i},Dt=(t,e,r,n,o,i)=>Se(t)?ct(t,e,r,n,o,i):Array.isArray(t)?t.map(s=>Dt(s,e,r,n,o,i)):typeof t!="object"||t===null||t instanceof Date?t:Object.fromEntries(Object.entries(t).map(([s,a])=>[s,Dt(a,e,r,n,o,i)])),po=(t,e,r,n,o,i)=>({...t,...t.query?{query:Dt(t.query,e,r,n,o,i)}:{},...t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?{pred:po(t.pred,e,r,n,o,i)}:{},...Array.isArray(t.pred)?{pred:t.pred.map(s=>typeof s=="string"?s:po(s,e,r,n,o,i))}:{}}),ct=(t,e,r,n=!0,o=new Set,i=[])=>{if(!e)return ne(t);if(!t.schema){const m=ne(t);return m.from&&(m.from=ct(m.from,e,r,n,new Set,i)),m}n&&xr(t,e,r,i);const s=Fe(e,t.schema),a=o.has(t.schema),u=new Set(o).add(t.schema),c=ne(t);c.query&&(c.query=Dt(c.query,e,r,n,new Set,i)),c.preds&&(c.preds=c.preds.map(m=>po(m,e,r,n,new Set,i))),c.from&&(c.from=ct(c.from,e,r,n,new Set,i));const p=a||t.from?void 0:s?.rowPermissions,l=(t.from?[]:Hl(t,e,r)).map(m=>Dt(Br(m,t.version),e,r,!1,u,i));p&&l.push(Dt(Br(ne(p),t.version),e,r,!1,u,i));const f=[c.query,...l].filter(m=>m!==void 0&&Object.keys(m).length>0);return f.length===1?c.query=f[0]:f.length>1?c.query={$and:f}:delete c.query,c},Ql=(t,e)=>{if(t)for(const[r,n]of Object.entries(t)){const o=e(r),i=n.columnPermissions?.whitelist;if(i&&(!Array.isArray(i)||i.some(s=>typeof s!="string")))throw new d("INVALID_COLUMN_PERMISSIONS",`Column permissions whitelist must be an array of strings: ${r}`,{schemaId:r});for(const s of i??[])if(!o.properties.some(({id:a,name:u})=>a===s||u===s))throw new d("INVALID_COLUMN_PERMISSION",`Column permission property not found: ${r}.${s}`,{schemaId:r,property:s})}},xs=(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")}},Bs=(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=xs(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)},Gl=(t,e)=>{const r=Ui(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=xs(e,t.timeZone);let o=Bs({...n,...r},t.timeZone);if(o.getTime()<=e.getTime()){const i=new Date(Date.UTC(n.year,n.month-1,n.day+1));o=Bs({year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),...r},t.timeZone)}return o},Wl=(t,e)=>{const r=t.flatMap(n=>n.mode==="manual"?[]:n.mode==="ttl"?[new Date(e.getTime()+n.ttlSeconds*1e3)]:[Gl(n,e)]);return r.length===0?void 0:new Date(Math.min(...r.map(n=>n.getTime())))},fo=(t,e)=>e.findSource(t.schemaId,t.mappingSource??t.source,t.connectionId),er=(t,e,r)=>{if(Et(t)){e.push(t.plan);return}if(Li(t)){for(const n of t.sources??[])r.set(`${n.schemaId}:${n.connectionId??""}:${n.source}`,n);return}if(Array.isArray(t)){for(const n of t)er(n,e,r);return}if(!(typeof t!="object"||t===null||t instanceof Date))for(const n of Object.values(t))er(n,e,r)},tr=(t,e,r)=>{if(t.kind==="window"){tr(t.input,e,r);for(const n of t.partitionBy)tr(n,e,r);return}if(t.kind==="operator"){er(t.query,e,r),t.input&&tr(t.input,e,r);for(const n of t.inputs??[])tr(n,e,r)}},Ae=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 Ae(o))r(i);else if(t.sourcePlan)for(const o of Ae(t.sourcePlan))r(o);else t.source&&r({schemaId:t.schemaId,source:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});for(const o of t.joins??[])r({schemaId:o.targetSchemaId,source:o.targetSource,...o.targetConnectionId?{connectionId:o.targetConnectionId}:{}});for(const o of t.enrichmentJoins??[])r({schemaId:t.schemaId,source:o.source,mappingSource:t.source,...t.connectionId?{connectionId:t.connectionId}:{}});const n=[];er(t.query,n,e),er(t.having,n,e);for(const o of t.projections)tr(o.expression,n,e);for(const o of n)for(const i of Ae(o))r(i);return[...e.values()]},rr=t=>{const e=new Map;for(const r of t.flat())e.set(`${r.schemaId}:${r.connectionId??""}:${r.mappingSource??""}:${r.source}`,r);return[...e.values()]},Vs=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})}},zl=(t,e)=>{const r=[];for(const n of t){const o=fo(n,e),i=n.mappingSource?o?.enrichments?.find(({source:s})=>s===n.source)?.freshness:o?.freshness;if(!i)return;r.push(i)}return r},Re=async(t,e,r)=>{t=vs(t),r.signal?.throwIfAborted();const n=r.cache?zl(e,r.schemaMappings):void 0;if(!r.cache||!n)return Vs(r.provider,{...t,...r.signal?{signal:r.signal}:{}});const o={namespace:r.cache.namespace,provider:r.provider.kind,...r.connectionId?{connectionId:r.connectionId}:{},sql:t.sql,parameters:t.parameters};try{const s=await r.cache.store.get(o);if(r.signal?.throwIfAborted(),s)return[...s]}catch{r.signal?.throwIfAborted()}const i=await Vs(r.provider,{...t,...r.signal?{signal:r.signal}:{}});try{const s=Wl(n,new Date);await r.cache.store.set(o,i,{sources:[...new Set(e.map(({source:a})=>a))],...s?{expiresAt:s}:{}})}catch{}return i},vs=t=>({...t,sql:el(t.sql)}),Kl=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")},Jl=(t,e,r)=>{const n=Kl(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}},Fs=async(t,e)=>{if(!at(e.permissions,t.schema.id,t.idProperty))throw new d("COLUMN_PERMISSION_DENIED",`Entity hydration requires the ID property in the column permissions: ${t.schema.id}.${t.idProperty.name}`,{schemaId:t.schema.id,property:t.idProperty.name});const r=t.schema.properties.filter(h=>at(e.permissions,t.schema.id,h)),n=e.schemaMappings.list(t.schema.id),o=n.find(({connectionId:h})=>h===e.preferredConnectionId)?.connectionId??n[0]?.connectionId,i=o&&e.providerForConnection?e.providerForConnection(o):e.provider,s={version:e.version,schema:t.schema.id,query:Jl(t.idProperty.name,t.ids,i.maxInListItems),preds:r.map(h=>({pred:h.name,name:h.name}))},a=ct(s,e.permissions,e.resolveSchema,!0,new Set,e.plugins),u=await st(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=Oe(u,t.schema,e.operators,e.schemaMappings,{resolveSchema:e.resolveSchema,...o?{preferredConnectionId:o}:{},canUsePropertyRowIdentity:(h,g)=>at(e.permissions,h.id,g)}),p=new Set(Ae(c).map(h=>e.schemaMappings.findSource(h.schemaId,h.source,h.connectionId)?.connectionId).filter(h=>!!h));if(p.size>1)throw new d("CROSS_CONNECTION_ENTITY_HYDRATION_UNSUPPORTED",`Entity hydration cannot span connections: ${[...p].join(", ")}`);const l=[...p][0]??o,f=l&&e.providerForConnection?e.providerForConnection(l):i,m=he(c,f,e.operators);e.onCompiled?.(m,u,f,l);const y=await Re(m,Ae(c),{provider:f,...l?{connectionId:l}:{},schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}});return zn(y,c.rowIdentity)},Ys=t=>String(t),Xl=(t,e,r)=>{const n=`\u6570\u636E\u5E93\u4E2D\u672A\u627E\u5230 ID \u4E3A\u300C${Ys(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=Ys(r),o},Hs=(t,e)=>`${t}:${String(e)}`,Zl=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 ep{#e;#t=new Map;#r=new Map;#n=new Map;#o=!1;constructor(e){this.#e=e}load=(e,r)=>{const n=Hs(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(yi(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=Zl(s);let u,c;const p=new Promise((f,m)=>{u=f,c=m}),l=this.#n.get(e)??{schema:s,idProperty:a,loads:new Map};return l.loads.set(n,{id:r,resolve:f=>u?.(f),reject:f=>c?.(f)}),this.#n.set(e,l),this.#r.set(n,p),this.#s(),p};#s(){this.#o||(this.#o=!0,queueMicrotask(()=>{this.#i()}))}async#i(){this.#o=!1;const e=this.#n;this.#n=new Map,await Promise.all([...e.values()].map(r=>this.#a(r)))}async#a(e){const r={schema:e.schema,idProperty:e.idProperty,ids:[...e.loads.values()].map(({id:n})=>n)};try{const n=await this.#e.fetchEntities(r),o=new Map;for(const i of n){const s=i[e.idProperty.name]??i._id;if(s!=null){const a=typeof s=="string"?s:typeof s=="number"||typeof s=="boolean"||typeof s=="bigint"?String(s):JSON.stringify(s),u=i._id===a?i:{...i,_id:a};o.set(Hs(e.schema.id,s),u)}}for(const[i,s]of e.loads){const a=o.get(i)??Xl(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 tp=(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})}},rp=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=tp(o[i.name],i),a=r.get(i.type).hydrateResult;if(!a){o[i.name]=s;return}o[i.name]=i.isArray&&Array.isArray(s)?await Promise.all(s.map(u=>a(u,{property:i,requestEntity:n}))):await a(s,{property:i,requestEntity:n})}))}))},Qs=5,np=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof Date),op=(t,e)=>{const r=e.properties.find(({type:n})=>n==="ID");return r?t[r.name]:void 0},ip=(t,e)=>{const r=wa(e);t._title=t[r.name]??t._id},sp=(t,e)=>{const r=structuredClone(t);if(!("_id"in r)){const n=op(r,e);(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(r._id=String(n))}return r},ap=(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})},cp=async(t,e,r)=>{const n=new ep(r);let o=[{rows:t,properties:e,expandEntities:!0}];for(let i=0;o.length>0;i+=1){await Promise.all(o.map(a=>{const u=a.expandEntities&&i<Qs;return rp(a.rows,a.properties,r.semanticTypes,u?n.load:(c,p)=>Promise.resolve(p))}));for(const a of o)if(a.schema)for(const u of a.rows)ip(u,a.schema);if(i>=Qs)return;const s=new Map;for(const a of o)if(a.expandEntities)for(const u of a.properties){if(u.primal_type!=="entity"&&u.primal_type!=="object"||!u.ref)continue;const c=r.resolveSchema(u.ref);for(const p of a.rows){if(!(u.name in p))continue;const l=p[u.name],f=u.isArray?Array.isArray(l)?l:[l]:[l];for(const[m,y]of f.entries()){if(!np(y))continue;const h=sp(y,c);u.isArray?f[m]=h:p[u.name]=h,ap(s,c,h,!u.isArray)}u.isArray&&(p[u.name]=f)}}o=[...s.values()]}},Gs=async(t,e,r)=>{const n=t.map(o=>({...o}));return await cp(n,e,r),n},mo=t=>`'${t.replaceAll("'","''")}'`,Ws=t=>{const e=[["\\","\\\\"],["\0","\\0"],["\b","\\b"],[" ","\\t"],[`
|
|
4
|
+
`,"\\n"],["\r","\\r"],["","\\Z"],['"','\\"'],["'","\\'"]];let r=t;for(const[n,o]of e)r=r.replaceAll(n,o);return`'${r}'`},nr=(t,e)=>{if(t==null)return"NULL";if(typeof t=="boolean")return e==="mysql"?t?"true":"false":e==="sqlserver"?t?"1":"0":t?"TRUE":"FALSE";if(typeof t=="number")return String(t);if(typeof t=="bigint")return e==="mysql"||e==="sqlserver"?t.toString():mo(t.toString());if(typeof t=="string")return e==="mysql"?Ws(t):mo(t);if(t instanceof Date){const r=e==="clickhouse"||e==="mysql"?t.toISOString().replace("T"," ").replace("Z",""):t.toISOString();return e==="mysql"?Ws(r):mo(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}`)},up=(t,e)=>t.replace(/\{p(\d+):[^}]+\}/g,(r,n)=>{const o=Number(n);return o in e?nr(e[o],"clickhouse"):r}),dp=(t,e)=>t.replace(/:([1-9]\d*)\b/g,(r,n)=>{const o=Number(n)-1;return o in e?nr(e[o],"oracle"):r}),lp=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="$"){const s=/^\$(\d+)/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a)-1;if(u in e){r+=nr(e[u],"postgresql"),o+=s[0].length-1;continue}}}r+=i}}return r},yo=(t,e,r)=>{let n="",o=0,i;for(let s=0;s<t.length;s+=1){const a=t[s];if(a){if(i){n+=a,a===i&&(t[s+1]===i?(n+=i,s+=1):i=void 0);continue}if(a==="'"||a==='"'||a==="`"){i=a,n+=a;continue}if(a==="?"&&o<e.length){n+=nr(e[o],r),o+=1;continue}n+=a}}return n},pp=(t,e)=>yo(t,e,"mysql"),ho=(t,e)=>yo(t,e,"snowflake"),fp=(t,e)=>yo(t,e,"dameng"),mp=(t,e)=>{let r="",n;for(let o=0;o<t.length;o+=1){const i=t[o];if(i){if(n){r+=i,i===n&&(t[o+1]===n?(r+=n,o+=1):n=void 0);continue}if(i==="'"||i==='"'){n=i,r+=i;continue}if(i==="["){n="]",r+=i;continue}if(i==="@"){const s=/^@p(\d+)\b/.exec(t.slice(o)),a=s?.[1];if(s&&a){const u=Number(a);if(u in e){r+=nr(e[u],"sqlserver"),o+=s[0].length-1;continue}}}r+=i}}return r},Ke=(t,e)=>new Error(`Database driver "${t}" is not installed or could not be loaded. Install it with: npm install ${t}`,{cause:e}),or=t=>{for(const[e,r]of Object.entries({database:t.database,schema:t.schema}))if(r!==void 0&&!r.trim())throw new d("INVALID_TABLE_SCOPE",`Table discovery ${e} must not be empty`)},Te=(t,e)=>{throw new d("UNSUPPORTED_TABLE_SCOPE",`${t.kind} table discovery does not support a ${e} override`)},qe=(t,e)=>Object.entries(t).find(([r])=>r.toLowerCase()===e.toLowerCase())?.[1],Ne=(t,e)=>{const r=qe(t,e);if(typeof r!="string"||!r)throw new d("INVALID_TABLE_METADATA",`Expected a non-empty metadata field: ${e}`);return r},zs=t=>{const e=Ne(t,"table_name"),r=qe(t,"table_database"),n=qe(t,"table_schema"),o=Ne(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"}},yp=t=>t.map(zs),ut=async(t,e)=>{e.signal?.throwIfAborted(),or(e);const r=[],n=u=>{const c=t.parameter(r.length,u);return r.push(u),c},o=e.database,i=e.schema;let s;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":i!==void 0&&Te(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&&Te(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&&Te(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&&Te(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(),yp(a)},go=t=>{if(or(t),!t.table.trim())throw new d("INVALID_TABLE_NAME","Table name must not be empty")},Vr=(t,e)=>{const r=qe(t,e);return typeof r=="string"?r:""},hp=t=>{const e=Ne(t,"column_type"),r=qe(t,"type_length"),n=qe(t,"type_precision"),o=qe(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},Ks=t=>{const e=qe(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:Ne(t,"column_name"),type:hp(t),comment:Vr(t,"column_comment"),...r!==void 0?{primaryKey:r}:{}}},gp=(t,e)=>{const r=[],n=c=>{const p=t.parameter(r.length,c);return r.push(c),p},o=n(e.table),{database:i,schema:s}=e;let a,u;switch(t.kind){case"mysql":case"doris":case"gbase":case"starrocks":{s!==void 0&&Te(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&&Te(t,"database");const c=`c.relname = ${o} AND n.nspname = ${s!==void 0?n(s):"current_schema()"}`;a=`SELECT c.relname AS table_name, current_database() AS table_database, n.nspname AS table_schema, CASE WHEN c.relkind IN ('v', 'm') THEN 'VIEW' ELSE 'TABLE' END AS table_type, obj_description(c.oid, 'pg_class') AS table_comment FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE ${c} AND c.relkind IN ('r', 'v', 'm', 'p', 'f')`,u=`SELECT a.attname AS column_name, format_type(a.atttypid, a.atttypmod) AS column_type, col_description(c.oid, a.attnum) AS column_comment, EXISTS (SELECT 1 FROM pg_catalog.pg_index i WHERE i.indrelid = c.oid AND i.indisprimary AND a.attnum = ANY(i.indkey)) AS is_primary_key FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE ${c} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`;break}case"sqlserver":{const c=i!==void 0?`${t.quoteIdentifier(i)}.`:"",p=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"SCHEMA_NAME()"}`,l=`JOIN ${c}sys.schemas s ON s.name = c.TABLE_SCHEMA JOIN ${c}sys.objects o ON o.schema_id = s.schema_id AND o.name = c.TABLE_NAME `;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_CATALOG AS table_database, c.TABLE_SCHEMA AS table_schema, c.TABLE_TYPE AS table_type, CAST(ep.value AS nvarchar(max)) AS table_comment FROM ${c}INFORMATION_SCHEMA.TABLES c ${l}LEFT JOIN ${c}sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id AND ep.minor_id = 0 AND ep.name = 'MS_Description' WHERE ${p}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, c.CHARACTER_MAXIMUM_LENGTH AS type_length, c.NUMERIC_PRECISION AS type_precision, c.NUMERIC_SCALE AS type_scale, CAST(ep.value AS nvarchar(max)) AS column_comment, CASE WHEN EXISTS (SELECT 1 FROM ${c}sys.indexes i JOIN ${c}sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id WHERE i.object_id = o.object_id AND i.is_primary_key = 1 AND ic.key_ordinal > 0 AND ic.column_id = sc.column_id) THEN 1 ELSE 0 END AS is_primary_key FROM ${c}INFORMATION_SCHEMA.COLUMNS c ${l}JOIN ${c}sys.columns sc ON sc.object_id = o.object_id AND sc.name = c.COLUMN_NAME LEFT JOIN ${c}sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id AND ep.minor_id = sc.column_id AND ep.name = 'MS_Description' WHERE ${p} ORDER BY c.ORDINAL_POSITION`;break}case"snowflake":{const c=`${i!==void 0?`${t.quoteIdentifier(i)}.`:""}INFORMATION_SCHEMA`,p=`c.TABLE_NAME = ${o} AND c.TABLE_SCHEMA = ${s!==void 0?n(s):"CURRENT_SCHEMA()"}`;a=`SELECT c.TABLE_NAME AS table_name, c.TABLE_CATALOG AS table_database, c.TABLE_SCHEMA AS table_schema, c.TABLE_TYPE AS table_type, c.COMMENT AS table_comment FROM ${c}.TABLES c WHERE ${p}`,u=`SELECT c.COLUMN_NAME AS column_name, c.DATA_TYPE AS column_type, c.COMMENT AS column_comment, c.CHARACTER_MAXIMUM_LENGTH AS type_length, c.NUMERIC_PRECISION AS type_precision, c.NUMERIC_SCALE AS type_scale FROM ${c}.COLUMNS c WHERE ${p} ORDER BY c.ORDINAL_POSITION`;break}case"oracle":case"dameng":{i!==void 0&&Te(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&&Te(t,"schema");const c=i!==void 0?n(i):"currentDatabase()";a=`SELECT c.name AS table_name, c.database AS table_database, c.comment AS table_comment, if(c.engine IN ('View', 'MaterializedView', 'LiveView', 'WindowView'), 'VIEW', 'TABLE') AS table_type FROM system.tables c WHERE c.name = ${o} AND c.database = ${c}`,u=`SELECT c.name AS column_name, c.type AS column_type, c.comment AS column_comment, c.is_in_primary_key AS is_primary_key FROM system.columns c WHERE c.table = ${o} AND c.database = ${c} ORDER BY c.position`;break}default:throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`No table description SQL for provider: ${t.kind}`)}return{tableSql:a,columnSql:u,parameters:r}},Js=(t,e)=>{const r=[];return!["postgresql","oracle","dameng"].includes(t.kind)&&e.database!==void 0&&r.push(e.database),e.schema!==void 0&&r.push(e.schema),r.push(e.name),r.map(n=>t.quoteIdentifier(n)).join(".")},Ct=async(t,e,r,n=[])=>{e.signal?.throwIfAborted();const o=await t.execute({sql:r,parameters:n,...e.signal?{signal:e.signal}:{}});return e.signal?.throwIfAborted(),o},$o=async(t,e,r)=>{if(e.includeSample===!1)return r;const n=Js(t,r.tableInfo),o=t.kind==="sqlserver"?`SELECT TOP (1) * FROM ${n}`:["oracle","dameng"].includes(t.kind)?`SELECT * FROM ${n} FETCH FIRST 1 ROWS ONLY`:`SELECT * FROM ${n} LIMIT 1`;let i;try{[i]=await Ct(t,e,o)}catch{return e.signal?.throwIfAborted(),r}return i?{...r,columns:r.columns.map(s=>({...s,...Object.hasOwn(i,s.name)?{exampleValue:i[s.name]}:{}}))}:r},$p=async(t,e)=>{let{database:r,schema:n}=e;if(r===void 0||n===void 0){const[l]=await Ct(t,e,"SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!l)throw new d("INVALID_TABLE_METADATA","Databricks current namespace was not returned");r??=Ne(l,"table_database"),n??=Ne(l,"table_schema")}const o=Js(t,{name:e.table,database:r,schema:n}),i=await Ct(t,e,`DESCRIBE TABLE EXTENDED ${o}`),s=[];let a=!0,u=!1,c="",p="table";for(const l of i){const f=qe(l,"col_name"),m=qe(l,"data_type"),y=(f==="# Partition Information"||f==="# Detailed Table Information")&&!m;(f===""||y)&&(a=!1),y&&f==="# Detailed Table Information"&&(u=!0),a?s.push({name:Ne(l,"col_name"),type:Ne(l,"data_type"),comment:Vr(l,"comment")}):u&&f==="Comment"?c=Vr(l,"data_type"):u&&f==="Type"&&m==="VIEW"&&(p="view")}if(!s.length)throw new d("INVALID_TABLE_METADATA","Databricks description did not contain columns");return $o(t,e,{columns:s,tableInfo:{name:e.table,database:r,schema:n,type:p,comment:c}})},Ap=async(t,e)=>{e.database!==void 0&&Te(t,"database"),e.schema!==void 0&&Te(t,"schema");const n=(await Ct(t,e,`DESC ${t.quoteIdentifier(e.table)}`)).map(Ks);if(!n.length)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);return $o(t,e,{columns:n,tableInfo:{name:e.table,type:"table",comment:""}})},Ye=async(t,e)=>{if(e.signal?.throwIfAborted(),go(e),t.kind==="databricks")return $p(t,e);if(t.kind==="maxcompute")return Ap(t,e);const{tableSql:r,columnSql:n,parameters:o}=gp(t,e),i=await Ct(t,e,r,o),[s]=i;if(!s)throw new d("TABLE_NOT_FOUND",`Table was not found or is not accessible: ${e.table}`);if(i.length!==1)throw new d("AMBIGUOUS_TABLE",`More than one table matched: ${e.table}`);const a={...zs(s),comment:Vr(s,"table_comment")},u=(await Ct(t,e,n,o)).map(Ks);return $o(t,e,{columns:u,tableInfo:a})},wp=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}`},Ep=t=>t===null?"Nullable(String)":typeof t=="boolean"?"Bool":typeof t=="number"?"Float64":t instanceof Date?"DateTime64(3)":"String",Xs=t=>t instanceof Date?t.toISOString().replace("T"," ").replace("Z",""):t;class _p{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 Ke("@clickhouse/client",r)});return e({url:wp(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}:${Ep(r)}}`}displayQuery(e,r){return up(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}`,Xs(i)]));return(await r.query({query:e.sql,format:"JSONEachRow",query_params:n,...e.signal?{abort_signal:e.signal}:{}})).json()}getTableList(e){return ut(this,e)}describeTable(e){return Ye(this,e)}async runSQL(e){e.signal?.throwIfAborted();const r=await this.#r();if(e.signal?.throwIfAborted(),!r.exec)throw new d("UNSUPPORTED_RAW_SQL","ClickHouse native SQL requires client.exec");const n=await r.exec({query:e.sql,query_params:Object.fromEntries(e.parameters.map((a,u)=>[`p${u}`,Xs(a)])),clickhouse_settings:{default_format:"JSONEachRow"},...e.signal?{abort_signal:e.signal}:{}}),o=[];for await(const a of n.stream)e.signal?.throwIfAborted(),o.push(Buffer.isBuffer(a)?a:Buffer.from(a));e.signal?.throwIfAborted();const i=Buffer.concat(o).toString("utf8").trim();return{rows:i?i.split(`
|
|
5
|
+
`).map(a=>{const u=JSON.parse(a);if(typeof u!="object"||u===null||Array.isArray(u))throw new Error("ClickHouse provider expected object rows");return u}):[]}}async close(){const e=this.#t;if(!e)return;await(await e).close(),this.#t=void 0}}const Sp=t=>[".azuredatabricks.net",".databricks.azure.cn",".databricks.azure.us"].some(e=>t.toLowerCase().replace(/^https?:\/\//,"").split("/")[0]?.endsWith(e)),Ip=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??(Sp(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)}`)},bp=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 Rp{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 Ke("@databricks/sql",r)})).DBSQLClient;if(this.#e)try{await e.connect(Ip(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 ho(e,r)}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Databricks date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${e})`}datePart(e,r){const n={second:"SECOND",minute:"MINUTE",hour:"HOUR",day:"DAYOFMONTH",week:"WEEKOFYEAR",month:"MONTH",quarter:"QUARTER",year:"YEAR"};return r==="weekday"?`(WEEKDAY(${e}) + 1)`:`${n[r]}(${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported Databricks date shift: ${r}/${n}`);return`TIMESTAMPADD(${r.toUpperCase()}, ${n}, ${e})`}castValue(e,r){return r==="timestamp"?`CAST(${e} AS TIMESTAMP)`:r==="date"?`CAST(${e} AS DATE)`:e}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Databricks aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS STRING)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Databricks regex options: ${n}`);return`${e} RLIKE ${n==="i"?`CONCAT('(?i)', ${r})`:r}`}arrayContains(e,r){return`ARRAY_CONTAINS(${e}, ${r})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`LATERAL VIEW EXPLODE(${e}) ${o} AS ${i}`,valueExpression:`${o}.${i}`}}async execute(e){e.signal?.throwIfAborted();const r=await this.#n();e.signal?.throwIfAborted();const n=this.#e?.schema??this.#e?.database,o=await r.openSession({...this.#e?.catalog?{initialCatalog:this.#e.catalog}:{},...n?{initialSchema:n}:{}});let i;const s=()=>{i&&i.cancel().catch(()=>{})};e.signal?.addEventListener("abort",s,{once:!0});try{e.signal?.throwIfAborted(),i=await o.executeStatement(e.sql,{ordinalParameters:e.parameters.map(bp)}),e.signal?.aborted&&s(),e.signal?.throwIfAborted(),await i.finished?.(),e.signal?.throwIfAborted();const a=await i.fetchAll();if(e.signal?.throwIfAborted(),!Array.isArray(a))throw new Error("Databricks provider expected an array result");return a}finally{e.signal?.removeEventListener("abort",s);try{i&&await i.close()}finally{await o.close()}}}async runSQL(e){return{rows:await this.execute(e)}}describeTable(e){const r=e.database??this.#e?.catalog,n=e.schema??this.#e?.schema??this.#e?.database;return Ye(this,{...e,...r!==void 0?{database:r}:{},...n!==void 0?{schema:n}:{}})}async getTableList(e){e.signal?.throwIfAborted(),or(e);const r=c=>this.execute({sql:c,parameters:[],...e.signal?{signal:e.signal}:{}});let n=e.database??this.#e?.catalog,o=e.schema??this.#e?.schema??this.#e?.database;if(n===void 0||o===void 0){const[c]=await r("SELECT current_catalog() AS table_database, current_schema() AS table_schema");if(!c)throw new Error("Databricks current namespace was not returned");n??=Ne(c,"table_database"),o??=Ne(c,"table_schema")}const i=`${this.quoteIdentifier(n)}.${this.quoteIdentifier(o)}`,s=await r(`SHOW TABLES IN ${i}`),a=await r(`SHOW VIEWS IN ${i}`),u=new Map;for(const c of s){const p=Ne(c,"tableName");u.set(p,{name:p,database:n,schema:o,type:"table"})}for(const c of a){const p=Ne(c,"viewName");u.set(p,{name:p,database:n,schema:o,type:"view"})}return[...u.values()].sort((c,p)=>c.name.localeCompare(p.name))}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}const Zs=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}`)},Np=t=>{const{host:e,port:r,...n}=t;return{...n,connectString:t.connectString??`${e??"localhost"}:${r??5236}`}};class Op{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={...Np(this.#e),poolAlias:typeof this.#e.poolAlias=="string"?this.#e.poolAlias:`semanticdb-${Co()}`};if(this.#t)return this.#t.createPool(e);const{default:r}=await import("dmdb").catch(n=>{throw Ke("dmdb",n)});return r.createPool(e)})();try{return await this.#r}catch(e){throw this.#r=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} ${this.quoteIdentifier(r)}`}paginate(e,r,n){return n>0?`${e} OFFSET ${n} ROWS FETCH NEXT ${r} ROWS ONLY`:`${e} FETCH FIRST ${r} ROWS ONLY`}parameter(e,r){return"?"}displayQuery(e,r){return fp(e,r.map(Zs))}dateBucket(e,r){const n={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(r in n))throw new Error(`Unsupported Dameng date level: ${r}`);const o=n[r];return o?`TRUNC(${e}, '${o}')`:`TRUNC(${e})`}datePart(e,r){return r==="weekday"?`(TRUNC(${e}) - TRUNC(${e}, 'IW') + 1)`:`TO_NUMBER(TO_CHAR(${e}, '${{second:"SS",minute:"MI",hour:"HH24",day:"DD",week:"IW",month:"MM",quarter:"Q",year:"YYYY"}[r]}'))`}dateShift(e,r,n){if(!Number.isInteger(n))throw new Error(`Unsupported Dameng date shift: ${r}/${n}`);const i={month:1,quarter:3,year:12}[r];if(i)return`ADD_MONTHS(${e}, ${n*i})`;const a={second:{unit:"SECOND",multiplier:1},minute:{unit:"MINUTE",multiplier:1},hour:{unit:"HOUR",multiplier:1},day:{unit:"DAY",multiplier:1},week:{unit:"DAY",multiplier:7}}[r];if(!a)throw new Error(`Unsupported Dameng date shift: ${r}/${n}`);return`(${e} + NUMTODSINTERVAL(${n*a.multiplier}, '${a.unit}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Dameng aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_CHAR(${e})`}concat(e){return`(${e.join(" || ")})`}substring(e,r,n){return`SUBSTR(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Dameng regex options: ${n}`);return`REGEXP_LIKE(${e}, ${r}${n?", 'i'":""})`}async execute(e){return(await this.#o(e,!1)).rows}async runSQL(e){return this.#o(e,!0)}getTableList(e){return ut(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}describeTable(e){return Ye(this,{...e,...e.schema===void 0&&this.#e.schema!==void 0?{schema:this.#e.schema}:{}})}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=await n.getConnection();try{e.signal?.throwIfAborted();const i=await o.execute(e.sql,e.parameters.map(Zs),{outFormat:4002,...r?{autoCommit:!0}:{}});if(e.signal?.throwIfAborted(),!(r&&i.rows===void 0)&&!Array.isArray(i.rows))throw new Error("Dameng provider expected an array result");return{rows:i.rows??[],...typeof i.rowsAffected=="number"?{affectedRows:i.rowsAffected}:{}}}finally{await o.close()}}async close(){const e=this.#r;if(!e)return;await(await e).close(0),this.#r=void 0}}const X={quoteIdentifier(t){return`\`${t.replaceAll("`","``")}\``},tableAlias(t,e){return`${t} AS ${this.quoteIdentifier(e)}`},paginate(t,e,r){return`${t} LIMIT ${e}${r>0?` OFFSET ${r}`:""}`},parameter(t,e){return"?"},displayQuery(t,e){return pp(t,e)},dateBucket(t,e){const r={hour:"%Y-%m-%d %H:00:00",day:"%Y-%m-%d",month:"%Y-%m-01",year:"%Y-01-01"};if(e==="week")return`DATE_SUB(DATE(${t}), INTERVAL WEEKDAY(${t}) DAY)`;if(e==="quarter")return`MAKEDATE(YEAR(${t}), 1) + INTERVAL (QUARTER(${t}) - 1) QUARTER`;const n=r[e];if(!n)throw new Error(`Unsupported MySQL-compatible date level: ${e}`);return`DATE_FORMAT(${t}, '${n}')`},datePart(t,e){const r={second:"SECOND",minute:"MINUTE",hour:"HOUR",day:"DAYOFMONTH",month:"MONTH",quarter:"QUARTER",year:"YEAR"};if(e==="weekday")return`(WEEKDAY(${t}) + 1)`;if(e==="week")return`WEEK(${t}, 3)`;const n=r[e];if(!n)throw new Error(`Unsupported MySQL-compatible date part: ${e}`);return`${n}(${t})`},dateShift(t,e,r){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(e)||!Number.isInteger(r))throw new Error(`Unsupported MySQL-compatible date shift: ${e}/${r}`);return`DATE_ADD(${t}, INTERVAL ${r} ${e.toUpperCase()})`},datePeriodBoundary(t,e,r){if(r==="start")return this.dateBucket(t,e);switch(e){case"hour":return`DATE_FORMAT(${t}, '%Y-%m-%d %H:59:59')`;case"day":return`TIMESTAMP(DATE(${t}), '23:59:59')`;case"month":return`TIMESTAMP(LAST_DAY(${t}), '23:59:59')`;case"year":return`CONCAT(YEAR(${t}), '-12-31 23:59:59')`;default:return this.dateShift(this.dateShift(this.dateBucket(t,e),e,1),"second",-1)}},aggregateFunction(t,e="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(t))throw new Error(`Unsupported MySQL-compatible aggregate function: ${t}`);return`${t.toUpperCase()}(${e})`},stringify(t){return`CAST(${t} AS CHAR)`},concat(t){return`CONCAT(${t.join(", ")})`},substring(t,e,r){return`SUBSTRING(${t}, ${e}, ${r})`},stringLength(t){return`CHAR_LENGTH(${t})`},regex(t,e,r){if(r&&r!=="i")throw new Error(`Unsupported MySQL-compatible regex options: ${r}`);return r==="i"?`LOWER(${t}) REGEXP LOWER(${e})`:`${t} REGEXP ${e}`},arrayContains(t,e){return`JSON_OVERLAPS(${t}, JSON_ARRAY(${e}))`},expandArray(t,e,r){const n=this.quoteIdentifier(e),o=this.quoteIdentifier(r);return{joinSql:`CROSS JOIN JSON_TABLE(CASE WHEN JSON_TYPE(${t}) = 'ARRAY' THEN ${t} ELSE JSON_ARRAY() END, '$[*]' COLUMNS (${o} JSON PATH '$')) AS ${n}`,valueExpression:`${n}.${o}`}}},Tp={connectionLimit:30,maxIdle:10,idleTimeout:6e4,enableKeepAlive:!0,keepAliveInitialDelay:0};class vr{supportsRecursiveCte=!0;#e;#t;constructor(e={}){this.#e=e.connection??{},this.#t=e.pool?Promise.resolve(e.pool):void 0}async#r(){this.#t??=(async()=>{const{createPool:e}=await import("mysql2/promise").catch(r=>{throw Ke("mysql2",r)});return e({...Tp,decimalNumbers:!0,...this.#e})})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return X.quoteIdentifier(e)}tableAlias(e,r){return X.tableAlias(e,r)}paginate(e,r,n){return X.paginate(e,r,n)}parameter(e,r){return X.parameter(e,r)}displayQuery(e,r){return X.displayQuery(e,r)}dateBucket(e,r){return X.dateBucket(e,r)}datePart(e,r){return X.datePart(e,r)}dateShift(e,r,n){return X.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=X.datePeriodBoundary?.bind(X);if(!o)throw new Error("MySQL date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return X.aggregateFunction(e,r)}stringify(e){return X.stringify(e)}concat(e){return X.concat(e)}substring(e,r,n){return X.substring(e,r,n)}stringLength(e){return X.stringLength(e)}regex(e,r,n){return X.regex(e,r,n)}arrayContains(e,r){const n=X.arrayContains?.bind(X);if(!n)throw new Error("MySQL-compatible array conditions are unavailable");return n(e,r)}expandArray(e,r,n){const o=X.expandArray?.bind(X);if(!o)throw new Error("MySQL-compatible array expansion is unavailable");return o(e,r,n)}async execute(e){return(await this.#n(e,!1)).rows}async runSQL(e){return this.#n(e,!0)}getTableList(e){return ut(this,e)}describeTable(e){return Ye(this,e)}async#n(e,r){e.signal?.throwIfAborted();const n=await this.#r();e.signal?.throwIfAborted();const[o]=await n.execute(e.sql,e.parameters);if(e.signal?.throwIfAborted(),r&&typeof o=="object"&&o!==null&&"affectedRows"in o&&typeof o.affectedRows=="number")return{rows:[],affectedRows:o.affectedRows};if(!Array.isArray(o))throw new Error(`${this.kind} provider expected an array result`);return{rows:o}}async close(){const e=this.#t;if(!e)return;await(await e).end(),this.#t=void 0}}class Pp extends vr{kind="doris";constructor(e={}){super(e)}}class Lp extends vr{kind="gbase";supportsRecursiveCte=!1;constructor(e={}){super({...e,connection:{port:5258,...e.connection}})}}class Dp{kind="maxcompute";supportsRecursiveCte=!1;#e;#t=!1;constructor(e){this.#e=e.client}quoteIdentifier(e){return X.quoteIdentifier(e)}tableAlias(e,r){return X.tableAlias(e,r)}paginate(e,r,n){return X.paginate(e,r,n)}parameter(e,r){return X.parameter(e,r)}displayQuery(e,r){return X.displayQuery(e,r)}dateBucket(e,r){return X.dateBucket(e,r)}datePart(e,r){return X.datePart(e,r)}dateShift(e,r,n){return X.dateShift(e,r,n)}datePeriodBoundary(e,r,n){const o=X.datePeriodBoundary?.bind(X);if(!o)throw new Error("MaxCompute date period boundary renderer is unavailable");return o(e,r,n)}aggregateFunction(e,r){return X.aggregateFunction(e,r)}stringify(e){return X.stringify(e)}concat(e){return X.concat(e)}substring(e,r,n){return X.substring(e,r,n)}stringLength(e){return X.stringLength(e)}regex(e,r,n){return X.regex(e,r,n)}async execute(e){e.signal?.throwIfAborted();const r=await this.#e.execute(e);if(e.signal?.throwIfAborted(),!Array.isArray(r))throw new Error("MaxCompute provider expected an array result");return r}async runSQL(e){e.signal?.throwIfAborted();const r=this.#e.runSQL?await this.#e.runSQL(e):{rows:await this.execute(e)};return e.signal?.throwIfAborted(),r}async getTableList(e){if(e.signal?.throwIfAborted(),or(e),this.#e.getTableList){const n=await this.#e.getTableList(e);return e.signal?.throwIfAborted(),n}return e.database!==void 0&&Te(this,"database"),e.schema!==void 0&&Te(this,"schema"),(await this.execute({sql:"SHOW TABLES",parameters:[],...e.signal?{signal:e.signal}:{}})).map(n=>({name:Ne(n,"table_name"),type:"table"}))}async close(){this.#t||(await this.#e.close(),this.#t=!0)}async describeTable(e){if(e.signal?.throwIfAborted(),go(e),!this.#e.describeTable)return Ye(this,e);const r=await this.#e.describeTable(e);return e.signal?.throwIfAborted(),r}}class Cp extends vr{kind="mysql";constructor(e={}){super(e)}}const ea=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}`)},kp=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class Up{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 dp(e,r.map(ea))}dateBucket(e,r){const n={hour:"HH24",day:void 0,week:"IW",month:"MM",quarter:"Q",year:"YYYY"};if(!(r in n))throw new Error(`Unsupported Oracle date level: ${r}`);const o=n[r];return o?`TRUNC(${e}, '${o}')`:`TRUNC(${e})`}datePart(e,r){return r==="weekday"?`(TRUNC(${e}) - TRUNC(${e}, 'IW') + 1)`:`TO_NUMBER(TO_CHAR(${e}, '${{second:"SS",minute:"MI",hour:"HH24",day:"DD",week:"IW",month:"MM",quarter:"Q",year:"YYYY"}[r]}'))`}dateShift(e,r,n){if(!Number.isInteger(n))throw new Error(`Unsupported Oracle date shift: ${r}/${n}`);const i={month:1,quarter:3,year:12}[r];if(i)return`ADD_MONTHS(${e}, ${n*i})`;const a={second:{unit:"SECOND",multiplier:1},minute:{unit:"MINUTE",multiplier:1},hour:{unit:"HOUR",multiplier:1},day:{unit:"DAY",multiplier:1},week:{unit:"DAY",multiplier:7}}[r];if(!a)throw new Error(`Unsupported Oracle date shift: ${r}/${n}`);return`(${e} + NUMTODSINTERVAL(${n*a.multiplier}, '${a.unit}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Oracle aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_CHAR(${e})`}concat(e){return`(${e.join(" || ")})`}substring(e,r,n){return`SUBSTR(${e}, ${r}, ${n})`}stringLength(e){return`LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Oracle regex options: ${n}`);return`REGEXP_LIKE(${e}, ${r}${n?", 'i'":""})`}arrayContains(e,r){return`JSON_EXISTS(${e}, '$?(@ == $value)' PASSING ${r} AS "value")`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS APPLY JSON_TABLE(${e}, '$[*]' COLUMNS (${i} VARCHAR2(4000) PATH '$')) ${o}`,valueExpression:`${o}.${i}`}}async#n(){this.#r??=(async()=>{if(this.#t)return this.#t.createPool(this.#e);const{default:e}=await import("oracledb").catch(r=>{throw Ke("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 ut(this,e)}describeTable(e){return Ye(this,e)}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=await n.getConnection(),i=e.signal,s=()=>{o.break().catch(()=>{})};i?.addEventListener("abort",s,{once:!0});try{i?.throwIfAborted();const a=await o.execute(e.sql,e.parameters.map(ea),{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?kp(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 Mp{kind="postgresql";supportsHavingAlias=!1;supportsRecursiveCte=!0;#e;#t;constructor(e={}){this.#e=e.connection??{},this.#t=e.pool?Promise.resolve(e.pool):void 0}async#r(){this.#t??=(async()=>{const{Pool:e}=await import("pg").catch(r=>{throw Ke("pg",r)});return new e(this.#e)})();try{return await this.#t}catch(e){throw this.#t=void 0,e}}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return`$${e+1}`}displayQuery(e,r){return lp(e,r)}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported PostgreSQL date level: ${r}`);return`DATE_TRUNC('${r}', ${e})`}datePart(e,r){return`EXTRACT(${r==="weekday"?"ISODOW":r.toUpperCase()} FROM ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported PostgreSQL date shift: ${r}/${n}`);return`(${e} + (${n} * INTERVAL '1 ${r}'))`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported PostgreSQL aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`CAST(${e} AS TEXT)`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e} FROM ${r} FOR ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported PostgreSQL regex options: ${n}`);return`${e} ${n==="i"?"~*":"~"} ${r}`}arrayContains(e,r){return`${r} = ANY(${e})`}expandArray(e,r,n){const o=this.quoteIdentifier(r),i=this.quoteIdentifier(n);return{joinSql:`CROSS JOIN LATERAL unnest(${e}) AS ${o}(${i})`,valueExpression:`${o}.${i}`}}async execute(e){return(await this.runSQL(e)).rows}getTableList(e){return ut(this,e)}describeTable(e){return Ye(this,e)}async runSQL(e){e.signal?.throwIfAborted();const r=await this.#r();e.signal?.throwIfAborted();const n=await r.query(e.sql,[...e.parameters]);if(e.signal?.throwIfAborted(),!Array.isArray(n.rows))throw new Error("PostgreSQL provider expected an array result");return{rows:n.rows,...typeof n.rowCount=="number"&&["INSERT","UPDATE","DELETE","MERGE"].includes(n.command??"")?{affectedRows:n.rowCount}:{}}}async close(){const e=this.#t;if(!e)return;await(await e).end(),this.#t=void 0}}const ta=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}`)},qp=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError");class jp{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 Ke("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 ho(e,r.map(ta))}dateBucket(e,r){if(!new Set(["hour","day","week","month","quarter","year"]).has(r))throw new Error(`Unsupported Snowflake date level: ${r}`);return`DATE_TRUNC('${r.toUpperCase()}', ${e})`}datePart(e,r){return`DATE_PART(${r==="weekday"?"DAYOFWEEKISO":r==="week"?"WEEKISO":r.toUpperCase()}, ${e})`}dateShift(e,r,n){if(!new Set(["second","minute","hour","day","week","month","quarter","year"]).has(r)||!Number.isInteger(n))throw new Error(`Unsupported Snowflake date shift: ${r}/${n}`);return`DATEADD(${r.toUpperCase()}, ${n}, ${e})`}aggregateFunction(e,r="*"){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(e))throw new Error(`Unsupported Snowflake aggregate function: ${e}`);return`${e.toUpperCase()}(${r})`}stringify(e){return`TO_VARCHAR(${e})`}concat(e){return`CONCAT(${e.join(", ")})`}substring(e,r,n){return`SUBSTRING(${e}, ${r}, ${n})`}stringLength(e){return`CHAR_LENGTH(${e})`}regex(e,r,n){if(n&&n!=="i")throw new Error(`Unsupported Snowflake regex options: ${n}`);return n?`REGEXP_INSTR(${e}, ${r}, 1, 1, 0, '${n}') > 0`:`REGEXP_INSTR(${e}, ${r}) > 0`}arrayContains(e,r){return`ARRAY_CONTAINS(${r}::VARIANT, ${e})`}expandArray(e,r,n){const o=this.quoteIdentifier(r);return{joinSql:`, LATERAL FLATTEN(INPUT => ${e}) ${o}`,valueExpression:`${o}.VALUE`}}async#s(){if(this.#r)return;const e=await this.#o();this.#n??=new Promise((r,n)=>{e.connect(o=>{if(o){n(o);return}this.#r=!0,r()})});try{await this.#n}catch(r){throw this.#n=void 0,r}}async execute(e){return(await this.#i(e,!1)).rows}async runSQL(e){return this.#i(e,!0)}getTableList(e){return ut(this,e)}describeTable(e){return Ye(this,e)}async#i(e,r){e.signal?.throwIfAborted(),await this.#s(),e.signal?.throwIfAborted();const n=await this.#o();e.signal?.throwIfAborted();const o=e.parameters.map(ta);return new Promise((i,s)=>{const a=e.signal,u={};let c=!1;const p=f=>{c||(c=!0,a?.removeEventListener("abort",l),f())},l=()=>{u.current?.cancel(),a&&p(()=>s(qp(a)))};a?.addEventListener("abort",l,{once:!0}),u.current=n.execute({sqlText:e.sql,binds:o,complete:(f,m,y)=>{if(f){p(()=>s(f));return}if(!(r&&y===void 0)&&!Array.isArray(y)){p(()=>s(new Error("Snowflake provider expected an array result")));return}const h=r?m.getNumUpdatedRows?.():void 0;p(()=>i({rows:y??[],...typeof h=="number"&&h>=0?{affectedRows:h}:{}}))}}),a?.aborted&&l()})}async close(){if(!this.#r)return;const e=await this.#o();await new Promise((r,n)=>{e.destroy(o=>{if(o){n(o);return}this.#r=!1,this.#n=void 0,this.#t=void 0,r()})})}}const xp=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}}},Bp=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}`)},Vp=t=>t.reason instanceof Error?t.reason:new DOMException("The operation was aborted","AbortError"),vp=t=>t instanceof Error?t:new Error("SQL Server query failed",{cause:t}),Fp=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 Yp{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 Ke("mssql",n)}),r=new e.ConnectionPool(xp(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`${Fp(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 mp(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 ut(this,e)}describeTable(e){return Ye(this,e)}async#o(e,r){e.signal?.throwIfAborted();const n=await this.#n();e.signal?.throwIfAborted();const o=n.request();return e.parameters.forEach((i,s)=>o.input(`p${s}`,Bp(i))),new Promise((i,s)=>{const a=e.signal;let u=!1;const c=l=>{u||(u=!0,a?.removeEventListener("abort",p),l())},p=()=>{o.cancel(),a&&c(()=>s(Vp(a)))};a?.addEventListener("abort",p,{once:!0}),o.query(e.sql).then(l=>{if(!Array.isArray(l.recordset)&&!(r&&l.recordset===void 0)){c(()=>s(new Error("SQL Server provider expected an array result")));return}c(()=>i({rows:l.recordset??[],...l.rowsAffected?{affectedRows:l.rowsAffected.reduce((f,m)=>f+m,0)}:{}}))},l=>c(()=>s(vp(l)))),a?.aborted&&p()})}async close(){const e=this.#r;if(!e)return;await(await e).close(),this.#r=void 0}}class Hp extends vr{kind="starrocks";constructor(e={}){super(e)}}const Pe=t=>{const{id:e,kind:r,...n}=t;return n},Qp=Object.freeze([{kind:"mysql",create:t=>new Cp({connection:Pe(t)})},{kind:"doris",create:t=>new Pp({connection:Pe(t)})},{kind:"gbase",create:t=>new Lp({connection:Pe(t)})},{kind:"starrocks",create:t=>new Hp({connection:Pe(t)})},{kind:"maxcompute",create:t=>new Dp(Pe(t))},{kind:"postgresql",create:t=>new Mp({connection:Pe(t)})},{kind:"clickhouse",create:t=>new _p(Pe(t))},{kind:"databricks",create:t=>new Rp({connection:Pe(t)})},{kind:"dameng",create:t=>new Op({connection:Pe(t)})},{kind:"snowflake",create:t=>new jp({connection:Pe(t)})},{kind:"sqlserver",create:t=>new Yp({connection:Pe(t)})},{kind:"oracle",create:t=>new Up({connection:Pe(t)})}]);class ra{#e=new Map;constructor(e=Qp){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 na=new ra,oa=(t,e=na)=>e.create(t);class Gp{create;#e=new Map;constructor(e=oa){this.create=e}get(e){const r=this.#e.get(e.id);if(r){if(!Ea(r.connection,e))throw new d("DATABASE_CONNECTION_CONFIGURATION_MISMATCH",`Database connection configuration changed for id: ${e.id}`,{connectionId:e.id});return r.provider}const n=this.create(e);return this.#e.set(e.id,{connection:e,provider:n}),n}async close(){const e=[...this.#e.values()].map(({provider:o})=>o);this.#e.clear();const r=await Promise.allSettled(e.map(async o=>o.close())),n=[];for(const o of r)o.status==="rejected"&&n.push(o.reason);if(n.length>0)throw new AggregateError(n,"Failed to close one or more database connections")}}const Fr=new Map,Wp=t=>{const e=Fr.get(t);if(e)return e;const r=new Gp(n=>oa(n,t));return Fr.set(t,r),r},Yr=(t,e=na)=>Wp(e).get(t),ia=async()=>{const t=[...Fr.values()];Fr.clear();const r=(await Promise.allSettled(t.map(async n=>n.close()))).flatMap(n=>n.status==="rejected"?[n.reason]:[]);if(r.length>0)throw new AggregateError(r,"Failed to close one or more connection registries")},zp=async t=>{if(t.signal?.throwIfAborted(),!t.sql.trim())throw new d("INVALID_SQL","SQL must not be empty");const e=Yr(t.connection,t.providerRegistry);if(!e.runSQL)throw new d("UNSUPPORTED_RAW_SQL",`Provider does not support native SQL: ${e.kind}`);const r=await e.runSQL({sql:t.sql,parameters:t.parameters??[],...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},Kp=async t=>{t.signal?.throwIfAborted(),or(t);const e=Yr(t.connection,t.providerRegistry);if(!e.getTableList)throw new d("UNSUPPORTED_TABLE_DISCOVERY",`Provider does not support table discovery: ${e.kind}`);const r=await e.getTableList({...t.database!==void 0?{database:t.database}:{},...t.schema!==void 0?{schema:t.schema}:{},...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},Jp=async t=>{t.signal?.throwIfAborted(),go(t);const e=Yr(t.connection,t.providerRegistry);if(!e.describeTable)throw new d("UNSUPPORTED_TABLE_DESCRIPTION",`Provider does not support table description: ${e.kind}`);const r=await e.describeTable({table:t.table,...t.database!==void 0?{database:t.database}:{},...t.schema!==void 0?{schema:t.schema}:{},...t.includeSample!==void 0?{includeSample:t.includeSample}:{},...t.signal?{signal:t.signal}:{}});return t.signal?.throwIfAborted(),r},Xp=Object.freeze({runSQL:zp,getTableList:Kp,describeTable:Jp,close:ia}),Zp=t=>{const{name:e,kind:r}=t;switch(r){case"boolean":return{name:e,kind:r,type:Uo,sqlType:"BOOLEAN"};case"date":return{name:e,kind:r,type:Zr,sqlType:"TIMESTAMP"};case"number":return{name:e,kind:r,type:ko,sqlType:"DOUBLE"};case"string":return{name:e,kind:r,type:mt,sqlType:"VARCHAR"}}},ef=t=>typeof t=="boolean"?t:t===1||t==="1"||t==="true"?!0:t===0||t==="0"||t==="false"?!1:!!t,tf=(t,e)=>{if(t==null)return null;switch(e.kind){case"boolean":return Be(ef(t),Uo);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:Be(r,Zr)}case"number":{const r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?Be(r,ko):null}case"string":return typeof t=="string"?Be(t,mt):typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?Be(t.toString(),mt):typeof t=="symbol"?Be(t.description??"",mt):typeof t=="function"?Be(t.name,mt):Be(JSON.stringify(t),mt)}},rf=t=>{if(t==null)return null;if(t instanceof Date)return Be(t,Zr);if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"||typeof t=="string")return t;if(Buffer.isBuffer(t))return Sa(t);throw new TypeError(`Unsupported DuckDB coordinator parameter: ${typeof t}`)};class Kr{instance;connection;kind="duckdb";supportsHavingAlias=!0;supportsRecursiveCte=!0;static async create(){const e=await _a.create(":memory:"),r=await e.connect();return new Kr(e,r)}constructor(e,r){this.instance=e,this.connection=r}quoteIdentifier(e){return`"${e.replaceAll('"','""')}"`}tableAlias(e,r){return`${e} AS ${this.quoteIdentifier(r)}`}paginate(e,r,n){return`${e} LIMIT ${r}${n>0?` OFFSET ${n}`:""}`}parameter(e,r){return"?"}displayQuery(e,r){return ho(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(Zp),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=tf(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(rf));return e.signal?.throwIfAborted(),r.getRowObjectsJS()}close(){return this.connection.closeSync(),this.instance.closeSync(),Promise.resolve()}}const Ao="__sdb_total__",nf="__sdb_total_source__",wo=t=>{const e={...t,orderBy:[]};return delete e.pagination,e},of=t=>{const e={...t};return delete e.limit,delete e.page,e},Eo=(t,e)=>({sql:`SELECT ${e.aggregateFunction("count")} AS ${e.quoteIdentifier(Ao)} FROM ${e.tableAlias(`(${t.sql})`,nf)}`,parameters:t.parameters}),Hr=t=>{if(t.length===0)return 0;const e=t[0]??{},r=e[Ao]??e[Ao.toUpperCase()]??Object.values(e)[0],n=typeof r=="number"?r:Number(r);if(!Number.isSafeInteger(n)||n<0)throw new d("INVALID_TOTAL_RESULT","The total query must return a non-negative safe integer",{total:r});return n},kt="__semanticdb_coordinator__",sa=(t,e)=>{const r=new Set;for(const n of Ae(t)){const o=e.findSource(n.schemaId,n.source,n.connectionId);if(!o)throw new d("SCHEMA_MAPPING_NOT_FOUND",`Schema mapping is not registered: ${n.schemaId}:${n.source}`,{schemaId:n.schemaId,source:n.source});r.add(o.connectionId)}return[...r]},ir=(t,e)=>!!t.subplans&&new Set(t.subplans?.flatMap(r=>sa(r,e))).size>1||!!(t.sourcePlan&&ir(t.sourcePlan,e)),sf=(t,e)=>({name:t,expression:{kind:"column",property:t,column:t,qualifier:e}}),af=(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"},aa=(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"?af(e,n):"string";return{name:n,kind:i}})},cf=(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=>sf(n,e)),...t.columnProperties?{columnProperties:t.columnProperties}:{},groupBy:[],orderBy:[],rowIdentity:{kind:"generated"}}},uf=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:JSON.stringify(r.names.map(o=>{const i=n[o];return i==null?["null"]:i instanceof Date?["date",i.toISOString()]:typeof i=="bigint"?["bigint",i.toString()]:typeof i=="object"?"_id"in i||"id"in i?["entity",Tr(i)]:["object",JSON.stringify(i)]:[typeof i,i]}))}))}if(e.rowIdentity.kind==="singleton")return t.map(r=>({...r,_id:"0"}));throw new d("UNSTABLE_FEDERATED_IDENTITY","A federated composition branch must be grouped or aggregate to a singleton row")},ca=(t,e)=>{if(e.rowIdentity.kind==="group"){const r=e.rowIdentity;return t.map(n=>({...n,_id:Wn(n,r.names,r.separator,r.nullLabel)}))}return e.rowIdentity.kind==="singleton"?t.map(r=>({...r,_id:"0"})):[...t]},Qr=async(t,e)=>{if(!Number.isSafeInteger(e.maxMaterializedRows)||e.maxMaterializedRows<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:e.maxMaterializedRows});if(t.sourcePlan&&ir(t.sourcePlan,e.schemaMappings)){const s=await Qr(t.sourcePlan,e),a=await Kr.create();try{const u="__federated_source";await a.materialize(u,aa(t.sourcePlan,s.rows),s.rows);const c={...t,source:u};delete c.sourcePlan,delete c.sourceLogicform,delete c.connectionId;const p=he(c,a,e.operators),l=Eo(he(wo(c),a,e.operators),a);e.onCompiled({compiled:p,connectionId:kt,provider:a,type:"computation",logicform:e.logicform}),e.onCompiled({compiled:l,connectionId:kt,provider:a,type:"total",logicform:e.logicform});const f=await a.execute({...l,...e.signal?{signal:e.signal}:{}}),m=await a.execute({...p,...e.signal?{signal:e.signal}:{}});return{rows:ca(m,t),total:Hr(f),connections:s.connections}}finally{await a.close()}}if(!t.subplans||t.subplans.length<2)throw new d("INVALID_FEDERATED_PLAN","A federated composition requires at least two child plans");const r=new Map,n=await Promise.all(t.subplans.map(async s=>{const a=sa(s,e.schemaMappings);if(a.length!==1)throw new d("CROSS_CONNECTION_FRAGMENT_UNSUPPORTED","A federated branch must compile completely on one physical connection",{schemaId:s.schemaId,connectionIds:a});const u=a[0],c=e.providerForConnection(u);r.set(u,c.kind);const p=he(s,c,e.operators);e.onCompiled({compiled:p,connectionId:u,provider:c,type:"computation",logicform:e.logicform});const l=await Re(p,Ae(s),{provider:c,connectionId:u,schemaMappings:e.schemaMappings,...e.cache?{cache:e.cache}:{},...e.signal?{signal:e.signal}:{}}),f=await ot(l,s.projections,e.operators);return{child:s,rows:uf(f,s)}})),o=n.reduce((s,a)=>s+a.rows.length,0);if(o>e.maxMaterializedRows)throw new d("FEDERATED_RESULT_LIMIT_EXCEEDED",`Federated execution materialized ${o} rows; maximum is ${e.maxMaterializedRows}`,{materializedRowCount:o,maxMaterializedRows:e.maxMaterializedRows});const i=await Kr.create();try{const s=n.flatMap(({rows:m})=>m),a=[];for(const[m,{child:y,rows:h}]of n.entries()){const g=`__federated_branch_${m}`;await i.materialize(g,aa(y,s),h),a.push(cf(y,g))}const u={...t,subplans:a},c=he(u,i,e.operators),p=Eo(he(wo(u),i,e.operators),i);e.onCompiled({compiled:c,connectionId:kt,provider:i,type:"computation",logicform:e.logicform}),e.onCompiled({compiled:p,connectionId:kt,provider:i,type:"total",logicform:e.logicform});const l=await i.execute({...p,...e.signal?{signal:e.signal}:{}}),f=await i.execute({...c,...e.signal?{signal:e.signal}:{}});return{rows:ca(f,t),total:Hr(l),connections:[...r].map(([m,y])=>({connectionId:m,provider:y}))}}finally{await i.close()}},df=new Set(["$sply","$splm","$splq","$splw","$yoy","$mom","$qoq","$wow","$yoyd","$momd","$qoqd","$wowd","$percentage"]),_o=t=>!W(t)||!Array.isArray(t.properties)?[]:t.properties.filter(W),lf=(t,e)=>{const r=e[t];return W(r)?r:Object.values(e).find(n=>W(n)&&(n.id===t||n._id===t))},ua=(t,e,r)=>{const n=lf(t,r);if(!n)return;const i=_o(n).map(s=>{const u=[s.id,s._id,s.name].filter(c=>typeof c=="string").filter(c=>e===c||e.startsWith(`${c}_`)).sort((c,p)=>p.length-c.length)[0];return u?{property:s,key:u}:void 0}).filter(s=>s!==void 0).sort((s,a)=>a.key.length-s.key.length)[0];if(i)return e===i.key?i.property:typeof i.property.ref=="string"?ua(i.property.ref,e.slice(i.key.length+1),r):void 0},Ut=(t,e,r)=>{const n=(o,i,s)=>{const c=_o(r[o]).map(y=>{const h=typeof y.id=="string"?y.id:void 0,g=typeof y.name=="string"?y.name:void 0,w=[h,g].filter(S=>!!S&&(i===S||i.startsWith(`${S}_`))).sort((S,E)=>E.length-S.length)[0];return w?{property:y,key:w}:void 0}).filter(y=>!!y).sort((y,h)=>h.key.length-y.key.length)[0];if(!c)return;const p=String(c.property.id??c.property.name),l=i===c.key?"":i.slice(c.key.length+1);if(!l)return p;const f=typeof c.property.ref=="string"?c.property.ref:void 0;if(!f||s.has(f))return;const m=n(f,l,new Set(s).add(f));return m?`${p}_${m}`:void 0};return n(t,e,new Set([t]))},So=(t,e,r)=>{const n=_o(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 So(n.ref,e.slice(n.id.length+1),r)}},da=t=>Object.keys(t).filter(e=>e!=="$and"&&e!=="$or"),W=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),la=t=>typeof t=="string"&&/^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?$/.test(t),pa=t=>{if(!W(t))return t;if(W(t.$offset)){const e=Object.entries(t.$offset),r=e[0];if(e.length===1&&r&&Number.isInteger(r[1]))return{granularity:r[0],offset:r[1]}}return t},pf=t=>typeof t=="string"&&t.length>0||typeof t=="number"&&Number.isSafeInteger(t),ff=(t,e)=>{if(!e)return;const r=e[t]??Object.values(e).find(u=>W(u)&&(u.id===t||u._id===t));if(!W(r))return;const n=r.hierarchy,o=Array.isArray(n)?n:W(n)&&Array.isArray(n.levels)?n.levels:void 0;if(!o)return;const i=o.map(u=>{if(!W(u)||typeof u.name!="string")return;const c=u.codeLength??u.code_length;return Number.isInteger(c)&&Number(c)>0?{name:u.name,codeLength:Number(c)}:void 0});if(i.length===0||i.some(u=>u===void 0))return;const s=o[0],a=Array.isArray(n)?W(s)&&s.use_full_length===!0?"zero-padded":"compact":W(n)&&n.storage==="zero-padded"?"zero-padded":"compact";return{levels:i.filter(u=>u!==void 0),storage:a}},mf=(t,e,r)=>{const n=ff(t,r);if(!n)return;const o=String(e),i=n.levels.reduce((a,u)=>a+u.codeLength,0);let s=0;for(const a of n.levels)if(s+=a.codeLength,o.length===s||n.storage==="zero-padded"&&o.length===i&&o.slice(s)==="0".repeat(i-s))return a.name;throw new d("LEGACY_HIERARCHY_LEVEL_INFERENCE_FAILED",`Cannot infer hierarchy level from entity_id ${o} in Schema ${t}`,{schemaId:t,entityId:e})},yf=(t,e)=>e.length===0?t:e.length===1&&t.$expr===void 0?{...t,$expr:e[0]}:{$and:[...Object.keys(t).length>0?[t]:[],...e.map(n=>({$expr:n}))]},Io=(t,e)=>{const r={},n=[];for(const[o,i]of Object.entries(t)){if((o==="$and"||o==="$or")&&Array.isArray(i)){r[o]=i.map(y=>W(y)?Io(y,e):y);continue}if(!W(i)){r[o]=i;continue}const s=i.entity_id;if(typeof i.schema!="string"||!W(i.query)||!pf(s)){r[o]=i;continue}const a=i.entity_level,u=typeof a=="string"&&a.length>0?a:mf(i.schema,s,e);if(!u){r[o]=i;continue}const{entity_id:c,entity_level:p,...l}=i,f=Io(i.query,e),m=Object.keys(l).filter(y=>y!=="schema"&&y!=="version"&&y!=="query");(Object.keys(f).length>0||m.length>0)&&(r[o]={...l,query:f}),n.push({pred:{operator:"$hierarchyLevel",pred:o,args:{level:u}},condition:s})}return yf(r,n)},hf=(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}},fa=(t,e)=>{if(!W(e)||!Array.isArray(e.cases)||e.cases.length===0)throw new d("INVALID_LEGACY_CASE_ARGS",`${t} requires a non-empty params.cases array`);return{cases:e.cases.map((n,o)=>{if(!W(n))throw new d("INVALID_LEGACY_CASE_ARGS",`${t} case ${o} must be an object`);if(n.sql!==void 0)throw new d("LEGACY_CASE_SQL_UNSUPPORTED",`${t} case.sql cannot be migrated to the structured v2 $case operator`);if(!W(n.query)||typeof n.name!="string"||n.name.length===0)throw new d("INVALID_LEGACY_CASE_ARGS",`${t} case ${o} requires query and a non-empty name`);return{when:n.query,then:n.name}}),...Object.hasOwn(e,"default")?{default:e.default}:{}}},He=(t,e,r)=>{if(Array.isArray(t))return t.map(u=>He(u,e,r));if(!W(t))return t;const n=pa(t);if(n!==t)return n;const o=t,i=typeof o.schema=="string"?o.schema:r,s={};for(const[u,c]of Object.entries(o))u==="skip"||u==="_snapshot"||u==="_snapshots"||(s[u]=He(c,e,i));if(typeof o.version=="string"&&/^1\./.test(o.version)&&(s.version="2.0"),Array.isArray(o.groupby)){const u=o.groupby;s.groupby=u.map(c=>{if(!W(c))return c;const p=He(c,e,i);if(!W(p))return p;const{_id:l,level:f,...m}=p,y={...m,...m.pred===void 0&&typeof l=="string"?{pred:l}:{}};return typeof f=="string"&&(y.operator="$dateBucket",y.args={...W(y.args)?y.args:{},granularity:f}),y})}const a=o.skip;if(typeof a=="number"&&Number.isInteger(a)&&a>=0){const u=o.limit;a===0?delete s.skip:typeof u=="number"&&Number.isInteger(u)&&u>0&&a%u===0?s.page=a/u+1:s.skip=a}else a!==void 0&&(s.skip=He(a,e,i));if(o.operator&&typeof o.operator=="string"){const u=hf(o.operator,W(s.args)?s.args:{});if(u.operator&&(s.operator=u.operator),s.args=u.args,o.operator==="$comp"||o.operator==="$compabs"){const c=W(s.args)?s.args.preds:void 0;if(!Array.isArray(c)||c.length!==2)throw new d("INVALID_LEGACY_COMP_ARGS",`${o.operator} requires exactly 2 preds in args.preds`);const p={operator:"$subtract",pred:c,args:{nullAsZero:!0}};s.operator=o.operator==="$comp"?"$subtract":"$abs",s.pred=o.operator==="$compabs"?p:c,s.args=o.operator==="$comp"?{nullAsZero:!0}:{}}if(o.operator==="$switch"){const c=W(s.params)?s.params:s.args;s.operator="$case",s.args=fa("$switch",c),delete s.params}if(o.operator==="$piecewise"){const c=typeof s.pred=="string"?s.pred:typeof o._id=="string"?o._id:void 0;if(e&&i&&c&&ua(i,c,e)?.cases!==void 0)throw new d("LEGACY_PIECEWISE_PROPERTY_CASES_UNSUPPORTED","$piecewise property cases contain trusted SQL and cannot be migrated safely to v2 $case",{schemaId:i,property:c});const p=W(s.params)?s.params:W(s.args)?s.args:{};s.operator="$case",s.args=Array.isArray(p.cases)?fa("$piecewise",p):{mode:"auto",buckets:Number.isInteger(p.buckets)?p.buckets:10},delete s.params}df.has(o.operator)&&typeof s.pred=="string"&&(s.pred={operator:"$sum",pred:s.pred})}return o.params!==void 0&&s.args===void 0&&(s.args=Array.isArray(o.params)?{values:He(o.params,e,i)}:He(o.params,e,i)),o.inputs!==void 0&&s.pred===void 0&&Array.isArray(o.inputs)&&(s.pred=o.inputs.map(u=>He(u,e,i)),W(s.args)&&delete s.args.inputs),o.pred===void 0&&typeof o.operator=="string"&&o.operator==="$sql"&&typeof o.sql=="string"&&(s.args={...W(s.args)?s.args:{},sql:o.sql},delete s.sql),o.$options!==void 0&&s.$regex!==void 0?(s.args={...W(s.args)?s.args:{},options:o.$options},delete s.$options):"$options"in o&&la(o.$gte)&&la(o.$lte)&&delete s.$options,o.query&&W(o.query)&&(s.query=gf(o.query,e,i)),s},gf=(t,e,r)=>{const n=He(t,e,r);for(const[o,i]of Object.entries(n))n[o]=pa(i);return Io(n,e)},ma=(t,e)=>{const r=W(t)?t:void 0,n=He(t,e);if(!W(n))return n;if(r&&typeof r.operator=="string"&&r.preds===void 0){const o={};for(const a of["version","schema","query","groupby","having","sort","limit","page","skip","output","representation","currency"])n[a]!==void 0&&(o[a]=n[a]);const i=new Set(["version","schema","query","groupby","having","sort","limit","page","skip","output","representation","currency"]),s=Object.fromEntries(Object.entries(n).filter(([a])=>!i.has(a)));return o.preds=[s],ma(o,e)}return(n.version===void 0||typeof n.version=="string"&&/^1\./.test(n.version))&&(n.version="2.0"),e?$f(n,e):n},$f=(t,e)=>{const r=t;if(!Array.isArray(r.preds))return t;const n=r.preds,o=typeof r.schema=="string"?r.schema:void 0;if(!o)return t;const i=new Set([o]);for(const u of n)W(u)&&typeof u.schema=="string"&&i.add(u.schema);if(i.size<2)return t;if(!e)throw new Error("Cannot migrate cross-Schema LogicForm without Schema metadata for field alignment");const s=Array.isArray(r.groupby)?r.groupby.map(u=>W(u)&&typeof u.pred=="string"?Ut(o,u.pred,e):void 0):[];for(const u of i)if(Array.isArray(r.groupby)&&r.groupby.map((c,p)=>{if(!W(c)||typeof c.pred!="string")return c;const l=u===o?Ut(u,c.pred,e):Ut(u,So(o,s[p]??"",e)??c.pred,e);if(!l)return c;const f=l.split("_").at(-1)??c.pred;return{...c,pred:l,name:f}}),W(r.query))for(const c of da(r.query)){const p=Ut(o,c,e);if(!(u===o?p:Ut(u,(p&&So(o,p,e))??c,e))&&u===o)throw new Error(`Cannot align legacy query field ${c} in Schema ${u}`)}const a={...r};if(Array.isArray(r.groupby)&&(a.groupby=r.groupby.map((u,c)=>{if(!W(u)||typeof u.pred!="string")return u;const p=s[c];return p?{...u,pred:p}:u})),W(r.query)){const u=r.query,c=da(u).map(p=>[Ut(o,p,e)??p,u[p]]);a.query=Object.fromEntries(c)}return a},Af=t=>{const e=(r,n)=>{if(Array.isArray(r)){r.forEach((o,i)=>e(o,`${n}[${i}]`));return}if(W(r))for(const[o,i]of Object.entries(r)){if(["is_snapshot","is_observation","_snapshot","_snapshots","$options","params","inputs","entity_level","entity_codelength"].includes(o))throw new d("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);if(o==="_id"&&(n.endsWith(".groupby")||n.includes(".groupby[")))throw new d("LEGACY_LOGICFORM_NOT_ALLOWED",`Legacy LogicForm field is not supported in v2: ${n}.${o}`);e(i,`${n}.${o}`)}};e(t,"$")},bo=t=>{if(Array.isArray(t))return t.map(bo).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,bo(o)]).filter(([,n])=>n!==void 0);if(!(e.length>0&&r.length===0))return Object.fromEntries(r)},wf=t=>{if(t.comparable!=null)return t.comparable;if(t.is_comparable!==!0||t.isArray===!0||t.type!=="string"&&t.type!=="category"||!Array.isArray(t.constraints?.enum))return;const r=t.constraints.enum.map(n=>Array.isArray(n)?n[0]:n);if(!(r.length===0||r.some(n=>typeof n!="string")))return{values:[...new Set(r)],direction:t.comparable_order===-1?-1:1}},Ef=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}},_f=(t,e=[],r=!0)=>{const n=me(e),o={},i=new Set(n.flatMap(s=>[...s.schemaMetadata?.keys??[],...s.legacySchemaKeys??[]]));for(const[s,a]of Object.entries(t)){const u=bo(a),c=u,l=(Array.isArray(c.properties)?c.properties:[]).some(S=>S.is_observation===!0)||c.is_observation===!0,f=c.is_snapshot===!0,m=typeof u.id=="string"&&u.id.length>0?u.id:r&&typeof u._id=="string"&&u._id.length>0?u._id:u.id,{properties:y}=u,h=Object.fromEntries(Object.entries(u).filter(([S])=>(r?!["_id","_sid","sid","is_observation","is_snapshot"].includes(S):S!=="properties")&&S!=="properties"&&!i.has(S))),g=y.map(S=>{const E=S,$=typeof E.id=="string"&&E.id.length>0?E.id:r&&typeof E._id=="string"&&E._id.length>0?E._id:E.id,{udf:R,...O}=E,D=wf(E),M=Ef(R),z=D!==void 0&&E.comparable==null?"category":E.type==="object"?"entity":E.type;return{...r?Object.fromEntries(Object.entries(O).filter(([v])=>!["_id","_sid","sid","is_observation","is_comparable","comparable_order"].includes(v))):O,type:z,...E.primal_type==="object"?{primal_type:"entity"}:{},...$!==void 0?{id:$}:{},...M!==void 0?{udf:M}:{},...D!==void 0?{comparable:D}:{}}});let A={};for(const S of n)for(const E of S.schemaMetadata?.keys??[])u[E]!==void 0&&(A={...A,[E]:u[E]});for(const S of n)A={...A,...S.normalizeLegacySchema?.({source:u,properties:g})};const w={...h,...m!==void 0?{id:m}:{},properties:g,...r&&(f||l)?{temporalSemantics:"snapshot"}:{},...A};o[s]=w}return o},ya=(t,e)=>[...me(t).flatMap(r=>r.locales??[]),...e===void 0?[]:"locale"in e?[e]:e],Gr=t=>({kind:"query",logicform:t.logicform,...t.prepare!==void 0?{prepare:t.prepare}:{},...t.mapResult?{mapResult:t.mapResult}:{},...t.groupKeyShifts?{groupKeyShifts:t.groupKeyShifts}:{}}),ha=t=>t instanceof Error?t:new Error(String(t)),Sf=(t,e="zh-CN",r)=>t instanceof d?t.localizedMessage(e,r):t.message,If=(t,e,r={},n="zh-CN",o)=>{const i=ha(t);return{errorCode:"100",error:Sf(i,n,o),result:[],...r.schema?{schema:r.schema}:{},normedLogicform:r.normedLogicform??e,sqls:r.sqls??[],...r.provider?{provider:r.provider}:{},...r.lineage?{lineage:r.lineage}:{}}},bf=(t,e,r)=>{const n=e.projections.map(({name:c})=>c),o=new Map((e.columnProperties??[]).map(c=>[c.name,c])),i=[],s=(c,p)=>{const l=r.parameter(i.length,p);i.push(p);const f=o.get(c)?.type;return f&&(f==="date"||f==="timestamp")&&r.castValue?r.castValue(l,f):l},a=c=>`SELECT ${n.map(p=>`${s(p,c[p])} AS ${r.quoteIdentifier(p)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""}`;return{sql:t.length>0?t.map(a).join(" UNION ALL "):`SELECT ${n.map(c=>`NULL AS ${r.quoteIdentifier(c)}`).join(", ")}${r.kind==="oracle"||r.kind==="dameng"?" FROM DUAL":""} WHERE 1 = 0`,parameters:i}},Rf=(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),...Ae(r)];for(const i of o){const s=fo(i,e);if(!s)return!1;n.add(s.connectionId)}return n.size<=1},Nf=async(t,e,r)=>{await t?.({...e,partialResult:r})},Of=(t,e,r,n,o,i,s=r,a)=>({type:r,...a?{connectionId:a}:{},provider:e.kind,explain:i.translate(o,s==="time-watermark"?"sql.timeWatermark":s==="auto-case"?"sql.autoCase":s==="entity-expansion"?"sql.entityExpansion":s==="total"?"sql.total":s==="computation"?"sql.computation":"sql.semanticResolution"),logicform:n,sql:t.sql,parameters:[...t.parameters],displaySql:e.displayQuery(t.sql,t.parameters)}),Ro=(t,e)=>{if(e.connectionId)for(const r of Ae(t)){const n=fo(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})}},Tf=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 No(o))e.add(i)};return r(t),[...e]},No=t=>{const e=t.schema?[t.schema]:[];return t.pred&&typeof t.pred=="object"&&!Array.isArray(t.pred)?[...e,...No(t.pred)]:Array.isArray(t.pred)?[...e,...t.pred.flatMap(r=>typeof r=="string"?[]:No(r))]:e},Pf=async(t,e)=>{const r=e.locale??"zh-CN",n=e.localeRegistry??lr(ya(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&&Af(t);const u=a?ma(t,e.schemas):t,c={...e,locale:r,localeRegistry:n,schemas:_f(e.schemas,o,a)},p=Xr.now(),l=c.semanticTypes===void 0?no(o):c.semanticTypesResolved?c.semanticTypes:ws(c.semanticTypes,o),f=c.operators??Le(o);if(c.operators&&!c.operatorsResolved)for(const C of o)for(const F of C.operators??[])if(f.has(F.name)){if(f.get(F.name)!==F)throw new d("PLUGIN_OPERATOR_ALREADY_REGISTERED",`Plugin Operator is already registered: ${F.name}`,{operator:F.name,plugin:C.name})}else f.register(F);const m=c.schemaMappings,y=new Date,h=new Map,g=new Map,A=[],w=new Set,S=C=>{const F=JSON.stringify(C);w.has(F)||(w.add(F),A.push(C),E={...E,schemaMappingSelections:[...A]})};let E={provider:c.provider.kind};const $=[],R=new Map;c.connectionId&&R.set(c.connectionId,c.provider.kind);const O=(C,F,Z,j=F,le=c.provider,_=c.connectionId)=>{_&&_!==kt&&R.set(_,le.kind),$.push(Of(vs(C),le,F,Z,c.locale??"zh-CN",n,j,_)),E={...E,sqls:[...$],providers:[...R].map(([I,b])=>({connectionId:I,provider:b}))}},D=async(C,F={})=>{E={...E,...F},await Nf(c.onProgress,C,E)},M=C=>ys(nc(C,c.schemas),l,o),z=new Map,q=C=>{const F=z.get(C);return F||(Fe(c.permissions,C),M(C))},v=C=>{if(C.schema)return q(C.schema);if(C.from)return v(C.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},k=C=>{if(C.schema)return M(C.schema);if(C.from)return k(C.from);throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain a physical schema leaf")},H={plugins:o,resolveSchema:q,onSchemaMappingSelection:S,...c.connectionId?{preferredConnectionId:c.connectionId}:{},canUsePropertyRowIdentity:(C,F)=>at(c.permissions,C.id,F)},ae=(C,F)=>{const Z=Hi(Oe(C,v(C),f,m,H),F);return z.set(Z.id,Z),Z},te=async(C,F,Z)=>{const j=`${C.id}:${F.id}:${Z.toISOString()}`,le=h.get(j);if(le)return le;const _=(async()=>{const I=me(o).find(ee=>ee.createTimeWatermarkLogicform)?.createTimeWatermarkLogicform;if(!I)return;const b=I({logicform:u,rootSchema:C,rootProperty:F,requestedUpperBound:Z,now:y,...c.timeWatermark?{defaultPolicy:c.timeWatermark}:{},resolveSchema:q,inferPropertyPath:(ee,J,B)=>Us(ee,J,B,q)}),T=ct(b,c.permissions,q,!1,new Set,o),P=await st(T,C,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,resolveFromSchema:ae}),Y=Oe(P,C,f,m,H);let K;if(ir(Y,m)){const ee=c.providerForConnection;if(!ee)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated timeWatermark resolution requires a provider resolver");K=(await Qr(Y,{logicform:P,operators:f,schemaMappings:m,providerForConnection:ee,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:B,logicform:ye,provider:ce,connectionId:De})=>O(B,"semantic-resolution",ye,"time-watermark",ce,De)})).rows}else{Ro(Y,c);const ee=he(Y,c.provider,f);O(ee,"semantic-resolution",P,"time-watermark"),K=await Re(ee,Ae(Y),c)}const re=K[0]?.__timeWatermark__??Object.values(K[0]??{})[0];if(re==null||!(re instanceof Date)&&typeof re!="string"&&typeof re!="number")return;const L=re instanceof Date?re:new Date(re);return Number.isNaN(L.getTime())?void 0:L})();return h.set(j,_),_},fe=async(C,F,Z)=>{const j=JSON.stringify([C.id,F,Z??null]),le=g.get(j);if(le)return le;const _=(async()=>{const I={version:"2.0",schema:C.id,...Z?{query:Z}:{},preds:[{name:"__autoCaseMin__",operator:"$min",pred:F},{name:"__autoCaseMax__",operator:"$max",pred:F},{name:"__autoCaseCount__",operator:"$count",pred:F}]},b=await st(I,C,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,resolveFromSchema:ae}),T=Oe(b,C,f,m,H);let P;if(ir(T,m)){const ye=c.providerForConnection;if(!ye)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated automatic bucket resolution requires a provider resolver");P=(await Qr(T,{logicform:b,operators:f,schemaMappings:m,providerForConnection:ye,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:De,logicform:lt,provider:pt,connectionId:Je})=>O(De,"semantic-resolution",lt,"auto-case",pt,Je)})).rows}else{Ro(T,c);const ye=he(T,c.provider,f);O(ye,"semantic-resolution",b,"auto-case"),P=await Re(ye,Ae(T),c)}const Y=P[0],K=Y?.__autoCaseMin__,re=Y?.__autoCaseMax__,L=Y?.__autoCaseCount__;if(K==null||re===null||re===void 0||L===null||L===void 0||Number(L)===0)return{empty:!0};const ee=Number(K),J=Number(re),B=Number(L);if(!Number.isFinite(ee)||!Number.isFinite(J)||!Number.isSafeInteger(B)||B<0)throw new d("INVALID_AUTO_CASE_STATS","Automatic bucket statistics must contain finite min/max and a non-negative integer count",{min:K,max:re,count:L});return{min:ee,max:J,count:B}})();return g.set(j,_),_};try{c.signal?.throwIfAborted(),oo(u),await D({stage:"started",logicform:u}),Ql(c.permissions,M);const C=v(u);await D({stage:"validated",schema:C});const F=ct(u,c.permissions,q,!0,new Set,o),Z=await st(F,C,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,resolveFromSchema:ae,canProjectProperty:(N,x)=>at(c.permissions,N.id,x),requestTimeWatermark:te,requestAutoCaseBounds:fe});await D({stage:"normalized",normedLogicform:Z},{normedLogicform:Z});const j=Oe(Z,C,f,m,H),le=ir(j,m);le||Ro(j,c);const _=j.columnProperties??[],I=Yi(j,C);z.set(I.id,I),await D({stage:"planned",plan:j},{schema:I});const b=ki(j,C,c.provider,f,c.providerForConnection);if(await D({stage:"lineage",lineage:b},{lineage:b}),le){const N=c.providerForConnection;if(!N)throw new d("DATABASE_CONNECTION_ROUTER_REQUIRED","Federated execution requires a provider resolver for every physical connection");const x=await Qr(j,{logicform:Z,operators:f,schemaMappings:m,providerForConnection:N,maxMaterializedRows:c.federation?.maxMaterializedRows??1e5,...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:({compiled:Ee,type:se,logicform:oe,provider:$e,connectionId:pe})=>O(Ee,se,oe,se,$e,pe)});await D({stage:"compiled",sqls:[...$]},{sqls:[...$]}),await D({stage:"executing",provider:"duckdb",connectionId:kt}),await D({stage:"hydrating"});const G=x.connections.length===1?x.connections[0]?.connectionId:void 0,U=await Gs(x.rows,_,{semanticTypes:l,plugins:o,resolveSchema:q,fetchEntities:Ee=>Fs(Ee,{version:Z.version,operators:f,schemaMappings:m,semanticTypes:l,plugins:o,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,...c.permissions?{permissions:c.permissions}:{},provider:c.provider,providerForConnection:N,...G?{preferredConnectionId:G}:{},...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:(se,oe,$e,pe)=>O(se,"semantic-resolution",oe,"entity-expansion",$e,pe)})}),Q=zn(U,j.rowIdentity);return await D({stage:"result",result:Q},{result:Q,total:x.total,sqls:[...$],providers:x.connections}),await D({stage:"completed",durationMs:Xr.now()-p}),{result:Q,total:x.total,schema:I,normedLogicform:Z,sqls:[...$],lineage:b,provider:"duckdb",providers:x.connections,schemaMappingSelections:[...A]}}const T=Pr(Z,j,C,f,q,void 0,r,n.translator(r)),P=async(N,x)=>{const G=x&&N.logicform.schema===x.id?x:v(N.logicform),U=N.prepare?await st(ct(N.logicform,c.permissions,q,!0,new Set,o),G,{semanticTypes:l,operators:f,plugins:o,now:y,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,resolveFromSchema:ae,canProjectProperty:(se,oe)=>at(c.permissions,se.id,oe),requestTimeWatermark:te}):N.logicform,Q=Oe(U,G,f,m,H),Ee=Pr(U,Q,G,f,q,N.logicform,r,n.translator(r));if(Ee){if(Ee.length!==1)throw new Error("A generated component must produce exactly one execution unit");const se=Ee[0];if("logicform"in se){const pe=await P(se,G),ft=pe.component.mapResult,je=N.mapResult;return{...pe,component:{...N,logicform:pe.component.logicform,...ft||je?{mapResult:xe=>{const Xe=ft?.(xe)??[...xe];return je?.(Xe)??[...Xe]}}:{}}}}if("mergeRow"in se)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","A JavaScript composite metric cannot currently be nested as a generated component");const oe=await Promise.all(se.components.map(async pe=>({name:pe.name,prepared:await P(Gr(pe)),...pe.groupKeyShifts?{groupKeyShifts:pe.groupKeyShifts}:{},...pe.joinKeys?{joinKeys:pe.joinKeys}:{}}))),$e=Or(se,oe.map(({name:pe,prepared:ft,...je})=>({name:pe,plan:ft.plan,...je})),Q,se.outputName,c.provider,f);return{component:{...N,logicform:U},plan:Q,compiled:$e,sources:rr(oe.map(({prepared:pe})=>pe.sources))}}return{component:{...N,logicform:U},plan:Q,compiled:he(Q,c.provider,f),sources:Ae(Q)}},Y=async(N,x)=>{const G=Pr(N,x,v(N),f,q,void 0,r,n.translator(r));if(!G)return{compiled:he(x,c.provider,f),sources:Ae(x)};const U=await Promise.all(G.map(async Q=>{if("logicform"in Q){const oe=await P(Q);return{plan:oe.plan,compiled:oe.compiled,outputs:oe.plan.projections.map(({name:$e})=>$e).filter($e=>!x.groupBy.some(pe=>pe.name===$e))}}if("mergeRow"in Q)throw new d("UNSUPPORTED_NESTED_JS_COMPONENT","JavaScript composite metrics cannot be used as a derived source");const Ee=await Promise.all(Q.components.map(async oe=>{const $e=await P(Gr(oe));return{name:oe.name,plan:$e.plan,...oe.joinKeys?{joinKeys:oe.joinKeys}:{},...oe.groupKeyShifts?{groupKeyShifts:oe.groupKeyShifts}:{}}})),se=Or(Q,Ee,x,Q.outputName,c.provider,f);return{plan:x,compiled:se,outputs:[Q.outputName,...Q.components.map(oe=>oe.name)]}}));return{compiled:Hn(U,x,c.provider,f),sources:rr(U.map(({plan:Q})=>Ae(Q)))}},K=new WeakMap,re=async N=>{if(!N.sourcePlan||!N.sourceLogicform)return he(N,c.provider,f);const x=k(N.sourceLogicform),G=Pr(N.sourceLogicform,N.sourcePlan,x,f,q,void 0,r,n.translator(r));if(G?.some(oe=>"mergeRow"in oe)){const oe=K.get(N.sourcePlan);if(oe){const ie={...N};delete ie.sourcePlan,delete ie.sourceLogicform;const Ge=he({...ie,sourceSql:oe.sql,source:N.source},c.provider,f,oe.parameters.length);return{sql:Ge.sql,parameters:[...oe.parameters,...Ge.parameters]}}const $e=await Promise.all(G.map(async ie=>{if("logicform"in ie)return{kind:"query",unit:ie,prepared:await P(ie,x)};const Ge=await Promise.all(ie.components.map(async ge=>({input:ge,prepared:await P(Gr(ge),x)})));return"mergeRow"in ie?{kind:"js",unit:ie,components:Ge}:{kind:"component",unit:ie,components:Ge,compiled:Or(ie,Ge.map(({input:ge,prepared:Ce})=>({name:ge.name,plan:Ce.plan,...ge.joinKeys?{joinKeys:ge.joinKeys}:{},...ge.groupKeyShifts?{groupKeyShifts:ge.groupKeyShifts}:{}})),N.sourcePlan,ie.outputName,c.provider,f)}})),pe=N.sourcePlan.groupBy.map(({name:ie})=>ie),ft=await Promise.all($e.map(async ie=>{if(ie.kind==="query"){O(ie.prepared.compiled,"computation",ie.prepared.component.logicform);const ge=await Re(ie.prepared.compiled,ie.prepared.sources,c),Ce=await ot(ge,ie.prepared.plan.projections,f);return ie.unit.mapResult?.(Ce)??Ce}if(ie.kind==="component")return O(ie.compiled,"computation",N.sourceLogicform),Re(ie.compiled,rr(ie.components.map(({prepared:ge})=>ge.sources)),c);const Ge=await Promise.all(ie.components.map(async({input:ge,prepared:Ce})=>{O(Ce.compiled,"computation",Ce.component.logicform);const Aa=await Re(Ce.compiled,Ce.sources,c),Lo=await ot(Aa,Ce.plan.projections,f);return ge.mapResult?.(Lo)??Lo}));return Promise.all(Jn(Ge,pe).map(async ge=>({...ge,[ie.unit.outputName]:await ie.unit.mergeRow(ge)})))})),je=Xn(ft,N.sourcePlan),xe=c.federation?.maxMaterializedRows??1e5;if(!Number.isSafeInteger(xe)||xe<1)throw new d("INVALID_FEDERATION_LIMIT","federation.maxMaterializedRows must be a positive safe integer",{maxMaterializedRows:xe});if(je.length>xe)throw new d("MATERIALIZED_RESULT_LIMIT_EXCEEDED",`Nested component materialized ${je.length} rows; maximum is ${xe}`,{materializedRowCount:je.length,maxMaterializedRows:xe});const Xe=bf(je,N.sourcePlan,c.provider);K.set(N.sourcePlan,Xe);const Jr={...N};delete Jr.sourcePlan,delete Jr.sourceLogicform;const Po=he({...Jr,sourceSql:Xe.sql,source:N.source},c.provider,f,Xe.parameters.length);return{sql:Po.sql,parameters:[...Xe.parameters,...Po.parameters]}}const U=await Y(N.sourceLogicform,N.sourcePlan),Q={...N};delete Q.sourcePlan,delete Q.sourceLogicform;const Ee={...Q,sourceSql:U.compiled.sql,source:N.source},se=he(Ee,c.provider,f,U.compiled.parameters.length);return{sql:se.sql,parameters:[...U.compiled.parameters,...se.parameters]}},L=T?await Promise.all(T.map(async N=>{if("logicform"in N)return{kind:"query",unit:N,...await P(N)};const x=await Promise.all(N.components.map(async U=>({name:U.name,prepared:await P(Gr(U)),...U.groupKeyShifts?{groupKeyShifts:U.groupKeyShifts}:{},...U.joinKeys?{joinKeys:U.joinKeys}:{}})));if("mergeRow"in N)return{kind:"js",unit:N,components:x.map(({prepared:U})=>U)};const G=x.map(({name:U,prepared:Q,...Ee})=>({name:U,plan:Q.plan,...Ee}));return{kind:"component",unit:N,plan:j,compiled:Or(N,G,j,N.outputName,c.provider,f),sources:rr(x.map(({prepared:U})=>U.sources))}})):void 0,ee=L&&Rf(L,m,j)?L.map(N=>{const x=new Set(j.groupBy.map(({name:U})=>U));if(N.kind==="query")return{plan:N.plan,compiled:N.compiled,outputs:N.plan.projections.map(({name:U})=>U).filter(U=>!x.has(U))};const G=N.unit.outputName;if(!G)throw new d("INVALID_COMPONENT_PLAN","Component output projection is missing");return{plan:N.plan,compiled:N.compiled,outputs:[G,...N.unit.components.map(U=>U.name)]}}):void 0,J=ee?Hn(ee,j,c.provider,f):void 0,B=L?void 0:await re(j),ye=wo(j),ce=j.pagination&&(J||B)?Eo(ee?Hn(ee,ye,c.provider,f):await re(ye),c.provider):void 0;if(J)O(J,"computation",Z);else if(L)for(const N of L)if(N.kind==="js")for(const x of N.components)O(x.compiled,"computation",x.component.logicform);else O(N.compiled,"computation",Z);else O(B,"computation",Z);ce&&O(ce,"total",of(Z)),await D({stage:"compiled",sqls:[...$]},{sqls:[...$]}),await D({stage:"executing",provider:c.provider.kind});const De=J?await(async()=>{const N=rr([...L.map(Q=>Q.sources),Ae(j)]),[x,G]=await Promise.all([Re(J,N,c),ce?Re(ce,N,c):Promise.resolve(void 0)]),U=await ot(x,j.projections,f);return{rows:U,total:G?Hr(G):U.length}})():L?await(async()=>{const N=await Promise.all(L.map(async G=>{if(G.kind==="js"){const Ee=await Promise.all(G.components.map(async se=>{const oe=await Re(se.compiled,se.sources,c),$e=await ot(oe,se.plan.projections,f);return se.component.mapResult?.($e)??$e}));return Promise.all(Jn(Ee,j.groupBy.map(({name:se})=>se)).map(async se=>{const oe=await G.unit.mergeRow(se);return{...se,[G.unit.outputName]:oe}}))}const U=await Re(G.compiled,G.sources,c),Q=G.kind==="query"?await ot(U,G.plan.projections,f):U;return G.kind==="query"?G.unit.mapResult?.(Q)??Q:Q})),x=Xn(N,ye);return{rows:j.pagination?Xn(N,j):x,total:x.length}})():await(async()=>{const N=Ae(j),[x,G]=await Promise.all([Re(B,N,c),ce?Re(ce,N,c):Promise.resolve(void 0)]),U=await ot(x,j.projections,f);return{rows:U,total:G?Hr(G):U.length}})(),{rows:lt,total:pt}=De;await D({stage:"hydrating"});const Je=await Gs(lt,_,{semanticTypes:l,plugins:o,resolveSchema:q,fetchEntities:N=>Fs(N,{version:Z.version,operators:f,schemaMappings:m,semanticTypes:l,plugins:o,...c.locale?{locale:c.locale}:{},localeRegistry:n,resolveSchema:q,...c.permissions?{permissions:c.permissions}:{},provider:c.provider,...c.connectionId?{preferredConnectionId:c.connectionId}:{},...c.providerForConnection?{providerForConnection:c.providerForConnection}:{},...c.cache?{cache:c.cache}:{},...c.signal?{signal:c.signal}:{},onCompiled:(x,G,U,Q)=>O(x,"semantic-resolution",G,"entity-expansion",U,Q)})}),Qe=zn(Je,j.rowIdentity);return await D({stage:"result",result:Qe},{result:Qe,total:pt,sqls:[...$]}),await D({stage:"completed",durationMs:Xr.now()-p}),{result:Qe,total:pt,schema:I,normedLogicform:Z,sqls:[...$],lineage:b,provider:c.provider.kind,providers:[...R].map(([N,x])=>({connectionId:N,provider:x})),schemaMappingSelections:[...A],...Z.output?await(async()=>{const N=mi(Z.output?.type??"",o);return N?{output:await N.handle({rows:Qe,logicform:Z,schema:I})}:{}})():{}}}catch(C){const F=ha(C);try{await D({stage:"failed",error:F})}catch{}throw F}},Lf=async(t,e)=>{let r={};const n=e.locale??"zh-CN",o=lr(ya(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 A of e.connections){if(A.id.trim().length===0)throw new d("INVALID_DATABASE_CONNECTION","Database connection id must not be empty");if(i.has(A.id))throw new d("DATABASE_CONNECTION_ALREADY_REGISTERED",`Database connection id is duplicated: ${A.id}`,{connectionId:A.id});i.set(A.id,A)}const s=new Un(e.schemaMappings,e.plugins),u=Tf(t).flatMap(A=>s.list(A)).map(({connectionId:A})=>A)[0];if(!u)throw new d("LOGICFORM_SCHEMA_REQUIRED","A LogicForm must contain at least one physical Schema leaf");const c=A=>{const w=i.get(A);if(!w)throw new d("DATABASE_CONNECTION_NOT_FOUND",`Database connection is not registered: ${A}`,{connectionId:A});return Yr(w,e.providerRegistry)},p=c(u);r={provider:p.kind};const l=Le(e.plugins),f=e.operators===void 0?[]:Array.isArray(e.operators)?e.operators:[e.operators],m=new wr(f),y=new Set(m.definitions().map(({name:A})=>A)),h=f.length===0?l:new wr([...l.definitions().filter(({name:A})=>!y.has(A)),...m.definitions()]),g=e.semanticTypes===void 0?no(e.plugins):ws(e.semanticTypes,e.plugins??[]);return await Pf(t,{...e,schemaMappings:s,locale:n,localeRegistry:o,provider:p,providerForConnection:c,operators:h,operatorsResolved:!0,semanticTypes:g,semanticTypesResolved:!0,connectionId:u,onProgress:async A=>{r=A.partialResult,await e.onProgress?.(A)}})}catch(i){return If(i,t,r,n,o)}},ga="semanticdb_calendar_dates",Oo="semanticdb_calendar_relations",dt={dates:"__sdb_calendar_dates",relations:"__sdb_calendar_relations"},To=t=>`${typeof t}:${String(t)}`,Df=(t,e)=>{const r=typeof t=="number"?t:Number(t),n=typeof e=="number"?e:Number(e);return Number.isFinite(r)&&Number.isFinite(n)?r-n:String(t).localeCompare(String(e))},$a=(t,e,r)=>{const n=r.filter(u=>u.calendar===e.calendar&&u.grain===e.grain&&u.relation===e.relation&&(e.key===void 0||u.key===e.key)),o=new Map(n.map(u=>[To(u.sourceDateId),u])),i=t.flatMap(u=>{const c=o.get(To(u))?.targetDateId;return c==null?[]:[c]}),s=[...new Map(i.map(u=>[To(u),u])).values()].sort(Df),a=[];for(const u of s){const c=a[a.length-1];if(c&&typeof c.end=="number"&&typeof u=="number"&&u===c.end+1)c.end=u;else if(c&&String(c.end).match(/^\d{8}$/)&&String(u).match(/^\d{8}$/)){const p=Number(c.end),l=Number(u),f=new Date(Date.UTC(Math.floor(p/1e4),Math.floor(p/100)%100-1,p%100));f.setUTCDate(f.getUTCDate()+1);const m=new Date(Date.UTC(Math.floor(l/1e4),Math.floor(l/100)%100-1,l%100));if(f.getTime()===m.getTime()){c.end=u;continue}a.push({start:u,end:u})}else a.push({start:u,end:u})}return{dateIds:s,ranges:a}},Cf=async(t,e,r)=>$a(t,e,await r.loadRelations(t,e)),kf=(t,e)=>t.filter(r=>Object.entries(e).every(([n,o])=>r[n]===o)).map(r=>r.dateId),Uf=["source_date_id","target_date_id","calendar","grain","relation","relation_key"];class Mf{provider;constructor(e){this.provider=e}async loadRelations(e,r){if(e.length===0)return[];const n=[...e,r.calendar,r.grain,r.relation];r.key!==void 0&&n.push(r.key);const o=e.map((c,p)=>this.provider.parameter(p,c)),i=c=>this.provider.parameter(c,n[c]),s=c=>this.provider.quoteIdentifier(c),a=[`${s("source_date_id")} IN (${o.join(", ")})`,`${s("calendar")} = ${i(e.length)}`,`${s("grain")} = ${i(e.length+1)}`,`${s("relation")} = ${i(e.length+2)}`];return r.key!==void 0&&a.push(`${s("relation_key")} = ${i(e.length+3)}`),(await this.provider.execute({sql:`SELECT ${Uf.map(s).join(", ")} FROM ${s(Oo)} WHERE ${a.join(" AND ")}`,parameters:n})).map(c=>({sourceDateId:c.source_date_id,targetDateId:c.target_date_id,calendar:String(c.calendar),grain:String(c.grain),relation:String(c.relation),...typeof c.relation_key=="string"||typeof c.relation_key=="number"?{key:String(c.relation_key)}:{}}))}}const qf={[dt.dates]:{id:dt.dates,name:dt.dates,type:"entity",source:ga,properties:[{id:"date_id",name:"date_id",type:"id",primal_type:"string"},{id:"calendar",name:"calendar",type:"string",primal_type:"string"},{id:"grain",name:"grain",type:"string",primal_type:"string"},{id:"period_key",name:"period_key",type:"string",primal_type:"string"},{id:"relative_day",name:"relative_day",type:"int",primal_type:"number"}]},[dt.relations]:{id:dt.relations,name:dt.relations,type:"entity",source:Oo,properties:[{id:"source_date_id",name:"source_date_id",type:"string",primal_type:"string"},{id:"target_date_id",name:"target_date_id",type:"string",primal_type:"string"},{id:"calendar",name:"calendar",type:"string",primal_type:"string"},{id:"grain",name:"grain",type:"string",primal_type:"string"},{id:"relation",name:"relation",type:"string",primal_type:"string"},{id:"relation_key",name:"relation_key",type:"string",primal_type:"string"}]}},jf=Object.freeze({execute:Lf,close:ia});export{ga as CALENDAR_DATES_TABLE,Oo as CALENDAR_RELATIONS_TABLE,dt as CALENDAR_SYSTEM_SCHEMA_IDS,Xp as DBConnector,on as LocaleRegistry,jf as Logicform,wr as OperatorRegistry,qi as PlannerSemanticRegistry,Mf as ProviderCalendarRelationStore,ra as ProviderRegistry,Un as SchemaMappingRegistry,d as SemanticDBError,Zn as SemanticTypeRegistry,Rd as builtinOperators,Dn as builtinSemanticTypes,qf as calendarSystemSchemas,lr as createLocaleRegistry,Le as createOperatorRegistry,ji as createPlannerSemanticRegistry,no as createSemanticTypeRegistry,pr as defaultLocaleRegistry,Zo as enUS,Dd as fromYiAskSchemaMapping,$a as resolveCalendarPeriod,Cf as resolveCalendarPeriodFromStore,Pi as resolveOperator,ys as resolveSchema,kf as selectCalendarDates,ms as validateResolvedSchema,ei as zhCN};
|