@malloydata/render 0.0.314 → 0.0.315
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 +10 -12
- package/dist/module/index.umd.js +3 -3
- package/package.json +5 -5
package/dist/module/index.mjs
CHANGED
|
@@ -117264,7 +117264,7 @@ var zP = {}, DD = {}, wD = {};
|
|
|
117264
117264
|
if (e.TD.isTimestamp(a.e.typeDef)) {
|
|
117265
117265
|
const f = (0, r.qtz)(o);
|
|
117266
117266
|
if (f) {
|
|
117267
|
-
const d = `(${l}::TIMESTAMPTZ AT TIME ZONE '${f}')`;
|
|
117267
|
+
const d = `((${l})::TIMESTAMPTZ AT TIME ZONE '${f}')`;
|
|
117268
117268
|
let x = `DATE_TRUNC('${a.units}', ${d})`;
|
|
117269
117269
|
return u && (x = `(${x} - INTERVAL '1' DAY)`), `(${`${x} AT TIME ZONE '${f}'`})::TIMESTAMP`;
|
|
117270
117270
|
}
|
|
@@ -119940,19 +119940,17 @@ $$ LANGUAGE SQL;
|
|
|
119940
119940
|
sqlNowExpr() {
|
|
119941
119941
|
return "LOCALTIMESTAMP";
|
|
119942
119942
|
}
|
|
119943
|
-
// truncToUnit(sql, unit: string): string {
|
|
119944
|
-
// return `EXTRACT(${unit} FROM ${sql})`;
|
|
119945
|
-
// }
|
|
119946
119943
|
sqlTruncExpr(e, r) {
|
|
119947
|
-
|
|
119948
|
-
if (
|
|
119949
|
-
const
|
|
119950
|
-
if (
|
|
119951
|
-
const
|
|
119952
|
-
return `(${`CONVERT_TZ(${`${this.truncToUnit(
|
|
119944
|
+
const i = r.e.sql || "internal-error-in-sql-generation", s = r.units === "week";
|
|
119945
|
+
if (Yc.TD.isTimestamp(r.e.typeDef)) {
|
|
119946
|
+
const u = (0, Tg.qtz)(e);
|
|
119947
|
+
if (u) {
|
|
119948
|
+
const l = `(CONVERT_TZ(${i}, 'UTC','${u}'))`, c = s ? `DATE_SUB(${l}, INTERVAL DAYOFWEEK(${l}) - 1 DAY)` : l;
|
|
119949
|
+
return `(${`CONVERT_TZ(${`${this.truncToUnit(c, r.units)}`}, '${u}', 'UTC')`})`;
|
|
119953
119950
|
}
|
|
119954
119951
|
}
|
|
119955
|
-
|
|
119952
|
+
const o = s ? `DATE_SUB(${i}, INTERVAL DAYOFWEEK(${i}) - 1 DAY)` : i;
|
|
119953
|
+
return `${this.truncToUnit(o, r.units)}`;
|
|
119956
119954
|
}
|
|
119957
119955
|
truncToUnit(e, r) {
|
|
119958
119956
|
let i = "'%Y-%m-%d %H:%i:%s'";
|
|
@@ -154510,7 +154508,7 @@ function pyt(t) {
|
|
|
154510
154508
|
var $e = {}, IO = {};
|
|
154511
154509
|
Object.defineProperty(IO, "__esModule", { value: !0 });
|
|
154512
154510
|
IO.MALLOY_VERSION = void 0;
|
|
154513
|
-
IO.MALLOY_VERSION = "0.0.
|
|
154511
|
+
IO.MALLOY_VERSION = "0.0.315";
|
|
154514
154512
|
Object.defineProperty($e, "__esModule", { value: !0 });
|
|
154515
154513
|
$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
154514
|
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
|
@@ -765,7 +765,7 @@ AS (
|
|
|
765
765
|
${(0,m0e.indent)(r)}
|
|
766
766
|
);
|
|
767
767
|
`}sqlCreateFunctionCombineLastStage(e){return`SELECT ARRAY((SELECT AS STRUCT * FROM ${e}))
|
|
768
|
-
`}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return"`"+e+"`"}sqlNowExpr(){return"CURRENT_TIMESTAMP()"}sqlTruncExpr(e,r){const i=TT(e),s=i?`, "${i}"`:"";return sl.TD.isDate(r.e.typeDef)?$nt(r.units)?`DATE_TRUNC(${r.e.sql},${r.units})`:`TIMESTAMP(${r.e.sql}${s})`:`TIMESTAMP_TRUNC(${r.e.sql},${r.units}${s})`}sqlTimeExtractExpr(e,r){const i=Bnt[r.units]||r.units,s=sl.TD.isTimestamp(r.e.typeDef)&&TT(e),o=s?` AT TIME ZONE '${s}'`:"";return`EXTRACT(${i} FROM ${r.e.sql}${o})`}sqlAlterTimeExpr(e){const r=e.kids.base;let i=r==null?void 0:r.typeDef.type,s=r.sql;e.units!=="day"&&y0e(e.units)?i!=="timestamp"&&(s=`TIMESTAMP(${s})`,i="timestamp"):i==="timestamp"&&(s=`DATETIME(${s})`,i="datetime");const o=e.op==="+"?"_ADD":"_SUB",u=`${`${i.toUpperCase()}${o}`}(${s}, INTERVAL ${e.kids.delta.sql} ${e.units})`;return i===r.typeDef.type?u:`${r.typeDef.type.toUpperCase()}(${u})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,r){const{op:i,srcTypeDef:s,dstTypeDef:o,dstSQLType:a}=this.sqlCastPrep(r),u=TT(e),l=r.e.sql||"";return i==="timestamp::date"&&u?`DATE(${l},'${u}')`:i==="date::timestamp"&&u?`TIMESTAMP(${l}, '${u}')`:sl.TD.eq(s,o)?l:`${r.safe?"SAFE_CAST":"CAST"}(${l} AS ${a})`}sqlRegexpMatch(e){return`REGEXP_CONTAINS(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlLiteralTime(e,r){if(sl.TD.isDate(r.typeDef))return`DATE('${r.literal}')`;if(sl.TD.isTimestamp(r.typeDef)){let i=`'${r.literal}'`;const s=r.timezone||TT(e);return s&&s!=="UTC"&&(i+=`,'${s}'`),`TIMESTAMP(${i})`}else throw new Error(`Unsupported Literal time format ${r.typeDef}`)}sqlMeasureTimeExpr(e){const r={microsecond:{use:"microsecond",ratio:1},millisecond:{use:"microsecond",ratio:1e3},second:{use:"millisecond",ratio:1e3},minute:{use:"second",ratio:60},hour:{use:"minute",ratio:60},day:{use:"hour",ratio:24},week:{use:"day",ratio:7}},i=e.kids.left,s=e.kids.right;let o=i.sql,a=s.sql;if(r[e.units]){const{use:u,ratio:l}=r[e.units];if(!y0e(u))throw new Error(`Measure in '${u} not implemented`);if(!sl.TD.eq(i.typeDef,s.typeDef))throw new Error("Can't measure difference between different types");sl.TD.isDate(i.typeDef)&&(o=`TIMESTAMP(${o})`,a=`TIMESTAMP(${a})`);let c=`TIMESTAMP_DIFF(${a},${o},${u})`;return l!==1&&(c=`FLOOR(${c}/${l.toString()}.0)`),c}throw new Error(`Measure '${e.units} not implemented`)}sqlSampleTable(e,r){if(r!==void 0){if((0,sl.isSamplingEnable)(r)&&r.enable&&(r=this.defaultSampling),(0,sl.isSamplingRows)(r))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,sl.isSamplingPercent)(r))return`(SELECT * FROM ${e} TABLESAMPLE SYSTEM (${r.percent} PERCENT))`}return e}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getDialectFunctionOverrides(){return(0,g0e.expandOverrideMap)(Int.STANDARDSQL_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,g0e.expandBlueprintMap)(Lnt.STANDARDSQL_DIALECT_FUNCTIONS)}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"INT64":"FLOAT64":e.type}sqlTypeToMalloyType(e){var r,i,s;const o=(i=(r=e.match(/^(\w+)/))===null||r===void 0?void 0:r.at(0))!==null&&i!==void 0?i:e;return(s=knt[o.toUpperCase()])!==null&&s!==void 0?s:{type:"sql native",rawType:e.toLowerCase()}}castToString(e){return`CAST(${e} as STRING)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}sqlLiteralRecord(e){const r=[];for(const[i,s]of Object.entries(e.kids)){const o=s.sql||"internal-error-literal-record";r.push(`${o} AS ${this.sqlMaybeQuoteIdentifier(i)}`)}return`STRUCT(${r.join(",")})`}sqlLiteralArray(e){return"["+e.kids.values.map(i=>i.sql).join(",")+"]"}}ET.StandardSQLDialect=Mnt,function(t){var e=R&&R.__createBinding||(Object.create?function(i,s,o,a){a===void 0&&(a=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,a,u)}:function(i,s,o,a){a===void 0&&(a=o),i[a]=s[o]}),r=R&&R.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(ET,t)}(Qk);var Zk={},RT={},DT={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.PostgresBase=t.timeExtractMap=void 0;const e=Ye,r=xf;t.timeExtractMap={day_of_week:"dow",day_of_year:"doy"};class i extends r.Dialect{sqlTruncExpr(o,a){const u=a.units==="week",l=u?`${a.e.sql} + INTERVAL '1' DAY`:a.e.sql;if(e.TD.isTimestamp(a.e.typeDef)){const f=(0,r.qtz)(o);if(f){const d=`(${l}::TIMESTAMPTZ AT TIME ZONE '${f}')`;let x=`DATE_TRUNC('${a.units}', ${d})`;return u&&(x=`(${x} - INTERVAL '1' DAY)`),`(${`${x} AT TIME ZONE '${f}'`})::TIMESTAMP`}}let c=`DATE_TRUNC('${a.units}', ${l})`;return u&&(c=`(${c} - INTERVAL '1' DAY)`),c}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTimeExtractExpr(o,a){const u=t.timeExtractMap[a.units]||a.units;let l=a.e.sql;if(e.TD.isTimestamp(a.e.typeDef)){const f=(0,r.qtz)(o);f&&(l=`(${l}::TIMESTAMPTZ AT TIME ZONE '${f}')`)}const c=`EXTRACT(${u} FROM ${l})`;return a.units==="day_of_week"?`(${c}+1)`:c}sqlCast(o,a){const u=a.e.sql||"",{op:l,srcTypeDef:c,dstTypeDef:f,dstSQLType:d}=this.sqlCastPrep(a),x=(0,r.qtz)(o);return l==="timestamp::date"&&x?`CAST((${`${u}::TIMESTAMPTZ`}) AT TIME ZONE '${x}' AS DATE)`:l==="date::timestamp"&&x?`CAST((${u})::TIMESTAMP AT TIME ZONE '${x}' AS TIMESTAMP)`:e.TD.eq(c,f)?u:`${a.safe?"TRY_CAST":"CAST"}(${u} AS ${d})`}sqlRegexpMatch(o){return`${o.kids.expr.sql} ~ ${o.kids.regex.sql}`}sqlLiteralTime(o,a){if(e.TD.isDate(a.typeDef))return`DATE '${a.literal}'`;const u=a.timezone||(0,r.qtz)(o);return u?`TIMESTAMPTZ '${a.literal} ${u}'::TIMESTAMP`:`TIMESTAMP '${a.literal}'`}sqlLiteralRecord(o){throw new Error("Cannot create a record literal for postgres base dialect")}sqlLiteralArray(o){return"ARRAY["+o.kids.values.map(u=>u.sql).join(",")+"]"}sqlMaybeQuoteIdentifier(o){return'"'+o.replace(/"/g,'""')+'"'}}t.PostgresBase=i})(DT);var wT={};Object.defineProperty(wT,"__esModule",{value:!0}),wT.POSTGRES_DIALECT_FUNCTIONS=void 0;const E0e=Wt,eM={default_separator:{takes:{value:{dimension:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"STRING_AGG(${value}, ','${order_by:})"}},with_separator:{takes:{value:{dimension:"string"},separator:{literal:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"STRING_AGG(${value}, ${separator}${order_by:})"}}},Pnt={default_separator:{...eM.default_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"STRING_AGG(DISTINCT ${value}, ','${order_by:})",defaultOrderByArgIndex:0}},with_separator:{...eM.with_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"STRING_AGG(DISTINCT ${value}, ${separator}${order_by:})",defaultOrderByArgIndex:0}}};wT.POSTGRES_DIALECT_FUNCTIONS={string_agg:eM,string_agg_distinct:Pnt,...(0,E0e.def)("repeat",{str:"string",n:"number"},"string"),...(0,E0e.def)("reverse",{str:"string"},"string")};var OT={};Object.defineProperty(OT,"__esModule",{value:!0}),OT.POSTGRES_MALLOY_STANDARD_OVERLOADS=void 0;function v0e(t){return"CASE WHEN NUM_NULLS(${...values}) > 0 THEN NULL ELSE "+t+"(${...values}) END"}OT.POSTGRES_MALLOY_STANDARD_OVERLOADS={byte_length:{function:"OCTET_LENGTH"},ends_with:{sql:"COALESCE(RIGHT(${value}, LENGTH(${suffix})) = ${suffix}, false)"},greatest:{sql:v0e("GREATEST")},least:{sql:v0e("LEAST")},ifnull:{sql:"COALESCE(${value}, ${default})"},is_inf:{sql:"COALESCE(${value} = DOUBLE PRECISION 'Infinity' OR ${value} = DOUBLE PRECISION '-Infinity', false)"},is_nan:{sql:"COALESCE(${value} = NUMERIC 'NaN', false)"},log:{sql:"LOG(${base}, ${value})"},rand:{function:"RANDOM"},regexp_extract:{function:"SUBSTRING"},replace:{regular_expression:{sql:"REGEXP_REPLACE(${value}, ${pattern}, ${replacement}, 'g')"}},round:{to_integer:{sql:"ROUND((${value})::NUMERIC)"},to_precision:{sql:"ROUND((${value})::NUMERIC, ${precision})"}},stddev:{sql:"STDDEV(${value}::DOUBLE PRECISION)"},substr:{position_only:{sql:"SUBSTR(${value}, CASE WHEN ${position} < 0 THEN LENGTH(${value}) + ${position} + 1 ELSE ${position} END)"},with_length:{sql:"SUBSTR(${value}, CASE WHEN ${position} < 0 THEN LENGTH(${value}) + ${position} + 1 ELSE ${position} END, ${length})"}},trunc:{to_integer:{sql:"TRUNC(${value}::NUMERIC)"},to_precision:{sql:"TRUNC((${value}::NUMERIC), ${precision})"}},unicode:{function:"ASCII"}},Object.defineProperty(RT,"__esModule",{value:!0}),RT.PostgresDialect=void 0;const Unt=wt,FT=Ye,_0e=mf,jnt=xf,A0e=DT,qnt=wT,znt=OT,Hnt={year:"years",month:"months",week:"weeks",day:"days",hour:"hours",minute:"mins",second:"secs"},S0e={second:1,minute:60,hour:3600,day:24*3600,week:7*24*3600},Qnt={"character varying":{type:"string"},name:{type:"string"},text:{type:"string"},date:{type:"date"},integer:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},"double precision":{type:"number",numberType:"float"},"timestamp without time zone":{type:"timestamp"},oid:{type:"string"},boolean:{type:"boolean"},timestamp:{type:"timestamp"},'"char"':{type:"string"},character:{type:"string"},smallint:{type:"number",numberType:"integer"},xid:{type:"string"},real:{type:"number",numberType:"float"},interval:{type:"string"},inet:{type:"string"},regtype:{type:"string"},numeric:{type:"number",numberType:"float"},bytea:{type:"string"},pg_ndistinct:{type:"number",numberType:"integer"},varchar:{type:"string"}};class Gnt extends A0e.PostgresBase{constructor(){super(...arguments),this.name="postgres",this.defaultNumberType="DOUBLE PRECISION",this.defaultDecimalType="NUMERIC",this.udfPrefix="pg_temp.__udf",this.hasFinalStage=!0,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!0,this.unnestWithNumbers=!1,this.defaultSampling={rows:5e4},this.supportUnnestArrayAgg=!0,this.supportsAggDistinct=!0,this.supportsCTEinCoorelatedSubQueries=!0,this.supportsSafeCast=!1,this.dontUnionIndex=!1,this.supportsQualify=!1,this.supportsNesting=!0,this.experimental=!1,this.readsNestedData=!1,this.supportsComplexFilteredSources=!1,this.compoundObjectInSchema=!1,this.likeEscape=!1}quoteTablePath(e){return e.split(".").map(r=>`"${r}"`).join(".")}sqlGroupSetTable(e){return`CROSS JOIN GENERATE_SERIES(0,${e},1) as group_set`}sqlAnyValue(e,r){return`MAX(${r})`}mapFields(e){return e.map(r=>`
|
|
768
|
+
`}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return"`"+e+"`"}sqlNowExpr(){return"CURRENT_TIMESTAMP()"}sqlTruncExpr(e,r){const i=TT(e),s=i?`, "${i}"`:"";return sl.TD.isDate(r.e.typeDef)?$nt(r.units)?`DATE_TRUNC(${r.e.sql},${r.units})`:`TIMESTAMP(${r.e.sql}${s})`:`TIMESTAMP_TRUNC(${r.e.sql},${r.units}${s})`}sqlTimeExtractExpr(e,r){const i=Bnt[r.units]||r.units,s=sl.TD.isTimestamp(r.e.typeDef)&&TT(e),o=s?` AT TIME ZONE '${s}'`:"";return`EXTRACT(${i} FROM ${r.e.sql}${o})`}sqlAlterTimeExpr(e){const r=e.kids.base;let i=r==null?void 0:r.typeDef.type,s=r.sql;e.units!=="day"&&y0e(e.units)?i!=="timestamp"&&(s=`TIMESTAMP(${s})`,i="timestamp"):i==="timestamp"&&(s=`DATETIME(${s})`,i="datetime");const o=e.op==="+"?"_ADD":"_SUB",u=`${`${i.toUpperCase()}${o}`}(${s}, INTERVAL ${e.kids.delta.sql} ${e.units})`;return i===r.typeDef.type?u:`${r.typeDef.type.toUpperCase()}(${u})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,r){const{op:i,srcTypeDef:s,dstTypeDef:o,dstSQLType:a}=this.sqlCastPrep(r),u=TT(e),l=r.e.sql||"";return i==="timestamp::date"&&u?`DATE(${l},'${u}')`:i==="date::timestamp"&&u?`TIMESTAMP(${l}, '${u}')`:sl.TD.eq(s,o)?l:`${r.safe?"SAFE_CAST":"CAST"}(${l} AS ${a})`}sqlRegexpMatch(e){return`REGEXP_CONTAINS(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlLiteralTime(e,r){if(sl.TD.isDate(r.typeDef))return`DATE('${r.literal}')`;if(sl.TD.isTimestamp(r.typeDef)){let i=`'${r.literal}'`;const s=r.timezone||TT(e);return s&&s!=="UTC"&&(i+=`,'${s}'`),`TIMESTAMP(${i})`}else throw new Error(`Unsupported Literal time format ${r.typeDef}`)}sqlMeasureTimeExpr(e){const r={microsecond:{use:"microsecond",ratio:1},millisecond:{use:"microsecond",ratio:1e3},second:{use:"millisecond",ratio:1e3},minute:{use:"second",ratio:60},hour:{use:"minute",ratio:60},day:{use:"hour",ratio:24},week:{use:"day",ratio:7}},i=e.kids.left,s=e.kids.right;let o=i.sql,a=s.sql;if(r[e.units]){const{use:u,ratio:l}=r[e.units];if(!y0e(u))throw new Error(`Measure in '${u} not implemented`);if(!sl.TD.eq(i.typeDef,s.typeDef))throw new Error("Can't measure difference between different types");sl.TD.isDate(i.typeDef)&&(o=`TIMESTAMP(${o})`,a=`TIMESTAMP(${a})`);let c=`TIMESTAMP_DIFF(${a},${o},${u})`;return l!==1&&(c=`FLOOR(${c}/${l.toString()}.0)`),c}throw new Error(`Measure '${e.units} not implemented`)}sqlSampleTable(e,r){if(r!==void 0){if((0,sl.isSamplingEnable)(r)&&r.enable&&(r=this.defaultSampling),(0,sl.isSamplingRows)(r))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,sl.isSamplingPercent)(r))return`(SELECT * FROM ${e} TABLESAMPLE SYSTEM (${r.percent} PERCENT))`}return e}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getDialectFunctionOverrides(){return(0,g0e.expandOverrideMap)(Int.STANDARDSQL_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,g0e.expandBlueprintMap)(Lnt.STANDARDSQL_DIALECT_FUNCTIONS)}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"INT64":"FLOAT64":e.type}sqlTypeToMalloyType(e){var r,i,s;const o=(i=(r=e.match(/^(\w+)/))===null||r===void 0?void 0:r.at(0))!==null&&i!==void 0?i:e;return(s=knt[o.toUpperCase()])!==null&&s!==void 0?s:{type:"sql native",rawType:e.toLowerCase()}}castToString(e){return`CAST(${e} as STRING)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}sqlLiteralRecord(e){const r=[];for(const[i,s]of Object.entries(e.kids)){const o=s.sql||"internal-error-literal-record";r.push(`${o} AS ${this.sqlMaybeQuoteIdentifier(i)}`)}return`STRUCT(${r.join(",")})`}sqlLiteralArray(e){return"["+e.kids.values.map(i=>i.sql).join(",")+"]"}}ET.StandardSQLDialect=Mnt,function(t){var e=R&&R.__createBinding||(Object.create?function(i,s,o,a){a===void 0&&(a=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,a,u)}:function(i,s,o,a){a===void 0&&(a=o),i[a]=s[o]}),r=R&&R.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(ET,t)}(Qk);var Zk={},RT={},DT={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.PostgresBase=t.timeExtractMap=void 0;const e=Ye,r=xf;t.timeExtractMap={day_of_week:"dow",day_of_year:"doy"};class i extends r.Dialect{sqlTruncExpr(o,a){const u=a.units==="week",l=u?`${a.e.sql} + INTERVAL '1' DAY`:a.e.sql;if(e.TD.isTimestamp(a.e.typeDef)){const f=(0,r.qtz)(o);if(f){const d=`((${l})::TIMESTAMPTZ AT TIME ZONE '${f}')`;let x=`DATE_TRUNC('${a.units}', ${d})`;return u&&(x=`(${x} - INTERVAL '1' DAY)`),`(${`${x} AT TIME ZONE '${f}'`})::TIMESTAMP`}}let c=`DATE_TRUNC('${a.units}', ${l})`;return u&&(c=`(${c} - INTERVAL '1' DAY)`),c}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTimeExtractExpr(o,a){const u=t.timeExtractMap[a.units]||a.units;let l=a.e.sql;if(e.TD.isTimestamp(a.e.typeDef)){const f=(0,r.qtz)(o);f&&(l=`(${l}::TIMESTAMPTZ AT TIME ZONE '${f}')`)}const c=`EXTRACT(${u} FROM ${l})`;return a.units==="day_of_week"?`(${c}+1)`:c}sqlCast(o,a){const u=a.e.sql||"",{op:l,srcTypeDef:c,dstTypeDef:f,dstSQLType:d}=this.sqlCastPrep(a),x=(0,r.qtz)(o);return l==="timestamp::date"&&x?`CAST((${`${u}::TIMESTAMPTZ`}) AT TIME ZONE '${x}' AS DATE)`:l==="date::timestamp"&&x?`CAST((${u})::TIMESTAMP AT TIME ZONE '${x}' AS TIMESTAMP)`:e.TD.eq(c,f)?u:`${a.safe?"TRY_CAST":"CAST"}(${u} AS ${d})`}sqlRegexpMatch(o){return`${o.kids.expr.sql} ~ ${o.kids.regex.sql}`}sqlLiteralTime(o,a){if(e.TD.isDate(a.typeDef))return`DATE '${a.literal}'`;const u=a.timezone||(0,r.qtz)(o);return u?`TIMESTAMPTZ '${a.literal} ${u}'::TIMESTAMP`:`TIMESTAMP '${a.literal}'`}sqlLiteralRecord(o){throw new Error("Cannot create a record literal for postgres base dialect")}sqlLiteralArray(o){return"ARRAY["+o.kids.values.map(u=>u.sql).join(",")+"]"}sqlMaybeQuoteIdentifier(o){return'"'+o.replace(/"/g,'""')+'"'}}t.PostgresBase=i})(DT);var wT={};Object.defineProperty(wT,"__esModule",{value:!0}),wT.POSTGRES_DIALECT_FUNCTIONS=void 0;const E0e=Wt,eM={default_separator:{takes:{value:{dimension:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"STRING_AGG(${value}, ','${order_by:})"}},with_separator:{takes:{value:{dimension:"string"},separator:{literal:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"STRING_AGG(${value}, ${separator}${order_by:})"}}},Pnt={default_separator:{...eM.default_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"STRING_AGG(DISTINCT ${value}, ','${order_by:})",defaultOrderByArgIndex:0}},with_separator:{...eM.with_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"STRING_AGG(DISTINCT ${value}, ${separator}${order_by:})",defaultOrderByArgIndex:0}}};wT.POSTGRES_DIALECT_FUNCTIONS={string_agg:eM,string_agg_distinct:Pnt,...(0,E0e.def)("repeat",{str:"string",n:"number"},"string"),...(0,E0e.def)("reverse",{str:"string"},"string")};var OT={};Object.defineProperty(OT,"__esModule",{value:!0}),OT.POSTGRES_MALLOY_STANDARD_OVERLOADS=void 0;function v0e(t){return"CASE WHEN NUM_NULLS(${...values}) > 0 THEN NULL ELSE "+t+"(${...values}) END"}OT.POSTGRES_MALLOY_STANDARD_OVERLOADS={byte_length:{function:"OCTET_LENGTH"},ends_with:{sql:"COALESCE(RIGHT(${value}, LENGTH(${suffix})) = ${suffix}, false)"},greatest:{sql:v0e("GREATEST")},least:{sql:v0e("LEAST")},ifnull:{sql:"COALESCE(${value}, ${default})"},is_inf:{sql:"COALESCE(${value} = DOUBLE PRECISION 'Infinity' OR ${value} = DOUBLE PRECISION '-Infinity', false)"},is_nan:{sql:"COALESCE(${value} = NUMERIC 'NaN', false)"},log:{sql:"LOG(${base}, ${value})"},rand:{function:"RANDOM"},regexp_extract:{function:"SUBSTRING"},replace:{regular_expression:{sql:"REGEXP_REPLACE(${value}, ${pattern}, ${replacement}, 'g')"}},round:{to_integer:{sql:"ROUND((${value})::NUMERIC)"},to_precision:{sql:"ROUND((${value})::NUMERIC, ${precision})"}},stddev:{sql:"STDDEV(${value}::DOUBLE PRECISION)"},substr:{position_only:{sql:"SUBSTR(${value}, CASE WHEN ${position} < 0 THEN LENGTH(${value}) + ${position} + 1 ELSE ${position} END)"},with_length:{sql:"SUBSTR(${value}, CASE WHEN ${position} < 0 THEN LENGTH(${value}) + ${position} + 1 ELSE ${position} END, ${length})"}},trunc:{to_integer:{sql:"TRUNC(${value}::NUMERIC)"},to_precision:{sql:"TRUNC((${value}::NUMERIC), ${precision})"}},unicode:{function:"ASCII"}},Object.defineProperty(RT,"__esModule",{value:!0}),RT.PostgresDialect=void 0;const Unt=wt,FT=Ye,_0e=mf,jnt=xf,A0e=DT,qnt=wT,znt=OT,Hnt={year:"years",month:"months",week:"weeks",day:"days",hour:"hours",minute:"mins",second:"secs"},S0e={second:1,minute:60,hour:3600,day:24*3600,week:7*24*3600},Qnt={"character varying":{type:"string"},name:{type:"string"},text:{type:"string"},date:{type:"date"},integer:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},"double precision":{type:"number",numberType:"float"},"timestamp without time zone":{type:"timestamp"},oid:{type:"string"},boolean:{type:"boolean"},timestamp:{type:"timestamp"},'"char"':{type:"string"},character:{type:"string"},smallint:{type:"number",numberType:"integer"},xid:{type:"string"},real:{type:"number",numberType:"float"},interval:{type:"string"},inet:{type:"string"},regtype:{type:"string"},numeric:{type:"number",numberType:"float"},bytea:{type:"string"},pg_ndistinct:{type:"number",numberType:"integer"},varchar:{type:"string"}};class Gnt extends A0e.PostgresBase{constructor(){super(...arguments),this.name="postgres",this.defaultNumberType="DOUBLE PRECISION",this.defaultDecimalType="NUMERIC",this.udfPrefix="pg_temp.__udf",this.hasFinalStage=!0,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!0,this.unnestWithNumbers=!1,this.defaultSampling={rows:5e4},this.supportUnnestArrayAgg=!0,this.supportsAggDistinct=!0,this.supportsCTEinCoorelatedSubQueries=!0,this.supportsSafeCast=!1,this.dontUnionIndex=!1,this.supportsQualify=!1,this.supportsNesting=!0,this.experimental=!1,this.readsNestedData=!1,this.supportsComplexFilteredSources=!1,this.compoundObjectInSchema=!1,this.likeEscape=!1}quoteTablePath(e){return e.split(".").map(r=>`"${r}"`).join(".")}sqlGroupSetTable(e){return`CROSS JOIN GENERATE_SERIES(0,${e},1) as group_set`}sqlAnyValue(e,r){return`MAX(${r})`}mapFields(e){return e.map(r=>`
|
|
769
769
|
${r.sqlExpression}${r.typeDef.type==="number"?`::${this.defaultNumberType}`:""} as ${r.sqlOutputName}`).join(", ")}sqlAggregateTurtle(e,r,i){return`COALESCE(TO_JSONB((ARRAY_AGG((SELECT TO_JSONB(__x) FROM (SELECT ${this.mapFields(r)}
|
|
770
770
|
) as __x) ${i} ) FILTER (WHERE group_set=${e}))),'[]'::JSONB)`}sqlAnyValueTurtle(e,r){const i=r.map(s=>`${s.sqlExpression} as ${s.sqlOutputName}`).join(", ");return`ANY_VALUE(CASE WHEN group_set=${e} THEN STRUCT(${i}))`}sqlAnyValueLastTurtle(e,r,i){return`(ARRAY_AGG(${e}) FILTER (WHERE group_set=${r} AND ${e} IS NOT NULL))[1] as ${i}`}sqlCoaleseMeasuresInline(e,r){return`TO_JSONB((ARRAY_AGG((SELECT __x FROM (SELECT ${this.mapFields(r)}) as __x)) FILTER (WHERE group_set=${e}))[1])`}sqlUnnestAlias(e,r,i,s,o,a){return o?s?`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('__row_id', row_number() over (), 'value', v) FROM JSONB_ARRAY_ELEMENTS(TO_JSONB(${e})) as v))) as ${r} ON true`:`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('value', v) FROM JSONB_ARRAY_ELEMENTS(TO_JSONB(${e})) as v))) as ${r} ON true`:s?`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('__row_number', row_number() over())|| __xx::jsonb as b FROM JSONB_ARRAY_ELEMENTS(${e}) __xx ))) as ${r} ON true`:`LEFT JOIN JSONB_ARRAY_ELEMENTS(${e}) as ${r} ON true`}sqlSumDistinctHashedKey(e){return`('x' || MD5(${e}::varchar))::bit(64)::bigint::DECIMAL(65,0) *18446744073709551616 + ('x' || SUBSTR(MD5(${e}::varchar),17))::bit(64)::bigint::DECIMAL(65,0)`}sqlGenerateUUID(){return"GEN_RANDOM_UUID()"}sqlFieldReference(e,r,i,s){if(i==="__row_id")return`(${e}->>'__row_id')`;if(r!=="table"){let o=`JSONB_EXTRACT_PATH_TEXT(${e},'${i}')`;switch(s){case"string":break;case"number":o=`${o}::double precision`;break;case"struct":case"array":case"record":case"array[record]":case"sql native":o=`JSONB_EXTRACT_PATH(${e},'${i}')`;break}return o}else{const o=this.sqlMaybeQuoteIdentifier(i);return`${e}.${o}`}}sqlUnnestPipelineHead(e,r){return e?`UNNEST(ARRAY((SELECT ${r})))`:`JSONB_ARRAY_ELEMENTS(${r})`}sqlCreateFunction(e,r){return`CREATE FUNCTION ${e}(JSONB) RETURNS JSONB AS $$
|
|
771
771
|
${(0,Unt.indent)(r)}
|
|
@@ -948,7 +948,7 @@ CROSS JOIN UNNEST(ARRAY[CASE WHEN ${e} IS NOT NULL THEN __row_id_almost_${r} END
|
|
|
948
948
|
${(0,_rt.indent)(r)}
|
|
949
949
|
$$ LANGUAGE SQL;
|
|
950
950
|
`}sqlCreateFunctionCombineLastStage(e){return`SELECT ARRAY((SELECT AS STRUCT * FROM ${e}))
|
|
951
|
-
`}sqlSelectAliasAsStruct(e,r){return"MYSQL: Implement this"}sqlMaybeQuoteIdentifier(e){return"`"+e.replace(/`/g,"``")+"`"}sqlCreateTableAsSelect(e,r){throw new Error("Not implemented Yet")}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTruncExpr(e,r){
|
|
951
|
+
`}sqlSelectAliasAsStruct(e,r){return"MYSQL: Implement this"}sqlMaybeQuoteIdentifier(e){return"`"+e.replace(/`/g,"``")+"`"}sqlCreateTableAsSelect(e,r){throw new Error("Not implemented Yet")}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTruncExpr(e,r){const i=r.e.sql||"internal-error-in-sql-generation",s=r.units==="week";if(yf.TD.isTimestamp(r.e.typeDef)){const u=(0,GE.qtz)(e);if(u){const l=`(CONVERT_TZ(${i}, 'UTC','${u}'))`,c=s?`DATE_SUB(${l}, INTERVAL DAYOFWEEK(${l}) - 1 DAY)`:l;return`(${`CONVERT_TZ(${`${this.truncToUnit(c,r.units)}`}, '${u}', 'UTC')`})`}}const o=s?`DATE_SUB(${i}, INTERVAL DAYOFWEEK(${i}) - 1 DAY)`:i;return`${this.truncToUnit(o,r.units)}`}truncToUnit(e,r){let i="'%Y-%m-%d %H:%i:%s'";switch(r){case"minute":i="'%Y-%m-%d %H:%i:00'";break;case"hour":i="'%Y-%m-%d %H:00:00'";break;case"day":case"week":i="'%Y-%m-%d 00:00:00'";break;case"month":i="'%Y-%m-01 00:00:00'";break;case"quarter":i=`CASE WHEN MONTH(${e}) > 9 THEN '%Y-10-01 00:00:00' WHEN MONTH(${e}) > 6 THEN '%Y-07-01 00:00:00' WHEN MONTH(${e}) > 3 THEN '%Y-04-01 00:00:00' ELSE '%Y-01-01 00:00:00' end`;break;case"year":i="'%Y-01-01 00:00:00'";break}return`TIMESTAMP(DATE_FORMAT(${e}, ${i}))`}sqlTimeExtractExpr(e,r){const i=brt[r.units]||r.units;let s=r.e.sql;if(yf.TD.isTimestamp(r.e.typeDef)){const o=(0,GE.qtz)(e);o&&(s=`CONVERT_TZ(${s}, 'UTC', '${o}')`)}return`${i}(${s})`}sqlAlterTimeExpr(e){let r=e.units,i=e.kids.delta.sql;r==="quarter"?(r="month",i=`${i}*3`):r==="week"&&(r="day",i=`${i}*7`);const s=`INTERVAL ${i} ${r} `;return`(${e.kids.base.sql})${e.op}${s}`}sqlCast(e,r){const i=r.e.sql||"internal-error-in-sql-generation",{op:s,srcTypeDef:o,dstTypeDef:a,dstSQLType:u}=this.sqlCastPrep(r),l=(0,GE.qtz)(e);if(s==="timestamp::date"&&l)return`CAST(CONVERT_TZ(${i}, 'UTC', '${l}') AS DATE) `;if(s==="date::timestamp"&&l)return` CONVERT_TZ(${i}, '${l}', 'UTC')`;if(!yf.TD.eq(o,a)){if(r.safe)throw new Error("Mysql dialect doesn't support Safe Cast");return yf.TD.isString(a)?`CONCAT(${i}, '')`:`CAST(${i} AS ${u})`}return i}sqlRegexpMatch(e){return`REGEXP_LIKE(${e.kids.expr.sql}, ${e.kids.regex.sql})`}sqlLiteralTime(e,r){if(yf.TD.isDate(r.typeDef))return`DATE '${r.literal}'`;const i=r.timezone||(0,GE.qtz)(e);return i?` CONVERT_TZ('${r.literal}', '${i}', 'UTC')`:`TIMESTAMP '${r.literal}'`}sqlMeasureTimeExpr(e){let r=e.kids.left.sql,i=e.kids.right.sql;if(k0e[e.units]){r=`UNIX_TIMESTAMP(${r})`,i=`UNIX_TIMESTAMP(${i})`;const s=`${i}-${r}`;return e.units==="second"?`FLOOR(${s})`:`FLOOR((${s})/${k0e[e.units].toString()}.0)`}throw new Error(`Unknown or unhandled MySQL time unit: ${e.units}`)}sqlAggDistinct(e,r,i){throw new Error("MySQL dialect does not support nesting.")}sqlSampleTable(e,r){if(r!==void 0){if((0,yf.isSamplingEnable)(r)&&r.enable&&(r=this.defaultSampling),(0,yf.isSamplingRows)(r))return`(SELECT * FROM ${e} ORDER BY rand() LIMIT ${r.rows} )`;if((0,yf.isSamplingPercent)(r))return`(SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY rand()) as __row_number, __source_tbl.* from ${e} as __source_tbl) as __rand_tbl where __row_number % FLOOR(100.0 / ${r.percent}) = 1)`}return e}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/'/g,"''")+"'"}getDialectFunctionOverrides(){return(0,B0e.expandOverrideMap)(Srt.MYSQL_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,B0e.expandBlueprintMap)(Art.MYSQL_DIALECT_FUNCTIONS)}mapFieldsForJsonObject(e,r){return e.map(i=>`${i.sqlOutputName.replace(/`/g,"'")}, ${r?"NULL":i.sqlExpression}
|
|
952
952
|
`).join(", ")}castToString(e){return`CONCAT(${e}, '')`}concat(...e){return`CONCAT(${e.join(",")})`}validateTypeName(e){return e.match(/^[A-Za-z\s(),0-9]*$/)!==null}sqlLiteralArray(e){return`JSON_ARRAY(${e.kids.values.map(i=>i.sql).join(",")})`}sqlLiteralRecord(e){return`JSON_OBJECT(${Object.entries(e.kids).map(([i,s])=>`${this.sqlLiteralString(i)},${s.sql}`).join(", ")})`}}jT.MySQLDialect=Rrt,function(t){var e=R&&R.__createBinding||(Object.create?function(i,s,o,a){a===void 0&&(a=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,a,u)}:function(i,s,o,a){a===void 0&&(a=o),i[a]=s[o]}),r=R&&R.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(jT,t)}(lM);var Vx={};Object.defineProperty(Vx,"__esModule",{value:!0}),Vx.getDialect=Lrt,Vx.registerDialect=Ef,Vx.getDialects=Irt;const Drt=tM,wrt=Zk,Ort=iM,Frt=Qk,M0e=oM,Nrt=lM,fM=new Map;function Lrt(t){const e=fM.get(t);if(e===void 0)throw new Error(`Unknown Dialect ${t}`);return e}function Ef(t){fM.set(t.name,t)}function Irt(){return[...fM.values()]}Ef(new wrt.PostgresDialect),Ef(new Frt.StandardSQLDialect),Ef(new Drt.DuckDBDialect),Ef(new Ort.SnowflakeDialect),Ef(new M0e.TrinoDialect),Ef(new M0e.PrestoDialect),Ef(new Nrt.MySQLDialect),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TinyParser=t.getMalloyStandardFunctions=t.registerDialect=t.getDialect=t.MySQLDialect=t.TrinoDialect=t.SnowflakeDialect=t.DuckDBDialect=t.PostgresDialect=t.StandardSQLDialect=t.qtz=t.Dialect=t.sql=t.literal=t.variadicParam=t.param=t.spread=t.maxScalar=t.minAggregate=t.minScalar=t.overload=t.makeParam=t.anyExprType=t.arg=void 0;var e=Wt;Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return e.arg}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return e.anyExprType}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return e.makeParam}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return e.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return e.minScalar}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return e.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return e.maxScalar}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return e.spread}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return e.param}}),Object.defineProperty(t,"variadicParam",{enumerable:!0,get:function(){return e.variadicParam}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return e.literal}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return e.sql}});var r=xf;Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return r.Dialect}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return r.qtz}});var i=Qk;Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return i.StandardSQLDialect}});var s=Zk;Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return s.PostgresDialect}});var o=tM;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return o.DuckDBDialect}});var a=iM;Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return a.SnowflakeDialect}});var u=oM;Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return u.TrinoDialect}});var l=lM;Object.defineProperty(t,"MySQLDialect",{enumerable:!0,get:function(){return l.MySQLDialect}});var c=Vx;Object.defineProperty(t,"getDialect",{enumerable:!0,get:function(){return c.getDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return c.registerDialect}});var f=mf;Object.defineProperty(t,"getMalloyStandardFunctions",{enumerable:!0,get:function(){return f.getMalloyStandardFunctions}});var d=Wx;Object.defineProperty(t,"TinyParser",{enumerable:!0,get:function(){return d.TinyParser}})}(Gx);var Ri={},Rt={},Ns={};Object.defineProperty(Ns,"__esModule",{value:!0}),Ns.addModelScope=$rt,Ns.annotationToTaglines=U0e,Ns.annotationToTag=j0e;const P0e=rs;function $rt(t,e){const r=t?{...t}:{};return r.scopes?r.scopes=r.scopes.concat(e):r.scopes=[e],r}function U0e(t,e){t||(t={});const r=t.inherits?U0e(t.inherits,e):[];function i(s){const o=[];for(const a of s||[])(e===void 0||a.text.match(e))&&o.push(a.text);return o}return r.concat(i(t.blockNotes),i(t.notes))}function j0e(t,e={}){var r;let i=e.extending||new P0e.Tag;const s=e.prefix||/^##? /;t||(t={});const o=[];if(t.inherits){const l=j0e(t.inherits,e);o.push(...l.log),i=l.tag}const a=[];t.blockNotes&&a.push(...t.blockNotes),t.notes&&a.push(...t.notes);const u=[];for(const l of a)l.text.match(s)&&u.push(l);for(let l=0;l<u.length;l++){const c=u[l];if(c.text.match(s)){const f=P0e.Tag.fromTagLine(c.text,l,i,...(r=e.scopes)!==null&&r!==void 0?r:[]);i=f.tag,o.push(...f.log.map(d=>Brt(d,c)))}}return{tag:i,log:o}}function Brt(t,e){const r={line:e.at.range.start.line,character:e.at.range.start.character+t.offset};return{code:"tag-parse-error",severity:"error",message:t.message,at:{url:e.at.url,range:{start:r,end:r}}}}Object.defineProperty(Rt,"__esModule",{value:!0}),Rt.QueryStruct=Rt.QueryFieldUnsupported=Rt.QueryFieldTimestamp=Rt.QueryFieldStruct=Rt.QueryFieldString=Rt.QueryFieldNumber=Rt.QueryFieldJSON=Rt.QueryFieldDistinctKey=Rt.QueryFieldDate=Rt.QueryFieldBoolean=Rt.QueryAtomicField=Rt.QueryField=void 0,Rt.isAggregateField=K0e,Rt.isCalculatedField=X0e,Rt.isScalarField=J0e,Rt.isBasicAggregate=qrt,Rt.isBasicCalculation=zrt,Rt.isBasicScalar=Z0e;const krt=H2,Dn=Ye,Mrt=Ns,Prt=Gx,Urt=wt;class jrt{constructor(e){this.referenceId=e??(0,krt.v4)()}getChildByName(e){}}let dM=class extends jrt{constructor(e,r,i){super(i),this.fieldDef=e,this.parent=r,this.fieldDef=e}getIdentifier(){return(0,Dn.getIdentifier)(this.fieldDef)}getJoinableParent(){const e=this.parent;return e.structDef.type==="record"?e.getJoinableParent():e}isAtomic(){return(0,Dn.isAtomic)(this.fieldDef)}getFullOutputName(){return this.parent.getFullOutputName()+this.getIdentifier()}isNestedInParent(e){switch(e.type){case"record":case"array":return!0;default:return!1}}isArrayElement(e){return e.type==="array"&&e.elementTypeDef.type!=="record_element"}includeInWildcard(){return!1}};Rt.QueryField=dM;class zo extends dM{constructor(e,r,i){super(e,r,i),this.fieldDef=e}includeInWildcard(){return this.fieldDef.name!=="__distinct_key"}getFilterList(){return[]}}Rt.QueryAtomicField=zo;class q0e extends zo{}Rt.QueryFieldBoolean=q0e;class z0e extends zo{}Rt.QueryFieldDate=z0e;class H0e extends zo{}Rt.QueryFieldDistinctKey=H0e;class Q0e extends zo{}Rt.QueryFieldJSON=Q0e;class G0e extends zo{}Rt.QueryFieldNumber=G0e;class W0e extends zo{}Rt.QueryFieldString=W0e;class vf extends dM{constructor(e,r,i,s,o){super(e,i,o),this.fieldDef=e,this.queryStruct=new _f(e,r,{struct:i},s)}getJoinableParent(){return this.queryStruct.getJoinableParent()}getFullOutputName(){return this.queryStruct.getFullOutputName()}includeInWildcard(){return this.isAtomic()}}Rt.QueryFieldStruct=vf;class V0e extends zo{}Rt.QueryFieldTimestamp=V0e;class Y0e extends zo{}Rt.QueryFieldUnsupported=Y0e;function K0e(t){return t.isAtomic()&&(0,Dn.hasExpression)(t.fieldDef)?(0,Dn.expressionIsAggregate)(t.fieldDef.expressionType):!1}function X0e(t){return t.isAtomic()&&(0,Dn.hasExpression)(t.fieldDef)?(0,Dn.expressionIsCalculation)(t.fieldDef.expressionType):!1}function J0e(t){if(t.isAtomic()){if((0,Dn.hasExpression)(t.fieldDef)){const e=t.fieldDef.expressionType;if((0,Dn.expressionIsCalculation)(e)||(0,Dn.expressionIsAggregate)(e))return!1}return!0}return!1}function qrt(t){return t instanceof zo&&K0e(t)}function zrt(t){return t instanceof zo&&X0e(t)}function Z0e(t){return t instanceof zo&&J0e(t)}function Hrt(t){return t.replace(/[^a-zA-Z0-9_]/g,"_o_")}class _f{constructor(e,r,i,s){if(this.structDef=e,this.sourceArguments=r,this.prepareResultOptions=s,this.nameMap=new Map,this._modelTag=void 0,this._arguments=void 0,this.setParent(i),"model"in i)if(this.model=i.model,this.pathAliasMap=new Map,(0,Dn.isSourceDef)(e))this.connectionName=e.connection;else throw new Error("All root StructDefs should be a baseTable");else this.model=this.getModel(),this.pathAliasMap=this.root().pathAliasMap,this.connectionName=this.root().connectionName;this.dialect=(0,Prt.getDialect)(this.findFirstDialect()),this.addFieldsFromFieldList(e.fields)}static registerTurtleFieldMaker(e){_f.turtleFieldMaker=e}modelCompilerFlags(){if(this._modelTag===void 0){const e=this.structDef.modelAnnotation,{tag:r}=(0,Mrt.annotationToTag)(e,{prefix:/^##!\s*/});this._modelTag=r}return this._modelTag}findFirstDialect(){if((0,Dn.isSourceDef)(this.structDef))return this.structDef.dialect;if(this.parent)return this.parent.findFirstDialect();throw new Error("Cannot create QueryStruct from record with model parent")}maybeEmitParameterizedSourceUsage(){var e;if((0,Dn.isSourceDef)(this.structDef)){const r={...this.structDef.parameters,...this.structDef.arguments};if(Object.values(r).length===0)return;(e=this.eventStream)===null||e===void 0||e.emit("parameterized-source-compiled",{parameters:r})}}resolveParentParameterReferences(e){return{...e,value:e.value===null?null:(0,Urt.exprMap)(e.value,r=>{if(r.node==="parameter"){const i=(this.parent?this.parent.arguments():this.arguments())[r.path[0]],s=this.parent?this.parent.resolveParentParameterReferences(i):i;if(s.value===null)throw new Error("Invalid parameter value");return s.value}return r})}}arguments(){var e;if(this._arguments!==void 0)return this._arguments;if(this._arguments={},(0,Dn.isSourceDef)(this.structDef)){const r=(e=this.structDef.parameters)!==null&&e!==void 0?e:{};for(const s in r)this._arguments[s]=r[s];const i={...this.structDef.arguments,...this.sourceArguments};for(const s in i){const o=i[s];this._arguments[s]=this.resolveParentParameterReferences(o)}}return this._arguments}addFieldsFromFieldList(e){for(const r of e){const i=(0,Dn.getIdentifier)(r);if(r.type==="turtle"){if(!_f.turtleFieldMaker)throw new Error("INTERNAL ERROR: QueryQuery must initialize QueryStruct nested factory method");this.addFieldToNameMap(i,_f.turtleFieldMaker(r,this))}else if((0,Dn.isAtomic)(r)||(0,Dn.isJoinedSource)(r))this.addFieldToNameMap(i,this.makeQueryField(r));else throw new Error("mtoy did nit add field")}this.nameMap.has("__distinct_key")||this.addFieldToNameMap("__distinct_key",new H0e({type:"string",name:"__distinct_key"},this))}getAliasIdentifier(){const e=this.getFullOutputName(),r=this.pathAliasMap.get(e);if(r===void 0){const i=Array.from(this.pathAliasMap.values()),s=Hrt((0,Dn.getIdentifier)(this.structDef));let o=`${s}_0`,a=1;for(;i.includes(o)&&a<1e3;)a++,o=`${s}_${a}`;if(a<1e3)return this.pathAliasMap.set(e,o),o;throw new Error("Internal Error: cannot create unique alias name")}else return r}getSQLIdentifier(){return this.unnestWithNumbers()&&this.parent!==void 0?this.parent.getSQLIdentifier()+"."+(0,Dn.getIdentifier)(this.structDef)+`[${this.getIdentifier()}.__row_id]`:this.getIdentifier()}sqlSimpleChildReference(e){const r=this.getSQLIdentifier();let i="table";this.structDef.type==="record"?i="record":this.structDef.type==="array"?i=this.structDef.elementTypeDef.type==="record_element"?"array[record]":"array[scalar]":this.structDef.type==="nest_source"&&(i="nest source");const s=this.getChildByName(e),o=(s==null?void 0:s.fieldDef.type)||"unknown";return this.dialect.sqlFieldReference(r,i,e,o)}getIdentifier(){if((0,Dn.isBaseTable)(this.structDef))return"base";if(this.structDef.type==="record"&&(0,Dn.hasExpression)(this.structDef)){if(this.computeRecordExpression)return this.recordValue||(this.recordValue=this.computeRecordExpression()),this.recordValue;throw new Error("INTERNAL ERROR, record field alias not pre-computed")}return this.structDef.type==="record"&&this.parent?this.parent.sqlSimpleChildReference((0,Dn.getIdentifier)(this.structDef)):this.getAliasIdentifier()}getFullOutputName(){return this.parent?this.parent.getFullOutputName()+(0,Dn.getIdentifier)(this.structDef)+".":""}unnestWithNumbers(){return this.dialect.unnestWithNumbers&&this.structDef.type==="array"}getJoinableParent(){if(this.structDef.type==="record"){if(this.parent)return this.parent.getJoinableParent();throw new Error("Internal Error: inline struct cannot be root")}return this}addFieldToNameMap(e,r){if(this.nameMap.has(e))throw new Error(`Redefinition of ${e}`);this.nameMap.set(e,r)}getPrimaryKeyField(e){let r;if(r=this.primaryKey())return r;throw new Error(`Missing primary key for ${e}`)}resolveQueryFields(e){if(this.structDef.type==="query_source"&&e){const r=e(this.structDef.query,this.prepareResultOptions);if(!r)throw new Error("Internal Error, query didn't produce a struct");const i={...this.structDef};for(const s of r.fields){const o=(0,Dn.getIdentifier)(s);this.nameMap.has(o)||(i.fields.push(s),this.nameMap.set(o,this.makeQueryField(s)))}this.structDef=i,!this.structDef.primaryKey&&r.primaryKey&&(this.structDef.primaryKey=r.primaryKey)}for(const[,r]of this.nameMap)r instanceof vf&&r.queryStruct.resolveQueryFields(e)}getModel(){if(this.model)return this.model;if(this.parent===void 0)throw new Error("Expected this query struct to have a parent, as no model was present.");return this.parent.getModel()}get eventStream(){return this.getModel().eventStream}setParent(e){"struct"in e&&(this.parent=e.struct),"model"in e?this.model=e.model:this.model=this.getModel()}makeQueryField(e,r){switch(e.type){case"array":case"record":case"query_source":case"table":case"sql_select":case"composite":return new vf(e,void 0,this,this.prepareResultOptions);case"string":return new W0e(e,this,r);case"date":return new z0e(e,this,r);case"timestamp":return new V0e(e,this,r);case"number":return new G0e(e,this,r);case"boolean":return new q0e(e,this,r);case"json":return new Q0e(e,this,r);case"sql native":return new Y0e(e,this,r);case"turtle":if(!_f.turtleFieldMaker)throw new Error("INTERNAL ERROR: QueryQuery must initialize QueryStruct nested factory method");return _f.turtleFieldMaker(e,this);default:throw new Error(`unknown field definition ${JSON.stringify(e),2}`)}}root(){return this.parent?this.parent.root():this}primaryKey(){if((0,Dn.isSourceDef)(this.structDef)&&this.structDef.primaryKey)return this.getDimensionByName([this.structDef.primaryKey])}getChildByName(e){return this.nameMap.get(e)}getFieldByName(e){let r,i=this,s=e[0];for(const o of e){if(r=i==null?void 0:i.getChildByName(o),!r){s=o;break}i=r instanceof vf?r.queryStruct:void 0}if(r===void 0){const o=e.length>1?` in ${e.join(".")}`:"";throw new Error(`${s} not found${o}`)}return r}getQueryFieldByName(e){const r=this.getFieldByName(e);if(r instanceof vf)throw new Error(`Cannot reference ${e.join(".")} as a scalar'`);return r}getQueryFieldReference(e){const{path:r,annotation:i,drillExpression:s}=e,o=this.getFieldByName(r);if(i||s){if(o.parent===void 0)throw new Error("Inconcievable, field reference to orphaned query field");if(o instanceof vf){const a={...o.fieldDef,annotation:i,drillExpression:s};return new vf(a,void 0,o.parent,o.parent.prepareResultOptions,o.referenceId)}else{const a={...o.fieldDef,annotation:i,drillExpression:s};return o.parent.makeQueryField(a,o.referenceId)}}return o}getDimensionOrMeasureByName(e){const r=this.getFieldByName(e);if(!r.isAtomic())throw new Error(`${e} is not an atomic field? Inconceivable!`);return r}getDimensionByName(e){const r=this.getFieldByName(e);if(Z0e(r))return r;throw new Error(`${e} is not an atomic scalar field? Inconceivable!`)}getStructByName(e){if(e.length===0)return this;const r=this.getFieldByName(e);if(r instanceof vf)return r.queryStruct;throw new Error(`Error: Path to structure not found '${e.join(".")}'`)}getDistinctKey(){if(this.structDef.type!=="record")return this.getDimensionByName(["__distinct_key"]);if(this.parent)return this.parent.getDistinctKey();throw new Error("Asking a record for a primary key? Inconceivable!")}applyStructFiltersToTurtleDef(e){const r=[...e.pipeline],i=e.annotation,s=e.filterList||[];return r[0]={...r[0],filterList:s.concat(r[0].filterList||[],(0,Dn.isSourceDef)(this.structDef)?this.structDef.filterList||[]:[])},{type:"turtle",name:e.name,pipeline:r,annotation:i,location:e.location}}}Rt.QueryStruct=_f;var Hn={},W2={},as={};Object.defineProperty(as,"__esModule",{value:!0}),as.isChainOp=Qrt,as.isStringCondition=Grt,as.isStringFilter=Wrt,as.isBooleanFilter=Vrt,as.isNumberFilter=Yrt,as.isTemporalFilter=Krt,as.isFilterExpression=Xrt,as.isFilterable=Jrt;function Qrt(t){return["and","or",","].includes(t)}function Grt(t){return["starts","ends","contains","="].includes(t.operator)}function Wrt(t){return"operator"in t&&typeof t.operator=="string"&&["starts","ends","contains","=","~","null","empty","and","or",",","()"].includes(t.operator)}function Vrt(t){return"operator"in t&&typeof t.operator=="string"&&["null","true","false","false_or_null"].includes(t.operator)}function Yrt(t){return"operator"in t&&typeof t.operator=="string"&&["range","<=",">=","!=","=",">","<","and","or","()","null"].includes(t.operator)}function Krt(t){return"operator"in t&&typeof t.operator=="string"&&["literal","before","after","to","for","in","and","or","in_last","this","last","next","()","null"].includes(t.operator)}function Xrt(t){return!!t&&"operator"in t}function Jrt(t){return["string","number","boolean","timestamp","date"].includes(t)}var HT={};Object.defineProperty(HT,"__esModule",{value:!0}),HT.BooleanFilterExpression=void 0,HT.BooleanFilterExpression={parse(t){var e;if(t.match(/^\s*$/))return{parsed:null,log:[]};const r={parsed:null,log:[]};let i=t.toLowerCase().trim().replace(/\s\s+/," "),s=!1;if(i.startsWith("not ")&&(s=!0,i=i.slice(4)),i==="true")r.parsed={operator:"true"};else if(i==="false")r.parsed={operator:"false_or_null"};else if(i==="=false")r.parsed={operator:"false"};else if(i==="null")r.parsed={operator:"null"};else if(i==="not null")r.parsed={operator:"null",not:!0};else{const o=t.match(/[^\s]/),a=o&&(e=o.index)!==null&&e!==void 0?e:0;r.log=[{message:"Illegal boolean filter. Must be one of true,false,=false,null,not null",severity:"error",startIndex:a,endIndex:a+t.length-1}]}return s&&r.parsed&&(r.parsed.not=!0),r},unparse(t){if(t===null)return"";const e=t.not?"not ":"";switch(t.operator){case"true":case"null":return e+t.operator;case"false_or_null":return e+"false";case"false":return e+"=false"}}};var efe={},tfe={exports:{}};(function(t){(function(e,r){t.exports?t.exports=r():e.nearley=r()})(R,function(){function e(c,f,d){return this.id=++e.highestId,this.name=c,this.symbols=f,this.postprocess=d,this}e.highestId=0,e.prototype.toString=function(c){var f=typeof c>"u"?this.symbols.map(l).join(" "):this.symbols.slice(0,c).map(l).join(" ")+" ● "+this.symbols.slice(c).map(l).join(" ");return this.name+" → "+f};function r(c,f,d,x){this.rule=c,this.dot=f,this.reference=d,this.data=[],this.wantedBy=x,this.isComplete=this.dot===c.symbols.length}r.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},r.prototype.nextState=function(c){var f=new r(this.rule,this.dot+1,this.reference,this.wantedBy);return f.left=this,f.right=c,f.isComplete&&(f.data=f.build(),f.right=void 0),f},r.prototype.build=function(){var c=[],f=this;do c.push(f.right.data),f=f.left;while(f.left);return c.reverse(),c},r.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,a.fail))};function i(c,f){this.grammar=c,this.index=f,this.states=[],this.wants={},this.scannable=[],this.completed={}}i.prototype.process=function(c){for(var f=this.states,d=this.wants,x=this.completed,p=0;p<f.length;p++){var m=f[p];if(m.isComplete){if(m.finish(),m.data!==a.fail){for(var g=m.wantedBy,y=g.length;y--;){var v=g[y];this.complete(v,m)}if(m.reference===this.index){var E=m.rule.name;(this.completed[E]=this.completed[E]||[]).push(m)}}}else{var E=m.rule.symbols[m.dot];if(typeof E!="string"){this.scannable.push(m);continue}if(d[E]){if(d[E].push(m),x.hasOwnProperty(E))for(var _=x[E],y=0;y<_.length;y++){var A=_[y];this.complete(m,A)}}else d[E]=[m],this.predict(E)}}},i.prototype.predict=function(c){for(var f=this.grammar.byName[c]||[],d=0;d<f.length;d++){var x=f[d],p=this.wants[c],m=new r(x,0,this.index,p);this.states.push(m)}},i.prototype.complete=function(c,f){var d=c.nextState(f);this.states.push(d)};function s(c,f){this.rules=c,this.start=f||this.rules[0].name;var d=this.byName={};this.rules.forEach(function(x){d.hasOwnProperty(x.name)||(d[x.name]=[]),d[x.name].push(x)})}s.fromCompiled=function(x,f){var d=x.Lexer;x.ParserStart&&(f=x.ParserStart,x=x.ParserRules);var x=x.map(function(m){return new e(m.name,m.symbols,m.postprocess)}),p=new s(x,f);return p.lexer=d,p};function o(){this.reset("")}o.prototype.reset=function(c,f){this.buffer=c,this.index=0,this.line=f?f.line:1,this.lastLineBreak=f?-f.col:0},o.prototype.next=function(){if(this.index<this.buffer.length){var c=this.buffer[this.index++];return c===`
|
|
953
953
|
`&&(this.line+=1,this.lastLineBreak=this.index),{value:c}}},o.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},o.prototype.formatError=function(c,f){var d=this.buffer;if(typeof d=="string"){var x=d.split(`
|
|
954
954
|
`).slice(Math.max(0,this.line-5),this.line),p=d.indexOf(`
|
|
@@ -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.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:
|
|
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.315",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.315",
|
|
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.315",
|
|
33
|
+
"@malloydata/malloy-interfaces": "0.0.315",
|
|
34
|
+
"@malloydata/malloy-tag": "0.0.315",
|
|
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.315",
|
|
47
47
|
"@storybook/addon-essentials": "^8.5.8",
|
|
48
48
|
"@storybook/addon-interactions": "^8.5.8",
|
|
49
49
|
"@storybook/addon-links": "^8.5.8",
|