@malloydata/render 0.0.312 → 0.0.314
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/module/index.mjs +40 -40
- package/dist/module/index.umd.js +4 -4
- package/package.json +5 -5
package/dist/module/index.mjs
CHANGED
|
@@ -119891,7 +119891,7 @@ class Jrt extends Tg.Dialect {
|
|
|
119891
119891
|
return "UNUSED";
|
|
119892
119892
|
}
|
|
119893
119893
|
sqlSumDistinct(e, r, i) {
|
|
119894
|
-
const s = `CONCAT(${e}, '')`, o = `CAST(CONV(SUBSTRING(MD5(${s}), 1, 16), 16, 10) AS DECIMAL(
|
|
119894
|
+
const s = `CONCAT(${e}, '')`, o = `CAST(CONV(SUBSTRING(MD5(${s}), 1, 16), 16, 10) AS DECIMAL(55, 10)) * 4294967296`, a = `CAST(CONV(SUBSTRING(MD5(${s}), 16, 8), 16, 10) AS DECIMAL(55, 10))`, u = `(${o} + ${a})`, l = `CAST(COALESCE(${r},0) as DECIMAL(55, 10))`, c = `(SUM(DISTINCT ${u} + ${l}) - SUM(DISTINCT ${u}))`;
|
|
119895
119895
|
if (i === "SUM")
|
|
119896
119896
|
return c;
|
|
119897
119897
|
if (i === "AVG")
|
|
@@ -122517,7 +122517,7 @@ const Nv = /* @__PURE__ */ bZ(Kve);
|
|
|
122517
122517
|
return m.length === 1 ? `${m[0]}${y}` : `(${m.join(" AND ")})${y}`;
|
|
122518
122518
|
}
|
|
122519
122519
|
t.FilterCompilers = {
|
|
122520
|
-
compile(m, g, y, v) {
|
|
122520
|
+
compile(m, g, y, v, E = {}) {
|
|
122521
122521
|
if (g === null)
|
|
122522
122522
|
return "true";
|
|
122523
122523
|
if (m === "string" && (0, e.isStringFilter)(g))
|
|
@@ -122527,7 +122527,7 @@ const Nv = /* @__PURE__ */ bZ(Kve);
|
|
|
122527
122527
|
if (m === "boolean" && (0, e.isBooleanFilter)(g))
|
|
122528
122528
|
return t.FilterCompilers.booleanCompile(g, y, v);
|
|
122529
122529
|
if ((m === "date" || m === "timestamp") && (0, e.isTemporalFilter)(g))
|
|
122530
|
-
return t.FilterCompilers.temporalCompile(g, y, v, m);
|
|
122530
|
+
return t.FilterCompilers.temporalCompile(g, y, v, m, E);
|
|
122531
122531
|
throw new Error("INTERNAL ERROR: No filter compiler for " + m);
|
|
122532
122532
|
},
|
|
122533
122533
|
numberCompile(m, g, y) {
|
|
@@ -122644,14 +122644,14 @@ const Nv = /* @__PURE__ */ bZ(Kve);
|
|
|
122644
122644
|
}
|
|
122645
122645
|
},
|
|
122646
122646
|
// mtoy todo figure out what to do about dates
|
|
122647
|
-
temporalCompile(m, g, y, v) {
|
|
122648
|
-
return new p(g, y, v).compile(m);
|
|
122647
|
+
temporalCompile(m, g, y, v, E = {}) {
|
|
122648
|
+
return new p(g, y, v, E).compile(m);
|
|
122649
122649
|
}
|
|
122650
122650
|
};
|
|
122651
122651
|
const u = "yyyy", l = `${u}-LL`, c = `${l}-dd`, f = `${c} HH`, d = `${f}:mm`, x = `${d}:ss`;
|
|
122652
122652
|
class p {
|
|
122653
|
-
constructor(g, y, v = "timestamp") {
|
|
122654
|
-
this.expr = g, this.timetype = v, this.d = y;
|
|
122653
|
+
constructor(g, y, v = "timestamp", E = {}) {
|
|
122654
|
+
this.expr = g, this.timetype = v, this.d = y, this.qi = E;
|
|
122655
122655
|
}
|
|
122656
122656
|
time(g) {
|
|
122657
122657
|
return this.timetype === "timestamp" ? g : this.d.sqlCast({}, {
|
|
@@ -122755,7 +122755,7 @@ const Nv = /* @__PURE__ */ bZ(Kve);
|
|
|
122755
122755
|
typeDef: { type: "timestamp" },
|
|
122756
122756
|
literal: g
|
|
122757
122757
|
};
|
|
122758
|
-
return { ...y, sql: this.d.sqlLiteralTime(
|
|
122758
|
+
return this.qi.queryTimezone && (y.timezone = this.qi.queryTimezone), { ...y, sql: this.d.sqlLiteralTime(this.qi, y) };
|
|
122759
122759
|
}
|
|
122760
122760
|
nowExpr() {
|
|
122761
122761
|
return {
|
|
@@ -122785,7 +122785,7 @@ const Nv = /* @__PURE__ */ bZ(Kve);
|
|
|
122785
122785
|
e: (0, r.mkTemporal)(g, "timestamp"),
|
|
122786
122786
|
units: "day_of_week"
|
|
122787
122787
|
};
|
|
122788
|
-
return { ...y, sql: this.d.sqlTimeExtractExpr(
|
|
122788
|
+
return { ...y, sql: this.d.sqlTimeExtractExpr(this.qi, y) };
|
|
122789
122789
|
}
|
|
122790
122790
|
nowDot(g) {
|
|
122791
122791
|
const y = {
|
|
@@ -122793,7 +122793,7 @@ const Nv = /* @__PURE__ */ bZ(Kve);
|
|
|
122793
122793
|
e: this.nowExpr(),
|
|
122794
122794
|
units: g
|
|
122795
122795
|
};
|
|
122796
|
-
return { ...y, sql: this.d.sqlTruncExpr(
|
|
122796
|
+
return { ...y, sql: this.d.sqlTruncExpr(this.qi, y) };
|
|
122797
122797
|
}
|
|
122798
122798
|
thisUnit(g) {
|
|
122799
122799
|
const y = this.nowDot(g), v = this.delta(y, "+", "1", g);
|
|
@@ -122863,10 +122863,10 @@ const Nv = /* @__PURE__ */ bZ(Kve);
|
|
|
122863
122863
|
}
|
|
122864
122864
|
weekdayMoment(g, y) {
|
|
122865
122865
|
const v = y || "last", E = this.dayofWeek(this.nowExpr()), _ = this.thisUnit("day").begin, A = g - 1, S = `(${E.sql}-1)`;
|
|
122866
|
-
let b;
|
|
122867
|
-
v === "next" ? b = `${this.mod7(`${A}-${S}+6`)}+1` : b = `${this.mod7(`${S}-${A}+6`)}+1
|
|
122868
|
-
const
|
|
122869
|
-
return { begin:
|
|
122866
|
+
let b, C;
|
|
122867
|
+
v === "next" ? (b = `${this.mod7(`${A}-${S}+6`)}+1`, C = `${this.mod7(`${A}-${S}+6`)}+2`) : (b = `${this.mod7(`${S}-${A}+6`)}+1`, C = `${this.mod7(`${S}-${A}+6`)}`);
|
|
122868
|
+
const T = this.delta(_, v === "next" ? "+" : "-", b, "day"), D = this.delta(_, v === "next" ? "+" : "-", C, "day");
|
|
122869
|
+
return { begin: T, end: D.sql };
|
|
122870
122870
|
}
|
|
122871
122871
|
}
|
|
122872
122872
|
t.TemporalFilterCompiler = p;
|
|
@@ -123013,51 +123013,51 @@ function Qo(t, e, r, i = new As.GenerateState()) {
|
|
|
123013
123013
|
case "compositeField":
|
|
123014
123014
|
return "{COMPOSITE_FIELD}";
|
|
123015
123015
|
case "filterMatch":
|
|
123016
|
-
return ost(e, a);
|
|
123016
|
+
return ost(e, a, u);
|
|
123017
123017
|
case "filterLiteral":
|
|
123018
123018
|
return "INTERNAL ERROR FILTER EXPRESSION VALUE SHOULD NOT BE USED";
|
|
123019
123019
|
default:
|
|
123020
123020
|
throw new Error(`Internal Error: Unknown expression node '${a.node}' ${JSON.stringify(a, void 0, 2)}`);
|
|
123021
123021
|
}
|
|
123022
123022
|
}
|
|
123023
|
-
function ost(t, e) {
|
|
123024
|
-
var
|
|
123025
|
-
let
|
|
123026
|
-
for (;
|
|
123027
|
-
|
|
123028
|
-
if (
|
|
123029
|
-
const
|
|
123030
|
-
(
|
|
123031
|
-
const
|
|
123032
|
-
if (
|
|
123033
|
-
|
|
123023
|
+
function ost(t, e, r) {
|
|
123024
|
+
var i;
|
|
123025
|
+
let s = e.kids.filterExpr;
|
|
123026
|
+
for (; s.node === "()"; )
|
|
123027
|
+
s = s.e;
|
|
123028
|
+
if (s.node === "parameter") {
|
|
123029
|
+
const u = s.path[0];
|
|
123030
|
+
(i = t.eventStream) === null || i === void 0 || i.emit("source-argument-compiled", { name: u });
|
|
123031
|
+
const l = t.arguments()[u];
|
|
123032
|
+
if (l.value)
|
|
123033
|
+
s = l.value;
|
|
123034
123034
|
else
|
|
123035
|
-
throw new Error(`Parameter ${
|
|
123035
|
+
throw new Error(`Parameter ${u} was expected to be a filter expression`);
|
|
123036
123036
|
}
|
|
123037
|
-
if (
|
|
123037
|
+
if (s.node !== "filterLiteral")
|
|
123038
123038
|
throw new Error("Can only use filter expression literals or parameters as filter expressions");
|
|
123039
|
-
const
|
|
123040
|
-
let
|
|
123039
|
+
const o = s.filterSrc;
|
|
123040
|
+
let a;
|
|
123041
123041
|
switch (e.dataType) {
|
|
123042
123042
|
case "string":
|
|
123043
|
-
|
|
123043
|
+
a = BA.StringFilterExpression.parse(o);
|
|
123044
123044
|
break;
|
|
123045
123045
|
case "number":
|
|
123046
|
-
|
|
123046
|
+
a = BA.NumberFilterExpression.parse(o);
|
|
123047
123047
|
break;
|
|
123048
123048
|
case "boolean":
|
|
123049
|
-
|
|
123049
|
+
a = BA.BooleanFilterExpression.parse(o);
|
|
123050
123050
|
break;
|
|
123051
123051
|
case "date":
|
|
123052
123052
|
case "timestamp":
|
|
123053
|
-
|
|
123053
|
+
a = BA.TemporalFilterExpression.parse(o);
|
|
123054
123054
|
break;
|
|
123055
123055
|
default:
|
|
123056
123056
|
throw new Error(`unsupported filter type ${e.dataType}`);
|
|
123057
123057
|
}
|
|
123058
|
-
if (
|
|
123059
|
-
throw new Error(`Filter expression parse error: ${
|
|
123060
|
-
return ist.FilterCompilers.compile(e.dataType,
|
|
123058
|
+
if (a.log.length > 0)
|
|
123059
|
+
throw new Error(`Filter expression parse error: ${a.log[0]}`);
|
|
123060
|
+
return ist.FilterCompilers.compile(e.dataType, a.parsed, e.kids.expr.sql || "", t.dialect, r);
|
|
123061
123061
|
}
|
|
123062
123062
|
function ast(t, e) {
|
|
123063
123063
|
return new Map(t.params.map((r, i) => {
|
|
@@ -153966,9 +153966,9 @@ class F1e extends fyt.AbstractParseTreeVisitor {
|
|
|
153966
153966
|
return i === void 0 ? (this.illegal(e, `${H7} must have a run statement`), null) : this.visitRunStatement(i);
|
|
153967
153967
|
}
|
|
153968
153968
|
visitRunStatement(e) {
|
|
153969
|
-
const r = e.topLevelAnonQueryDef(), i = this.getQueryDefinition(r.sqExpr()), s = this.getAnnotations(e.topLevelAnonQueryDef().tags());
|
|
153969
|
+
const r = e.topLevelAnonQueryDef(), i = this.getQueryDefinition(r.sqExpr()), s = this.getAnnotations(e.tags()), o = this.getAnnotations(e.topLevelAnonQueryDef().tags()), a = this.combineAnnotations(s, o);
|
|
153970
153970
|
return i !== null ? {
|
|
153971
|
-
annotations:
|
|
153971
|
+
annotations: a,
|
|
153972
153972
|
definition: i
|
|
153973
153973
|
} : null;
|
|
153974
153974
|
}
|
|
@@ -154510,7 +154510,7 @@ function pyt(t) {
|
|
|
154510
154510
|
var $e = {}, IO = {};
|
|
154511
154511
|
Object.defineProperty(IO, "__esModule", { value: !0 });
|
|
154512
154512
|
IO.MALLOY_VERSION = void 0;
|
|
154513
|
-
IO.MALLOY_VERSION = "0.0.
|
|
154513
|
+
IO.MALLOY_VERSION = "0.0.314";
|
|
154514
154514
|
Object.defineProperty($e, "__esModule", { value: !0 });
|
|
154515
154515
|
$e.InMemoryModelCache = $e.CacheManager = $e.CSVWriter = $e.JSONWriter = $e.DataWriter = $e.DataRecord = $e.DataArray = $e.Result = $e.ExploreMaterializer = $e.PreparedResultMaterializer = $e.QueryMaterializer = $e.ModelMaterializer = $e.SingleConnectionRuntime = $e.ConnectionRuntime = $e.Runtime = $e.ExploreField = $e.JoinRelationship = $e.QueryField = $e.Query = $e.StringField = $e.UnsupportedField = $e.JSONField = $e.BooleanField = $e.NumberField = $e.TimestampField = $e.DateField = $e.TimestampTimeframe = $e.DateTimeframe = $e.AtomicField = $e.AtomicFieldType = $e.Explore = $e.SourceRelationship = $e.FixedConnectionMap = $e.InMemoryURLReader = $e.EmptyURLReader = $e.PreparedResult = $e.DocumentCompletion = $e.DocumentSymbol = $e.DocumentPosition = $e.DocumentRange = $e.DocumentTablePath = $e.Parse = $e.PreparedQuery = $e.Model = $e.MalloyError = $e.Malloy = void 0;
|
|
154516
154516
|
const QX = GD, fr = wi, GX = Nv, Q7 = uh, myt = IO, gyt = w1, Qn = ks, yyt = ph, Eyt = Hr, vyt = p_;
|
package/dist/module/index.umd.js
CHANGED
|
@@ -944,7 +944,7 @@ CROSS JOIN UNNEST(ARRAY[CASE WHEN ${e} IS NOT NULL THEN __row_id_almost_${r} END
|
|
|
944
944
|
${s}
|
|
945
945
|
)
|
|
946
946
|
)`}sqlUnnestAlias(e,r,i,s,o,a){return`
|
|
947
|
-
LEFT JOIN ${this.jsonTable(e,i,o)} as ${r} ON 1=1`}sqlUnnestPipelineHead(e,r,i){return this.jsonTable(r,i,e)}sqlSumDistinctHashedKey(e){return"UNUSED"}sqlSumDistinct(e,r,i){const s=`CONCAT(${e}, '')`,o=`CAST(CONV(SUBSTRING(MD5(${s}), 1, 16), 16, 10) AS DECIMAL(
|
|
947
|
+
LEFT JOIN ${this.jsonTable(e,i,o)} as ${r} ON 1=1`}sqlUnnestPipelineHead(e,r,i){return this.jsonTable(r,i,e)}sqlSumDistinctHashedKey(e){return"UNUSED"}sqlSumDistinct(e,r,i){const s=`CONCAT(${e}, '')`,o=`CAST(CONV(SUBSTRING(MD5(${s}), 1, 16), 16, 10) AS DECIMAL(55, 10)) * 4294967296`,a=`CAST(CONV(SUBSTRING(MD5(${s}), 16, 8), 16, 10) AS DECIMAL(55, 10))`,u=`(${o} + ${a})`,l=`CAST(COALESCE(${r},0) as DECIMAL(55, 10))`,c=`(SUM(DISTINCT ${u} + ${l}) - SUM(DISTINCT ${u}))`;if(i==="SUM")return c;if(i==="AVG")return`(${c})/NULLIF(COUNT(DISTINCT CASE WHEN ${r} IS NOT NULL THEN ${e} END),0)`;throw new Error(`Unknown Symmetric Aggregate function ${i}`)}sqlGenerateUUID(){return"CONCAT(ROW_NUMBER() OVER(), UUID())"}sqlFieldReference(e,r,i,s){if(r==="array[scalar]"||r==="record"){let a=`JSON_UNQUOTE(JSON_EXTRACT(${e},'$.${i}'))`;switch(r==="array[scalar]"&&(a=`JSON_UNQUOTE(${e}.\`value\`)`),s){case"string":return`CONCAT(${a}, '')`;case"number":return`CAST(${a} as double)`;case"record":case"array":return`CAST(${a} as JSON)`}}const o=this.sqlMaybeQuoteIdentifier(i);return`${e}.${o}`}sqlCreateFunction(e,r){return`CREATE FUNCTION ${e}(JSONB) RETURNS JSONB AS $$
|
|
948
948
|
${(0,_rt.indent)(r)}
|
|
949
949
|
$$ LANGUAGE SQL;
|
|
950
950
|
`}sqlCreateFunctionCombineLastStage(e){return`SELECT ARRAY((SELECT AS STRUCT * FROM ${e}))
|
|
@@ -967,10 +967,10 @@ Use (?: … ) instead`);if(!Y.lineBreaks&&q.test(`
|
|
|
967
967
|
`))throw new Error("Rule should declare lineBreaks: "+q);ee.push(l(B))}}var V=U&&U.fallback,L=i&&!V?"ym":"gm",P=i||V?"":"|";G===!0&&(L+="u");var j=new RegExp(c(ee)+P,L);return{regexp:j,groups:J,fast:X,error:U||v}}function _(w){var k=E(y(w));return new C({start:k},"start")}function A(w,k,U){var X=w&&(w.push||w.next);if(X&&!U[X])throw new Error("Missing state '"+X+"' (in token '"+w.defaultType+"' of state '"+k+"')");if(w&&w.pop&&+w.pop!=1)throw new Error("pop must be 1 (in token '"+w.defaultType+"' of state '"+k+"')")}function S(w,k){var U=w.$all?y(w.$all):[];delete w.$all;var X=Object.getOwnPropertyNames(w);k||(k=X[0]);for(var Q=Object.create(null),G=0;G<X.length;G++){var J=X[G];Q[J]=y(w[J]).concat(U)}for(var G=0;G<X.length;G++)for(var J=X[G],ee=Q[J],W=Object.create(null),Y=0;Y<ee.length;Y++){var re=ee[Y];if(re.include){var de=[Y,1];if(re.include!==J&&!W[re.include]){W[re.include]=!0;var I=Q[re.include];if(!I)throw new Error("Cannot include nonexistent state '"+re.include+"' (in state '"+J+"')");for(var F=0;F<I.length;F++){var B=I[F];ee.indexOf(B)===-1&&de.push(B)}}ee.splice.apply(ee,de),Y--}}for(var q=Object.create(null),G=0;G<X.length;G++){var J=X[G];q[J]=E(Q[J],!0)}for(var G=0;G<X.length;G++){for(var Z=X[G],V=q[Z],L=V.groups,Y=0;Y<L.length;Y++)A(L[Y],Z,q);for(var P=Object.getOwnPropertyNames(V.fast),Y=0;Y<P.length;Y++)A(V.fast[P[Y]],Z,q)}return new C(q,k)}function b(w){for(var k=typeof Map<"u",U=k?new Map:Object.create(null),X=Object.getOwnPropertyNames(w),Q=0;Q<X.length;Q++){var G=X[Q],J=w[G],ee=Array.isArray(J)?J:[J];ee.forEach(function(W){if(typeof W!="string")throw new Error("keyword must be string (in keyword '"+G+"')");k?U.set(W,G):U[W]=G})}return function(W){return k?U.get(W):U[W]}}var C=function(w,k){this.startState=k,this.states=w,this.buffer="",this.stack=[],this.reset()};C.prototype.reset=function(w,k){return this.buffer=w||"",this.index=0,this.line=k?k.line:1,this.col=k?k.col:1,this.queuedToken=k?k.queuedToken:null,this.queuedText=k?k.queuedText:"",this.queuedThrow=k?k.queuedThrow:null,this.setState(k?k.state:this.startState),this.stack=k&&k.stack?k.stack.slice():[],this},C.prototype.save=function(){return{line:this.line,col:this.col,state:this.state,stack:this.stack.slice(),queuedToken:this.queuedToken,queuedText:this.queuedText,queuedThrow:this.queuedThrow}},C.prototype.setState=function(w){if(!(!w||this.state===w)){this.state=w;var k=this.states[w];this.groups=k.groups,this.error=k.error,this.re=k.regexp,this.fast=k.fast}},C.prototype.popState=function(){this.setState(this.stack.pop())},C.prototype.pushState=function(w){this.stack.push(this.state),this.setState(w)};var T=i?function(w,k){return w.exec(k)}:function(w,k){var U=w.exec(k);return U[0].length===0?null:U};C.prototype._getGroup=function(w){for(var k=this.groups.length,U=0;U<k;U++)if(w[U+1]!==void 0)return this.groups[U];throw new Error("Cannot find token type for matched text")};function D(){return this.value}if(C.prototype.next=function(){var w=this.index;if(this.queuedGroup){var k=this._token(this.queuedGroup,this.queuedText,w);return this.queuedGroup=null,this.queuedText="",k}var U=this.buffer;if(w!==U.length){var J=this.fast[U.charCodeAt(w)];if(J)return this._token(J,U.charAt(w),w);var X=this.re;X.lastIndex=w;var Q=T(X,U),G=this.error;if(Q==null)return this._token(G,U.slice(w,U.length),w);var J=this._getGroup(Q),ee=Q[0];return G.fallback&&Q.index!==w?(this.queuedGroup=J,this.queuedText=ee,this._token(G,U.slice(w,Q.index),w)):this._token(J,ee,w)}},C.prototype._token=function(w,k,U){var X=0;if(w.lineBreaks){var Q=/\n/g,G=1;if(k===`
|
|
968
968
|
`)X=1;else for(;Q.exec(k);)X++,G=Q.lastIndex}var J={type:typeof w.type=="function"&&w.type(k)||w.defaultType,value:typeof w.value=="function"?w.value(k):k,text:k,toString:D,offset:U,lineBreaks:X,line:this.line,col:this.col},ee=k.length;if(this.index+=ee,this.line+=X,X!==0?this.col=ee-G+1:this.col+=ee,w.shouldThrow){var W=new Error(this.formatError(J,"invalid syntax"));throw W}return w.pop?this.popState():w.push?this.pushState(w.push):w.next&&this.setState(w.next),J},typeof Symbol<"u"&&Symbol.iterator){var O=function(w){this.lexer=w};O.prototype.next=function(){var w=this.lexer.next();return{value:w,done:!w}},O.prototype[Symbol.iterator]=function(){return this},C.prototype[Symbol.iterator]=function(){return new O(this)}}return C.prototype.formatError=function(w,k){if(w==null)var U=this.buffer.slice(this.index),w={text:U,offset:this.index,lineBreaks:U.indexOf(`
|
|
969
969
|
`)===-1?0:1,line:this.line,col:this.col};var X=2,Q=Math.max(w.line-X,1),G=w.line+X,J=String(G).length,ee=x(this.buffer,this.line-w.line+X+1).slice(0,5),W=[];W.push(k+" at line "+w.line+" col "+w.col+":"),W.push("");for(var Y=0;Y<ee.length;Y++){var re=ee[Y],de=Q+Y;W.push(d(String(de),J)+" "+re),de===w.line&&W.push(d("",J+w.col+1)+"^")}return W.join(`
|
|
970
|
-
`)},C.prototype.clone=function(){return new C(this.states,this.state)},C.prototype.has=function(w){return!0},{compile:_,states:S,error:Object.freeze({error:!0}),fallback:Object.freeze({fallback:!0}),keywords:b}})})(nfe);var pM=nfe.exports,Ur={};Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.maybeNot=Zrt,Ur.unescape=WE,Ur.escape=eit,Ur.matchOp=tit,Ur.conjoin=nit,Ur.joinNumbers=rit,Ur.mkRange=iit,Ur.mkValues=sit,Ur.numNot=oit,Ur.temporalNot=ait,Ur.joinTemporal=uit,Ur.timeLiteral=lit,Ur.mkUnits=cit;const ol=as;function Zrt(t){const[e,r]=t;return e&&r&&(0,ol.isStringFilter)(r)?{...r,not:!0}:r}function WE(t){return t.replace(/\\(.)/g,"$1")}function eit(t){const e=t.toLowerCase();return e==="null"||e==="empty"?"\\"+t:t.replace(/([,; |()\\%_-])/g,"\\$1")}function QT(t){let e=!1,r=!1,i=0,s=!1;const o=t.length;for(let a=0;a<o;a+=1){const u=t[a];if(u===" "||u===" "){i+=1;continue}i=0,u==="%"?(s=!0,a===0&&(e=!0),r=!0):(r=!1,u==="\\"?a+=1:u==="_"&&(s=!0))}return{hasLike:s,percentEnd:r&&o>1,percentStart:e&&o>1,endSpace:i}}function tit(t){let e=t.trimStart();const{hasLike:r,percentEnd:i,percentStart:s,endSpace:o}=QT(e);if(o>0&&(e=e.slice(0,-o)),r){if(s&&i){const a=e.slice(1,-1);if(!QT(a).hasLike&&a.length>0)return{operator:"contains",values:[WE(a)]}}else if(i){const a=e.slice(0,-1);if(!QT(a).hasLike)return{operator:"starts",values:[WE(a)]}}else if(s){const a=e.slice(1);if(!QT(a).hasLike)return{operator:"ends",values:[WE(a)]}}return{operator:"~",escaped_values:[e]}}return e.toLowerCase()==="null"?{operator:"null"}:e.toLowerCase()==="empty"?{operator:"empty"}:{operator:"=",values:[WE(e)]}}function mM(t,e){var r,i;return t.operator===e.operator&&((r=t.not)!==null&&r!==void 0?r:!1)===((i=e.not)!==null&&i!==void 0?i:!1)}function nit(t,e,r){if(e=e.toLowerCase(),(0,ol.isStringFilter)(t)&&(0,ol.isStringFilter)(r)){if(e===","){if(t.operator==="~"&&mM(t,r))return{...t,escaped_values:[...t.escaped_values,...r.escaped_values]};if((0,ol.isStringCondition)(t)&&mM(t,r))return{...t,values:[...t.values,...r.values]}}const i=e===","?",":e==="|"?"or":e===";"?"and":void 0;if(i)return t.operator===i?{...t,members:[...t.members,r]}:{operator:i,members:[t,r]}}return null}function rit(t,e,r){if(e=e.toLowerCase(),(0,ol.isNumberFilter)(t)&&(0,ol.isNumberFilter)(r)){if(e==="or"&&t.operator==="="&&mM(t,r)){const i={operator:"=",values:[...t.values,...r.values]};return t.not&&(i.not=!0),i}if(e==="and"||e==="or")return t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}}return null}function iit(t,e,r,i){return{operator:"range",startValue:e,startOperator:t==="("?">":">=",endValue:r,endOperator:i===")"?"<":"<="}}function sit(t,e){return{values:[t,...e]}}function oit(t,e){return(0,ol.isNumberFilter)(t)&&e?t.operator==="="?{operator:"!=",values:t.values}:t.operator==="!="?{operator:"=",values:t.values}:{...t,not:!0}:t}function ait(t,e){if((0,ol.isTemporalFilter)(t)&&e){if("not"in t){const r={...t};return t.not?delete r.not:r.not=!0,r}return{...t,not:!0}}return t}function uit(t,e,r){return e=e.toLowerCase(),(0,ol.isTemporalFilter)(t)&&(0,ol.isTemporalFilter)(r)&&(e==="and"||e==="or")?t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}:null}function lit(t,e){const r={moment:"literal",literal:t};return e&&(r.units=e),r}function cit(t){switch(t.toLowerCase()){case"second":case"seconds":return"second";case"minute":case"minutes":return"minute";case"hour":case"hours":return"hour";case"day":case"days":return"day";case"week":case"weeks":return"week";case"month":case"months":return"month";case"quarter":case"quarters":return"quarter";case"year":case"years":return"year"}}var fit=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(hM,"__esModule",{value:!0});function dit(t){return t[0]}const rfe=fit(pM),V2=Ur,xit=rfe.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to"}),Qn=rfe.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:t=>xit(t.toLowerCase())},oparen:"(",cparen:")",obrack:"[",cbrack:"]",comma:",",op:/<=|>=|<|>/,ne:"!=",eq:"=",float:/-?(?:\d+)?\.\d+(?:[Ee][+-]?\d+)?/,numberE:/-?\d+[Ee][+-]?\d+/,integer:/-?\d+/}),hit=Qn.next;Qn.next=(t=>()=>{for(;;){const e=t.call(Qn);if(e===void 0||e.type!=="WS")return e}})(hit);const pit={Lexer:Qn,ParserRules:[{name:"numberFilter",symbols:["numberFilter","conjunction","numberUnary"],postprocess:([t,e,r])=>(0,V2.joinNumbers)(t,e[0].text,r)},{name:"numberFilter",symbols:["numberUnary"],postprocess:t=>t[0]},{name:"numberUnary$ebnf$1",symbols:[Qn.has("NOT")?{type:"NOT"}:NOT],postprocess:dit},{name:"numberUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"numberUnary",symbols:["numberUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,V2.numNot)(e,t)},{name:"clause",symbols:[Qn.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause$ebnf$1",symbols:[]},{name:"clause$ebnf$1",symbols:["clause$ebnf$1","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:["N","clause$ebnf$1"],postprocess:([t,e])=>({operator:"=",...(0,V2.mkValues)(t,e)})},{name:"clause$ebnf$2",symbols:[]},{name:"clause$ebnf$2",symbols:["clause$ebnf$2","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Qn.has("eq")?{type:"eq"}:eq,"N","clause$ebnf$2"],postprocess:([t,e,r])=>({operator:"=",...(0,V2.mkValues)(e,r)})},{name:"clause$ebnf$3",symbols:[]},{name:"clause$ebnf$3",symbols:["clause$ebnf$3","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Qn.has("ne")?{type:"ne"}:ne,"N","clause$ebnf$3"],postprocess:([t,e,r])=>({operator:"!=",...(0,V2.mkValues)(e,r)})},{name:"clause",symbols:[Qn.has("op")?{type:"op"}:op,"N"],postprocess:([t,e])=>({operator:t.text,values:[e]})},{name:"clause",symbols:[Qn.has("oparen")?{type:"oparen"}:oparen,"numberFilter",Qn.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:["openInterval","N",Qn.has("TO")?{type:"TO"}:TO,"N","closeInterval"],postprocess:([t,e,r,i,s])=>(0,V2.mkRange)(t[0].text,e,i,s[0].text)},{name:"numberList",symbols:[Qn.has("comma")?{type:"comma"}:comma,"N"],postprocess:([t,e])=>e},{name:"closeInterval",symbols:[Qn.has("cbrack")?{type:"cbrack"}:cbrack]},{name:"closeInterval",symbols:[Qn.has("cparen")?{type:"cparen"}:cparen]},{name:"openInterval",symbols:[Qn.has("obrack")?{type:"obrack"}:obrack]},{name:"openInterval",symbols:[Qn.has("oparen")?{type:"oparen"}:oparen]},{name:"N$subexpression$1",symbols:[Qn.has("float")?{type:"float"}:float]},{name:"N$subexpression$1",symbols:[Qn.has("numberE")?{type:"numberE"}:numberE]},{name:"N$subexpression$1",symbols:[Qn.has("integer")?{type:"integer"}:integer]},{name:"N",symbols:["N$subexpression$1"],postprocess:([t])=>t[0].text},{name:"conjunction",symbols:[Qn.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Qn.has("AND")?{type:"AND"}:AND]}],ParserStart:"numberFilter"};hM.default=pit;var VE={};Object.defineProperty(VE,"__esModule",{value:!0}),VE.run_parser=git;const mit=as;function git(t,e){try{e.feed(t);const i=e.finish()[0];return(0,mit.isFilterExpression)(i)?{parsed:i,log:[]}:{parsed:null,log:[]}}catch(r){let i=r.message,s=1,o=t.length;if(r.token){const a=r.token;s=a.col,o=a.text.length;const l=r.message.match(new RegExp("(?<=A ).*(?= based on:)","g")).map(c=>c.replace(/\s+token/i,""));i=`Unexpected ${a.type} token "${a.value}"`,l&&l.length&&(i+=` Tokens expected: ${[...new Set(l)]}`)}return{parsed:null,log:[{message:i,startIndex:s-1,endIndex:s-1+o-1,severity:"error"}]}}}(function(t){var e=R&&R.__createBinding||(Object.create?function(c,f,d,x){x===void 0&&(x=d);var p=Object.getOwnPropertyDescriptor(f,d);(!p||("get"in p?!f.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return f[d]}}),Object.defineProperty(c,x,p)}:function(c,f,d,x){x===void 0&&(x=d),c[x]=f[d]}),r=R&&R.__setModuleDefault||(Object.create?function(c,f){Object.defineProperty(c,"default",{enumerable:!0,value:f})}:function(c,f){c.default=f}),i=R&&R.__importStar||function(){var c=function(f){return c=Object.getOwnPropertyNames||function(d){var x=[];for(var p in d)Object.prototype.hasOwnProperty.call(d,p)&&(x[x.length]=p);return x},c(f)};return function(f){if(f&&f.__esModule)return f;var d={};if(f!=null)for(var x=c(f),p=0;p<x.length;p++)x[p]!=="default"&&e(d,f,x[p]);return r(d,f),d}}(),s=R&&R.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.NumberFilterExpression=void 0;const o=as,a=i(xM),u=s(hM),l=VE;t.NumberFilterExpression={parse(c){if(c.match(/^\s*$/))return{parsed:null,log:[]};const f=new a.Parser(a.Grammar.fromCompiled(u.default)),d=(0,l.run_parser)(c,f);return d.parsed&&(0,o.isNumberFilter)(d.parsed)?{parsed:d.parsed,log:[]}:{parsed:null,log:d.log}},unparse(c){if(c===null)return"";switch(c.operator){case"=":return c.values.join(", ");case"!=":return"!= "+c.values.join(", ");case">":case"<":case"<=":case">=":return c.not?c.values.map(f=>c.operator==="="?`not ${f}`:`not ${c.operator} ${f}`).join(", "):c.values.map(f=>`${c.operator} ${f}`).join(", ");case"range":{const f=c.startOperator===">"?"(":"[",d=c.endOperator==="<"?")":"]",x=`${f}${c.startValue} to ${c.endValue}${d}`;return c.not?`not ${x}`:x}case"null":return c.not?"not null":"null";case"and":case"or":return c.members.map(f=>t.NumberFilterExpression.unparse(f)).join(` ${c.operator} `);case"()":{const f="("+t.NumberFilterExpression.unparse(c.expr)+")";return c.not?"not "+f:f}}return`no unparse for ${JSON.stringify(c)}`}}})(efe);var ife={},gM={},yit=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gM,"__esModule",{value:!0});function Eit(t){return t[0]}const vit=yit(pM),yM=Ur,za=vit.default.compile({WS:/[ \t]+/,comma:",",semi:";",or:"|",open:"(",close:")",minus:"-",matchStr:/(?:\\[^\n]|[^\n,;()|])+/}),_it=za.next;za.next=(t=>()=>{for(;;){const e=t.call(za);if(e==null||e.type!=="WS")return e}})(_it);const Ait={Lexer:za,ParserRules:[{name:"stringFilter",symbols:["stringFilter","conjunction","sfUnary"],postprocess:([t,e,r])=>(0,yM.conjoin)(t,e[0].text,r)},{name:"stringFilter",symbols:["sfUnary"],postprocess:t=>t[0]},{name:"sfUnary$ebnf$1",symbols:[za.has("minus")?{type:"minus"}:minus],postprocess:Eit},{name:"sfUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"sfUnary",symbols:["sfUnary$ebnf$1","clause"],postprocess:t=>(0,yM.maybeNot)(t)},{name:"parens",symbols:[za.has("open")?{type:"open"}:open,"stringFilter",za.has("close")?{type:"close"}:close],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:[za.has("matchStr")?{type:"matchStr"}:matchStr],postprocess:([t])=>(0,yM.matchOp)(t.text)},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"conjunction",symbols:[za.has("comma")?{type:"comma"}:comma]},{name:"conjunction",symbols:[za.has("semi")?{type:"semi"}:semi]},{name:"conjunction",symbols:[za.has("or")?{type:"or"}:or]}],ParserStart:"stringFilter"};gM.default=Ait,function(t){var e=R&&R.__createBinding||(Object.create?function(f,d,x,p){p===void 0&&(p=x);var m=Object.getOwnPropertyDescriptor(d,x);(!m||("get"in m?!d.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return d[x]}}),Object.defineProperty(f,p,m)}:function(f,d,x,p){p===void 0&&(p=x),f[p]=d[x]}),r=R&&R.__setModuleDefault||(Object.create?function(f,d){Object.defineProperty(f,"default",{enumerable:!0,value:d})}:function(f,d){f.default=d}),i=R&&R.__importStar||function(){var f=function(d){return f=Object.getOwnPropertyNames||function(x){var p=[];for(var m in x)Object.prototype.hasOwnProperty.call(x,m)&&(p[p.length]=m);return p},f(d)};return function(d){if(d&&d.__esModule)return d;var x={};if(d!=null)for(var p=f(d),m=0;m<p.length;m++)p[m]!=="default"&&e(x,d,p[m]);return r(x,d),x}}(),s=R&&R.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.StringFilterExpression=void 0;const o=as,a=i(xM),u=s(gM),l=Ur,c=VE;t.StringFilterExpression={parse(f){if(f.match(/^\s*$/))return{parsed:null,log:[]};const d=new a.Parser(a.Grammar.fromCompiled(u.default)),x=(0,c.run_parser)(f,d);return x.parsed&&(0,o.isStringFilter)(x.parsed)?{parsed:x.parsed,log:[]}:{parsed:null,log:x.log}},unparse(f){if(f===null)return"";switch(f.operator){case"=":return f.not?f.values.map(d=>"-"+(0,l.escape)(d)).join(", "):f.values.map(d=>(0,l.escape)(d)).join(", ");case"~":return f.not?f.escaped_values.map(d=>"-"+d).join(", "):f.escaped_values.join(", ");case"starts":return f.not?f.values.map(d=>"-"+(0,l.escape)(d)+"%").join(", "):f.values.map(d=>(0,l.escape)(d)+"%").join(", ");case"ends":return f.not?f.values.map(d=>"-%"+(0,l.escape)(d)).join(", "):f.values.map(d=>"%"+(0,l.escape)(d)).join(", ");case"contains":return f.not?f.values.map(d=>"-%"+(0,l.escape)(d)+"%").join(", "):f.values.map(d=>"%"+(0,l.escape)(d)+"%").join(", ");case"or":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join(" | ");case"and":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join("; ");case",":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join(", ");case"()":{const d="("+t.StringFilterExpression.unparse(f.expr)+")";return f.not?"-"+d:d}case"null":return f.not?"-null":"null";case"empty":return f.not?"-empty":"empty"}}}}(ife);var sfe={},EM={},Sit=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(EM,"__esModule",{value:!0});function bit(t){return t[0]}const ofe=Sit(pM),Ha=Ur,Cit=ofe.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to",NOW:"now",LAST:"last",THIS:"this",NEXT:"next",AGO:"ago",FROM:"from",BEFORE:"before",AFTER:"after",THROUGH:"through",STARTING:"starting",FOR:"for",TODAY:"today",YESTERDAY:"yesterday",TOMORROW:"tomorrow",SECOND:"second",MINUTE:"minute",HOUR:"hour",DAY:"day",WEEK:"week",MONTH:"month",QUARTER:"quarter",YEAR:"year",SECONDS:"seconds",MINUTES:"minutes",HOURS:"hours",DAYS:"days",WEEKS:"weeks",MONTHS:"months",QUARTERS:"quarters",YEARS:"years",MONDAY:"monday",TUESDAY:"tuesday",WEDNESDAY:"wednesday",THURSDAY:"thursday",FRIDAY:"friday",SATURDAY:"saturday",SUNDAY:"sunday"}),Xe=ofe.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:t=>Cit(t.toLowerCase())},oparen:"(",cparen:")",comma:",",literal:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d(?::\d\d(?:[.,]\d*)?)/,lit_week:/\d\d\d\d-\d\d-\d\d-[Ww][Kk]/,lit_quarter:/\d\d\d\d-[qQ][1234]/,lit_min:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d/,lit_hour:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d/,lit_day:/\d\d\d\d-\d\d-\d\d/,lit_month:/\d\d\d\d-\d\d/,lit_year:/\d\d\d\d/,n:/\d+/}),Tit=Xe.next;Xe.next=(t=>()=>{for(;;){const e=t.call(Xe);if(e===void 0||e.type!=="WS")return e}})(Tit);const Rit={Lexer:Xe,ParserRules:[{name:"temporalFilter",symbols:["temporalFilter","conjunction","temporalUnary"],postprocess:([t,e,r])=>(0,Ha.joinTemporal)(t,e[0].text,r)},{name:"temporalFilter",symbols:["temporalUnary"],postprocess:t=>t[0]},{name:"temporalUnary$ebnf$1",symbols:[Xe.has("NOT")?{type:"NOT"}:NOT],postprocess:bit},{name:"temporalUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"temporalUnary",symbols:["temporalUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,Ha.temporalNot)(e,t)},{name:"duration",symbols:["number","unit"],postprocess:([t,e])=>({units:e,n:t})},{name:"number",symbols:[Xe.has("n")?{type:"n"}:n],postprocess:([t])=>t.text},{name:"number",symbols:[Xe.has("lityear")?{type:"lityear"}:lityear],postprocess:([t])=>t.text},{name:"unit$subexpression$1",symbols:[Xe.has("SECOND")?{type:"SECOND"}:SECOND]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTE")?{type:"MINUTE"}:MINUTE]},{name:"unit$subexpression$1",symbols:[Xe.has("HOUR")?{type:"HOUR"}:HOUR]},{name:"unit$subexpression$1",symbols:[Xe.has("DAY")?{type:"DAY"}:DAY]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEK")?{type:"WEEK"}:WEEK]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTH")?{type:"MONTH"}:MONTH]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTER")?{type:"QUARTER"}:QUARTER]},{name:"unit$subexpression$1",symbols:[Xe.has("YEAR")?{type:"YEAR"}:YEAR]},{name:"unit$subexpression$1",symbols:[Xe.has("SECONDS")?{type:"SECONDS"}:SECONDS]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTES")?{type:"MINUTES"}:MINUTES]},{name:"unit$subexpression$1",symbols:[Xe.has("HOURS")?{type:"HOURS"}:HOURS]},{name:"unit$subexpression$1",symbols:[Xe.has("DAYS")?{type:"DAYS"}:DAYS]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEKS")?{type:"WEEKS"}:WEEKS]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTHS")?{type:"MONTHS"}:MONTHS]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTERS")?{type:"QUARTERS"}:QUARTERS]},{name:"unit$subexpression$1",symbols:[Xe.has("YEARS")?{type:"YEARS"}:YEARS]},{name:"unit",symbols:["unit$subexpression$1"],postprocess:([t])=>(0,Ha.mkUnits)(t[0].text)},{name:"clause",symbols:[Xe.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"clause",symbols:["duration"],postprocess:([t])=>({operator:"in_last",...t})},{name:"clause",symbols:[Xe.has("BEFORE")?{type:"BEFORE"}:BEFORE,"moment"],postprocess:([t,e])=>({operator:"before",before:e})},{name:"clause",symbols:[Xe.has("STARTING")?{type:"STARTING"}:STARTING,"moment"],postprocess:([t,e])=>({operator:"before",before:e,not:!0})},{name:"clause",symbols:[Xe.has("AFTER")?{type:"AFTER"}:AFTER,"moment"],postprocess:([t,e])=>({operator:"after",after:e})},{name:"clause",symbols:[Xe.has("THROUGH")?{type:"THROUGH"}:THROUGH,"moment"],postprocess:([t,e])=>({operator:"after",after:e,not:!0})},{name:"clause",symbols:["moment",Xe.has("TO")?{type:"TO"}:TO,"moment"],postprocess:([t,e,r])=>({operator:"to",fromMoment:t,toMoment:r})},{name:"clause",symbols:["moment",Xe.has("FOR")?{type:"FOR"}:FOR,"duration"],postprocess:([t,e,r])=>({...r,operator:"for",begin:t})},{name:"clause$subexpression$1",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST]},{name:"clause$subexpression$1",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT]},{name:"clause",symbols:["clause$subexpression$1","duration"],postprocess:([t,e])=>({operator:t[0].text,...e})},{name:"clause",symbols:["moment"],postprocess:([t])=>({operator:"in",in:t})},{name:"lastNextThis",symbols:[Xe.has("THIS")?{type:"THIS"}:THIS],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST],postprocess:([t])=>t.text.toLowerCase()},{name:"moment",symbols:[Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:()=>({moment:"now"})},{name:"moment",symbols:["lastNextThis","unit"],postprocess:([t,e])=>({moment:t,units:e})},{name:"moment",symbols:[Xe.has("TODAY")?{type:"TODAY"}:TODAY],postprocess:()=>({moment:"today"})},{name:"moment",symbols:[Xe.has("YESTERDAY")?{type:"YESTERDAY"}:YESTERDAY],postprocess:()=>({moment:"yesterday"})},{name:"moment",symbols:[Xe.has("TOMORROW")?{type:"TOMORROW"}:TOMORROW],postprocess:()=>({moment:"tomorrow"})},{name:"moment",symbols:["duration",Xe.has("AGO")?{type:"AGO"}:AGO],postprocess:([t,e])=>({moment:"ago",...t})},{name:"moment",symbols:["duration",Xe.has("FROM")?{type:"FROM"}:FROM,Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:([t,e])=>({moment:"from_now",...t})},{name:"moment",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"next"})},{name:"moment",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"last"})},{name:"moment",symbols:["weekday"],postprocess:([t])=>({moment:t.toLowerCase(),which:"last"})},{name:"moment",symbols:["timeLiteral"],postprocess:t=>t[0]},{name:"timeLiteral",symbols:[Xe.has("literal")?{type:"literal"}:literal],postprocess:([t])=>(0,Ha.timeLiteral)(t.text)},{name:"timeLiteral",symbols:[Xe.has("lit_day")?{type:"lit_day"}:lit_day],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"day")},{name:"timeLiteral",symbols:[Xe.has("lit_min")?{type:"lit_min"}:lit_min],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"minute")},{name:"timeLiteral",symbols:[Xe.has("lit_hour")?{type:"lit_hour"}:lit_hour],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"hour")},{name:"timeLiteral",symbols:[Xe.has("lit_month")?{type:"lit_month"}:lit_month],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"month")},{name:"timeLiteral",symbols:[Xe.has("lit_quarter")?{type:"lit_quarter"}:lit_quarter],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"quarter")},{name:"timeLiteral",symbols:[Xe.has("lit_week")?{type:"lit_week"}:lit_week],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"week")},{name:"timeLiteral",symbols:[Xe.has("lit_year")?{type:"lit_year"}:lit_year],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"year")},{name:"weekday$subexpression$1",symbols:[Xe.has("MONDAY")?{type:"MONDAY"}:MONDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("TUESDAY")?{type:"TUESDAY"}:TUESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("WEDNESDAY")?{type:"WEDNESDAY"}:WEDNESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("THURSDAY")?{type:"THURSDAY"}:THURSDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("FRIDAY")?{type:"FRIDAY"}:FRIDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SATURDAY")?{type:"SATURDAY"}:SATURDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SUNDAY")?{type:"SUNDAY"}:SUNDAY]},{name:"weekday",symbols:["weekday$subexpression$1"],postprocess:([t])=>t[0].text},{name:"parens",symbols:[Xe.has("oparen")?{type:"oparen"}:oparen,"temporalFilter",Xe.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"conjunction",symbols:[Xe.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Xe.has("AND")?{type:"AND"}:AND]}],ParserStart:"temporalFilter"};EM.default=Rit,function(t){var e=R&&R.__createBinding||(Object.create?function(x,p,m,g){g===void 0&&(g=m);var y=Object.getOwnPropertyDescriptor(p,m);(!y||("get"in y?!p.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(x,g,y)}:function(x,p,m,g){g===void 0&&(g=m),x[g]=p[m]}),r=R&&R.__setModuleDefault||(Object.create?function(x,p){Object.defineProperty(x,"default",{enumerable:!0,value:p})}:function(x,p){x.default=p}),i=R&&R.__importStar||function(){var x=function(p){return x=Object.getOwnPropertyNames||function(m){var g=[];for(var y in m)Object.prototype.hasOwnProperty.call(m,y)&&(g[g.length]=y);return g},x(p)};return function(p){if(p&&p.__esModule)return p;var m={};if(p!=null)for(var g=x(p),y=0;y<g.length;y++)g[y]!=="default"&&e(m,p,g[y]);return r(m,p),m}}(),s=R&&R.__importDefault||function(x){return x&&x.__esModule?x:{default:x}};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=void 0;const o=as,a=s(EM),u=i(xM),l=VE;t.TemporalFilterExpression={parse(x){if(x.match(/^\s*$/))return{parsed:null,log:[]};const p=new u.Parser(u.Grammar.fromCompiled(a.default)),m=(0,l.run_parser)(x,p);return m.parsed&&(0,o.isTemporalFilter)(m.parsed)?{parsed:m.parsed,log:[]}:{parsed:null,log:m.log}},unparse(x){if(x===null)return"";switch(x.operator){case"null":return c(x,"null");case"in":return c(x,d(x.in));case"()":return"("+t.TemporalFilterExpression.unparse(x.expr)+")";case"in_last":return c(x,f(x));case"last":case"next":return c(x,`${x.operator} ${f(x)}`);case"before":return`${x.not?"starting":"before"} ${d(x.before)}`;case"after":return`${x.not?"through":"after"} ${d(x.after)}`;case"to":return c(x,`${d(x.fromMoment)} to ${d(x.toMoment)}`);case"for":return c(x,`${d(x.begin)} for ${f(x)}`);case"or":return x.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" or ");case"and":return x.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" and ")}}};function c(x,p){return"not"in x&&x.not?"not "+p:p}function f(x){return x.n==="1"?`1 ${x.units}`:`${x.n} ${x.units}s`}function d(x){switch(x.moment){case"literal":return x.literal;case"now":case"today":case"yesterday":case"tomorrow":return x.moment;case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":return x.which==="next"?"next "+x.moment:x.moment;case"this":case"next":case"last":return`${x.moment} ${x.units}`;case"ago":return`${f(x)} ago`;case"from_now":return`${f(x)} from now`}}}(sfe),function(t){var e=R&&R.__createBinding||(Object.create?function(u,l,c,f){f===void 0&&(f=c);var d=Object.getOwnPropertyDescriptor(l,c);(!d||("get"in d?!l.__esModule:d.writable||d.configurable))&&(d={enumerable:!0,get:function(){return l[c]}}),Object.defineProperty(u,f,d)}:function(u,l,c,f){f===void 0&&(f=c),u[f]=l[c]}),r=R&&R.__exportStar||function(u,l){for(var c in u)c!=="default"&&!Object.prototype.hasOwnProperty.call(l,c)&&e(l,u,c)};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=t.StringFilterExpression=t.NumberFilterExpression=t.BooleanFilterExpression=void 0,r(as,t);var i=HT;Object.defineProperty(t,"BooleanFilterExpression",{enumerable:!0,get:function(){return i.BooleanFilterExpression}});var s=efe;Object.defineProperty(t,"NumberFilterExpression",{enumerable:!0,get:function(){return s.NumberFilterExpression}});var o=ife;Object.defineProperty(t,"StringFilterExpression",{enumerable:!0,get:function(){return o.StringFilterExpression}});var a=sfe;Object.defineProperty(t,"TemporalFilterExpression",{enumerable:!0,get:function(){return a.TemporalFilterExpression}})}(W2);var Ho={},GT={};Object.defineProperty(GT,"__esModule",{value:!0}),GT.JoinInstance=void 0;const Dit=Rt,wit=wt,vM=Ye;class Oit{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,vM.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new Dit.QueryFieldBoolean({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,vM.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,vM.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return(0,wit.getDialectFieldList)(this.queryStruct.structDef)}}GT.JoinInstance=Oit,Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.FieldInstanceResultRoot=Ho.FieldInstanceResult=Ho.FieldInstanceField=void 0,Ho.sqlFullChildReference=ufe;const Fc=Ye,afe=wt,Fit=GT,Yx=Rt;class Ls{constructor(e,r,i,s){this.f=e,this.fieldUsage=r,this.parent=i,this.drillExpression=s,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}static registerExpressionCompiler(e){Ls.exprCompiler=e}getSQL(){let e=this.generateExpression();return(0,Yx.isScalarField)(this.f)&&(e=(0,afe.caseGroup)(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}generateExpression(){if(!Ls.exprCompiler)throw new Error("Expression compiler not registered with FieldInstanceField");return this.f.fieldDef.type==="string"&&this.f.fieldDef.name==="__distinct_key"?this.generateDistinctKeyExpression():(0,Fc.hasExpression)(this.f.fieldDef)?Ls.exprCompiler(this.parent,this.f.parent,this.f.fieldDef.e):ufe(this.f.parent,this.f.fieldDef.name,this.f.parent.structDef.type==="record"?{result:this.parent,field:this.f}:void 0)}generateDistinctKeyExpression(){var e;if(this.f.parent.primaryKey()){const r=this.f.parent.getPrimaryKeyField(this.f.fieldDef),i=r.fieldDef.as||r.fieldDef.name;return this.parent.getField(i).generateExpression()}else if(this.f.parent.structDef.type==="array"){if(((e=this.f.parent.parent)===null||e===void 0?void 0:e.getDistinctKey())&&this.parent.parent){const s=this.parent.parent.getField("__distinct_key").generateExpression();return this.f.parent.dialect.sqlMakeUnnestKey(s,this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__row_id","string"))}return this.f.parent.dialect.sqlMakeUnnestKey("",this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__row_id","string"))}else return this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__distinct_key","string")}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}Ho.FieldInstanceField=Ls;class WT{constructor(e,r){this.turtleDef=e,this.parent=r,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getLimit(){if(this.firstSegment.type==="reduce"||this.firstSegment.type==="project")return this.firstSegment.limit}getQueryInfo(){if(!(0,Fc.isIndexSegment)(this.firstSegment)&&!(0,Fc.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return this.parent?this.parent.getQueryInfo():{}}addField(e,r,i,s){const o=this.allFields.get(e);if(o){if(o.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(o.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Ls(r,i,this,s))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Ls}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Ls)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Ls&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[a,u]of this.ungroupedSets){const l=e++;u.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[a,u]of this.allFields)if(u.type==="query"){const l=u;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Ls&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Ls&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if((0,Yx.isBasicScalar)(r.f))return"nested";r.f instanceof Yx.QueryFieldStruct&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof WT&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Ls&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Fc.isJoined)(i.f.fieldDef)||(0,Fc.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if((0,Yx.isBasicAggregate)(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r){var i;const s=e.getIdentifier();let o=this.root().joins.get(s);if(o){o.uniqueKeyRequirement=(0,Fc.mergeUniqueKeyRequirement)(o.uniqueKeyRequirement,r);return}let a;const u=(i=e.parent)===null||i===void 0?void 0:i.getJoinableParent();u&&(this.addStructToJoin(u,void 0),a=this.root().joins.get(u.getIdentifier())),(o=this.root().joins.get(s))||(o=new Fit.JoinInstance(e,s,a),this.root().joins.set(s,o)),o.uniqueKeyRequirement=(0,Fc.mergeUniqueKeyRequirement)(o.uniqueKeyRequirement,r)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];s=this.fields(l=>(0,Yx.isBasicScalar)(l.f)&&l.fieldUsage.type==="result"&&u.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let a=!0;for(;i!==void 0;)(a||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(u=>(0,Yx.isScalarField)(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),r=r.concat(i.fields(u=>(0,Yx.isScalarField)(u.f)&&u.fieldUsage.type==="result"&&s.indexOf(u.f.getIdentifier())===-1)),i=i.parent,a=!1;for(const u of(e==null?void 0:e.fields)||[])if(o.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}Ho.FieldInstanceResult=WT;class Nit extends WT{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new afe.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){var e;let r;for(const[i,s]of this.joins)if(s.parentRelationship()==="many_to_many"||s.forceAllSymmetricCalculations())r="0never";else if(r===void 0)r=i;else if(s.parentRelationship()==="one_to_many"){const a=s.queryStruct;a.parent&&a.parent.getIdentifier()===r?r=i:r="0never"}for(const[i,s]of this.joins)s.leafiest=i===r;for(const[i,s]of this.joins)if(s.leafiest&&s.parent!==void 0&&(!((e=s.uniqueKeyRequirement)===null||e===void 0)&&e.isCount)||!s.leafiest&&s.uniqueKeyRequirement){let o=s;for(;o;)o.queryStruct.primaryKey()||(o.makeUniqueKey=!0),o.queryStruct.structDef.type==="array"?o=o.parent:o=void 0}}}Ho.FieldInstanceResultRoot=Nit;function ufe(t,e,r){let i=t.getSQLIdentifier();if(r&&(0,Fc.isAtomic)(t.structDef)&&(0,Fc.hasExpression)(t.structDef)){if(!t.parent)throw new Error(`Cannot expand reference to ${e} without parent`);if(!Ls.exprCompiler)throw new Error("Expression compiler not registered with FieldInstanceField");i=Ls.exprCompiler(r.result,t.parent,t.structDef.e)}let s="table";t.structDef.type==="record"?s="record":t.structDef.type==="array"?s=t.structDef.elementTypeDef.type==="record_element"?"array[record]":"array[scalar]":t.structDef.type==="nest_source"&&(s="nest source");const o=t.getChildByName(e),a=(o==null?void 0:o.fieldDef.type)||"unknown";return t.dialect.sqlFieldReference(i,s,e,a)}var lfe={};const YE=zq(Zve);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterCompiler=t.FilterCompilers=void 0;const e=W2,r=Ye,i=YE;function s(m){return m.replace(/([%_\\])/g,"\\$1")}function o(m){return m===">"?"<=":m==="<"?">=":m===">="?"<":">"}function a(m,g){const y=` OR ${g} IS NULL`;return m.length===1?`${m[0]}${y}`:`(${m.join(" AND ")})${y}`}t.FilterCompilers={compile(m,g,y,v){if(g===null)return"true";if(m==="string"&&(0,e.isStringFilter)(g))return t.FilterCompilers.stringCompile(g,y,v);if(m==="number"&&(0,e.isNumberFilter)(g))return t.FilterCompilers.numberCompile(g,y,v);if(m==="boolean"&&(0,e.isBooleanFilter)(g))return t.FilterCompilers.booleanCompile(g,y,v);if((m==="date"||m==="timestamp")&&(0,e.isTemporalFilter)(g))return t.FilterCompilers.temporalCompile(g,y,v,m);throw new Error("INTERNAL ERROR: No filter compiler for "+m)},numberCompile(m,g,y){switch(m.operator){case"!=":case"=":{const v=m.operator==="="&&m.not||m.operator==="!="&&!m.not,E=m.values.join(", ");return m.values.length===1?v?`${g} != ${E} OR ${g} IS NULL`:`${g} = ${E}`:v?`${g} NOT IN (${E}) OR ${g} IS NULL`:`${g} IN (${E})`}case">":case"<":case">=":case"<=":{const v=m.not?o(m.operator):m.operator;return m.values.map(E=>`${g} ${v} ${E}`).join(m.not?" AND ":" OR ")}case"range":{let v=m.startOperator,E=m.endOperator,_=" AND ";return m.not&&(v=o(v),E=o(E),_=" OR "),`${g} ${v} ${m.startValue} ${_} ${g} ${E} ${m.endValue}`}case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"()":{const v="("+t.FilterCompilers.numberCompile(m.expr,g,y)+")";return m.not?`NOT ${v}`:v}case"and":case"or":return m.members.map(v=>t.FilterCompilers.numberCompile(v,g,y)).join(` ${m.operator.toUpperCase()} `)}},booleanCompile(m,g,y){switch(m.operator){case"true":return m.not?`NOT COALESCE(${g}, false)`:`COALESCE(${g}, false)`;case"false":return m.not?`COALESCE(${g} != false, true)`:`COALESCE(${g} = false, false)`;case"false_or_null":return m.not?`COALESCE(${g}, false)`:`NOT COALESCE(${g}, false)`;case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`}},stringCompile(m,g,y){switch(m.operator){case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"empty":return m.not?`COALESCE(${g},'') != ''`:`COALESCE(${g},'') = ''`;case"=":{if(m.values.length===1){const E=m.not?"!=":"=",_=`${g} ${E} ${y.sqlLiteralString(m.values[0])}`;return m.not?`(${_} OR ${g} IS NULL)`:_}const v="("+m.values.map(E=>y.sqlLiteralString(E)).join(", ")+")";return m.not?`(${g} NOT IN ${v} OR ${g} IS NULL)`:`${g} IN ${v}`}case"()":{const v="("+t.FilterCompilers.stringCompile(m.expr,g,y)+")";return m.not?`not ${v}`:v}case"contains":{const v=m.values.map(E=>"%"+s(E)+"%");return m.not?a(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"starts":{const v=m.values.map(E=>s(E)+"%");return m.not?a(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"ends":{const v=m.values.map(E=>"%"+s(E));return m.not?a(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"~":return m.not?a(m.escaped_values.map(v=>y.sqlLike("NOT LIKE",g,v)),g):m.escaped_values.map(v=>y.sqlLike("LIKE",g,v)).join(" OR ");case"and":return m.members.map(E=>t.FilterCompilers.stringCompile(E,g,y)).join(" AND ");case"or":return m.members.map(E=>t.FilterCompilers.stringCompile(E,g,y)).join(" OR ");case",":{const v=[],E=[];let _=!1,A=!1,S=!1,b=!1;for(const D of m.members)switch(D.operator){case"or":case"and":case",":v.push(D);break;case"null":D.not?A=!0:_=!0;break;case"empty":D.not?(b=!0,A=!0):(S=!0,_=!0);break;default:(D.not?E:v).push(D)}if(S&&b||_&&A)return"false";let C="";if(v.length>0||_||S){b=!1,A=!1;const D=v.map(O=>t.FilterCompilers.stringCompile(O,g,y));S&&D.push(`${g} = ''`),_&&D.push(`${g} IS NULL`),C=D.join(" OR ")}let T="";if(E.length>0||b||A){const D=E.map(O=>t.FilterCompilers.stringCompile(O,g,y));b&&D.push(`${g} != ''`),A&&D.push(`${g} IS NOT NULL`),T=D.join(" AND ")}return C?T!==""?`(${C}) AND (${T})`:C:T!==""?T:"true"}}},temporalCompile(m,g,y,v){return new p(g,y,v).compile(m)}};const u="yyyy",l=`${u}-LL`,c=`${l}-dd`,f=`${c} HH`,d=`${f}:mm`,x=`${d}:ss`;class p{constructor(g,y,v="timestamp"){this.expr=g,this.timetype=v,this.d=y}time(g){return this.timetype==="timestamp"?g:this.d.sqlCast({},{node:"cast",e:{node:"genericSQLExpr",src:["",g],kids:{args:[]},sql:g},srcType:{type:"timestamp"},dstType:{type:"date"},safe:!1})}compile(g){const y=this.expr;switch(g.operator){case"after":return`${y} ${g.not?"<":">="} ${this.time(this.moment(g.after).end)}`;case"before":return`${y} ${g.not?">=":"<"} ${this.time(this.moment(g.before).begin.sql)}`;case"in":{const v=this.moment(g.in);return v.begin.sql===v.end?g.not?`${y} != ${this.time(v.end)} OR ${y} IS NULL`:`${y} = ${this.time(v.end)}`:this.isIn(g.not,v.begin.sql,v.end)}case"for":{const v=this.moment(g.begin),E=this.delta(v.begin,"+",g.n,g.units);return this.isIn(g.not,v.begin.sql,E.sql)}case"in_last":{const v=Number(g.n)-1,E=this.nowDot(g.units),_=v>0?this.delta(E,"-",v.toString(),g.units):E,A=this.delta(E,"+","1",g.units);return this.isIn(g.not,_.sql,A.sql)}case"to":{const v=this.moment(g.fromMoment),E=this.moment(g.toMoment);return this.isIn(g.not,v.begin.sql,E.begin.sql)}case"last":{const v=this.nowDot(g.units),E=this.delta(v,"-",g.n,g.units);return this.isIn(g.not,E.sql,v.sql)}case"next":{const v=this.nowDot(g.units),E=this.delta(v,"+","1",g.units),_=this.delta(v,"+",(Number(g.n)+1).toString(),g.units);return this.isIn(g.not,E.sql,_.sql)}case"null":return g.not?`${y} IS NOT NULL`:`${y} IS NULL`;case"()":{const v="("+this.compile(g.expr)+")";return g.not?`NOT ${v}`:v}case"and":case"or":return g.members.map(v=>this.compile(v)).join(` ${g.operator.toUpperCase()} `)}}expandLiteral(g){let y=g.literal;switch(g.units){case"year":{const v=i.DateTime.fromFormat(y,u),E=this.literalNode(v.toFormat(x)),_=v.plus({year:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"month":{const v=i.DateTime.fromFormat(y,l),E=this.literalNode(v.toFormat(x)),_=v.plus({month:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"day":{const v=i.DateTime.fromFormat(y,c),E=this.literalNode(v.toFormat(x)),_=v.plus({day:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"hour":{const v=i.DateTime.fromFormat(y,f),E=this.literalNode(v.toFormat(x)),_=v.plus({hour:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"minute":{const v=i.DateTime.fromFormat(y,d),E=this.literalNode(v.toFormat(x)),_=v.plus({minute:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"week":{const _=i.DateTime.fromFormat(y.slice(0,10),c).plus({day:1}).startOf("week").minus({day:1}),A=this.literalNode(_.toFormat(x)),S=_.plus({days:7});return{begin:A,end:this.literalNode(S.toFormat(x)).sql}}case"quarter":{const v=y.slice(0,4),E=y.slice(6);E==="1"?y=`${v}-01-01 00:00:00`:E==="2"?y=`${v}-03-01 00:00:00`:E==="3"?y=`${v}-06-01 00:00:00`:y=`${v}-09-01 00:00:00`;const _=this.literalNode(y),S=i.DateTime.fromFormat(y,x).plus({months:3});return{begin:_,end:this.literalNode(S.toFormat(x)).sql}}case void 0:case"second":{const v=this.literalNode(y);return{begin:v,end:v.sql}}}}literalNode(g){const y={node:"timeLiteral",typeDef:{type:"timestamp"},literal:g};return{...y,sql:this.d.sqlLiteralTime({},y)}}nowExpr(){return{node:"now",typeDef:{type:"timestamp"},sql:this.d.sqlNowExpr()}}n(g){return{node:"numberLiteral",literal:g,sql:g}}delta(g,y,v,E){const _={node:"delta",op:y,units:E,kids:{base:(0,r.mkTemporal)(g,"timestamp"),delta:this.n(v)}};return{..._,sql:this.d.sqlAlterTimeExpr(_)}}dayofWeek(g){const y={node:"extract",e:(0,r.mkTemporal)(g,"timestamp"),units:"day_of_week"};return{...y,sql:this.d.sqlTimeExtractExpr({},y)}}nowDot(g){const y={node:"trunc",e:this.nowExpr(),units:g};return{...y,sql:this.d.sqlTruncExpr({},y)}}thisUnit(g){const y=this.nowDot(g),v=this.delta(y,"+","1",g);return{begin:y,end:v.sql}}lastUnit(g){const y=this.nowDot(g);return{begin:this.delta(y,"-","1",g),end:y.sql}}nextUnit(g){const y=this.nowDot(g),v=this.delta(y,"+","1",g),E=this.delta(y,"+","2",g);return{begin:v,end:E.sql}}mod7(g){return this.d.hasModOperator?`(${g})%7`:`MOD(${g},7)`}moment(g){switch(g.moment){case"now":{const y=this.nowExpr();return{begin:y,end:y.sql}}case"literal":return this.expandLiteral(g);case"ago":case"from_now":{const y=this.nowDot(g.units),v=(0,r.mkTemporal)(y,"timestamp"),E=this.delta(v,g.moment==="ago"?"-":"+",g.n,g.units);if(g.moment==="ago"&&g.n==="1")return{begin:E,end:y.sql};const _=Number(g.n)+(g.moment==="ago"?-1:1),A={...E,kids:{base:v,delta:this.n(_.toString())}};return{begin:E,end:this.d.sqlAlterTimeExpr(A)}}case"today":return this.thisUnit("day");case"yesterday":return this.lastUnit("day");case"tomorrow":return this.nextUnit("day");case"this":return this.thisUnit(g.units);case"last":return this.lastUnit(g.units);case"next":return this.nextUnit(g.units);case"sunday":return this.weekdayMoment(1,g.which);case"monday":return this.weekdayMoment(2,g.which);case"tuesday":return this.weekdayMoment(3,g.which);case"wednesday":return this.weekdayMoment(4,g.which);case"thursday":return this.weekdayMoment(5,g.which);case"friday":return this.weekdayMoment(6,g.which);case"saturday":return this.weekdayMoment(7,g.which)}}isIn(g,y,v){let E=">=",_="<",A="AND";return g&&(A="OR",E="<",_=">="),y=this.time(y),v=this.time(v),`${this.expr} ${E} ${y} ${A} ${this.expr} ${_} ${v}`}weekdayMoment(g,y){const v=y||"last",E=this.dayofWeek(this.nowExpr()),_=this.thisUnit("day").begin,A=g-1,S=`(${E.sql}-1)`;let b;v==="next"?b=`${this.mod7(`${A}-${S}+6`)}+1`:b=`${this.mod7(`${S}-${A}+6`)}+1`;const C=this.delta(_,v==="next"?"+":"-",b,"day"),T=this.delta(C,"+","1","day");return{begin:C,end:T.sql}}}t.TemporalFilterCompiler=p})(lfe),Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.exprToSQL=Qo,Hn.generateFunctionCallExpression=hfe,Hn.generateFieldFragment=YT,Hn.generateOutputFieldFragment=pfe,Hn.generateParameterFragment=mfe,Hn.generateFilterFragment=gfe,Hn.generateDimFragment=ul,Hn.generateUngroupedFragment=yfe,Hn.generateDistinctKeyIfNecessary=KT,Hn.generateSumFragment=vfe,Hn.generateSymmetricFragment=_fe,Hn.generateAvgFragment=Afe,Hn.generateCountFragment=Sfe,Hn.generateSourceReference=bfe,Hn.generateCaseSQL=Cfe,Hn.getFunctionOrderBy=_M,Hn.getAnalyticPartitions=Tfe,Hn.stringsFromSQLExpression=Rfe;const al=Ye,VT=W2,Lit=Ho,Iit=lfe,Is=wt,$it=Rt,cfe=9;function ffe(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-cfe);let c=`(${`(
|
|
970
|
+
`)},C.prototype.clone=function(){return new C(this.states,this.state)},C.prototype.has=function(w){return!0},{compile:_,states:S,error:Object.freeze({error:!0}),fallback:Object.freeze({fallback:!0}),keywords:b}})})(nfe);var pM=nfe.exports,Ur={};Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.maybeNot=Zrt,Ur.unescape=WE,Ur.escape=eit,Ur.matchOp=tit,Ur.conjoin=nit,Ur.joinNumbers=rit,Ur.mkRange=iit,Ur.mkValues=sit,Ur.numNot=oit,Ur.temporalNot=ait,Ur.joinTemporal=uit,Ur.timeLiteral=lit,Ur.mkUnits=cit;const ol=as;function Zrt(t){const[e,r]=t;return e&&r&&(0,ol.isStringFilter)(r)?{...r,not:!0}:r}function WE(t){return t.replace(/\\(.)/g,"$1")}function eit(t){const e=t.toLowerCase();return e==="null"||e==="empty"?"\\"+t:t.replace(/([,; |()\\%_-])/g,"\\$1")}function QT(t){let e=!1,r=!1,i=0,s=!1;const o=t.length;for(let a=0;a<o;a+=1){const u=t[a];if(u===" "||u===" "){i+=1;continue}i=0,u==="%"?(s=!0,a===0&&(e=!0),r=!0):(r=!1,u==="\\"?a+=1:u==="_"&&(s=!0))}return{hasLike:s,percentEnd:r&&o>1,percentStart:e&&o>1,endSpace:i}}function tit(t){let e=t.trimStart();const{hasLike:r,percentEnd:i,percentStart:s,endSpace:o}=QT(e);if(o>0&&(e=e.slice(0,-o)),r){if(s&&i){const a=e.slice(1,-1);if(!QT(a).hasLike&&a.length>0)return{operator:"contains",values:[WE(a)]}}else if(i){const a=e.slice(0,-1);if(!QT(a).hasLike)return{operator:"starts",values:[WE(a)]}}else if(s){const a=e.slice(1);if(!QT(a).hasLike)return{operator:"ends",values:[WE(a)]}}return{operator:"~",escaped_values:[e]}}return e.toLowerCase()==="null"?{operator:"null"}:e.toLowerCase()==="empty"?{operator:"empty"}:{operator:"=",values:[WE(e)]}}function mM(t,e){var r,i;return t.operator===e.operator&&((r=t.not)!==null&&r!==void 0?r:!1)===((i=e.not)!==null&&i!==void 0?i:!1)}function nit(t,e,r){if(e=e.toLowerCase(),(0,ol.isStringFilter)(t)&&(0,ol.isStringFilter)(r)){if(e===","){if(t.operator==="~"&&mM(t,r))return{...t,escaped_values:[...t.escaped_values,...r.escaped_values]};if((0,ol.isStringCondition)(t)&&mM(t,r))return{...t,values:[...t.values,...r.values]}}const i=e===","?",":e==="|"?"or":e===";"?"and":void 0;if(i)return t.operator===i?{...t,members:[...t.members,r]}:{operator:i,members:[t,r]}}return null}function rit(t,e,r){if(e=e.toLowerCase(),(0,ol.isNumberFilter)(t)&&(0,ol.isNumberFilter)(r)){if(e==="or"&&t.operator==="="&&mM(t,r)){const i={operator:"=",values:[...t.values,...r.values]};return t.not&&(i.not=!0),i}if(e==="and"||e==="or")return t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}}return null}function iit(t,e,r,i){return{operator:"range",startValue:e,startOperator:t==="("?">":">=",endValue:r,endOperator:i===")"?"<":"<="}}function sit(t,e){return{values:[t,...e]}}function oit(t,e){return(0,ol.isNumberFilter)(t)&&e?t.operator==="="?{operator:"!=",values:t.values}:t.operator==="!="?{operator:"=",values:t.values}:{...t,not:!0}:t}function ait(t,e){if((0,ol.isTemporalFilter)(t)&&e){if("not"in t){const r={...t};return t.not?delete r.not:r.not=!0,r}return{...t,not:!0}}return t}function uit(t,e,r){return e=e.toLowerCase(),(0,ol.isTemporalFilter)(t)&&(0,ol.isTemporalFilter)(r)&&(e==="and"||e==="or")?t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}:null}function lit(t,e){const r={moment:"literal",literal:t};return e&&(r.units=e),r}function cit(t){switch(t.toLowerCase()){case"second":case"seconds":return"second";case"minute":case"minutes":return"minute";case"hour":case"hours":return"hour";case"day":case"days":return"day";case"week":case"weeks":return"week";case"month":case"months":return"month";case"quarter":case"quarters":return"quarter";case"year":case"years":return"year"}}var fit=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(hM,"__esModule",{value:!0});function dit(t){return t[0]}const rfe=fit(pM),V2=Ur,xit=rfe.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to"}),Qn=rfe.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:t=>xit(t.toLowerCase())},oparen:"(",cparen:")",obrack:"[",cbrack:"]",comma:",",op:/<=|>=|<|>/,ne:"!=",eq:"=",float:/-?(?:\d+)?\.\d+(?:[Ee][+-]?\d+)?/,numberE:/-?\d+[Ee][+-]?\d+/,integer:/-?\d+/}),hit=Qn.next;Qn.next=(t=>()=>{for(;;){const e=t.call(Qn);if(e===void 0||e.type!=="WS")return e}})(hit);const pit={Lexer:Qn,ParserRules:[{name:"numberFilter",symbols:["numberFilter","conjunction","numberUnary"],postprocess:([t,e,r])=>(0,V2.joinNumbers)(t,e[0].text,r)},{name:"numberFilter",symbols:["numberUnary"],postprocess:t=>t[0]},{name:"numberUnary$ebnf$1",symbols:[Qn.has("NOT")?{type:"NOT"}:NOT],postprocess:dit},{name:"numberUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"numberUnary",symbols:["numberUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,V2.numNot)(e,t)},{name:"clause",symbols:[Qn.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause$ebnf$1",symbols:[]},{name:"clause$ebnf$1",symbols:["clause$ebnf$1","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:["N","clause$ebnf$1"],postprocess:([t,e])=>({operator:"=",...(0,V2.mkValues)(t,e)})},{name:"clause$ebnf$2",symbols:[]},{name:"clause$ebnf$2",symbols:["clause$ebnf$2","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Qn.has("eq")?{type:"eq"}:eq,"N","clause$ebnf$2"],postprocess:([t,e,r])=>({operator:"=",...(0,V2.mkValues)(e,r)})},{name:"clause$ebnf$3",symbols:[]},{name:"clause$ebnf$3",symbols:["clause$ebnf$3","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Qn.has("ne")?{type:"ne"}:ne,"N","clause$ebnf$3"],postprocess:([t,e,r])=>({operator:"!=",...(0,V2.mkValues)(e,r)})},{name:"clause",symbols:[Qn.has("op")?{type:"op"}:op,"N"],postprocess:([t,e])=>({operator:t.text,values:[e]})},{name:"clause",symbols:[Qn.has("oparen")?{type:"oparen"}:oparen,"numberFilter",Qn.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:["openInterval","N",Qn.has("TO")?{type:"TO"}:TO,"N","closeInterval"],postprocess:([t,e,r,i,s])=>(0,V2.mkRange)(t[0].text,e,i,s[0].text)},{name:"numberList",symbols:[Qn.has("comma")?{type:"comma"}:comma,"N"],postprocess:([t,e])=>e},{name:"closeInterval",symbols:[Qn.has("cbrack")?{type:"cbrack"}:cbrack]},{name:"closeInterval",symbols:[Qn.has("cparen")?{type:"cparen"}:cparen]},{name:"openInterval",symbols:[Qn.has("obrack")?{type:"obrack"}:obrack]},{name:"openInterval",symbols:[Qn.has("oparen")?{type:"oparen"}:oparen]},{name:"N$subexpression$1",symbols:[Qn.has("float")?{type:"float"}:float]},{name:"N$subexpression$1",symbols:[Qn.has("numberE")?{type:"numberE"}:numberE]},{name:"N$subexpression$1",symbols:[Qn.has("integer")?{type:"integer"}:integer]},{name:"N",symbols:["N$subexpression$1"],postprocess:([t])=>t[0].text},{name:"conjunction",symbols:[Qn.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Qn.has("AND")?{type:"AND"}:AND]}],ParserStart:"numberFilter"};hM.default=pit;var VE={};Object.defineProperty(VE,"__esModule",{value:!0}),VE.run_parser=git;const mit=as;function git(t,e){try{e.feed(t);const i=e.finish()[0];return(0,mit.isFilterExpression)(i)?{parsed:i,log:[]}:{parsed:null,log:[]}}catch(r){let i=r.message,s=1,o=t.length;if(r.token){const a=r.token;s=a.col,o=a.text.length;const l=r.message.match(new RegExp("(?<=A ).*(?= based on:)","g")).map(c=>c.replace(/\s+token/i,""));i=`Unexpected ${a.type} token "${a.value}"`,l&&l.length&&(i+=` Tokens expected: ${[...new Set(l)]}`)}return{parsed:null,log:[{message:i,startIndex:s-1,endIndex:s-1+o-1,severity:"error"}]}}}(function(t){var e=R&&R.__createBinding||(Object.create?function(c,f,d,x){x===void 0&&(x=d);var p=Object.getOwnPropertyDescriptor(f,d);(!p||("get"in p?!f.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return f[d]}}),Object.defineProperty(c,x,p)}:function(c,f,d,x){x===void 0&&(x=d),c[x]=f[d]}),r=R&&R.__setModuleDefault||(Object.create?function(c,f){Object.defineProperty(c,"default",{enumerable:!0,value:f})}:function(c,f){c.default=f}),i=R&&R.__importStar||function(){var c=function(f){return c=Object.getOwnPropertyNames||function(d){var x=[];for(var p in d)Object.prototype.hasOwnProperty.call(d,p)&&(x[x.length]=p);return x},c(f)};return function(f){if(f&&f.__esModule)return f;var d={};if(f!=null)for(var x=c(f),p=0;p<x.length;p++)x[p]!=="default"&&e(d,f,x[p]);return r(d,f),d}}(),s=R&&R.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.NumberFilterExpression=void 0;const o=as,a=i(xM),u=s(hM),l=VE;t.NumberFilterExpression={parse(c){if(c.match(/^\s*$/))return{parsed:null,log:[]};const f=new a.Parser(a.Grammar.fromCompiled(u.default)),d=(0,l.run_parser)(c,f);return d.parsed&&(0,o.isNumberFilter)(d.parsed)?{parsed:d.parsed,log:[]}:{parsed:null,log:d.log}},unparse(c){if(c===null)return"";switch(c.operator){case"=":return c.values.join(", ");case"!=":return"!= "+c.values.join(", ");case">":case"<":case"<=":case">=":return c.not?c.values.map(f=>c.operator==="="?`not ${f}`:`not ${c.operator} ${f}`).join(", "):c.values.map(f=>`${c.operator} ${f}`).join(", ");case"range":{const f=c.startOperator===">"?"(":"[",d=c.endOperator==="<"?")":"]",x=`${f}${c.startValue} to ${c.endValue}${d}`;return c.not?`not ${x}`:x}case"null":return c.not?"not null":"null";case"and":case"or":return c.members.map(f=>t.NumberFilterExpression.unparse(f)).join(` ${c.operator} `);case"()":{const f="("+t.NumberFilterExpression.unparse(c.expr)+")";return c.not?"not "+f:f}}return`no unparse for ${JSON.stringify(c)}`}}})(efe);var ife={},gM={},yit=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gM,"__esModule",{value:!0});function Eit(t){return t[0]}const vit=yit(pM),yM=Ur,za=vit.default.compile({WS:/[ \t]+/,comma:",",semi:";",or:"|",open:"(",close:")",minus:"-",matchStr:/(?:\\[^\n]|[^\n,;()|])+/}),_it=za.next;za.next=(t=>()=>{for(;;){const e=t.call(za);if(e==null||e.type!=="WS")return e}})(_it);const Ait={Lexer:za,ParserRules:[{name:"stringFilter",symbols:["stringFilter","conjunction","sfUnary"],postprocess:([t,e,r])=>(0,yM.conjoin)(t,e[0].text,r)},{name:"stringFilter",symbols:["sfUnary"],postprocess:t=>t[0]},{name:"sfUnary$ebnf$1",symbols:[za.has("minus")?{type:"minus"}:minus],postprocess:Eit},{name:"sfUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"sfUnary",symbols:["sfUnary$ebnf$1","clause"],postprocess:t=>(0,yM.maybeNot)(t)},{name:"parens",symbols:[za.has("open")?{type:"open"}:open,"stringFilter",za.has("close")?{type:"close"}:close],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:[za.has("matchStr")?{type:"matchStr"}:matchStr],postprocess:([t])=>(0,yM.matchOp)(t.text)},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"conjunction",symbols:[za.has("comma")?{type:"comma"}:comma]},{name:"conjunction",symbols:[za.has("semi")?{type:"semi"}:semi]},{name:"conjunction",symbols:[za.has("or")?{type:"or"}:or]}],ParserStart:"stringFilter"};gM.default=Ait,function(t){var e=R&&R.__createBinding||(Object.create?function(f,d,x,p){p===void 0&&(p=x);var m=Object.getOwnPropertyDescriptor(d,x);(!m||("get"in m?!d.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return d[x]}}),Object.defineProperty(f,p,m)}:function(f,d,x,p){p===void 0&&(p=x),f[p]=d[x]}),r=R&&R.__setModuleDefault||(Object.create?function(f,d){Object.defineProperty(f,"default",{enumerable:!0,value:d})}:function(f,d){f.default=d}),i=R&&R.__importStar||function(){var f=function(d){return f=Object.getOwnPropertyNames||function(x){var p=[];for(var m in x)Object.prototype.hasOwnProperty.call(x,m)&&(p[p.length]=m);return p},f(d)};return function(d){if(d&&d.__esModule)return d;var x={};if(d!=null)for(var p=f(d),m=0;m<p.length;m++)p[m]!=="default"&&e(x,d,p[m]);return r(x,d),x}}(),s=R&&R.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.StringFilterExpression=void 0;const o=as,a=i(xM),u=s(gM),l=Ur,c=VE;t.StringFilterExpression={parse(f){if(f.match(/^\s*$/))return{parsed:null,log:[]};const d=new a.Parser(a.Grammar.fromCompiled(u.default)),x=(0,c.run_parser)(f,d);return x.parsed&&(0,o.isStringFilter)(x.parsed)?{parsed:x.parsed,log:[]}:{parsed:null,log:x.log}},unparse(f){if(f===null)return"";switch(f.operator){case"=":return f.not?f.values.map(d=>"-"+(0,l.escape)(d)).join(", "):f.values.map(d=>(0,l.escape)(d)).join(", ");case"~":return f.not?f.escaped_values.map(d=>"-"+d).join(", "):f.escaped_values.join(", ");case"starts":return f.not?f.values.map(d=>"-"+(0,l.escape)(d)+"%").join(", "):f.values.map(d=>(0,l.escape)(d)+"%").join(", ");case"ends":return f.not?f.values.map(d=>"-%"+(0,l.escape)(d)).join(", "):f.values.map(d=>"%"+(0,l.escape)(d)).join(", ");case"contains":return f.not?f.values.map(d=>"-%"+(0,l.escape)(d)+"%").join(", "):f.values.map(d=>"%"+(0,l.escape)(d)+"%").join(", ");case"or":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join(" | ");case"and":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join("; ");case",":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join(", ");case"()":{const d="("+t.StringFilterExpression.unparse(f.expr)+")";return f.not?"-"+d:d}case"null":return f.not?"-null":"null";case"empty":return f.not?"-empty":"empty"}}}}(ife);var sfe={},EM={},Sit=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(EM,"__esModule",{value:!0});function bit(t){return t[0]}const ofe=Sit(pM),Ha=Ur,Cit=ofe.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to",NOW:"now",LAST:"last",THIS:"this",NEXT:"next",AGO:"ago",FROM:"from",BEFORE:"before",AFTER:"after",THROUGH:"through",STARTING:"starting",FOR:"for",TODAY:"today",YESTERDAY:"yesterday",TOMORROW:"tomorrow",SECOND:"second",MINUTE:"minute",HOUR:"hour",DAY:"day",WEEK:"week",MONTH:"month",QUARTER:"quarter",YEAR:"year",SECONDS:"seconds",MINUTES:"minutes",HOURS:"hours",DAYS:"days",WEEKS:"weeks",MONTHS:"months",QUARTERS:"quarters",YEARS:"years",MONDAY:"monday",TUESDAY:"tuesday",WEDNESDAY:"wednesday",THURSDAY:"thursday",FRIDAY:"friday",SATURDAY:"saturday",SUNDAY:"sunday"}),Xe=ofe.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:t=>Cit(t.toLowerCase())},oparen:"(",cparen:")",comma:",",literal:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d(?::\d\d(?:[.,]\d*)?)/,lit_week:/\d\d\d\d-\d\d-\d\d-[Ww][Kk]/,lit_quarter:/\d\d\d\d-[qQ][1234]/,lit_min:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d/,lit_hour:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d/,lit_day:/\d\d\d\d-\d\d-\d\d/,lit_month:/\d\d\d\d-\d\d/,lit_year:/\d\d\d\d/,n:/\d+/}),Tit=Xe.next;Xe.next=(t=>()=>{for(;;){const e=t.call(Xe);if(e===void 0||e.type!=="WS")return e}})(Tit);const Rit={Lexer:Xe,ParserRules:[{name:"temporalFilter",symbols:["temporalFilter","conjunction","temporalUnary"],postprocess:([t,e,r])=>(0,Ha.joinTemporal)(t,e[0].text,r)},{name:"temporalFilter",symbols:["temporalUnary"],postprocess:t=>t[0]},{name:"temporalUnary$ebnf$1",symbols:[Xe.has("NOT")?{type:"NOT"}:NOT],postprocess:bit},{name:"temporalUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"temporalUnary",symbols:["temporalUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,Ha.temporalNot)(e,t)},{name:"duration",symbols:["number","unit"],postprocess:([t,e])=>({units:e,n:t})},{name:"number",symbols:[Xe.has("n")?{type:"n"}:n],postprocess:([t])=>t.text},{name:"number",symbols:[Xe.has("lityear")?{type:"lityear"}:lityear],postprocess:([t])=>t.text},{name:"unit$subexpression$1",symbols:[Xe.has("SECOND")?{type:"SECOND"}:SECOND]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTE")?{type:"MINUTE"}:MINUTE]},{name:"unit$subexpression$1",symbols:[Xe.has("HOUR")?{type:"HOUR"}:HOUR]},{name:"unit$subexpression$1",symbols:[Xe.has("DAY")?{type:"DAY"}:DAY]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEK")?{type:"WEEK"}:WEEK]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTH")?{type:"MONTH"}:MONTH]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTER")?{type:"QUARTER"}:QUARTER]},{name:"unit$subexpression$1",symbols:[Xe.has("YEAR")?{type:"YEAR"}:YEAR]},{name:"unit$subexpression$1",symbols:[Xe.has("SECONDS")?{type:"SECONDS"}:SECONDS]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTES")?{type:"MINUTES"}:MINUTES]},{name:"unit$subexpression$1",symbols:[Xe.has("HOURS")?{type:"HOURS"}:HOURS]},{name:"unit$subexpression$1",symbols:[Xe.has("DAYS")?{type:"DAYS"}:DAYS]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEKS")?{type:"WEEKS"}:WEEKS]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTHS")?{type:"MONTHS"}:MONTHS]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTERS")?{type:"QUARTERS"}:QUARTERS]},{name:"unit$subexpression$1",symbols:[Xe.has("YEARS")?{type:"YEARS"}:YEARS]},{name:"unit",symbols:["unit$subexpression$1"],postprocess:([t])=>(0,Ha.mkUnits)(t[0].text)},{name:"clause",symbols:[Xe.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"clause",symbols:["duration"],postprocess:([t])=>({operator:"in_last",...t})},{name:"clause",symbols:[Xe.has("BEFORE")?{type:"BEFORE"}:BEFORE,"moment"],postprocess:([t,e])=>({operator:"before",before:e})},{name:"clause",symbols:[Xe.has("STARTING")?{type:"STARTING"}:STARTING,"moment"],postprocess:([t,e])=>({operator:"before",before:e,not:!0})},{name:"clause",symbols:[Xe.has("AFTER")?{type:"AFTER"}:AFTER,"moment"],postprocess:([t,e])=>({operator:"after",after:e})},{name:"clause",symbols:[Xe.has("THROUGH")?{type:"THROUGH"}:THROUGH,"moment"],postprocess:([t,e])=>({operator:"after",after:e,not:!0})},{name:"clause",symbols:["moment",Xe.has("TO")?{type:"TO"}:TO,"moment"],postprocess:([t,e,r])=>({operator:"to",fromMoment:t,toMoment:r})},{name:"clause",symbols:["moment",Xe.has("FOR")?{type:"FOR"}:FOR,"duration"],postprocess:([t,e,r])=>({...r,operator:"for",begin:t})},{name:"clause$subexpression$1",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST]},{name:"clause$subexpression$1",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT]},{name:"clause",symbols:["clause$subexpression$1","duration"],postprocess:([t,e])=>({operator:t[0].text,...e})},{name:"clause",symbols:["moment"],postprocess:([t])=>({operator:"in",in:t})},{name:"lastNextThis",symbols:[Xe.has("THIS")?{type:"THIS"}:THIS],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST],postprocess:([t])=>t.text.toLowerCase()},{name:"moment",symbols:[Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:()=>({moment:"now"})},{name:"moment",symbols:["lastNextThis","unit"],postprocess:([t,e])=>({moment:t,units:e})},{name:"moment",symbols:[Xe.has("TODAY")?{type:"TODAY"}:TODAY],postprocess:()=>({moment:"today"})},{name:"moment",symbols:[Xe.has("YESTERDAY")?{type:"YESTERDAY"}:YESTERDAY],postprocess:()=>({moment:"yesterday"})},{name:"moment",symbols:[Xe.has("TOMORROW")?{type:"TOMORROW"}:TOMORROW],postprocess:()=>({moment:"tomorrow"})},{name:"moment",symbols:["duration",Xe.has("AGO")?{type:"AGO"}:AGO],postprocess:([t,e])=>({moment:"ago",...t})},{name:"moment",symbols:["duration",Xe.has("FROM")?{type:"FROM"}:FROM,Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:([t,e])=>({moment:"from_now",...t})},{name:"moment",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"next"})},{name:"moment",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"last"})},{name:"moment",symbols:["weekday"],postprocess:([t])=>({moment:t.toLowerCase(),which:"last"})},{name:"moment",symbols:["timeLiteral"],postprocess:t=>t[0]},{name:"timeLiteral",symbols:[Xe.has("literal")?{type:"literal"}:literal],postprocess:([t])=>(0,Ha.timeLiteral)(t.text)},{name:"timeLiteral",symbols:[Xe.has("lit_day")?{type:"lit_day"}:lit_day],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"day")},{name:"timeLiteral",symbols:[Xe.has("lit_min")?{type:"lit_min"}:lit_min],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"minute")},{name:"timeLiteral",symbols:[Xe.has("lit_hour")?{type:"lit_hour"}:lit_hour],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"hour")},{name:"timeLiteral",symbols:[Xe.has("lit_month")?{type:"lit_month"}:lit_month],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"month")},{name:"timeLiteral",symbols:[Xe.has("lit_quarter")?{type:"lit_quarter"}:lit_quarter],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"quarter")},{name:"timeLiteral",symbols:[Xe.has("lit_week")?{type:"lit_week"}:lit_week],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"week")},{name:"timeLiteral",symbols:[Xe.has("lit_year")?{type:"lit_year"}:lit_year],postprocess:([t])=>(0,Ha.timeLiteral)(t.text,"year")},{name:"weekday$subexpression$1",symbols:[Xe.has("MONDAY")?{type:"MONDAY"}:MONDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("TUESDAY")?{type:"TUESDAY"}:TUESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("WEDNESDAY")?{type:"WEDNESDAY"}:WEDNESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("THURSDAY")?{type:"THURSDAY"}:THURSDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("FRIDAY")?{type:"FRIDAY"}:FRIDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SATURDAY")?{type:"SATURDAY"}:SATURDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SUNDAY")?{type:"SUNDAY"}:SUNDAY]},{name:"weekday",symbols:["weekday$subexpression$1"],postprocess:([t])=>t[0].text},{name:"parens",symbols:[Xe.has("oparen")?{type:"oparen"}:oparen,"temporalFilter",Xe.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"conjunction",symbols:[Xe.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Xe.has("AND")?{type:"AND"}:AND]}],ParserStart:"temporalFilter"};EM.default=Rit,function(t){var e=R&&R.__createBinding||(Object.create?function(x,p,m,g){g===void 0&&(g=m);var y=Object.getOwnPropertyDescriptor(p,m);(!y||("get"in y?!p.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(x,g,y)}:function(x,p,m,g){g===void 0&&(g=m),x[g]=p[m]}),r=R&&R.__setModuleDefault||(Object.create?function(x,p){Object.defineProperty(x,"default",{enumerable:!0,value:p})}:function(x,p){x.default=p}),i=R&&R.__importStar||function(){var x=function(p){return x=Object.getOwnPropertyNames||function(m){var g=[];for(var y in m)Object.prototype.hasOwnProperty.call(m,y)&&(g[g.length]=y);return g},x(p)};return function(p){if(p&&p.__esModule)return p;var m={};if(p!=null)for(var g=x(p),y=0;y<g.length;y++)g[y]!=="default"&&e(m,p,g[y]);return r(m,p),m}}(),s=R&&R.__importDefault||function(x){return x&&x.__esModule?x:{default:x}};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=void 0;const o=as,a=s(EM),u=i(xM),l=VE;t.TemporalFilterExpression={parse(x){if(x.match(/^\s*$/))return{parsed:null,log:[]};const p=new u.Parser(u.Grammar.fromCompiled(a.default)),m=(0,l.run_parser)(x,p);return m.parsed&&(0,o.isTemporalFilter)(m.parsed)?{parsed:m.parsed,log:[]}:{parsed:null,log:m.log}},unparse(x){if(x===null)return"";switch(x.operator){case"null":return c(x,"null");case"in":return c(x,d(x.in));case"()":return"("+t.TemporalFilterExpression.unparse(x.expr)+")";case"in_last":return c(x,f(x));case"last":case"next":return c(x,`${x.operator} ${f(x)}`);case"before":return`${x.not?"starting":"before"} ${d(x.before)}`;case"after":return`${x.not?"through":"after"} ${d(x.after)}`;case"to":return c(x,`${d(x.fromMoment)} to ${d(x.toMoment)}`);case"for":return c(x,`${d(x.begin)} for ${f(x)}`);case"or":return x.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" or ");case"and":return x.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" and ")}}};function c(x,p){return"not"in x&&x.not?"not "+p:p}function f(x){return x.n==="1"?`1 ${x.units}`:`${x.n} ${x.units}s`}function d(x){switch(x.moment){case"literal":return x.literal;case"now":case"today":case"yesterday":case"tomorrow":return x.moment;case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":return x.which==="next"?"next "+x.moment:x.moment;case"this":case"next":case"last":return`${x.moment} ${x.units}`;case"ago":return`${f(x)} ago`;case"from_now":return`${f(x)} from now`}}}(sfe),function(t){var e=R&&R.__createBinding||(Object.create?function(u,l,c,f){f===void 0&&(f=c);var d=Object.getOwnPropertyDescriptor(l,c);(!d||("get"in d?!l.__esModule:d.writable||d.configurable))&&(d={enumerable:!0,get:function(){return l[c]}}),Object.defineProperty(u,f,d)}:function(u,l,c,f){f===void 0&&(f=c),u[f]=l[c]}),r=R&&R.__exportStar||function(u,l){for(var c in u)c!=="default"&&!Object.prototype.hasOwnProperty.call(l,c)&&e(l,u,c)};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=t.StringFilterExpression=t.NumberFilterExpression=t.BooleanFilterExpression=void 0,r(as,t);var i=HT;Object.defineProperty(t,"BooleanFilterExpression",{enumerable:!0,get:function(){return i.BooleanFilterExpression}});var s=efe;Object.defineProperty(t,"NumberFilterExpression",{enumerable:!0,get:function(){return s.NumberFilterExpression}});var o=ife;Object.defineProperty(t,"StringFilterExpression",{enumerable:!0,get:function(){return o.StringFilterExpression}});var a=sfe;Object.defineProperty(t,"TemporalFilterExpression",{enumerable:!0,get:function(){return a.TemporalFilterExpression}})}(W2);var Ho={},GT={};Object.defineProperty(GT,"__esModule",{value:!0}),GT.JoinInstance=void 0;const Dit=Rt,wit=wt,vM=Ye;class Oit{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,vM.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new Dit.QueryFieldBoolean({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,vM.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,vM.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return(0,wit.getDialectFieldList)(this.queryStruct.structDef)}}GT.JoinInstance=Oit,Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.FieldInstanceResultRoot=Ho.FieldInstanceResult=Ho.FieldInstanceField=void 0,Ho.sqlFullChildReference=ufe;const Fc=Ye,afe=wt,Fit=GT,Yx=Rt;class Ls{constructor(e,r,i,s){this.f=e,this.fieldUsage=r,this.parent=i,this.drillExpression=s,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}static registerExpressionCompiler(e){Ls.exprCompiler=e}getSQL(){let e=this.generateExpression();return(0,Yx.isScalarField)(this.f)&&(e=(0,afe.caseGroup)(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}generateExpression(){if(!Ls.exprCompiler)throw new Error("Expression compiler not registered with FieldInstanceField");return this.f.fieldDef.type==="string"&&this.f.fieldDef.name==="__distinct_key"?this.generateDistinctKeyExpression():(0,Fc.hasExpression)(this.f.fieldDef)?Ls.exprCompiler(this.parent,this.f.parent,this.f.fieldDef.e):ufe(this.f.parent,this.f.fieldDef.name,this.f.parent.structDef.type==="record"?{result:this.parent,field:this.f}:void 0)}generateDistinctKeyExpression(){var e;if(this.f.parent.primaryKey()){const r=this.f.parent.getPrimaryKeyField(this.f.fieldDef),i=r.fieldDef.as||r.fieldDef.name;return this.parent.getField(i).generateExpression()}else if(this.f.parent.structDef.type==="array"){if(((e=this.f.parent.parent)===null||e===void 0?void 0:e.getDistinctKey())&&this.parent.parent){const s=this.parent.parent.getField("__distinct_key").generateExpression();return this.f.parent.dialect.sqlMakeUnnestKey(s,this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__row_id","string"))}return this.f.parent.dialect.sqlMakeUnnestKey("",this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__row_id","string"))}else return this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__distinct_key","string")}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}Ho.FieldInstanceField=Ls;class WT{constructor(e,r){this.turtleDef=e,this.parent=r,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getLimit(){if(this.firstSegment.type==="reduce"||this.firstSegment.type==="project")return this.firstSegment.limit}getQueryInfo(){if(!(0,Fc.isIndexSegment)(this.firstSegment)&&!(0,Fc.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return this.parent?this.parent.getQueryInfo():{}}addField(e,r,i,s){const o=this.allFields.get(e);if(o){if(o.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(o.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Ls(r,i,this,s))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Ls}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Ls)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Ls&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[a,u]of this.ungroupedSets){const l=e++;u.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[a,u]of this.allFields)if(u.type==="query"){const l=u;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Ls&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Ls&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if((0,Yx.isBasicScalar)(r.f))return"nested";r.f instanceof Yx.QueryFieldStruct&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof WT&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Ls&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Fc.isJoined)(i.f.fieldDef)||(0,Fc.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if((0,Yx.isBasicAggregate)(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r){var i;const s=e.getIdentifier();let o=this.root().joins.get(s);if(o){o.uniqueKeyRequirement=(0,Fc.mergeUniqueKeyRequirement)(o.uniqueKeyRequirement,r);return}let a;const u=(i=e.parent)===null||i===void 0?void 0:i.getJoinableParent();u&&(this.addStructToJoin(u,void 0),a=this.root().joins.get(u.getIdentifier())),(o=this.root().joins.get(s))||(o=new Fit.JoinInstance(e,s,a),this.root().joins.set(s,o)),o.uniqueKeyRequirement=(0,Fc.mergeUniqueKeyRequirement)(o.uniqueKeyRequirement,r)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];s=this.fields(l=>(0,Yx.isBasicScalar)(l.f)&&l.fieldUsage.type==="result"&&u.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let a=!0;for(;i!==void 0;)(a||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(u=>(0,Yx.isScalarField)(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),r=r.concat(i.fields(u=>(0,Yx.isScalarField)(u.f)&&u.fieldUsage.type==="result"&&s.indexOf(u.f.getIdentifier())===-1)),i=i.parent,a=!1;for(const u of(e==null?void 0:e.fields)||[])if(o.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}Ho.FieldInstanceResult=WT;class Nit extends WT{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new afe.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){var e;let r;for(const[i,s]of this.joins)if(s.parentRelationship()==="many_to_many"||s.forceAllSymmetricCalculations())r="0never";else if(r===void 0)r=i;else if(s.parentRelationship()==="one_to_many"){const a=s.queryStruct;a.parent&&a.parent.getIdentifier()===r?r=i:r="0never"}for(const[i,s]of this.joins)s.leafiest=i===r;for(const[i,s]of this.joins)if(s.leafiest&&s.parent!==void 0&&(!((e=s.uniqueKeyRequirement)===null||e===void 0)&&e.isCount)||!s.leafiest&&s.uniqueKeyRequirement){let o=s;for(;o;)o.queryStruct.primaryKey()||(o.makeUniqueKey=!0),o.queryStruct.structDef.type==="array"?o=o.parent:o=void 0}}}Ho.FieldInstanceResultRoot=Nit;function ufe(t,e,r){let i=t.getSQLIdentifier();if(r&&(0,Fc.isAtomic)(t.structDef)&&(0,Fc.hasExpression)(t.structDef)){if(!t.parent)throw new Error(`Cannot expand reference to ${e} without parent`);if(!Ls.exprCompiler)throw new Error("Expression compiler not registered with FieldInstanceField");i=Ls.exprCompiler(r.result,t.parent,t.structDef.e)}let s="table";t.structDef.type==="record"?s="record":t.structDef.type==="array"?s=t.structDef.elementTypeDef.type==="record_element"?"array[record]":"array[scalar]":t.structDef.type==="nest_source"&&(s="nest source");const o=t.getChildByName(e),a=(o==null?void 0:o.fieldDef.type)||"unknown";return t.dialect.sqlFieldReference(i,s,e,a)}var lfe={};const YE=zq(Zve);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterCompiler=t.FilterCompilers=void 0;const e=W2,r=Ye,i=YE;function s(m){return m.replace(/([%_\\])/g,"\\$1")}function o(m){return m===">"?"<=":m==="<"?">=":m===">="?"<":">"}function a(m,g){const y=` OR ${g} IS NULL`;return m.length===1?`${m[0]}${y}`:`(${m.join(" AND ")})${y}`}t.FilterCompilers={compile(m,g,y,v,E={}){if(g===null)return"true";if(m==="string"&&(0,e.isStringFilter)(g))return t.FilterCompilers.stringCompile(g,y,v);if(m==="number"&&(0,e.isNumberFilter)(g))return t.FilterCompilers.numberCompile(g,y,v);if(m==="boolean"&&(0,e.isBooleanFilter)(g))return t.FilterCompilers.booleanCompile(g,y,v);if((m==="date"||m==="timestamp")&&(0,e.isTemporalFilter)(g))return t.FilterCompilers.temporalCompile(g,y,v,m,E);throw new Error("INTERNAL ERROR: No filter compiler for "+m)},numberCompile(m,g,y){switch(m.operator){case"!=":case"=":{const v=m.operator==="="&&m.not||m.operator==="!="&&!m.not,E=m.values.join(", ");return m.values.length===1?v?`${g} != ${E} OR ${g} IS NULL`:`${g} = ${E}`:v?`${g} NOT IN (${E}) OR ${g} IS NULL`:`${g} IN (${E})`}case">":case"<":case">=":case"<=":{const v=m.not?o(m.operator):m.operator;return m.values.map(E=>`${g} ${v} ${E}`).join(m.not?" AND ":" OR ")}case"range":{let v=m.startOperator,E=m.endOperator,_=" AND ";return m.not&&(v=o(v),E=o(E),_=" OR "),`${g} ${v} ${m.startValue} ${_} ${g} ${E} ${m.endValue}`}case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"()":{const v="("+t.FilterCompilers.numberCompile(m.expr,g,y)+")";return m.not?`NOT ${v}`:v}case"and":case"or":return m.members.map(v=>t.FilterCompilers.numberCompile(v,g,y)).join(` ${m.operator.toUpperCase()} `)}},booleanCompile(m,g,y){switch(m.operator){case"true":return m.not?`NOT COALESCE(${g}, false)`:`COALESCE(${g}, false)`;case"false":return m.not?`COALESCE(${g} != false, true)`:`COALESCE(${g} = false, false)`;case"false_or_null":return m.not?`COALESCE(${g}, false)`:`NOT COALESCE(${g}, false)`;case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`}},stringCompile(m,g,y){switch(m.operator){case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"empty":return m.not?`COALESCE(${g},'') != ''`:`COALESCE(${g},'') = ''`;case"=":{if(m.values.length===1){const E=m.not?"!=":"=",_=`${g} ${E} ${y.sqlLiteralString(m.values[0])}`;return m.not?`(${_} OR ${g} IS NULL)`:_}const v="("+m.values.map(E=>y.sqlLiteralString(E)).join(", ")+")";return m.not?`(${g} NOT IN ${v} OR ${g} IS NULL)`:`${g} IN ${v}`}case"()":{const v="("+t.FilterCompilers.stringCompile(m.expr,g,y)+")";return m.not?`not ${v}`:v}case"contains":{const v=m.values.map(E=>"%"+s(E)+"%");return m.not?a(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"starts":{const v=m.values.map(E=>s(E)+"%");return m.not?a(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"ends":{const v=m.values.map(E=>"%"+s(E));return m.not?a(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"~":return m.not?a(m.escaped_values.map(v=>y.sqlLike("NOT LIKE",g,v)),g):m.escaped_values.map(v=>y.sqlLike("LIKE",g,v)).join(" OR ");case"and":return m.members.map(E=>t.FilterCompilers.stringCompile(E,g,y)).join(" AND ");case"or":return m.members.map(E=>t.FilterCompilers.stringCompile(E,g,y)).join(" OR ");case",":{const v=[],E=[];let _=!1,A=!1,S=!1,b=!1;for(const D of m.members)switch(D.operator){case"or":case"and":case",":v.push(D);break;case"null":D.not?A=!0:_=!0;break;case"empty":D.not?(b=!0,A=!0):(S=!0,_=!0);break;default:(D.not?E:v).push(D)}if(S&&b||_&&A)return"false";let C="";if(v.length>0||_||S){b=!1,A=!1;const D=v.map(O=>t.FilterCompilers.stringCompile(O,g,y));S&&D.push(`${g} = ''`),_&&D.push(`${g} IS NULL`),C=D.join(" OR ")}let T="";if(E.length>0||b||A){const D=E.map(O=>t.FilterCompilers.stringCompile(O,g,y));b&&D.push(`${g} != ''`),A&&D.push(`${g} IS NOT NULL`),T=D.join(" AND ")}return C?T!==""?`(${C}) AND (${T})`:C:T!==""?T:"true"}}},temporalCompile(m,g,y,v,E={}){return new p(g,y,v,E).compile(m)}};const u="yyyy",l=`${u}-LL`,c=`${l}-dd`,f=`${c} HH`,d=`${f}:mm`,x=`${d}:ss`;class p{constructor(g,y,v="timestamp",E={}){this.expr=g,this.timetype=v,this.d=y,this.qi=E}time(g){return this.timetype==="timestamp"?g:this.d.sqlCast({},{node:"cast",e:{node:"genericSQLExpr",src:["",g],kids:{args:[]},sql:g},srcType:{type:"timestamp"},dstType:{type:"date"},safe:!1})}compile(g){const y=this.expr;switch(g.operator){case"after":return`${y} ${g.not?"<":">="} ${this.time(this.moment(g.after).end)}`;case"before":return`${y} ${g.not?">=":"<"} ${this.time(this.moment(g.before).begin.sql)}`;case"in":{const v=this.moment(g.in);return v.begin.sql===v.end?g.not?`${y} != ${this.time(v.end)} OR ${y} IS NULL`:`${y} = ${this.time(v.end)}`:this.isIn(g.not,v.begin.sql,v.end)}case"for":{const v=this.moment(g.begin),E=this.delta(v.begin,"+",g.n,g.units);return this.isIn(g.not,v.begin.sql,E.sql)}case"in_last":{const v=Number(g.n)-1,E=this.nowDot(g.units),_=v>0?this.delta(E,"-",v.toString(),g.units):E,A=this.delta(E,"+","1",g.units);return this.isIn(g.not,_.sql,A.sql)}case"to":{const v=this.moment(g.fromMoment),E=this.moment(g.toMoment);return this.isIn(g.not,v.begin.sql,E.begin.sql)}case"last":{const v=this.nowDot(g.units),E=this.delta(v,"-",g.n,g.units);return this.isIn(g.not,E.sql,v.sql)}case"next":{const v=this.nowDot(g.units),E=this.delta(v,"+","1",g.units),_=this.delta(v,"+",(Number(g.n)+1).toString(),g.units);return this.isIn(g.not,E.sql,_.sql)}case"null":return g.not?`${y} IS NOT NULL`:`${y} IS NULL`;case"()":{const v="("+this.compile(g.expr)+")";return g.not?`NOT ${v}`:v}case"and":case"or":return g.members.map(v=>this.compile(v)).join(` ${g.operator.toUpperCase()} `)}}expandLiteral(g){let y=g.literal;switch(g.units){case"year":{const v=i.DateTime.fromFormat(y,u),E=this.literalNode(v.toFormat(x)),_=v.plus({year:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"month":{const v=i.DateTime.fromFormat(y,l),E=this.literalNode(v.toFormat(x)),_=v.plus({month:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"day":{const v=i.DateTime.fromFormat(y,c),E=this.literalNode(v.toFormat(x)),_=v.plus({day:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"hour":{const v=i.DateTime.fromFormat(y,f),E=this.literalNode(v.toFormat(x)),_=v.plus({hour:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"minute":{const v=i.DateTime.fromFormat(y,d),E=this.literalNode(v.toFormat(x)),_=v.plus({minute:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"week":{const _=i.DateTime.fromFormat(y.slice(0,10),c).plus({day:1}).startOf("week").minus({day:1}),A=this.literalNode(_.toFormat(x)),S=_.plus({days:7});return{begin:A,end:this.literalNode(S.toFormat(x)).sql}}case"quarter":{const v=y.slice(0,4),E=y.slice(6);E==="1"?y=`${v}-01-01 00:00:00`:E==="2"?y=`${v}-03-01 00:00:00`:E==="3"?y=`${v}-06-01 00:00:00`:y=`${v}-09-01 00:00:00`;const _=this.literalNode(y),S=i.DateTime.fromFormat(y,x).plus({months:3});return{begin:_,end:this.literalNode(S.toFormat(x)).sql}}case void 0:case"second":{const v=this.literalNode(y);return{begin:v,end:v.sql}}}}literalNode(g){const y={node:"timeLiteral",typeDef:{type:"timestamp"},literal:g};return this.qi.queryTimezone&&(y.timezone=this.qi.queryTimezone),{...y,sql:this.d.sqlLiteralTime(this.qi,y)}}nowExpr(){return{node:"now",typeDef:{type:"timestamp"},sql:this.d.sqlNowExpr()}}n(g){return{node:"numberLiteral",literal:g,sql:g}}delta(g,y,v,E){const _={node:"delta",op:y,units:E,kids:{base:(0,r.mkTemporal)(g,"timestamp"),delta:this.n(v)}};return{..._,sql:this.d.sqlAlterTimeExpr(_)}}dayofWeek(g){const y={node:"extract",e:(0,r.mkTemporal)(g,"timestamp"),units:"day_of_week"};return{...y,sql:this.d.sqlTimeExtractExpr(this.qi,y)}}nowDot(g){const y={node:"trunc",e:this.nowExpr(),units:g};return{...y,sql:this.d.sqlTruncExpr(this.qi,y)}}thisUnit(g){const y=this.nowDot(g),v=this.delta(y,"+","1",g);return{begin:y,end:v.sql}}lastUnit(g){const y=this.nowDot(g);return{begin:this.delta(y,"-","1",g),end:y.sql}}nextUnit(g){const y=this.nowDot(g),v=this.delta(y,"+","1",g),E=this.delta(y,"+","2",g);return{begin:v,end:E.sql}}mod7(g){return this.d.hasModOperator?`(${g})%7`:`MOD(${g},7)`}moment(g){switch(g.moment){case"now":{const y=this.nowExpr();return{begin:y,end:y.sql}}case"literal":return this.expandLiteral(g);case"ago":case"from_now":{const y=this.nowDot(g.units),v=(0,r.mkTemporal)(y,"timestamp"),E=this.delta(v,g.moment==="ago"?"-":"+",g.n,g.units);if(g.moment==="ago"&&g.n==="1")return{begin:E,end:y.sql};const _=Number(g.n)+(g.moment==="ago"?-1:1),A={...E,kids:{base:v,delta:this.n(_.toString())}};return{begin:E,end:this.d.sqlAlterTimeExpr(A)}}case"today":return this.thisUnit("day");case"yesterday":return this.lastUnit("day");case"tomorrow":return this.nextUnit("day");case"this":return this.thisUnit(g.units);case"last":return this.lastUnit(g.units);case"next":return this.nextUnit(g.units);case"sunday":return this.weekdayMoment(1,g.which);case"monday":return this.weekdayMoment(2,g.which);case"tuesday":return this.weekdayMoment(3,g.which);case"wednesday":return this.weekdayMoment(4,g.which);case"thursday":return this.weekdayMoment(5,g.which);case"friday":return this.weekdayMoment(6,g.which);case"saturday":return this.weekdayMoment(7,g.which)}}isIn(g,y,v){let E=">=",_="<",A="AND";return g&&(A="OR",E="<",_=">="),y=this.time(y),v=this.time(v),`${this.expr} ${E} ${y} ${A} ${this.expr} ${_} ${v}`}weekdayMoment(g,y){const v=y||"last",E=this.dayofWeek(this.nowExpr()),_=this.thisUnit("day").begin,A=g-1,S=`(${E.sql}-1)`;let b,C;v==="next"?(b=`${this.mod7(`${A}-${S}+6`)}+1`,C=`${this.mod7(`${A}-${S}+6`)}+2`):(b=`${this.mod7(`${S}-${A}+6`)}+1`,C=`${this.mod7(`${S}-${A}+6`)}`);const T=this.delta(_,v==="next"?"+":"-",b,"day"),D=this.delta(_,v==="next"?"+":"-",C,"day");return{begin:T,end:D.sql}}}t.TemporalFilterCompiler=p})(lfe),Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.exprToSQL=Qo,Hn.generateFunctionCallExpression=hfe,Hn.generateFieldFragment=YT,Hn.generateOutputFieldFragment=pfe,Hn.generateParameterFragment=mfe,Hn.generateFilterFragment=gfe,Hn.generateDimFragment=ul,Hn.generateUngroupedFragment=yfe,Hn.generateDistinctKeyIfNecessary=KT,Hn.generateSumFragment=vfe,Hn.generateSymmetricFragment=_fe,Hn.generateAvgFragment=Afe,Hn.generateCountFragment=Sfe,Hn.generateSourceReference=bfe,Hn.generateCaseSQL=Cfe,Hn.getFunctionOrderBy=_M,Hn.getAnalyticPartitions=Tfe,Hn.stringsFromSQLExpression=Rfe;const al=Ye,VT=W2,Lit=Ho,Iit=lfe,Is=wt,$it=Rt,cfe=9;function ffe(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-cfe);let c=`(${`(
|
|
971
971
|
SUM(DISTINCT ${`ROUND(${`CAST(COALESCE(${e}, 0) AS ${t.defaultDecimalType})`}*${o}, ${cfe})`} + ${s})
|
|
972
972
|
- SUM(DISTINCT ${s})
|
|
973
|
-
)`}/${o})`;return c=`CAST(${c} AS ${t.defaultNumberType})`,c}function Qo(t,e,r,i=new Is.GenerateState){var s;const o=function(c){const f=Qo(t,e,c,i);return(0,al.exprHasKids)(c)?`(${f})`:f};let a=r;if((0,al.exprHasE)(r)){a={...r};const c=o(a.e);a.e={...a.e,sql:c}}else if((0,al.exprHasKids)(r)){a={...r};const c=r.kids;for(const[f,d]of Object.entries(c))d!==null&&(Array.isArray(d)?a.kids[f]=d.map(x=>({...x,sql:o(x)})):a.kids[f]={...c[f],sql:o(d)})}const u=t.getQueryInfo(),l=e.dialect.exprToSQL(u,a);if(l)return l;switch(a.node){case"field":return YT(t,e,a,i);case"parameter":return mfe(t,e,a,i);case"filteredExpr":return gfe(t,e,a,i);case"all":case"exclude":return yfe(t,e,a,i);case"genericSQLExpr":return Array.from(Rfe(t,e,a,i)).join("");case"aggregate":{let c="";if(a.function==="sum")c=vfe(t,e,a,i);else if(a.function==="avg")c=Afe(t,e,a,i);else if(a.function==="count")c=Sfe(t,e,a,i);else if(a.function==="min"||a.function==="max"||a.function==="distinct")c=_fe(t,e,a,i);else throw new Error(`Internal Error: Unknown aggregate function ${a.function}`);if(t.root().isComplexQuery){let f=t.groupSet;return i.totalGroupSet!==-1&&(f=i.totalGroupSet),(0,Is.caseGroup)([f],c)}return c}case"function_parameter":throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");case"outputField":return pfe(t,e,a);case"function_call":return hfe(t,e,a,i);case"spread":throw new Error("Internal Error: expandFunctionCall() failed to process node: 'spread'");case"source-reference":return bfe(t,e,a);case"+":case"-":case"*":case"%":case"/":case">":case"<":case">=":case"<=":case"=":return`${a.kids.left.sql}${a.node}${a.kids.right.sql}`;case"!=":return`COALESCE(${`${a.kids.left.sql}!=${a.kids.right.sql}`},true)`;case"and":case"or":return`${a.kids.left.sql} ${a.node} ${a.kids.right.sql}`;case"coalesce":return`COALESCE(${a.kids.left.sql},${a.kids.right.sql})`;case"in":{const c=a.kids.oneOf.map(f=>f.sql).join(",");return`${a.kids.e.sql} ${a.not?"NOT IN":"IN"} (${c})`}case"like":case"!like":{const c=a.node==="like"?"LIKE":"NOT LIKE",f=a.kids.right.node==="stringLiteral"?e.dialect.sqlLike(c,(s=a.kids.left.sql)!==null&&s!==void 0?s:"",a.kids.right.literal):`${a.kids.left.sql} ${c} ${a.kids.right.sql}`;return a.node==="like"?f:`COALESCE(${f},true)`}case"()":return`(${a.e.sql})`;case"not":return`COALESCE(NOT ${a.e.sql},TRUE)`;case"unary-":return`-${a.e.sql}`;case"is-null":return`${a.e.sql} IS NULL`;case"is-not-null":return`${a.e.sql} IS NOT NULL`;case"true":case"false":return a.node;case"null":return"NULL";case"case":return Cfe(a);case"":return"";case"filterCondition":return a.e.sql?(a.sql=a.e.sql,a.sql):"";case"functionDefaultOrderBy":case"functionOrderBy":return"";case"compositeField":return"{COMPOSITE_FIELD}";case"filterMatch":return Bit(e,a);case"filterLiteral":return"INTERNAL ERROR FILTER EXPRESSION VALUE SHOULD NOT BE USED";default:throw new Error(`Internal Error: Unknown expression node '${a.node}' ${JSON.stringify(a,void 0,2)}`)}}function Bit(t,e){var r;let i=e.kids.filterExpr;for(;i.node==="()";)i=i.e;if(i.node==="parameter"){const a=i.path[0];(r=t.eventStream)===null||r===void 0||r.emit("source-argument-compiled",{name:a});const u=t.arguments()[a];if(u.value)i=u.value;else throw new Error(`Parameter ${a} was expected to be a filter expression`)}if(i.node!=="filterLiteral")throw new Error("Can only use filter expression literals or parameters as filter expressions");const s=i.filterSrc;let o;switch(e.dataType){case"string":o=VT.StringFilterExpression.parse(s);break;case"number":o=VT.NumberFilterExpression.parse(s);break;case"boolean":o=VT.BooleanFilterExpression.parse(s);break;case"date":case"timestamp":o=VT.TemporalFilterExpression.parse(s);break;default:throw new Error(`unsupported filter type ${e.dataType}`)}if(o.log.length>0)throw new Error(`Filter expression parse error: ${o.log[0]}`);return Iit.FilterCompilers.compile(e.dataType,o.parsed,e.kids.expr.sql||"",t.dialect)}function kit(t,e){return new Map(t.params.map((r,i)=>{const s=r.isVariadic?(0,Is.range)(i,e):[i];return[r.name,{param:r,argIndexes:s}]}))}function dfe(t,e,r,i,s){function o(l){const c=[];for(let f=0;f<l.length;)c.push(l[f]),f+=1,f<l.length&&c.push(",");return c}const a=kit(e,r.length);if(e.dialect[t]===void 0)throw new Error(`Function is not defined for '${t}' dialect`);return(0,Is.exprMap)(e.dialect[t].e,l=>{var c,f;if(l.node==="spread"){const d=l.e;if(d.node!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const x=a.get(d.name);if(x===void 0)return l;const p=x.argIndexes.map(m=>r[m]);return(0,Is.composeSQLExpr)(o(p))}else if(l.node==="function_parameter"){const d=a.get(l.name);if(d===void 0)return l;if(d.param.isVariadic){const x=d.argIndexes.map(p=>r[p]);return(0,Is.composeSQLExpr)(o(x))}else return r[d.argIndexes[0]]}else{if(l.node==="aggregate_order_by")return i?(0,Is.composeSQLExpr)([` ${(c=l.prefix)!==null&&c!==void 0?c:""}${i}${(f=l.suffix)!==null&&f!==void 0?f:""}`]):{node:""};if(l.node==="aggregate_limit")return s?(0,Is.composeSQLExpr)([` ${s}`]):{node:""}}return l})}function xfe(t,e){const r=t.slice(0,e).find(i=>i.isVariadic);return r??t[e]}function Mit(t,e,r,i,s,o,a,u){if(o)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${a}`);const l=ul(t,e,r,u),c=i?ul(t,e,i,u):"";return e.dialect.sqlStringAggDistinct(s,l,c)}function Pit(t,e,r,i,s,o,a,u,l){const c=e.root().isComplexQuery,f=Tfe(e,u),d=[...c?["group_set"]:[],...f],x=d.length>0?`PARTITION BY ${d.join(", ")}`:"";let p=l??"";const m=s.dialect[t];if(!l&&m.needsWindowOrderBy){const E=[];let _;const A=e.firstSegment.orderBy||e.calculateDefaultOrderBy();for(const S of A){if(typeof S.field=="string"?_={name:S.field,fif:e.getField(S.field)}:_=e.getFieldByNumber(S.field),"expressionType"in _.fif.f.fieldDef){const b=_.fif.f.fieldDef.expressionType;if((0,al.expressionIsAnalytic)(b))continue}if(e.firstSegment.type==="reduce"){const b=_.fif.getAnalyticalSQL(!1);E.push(` ${b} ${S.dir||"ASC"}`)}else if(e.firstSegment.type==="project"){if(_.fif.parent!==e)throw new Error(`Field instance parent mismatch: field '${_.name}' has parent from different result structure. This likely means the field is from a previous pipeline stage and needs special handling.`);const b=_.fif.generateExpression();E.push(` ${b} ${S.dir||"ASC"}`)}}E.length>0&&(p=" "+r.dialect.sqlOrderBy(E,"analytical"))}let g="";if(m.between){const[E,_]=[m.between.preceding,m.between.following].map(A=>{if(A===-1)return"UNBOUNDED";if(typeof A=="number")return A;const S=s.params.findIndex(C=>C.name===A),b=a[S];if(b.node!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return b.literal});g=`ROWS BETWEEN ${E} PRECEDING AND ${_} FOLLOWING`}let v=`${Qo(e,r,i,o)} OVER(${x} ${p} ${g})`;return c&&(v=`CASE WHEN group_set=${e.groupSet} THEN ${v} END`),v}function hfe(t,e,r,i){var s,o,a;const u=r.overload,l=r.kids.args,c=(s=r.overload.isSymmetric)!==null&&s!==void 0?s:!1,f=(0,al.expressionIsAggregate)(u.returnType.expressionType)&&!c&&KT(t,e,r.structPath),d=r.limit?`LIMIT ${r.limit}`:void 0;if(r.name==="string_agg"&&f&&!e.dialect.supportsAggDistinct&&e.dialect.name!=="snowflake")return Mit(t,e,l[0],l[1],f,r.kids.orderBy,e.dialect.name,i);if(f){if(!e.dialect.supportsAggDistinct)throw new Error(`Function \`${r.name}\` does not support fanning out in ${e.dialect.name}`);const x=l.map(g=>ul(t,e,g,i)),p=(o=r.kids.orderBy)!==null&&o!==void 0?o:[],m=p.map(g=>{var y;const v=(y=u.dialect[e.dialect.name].defaultOrderByArgIndex)!==null&&y!==void 0?y:0,E=g.node==="functionOrderBy"?g.e:l[v];return ul(t,e,E,i)});return e.dialect.sqlAggDistinct(f,[...x,...m],g=>{const y=g.map((S,b)=>b<l.length&&xfe(u.params,b).allowedTypes.every(T=>(0,al.isLiteral)(T.evalSpace))?l[b]:(0,Is.composeSQLExpr)([S])),v=y.slice(0,x.length),E=y.slice(x.length).map((S,b)=>({node:"functionOrderBy",e:S,dir:p[b].dir})),_=_M(t,e,i,E,v,u),A=dfe(e.dialect.name,u,v,_,d);return Qo(t,e,A,i)})}else{const x=(0,al.expressionIsAggregate)(u.returnType.expressionType)?l.map((g,y)=>xfe(u.params,y).allowedTypes.every(E=>(0,al.isLiteral)(E.evalSpace))?g:(0,Is.composeSQLExpr)([ul(t,e,g,i)])):l,p=r.kids.orderBy?_M(t,e,i,r.kids.orderBy,l,u):"",m=dfe(e.dialect.name,u,x,p,d);if((0,al.expressionIsAnalytic)(u.returnType.expressionType)){const g=((a=r.partitionBy)!==null&&a!==void 0?a:[]).map(y=>`(${t.getField(y).getAnalyticalSQL(!1)})`);return Pit(e.dialect.name,t,e,m,u,i,l,g,p)}return Qo(t,e,m,i)}}function YT(t,e,r,i){const s=e.getFieldByName(r.path);return(0,al.hasExpression)(s.fieldDef)?`(${Qo(t,s.parent,s.fieldDef.e,i)})`:s.fieldDef.type==="string"&&s.fieldDef.name==="__distinct_key"?Dfe(s,t):(0,Lit.sqlFullChildReference)(s.parent,s.fieldDef.name,s.parent.structDef.type==="record"?{result:t,field:s}:void 0)}function pfe(t,e,r,i){return`(${t.getField(r.name).getAnalyticalSQL(!1)})`}function mfe(t,e,r,i){var s;const o=r.path[0];(s=e.eventStream)===null||s===void 0||s.emit("source-argument-compiled",{name:o});const a=e.arguments()[o];if(a.value)return Qo(t,e,a.value,i);throw new Error(`Can't generate SQL, no value for ${r.path}`)}function gfe(t,e,r,i){const s=new Is.AndChain(i.whereSQL);for(const o of r.kids.filterList)s.add(Qo(t,e,o.e,i.withWhere()));return Qo(t,e,r.kids.e,i.withWhere(s.sql()))}function ul(t,e,r,i){let s=Qo(t,e,r,i);return i.whereSQL&&(s=`CASE WHEN ${i.whereSQL} THEN ${s} END`),s}function yfe(t,e,r,i){if(i.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let s,o;if(r.fields&&r.fields.length>0){const f=(0,Is.groupingKey)(r.node,r.fields);if(o=t.ungroupedSets.get(f),o===void 0)throw new Error(`Internal Error, cannot find groupset with key ${f}`);s=o.groupSet}else s=t.parent?t.parent.groupSet:0;const a=Qo(t,e,r.e,i.withTotal(s)),u=t.getUngroupPartitions(o);let l="";const c=u.map(f=>f.getAnalyticalSQL(!0)).join(", ");return c.length>0&&(l=`PARTITION BY ${c}`),`MAX(${a}) OVER (${l})`}function Efe(t,e){const r=t.getDistinctKey();return Dfe(r,e)}function KT(t,e,r){let i=e;if(r&&(i=e.getStructByName(r)),Uit(i,t))return Efe(i,t)}function vfe(t,e,r,i){const s=ul(t,e,r.e,i),o=KT(t,e,r.structPath);let a;return o?e.dialect.supportsSumDistinctFunction?a=e.dialect.sqlSumDistinct(o,s,"SUM"):a=ffe(e.dialect,s,o):a=`SUM(${s})`,`COALESCE(${a},0)`}function _fe(t,e,r,i){const s=ul(t,e,r.e,i);return`${r.function==="distinct"?"count(distinct ":r.function+"("}${s})`}function Afe(t,e,r,i){const s=ul(t,e,r.e,i),o=KT(t,e,r.structPath);if(o){let a=o;i.whereSQL&&(a=`CASE WHEN ${i.whereSQL} THEN ${o} END`);let u,l;return e.dialect.supportsSumDistinctFunction?l=e.dialect.sqlSumDistinct(o,s,"AVG"):(u=ffe(e.dialect,s,o),l=`(${u})/NULLIF(COUNT(DISTINCT CASE WHEN ${s} IS NOT NULL THEN ${a} END),0)`),l}else return`AVG(${s})`}function Sfe(t,e,r,i){let s="COUNT(",o="1",a=e;r.structPath&&(a=e.getStructByName(r.structPath));const u=a.getJoinableParent().getIdentifier(),l=t.root().joins.get(u);if(!l)throw new Error(`Join ${u} not found in result set`);return(!l.leafiest||l.makeUniqueKey)&&(s="COUNT(DISTINCT ",o=Efe(a,t)),i.whereSQL?`${s}CASE WHEN ${i.whereSQL} THEN ${o} END)`:`${s}${o})`}function bfe(t,e,r){return r.path===void 0?e.getSQLIdentifier():e.getFieldByName(r.path).getIdentifier()}function Cfe(t){const e=["CASE"];t.kids.caseValue!==void 0&&e.push(`${t.kids.caseValue.sql}`);for(let r=0;r<t.kids.caseWhen.length;r+=1)e.push(`WHEN ${t.kids.caseWhen[r].sql} THEN ${t.kids.caseThen[r].sql}`);return t.kids.caseElse!==void 0&&e.push(`ELSE ${t.kids.caseElse.sql}`),e.push("END"),e.join(" ")}function _M(t,e,r,i,s,o){if(i.length!==0)return"ORDER BY "+i.map(a=>{var u;const l=(u=o.dialect[e.dialect.name].defaultOrderByArgIndex)!==null&&u!==void 0?u:0,c=a.node==="functionOrderBy"?a.e:s[l],f=ul(t,e,c,r),d=a.dir==="asc"?" ASC":a.dir==="desc"?" DESC":"";return`${f}${d}`}).join(", ")}function Tfe(t,e){const r=[];let i=t.parent;for(;i!==void 0;){const o=i.fields(a=>(0,$it.isBasicScalar)(a.f)&&a.fieldUsage.type==="result").map(a=>a.getAnalyticalSQL(!0));r.push(...o),i=i.parent}return e&&r.push(...e),r}function*Rfe(t,e,r,i){const s=[...r.kids.args];for(const o of r.src){yield o;const a=s.shift();a&&(yield Qo(t,e,a,i))}}function Dfe(t,e){var r;const i=t.parent;if(i.primaryKey()){const s=i.getPrimaryKeyField(t.fieldDef);return YT(e,i,{node:"field",path:[s.getIdentifier()]},new Is.GenerateState)}else if(i.structDef.type==="array"){const s=(r=i.parent)===null||r===void 0?void 0:r.getDistinctKey();let o="";return s&&i.parent&&(o=YT(e,i.parent,{node:"field",path:["__distinct_key"]},new Is.GenerateState)),i.dialect.sqlMakeUnnestKey(o,i.dialect.sqlFieldReference(i.getIdentifier(),"table","__row_id","string"))}else return i.dialect.sqlFieldReference(i.getIdentifier(),"table","__distinct_key","string")}function Uit(t,e){const r=t.getJoinableParent().getIdentifier(),i=e.root().joins.get(r);if(i)return!i.leafiest;throw new Error(`Join ${r} not found in result set`)}var KE={},XE={},Y2={};Object.defineProperty(Y2,"__esModule",{value:!0}),Y2.shouldMaterialize=zit,Y2.buildQueryMaterializationSpec=Hit;const jit=wt,qit=Ns;function zit(t){const e=structuredClone(t);return e&&(e.inherits=void 0),(0,qit.annotationToTag)(e).tag.has("materialize")}function Hit(t,e,r){if(!e)throw new Error(`Query tagged to materialize, but its name is not specified. ${t}`);if(!t)throw new Error(`Query tagged to materialize, but its path is not specified: ${e}`);const i={path:t,source:void 0,queryName:e},s=(0,jit.generateHash)(JSON.stringify(i)).replace(/-/g,"_"),o=`${r?`${r}_`:""}${e}_${s}`;return{...i,id:o}}Object.defineProperty(XE,"__esModule",{value:!0}),XE.StageWriter=void 0;const Qit=Y2,K2=wt;class Git{constructor(e=!0,r){this.parent=r,this.withs=[],this.stageNames=[],this.udfs=[],this.pdts=[],this.dependenciesToMaterialize={},this.stagePrefix="__stage",this.stageNumber=0,this.useCTE=e}nextName(){return`${this.stagePrefix}${this.root().stageNumber++}`}getName(e){return this.stageNames[e]}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){if(this.useCTE){this.withs.push(e);const r=this.nextName();return this.stageNames.push(r),r}else return this.withs[0]=e,(0,K2.indent)(`
|
|
973
|
+
)`}/${o})`;return c=`CAST(${c} AS ${t.defaultNumberType})`,c}function Qo(t,e,r,i=new Is.GenerateState){var s;const o=function(c){const f=Qo(t,e,c,i);return(0,al.exprHasKids)(c)?`(${f})`:f};let a=r;if((0,al.exprHasE)(r)){a={...r};const c=o(a.e);a.e={...a.e,sql:c}}else if((0,al.exprHasKids)(r)){a={...r};const c=r.kids;for(const[f,d]of Object.entries(c))d!==null&&(Array.isArray(d)?a.kids[f]=d.map(x=>({...x,sql:o(x)})):a.kids[f]={...c[f],sql:o(d)})}const u=t.getQueryInfo(),l=e.dialect.exprToSQL(u,a);if(l)return l;switch(a.node){case"field":return YT(t,e,a,i);case"parameter":return mfe(t,e,a,i);case"filteredExpr":return gfe(t,e,a,i);case"all":case"exclude":return yfe(t,e,a,i);case"genericSQLExpr":return Array.from(Rfe(t,e,a,i)).join("");case"aggregate":{let c="";if(a.function==="sum")c=vfe(t,e,a,i);else if(a.function==="avg")c=Afe(t,e,a,i);else if(a.function==="count")c=Sfe(t,e,a,i);else if(a.function==="min"||a.function==="max"||a.function==="distinct")c=_fe(t,e,a,i);else throw new Error(`Internal Error: Unknown aggregate function ${a.function}`);if(t.root().isComplexQuery){let f=t.groupSet;return i.totalGroupSet!==-1&&(f=i.totalGroupSet),(0,Is.caseGroup)([f],c)}return c}case"function_parameter":throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");case"outputField":return pfe(t,e,a);case"function_call":return hfe(t,e,a,i);case"spread":throw new Error("Internal Error: expandFunctionCall() failed to process node: 'spread'");case"source-reference":return bfe(t,e,a);case"+":case"-":case"*":case"%":case"/":case">":case"<":case">=":case"<=":case"=":return`${a.kids.left.sql}${a.node}${a.kids.right.sql}`;case"!=":return`COALESCE(${`${a.kids.left.sql}!=${a.kids.right.sql}`},true)`;case"and":case"or":return`${a.kids.left.sql} ${a.node} ${a.kids.right.sql}`;case"coalesce":return`COALESCE(${a.kids.left.sql},${a.kids.right.sql})`;case"in":{const c=a.kids.oneOf.map(f=>f.sql).join(",");return`${a.kids.e.sql} ${a.not?"NOT IN":"IN"} (${c})`}case"like":case"!like":{const c=a.node==="like"?"LIKE":"NOT LIKE",f=a.kids.right.node==="stringLiteral"?e.dialect.sqlLike(c,(s=a.kids.left.sql)!==null&&s!==void 0?s:"",a.kids.right.literal):`${a.kids.left.sql} ${c} ${a.kids.right.sql}`;return a.node==="like"?f:`COALESCE(${f},true)`}case"()":return`(${a.e.sql})`;case"not":return`COALESCE(NOT ${a.e.sql},TRUE)`;case"unary-":return`-${a.e.sql}`;case"is-null":return`${a.e.sql} IS NULL`;case"is-not-null":return`${a.e.sql} IS NOT NULL`;case"true":case"false":return a.node;case"null":return"NULL";case"case":return Cfe(a);case"":return"";case"filterCondition":return a.e.sql?(a.sql=a.e.sql,a.sql):"";case"functionDefaultOrderBy":case"functionOrderBy":return"";case"compositeField":return"{COMPOSITE_FIELD}";case"filterMatch":return Bit(e,a,u);case"filterLiteral":return"INTERNAL ERROR FILTER EXPRESSION VALUE SHOULD NOT BE USED";default:throw new Error(`Internal Error: Unknown expression node '${a.node}' ${JSON.stringify(a,void 0,2)}`)}}function Bit(t,e,r){var i;let s=e.kids.filterExpr;for(;s.node==="()";)s=s.e;if(s.node==="parameter"){const u=s.path[0];(i=t.eventStream)===null||i===void 0||i.emit("source-argument-compiled",{name:u});const l=t.arguments()[u];if(l.value)s=l.value;else throw new Error(`Parameter ${u} was expected to be a filter expression`)}if(s.node!=="filterLiteral")throw new Error("Can only use filter expression literals or parameters as filter expressions");const o=s.filterSrc;let a;switch(e.dataType){case"string":a=VT.StringFilterExpression.parse(o);break;case"number":a=VT.NumberFilterExpression.parse(o);break;case"boolean":a=VT.BooleanFilterExpression.parse(o);break;case"date":case"timestamp":a=VT.TemporalFilterExpression.parse(o);break;default:throw new Error(`unsupported filter type ${e.dataType}`)}if(a.log.length>0)throw new Error(`Filter expression parse error: ${a.log[0]}`);return Iit.FilterCompilers.compile(e.dataType,a.parsed,e.kids.expr.sql||"",t.dialect,r)}function kit(t,e){return new Map(t.params.map((r,i)=>{const s=r.isVariadic?(0,Is.range)(i,e):[i];return[r.name,{param:r,argIndexes:s}]}))}function dfe(t,e,r,i,s){function o(l){const c=[];for(let f=0;f<l.length;)c.push(l[f]),f+=1,f<l.length&&c.push(",");return c}const a=kit(e,r.length);if(e.dialect[t]===void 0)throw new Error(`Function is not defined for '${t}' dialect`);return(0,Is.exprMap)(e.dialect[t].e,l=>{var c,f;if(l.node==="spread"){const d=l.e;if(d.node!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const x=a.get(d.name);if(x===void 0)return l;const p=x.argIndexes.map(m=>r[m]);return(0,Is.composeSQLExpr)(o(p))}else if(l.node==="function_parameter"){const d=a.get(l.name);if(d===void 0)return l;if(d.param.isVariadic){const x=d.argIndexes.map(p=>r[p]);return(0,Is.composeSQLExpr)(o(x))}else return r[d.argIndexes[0]]}else{if(l.node==="aggregate_order_by")return i?(0,Is.composeSQLExpr)([` ${(c=l.prefix)!==null&&c!==void 0?c:""}${i}${(f=l.suffix)!==null&&f!==void 0?f:""}`]):{node:""};if(l.node==="aggregate_limit")return s?(0,Is.composeSQLExpr)([` ${s}`]):{node:""}}return l})}function xfe(t,e){const r=t.slice(0,e).find(i=>i.isVariadic);return r??t[e]}function Mit(t,e,r,i,s,o,a,u){if(o)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${a}`);const l=ul(t,e,r,u),c=i?ul(t,e,i,u):"";return e.dialect.sqlStringAggDistinct(s,l,c)}function Pit(t,e,r,i,s,o,a,u,l){const c=e.root().isComplexQuery,f=Tfe(e,u),d=[...c?["group_set"]:[],...f],x=d.length>0?`PARTITION BY ${d.join(", ")}`:"";let p=l??"";const m=s.dialect[t];if(!l&&m.needsWindowOrderBy){const E=[];let _;const A=e.firstSegment.orderBy||e.calculateDefaultOrderBy();for(const S of A){if(typeof S.field=="string"?_={name:S.field,fif:e.getField(S.field)}:_=e.getFieldByNumber(S.field),"expressionType"in _.fif.f.fieldDef){const b=_.fif.f.fieldDef.expressionType;if((0,al.expressionIsAnalytic)(b))continue}if(e.firstSegment.type==="reduce"){const b=_.fif.getAnalyticalSQL(!1);E.push(` ${b} ${S.dir||"ASC"}`)}else if(e.firstSegment.type==="project"){if(_.fif.parent!==e)throw new Error(`Field instance parent mismatch: field '${_.name}' has parent from different result structure. This likely means the field is from a previous pipeline stage and needs special handling.`);const b=_.fif.generateExpression();E.push(` ${b} ${S.dir||"ASC"}`)}}E.length>0&&(p=" "+r.dialect.sqlOrderBy(E,"analytical"))}let g="";if(m.between){const[E,_]=[m.between.preceding,m.between.following].map(A=>{if(A===-1)return"UNBOUNDED";if(typeof A=="number")return A;const S=s.params.findIndex(C=>C.name===A),b=a[S];if(b.node!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return b.literal});g=`ROWS BETWEEN ${E} PRECEDING AND ${_} FOLLOWING`}let v=`${Qo(e,r,i,o)} OVER(${x} ${p} ${g})`;return c&&(v=`CASE WHEN group_set=${e.groupSet} THEN ${v} END`),v}function hfe(t,e,r,i){var s,o,a;const u=r.overload,l=r.kids.args,c=(s=r.overload.isSymmetric)!==null&&s!==void 0?s:!1,f=(0,al.expressionIsAggregate)(u.returnType.expressionType)&&!c&&KT(t,e,r.structPath),d=r.limit?`LIMIT ${r.limit}`:void 0;if(r.name==="string_agg"&&f&&!e.dialect.supportsAggDistinct&&e.dialect.name!=="snowflake")return Mit(t,e,l[0],l[1],f,r.kids.orderBy,e.dialect.name,i);if(f){if(!e.dialect.supportsAggDistinct)throw new Error(`Function \`${r.name}\` does not support fanning out in ${e.dialect.name}`);const x=l.map(g=>ul(t,e,g,i)),p=(o=r.kids.orderBy)!==null&&o!==void 0?o:[],m=p.map(g=>{var y;const v=(y=u.dialect[e.dialect.name].defaultOrderByArgIndex)!==null&&y!==void 0?y:0,E=g.node==="functionOrderBy"?g.e:l[v];return ul(t,e,E,i)});return e.dialect.sqlAggDistinct(f,[...x,...m],g=>{const y=g.map((S,b)=>b<l.length&&xfe(u.params,b).allowedTypes.every(T=>(0,al.isLiteral)(T.evalSpace))?l[b]:(0,Is.composeSQLExpr)([S])),v=y.slice(0,x.length),E=y.slice(x.length).map((S,b)=>({node:"functionOrderBy",e:S,dir:p[b].dir})),_=_M(t,e,i,E,v,u),A=dfe(e.dialect.name,u,v,_,d);return Qo(t,e,A,i)})}else{const x=(0,al.expressionIsAggregate)(u.returnType.expressionType)?l.map((g,y)=>xfe(u.params,y).allowedTypes.every(E=>(0,al.isLiteral)(E.evalSpace))?g:(0,Is.composeSQLExpr)([ul(t,e,g,i)])):l,p=r.kids.orderBy?_M(t,e,i,r.kids.orderBy,l,u):"",m=dfe(e.dialect.name,u,x,p,d);if((0,al.expressionIsAnalytic)(u.returnType.expressionType)){const g=((a=r.partitionBy)!==null&&a!==void 0?a:[]).map(y=>`(${t.getField(y).getAnalyticalSQL(!1)})`);return Pit(e.dialect.name,t,e,m,u,i,l,g,p)}return Qo(t,e,m,i)}}function YT(t,e,r,i){const s=e.getFieldByName(r.path);return(0,al.hasExpression)(s.fieldDef)?`(${Qo(t,s.parent,s.fieldDef.e,i)})`:s.fieldDef.type==="string"&&s.fieldDef.name==="__distinct_key"?Dfe(s,t):(0,Lit.sqlFullChildReference)(s.parent,s.fieldDef.name,s.parent.structDef.type==="record"?{result:t,field:s}:void 0)}function pfe(t,e,r,i){return`(${t.getField(r.name).getAnalyticalSQL(!1)})`}function mfe(t,e,r,i){var s;const o=r.path[0];(s=e.eventStream)===null||s===void 0||s.emit("source-argument-compiled",{name:o});const a=e.arguments()[o];if(a.value)return Qo(t,e,a.value,i);throw new Error(`Can't generate SQL, no value for ${r.path}`)}function gfe(t,e,r,i){const s=new Is.AndChain(i.whereSQL);for(const o of r.kids.filterList)s.add(Qo(t,e,o.e,i.withWhere()));return Qo(t,e,r.kids.e,i.withWhere(s.sql()))}function ul(t,e,r,i){let s=Qo(t,e,r,i);return i.whereSQL&&(s=`CASE WHEN ${i.whereSQL} THEN ${s} END`),s}function yfe(t,e,r,i){if(i.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let s,o;if(r.fields&&r.fields.length>0){const f=(0,Is.groupingKey)(r.node,r.fields);if(o=t.ungroupedSets.get(f),o===void 0)throw new Error(`Internal Error, cannot find groupset with key ${f}`);s=o.groupSet}else s=t.parent?t.parent.groupSet:0;const a=Qo(t,e,r.e,i.withTotal(s)),u=t.getUngroupPartitions(o);let l="";const c=u.map(f=>f.getAnalyticalSQL(!0)).join(", ");return c.length>0&&(l=`PARTITION BY ${c}`),`MAX(${a}) OVER (${l})`}function Efe(t,e){const r=t.getDistinctKey();return Dfe(r,e)}function KT(t,e,r){let i=e;if(r&&(i=e.getStructByName(r)),Uit(i,t))return Efe(i,t)}function vfe(t,e,r,i){const s=ul(t,e,r.e,i),o=KT(t,e,r.structPath);let a;return o?e.dialect.supportsSumDistinctFunction?a=e.dialect.sqlSumDistinct(o,s,"SUM"):a=ffe(e.dialect,s,o):a=`SUM(${s})`,`COALESCE(${a},0)`}function _fe(t,e,r,i){const s=ul(t,e,r.e,i);return`${r.function==="distinct"?"count(distinct ":r.function+"("}${s})`}function Afe(t,e,r,i){const s=ul(t,e,r.e,i),o=KT(t,e,r.structPath);if(o){let a=o;i.whereSQL&&(a=`CASE WHEN ${i.whereSQL} THEN ${o} END`);let u,l;return e.dialect.supportsSumDistinctFunction?l=e.dialect.sqlSumDistinct(o,s,"AVG"):(u=ffe(e.dialect,s,o),l=`(${u})/NULLIF(COUNT(DISTINCT CASE WHEN ${s} IS NOT NULL THEN ${a} END),0)`),l}else return`AVG(${s})`}function Sfe(t,e,r,i){let s="COUNT(",o="1",a=e;r.structPath&&(a=e.getStructByName(r.structPath));const u=a.getJoinableParent().getIdentifier(),l=t.root().joins.get(u);if(!l)throw new Error(`Join ${u} not found in result set`);return(!l.leafiest||l.makeUniqueKey)&&(s="COUNT(DISTINCT ",o=Efe(a,t)),i.whereSQL?`${s}CASE WHEN ${i.whereSQL} THEN ${o} END)`:`${s}${o})`}function bfe(t,e,r){return r.path===void 0?e.getSQLIdentifier():e.getFieldByName(r.path).getIdentifier()}function Cfe(t){const e=["CASE"];t.kids.caseValue!==void 0&&e.push(`${t.kids.caseValue.sql}`);for(let r=0;r<t.kids.caseWhen.length;r+=1)e.push(`WHEN ${t.kids.caseWhen[r].sql} THEN ${t.kids.caseThen[r].sql}`);return t.kids.caseElse!==void 0&&e.push(`ELSE ${t.kids.caseElse.sql}`),e.push("END"),e.join(" ")}function _M(t,e,r,i,s,o){if(i.length!==0)return"ORDER BY "+i.map(a=>{var u;const l=(u=o.dialect[e.dialect.name].defaultOrderByArgIndex)!==null&&u!==void 0?u:0,c=a.node==="functionOrderBy"?a.e:s[l],f=ul(t,e,c,r),d=a.dir==="asc"?" ASC":a.dir==="desc"?" DESC":"";return`${f}${d}`}).join(", ")}function Tfe(t,e){const r=[];let i=t.parent;for(;i!==void 0;){const o=i.fields(a=>(0,$it.isBasicScalar)(a.f)&&a.fieldUsage.type==="result").map(a=>a.getAnalyticalSQL(!0));r.push(...o),i=i.parent}return e&&r.push(...e),r}function*Rfe(t,e,r,i){const s=[...r.kids.args];for(const o of r.src){yield o;const a=s.shift();a&&(yield Qo(t,e,a,i))}}function Dfe(t,e){var r;const i=t.parent;if(i.primaryKey()){const s=i.getPrimaryKeyField(t.fieldDef);return YT(e,i,{node:"field",path:[s.getIdentifier()]},new Is.GenerateState)}else if(i.structDef.type==="array"){const s=(r=i.parent)===null||r===void 0?void 0:r.getDistinctKey();let o="";return s&&i.parent&&(o=YT(e,i.parent,{node:"field",path:["__distinct_key"]},new Is.GenerateState)),i.dialect.sqlMakeUnnestKey(o,i.dialect.sqlFieldReference(i.getIdentifier(),"table","__row_id","string"))}else return i.dialect.sqlFieldReference(i.getIdentifier(),"table","__distinct_key","string")}function Uit(t,e){const r=t.getJoinableParent().getIdentifier(),i=e.root().joins.get(r);if(i)return!i.leafiest;throw new Error(`Join ${r} not found in result set`)}var KE={},XE={},Y2={};Object.defineProperty(Y2,"__esModule",{value:!0}),Y2.shouldMaterialize=zit,Y2.buildQueryMaterializationSpec=Hit;const jit=wt,qit=Ns;function zit(t){const e=structuredClone(t);return e&&(e.inherits=void 0),(0,qit.annotationToTag)(e).tag.has("materialize")}function Hit(t,e,r){if(!e)throw new Error(`Query tagged to materialize, but its name is not specified. ${t}`);if(!t)throw new Error(`Query tagged to materialize, but its path is not specified: ${e}`);const i={path:t,source:void 0,queryName:e},s=(0,jit.generateHash)(JSON.stringify(i)).replace(/-/g,"_"),o=`${r?`${r}_`:""}${e}_${s}`;return{...i,id:o}}Object.defineProperty(XE,"__esModule",{value:!0}),XE.StageWriter=void 0;const Qit=Y2,K2=wt;class Git{constructor(e=!0,r){this.parent=r,this.withs=[],this.stageNames=[],this.udfs=[],this.pdts=[],this.dependenciesToMaterialize={},this.stagePrefix="__stage",this.stageNumber=0,this.useCTE=e}nextName(){return`${this.stagePrefix}${this.root().stageNumber++}`}getName(e){return this.stageNames[e]}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){if(this.useCTE){this.withs.push(e);const r=this.nextName();return this.stageNames.push(r),r}else return this.withs[0]=e,(0,K2.indent)(`
|
|
974
974
|
(${e})
|
|
975
975
|
`)}addUDF(e,r,i){var s;let{sql:o,lastStageName:a}=e.combineStages(!0);if(a===void 0)throw new Error("Internal Error: no stage to combine");o+=r.sqlCreateFunctionCombineLastStage(a,(0,K2.getDialectFieldList)(i),(s=i.resultMetadata)===null||s===void 0?void 0:s.orderBy);const u=`${r.udfPrefix}${this.root().udfs.length}`;return o=r.sqlCreateFunction(u,o),this.root().udfs.push(o),u}addMaterializedQuery(e,r,i){var s;const o=r.name;if(!o)throw new Error(`Source ${e} on a unnamed query that is tagged as materialize, only named queries can be materialized.`);const a=(s=r.location)===null||s===void 0?void 0:s.url;if(!a)throw new Error(`Trying to materialize query ${o}, but its path is not set.`);const u=(0,Qit.buildQueryMaterializationSpec)(a,o,i);return this.root().dependenciesToMaterialize[u.id]=u,u.id}addPDT(e,r){const i=this.combineStages(!1).sql+this.withs[this.withs.length-1],o=`scratch.${e+(0,K2.generateHash)(i)}`;return this.root().pdts.push(r.sqlCreateTableAsSelect(o,i)),o}combineStages(e){if(!this.useCTE)return{sql:this.withs[0],lastStageName:this.withs[0]};let r=this.getName(0),i="WITH ",s="";for(let o=0;o<this.withs.length-(e?0:1);o++){const a=this.withs[o];if(r=this.getName(o),a===void 0)throw new Error(`Expected sql WITH to be present for stage ${r}.`);s+=`${i}${r} AS (
|
|
976
976
|
${(0,K2.indent)(a)})
|
|
@@ -1394,7 +1394,7 @@ z{{{{{{{{Ӊ
|
|
|
1394
1394
|
| ${" ".repeat(u)}^`)}else s=`line ${a+1}: char ${u}: ${i.message}`}r!==o&&(s=`FILE: ${o}
|
|
1395
1395
|
`+s,r=o),e!==""?e=`${e}
|
|
1396
1396
|
${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const a of s.modelDef.exports){const u=s.modelDef.contents[a];((0,Nmt.isSourceDef)(u)||u.type==="query")&&(r[a]=u)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,Aj.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,Aj.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Af.MalloyTranslation=Sj;class w2e extends Sj{constructor(e,r){super(e),this.root=r}}Af.MalloyChildTranslator=w2e;class Zmt extends Sj{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new _j.Zone,this.importZone=new _j.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new _j.Zone,this.root=this,this.logger=new D2e.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,D2e.makeLogMessage)(e,r,{severity:"error",...i})),e}}Af.MalloyTranslator=Zmt;function O2e(t){return[...Object.keys(t),...Object.keys(t).map(e=>O2e(t[e])).flat()]}var n_={};Object.defineProperty(n_,"__esModule",{value:!0}),n_.ExploreQueryWalker=void 0,n_.exploreQueryWalkerBuilder=tgt;const egt=Z0;class F2e{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}n_.ExploreQueryWalker=F2e;function tgt(t,e){const r=new F2e(t),i=r;return egt.ParseTreeWalker.DEFAULT.walk(i,e),r}var r_={},i_={},eu={},ch={},s_={};Object.defineProperty(s_,"__esModule",{value:!0}),s_.MALLOY_INTERFACE_TYPES=void 0,s_.MALLOY_INTERFACE_TYPES={Aggregate:{type:"struct",name:"Aggregate",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},Annotation:{type:"struct",name:"Annotation",fields:{value:{type:"string",optional:!1,array:!1}}},AnonymousQueryInfo:{type:"struct",name:"AnonymousQueryInfo",fields:{schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},ArrayCell:{type:"struct",name:"ArrayCell",fields:{array_value:{type:"Cell",array:!0,optional:!1}}},ArrayType:{type:"struct",name:"ArrayType",fields:{element_type:{type:"AtomicType",optional:!1,array:!1}}},AtomicType:{type:"union",name:"AtomicType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType"}},BooleanCell:{type:"struct",name:"BooleanCell",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanLiteral:{type:"struct",name:"BooleanLiteral",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanType:{type:"struct",name:"BooleanType",fields:{}},CalculateInfo:{type:"struct",name:"CalculateInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},CalculateOperation:{type:"struct",name:"CalculateOperation",fields:{name:{type:"string",optional:!1,array:!1},field:{type:"Field",optional:!1,array:!1}}},Cell:{type:"union",name:"Cell",options:{string_cell:"StringCell",boolean_cell:"BooleanCell",date_cell:"DateCell",timestamp_cell:"TimestampCell",number_cell:"NumberCell",json_cell:"JSONCell",record_cell:"RecordCell",array_cell:"ArrayCell",null_cell:"NullCell",sql_native_cell:"SQLNativeCell"}},CompileModelRequest:{type:"struct",name:"CompileModelRequest",fields:{model_url:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileModelResponse:{type:"struct",name:"CompileModelResponse",fields:{model:{type:"ModelInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},CompileQueryRequest:{type:"struct",name:"CompileQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!0,array:!1},query_malloy:{type:"string",optional:!0,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileQueryResponse:{type:"struct",name:"CompileQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},CompileSourceRequest:{type:"struct",name:"CompileSourceRequest",fields:{model_url:{type:"string",optional:!1,array:!1},name:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileSourceResponse:{type:"struct",name:"CompileSourceResponse",fields:{source:{type:"SourceInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},CompilerNeeds:{type:"struct",name:"CompilerNeeds",fields:{table_schemas:{type:"SQLTable",array:!0,optional:!0},sql_schemas:{type:"SQLQuery",array:!0,optional:!0},files:{type:"File",array:!0,optional:!0},connections:{type:"Connection",array:!0,optional:!0},translations:{type:"Translation",array:!0,optional:!0}}},Connection:{type:"struct",name:"Connection",fields:{name:{type:"string",optional:!1,array:!1},dialect:{type:"string",optional:!0,array:!1}}},Data:{type:"union",name:"Data",options:{record_cell:"RecordCell",array_cell:"ArrayCell"}},DateCell:{type:"struct",name:"DateCell",fields:{date_value:{type:"string",optional:!1,array:!1}}},DateLiteral:{type:"struct",name:"DateLiteral",fields:{date_value:{type:"string",optional:!1,array:!1},granularity:{type:"DateTimeframe",optional:!0,array:!1},timezone:{type:"string",optional:!0,array:!1}}},DateTimeframe:{type:"enum",name:"DateTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5}},DateType:{type:"struct",name:"DateType",fields:{timeframe:{type:"DateTimeframe",optional:!0,array:!1}}},DimensionInfo:{type:"struct",name:"DimensionInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},DocumentPosition:{type:"struct",name:"DocumentPosition",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},DocumentRange:{type:"struct",name:"DocumentRange",fields:{start:{type:"DocumentPosition",optional:!1,array:!1},end:{type:"DocumentPosition",optional:!1,array:!1}}},DrillOperation:{type:"struct",name:"DrillOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},Expression:{type:"union",name:"Expression",options:{field_reference:"Reference",time_truncation:"TimeTruncationFieldReference",filtered_field:"FilteredField",literal_value:"LiteralValueExpression",moving_average:"MovingAverage"}},Field:{type:"struct",name:"Field",fields:{expression:{type:"Expression",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},FieldInfo:{type:"union",name:"FieldInfo",options:{dimension:"DimensionInfo",measure:"MeasureInfo",join:"JoinInfo",view:"ViewInfo",calculate:"CalculateInfo"}},File:{type:"struct",name:"File",fields:{url:{type:"string",optional:!1,array:!1},contents:{type:"string",optional:!0,array:!1},invalidation_key:{type:"string",optional:!0,array:!1}}},Filter:{type:"union",name:"Filter",options:{filter_string:"FilterStringApplication",literal_equality:"LiteralEqualityComparison"}},FilterExpressionLiteral:{type:"struct",name:"FilterExpressionLiteral",fields:{filter_expression_value:{type:"string",optional:!1,array:!1}}},FilterExpressionType:{type:"struct",name:"FilterExpressionType",fields:{filter_type:{type:"FilterableType",optional:!1,array:!1}}},FilterOperation:{type:"struct",name:"FilterOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},FilterStringApplication:{type:"struct",name:"FilterStringApplication",fields:{expression:{type:"Expression",optional:!1,array:!1},filter:{type:"string",optional:!1,array:!1}}},FilterableType:{type:"union",name:"FilterableType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",date_type:"DateType",timestamp_type:"TimestampType"}},FilteredField:{type:"struct",name:"FilteredField",fields:{field_reference:{type:"Reference",optional:!1,array:!1},where:{type:"FilterOperation",array:!0,optional:!1}}},GroupBy:{type:"struct",name:"GroupBy",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},JSONCell:{type:"struct",name:"JSONCell",fields:{json_value:{type:"string",optional:!1,array:!1}}},JSONType:{type:"struct",name:"JSONType",fields:{}},JoinInfo:{type:"struct",name:"JoinInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},relationship:{type:"Relationship",optional:!1,array:!1}}},Limit:{type:"struct",name:"Limit",fields:{limit:{type:"number",optional:!1,array:!1}}},LiteralEqualityComparison:{type:"struct",name:"LiteralEqualityComparison",fields:{expression:{type:"Expression",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},LiteralValue:{type:"union",name:"LiteralValue",options:{string_literal:"StringLiteral",number_literal:"NumberLiteral",date_literal:"DateLiteral",timestamp_literal:"TimestampLiteral",boolean_literal:"BooleanLiteral",null_literal:"NullLiteral",filter_expression_literal:"FilterExpressionLiteral"}},LiteralValueExpression:{type:"struct",name:"LiteralValueExpression",fields:{literal_value:{type:"LiteralValue",optional:!1,array:!1}}},Location:{type:"struct",name:"Location",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"Range",optional:!1,array:!1}}},LogMessage:{type:"struct",name:"LogMessage",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"DocumentRange",optional:!1,array:!1},severity:{type:"LogSeverity",optional:!1,array:!1},message:{type:"string",optional:!1,array:!1}}},LogSeverity:{type:"enum",name:"LogSeverity",values:{debug:1,info:2,warn:3,error:4}},MeasureInfo:{type:"struct",name:"MeasureInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ModelEntryValue:{type:"union",name:"ModelEntryValue",options:{source:"SourceInfo",query:"QueryInfo"}},ModelInfo:{type:"struct",name:"ModelInfo",fields:{entries:{type:"ModelEntryValue",array:!0,optional:!1},annotations:{type:"Annotation",array:!0,optional:!0},anonymous_queries:{type:"AnonymousQueryInfo",array:!0,optional:!1}}},MovingAverage:{type:"struct",name:"MovingAverage",fields:{field_reference:{type:"Reference",optional:!1,array:!1},rows_preceding:{type:"number",optional:!0,array:!1},rows_following:{type:"number",optional:!0,array:!1},partition_fields:{type:"Reference",array:!0,optional:!0}}},Nest:{type:"struct",name:"Nest",fields:{name:{type:"string",optional:!0,array:!1},view:{type:"View",optional:!1,array:!1}}},NullCell:{type:"struct",name:"NullCell",fields:{}},NullLiteral:{type:"struct",name:"NullLiteral",fields:{}},NumberCell:{type:"struct",name:"NumberCell",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberLiteral:{type:"struct",name:"NumberLiteral",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberSubtype:{type:"enum",name:"NumberSubtype",values:{integer:1,decimal:2}},NumberType:{type:"struct",name:"NumberType",fields:{subtype:{type:"NumberSubtype",optional:!0,array:!1}}},OrderBy:{type:"struct",name:"OrderBy",fields:{field_reference:{type:"Reference",optional:!1,array:!1},direction:{type:"OrderByDirection",optional:!0,array:!1}}},OrderByDirection:{type:"enum",name:"OrderByDirection",values:{asc:1,desc:2}},ParameterInfo:{type:"struct",name:"ParameterInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"ParameterType",optional:!1,array:!1},default_value:{type:"LiteralValue",optional:!0,array:!1}}},ParameterType:{type:"union",name:"ParameterType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType",filter_expression_type:"FilterExpressionType"}},ParameterValue:{type:"struct",name:"ParameterValue",fields:{name:{type:"string",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},Position:{type:"struct",name:"Position",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},Query:{type:"struct",name:"Query",fields:{definition:{type:"QueryDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},QueryArrow:{type:"struct",name:"QueryArrow",fields:{source:{type:"QueryArrowSource",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},QueryArrowSource:{type:"union",name:"QueryArrowSource",options:{refinement:"QueryRefinement",source_reference:"Reference"}},QueryDefinition:{type:"union",name:"QueryDefinition",options:{arrow:"QueryArrow",query_reference:"Reference",refinement:"QueryRefinement"}},QueryInfo:{type:"struct",name:"QueryInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},QueryRefinement:{type:"struct",name:"QueryRefinement",fields:{base:{type:"QueryDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},Range:{type:"struct",name:"Range",fields:{start:{type:"Position",optional:!1,array:!1},end:{type:"Position",optional:!1,array:!1}}},RecordCell:{type:"struct",name:"RecordCell",fields:{record_value:{type:"Cell",array:!0,optional:!1}}},RecordType:{type:"struct",name:"RecordType",fields:{fields:{type:"DimensionInfo",array:!0,optional:!1}}},Reference:{type:"struct",name:"Reference",fields:{name:{type:"string",optional:!1,array:!1},path:{type:"string",array:!0,optional:!0},parameters:{type:"ParameterValue",array:!0,optional:!0}}},Relationship:{type:"enum",name:"Relationship",values:{one:1,many:2,cross:3}},Result:{type:"struct",name:"Result",fields:{data:{type:"Data",optional:!0,array:!1},schema:{type:"Schema",optional:!1,array:!1},sql:{type:"string",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},model_annotations:{type:"Annotation",array:!0,optional:!0},query_timezone:{type:"string",optional:!0,array:!1},source_annotations:{type:"Annotation",array:!0,optional:!0}}},RunIndexQueryRequest:{type:"struct",name:"RunIndexQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},source_name:{type:"string",optional:!1,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunIndexQueryResponse:{type:"struct",name:"RunIndexQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},RunQueryRequest:{type:"struct",name:"RunQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!0,array:!1},query_malloy:{type:"string",optional:!0,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryResponse:{type:"struct",name:"RunQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},SQLNativeCell:{type:"struct",name:"SQLNativeCell",fields:{sql_native_value:{type:"string",optional:!1,array:!1}}},SQLNativeType:{type:"struct",name:"SQLNativeType",fields:{sql_type:{type:"string",optional:!0,array:!1}}},SQLQuery:{type:"struct",name:"SQLQuery",fields:{sql:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},SQLTable:{type:"struct",name:"SQLTable",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},Schema:{type:"struct",name:"Schema",fields:{fields:{type:"FieldInfo",array:!0,optional:!1}}},SourceInfo:{type:"struct",name:"SourceInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},parameters:{type:"ParameterInfo",array:!0,optional:!0}}},StringCell:{type:"struct",name:"StringCell",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringLiteral:{type:"struct",name:"StringLiteral",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringType:{type:"struct",name:"StringType",fields:{}},TimeTruncationFieldReference:{type:"struct",name:"TimeTruncationFieldReference",fields:{field_reference:{type:"Reference",optional:!1,array:!1},truncation:{type:"TimestampTimeframe",optional:!1,array:!1}}},TimestampCell:{type:"struct",name:"TimestampCell",fields:{timestamp_value:{type:"string",optional:!1,array:!1}}},TimestampLiteral:{type:"struct",name:"TimestampLiteral",fields:{timestamp_value:{type:"string",optional:!1,array:!1},granularity:{type:"TimestampTimeframe",optional:!0,array:!1},timezone:{type:"string",optional:!0,array:!1}}},TimestampTimeframe:{type:"enum",name:"TimestampTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5,hour:6,minute:7,second:8}},TimestampType:{type:"struct",name:"TimestampType",fields:{timeframe:{type:"TimestampTimeframe",optional:!0,array:!1}}},TimingInfo:{type:"struct",name:"TimingInfo",fields:{name:{type:"string",optional:!1,array:!1},duration_ms:{type:"number",optional:!1,array:!1},detailed_timing:{type:"TimingInfo",array:!0,optional:!0}}},Translation:{type:"struct",name:"Translation",fields:{url:{type:"string",optional:!1,array:!1},compiled_model_json:{type:"string",optional:!0,array:!1}}},View:{type:"struct",name:"View",fields:{definition:{type:"ViewDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ViewArrow:{type:"struct",name:"ViewArrow",fields:{source:{type:"ViewDefinition",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},ViewDefinition:{type:"union",name:"ViewDefinition",options:{arrow:"ViewArrow",view_reference:"Reference",refinement:"ViewRefinement",segment:"ViewSegment"}},ViewInfo:{type:"struct",name:"ViewInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"View",optional:!0,array:!1}}},ViewOperation:{type:"union",name:"ViewOperation",options:{group_by:"GroupBy",aggregate:"Aggregate",order_by:"OrderBy",limit:"Limit",where:"FilterOperation",nest:"Nest",having:"FilterOperation",drill:"DrillOperation",calculate:"CalculateOperation"}},ViewRefinement:{type:"struct",name:"ViewRefinement",fields:{base:{type:"ViewDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},ViewSegment:{type:"struct",name:"ViewSegment",fields:{operations:{type:"ViewOperation",array:!0,optional:!1}}}};var Tw={},bj={},Rw={};Object.defineProperty(Rw,"__esModule",{value:!0}),Rw.RESERVED_WORDS=void 0,Rw.RESERVED_WORDS=["accept","aggregate","declare","dimension","except","explore","group_by","having","index","join_cross","join_one","join_many","limit","measure","nest","order_by","primary_key","project","query","rename","sample","source","sql","turduck","top","where","all","as","asc","avg","boolean","by","case","cast","condition","count","date","day","days","desc","distinct","else","end","exclude","false","for","from","from_sql","has","hour","hours","import","is","json","last","max","min","minute","minutes","month","months","not","now","null","number","on","or","pick","quarter","quarters","second","seconds","string","sum","table","then","this","timestamp","to","true","turtle","week","weeks","when","with","year","years","ungrouped"],Object.defineProperty(bj,"__esModule",{value:!0}),bj.maybeQuoteIdentifier=igt;const ngt=Rw;function rgt(t){const e=!t.match(/^[A-Za-z_][A-Za-z_0-9]*$/),r=ngt.RESERVED_WORDS.includes(t.toLowerCase());return e||r}function igt(t){const e=t.split(".");for(let r=0;r<e.length;r++)rgt(e[r])&&(e[r]=`\`${e[r]}\``);return e.join(".")}Object.defineProperty(Tw,"__esModule",{value:!0}),Tw.queryToMalloy=sgt,Tw.filterToMalloy=ogt;const o_=bj;function sgt(t,{tabWidth:e}={tabWidth:2}){const r=cgt(t);return N2e(r,{tabWidth:e})}function ogt(t,{tabWidth:e}={tabWidth:2}){const r=k2e(t);return N2e(r,{tabWidth:e})}const Cj=Symbol("indent"),tu=Symbol("newline"),Tj=Symbol("outdent"),agt=Symbol("optional_newline_indent");function N2e(t,{tabWidth:e}={tabWidth:2}){let r="",i=0,s=!0;for(const o of t)if(o===tu)r+=`
|
|
1397
|
-
`,s=!0;else if(o===Tj)i--;else if(o===Cj)i++;else{if(o===agt)continue;s&&(r+=" ".repeat(i*e),s=!1),r+=o}return r}function $1(t,e,r,i){var s;if(e.includes(tu))return[t,tu,Cj,...e,tu,Tj,r];const a=((s=i==null?void 0:i.spaces)!==null&&s!==void 0?s:!0)?" ":"";return[t,a,...e,a,r]}function ugt(t){return{contents:t,quoteCharacter:'"'}}function lgt(t,e){const r=[];for(let i=0;i<t.length;i++){const s=t[i];r.push(s),i<t.length-1&&r.push(e)}return r}function Rj(t){var e,r;switch(t.kind){case"filter_expression_literal":return[B2e(t.filter_expression_value)];case"boolean_literal":return[t.boolean_value.toString()];case"string_literal":{const{contents:i,quoteCharacter:s}=ugt(t.string_value);return[s,i,s]}case"number_literal":return[t.number_value.toString()];case"null_literal":return["null"];case"date_literal":return[I2e(L2e(t.date_value),(e=t.granularity)!==null&&e!==void 0?e:"day",t.timezone)];case"timestamp_literal":return[I2e(L2e(t.timestamp_value),(r=t.granularity)!==null&&r!==void 0?r:"second",t.timezone)]}}function L2e(t){let e;if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)/.exec(t)){const[r,i,s,o,a,u,l]=e;return[i,s,o,a,u,l]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d)/.exec(t)){const[r,i,s,o,a,u]=e;return[i,s,o,a,u,"00"]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d)(?:00)?/.exec(t)){const[r,i,s,o,a]=e;return[i,s,o,a,"00","00"]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d)/.exec(t)){const[r,i,s,o]=e;return[i,s,o,"00","00","00"]}else if(e=/(\d\d\d\d)-(\d\d)/.exec(t)){const[r,i,s]=e;return[i,s,"01","00","00","00"]}else if(e=/(\d\d\d\d)/.exec(t)){const[r,i]=e;return[i,"01","01","00","00","00"]}return["1970","01","01","00","00","00"]}function I2e([t,e,r,i,s,o],a,u){switch(a){case"year":return`@${t}`;case"quarter":{const l=Math.floor(+e/3)+1;return`@${t}-Q${l}`}case"month":return`@${t}-${e}`;case"week":return`@${t}-${e}-${r}-WK`;case"day":return`@${t}-${e}-${r}`;case"hour":return`@${t}-${e}-${r} ${i}`;case"minute":return`@${t}-${e}-${r} ${i}:${s}`;case"second":return u!==void 0?`@${t}-${e}-${r} ${i}:${s}:${o}[${u}]`:`@${t}-${e}-${r} ${i}:${s}:${o}`;default:throw new Error("Unknown timeframe.")}}function Uc(t){var e;const r=[];for(const i of(e=t.path)!==null&&e!==void 0?e:[])r.push((0,o_.maybeQuoteIdentifier)(i)),r.push(".");if(r.push((0,o_.maybeQuoteIdentifier)(t.name)),t.parameters){const i=[];for(let s=0;s<t.parameters.length;s++){const o=t.parameters[s];i.push((0,o_.maybeQuoteIdentifier)(o.name)),i.push(" is "),i.push(...Rj(o.value)),s<t.parameters.length-1&&i.push(",",tu)}r.push(...$1("(",i,")",{spaces:!1}))}return r}function cgt(t){const e=[];return e.push(...a_(t.annotations)),e.push("run: "),e.push(...Dj(t.definition)),e}function fgt(t){const e=[];switch(t.kind){case"source_reference":{e.push(...Uc(t));break}case"refinement":e.push(...Dj(t));break}return e}function Dj(t){const e=[];switch(t.kind){case"arrow":{e.push(...fgt(t.source)),e.push(" -> "),e.push(...fh(t.view));break}case"query_reference":{e.push(...Uc(t));break}case"refinement":{const r=Dj(t.base);t.base.kind==="arrow"?e.push(...$1("(",r,")",{spaces:!1})):e.push(...r),e.push(" + "),e.push(...fh(t.refinement));break}}return e}function fh(t){const e=[];switch(t.kind){case"arrow":{e.push(...fh(t.source)),e.push(" -> "),e.push(...fh(t.view));break}case"view_reference":{e.push(...Uc(t));break}case"refinement":{e.push(...fh(t.base)),e.push(" + "),e.push(...fh(t.refinement));break}case"segment":{e.push(...dgt(t));break}}return e}function dgt(t){if(t.operations.length===0)return["{ }"];const e=t.operations.length>1,r=[];for(let i=0;i<t.operations.length;i++){const s=t.operations[i],o=[s];for(;i<t.operations.length-1;){const a=t.operations[i+1];if(a.kind===s.kind)o.push(a),i++;else break}r.push(...xgt(o)),e&&i<t.operations.length-1&&r.push(tu)}return $1("{",r,"}")}function xgt(t){switch(t[0].kind){case"aggregate":return Oj(t,"aggregate");case"group_by":return Oj(t,"group_by");case"order_by":return mgt(t);case"nest":return ygt(t);case"limit":return Agt(t);case"where":return $2e(t);case"having":return bgt(t);case"drill":return Sgt(t);case"calculate":return Oj(t,"calculate")}}function B1(t,e,r=""){const i=[];i.push(`${t}:`);const s=e.length>1||e.some(o=>o.includes(tu));s?i.push(tu,Cj):i.push(" ");for(let o=0;o<e.length;o++){const a=e[o];i.push(...a),e.length>1&&o<e.length-1&&i.push(r),s&&o<e.length-1&&i.push(tu)}return s&&i.push(Tj),i}function hgt(t){const e=[];return e.push(...wj(t.expression)),e}function tAt(t){return t}function wj(t){var e;switch(t.kind){case"field_reference":return Uc(t);case"time_truncation":return[...Uc(t.field_reference),".",t.truncation];case"filtered_field":return[...Uc(t.field_reference),...$1(" {",$2e(t.where),"}")];case"literal_value":return Rj(t.literal_value);case"moving_average":{const r=["avg_moving",...$1("(",[...Uc(t.field_reference),t.rows_preceding!==void 0?`, ${t.rows_preceding}`:", 0",t.rows_following!==void 0?`, ${t.rows_following}`:""],")",{spaces:!1})];return!((e=t.partition_fields)===null||e===void 0)&&e.length&&r.push(...$1(" {",["partition_by",": ",...lgt(t.partition_fields.flatMap(i=>Uc(i)),", ")],"}")),r}}}function pgt(t,e=!1){const r=[];return e||r.push(...a_(t.field.annotations)),t.name&&(r.push((0,o_.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...hgt(t.field)),r}function Oj(t,e){const r=[],i=t.length===1;return i&&r.push(...a_(t[0].field.annotations)),r.push(...B1(e,t.map(s=>pgt(s,i)))),r}function mgt(t){return B1("order_by",t.map(ggt),",")}function ggt(t){const e=[];return e.push(...Uc(t.field_reference)),t.direction&&(e.push(" "),e.push(t.direction)),e}function ygt(t){const e=[],r=t.length===1;return r&&e.push(...a_(t[0].view.annotations)),e.push(...B1("nest",t.map(i=>Egt(i,r)))),e}function Egt(t,e=!1){const r=[];return e||r.push(...a_(t.view.annotations)),t.name&&(r.push((0,o_.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...vgt(t.view)),r}function vgt(t){return fh(t.definition)}function _gt(t){return[`limit: ${t.limit}`]}function Agt(t){const e=[];for(let r=0;r<t.length;r++)r!==0&&e.push(tu),e.push(..._gt(t[r]));return e}function $2e(t){return B1("where",t.map(Fj),",")}function Sgt(t){return B1("drill",t.map(Fj),",")}function bgt(t){return B1("having",t.map(Fj),",")}const Cgt=["`","'",'"'];function B2e(t){let e,r;for(const i of Cgt){const s=Tgt(t,i);if(s===t)return`f${i}${t}${i}`;(r===void 0||s.length<r.length)&&(e=i,r=s)}return`f${e}${r}${e}`}function Tgt(t,e){let r="";for(let i=0;i<t.length;i++)t.slice(i).startsWith(e)?(r+="\\"+e,i+=e.length):(r+=t[i],t[i]==="\\"&&(r+=t[++i]));return r}function k2e(t){switch(t.kind){case"filter_string":return[...wj(t.expression)," ~ ",B2e(t.filter)];case"literal_equality":return[...wj(t.expression)," = ",...Rj(t.value)]}}function Fj(t){return k2e(t.filter)}function a_(t){return t?t.flatMap(Rgt):[]}function Rgt(t){return[t.value.trim(),tu]}var k1={};Object.defineProperty(k1,"__esModule",{value:!0}),k1.nestUnions=Nj,k1.unnestUnions=Dw,k1.convertFromThrift=ww,k1.convertToThrift=Ow;const Dgt=s_;function Nj(t){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(Nj);{const e={};let r;for(const i in t)i==="kind"?r=t[i]:e[i]=Nj(t[i]);return r===void 0?e:{[r]:e}}}function Dw(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(r=>Dw(r,e));{const r=M1(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=Dw(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=Dw(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}function ww(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(e==="number")return t;const r=M1(e);if(r.type!=="enum")throw new Error(`Found a number where a ${e} was expected`);const i=Object.entries(r.values).find(([,s])=>s===t);if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i[0]}else{if(Array.isArray(t))return t.map(r=>ww(r,e));{const r=M1(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0&&t[i]!==null){const s=ww(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=ww(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}}function M1(t){const e=Dgt.MALLOY_INTERFACE_TYPES[t];if(e===void 0)throw new Error(`Unknown Malloy interface type ${t}`);return e}function Ow(t,e){if(t==null)return t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string"){if(e==="string")return t;const r=M1(e);if(r.type==="enum"){const i=r.values[t];if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i}}else{if(Array.isArray(t))return t.map(r=>Ow(r,e));{const r=M1(e);if(r.type==="union"){const i=t.kind,s=r.options[i];if(s===void 0)throw new Error(`${i} is not a valid union of ${e}`);const o=M1(s);if(o.type!=="struct")throw new Error("Union fields must be structs");const a={};for(const u in t){if(u==="kind")continue;const l=o.fields[u];a[u]=Ow(t[u],l.type)}return{[i]:a}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=Ow(t[s],o.type)}return i}}}}(function(t){var e=R&&R.__createBinding||(Object.create?function(o,a,u,l){l===void 0&&(l=u);var c=Object.getOwnPropertyDescriptor(a,u);(!c||("get"in c?!a.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return a[u]}}),Object.defineProperty(o,l,c)}:function(o,a,u,l){l===void 0&&(l=u),o[l]=a[u]}),r=R&&R.__exportStar||function(o,a){for(var u in o)u!=="default"&&!Object.prototype.hasOwnProperty.call(a,u)&&e(a,o,u)};Object.defineProperty(t,"__esModule",{value:!0}),t.thingy4sddfdfsd=t.thingy4sdfsd=t.thingy4dfdsfs=t.thingy4asdfas=t.thingy4asdfasdf=t.thingy3dfdf=t.thingy3=t.thingy2asdf=t.thingyssdfg=t.thingy123r=t.thingy1=t.res=t.test=t.convertToThrift=t.convertFromThrift=t.unnestUnions=t.nestUnions=t.filterToMalloy=t.queryToMalloy=void 0,r(s_,t);var i=Tw;Object.defineProperty(t,"queryToMalloy",{enumerable:!0,get:function(){return i.queryToMalloy}}),Object.defineProperty(t,"filterToMalloy",{enumerable:!0,get:function(){return i.filterToMalloy}});var s=k1;Object.defineProperty(t,"nestUnions",{enumerable:!0,get:function(){return s.nestUnions}}),Object.defineProperty(t,"unnestUnions",{enumerable:!0,get:function(){return s.unnestUnions}}),Object.defineProperty(t,"convertFromThrift",{enumerable:!0,get:function(){return s.convertFromThrift}}),Object.defineProperty(t,"convertToThrift",{enumerable:!0,get:function(){return s.convertToThrift}}),t.test={entries:[{kind:"source",name:"flights",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"boolean_type"},annotations:[{value:"# foo=1"}]},{kind:"dimension",name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}},{kind:"dimension",name:"arr_rec",type:{kind:"array_type",element_type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}}},{kind:"dimension",name:"rec",type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}},{kind:"join",name:"carriers",relationship:"one",schema:{fields:[{kind:"dimension",name:"code",type:{kind:"string_type"}}]}},{kind:"view",name:"by_carrier",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]}}]},parameters:[{name:"param",type:{kind:"number_type"},default_value:{kind:"number_literal",number_value:7}}]}],anonymous_queries:[]},t.res={connection_name:"foo",data:{kind:"array_cell",array_value:[{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"UA"},{kind:"number_cell",number_value:12341234}]},{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"AA"},{kind:"number_cell",number_value:2343}]}]},schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]},sql:"SELECT * ..."},t.thingy1={definition:{kind:"query_reference",name:"flights_by_carrier"}},t.thingy123r={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingyssdfg={definition:{kind:"refinement",base:{kind:"query_reference",name:"flights"},refinement:{kind:"view_reference",name:"by_carrier"}}},t.thingy2asdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"where",filter:{kind:"filter_string",expression:{kind:"field_reference",name:"carrier"},filter:"WN"}}]}}}},t.thingy3={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}}},t.thingy3dfdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"view_reference",name:"top10"}}}},t.thingy4asdfasdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}},t.thingy4asdfas={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingy4dfdsfs={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"limit",limit:10}]}}}},t.thingy4sdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"limit",limit:10}]}}},t.thingy4sddfdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[]}}}})(ch);var wgt=R&&R.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Ogt=R&&R.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Fgt=R&&R.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var i=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&wgt(r,e,i[s]);return Ogt(r,e),r}}();Object.defineProperty(eu,"__esModule",{value:!0}),eu.sourceDefToSourceInfo=P2e,eu.modelDefToModelInfo=Ngt,eu.convertFieldInfos=P1,eu.writeLiteralToTag=H2e,eu.getResultStructMetadataAnnotation=Fw,eu.writeMalloyObjectToTag=U1,eu.extractMalloyObjectFromTag=Lw;const M2e=Fgt(ch),Ms=Ri,Lj=Ns,Ij=rs;function P2e(t){var e;const r=t.parameters&&Object.entries(t.parameters).length>0?Object.entries(t.parameters).map(([s,o])=>(0,Ms.isAtomic)(o)?{name:s,type:Nw(o),default_value:U2e(o.value)}:{name:s,type:{kind:"filter_expression_type",filter_type:{kind:`${o.filterType}_type`}},default_value:U2e(o.value)}):void 0;return{name:(e=t.as)!==null&&e!==void 0?e:t.name,schema:{fields:P1(t,t.fields)},parameters:r,annotations:$j(t)}}function Ngt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ms.isSourceDef)(i)){const s=P2e(i);e.entries.push({kind:"source",...s})}else if(i.type==="query"){const s=(0,Ms.getResultStructDefForQuery)(t,i),o=$j(i),a=s.resultMetadata?Fw(s,s.resultMetadata):void 0,u=[...o??[],...a?[a]:[]],l={kind:"source",name:r,schema:{fields:P1(s,s.fields)},annotations:u.length>0?u:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,Ms.getResultStructDefForQuery)(t,r),s=$j(r),o=i.resultMetadata?Fw(i,i.resultMetadata):void 0,a=[...s??[],...o?[o]:[]],u={schema:{fields:P1(i,i.fields)},annotations:a.length>0?a:void 0};e.anonymous_queries.push(u)}return e}function U2e(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function $j(t){return(0,Lj.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function P1(t,e){var r,i,s;const o=[];for(const a of e){if(!(a.accessModifier===void 0))continue;const c=(0,Lj.annotationToTaglines)(a.annotation).map(d=>({value:d})),f=c.length>0?c:void 0;if((0,Ms.isTurtle)(a)){const d=(0,Ms.getResultStructDefForView)(t,a),x=d.resultMetadata?Fw(d,d.resultMetadata):void 0,p=[...f??[],...x?[x]:[]],m={kind:"view",name:(r=a.as)!==null&&r!==void 0?r:a.name,annotations:p.length>0?p:void 0,schema:{fields:P1(d,d.fields)}};o.push(m)}else if((0,Ms.isAtomic)(a)){const d=(0,Ms.expressionIsAggregate)(a.expressionType),x=(0,Ms.expressionIsScalar)(a.expressionType);if(!d&&!x||a.type==="error")continue;const p=a.resultMetadata?j2e(a,a.resultMetadata):void 0;let m;if((0,Ms.isRecordOrRepeatedRecord)(a)&&a.queryTimezone){const v=Ij.Tag.withPrefix("#(malloy) ");v.set(["query_timezone"],a.queryTimezone),m={value:v.toString()}}const g=[...f??[],...p?[p]:[],...m?[m]:[]],y={kind:d?"measure":"dimension",name:(i=a.as)!==null&&i!==void 0?i:a.name,type:Nw(a),annotations:g.length>0?g:void 0};o.push(y)}else if((0,Ms.isJoinedSource)(a)){const d={kind:"join",name:(s=a.as)!==null&&s!==void 0?s:a.name,annotations:f,schema:{fields:P1(a,a.fields)},relationship:a.join};o.push(d)}}return o}function j2e(t,e){const r=Ij.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.drillable&&(r.set(["drillable"]),i=!0),e.filterList&&(q2e(r,e.filterList),i=!0),e.drillExpression&&(z2e(r,["drill_expression"],e.drillExpression),i=!0),e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Igt(t.name));r.set(["drill_expression","code"],o),i=!0}return i?{value:r.toString()}:void 0}function q2e(t,e){for(let r=0;r<e.length;r++){const i=e[r];i.expressionType!=="scalar"||i.isSourceFilter||(t.set(["drill_filters",r,"code"],i.code),i.filterView&&t.set(["drill_filters",r,"filter_view"],i.filterView),i.filterView===void 0&&i.stableFilter!==void 0&&(z2e(t,["drill_filters",r,"expression"],i.stableFilter.expression),i.stableFilter.kind==="filter_string"?(t.set(["drill_filters",r,"kind"],"filter_expression"),t.set(["drill_filters",r,"filter_expression"],i.stableFilter.filter)):(t.set(["drill_filters",r,"kind"],"literal_equality"),H2e(t,["drill_filters",r,"value"],i.stableFilter.value))))}}function z2e(t,e,r){U1(t,e,r,"Expression")}function H2e(t,e,r){U1(t,e,r,"LiteralValue")}function Lgt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Igt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Lgt(t)}\``}function Fw(t,e){var r,i;const s=Ij.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList&&(q2e(s,e.filterList),o=!0),e.drillable&&(s.set(["drillable"]),o=!0),e.orderBy){for(let a=0;a<e.orderBy.length;a++){const u=e.orderBy[a],l=typeof u.field=="number"?(r=t.fields[u.field-1].as)!==null&&r!==void 0?r:t.fields[u.field-1].name:u.field,c=(i=u.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",a,l],c)}o=!0}return t.queryTimezone&&(s.set(["query_timezone"],t.queryTimezone),o=!0),o?{value:s.toString()}:void 0}function Nw(t){if((0,Ms.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!$gt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Bgt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ms.isRepeatedRecord)(t))return{kind:"array_type",element_type:Q2e(t)};if(t.type==="record")return Q2e(t);if(t.type==="array")return{kind:"array_type",element_type:Nw(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Q2e(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=j2e(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,Lj.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ms.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:Nw(e)};throw new Error("Expected record type to not have a table as its child")})}}function $gt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Bgt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function nAt(t){return t}function rAt(t){return t}function U1(t,e,r,i){if(i==="string"){t.set(e,r);return}else if(i==="number"){t.set(e,r);return}else if(i==="boolean"){t.set(e,r.toString());return}const s=M2e.MALLOY_INTERFACE_TYPES[i];if(s===void 0)throw new Error(`Unknown Malloy interface type ${i}`);if(s.type==="enum")if(typeof r=="string")t.set(e,r);else throw new Error(`Expected string for enum ${i}`);else if(s.type==="struct")for(const o in s.fields){const a=s.fields[o],u=r[o];if(u===void 0){if(!a.optional)throw new Error(`Mising value for non-optional field ${o} in type ${i}`)}else if(a.array)if(Array.isArray(u))for(let l=0;l<u.length;l++)U1(t,[...e,o,l],u[l],a.type);else throw new Error(`Expected array for field ${o} of type ${i} but got ${typeof r}`);else U1(t,[...e,o],u,a.type)}else{const o=r.kind;t.set([...e,"kind"],o);const a=s.options[o];if(a===void 0)throw new Error(`Unknown Malloy interface union kind ${o} for type ${i}`);U1(t,e,r,a)}}function Lw(t,e){if(e==="string")return t.text();if(e==="number")return t.numeric();if(e==="boolean")return t.text()==="true";const r=M2e.MALLOY_INTERFACE_TYPES[e];if(r===void 0)throw new Error(`Unknown Malloy interface type ${e}`);if(r.type==="enum"){const i=t.text();if(i===void 0)throw new Error(`Missing value for enum ${e}`);if(i in r.values)return i;throw new Error(`Unknown value ${i} for enum ${e}`)}else if(r.type==="struct"){const i={};for(const[s,o]of Object.entries(r.fields)){const a=t.tag(s);if(a===void 0){if(o.optional)continue;throw new Error(`Missing value for key ${s} of type ${o}`)}if(o.array){const u=[],l=a.array();if(l===void 0)throw new Error(`Missing array value for key ${s} of type ${o}`);for(const c of l)u.push(Lw(c,o.type));i[s]=u}else{const u=Lw(a,o.type);u!=null&&(i[s]=u)}}return i}else{const i=t.text("kind");if(i===void 0)throw new Error(`Missing kind for union ${e}`);const s=r.options[i];if(s===void 0)throw new Error(`Unknown kind ${i} for union ${e}`);const o=Lw(t,s);return{kind:i,...o}}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_LOG_RANGE=void 0,t.wrapLegacyInfoConnection=a,t.wrapLegacyConnection=u,t.mapData=c,t.wrapResult=f,t.nodeToLiteralValue=d,t.mapLogs=x;const e=rs,r=Ns,i=Ri,s=eu,o=YE;function a(p){return{get dialectName(){return p.dialectName},async fetchSchemaForSQLQuery(m){const g=await p.fetchSchemaForSQLStruct({connection:p.name,selectStr:m},{}),y=g.structDef;if(y===void 0)throw new Error(g.error);return{fields:(0,s.convertFieldInfos)(y,y.fields)}},async fetchSchemaForTable(m){const g=`${p.name}:${m}`,y=await p.fetchSchemaForTables({[g]:m},{}),v=y.schemas[g];if(v===void 0)throw new Error(y.errors[g]);return{fields:(0,s.convertFieldInfos)(v,v.fields)}}}}function u(p){return{...a(p),runSQL:async(m,g)=>{const y=await p.runSQL(m);return c(y.rows,g)}}}function l(p){if(p instanceof Date)return p;if(p.constructor.name==="Date")return new Date(p);if(typeof p=="number")return new Date(p);if(typeof p!="string")return new Date(p.value);{let g=o.DateTime.fromISO(p,{zone:"UTC"});return g.isValid||(g=o.DateTime.fromSQL(p,{zone:"UTC"})),g.toJSDate()}}function c(p,m){function g(E,_){if(E===null)return{kind:"null_cell"};if(_.type.kind==="date_type"||_.type.kind==="timestamp_type"){const A=l(E).toISOString();return _.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(_.type.kind==="boolean_type"){if(typeof E=="number")return{kind:"boolean_cell",boolean_value:E!==0};if(typeof E!="boolean")throw new Error(`Invalid boolean ${E}`);return{kind:"boolean_cell",boolean_value:E}}else if(_.type.kind==="number_type"){if(typeof E!="number")throw new Error(`Invalid number ${E}`);return{kind:"number_cell",number_value:E}}else if(_.type.kind==="string_type"){if(typeof E!="string")throw new Error(`Invalid string ${E}`);return{kind:"string_cell",string_value:E}}else if(_.type.kind==="array_type"){if(!Array.isArray(E))throw new Error(`Invalid array ${E}`);return{kind:"array_cell",array_value:E.map(A=>g(A,{name:"array_element",type:_.type.element_type}))}}else{if(_.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(E)};if(_.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(E)};{const A=_.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(_)}, ${JSON.stringify(E)}`);return y(E,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(S=>({kind:"dimension",...S}))}})}}}function y(E,_){const A=[];for(const S of _.schema.fields){const b=E[S.name];if(S.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=g(b,S);A.push(C)}return{kind:"record_cell",record_value:A}}const v={kind:"join",schema:m,name:"root",relationship:"one"};return{kind:"array_cell",array_value:p.map(E=>y(E,v))}}function f(p){const m=p._queryResult.structs,g=m[m.length-1],y={fields:(0,s.convertFieldInfos)(g,g.fields)},v=(0,r.annotationToTaglines)(p.annotation).map(S=>({value:S})),E=g.resultMetadata?(0,s.getResultStructMetadataAnnotation)(g,g.resultMetadata):void 0;E&&v.push(E),v.push(...g.resultMetadata?[]:[]);const _=e.Tag.withPrefix("#(malloy) ");if(p.sourceExplore&&_.set(["source","name"],p.sourceExplore.name),p._sourceArguments){const S=Object.entries(p._sourceArguments);for(let b=0;b<S.length;b++){const[C,T]=S[b],D=d(T.value);D!==void 0&&(0,s.writeLiteralToTag)(_,["source","parameters",b,"value"],D),_.set(["source","parameters",b,"name"],C)}}v.push({value:_.toString()}),v.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],p.resultExplore.name).toString()});const A=(0,r.annotationToTaglines)(p._modelDef.annotation).map(S=>({value:S}));return{schema:y,data:c(p.data.toObject(),y),connection_name:p.connectionName,annotations:v.length>0?v:void 0,model_annotations:A.length>0?A:void 0,query_timezone:p.data.field.queryTimezone,sql:p.sql}}function d(p){switch(p==null?void 0:p.node){case"numberLiteral":return{kind:"number_literal",number_value:Number.parseFloat(p.literal)};case"null":return{kind:"null_literal"};case"stringLiteral":return{kind:"string_literal",string_value:p.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:p.filterSrc};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"timeLiteral":return p.typeDef.type==="date"?p.typeDef.timeframe===void 0||(0,i.isDateUnit)(p.typeDef.timeframe)?{kind:"date_literal",date_value:p.literal,timezone:p.timezone,granularity:p.typeDef.timeframe}:void 0:{kind:"timestamp_literal",timestamp_value:p.literal,timezone:p.timezone,granularity:p.typeDef.timeframe};default:return}}t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function x(p,m){return p.map(g=>{var y,v,E,_;return{severity:g.severity,message:g.message,range:(v=(y=g.at)===null||y===void 0?void 0:y.range)!==null&&v!==void 0?v:t.DEFAULT_LOG_RANGE,url:(_=(E=g.at)===null||E===void 0?void 0:E.url)!==null&&_!==void 0?_:m}})}})(i_);var kgt=R&&R.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Mgt=R&&R.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Pgt=R&&R.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var i=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&kgt(r,e,i[s]);return Mgt(r,e),r}}();Object.defineProperty(r_,"__esModule",{value:!0}),r_.MalloyToQuery=void 0,r_.malloyToQuery=Qgt;const Ugt=M2,jgt=s2,mt=Pgt($),G2e=J2,dh=ks,qgt=Ye,zgt=ND,W2e=jr,Hgt=i_,xh=ZE,Bj="Malloy query documents";class V2e extends jgt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,W2e.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,G2e.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${Bj}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${Bj} may only have one run statement`);return i===void 0?(this.illegal(e,`${Bj} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getSourceArguments(e){const r=[];for(const i of e.sourceArgument()){const s=i.argumentId();if(s===void 0)return this.contextError(i,"unnamed-source-argument","Source argument must be named"),null;const o=(0,dh.getId)(s),a=this.getLiteralIncludingNegativeNumber(i.fieldExpr());if(a===null)return null;r.push({name:o,value:a})}return r}getQueryReference(e){const r=e.sourceArguments(),i=(0,dh.getId)(e);if(r){const s=this.getSourceArguments(r);return s===null?null:{name:i,parameters:s}}else return{name:i}}getQueryDefinition(e){if(e instanceof mt.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof mt.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof mt.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof mt.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof mt.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof mt.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof mt.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof mt.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof mt.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof mt.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof mt.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof mt.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof mt.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var a;const u=[...r??[],...(a=o.field.annotations)!==null&&a!==void 0?a:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:u.length>0?u:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var a;const u=[...r??[],...(a=o.field.annotations)!==null&&a!==void 0?a:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:u.length>0?u:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,dh.getId)(s.fieldName()),a=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:a,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof mt.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const a=this.getAnnotations(o.tags()),u=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,dh.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,a,u)}})}return s}getViewExpression(e){if(e instanceof mt.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof mt.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.drillStatement()){const r=e.drillStatement(),i=this.getDrill(r);return i===null?null:i.map(s=>({kind:"drill",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,dh.getId)(o)),i=r[r.length-1],s=r.slice(0,-1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,qgt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const a=r.refExpr();if(a.timeframe()){const u=this.getTimeframe(a.timeframe());return u===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:u}}}}else a.aggregate()&&this.notAllowed(a,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,dh.getId)(r.fieldNameDef()),a=this.getFieldExpression(r.fieldExpr());return a===null?null:{name:o,field:{expression:a,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof mt.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof mt.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof mt.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const a of s){const u=a.whereStatement();if(u){const l=this.getWhere(u);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}else{const r=this.getLiteralIncludingNegativeNumber(e);return r===null?null:{kind:"literal_value",literal_value:r}}}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),a=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(a)return this.stripQuote(a.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),a=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(a)return this.stripQuote(a.text,"'")}return null}getFilterExpr(e){if(e instanceof mt.ExprCompareContext){if(e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof mt.ExprFieldPathContext&&i instanceof mt.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),a=i.literal();if(a instanceof mt.FilterString_stubContext){const u=this.getFilterString(a.filterString());return u===null?null:{filter:{kind:"filter_string",expression:{kind:"field_reference",name:o,path:s},filter:u}}}}}else if(e.compareOp().EQ()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof mt.ExprFieldPathContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),a=this.getLiteralIncludingNegativeNumber(i);return a===null?(this.notAllowed(e,"Filters other than comparisons with filter strings or equality with literals"),null):{filter:{kind:"literal_equality",expression:{kind:"field_reference",name:o,path:s},value:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings or equality with literals"),null}getTimeLiteral(e,r){const i=r(e.text);if(!i)return this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),null;const s=i.getValue(),o=s.timeframe;if(s.value.node!=="timeLiteral")return null;const a=s.value.literal,u=s.value.timezone;return s.type==="timestamp"?{kind:"timestamp_literal",timestamp_value:a,granularity:o,timezone:u}:o==="hour"||o==="minute"||o==="second"?null:{kind:"date_literal",date_value:a,granularity:o,timezone:u}}getLiteralIncludingNegativeNumber(e){if(e instanceof mt.ExprLiteralContext)return this.getLiteral(e.literal());if(e instanceof mt.ExprMinusContext){const r=e.fieldExpr();if(r instanceof mt.ExprLiteralContext){const i=this.getLiteral(r.literal());return i===null||i.kind!=="number_literal"?null:{kind:"number_literal",number_value:-i.number_value}}}return null}getLiteral(e){if(e instanceof mt.ExprTimeContext){const r=e.dateLiteral();return r instanceof mt.LiteralTimestampContext?this.getTimeLiteral(r,xh.LiteralTimestamp.parse):r instanceof mt.LiteralHourContext?this.getTimeLiteral(r,xh.LiteralHour.parse):r instanceof mt.LiteralDayContext?this.getTimeLiteral(r,xh.LiteralDay.parse):r instanceof mt.LiteralWeekContext?this.getTimeLiteral(r,xh.LiteralWeek.parse):r instanceof mt.LiteralMonthContext?this.getTimeLiteral(r,xh.LiteralMonth.parse):r instanceof mt.LiteralQuarterContext?this.getTimeLiteral(r,xh.LiteralQuarter.parse):r instanceof mt.LiteralYearContext?this.getTimeLiteral(r,xh.LiteralYear.parse):null}else{if(e instanceof mt.ExprArrayLiteralContext)return this.notAllowed(e,"array literals"),null;if(e instanceof mt.ExprLiteralRecordContext)return this.notAllowed(e,"record literals"),null;if(e instanceof mt.ExprStringContext){const[r,i]=(0,dh.getPlainString)(e);for(const s of i)s instanceof Ugt.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return{kind:"string_literal",string_value:r??""}}else{if(e instanceof mt.ExprBoolContext)return{kind:"boolean_literal",boolean_value:e.TRUE()!==null};if(e instanceof mt.ExprNumberContext)return{kind:"number_literal",number_value:Number(e.text)};if(e instanceof mt.ExprNULLContext)return{kind:"null_literal"};if(e instanceof mt.FilterString_stubContext){const r=e.getChild(0);if(r instanceof mt.FilterStringContext){const i=this.getFilterString(r);if(i)return{kind:"filter_expression_literal",filter_expression_value:i}}}}}return null}getDrill(e){const i=e.drillClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}r_.MalloyToQuery=V2e;function Qgt(t){const e=(0,W2e.getSourceInfo)(t),r=new G2e.BaseMessageLogger(null),i="internal://query.malloy",s=(0,zgt.runMalloyParser)(t,i,e,r),a=new V2e(s,r).visit(s.root),u=(0,Hgt.mapLogs)(r.getLog(),i);if(a===null)return{logs:u};if(!("definition"in a))throw new Error("Expected a query");return{query:a,logs:u}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Af;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=n_;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=r_;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})})(JT);var $e={},Iw={};Object.defineProperty(Iw,"__esModule",{value:!0}),Iw.MALLOY_VERSION=void 0,Iw.MALLOY_VERSION="0.0.312",Object.defineProperty($e,"__esModule",{value:!0}),$e.InMemoryModelCache=$e.CacheManager=$e.CSVWriter=$e.JSONWriter=$e.DataWriter=$e.DataRecord=$e.DataArray=$e.Result=$e.ExploreMaterializer=$e.PreparedResultMaterializer=$e.QueryMaterializer=$e.ModelMaterializer=$e.SingleConnectionRuntime=$e.ConnectionRuntime=$e.Runtime=$e.ExploreField=$e.JoinRelationship=$e.QueryField=$e.Query=$e.StringField=$e.UnsupportedField=$e.JSONField=$e.BooleanField=$e.NumberField=$e.TimestampField=$e.DateField=$e.TimestampTimeframe=$e.DateTimeframe=$e.AtomicField=$e.AtomicFieldType=$e.Explore=$e.SourceRelationship=$e.FixedConnectionMap=$e.InMemoryURLReader=$e.EmptyURLReader=$e.PreparedResult=$e.DocumentCompletion=$e.DocumentSymbol=$e.DocumentPosition=$e.DocumentRange=$e.DocumentTablePath=$e.Parse=$e.PreparedQuery=$e.Model=$e.MalloyError=$e.Malloy=void 0;const Y2e=JT,_r=Ri,K2e=YE,kj=Gx,Ggt=Iw,Wgt=H2,Vn=Ns,Vgt=nh,Ygt=jr,Kgt=Wv;function Xgt(t){return t.type==="table"||t.type==="sql_select"||t.type==="query_source"}const X2e="internal://internal.malloy";let jc=class zO{static get version(){return Ggt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(X2e));let a=r;s!=null&&s.importBaseURL&&(a=s==null?void 0:s.importBaseURL);const u=new Y2e.MalloyTranslator(r.toString(),a.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(u.allDialectsEnabled=!0),new Z2e(u,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return zO._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return qw(r,e).then(({contents:a,invalidationKey:u})=>zO._parse(a,e,s,o,u))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:a,refreshSchemaCache:u,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:d}){var x,p,m,g,y;let v;if(u&&(v=typeof u=="number"?u:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(X2e));const E={};if(r===void 0&&d!==void 0){const S=await d.getCachedModelDef(s,e.toString());if(S)return new j1(S.modelDef,[],[e.toString(),...jw(S.modelDef.dependencies)])}f??(f=e);let _;const A=e.toString();if(i!==void 0){_=i._translator;const S=(x=i._invalidationKey)!==null&&x!==void 0?x:await Kj(s,e);E[A]=S}else{if(r===void 0){const{contents:S,invalidationKey:b}=await qw(s,e);E[A]=b,r=S}else{const S=await Kj(s,e);E[A]=S}_=new Y2e.MalloyTranslator(A,f.toString(),{urls:{[A]:r}},c)}for(;;){const S=_.translate(a==null?void 0:a._modelDef);if(S.final)if(S.modelDef){await(d==null?void 0:d.setCachedModelDef(e.toString(),{modelDef:S.modelDef,invalidationKeys:E}));for(const b of _.newlyTranslatedDependencies())await(d==null?void 0:d.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:E}));return new j1(S.modelDef,S.problems||[],[...(p=a==null?void 0:a.fromSources)!==null&&p!==void 0?p:[],...(m=S.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},C=(a==null?void 0:a._modelDef)||b;return new j1(C,S.problems||[],[...(g=a==null?void 0:a.fromSources)!==null&&g!==void 0?g:[],...(y=S.fromSources)!==null&&y!==void 0?y:[]])}else{const b=S.problems||[],C=_.prettyErrors();throw new J2e(`Error(s) compiling model:
|
|
1397
|
+
`,s=!0;else if(o===Tj)i--;else if(o===Cj)i++;else{if(o===agt)continue;s&&(r+=" ".repeat(i*e),s=!1),r+=o}return r}function $1(t,e,r,i){var s;if(e.includes(tu))return[t,tu,Cj,...e,tu,Tj,r];const a=((s=i==null?void 0:i.spaces)!==null&&s!==void 0?s:!0)?" ":"";return[t,a,...e,a,r]}function ugt(t){return{contents:t,quoteCharacter:'"'}}function lgt(t,e){const r=[];for(let i=0;i<t.length;i++){const s=t[i];r.push(s),i<t.length-1&&r.push(e)}return r}function Rj(t){var e,r;switch(t.kind){case"filter_expression_literal":return[B2e(t.filter_expression_value)];case"boolean_literal":return[t.boolean_value.toString()];case"string_literal":{const{contents:i,quoteCharacter:s}=ugt(t.string_value);return[s,i,s]}case"number_literal":return[t.number_value.toString()];case"null_literal":return["null"];case"date_literal":return[I2e(L2e(t.date_value),(e=t.granularity)!==null&&e!==void 0?e:"day",t.timezone)];case"timestamp_literal":return[I2e(L2e(t.timestamp_value),(r=t.granularity)!==null&&r!==void 0?r:"second",t.timezone)]}}function L2e(t){let e;if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)/.exec(t)){const[r,i,s,o,a,u,l]=e;return[i,s,o,a,u,l]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d)/.exec(t)){const[r,i,s,o,a,u]=e;return[i,s,o,a,u,"00"]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d)(?:00)?/.exec(t)){const[r,i,s,o,a]=e;return[i,s,o,a,"00","00"]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d)/.exec(t)){const[r,i,s,o]=e;return[i,s,o,"00","00","00"]}else if(e=/(\d\d\d\d)-(\d\d)/.exec(t)){const[r,i,s]=e;return[i,s,"01","00","00","00"]}else if(e=/(\d\d\d\d)/.exec(t)){const[r,i]=e;return[i,"01","01","00","00","00"]}return["1970","01","01","00","00","00"]}function I2e([t,e,r,i,s,o],a,u){switch(a){case"year":return`@${t}`;case"quarter":{const l=Math.floor(+e/3)+1;return`@${t}-Q${l}`}case"month":return`@${t}-${e}`;case"week":return`@${t}-${e}-${r}-WK`;case"day":return`@${t}-${e}-${r}`;case"hour":return`@${t}-${e}-${r} ${i}`;case"minute":return`@${t}-${e}-${r} ${i}:${s}`;case"second":return u!==void 0?`@${t}-${e}-${r} ${i}:${s}:${o}[${u}]`:`@${t}-${e}-${r} ${i}:${s}:${o}`;default:throw new Error("Unknown timeframe.")}}function Uc(t){var e;const r=[];for(const i of(e=t.path)!==null&&e!==void 0?e:[])r.push((0,o_.maybeQuoteIdentifier)(i)),r.push(".");if(r.push((0,o_.maybeQuoteIdentifier)(t.name)),t.parameters){const i=[];for(let s=0;s<t.parameters.length;s++){const o=t.parameters[s];i.push((0,o_.maybeQuoteIdentifier)(o.name)),i.push(" is "),i.push(...Rj(o.value)),s<t.parameters.length-1&&i.push(",",tu)}r.push(...$1("(",i,")",{spaces:!1}))}return r}function cgt(t){const e=[];return e.push(...a_(t.annotations)),e.push("run: "),e.push(...Dj(t.definition)),e}function fgt(t){const e=[];switch(t.kind){case"source_reference":{e.push(...Uc(t));break}case"refinement":e.push(...Dj(t));break}return e}function Dj(t){const e=[];switch(t.kind){case"arrow":{e.push(...fgt(t.source)),e.push(" -> "),e.push(...fh(t.view));break}case"query_reference":{e.push(...Uc(t));break}case"refinement":{const r=Dj(t.base);t.base.kind==="arrow"?e.push(...$1("(",r,")",{spaces:!1})):e.push(...r),e.push(" + "),e.push(...fh(t.refinement));break}}return e}function fh(t){const e=[];switch(t.kind){case"arrow":{e.push(...fh(t.source)),e.push(" -> "),e.push(...fh(t.view));break}case"view_reference":{e.push(...Uc(t));break}case"refinement":{e.push(...fh(t.base)),e.push(" + "),e.push(...fh(t.refinement));break}case"segment":{e.push(...dgt(t));break}}return e}function dgt(t){if(t.operations.length===0)return["{ }"];const e=t.operations.length>1,r=[];for(let i=0;i<t.operations.length;i++){const s=t.operations[i],o=[s];for(;i<t.operations.length-1;){const a=t.operations[i+1];if(a.kind===s.kind)o.push(a),i++;else break}r.push(...xgt(o)),e&&i<t.operations.length-1&&r.push(tu)}return $1("{",r,"}")}function xgt(t){switch(t[0].kind){case"aggregate":return Oj(t,"aggregate");case"group_by":return Oj(t,"group_by");case"order_by":return mgt(t);case"nest":return ygt(t);case"limit":return Agt(t);case"where":return $2e(t);case"having":return bgt(t);case"drill":return Sgt(t);case"calculate":return Oj(t,"calculate")}}function B1(t,e,r=""){const i=[];i.push(`${t}:`);const s=e.length>1||e.some(o=>o.includes(tu));s?i.push(tu,Cj):i.push(" ");for(let o=0;o<e.length;o++){const a=e[o];i.push(...a),e.length>1&&o<e.length-1&&i.push(r),s&&o<e.length-1&&i.push(tu)}return s&&i.push(Tj),i}function hgt(t){const e=[];return e.push(...wj(t.expression)),e}function tAt(t){return t}function wj(t){var e;switch(t.kind){case"field_reference":return Uc(t);case"time_truncation":return[...Uc(t.field_reference),".",t.truncation];case"filtered_field":return[...Uc(t.field_reference),...$1(" {",$2e(t.where),"}")];case"literal_value":return Rj(t.literal_value);case"moving_average":{const r=["avg_moving",...$1("(",[...Uc(t.field_reference),t.rows_preceding!==void 0?`, ${t.rows_preceding}`:", 0",t.rows_following!==void 0?`, ${t.rows_following}`:""],")",{spaces:!1})];return!((e=t.partition_fields)===null||e===void 0)&&e.length&&r.push(...$1(" {",["partition_by",": ",...lgt(t.partition_fields.flatMap(i=>Uc(i)),", ")],"}")),r}}}function pgt(t,e=!1){const r=[];return e||r.push(...a_(t.field.annotations)),t.name&&(r.push((0,o_.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...hgt(t.field)),r}function Oj(t,e){const r=[],i=t.length===1;return i&&r.push(...a_(t[0].field.annotations)),r.push(...B1(e,t.map(s=>pgt(s,i)))),r}function mgt(t){return B1("order_by",t.map(ggt),",")}function ggt(t){const e=[];return e.push(...Uc(t.field_reference)),t.direction&&(e.push(" "),e.push(t.direction)),e}function ygt(t){const e=[],r=t.length===1;return r&&e.push(...a_(t[0].view.annotations)),e.push(...B1("nest",t.map(i=>Egt(i,r)))),e}function Egt(t,e=!1){const r=[];return e||r.push(...a_(t.view.annotations)),t.name&&(r.push((0,o_.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...vgt(t.view)),r}function vgt(t){return fh(t.definition)}function _gt(t){return[`limit: ${t.limit}`]}function Agt(t){const e=[];for(let r=0;r<t.length;r++)r!==0&&e.push(tu),e.push(..._gt(t[r]));return e}function $2e(t){return B1("where",t.map(Fj),",")}function Sgt(t){return B1("drill",t.map(Fj),",")}function bgt(t){return B1("having",t.map(Fj),",")}const Cgt=["`","'",'"'];function B2e(t){let e,r;for(const i of Cgt){const s=Tgt(t,i);if(s===t)return`f${i}${t}${i}`;(r===void 0||s.length<r.length)&&(e=i,r=s)}return`f${e}${r}${e}`}function Tgt(t,e){let r="";for(let i=0;i<t.length;i++)t.slice(i).startsWith(e)?(r+="\\"+e,i+=e.length):(r+=t[i],t[i]==="\\"&&(r+=t[++i]));return r}function k2e(t){switch(t.kind){case"filter_string":return[...wj(t.expression)," ~ ",B2e(t.filter)];case"literal_equality":return[...wj(t.expression)," = ",...Rj(t.value)]}}function Fj(t){return k2e(t.filter)}function a_(t){return t?t.flatMap(Rgt):[]}function Rgt(t){return[t.value.trim(),tu]}var k1={};Object.defineProperty(k1,"__esModule",{value:!0}),k1.nestUnions=Nj,k1.unnestUnions=Dw,k1.convertFromThrift=ww,k1.convertToThrift=Ow;const Dgt=s_;function Nj(t){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(Nj);{const e={};let r;for(const i in t)i==="kind"?r=t[i]:e[i]=Nj(t[i]);return r===void 0?e:{[r]:e}}}function Dw(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(r=>Dw(r,e));{const r=M1(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=Dw(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=Dw(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}function ww(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(e==="number")return t;const r=M1(e);if(r.type!=="enum")throw new Error(`Found a number where a ${e} was expected`);const i=Object.entries(r.values).find(([,s])=>s===t);if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i[0]}else{if(Array.isArray(t))return t.map(r=>ww(r,e));{const r=M1(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0&&t[i]!==null){const s=ww(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=ww(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}}function M1(t){const e=Dgt.MALLOY_INTERFACE_TYPES[t];if(e===void 0)throw new Error(`Unknown Malloy interface type ${t}`);return e}function Ow(t,e){if(t==null)return t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string"){if(e==="string")return t;const r=M1(e);if(r.type==="enum"){const i=r.values[t];if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i}}else{if(Array.isArray(t))return t.map(r=>Ow(r,e));{const r=M1(e);if(r.type==="union"){const i=t.kind,s=r.options[i];if(s===void 0)throw new Error(`${i} is not a valid union of ${e}`);const o=M1(s);if(o.type!=="struct")throw new Error("Union fields must be structs");const a={};for(const u in t){if(u==="kind")continue;const l=o.fields[u];a[u]=Ow(t[u],l.type)}return{[i]:a}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=Ow(t[s],o.type)}return i}}}}(function(t){var e=R&&R.__createBinding||(Object.create?function(o,a,u,l){l===void 0&&(l=u);var c=Object.getOwnPropertyDescriptor(a,u);(!c||("get"in c?!a.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return a[u]}}),Object.defineProperty(o,l,c)}:function(o,a,u,l){l===void 0&&(l=u),o[l]=a[u]}),r=R&&R.__exportStar||function(o,a){for(var u in o)u!=="default"&&!Object.prototype.hasOwnProperty.call(a,u)&&e(a,o,u)};Object.defineProperty(t,"__esModule",{value:!0}),t.thingy4sddfdfsd=t.thingy4sdfsd=t.thingy4dfdsfs=t.thingy4asdfas=t.thingy4asdfasdf=t.thingy3dfdf=t.thingy3=t.thingy2asdf=t.thingyssdfg=t.thingy123r=t.thingy1=t.res=t.test=t.convertToThrift=t.convertFromThrift=t.unnestUnions=t.nestUnions=t.filterToMalloy=t.queryToMalloy=void 0,r(s_,t);var i=Tw;Object.defineProperty(t,"queryToMalloy",{enumerable:!0,get:function(){return i.queryToMalloy}}),Object.defineProperty(t,"filterToMalloy",{enumerable:!0,get:function(){return i.filterToMalloy}});var s=k1;Object.defineProperty(t,"nestUnions",{enumerable:!0,get:function(){return s.nestUnions}}),Object.defineProperty(t,"unnestUnions",{enumerable:!0,get:function(){return s.unnestUnions}}),Object.defineProperty(t,"convertFromThrift",{enumerable:!0,get:function(){return s.convertFromThrift}}),Object.defineProperty(t,"convertToThrift",{enumerable:!0,get:function(){return s.convertToThrift}}),t.test={entries:[{kind:"source",name:"flights",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"boolean_type"},annotations:[{value:"# foo=1"}]},{kind:"dimension",name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}},{kind:"dimension",name:"arr_rec",type:{kind:"array_type",element_type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}}},{kind:"dimension",name:"rec",type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}},{kind:"join",name:"carriers",relationship:"one",schema:{fields:[{kind:"dimension",name:"code",type:{kind:"string_type"}}]}},{kind:"view",name:"by_carrier",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]}}]},parameters:[{name:"param",type:{kind:"number_type"},default_value:{kind:"number_literal",number_value:7}}]}],anonymous_queries:[]},t.res={connection_name:"foo",data:{kind:"array_cell",array_value:[{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"UA"},{kind:"number_cell",number_value:12341234}]},{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"AA"},{kind:"number_cell",number_value:2343}]}]},schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]},sql:"SELECT * ..."},t.thingy1={definition:{kind:"query_reference",name:"flights_by_carrier"}},t.thingy123r={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingyssdfg={definition:{kind:"refinement",base:{kind:"query_reference",name:"flights"},refinement:{kind:"view_reference",name:"by_carrier"}}},t.thingy2asdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"where",filter:{kind:"filter_string",expression:{kind:"field_reference",name:"carrier"},filter:"WN"}}]}}}},t.thingy3={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}}},t.thingy3dfdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"view_reference",name:"top10"}}}},t.thingy4asdfasdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}},t.thingy4asdfas={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingy4dfdsfs={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"limit",limit:10}]}}}},t.thingy4sdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"limit",limit:10}]}}},t.thingy4sddfdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[]}}}})(ch);var wgt=R&&R.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Ogt=R&&R.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Fgt=R&&R.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var i=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&wgt(r,e,i[s]);return Ogt(r,e),r}}();Object.defineProperty(eu,"__esModule",{value:!0}),eu.sourceDefToSourceInfo=P2e,eu.modelDefToModelInfo=Ngt,eu.convertFieldInfos=P1,eu.writeLiteralToTag=H2e,eu.getResultStructMetadataAnnotation=Fw,eu.writeMalloyObjectToTag=U1,eu.extractMalloyObjectFromTag=Lw;const M2e=Fgt(ch),Ms=Ri,Lj=Ns,Ij=rs;function P2e(t){var e;const r=t.parameters&&Object.entries(t.parameters).length>0?Object.entries(t.parameters).map(([s,o])=>(0,Ms.isAtomic)(o)?{name:s,type:Nw(o),default_value:U2e(o.value)}:{name:s,type:{kind:"filter_expression_type",filter_type:{kind:`${o.filterType}_type`}},default_value:U2e(o.value)}):void 0;return{name:(e=t.as)!==null&&e!==void 0?e:t.name,schema:{fields:P1(t,t.fields)},parameters:r,annotations:$j(t)}}function Ngt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ms.isSourceDef)(i)){const s=P2e(i);e.entries.push({kind:"source",...s})}else if(i.type==="query"){const s=(0,Ms.getResultStructDefForQuery)(t,i),o=$j(i),a=s.resultMetadata?Fw(s,s.resultMetadata):void 0,u=[...o??[],...a?[a]:[]],l={kind:"source",name:r,schema:{fields:P1(s,s.fields)},annotations:u.length>0?u:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,Ms.getResultStructDefForQuery)(t,r),s=$j(r),o=i.resultMetadata?Fw(i,i.resultMetadata):void 0,a=[...s??[],...o?[o]:[]],u={schema:{fields:P1(i,i.fields)},annotations:a.length>0?a:void 0};e.anonymous_queries.push(u)}return e}function U2e(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function $j(t){return(0,Lj.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function P1(t,e){var r,i,s;const o=[];for(const a of e){if(!(a.accessModifier===void 0))continue;const c=(0,Lj.annotationToTaglines)(a.annotation).map(d=>({value:d})),f=c.length>0?c:void 0;if((0,Ms.isTurtle)(a)){const d=(0,Ms.getResultStructDefForView)(t,a),x=d.resultMetadata?Fw(d,d.resultMetadata):void 0,p=[...f??[],...x?[x]:[]],m={kind:"view",name:(r=a.as)!==null&&r!==void 0?r:a.name,annotations:p.length>0?p:void 0,schema:{fields:P1(d,d.fields)}};o.push(m)}else if((0,Ms.isAtomic)(a)){const d=(0,Ms.expressionIsAggregate)(a.expressionType),x=(0,Ms.expressionIsScalar)(a.expressionType);if(!d&&!x||a.type==="error")continue;const p=a.resultMetadata?j2e(a,a.resultMetadata):void 0;let m;if((0,Ms.isRecordOrRepeatedRecord)(a)&&a.queryTimezone){const v=Ij.Tag.withPrefix("#(malloy) ");v.set(["query_timezone"],a.queryTimezone),m={value:v.toString()}}const g=[...f??[],...p?[p]:[],...m?[m]:[]],y={kind:d?"measure":"dimension",name:(i=a.as)!==null&&i!==void 0?i:a.name,type:Nw(a),annotations:g.length>0?g:void 0};o.push(y)}else if((0,Ms.isJoinedSource)(a)){const d={kind:"join",name:(s=a.as)!==null&&s!==void 0?s:a.name,annotations:f,schema:{fields:P1(a,a.fields)},relationship:a.join};o.push(d)}}return o}function j2e(t,e){const r=Ij.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.drillable&&(r.set(["drillable"]),i=!0),e.filterList&&(q2e(r,e.filterList),i=!0),e.drillExpression&&(z2e(r,["drill_expression"],e.drillExpression),i=!0),e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Igt(t.name));r.set(["drill_expression","code"],o),i=!0}return i?{value:r.toString()}:void 0}function q2e(t,e){for(let r=0;r<e.length;r++){const i=e[r];i.expressionType!=="scalar"||i.isSourceFilter||(t.set(["drill_filters",r,"code"],i.code),i.filterView&&t.set(["drill_filters",r,"filter_view"],i.filterView),i.filterView===void 0&&i.stableFilter!==void 0&&(z2e(t,["drill_filters",r,"expression"],i.stableFilter.expression),i.stableFilter.kind==="filter_string"?(t.set(["drill_filters",r,"kind"],"filter_expression"),t.set(["drill_filters",r,"filter_expression"],i.stableFilter.filter)):(t.set(["drill_filters",r,"kind"],"literal_equality"),H2e(t,["drill_filters",r,"value"],i.stableFilter.value))))}}function z2e(t,e,r){U1(t,e,r,"Expression")}function H2e(t,e,r){U1(t,e,r,"LiteralValue")}function Lgt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Igt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Lgt(t)}\``}function Fw(t,e){var r,i;const s=Ij.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList&&(q2e(s,e.filterList),o=!0),e.drillable&&(s.set(["drillable"]),o=!0),e.orderBy){for(let a=0;a<e.orderBy.length;a++){const u=e.orderBy[a],l=typeof u.field=="number"?(r=t.fields[u.field-1].as)!==null&&r!==void 0?r:t.fields[u.field-1].name:u.field,c=(i=u.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",a,l],c)}o=!0}return t.queryTimezone&&(s.set(["query_timezone"],t.queryTimezone),o=!0),o?{value:s.toString()}:void 0}function Nw(t){if((0,Ms.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!$gt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Bgt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ms.isRepeatedRecord)(t))return{kind:"array_type",element_type:Q2e(t)};if(t.type==="record")return Q2e(t);if(t.type==="array")return{kind:"array_type",element_type:Nw(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Q2e(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=j2e(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,Lj.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ms.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:Nw(e)};throw new Error("Expected record type to not have a table as its child")})}}function $gt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Bgt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function nAt(t){return t}function rAt(t){return t}function U1(t,e,r,i){if(i==="string"){t.set(e,r);return}else if(i==="number"){t.set(e,r);return}else if(i==="boolean"){t.set(e,r.toString());return}const s=M2e.MALLOY_INTERFACE_TYPES[i];if(s===void 0)throw new Error(`Unknown Malloy interface type ${i}`);if(s.type==="enum")if(typeof r=="string")t.set(e,r);else throw new Error(`Expected string for enum ${i}`);else if(s.type==="struct")for(const o in s.fields){const a=s.fields[o],u=r[o];if(u===void 0){if(!a.optional)throw new Error(`Mising value for non-optional field ${o} in type ${i}`)}else if(a.array)if(Array.isArray(u))for(let l=0;l<u.length;l++)U1(t,[...e,o,l],u[l],a.type);else throw new Error(`Expected array for field ${o} of type ${i} but got ${typeof r}`);else U1(t,[...e,o],u,a.type)}else{const o=r.kind;t.set([...e,"kind"],o);const a=s.options[o];if(a===void 0)throw new Error(`Unknown Malloy interface union kind ${o} for type ${i}`);U1(t,e,r,a)}}function Lw(t,e){if(e==="string")return t.text();if(e==="number")return t.numeric();if(e==="boolean")return t.text()==="true";const r=M2e.MALLOY_INTERFACE_TYPES[e];if(r===void 0)throw new Error(`Unknown Malloy interface type ${e}`);if(r.type==="enum"){const i=t.text();if(i===void 0)throw new Error(`Missing value for enum ${e}`);if(i in r.values)return i;throw new Error(`Unknown value ${i} for enum ${e}`)}else if(r.type==="struct"){const i={};for(const[s,o]of Object.entries(r.fields)){const a=t.tag(s);if(a===void 0){if(o.optional)continue;throw new Error(`Missing value for key ${s} of type ${o}`)}if(o.array){const u=[],l=a.array();if(l===void 0)throw new Error(`Missing array value for key ${s} of type ${o}`);for(const c of l)u.push(Lw(c,o.type));i[s]=u}else{const u=Lw(a,o.type);u!=null&&(i[s]=u)}}return i}else{const i=t.text("kind");if(i===void 0)throw new Error(`Missing kind for union ${e}`);const s=r.options[i];if(s===void 0)throw new Error(`Unknown kind ${i} for union ${e}`);const o=Lw(t,s);return{kind:i,...o}}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_LOG_RANGE=void 0,t.wrapLegacyInfoConnection=a,t.wrapLegacyConnection=u,t.mapData=c,t.wrapResult=f,t.nodeToLiteralValue=d,t.mapLogs=x;const e=rs,r=Ns,i=Ri,s=eu,o=YE;function a(p){return{get dialectName(){return p.dialectName},async fetchSchemaForSQLQuery(m){const g=await p.fetchSchemaForSQLStruct({connection:p.name,selectStr:m},{}),y=g.structDef;if(y===void 0)throw new Error(g.error);return{fields:(0,s.convertFieldInfos)(y,y.fields)}},async fetchSchemaForTable(m){const g=`${p.name}:${m}`,y=await p.fetchSchemaForTables({[g]:m},{}),v=y.schemas[g];if(v===void 0)throw new Error(y.errors[g]);return{fields:(0,s.convertFieldInfos)(v,v.fields)}}}}function u(p){return{...a(p),runSQL:async(m,g)=>{const y=await p.runSQL(m);return c(y.rows,g)}}}function l(p){if(p instanceof Date)return p;if(p.constructor.name==="Date")return new Date(p);if(typeof p=="number")return new Date(p);if(typeof p!="string")return new Date(p.value);{let g=o.DateTime.fromISO(p,{zone:"UTC"});return g.isValid||(g=o.DateTime.fromSQL(p,{zone:"UTC"})),g.toJSDate()}}function c(p,m){function g(E,_){if(E===null)return{kind:"null_cell"};if(_.type.kind==="date_type"||_.type.kind==="timestamp_type"){const A=l(E).toISOString();return _.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(_.type.kind==="boolean_type"){if(typeof E=="number")return{kind:"boolean_cell",boolean_value:E!==0};if(typeof E!="boolean")throw new Error(`Invalid boolean ${E}`);return{kind:"boolean_cell",boolean_value:E}}else if(_.type.kind==="number_type"){if(typeof E!="number")throw new Error(`Invalid number ${E}`);return{kind:"number_cell",number_value:E}}else if(_.type.kind==="string_type"){if(typeof E!="string")throw new Error(`Invalid string ${E}`);return{kind:"string_cell",string_value:E}}else if(_.type.kind==="array_type"){if(!Array.isArray(E))throw new Error(`Invalid array ${E}`);return{kind:"array_cell",array_value:E.map(A=>g(A,{name:"array_element",type:_.type.element_type}))}}else{if(_.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(E)};if(_.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(E)};{const A=_.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(_)}, ${JSON.stringify(E)}`);return y(E,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(S=>({kind:"dimension",...S}))}})}}}function y(E,_){const A=[];for(const S of _.schema.fields){const b=E[S.name];if(S.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=g(b,S);A.push(C)}return{kind:"record_cell",record_value:A}}const v={kind:"join",schema:m,name:"root",relationship:"one"};return{kind:"array_cell",array_value:p.map(E=>y(E,v))}}function f(p){const m=p._queryResult.structs,g=m[m.length-1],y={fields:(0,s.convertFieldInfos)(g,g.fields)},v=(0,r.annotationToTaglines)(p.annotation).map(S=>({value:S})),E=g.resultMetadata?(0,s.getResultStructMetadataAnnotation)(g,g.resultMetadata):void 0;E&&v.push(E),v.push(...g.resultMetadata?[]:[]);const _=e.Tag.withPrefix("#(malloy) ");if(p.sourceExplore&&_.set(["source","name"],p.sourceExplore.name),p._sourceArguments){const S=Object.entries(p._sourceArguments);for(let b=0;b<S.length;b++){const[C,T]=S[b],D=d(T.value);D!==void 0&&(0,s.writeLiteralToTag)(_,["source","parameters",b,"value"],D),_.set(["source","parameters",b,"name"],C)}}v.push({value:_.toString()}),v.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],p.resultExplore.name).toString()});const A=(0,r.annotationToTaglines)(p._modelDef.annotation).map(S=>({value:S}));return{schema:y,data:c(p.data.toObject(),y),connection_name:p.connectionName,annotations:v.length>0?v:void 0,model_annotations:A.length>0?A:void 0,query_timezone:p.data.field.queryTimezone,sql:p.sql}}function d(p){switch(p==null?void 0:p.node){case"numberLiteral":return{kind:"number_literal",number_value:Number.parseFloat(p.literal)};case"null":return{kind:"null_literal"};case"stringLiteral":return{kind:"string_literal",string_value:p.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:p.filterSrc};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"timeLiteral":return p.typeDef.type==="date"?p.typeDef.timeframe===void 0||(0,i.isDateUnit)(p.typeDef.timeframe)?{kind:"date_literal",date_value:p.literal,timezone:p.timezone,granularity:p.typeDef.timeframe}:void 0:{kind:"timestamp_literal",timestamp_value:p.literal,timezone:p.timezone,granularity:p.typeDef.timeframe};default:return}}t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function x(p,m){return p.map(g=>{var y,v,E,_;return{severity:g.severity,message:g.message,range:(v=(y=g.at)===null||y===void 0?void 0:y.range)!==null&&v!==void 0?v:t.DEFAULT_LOG_RANGE,url:(_=(E=g.at)===null||E===void 0?void 0:E.url)!==null&&_!==void 0?_:m}})}})(i_);var kgt=R&&R.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Mgt=R&&R.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Pgt=R&&R.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var i=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&kgt(r,e,i[s]);return Mgt(r,e),r}}();Object.defineProperty(r_,"__esModule",{value:!0}),r_.MalloyToQuery=void 0,r_.malloyToQuery=Qgt;const Ugt=M2,jgt=s2,mt=Pgt($),G2e=J2,dh=ks,qgt=Ye,zgt=ND,W2e=jr,Hgt=i_,xh=ZE,Bj="Malloy query documents";class V2e extends jgt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,W2e.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,G2e.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${Bj}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${Bj} may only have one run statement`);return i===void 0?(this.illegal(e,`${Bj} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.tags()),o=this.getAnnotations(e.topLevelAnonQueryDef().tags()),a=this.combineAnnotations(s,o);return i!==null?{annotations:a,definition:i}:null}getSourceArguments(e){const r=[];for(const i of e.sourceArgument()){const s=i.argumentId();if(s===void 0)return this.contextError(i,"unnamed-source-argument","Source argument must be named"),null;const o=(0,dh.getId)(s),a=this.getLiteralIncludingNegativeNumber(i.fieldExpr());if(a===null)return null;r.push({name:o,value:a})}return r}getQueryReference(e){const r=e.sourceArguments(),i=(0,dh.getId)(e);if(r){const s=this.getSourceArguments(r);return s===null?null:{name:i,parameters:s}}else return{name:i}}getQueryDefinition(e){if(e instanceof mt.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof mt.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof mt.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof mt.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof mt.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof mt.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof mt.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof mt.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof mt.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof mt.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof mt.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof mt.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof mt.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var a;const u=[...r??[],...(a=o.field.annotations)!==null&&a!==void 0?a:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:u.length>0?u:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var a;const u=[...r??[],...(a=o.field.annotations)!==null&&a!==void 0?a:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:u.length>0?u:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,dh.getId)(s.fieldName()),a=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:a,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof mt.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const a=this.getAnnotations(o.tags()),u=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,dh.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,a,u)}})}return s}getViewExpression(e){if(e instanceof mt.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof mt.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.drillStatement()){const r=e.drillStatement(),i=this.getDrill(r);return i===null?null:i.map(s=>({kind:"drill",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,dh.getId)(o)),i=r[r.length-1],s=r.slice(0,-1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,qgt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const a=r.refExpr();if(a.timeframe()){const u=this.getTimeframe(a.timeframe());return u===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:u}}}}else a.aggregate()&&this.notAllowed(a,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,dh.getId)(r.fieldNameDef()),a=this.getFieldExpression(r.fieldExpr());return a===null?null:{name:o,field:{expression:a,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof mt.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof mt.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof mt.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const a of s){const u=a.whereStatement();if(u){const l=this.getWhere(u);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}else{const r=this.getLiteralIncludingNegativeNumber(e);return r===null?null:{kind:"literal_value",literal_value:r}}}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),a=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(a)return this.stripQuote(a.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),a=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(a)return this.stripQuote(a.text,"'")}return null}getFilterExpr(e){if(e instanceof mt.ExprCompareContext){if(e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof mt.ExprFieldPathContext&&i instanceof mt.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),a=i.literal();if(a instanceof mt.FilterString_stubContext){const u=this.getFilterString(a.filterString());return u===null?null:{filter:{kind:"filter_string",expression:{kind:"field_reference",name:o,path:s},filter:u}}}}}else if(e.compareOp().EQ()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof mt.ExprFieldPathContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),a=this.getLiteralIncludingNegativeNumber(i);return a===null?(this.notAllowed(e,"Filters other than comparisons with filter strings or equality with literals"),null):{filter:{kind:"literal_equality",expression:{kind:"field_reference",name:o,path:s},value:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings or equality with literals"),null}getTimeLiteral(e,r){const i=r(e.text);if(!i)return this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),null;const s=i.getValue(),o=s.timeframe;if(s.value.node!=="timeLiteral")return null;const a=s.value.literal,u=s.value.timezone;return s.type==="timestamp"?{kind:"timestamp_literal",timestamp_value:a,granularity:o,timezone:u}:o==="hour"||o==="minute"||o==="second"?null:{kind:"date_literal",date_value:a,granularity:o,timezone:u}}getLiteralIncludingNegativeNumber(e){if(e instanceof mt.ExprLiteralContext)return this.getLiteral(e.literal());if(e instanceof mt.ExprMinusContext){const r=e.fieldExpr();if(r instanceof mt.ExprLiteralContext){const i=this.getLiteral(r.literal());return i===null||i.kind!=="number_literal"?null:{kind:"number_literal",number_value:-i.number_value}}}return null}getLiteral(e){if(e instanceof mt.ExprTimeContext){const r=e.dateLiteral();return r instanceof mt.LiteralTimestampContext?this.getTimeLiteral(r,xh.LiteralTimestamp.parse):r instanceof mt.LiteralHourContext?this.getTimeLiteral(r,xh.LiteralHour.parse):r instanceof mt.LiteralDayContext?this.getTimeLiteral(r,xh.LiteralDay.parse):r instanceof mt.LiteralWeekContext?this.getTimeLiteral(r,xh.LiteralWeek.parse):r instanceof mt.LiteralMonthContext?this.getTimeLiteral(r,xh.LiteralMonth.parse):r instanceof mt.LiteralQuarterContext?this.getTimeLiteral(r,xh.LiteralQuarter.parse):r instanceof mt.LiteralYearContext?this.getTimeLiteral(r,xh.LiteralYear.parse):null}else{if(e instanceof mt.ExprArrayLiteralContext)return this.notAllowed(e,"array literals"),null;if(e instanceof mt.ExprLiteralRecordContext)return this.notAllowed(e,"record literals"),null;if(e instanceof mt.ExprStringContext){const[r,i]=(0,dh.getPlainString)(e);for(const s of i)s instanceof Ugt.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return{kind:"string_literal",string_value:r??""}}else{if(e instanceof mt.ExprBoolContext)return{kind:"boolean_literal",boolean_value:e.TRUE()!==null};if(e instanceof mt.ExprNumberContext)return{kind:"number_literal",number_value:Number(e.text)};if(e instanceof mt.ExprNULLContext)return{kind:"null_literal"};if(e instanceof mt.FilterString_stubContext){const r=e.getChild(0);if(r instanceof mt.FilterStringContext){const i=this.getFilterString(r);if(i)return{kind:"filter_expression_literal",filter_expression_value:i}}}}}return null}getDrill(e){const i=e.drillClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}r_.MalloyToQuery=V2e;function Qgt(t){const e=(0,W2e.getSourceInfo)(t),r=new G2e.BaseMessageLogger(null),i="internal://query.malloy",s=(0,zgt.runMalloyParser)(t,i,e,r),a=new V2e(s,r).visit(s.root),u=(0,Hgt.mapLogs)(r.getLog(),i);if(a===null)return{logs:u};if(!("definition"in a))throw new Error("Expected a query");return{query:a,logs:u}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Af;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=n_;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=r_;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})})(JT);var $e={},Iw={};Object.defineProperty(Iw,"__esModule",{value:!0}),Iw.MALLOY_VERSION=void 0,Iw.MALLOY_VERSION="0.0.314",Object.defineProperty($e,"__esModule",{value:!0}),$e.InMemoryModelCache=$e.CacheManager=$e.CSVWriter=$e.JSONWriter=$e.DataWriter=$e.DataRecord=$e.DataArray=$e.Result=$e.ExploreMaterializer=$e.PreparedResultMaterializer=$e.QueryMaterializer=$e.ModelMaterializer=$e.SingleConnectionRuntime=$e.ConnectionRuntime=$e.Runtime=$e.ExploreField=$e.JoinRelationship=$e.QueryField=$e.Query=$e.StringField=$e.UnsupportedField=$e.JSONField=$e.BooleanField=$e.NumberField=$e.TimestampField=$e.DateField=$e.TimestampTimeframe=$e.DateTimeframe=$e.AtomicField=$e.AtomicFieldType=$e.Explore=$e.SourceRelationship=$e.FixedConnectionMap=$e.InMemoryURLReader=$e.EmptyURLReader=$e.PreparedResult=$e.DocumentCompletion=$e.DocumentSymbol=$e.DocumentPosition=$e.DocumentRange=$e.DocumentTablePath=$e.Parse=$e.PreparedQuery=$e.Model=$e.MalloyError=$e.Malloy=void 0;const Y2e=JT,_r=Ri,K2e=YE,kj=Gx,Ggt=Iw,Wgt=H2,Vn=Ns,Vgt=nh,Ygt=jr,Kgt=Wv;function Xgt(t){return t.type==="table"||t.type==="sql_select"||t.type==="query_source"}const X2e="internal://internal.malloy";let jc=class zO{static get version(){return Ggt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(X2e));let a=r;s!=null&&s.importBaseURL&&(a=s==null?void 0:s.importBaseURL);const u=new Y2e.MalloyTranslator(r.toString(),a.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(u.allDialectsEnabled=!0),new Z2e(u,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return zO._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return qw(r,e).then(({contents:a,invalidationKey:u})=>zO._parse(a,e,s,o,u))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:a,refreshSchemaCache:u,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:d}){var x,p,m,g,y;let v;if(u&&(v=typeof u=="number"?u:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(X2e));const E={};if(r===void 0&&d!==void 0){const S=await d.getCachedModelDef(s,e.toString());if(S)return new j1(S.modelDef,[],[e.toString(),...jw(S.modelDef.dependencies)])}f??(f=e);let _;const A=e.toString();if(i!==void 0){_=i._translator;const S=(x=i._invalidationKey)!==null&&x!==void 0?x:await Kj(s,e);E[A]=S}else{if(r===void 0){const{contents:S,invalidationKey:b}=await qw(s,e);E[A]=b,r=S}else{const S=await Kj(s,e);E[A]=S}_=new Y2e.MalloyTranslator(A,f.toString(),{urls:{[A]:r}},c)}for(;;){const S=_.translate(a==null?void 0:a._modelDef);if(S.final)if(S.modelDef){await(d==null?void 0:d.setCachedModelDef(e.toString(),{modelDef:S.modelDef,invalidationKeys:E}));for(const b of _.newlyTranslatedDependencies())await(d==null?void 0:d.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:E}));return new j1(S.modelDef,S.problems||[],[...(p=a==null?void 0:a.fromSources)!==null&&p!==void 0?p:[],...(m=S.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},C=(a==null?void 0:a._modelDef)||b;return new j1(C,S.problems||[],[...(g=a==null?void 0:a.fromSources)!==null&&g!==void 0?g:[],...(y=S.fromSources)!==null&&y!==void 0?y:[]])}else{const b=S.problems||[],C=_.prettyErrors();throw new J2e(`Error(s) compiling model:
|
|
1398
1398
|
${C}`,b)}else{if(S.urls)for(const C of S.urls)try{if(zw(C))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(d!==void 0){const w=await d.getCachedModelDef(s,C);if(w){for(const k in w.invalidationKeys)E[k]=w.invalidationKeys[k];_.update({translations:{[C]:w.modelDef}});continue}}const{contents:T,invalidationKey:D}=await qw(s,new URL(C)),O={[C]:T};E[C]=D,_.update({urls:O})}catch(T){_.update({errors:{urls:{[C]:T.message}}})}const{modelAnnotation:b}=_.modelAnnotation(a==null?void 0:a._modelDef);if(S.tables){const C=new Map;for(const T in S.tables){const{connectionName:D,tablePath:O}=S.tables[T],w=C.get(D);w===void 0?C.set(D,{[T]:O}):w[T]=O}for(const[T,D]of C)try{const O=await o.lookupConnection(T),{schemas:w,errors:k}=await zO.safelyFetchTableSchema(O,D,{refreshTimestamp:v,modelAnnotation:b});_.update({tables:w,errors:{tables:k}})}catch(O){const w={},k={};for(const U in D)k[U]=O.toString();_.update({tables:w,errors:{tables:k}})}}if(S.compileSQL){const C=S.compileSQL,T=C.connection,D=(0,Vgt.sqlKey)(C.connection,C.selectStr);try{const w=await(await o.lookupConnection(T)).fetchSchemaForSQLStruct(C,{refreshTimestamp:v,modelAnnotation:b});w.error&&_.update({errors:{compileSQL:{[D]:w.error}}}),w.structDef&&_.update({compileSQL:{[D]:w.structDef}})}catch(O){const w={};w[D]=O.toString(),_.update({errors:{compileSQL:w}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const a=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(a)}if(i){const a=await s.runSQL(i.selectStr);return new c_({structs:[i],sql:i.selectStr,result:a.rows,totalRows:a.totalRows,runStats:a.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:a.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const a=await s.runSQL(r.sql,o);return new c_({...r._rawQuery,result:a.rows,totalRows:a.totalRows,runStats:a.runStats,profilingUrl:a.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const a=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(a)}if(!s.canStream())throw new Error(`Connection '${a}' cannot stream results.`);let u,l;if(i)l=new lo(i),u=i.selectStr;else if(r!==void 0)l=r.resultExplore,u=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(u,o))yield new mh(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};$e.Malloy=jc;class J2e extends Error{constructor(e,r=[]){super(e),this.problems=r}}$e.MalloyError=J2e;class j1{constructor(e,r,i){var s,o;this.modelDef=e,this.problems=r,this.fromSources=i,this.references=new Kgt.ReferenceList((s=i[0])!==null&&s!==void 0?s:"",(o=e.references)!==null&&o!==void 0?o:[])}tagParse(e){return(0,Vn.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this.references.find(e)}getImport(e){var r;return(r=this.modelDef.imports)===null||r===void 0?void 0:r.find(i=>(0,Ygt.locationContainsPosition)(i.location,e))}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new hh(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new hh(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new hh(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if(r&&(0,_r.isSourceDef)(r))return new lo(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(_r.isSourceDef).map(e=>new lo(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}$e.Model=j1;class hh{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,Vn.annotationToTag)(this._modelDef.annotation).tag;return e=(0,Vn.addModelScope)(e,r),(0,Vn.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new _r.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new u_({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,_r.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}$e.PreparedQuery=hh;class Z2e{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new $w(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new e1e(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new t1e(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}$e.Parse=Z2e;class e1e{constructor(e){this._range=q1.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}$e.DocumentTablePath=e1e;class q1{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new q1(new Mj(e.start.line,e.start.character),new Mj(e.end.line,e.end.character))}}$e.DocumentRange=q1;class Mj{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}$e.DocumentPosition=Mj;class $w{constructor(e){this._range=q1.fromJSON(e.range),this._lensRange=e.lensRange?q1.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new $w(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}$e.DocumentSymbol=$w;class t1e{constructor(e){this.type=e.type,this.text=e.text}}$e.DocumentCompletion=t1e;class u_{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new u_(e,r)}tagParse(e){const r=(0,Vn.annotationToTag)(this.modelDef.annotation).tag;return e=(0,Vn.addModelScope)(e,r),(0,Vn.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,Vn.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new lo(r,this.sourceExplore)}catch{return new lo(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,_r.isSourceDef)(r))return new lo(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceArguments(){return this.inner.sourceArguments}get _sourceFilters(){return this.inner.sourceFilters||[]}}$e.PreparedResult=u_;class n1e{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}$e.EmptyURLReader=n1e;class Jgt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return zw(e.toString())?null:g1e(r)}}$e.InMemoryURLReader=Jgt;class Bw{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new Bw(new Map(e.map(r=>[r.name,r])))}}$e.FixedConnectionMap=Bw;var r1e;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(r1e||($e.SourceRelationship=r1e={}));class Pj{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof lo}isQuery(){return this instanceof Gj}}class lo extends Pj{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,_r.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,Vn.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,Vn.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i=r.fields.find(o=>{var a;return((a=o.as)!==null&&a!==void 0?a:o.name)===e});if(i===void 0)throw new Error(`No such view named \`${e}\``);if(i.type!=="turtle")throw new Error(`\`${e}\` is not a view`);const s={type:"query",structRef:r,pipeline:i.pipeline};return new hh(s,this.modelDef,[],e)}get modelDef(){if(!(0,_r.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new j1(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,_r.isJoined)(i))return[s,new Wj(i,this,o)];if(i.type==="turtle")return[s,new Gj(i,this,o)];if(i.type==="string")return[s,new Qj(i,this,o)];if(i.type==="number")return[s,new kw(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new kw({...i,type:"number"},this,o)]:[s,new Uj(i,this,o)];if(i.type==="timestamp")return[s,new jj(i,this,o)];if(i.type==="boolean")return[s,new qj(i,this,o)];if(i.type==="json")return[s,new zj(i,this,o)];if(i.type==="sql native")return[s,new Hj(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(a=>{if(typeof a.field=="string")return{field:this.fieldMap.get(a.field),dir:a.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(a=>a.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(a=>!o.has(a.name)).map(a=>({field:a,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof Wj}get filters(){var e;return(0,_r.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,_r.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?lo.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?lo.fromJSON(e.sourceExplore):void 0;return new lo(e._structDef,r,i)}get location(){return this.structDef.location}collectSourceComponents(e){const r=[];if(e.type==="composite"){for(const i of e.sources)r.push(...this.collectSourceComponents(i));return r}if(Xgt(e)){if(e.type==="table")r.push({type:"table",tableName:e.tablePath,componentID:`${e.connection}:${e.tablePath}`,sourceID:`${e.connection}:${e.tablePath}`});else if(e.type==="sql_select")r.push({type:"sql",selectStatement:e.selectStr,componentID:`${e.connection}:${e.selectStr}`,sourceID:`${e.connection}:${e.selectStr}`});else if(e.type==="query_source"){let i;try{i=new hh(e.query,this.modelDef,[]).getPreparedResult().sql}catch(o){i=`-- Could not compile SQL for query ${e.query.name||"unnamed query"}: ${o instanceof Error?o.message:String(o)}`}const s=`${e.connection}:${i}`;r.push({type:"sql",selectStatement:i,componentID:s,sourceID:s})}}else return[];for(const i of e.fields)(0,_r.isJoined)(i)&&r.push(...this.collectSourceComponents(i));return r}getSourceComponents(){const e={};if((0,_r.isSourceDef)(this.structDef)){const r=this.collectSourceComponents(this.structDef);for(const i of r)i.componentID?e[i.componentID]=i:i.sourceID&&(e[i.sourceID]=i)}return Object.values(e)}}$e.Explore=lo;var gl;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(gl||($e.AtomicFieldType=gl={}));class qf extends Pj{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return gl.String;case"boolean":return gl.Boolean;case"date":return gl.Date;case"timestamp":return gl.Timestamp;case"number":return gl.Number;case"json":return gl.Json;case"sql native":return gl.NativeUnsupported;case"error":return gl.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,Vn.addModelScope)(e,this.parent.modelTag),(0,Vn.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,_r.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,_r.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof Qj}isNumber(){return this instanceof kw}isDate(){return this instanceof Uj}isBoolean(){return this instanceof qj}isJSON(){return this instanceof zj}isTimestamp(){return this instanceof jj}isUnsupported(){return this instanceof Hj}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}$e.AtomicField=qf;var ph;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(ph||($e.DateTimeframe=ph={}));var yl;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(yl||($e.TimestampTimeframe=yl={}));let Uj=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return ph.Day;case"week":return ph.Week;case"month":return ph.Month;case"quarter":return ph.Quarter;case"year":return ph.Year}}};$e.DateField=Uj;let jj=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return yl.Day;case"week":return yl.Week;case"month":return yl.Month;case"quarter":return yl.Quarter;case"year":return yl.Year;case"second":return yl.Second;case"hour":return yl.Hour;case"minute":return yl.Minute}}};$e.TimestampField=jj;let kw=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}};$e.NumberField=kw;let qj=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}};$e.BooleanField=qj;let zj=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}};$e.JSONField=zj;class Hj extends qf{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}$e.UnsupportedField=Hj;let Qj=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}};$e.StringField=Qj;class i1e extends Pj{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}$e.Query=i1e;class Gj extends i1e{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,Vn.addModelScope)(e,this.parent.modelTag),(0,Vn.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}$e.QueryField=Gj;var z1;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(z1||($e.JoinRelationship=z1={}));class Wj extends lo{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,_r.isJoined)(this.structDef))switch(this.structDef.join){case"one":return z1.OneToOne;case"many":case"cross":return z1.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===z1.OneToOne}get isArray(){return this.joinRelationship!==z1.OneToOne}tagParse(e){return e=(0,Vn.addModelScope)(e,this._parentExplore.modelTag),(0,Vn.annotationToTag)(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}get queryTimezone(){return(0,_r.isRecordOrRepeatedRecord)(this._structDef)?this._structDef.queryTimezone:super.queryTimezone}}$e.ExploreField=Wj;class Vj{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new n1e),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new l_(this,async()=>jc.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new l_(this,async()=>new j1(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}$e.Runtime=Vj;class Zgt extends Vj{constructor({urlReader:e,connections:r}){super({connections:Bw.fromArray(r),urlReader:e}),this.rawConnections=r}}$e.ConnectionRuntime=Zgt;class eyt extends Vj{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,kj.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,kj.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,kj.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}$e.SingleConnectionRuntime=eyt;class Mw{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new s1e(this.runtime,e,r)}makeExploreMaterializer(e,r){return new a1e(this.runtime,e,r)}makePreparedResultMaterializer(e){return new o1e(this.runtime,e)}}class l_ extends Mw{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,a=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const u=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await jc.compile({...u,urlReader:o,connections:a,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new l_(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},a=await this.getModel();return await jc.compile({...o,urlReader:i,connections:s,model:a,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const a=await this.materialize(),u=new _r.QueryModel(a._modelDef,o),l=a.getExploreByName(e).structDef;if(!(0,_r.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await u.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,_r.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let a="{index: *}";o.getFieldByNameIfExists("search_index")&&(a="search_index");const u=`
|
|
1399
1399
|
run: ${e}
|
|
1400
1400
|
-> ${a}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@malloydata/render",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.314",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"main": "dist/module/index.umd.js",
|
|
6
6
|
"types": "dist/module/index.d.ts",
|
|
@@ -29,9 +29,9 @@
|
|
|
29
29
|
"generate-flow": "ts-node ../../scripts/gen-flow.ts"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@malloydata/malloy": "0.0.
|
|
33
|
-
"@malloydata/malloy-interfaces": "0.0.
|
|
34
|
-
"@malloydata/malloy-tag": "0.0.
|
|
32
|
+
"@malloydata/malloy": "0.0.314",
|
|
33
|
+
"@malloydata/malloy-interfaces": "0.0.314",
|
|
34
|
+
"@malloydata/malloy-tag": "0.0.314",
|
|
35
35
|
"@tanstack/solid-virtual": "^3.10.4",
|
|
36
36
|
"lodash": "^4.17.20",
|
|
37
37
|
"luxon": "^2.4.0",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"vega-lite": "^5.2.0"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
|
-
"@malloydata/db-duckdb": "0.0.
|
|
46
|
+
"@malloydata/db-duckdb": "0.0.314",
|
|
47
47
|
"@storybook/addon-essentials": "^8.5.8",
|
|
48
48
|
"@storybook/addon-interactions": "^8.5.8",
|
|
49
49
|
"@storybook/addon-links": "^8.5.8",
|