@malloydata/render 0.0.248-dev250325235002 → 0.0.248
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.umd.js
CHANGED
|
@@ -1024,7 +1024,7 @@ ${(0,xJe.indent)(r)}
|
|
|
1024
1024
|
$$ LANGUAGE SQL;
|
|
1025
1025
|
`}sqlCreateFunctionCombineLastStage(e){return`SELECT ARRAY((SELECT AS STRUCT * FROM ${e}))
|
|
1026
1026
|
`}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){let i=r.e.sql||"why could this be undefined";if(r.units==="week"&&(i=`DATE_SUB(${i}, INTERVAL DAYOFWEEK(${i}) - 1 DAY)`),Tc.TD.isTimestamp(r.e.typeDef)){const o=(0,_y.qtz)(e);if(o){const u=`(CONVERT_TZ(${i}, 'UTC','${o}'))`;return`(${`CONVERT_TZ(${`${this.truncToUnit(u,r.units)}`}, '${o}', 'UTC')`})`}}return`${this.truncToUnit(i,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=pJe[r.units]||r.units;let s=r.e.sql;if(Tc.TD.isTimestamp(r.e.typeDef)){const o=(0,_y.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:u,dstSQLType:a}=this.sqlCastPrep(r),l=(0,_y.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(!Tc.TD.eq(o,u)){if(r.safe)throw new Error("Mysql dialect doesn't support Safe Cast");return Tc.TD.isString(u)?`CONCAT(${i}, '')`:`CAST(${i} AS ${a})`}return i}sqlRegexpMatch(e){return`REGEXP_LIKE(${e.kids.expr.sql}, ${e.kids.regex.sql})`}sqlLiteralTime(e,r){if(Tc.TD.isDate(r.typeDef))return`DATE '${r.literal}'`;const i=r.timezone||(0,_y.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(aae[e.units]){r=`UNIX_TIMESTAMP(${r})`,i=`UNIX_TIMESTAMP(${i})`;const s=`${i}-${r}`;return e.units==="second"?`FLOOR(${s})`:`FLOOR((${s})/${aae[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,Tc.isSamplingEnable)(r)&&r.enable&&(r=this.defaultSampling),(0,Tc.isSamplingRows)(r))return`(SELECT * FROM ${e} ORDER BY rand() LIMIT ${r.rows} )`;if((0,Tc.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,uae.expandOverrideMap)(hJe.MYSQL_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,uae.expandBlueprintMap)(dJe.MYSQL_DIALECT_FUNCTIONS)}mapFieldsForJsonObject(e,r){return e.map(i=>`${i.sqlOutputName.replace(/`/g,"'")}, ${r?"NULL":i.sqlExpression}
|
|
1027
|
-
`).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(", ")})`}}B4.MySQLDialect=gJe,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__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(B4,t)}(Y$);var Ca={};Object.defineProperty(Ca,"__esModule",{value:!0}),Ca.getDialects=Ca.registerDialect=Ca.getDialect=void 0;const yJe=U$,EJe=k$,AJe=Q$,_Je=O$,lae=z$,vJe=Y$,J$=new Map;function CJe(t){const e=J$.get(t);if(e===void 0)throw new Error(`Unknown Dialect ${t}`);return e}Ca.getDialect=CJe;function Rc(t){J$.set(t.name,t)}Ca.registerDialect=Rc;function SJe(){return[...J$.values()]}Ca.getDialects=SJe,Rc(new EJe.PostgresDialect),Rc(new _Je.StandardSQLDialect),Rc(new yJe.DuckDBDialect),Rc(new AJe.SnowflakeDialect),Rc(new lae.TrinoDialect),Rc(new lae.PrestoDialect),Rc(new vJe.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=ot;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=vc;Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return r.Dialect}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return r.qtz}});var i=O$;Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return i.StandardSQLDialect}});var s=k$;Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return s.PostgresDialect}});var o=U$;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return o.DuckDBDialect}});var u=Q$;Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return u.SnowflakeDialect}});var a=z$;Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return a.TrinoDialect}});var l=Y$;Object.defineProperty(t,"MySQLDialect",{enumerable:!0,get:function(){return l.MySQLDialect}});var c=Ca;Object.defineProperty(t,"getDialect",{enumerable:!0,get:function(){return c.getDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return c.registerDialect}});var f=Sc;Object.defineProperty(t,"getMalloyStandardFunctions",{enumerable:!0,get:function(){return f.getMalloyStandardFunctions}});var x=Xx;Object.defineProperty(t,"TinyParser",{enumerable:!0,get:function(){return x.TinyParser}})}(Mp);var ji={},$s={},Qp={},ai={};Object.defineProperty(ai,"__esModule",{value:!0}),ai.annotationToTag=ai.annotationToTaglines=ai.addModelScope=void 0;const cae=Zo;function bJe(t,e){const r=t?{...t}:{};return r.scopes?r.scopes=r.scopes.concat(e):r.scopes=[e],r}ai.addModelScope=bJe;function fae(t,e){t||(t={});const r=t.inherits?fae(t.inherits,e):[];function i(s){const o=[];for(const u of s||[])(e===void 0||u.text.match(e))&&o.push(u.text);return o}return r.concat(i(t.blockNotes),i(t.notes))}ai.annotationToTaglines=fae;function xae(t,e={}){var r;let i=e.extending||new cae.Tag;const s=e.prefix||/^##? /;t||(t={});const o=[];if(t.inherits){const l=xae(t.inherits,e);o.push(...l.log),i=l.tag}const u=[];t.blockNotes&&u.push(...t.blockNotes),t.notes&&u.push(...t.notes);const a=[];for(const l of u)l.text.match(s)&&a.push(l);for(let l=0;l<a.length;l++){const c=a[l];if(c.text.match(s)){const f=cae.Tag.fromTagLine(c.text,l,i,...(r=e.scopes)!==null&&r!==void 0?r:[]);i=f.tag,o.push(...f.log.map(x=>TJe(x,c)))}}return{tag:i,log:o}}ai.annotationToTag=xae;function TJe(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(Qp,"__esModule",{value:!0}),Qp.buildQueryMaterializationSpec=Qp.shouldMaterialize=void 0;const RJe=$t,DJe=ai;function OJe(t){const e=structuredClone(t);return e&&(e.inherits=void 0),(0,DJe.annotationToTag)(e).tag.has("materialize")}Qp.shouldMaterialize=OJe;function FJe(t,e,r){if(!e)throw new Error(`Query tagged to materialize, but its name is not specified. ${t}`);if(!t)throw new Error(`Query tagged to materialize, but its path is not specified: ${e}`);const i={path:t,source:void 0,queryName:e},s=(0,RJe.generateHash)(JSON.stringify(i)).replace(/-/g,"_"),o=`${r?`${r}_`:""}${e}_${s}`;return{...i,id:o}}Qp.buildQueryMaterializationSpec=FJe;var dae={},P4={},Tn={};Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.isFilterable=Tn.isFilterExpression=Tn.isTemporalFilter=Tn.isNumberFilter=Tn.isBooleanFilter=Tn.isStringFilter=Tn.isStringCondition=Tn.isChainOp=void 0;function wJe(t){return["and","or",","].includes(t)}Tn.isChainOp=wJe;function NJe(t){return["starts","ends","contains","="].includes(t.operator)}Tn.isStringCondition=NJe;function LJe(t){return"operator"in t&&typeof t.operator=="string"&&["starts","ends","contains","=","~","null","empty","and","or",",","()"].includes(t.operator)}Tn.isStringFilter=LJe;function IJe(t){return"operator"in t&&typeof t.operator=="string"&&["null","true","false","false_or_null"].includes(t.operator)}Tn.isBooleanFilter=IJe;function $Je(t){return"operator"in t&&typeof t.operator=="string"&&["range","<=",">=","!=","=",">","<","and","or","()","null"].includes(t.operator)}Tn.isNumberFilter=$Je;function BJe(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)}Tn.isTemporalFilter=BJe;function kJe(t){return"operator"in t}Tn.isFilterExpression=kJe;function MJe(t){return["string","number","boolean","timestamp","date"].includes(t)}Tn.isFilterable=MJe;var U4={};Object.defineProperty(U4,"__esModule",{value:!0}),U4.BooleanFilterExpression=void 0,U4.BooleanFilterExpression={parse(t){var e;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]/),u=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:u,endIndex:u+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 hae={},pae={exports:{}};(function(t){(function(e,r){t.exports?t.exports=r():e.nearley=r()})(T,function(){function e(c,f,x){return this.id=++e.highestId,this.name=c,this.symbols=f,this.postprocess=x,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,x,h){this.rule=c,this.dot=f,this.reference=x,this.data=[],this.wantedBy=h,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,u.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,x=this.wants,h=this.completed,p=0;p<f.length;p++){var m=f[p];if(m.isComplete){if(m.finish(),m.data!==u.fail){for(var y=m.wantedBy,g=y.length;g--;){var E=y[g];this.complete(E,m)}if(m.reference===this.index){var A=m.rule.name;(this.completed[A]=this.completed[A]||[]).push(m)}}}else{var A=m.rule.symbols[m.dot];if(typeof A!="string"){this.scannable.push(m);continue}if(x[A]){if(x[A].push(m),h.hasOwnProperty(A))for(var _=h[A],g=0;g<_.length;g++){var v=_[g];this.complete(m,v)}}else x[A]=[m],this.predict(A)}}},i.prototype.predict=function(c){for(var f=this.grammar.byName[c]||[],x=0;x<f.length;x++){var h=f[x],p=this.wants[c],m=new r(h,0,this.index,p);this.states.push(m)}},i.prototype.complete=function(c,f){var x=c.nextState(f);this.states.push(x)};function s(c,f){this.rules=c,this.start=f||this.rules[0].name;var x=this.byName={};this.rules.forEach(function(h){x.hasOwnProperty(h.name)||(x[h.name]=[]),x[h.name].push(h)})}s.fromCompiled=function(h,f){var x=h.Lexer;h.ParserStart&&(f=h.ParserStart,h=h.ParserRules);var h=h.map(function(m){return new e(m.name,m.symbols,m.postprocess)}),p=new s(h,f);return p.lexer=x,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===`
|
|
1027
|
+
`).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(", ")})`}}B4.MySQLDialect=gJe,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__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(B4,t)}(Y$);var Ca={};Object.defineProperty(Ca,"__esModule",{value:!0}),Ca.getDialects=Ca.registerDialect=Ca.getDialect=void 0;const yJe=U$,EJe=k$,AJe=Q$,_Je=O$,lae=z$,vJe=Y$,J$=new Map;function CJe(t){const e=J$.get(t);if(e===void 0)throw new Error(`Unknown Dialect ${t}`);return e}Ca.getDialect=CJe;function Rc(t){J$.set(t.name,t)}Ca.registerDialect=Rc;function SJe(){return[...J$.values()]}Ca.getDialects=SJe,Rc(new EJe.PostgresDialect),Rc(new _Je.StandardSQLDialect),Rc(new yJe.DuckDBDialect),Rc(new AJe.SnowflakeDialect),Rc(new lae.TrinoDialect),Rc(new lae.PrestoDialect),Rc(new vJe.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=ot;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=vc;Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return r.Dialect}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return r.qtz}});var i=O$;Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return i.StandardSQLDialect}});var s=k$;Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return s.PostgresDialect}});var o=U$;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return o.DuckDBDialect}});var u=Q$;Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return u.SnowflakeDialect}});var a=z$;Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return a.TrinoDialect}});var l=Y$;Object.defineProperty(t,"MySQLDialect",{enumerable:!0,get:function(){return l.MySQLDialect}});var c=Ca;Object.defineProperty(t,"getDialect",{enumerable:!0,get:function(){return c.getDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return c.registerDialect}});var f=Sc;Object.defineProperty(t,"getMalloyStandardFunctions",{enumerable:!0,get:function(){return f.getMalloyStandardFunctions}});var x=Xx;Object.defineProperty(t,"TinyParser",{enumerable:!0,get:function(){return x.TinyParser}})}(Mp);var ji={},$s={},Qp={},ai={};Object.defineProperty(ai,"__esModule",{value:!0}),ai.annotationToTag=ai.annotationToTaglines=ai.addModelScope=void 0;const cae=Zo;function bJe(t,e){const r=t?{...t}:{};return r.scopes?r.scopes=r.scopes.concat(e):r.scopes=[e],r}ai.addModelScope=bJe;function fae(t,e){t||(t={});const r=t.inherits?fae(t.inherits,e):[];function i(s){const o=[];for(const u of s||[])(e===void 0||u.text.match(e))&&o.push(u.text);return o}return r.concat(i(t.blockNotes),i(t.notes))}ai.annotationToTaglines=fae;function xae(t,e={}){var r;let i=e.extending||new cae.Tag;const s=e.prefix||/^##? /;t||(t={});const o=[];if(t.inherits){const l=xae(t.inherits,e);o.push(...l.log),i=l.tag}const u=[];t.blockNotes&&u.push(...t.blockNotes),t.notes&&u.push(...t.notes);const a=[];for(const l of u)l.text.match(s)&&a.push(l);for(let l=0;l<a.length;l++){const c=a[l];if(c.text.match(s)){const f=cae.Tag.fromTagLine(c.text,l,i,...(r=e.scopes)!==null&&r!==void 0?r:[]);i=f.tag,o.push(...f.log.map(x=>TJe(x,c)))}}return{tag:i,log:o}}ai.annotationToTag=xae;function TJe(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(Qp,"__esModule",{value:!0}),Qp.buildQueryMaterializationSpec=Qp.shouldMaterialize=void 0;const RJe=$t,DJe=ai;function OJe(t){const e=structuredClone(t);return e&&(e.inherits=void 0),(0,DJe.annotationToTag)(e).tag.has("materialize")}Qp.shouldMaterialize=OJe;function FJe(t,e,r){if(!e)throw new Error(`Query tagged to materialize, but its name is not specified. ${t}`);if(!t)throw new Error(`Query tagged to materialize, but its path is not specified: ${e}`);const i={path:t,source:void 0,queryName:e},s=(0,RJe.generateHash)(JSON.stringify(i)).replace(/-/g,"_"),o=`${r?`${r}_`:""}${e}_${s}`;return{...i,id:o}}Qp.buildQueryMaterializationSpec=FJe;var dae={},P4={},Tn={};Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.isFilterable=Tn.isFilterExpression=Tn.isTemporalFilter=Tn.isNumberFilter=Tn.isBooleanFilter=Tn.isStringFilter=Tn.isStringCondition=Tn.isChainOp=void 0;function wJe(t){return["and","or",","].includes(t)}Tn.isChainOp=wJe;function NJe(t){return["starts","ends","contains","="].includes(t.operator)}Tn.isStringCondition=NJe;function LJe(t){return"operator"in t&&typeof t.operator=="string"&&["starts","ends","contains","=","~","null","empty","and","or",",","()"].includes(t.operator)}Tn.isStringFilter=LJe;function IJe(t){return"operator"in t&&typeof t.operator=="string"&&["null","true","false","false_or_null"].includes(t.operator)}Tn.isBooleanFilter=IJe;function $Je(t){return"operator"in t&&typeof t.operator=="string"&&["range","<=",">=","!=","=",">","<","and","or","()","null"].includes(t.operator)}Tn.isNumberFilter=$Je;function BJe(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)}Tn.isTemporalFilter=BJe;function kJe(t){return"operator"in t}Tn.isFilterExpression=kJe;function MJe(t){return["string","number","boolean","timestamp","date"].includes(t)}Tn.isFilterable=MJe;var U4={};Object.defineProperty(U4,"__esModule",{value:!0}),U4.BooleanFilterExpression=void 0,U4.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]/),u=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:u,endIndex:u+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 hae={},pae={exports:{}};(function(t){(function(e,r){t.exports?t.exports=r():e.nearley=r()})(T,function(){function e(c,f,x){return this.id=++e.highestId,this.name=c,this.symbols=f,this.postprocess=x,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,x,h){this.rule=c,this.dot=f,this.reference=x,this.data=[],this.wantedBy=h,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,u.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,x=this.wants,h=this.completed,p=0;p<f.length;p++){var m=f[p];if(m.isComplete){if(m.finish(),m.data!==u.fail){for(var y=m.wantedBy,g=y.length;g--;){var E=y[g];this.complete(E,m)}if(m.reference===this.index){var A=m.rule.name;(this.completed[A]=this.completed[A]||[]).push(m)}}}else{var A=m.rule.symbols[m.dot];if(typeof A!="string"){this.scannable.push(m);continue}if(x[A]){if(x[A].push(m),h.hasOwnProperty(A))for(var _=h[A],g=0;g<_.length;g++){var v=_[g];this.complete(m,v)}}else x[A]=[m],this.predict(A)}}},i.prototype.predict=function(c){for(var f=this.grammar.byName[c]||[],x=0;x<f.length;x++){var h=f[x],p=this.wants[c],m=new r(h,0,this.index,p);this.states.push(m)}},i.prototype.complete=function(c,f){var x=c.nextState(f);this.states.push(x)};function s(c,f){this.rules=c,this.start=f||this.rules[0].name;var x=this.byName={};this.rules.forEach(function(h){x.hasOwnProperty(h.name)||(x[h.name]=[]),x[h.name].push(h)})}s.fromCompiled=function(h,f){var x=h.Lexer;h.ParserStart&&(f=h.ParserStart,h=h.ParserRules);var h=h.map(function(m){return new e(m.name,m.symbols,m.postprocess)}),p=new s(h,f);return p.lexer=x,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===`
|
|
1028
1028
|
`&&(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 x=this.buffer;if(typeof x=="string"){var h=x.split(`
|
|
1029
1029
|
`).slice(Math.max(0,this.line-5),this.line),p=x.indexOf(`
|
|
1030
1030
|
`,this.index);p===-1&&(p=x.length);var m=this.index-this.lastLineBreak,y=String(this.line).length;return f+=" at line "+this.line+" col "+m+`:
|
|
@@ -1042,7 +1042,7 @@ Use (?: … ) instead`);if(!ue.lineBreaks&&j.test(`
|
|
|
1042
1042
|
`))throw new Error("Rule should declare lineBreaks: "+j);xe.push(l(L))}}var z=q&&q.fallback,F=i&&!z?"ym":"gm",k=i||z?"":"|";X===!0&&(F+="u");var U=new RegExp(c(xe)+k,F);return{regexp:U,groups:fe,fast:K,error:q||E}}function _(D){var B=A(g(D));return new S({start:B},"start")}function v(D,B,q){var K=D&&(D.push||D.next);if(K&&!q[K])throw new Error("Missing state '"+K+"' (in token '"+D.defaultType+"' of state '"+B+"')");if(D&&D.pop&&+D.pop!=1)throw new Error("pop must be 1 (in token '"+D.defaultType+"' of state '"+B+"')")}function C(D,B){var q=D.$all?g(D.$all):[];delete D.$all;var K=Object.getOwnPropertyNames(D);B||(B=K[0]);for(var H=Object.create(null),X=0;X<K.length;X++){var fe=K[X];H[fe]=g(D[fe]).concat(q)}for(var X=0;X<K.length;X++)for(var fe=K[X],xe=H[fe],te=Object.create(null),ue=0;ue<xe.length;ue++){var de=xe[ue];if(de.include){var Se=[ue,1];if(de.include!==fe&&!te[de.include]){te[de.include]=!0;var I=H[de.include];if(!I)throw new Error("Cannot include nonexistent state '"+de.include+"' (in state '"+fe+"')");for(var N=0;N<I.length;N++){var L=I[N];xe.indexOf(L)===-1&&Se.push(L)}}xe.splice.apply(xe,Se),ue--}}for(var j=Object.create(null),X=0;X<K.length;X++){var fe=K[X];j[fe]=A(H[fe],!0)}for(var X=0;X<K.length;X++){for(var V=K[X],z=j[V],F=z.groups,ue=0;ue<F.length;ue++)v(F[ue],V,j);for(var k=Object.getOwnPropertyNames(z.fast),ue=0;ue<k.length;ue++)v(z.fast[k[ue]],V,j)}return new S(j,B)}function b(D){for(var B=typeof Map<"u",q=B?new Map:Object.create(null),K=Object.getOwnPropertyNames(D),H=0;H<K.length;H++){var X=K[H],fe=D[X],xe=Array.isArray(fe)?fe:[fe];xe.forEach(function(te){if(typeof te!="string")throw new Error("keyword must be string (in keyword '"+X+"')");B?q.set(te,X):q[te]=X})}return function(te){return B?q.get(te):q[te]}}var S=function(D,B){this.startState=B,this.states=D,this.buffer="",this.stack=[],this.reset()};S.prototype.reset=function(D,B){return this.buffer=D||"",this.index=0,this.line=B?B.line:1,this.col=B?B.col:1,this.queuedToken=B?B.queuedToken:null,this.queuedText=B?B.queuedText:"",this.queuedThrow=B?B.queuedThrow:null,this.setState(B?B.state:this.startState),this.stack=B&&B.stack?B.stack.slice():[],this},S.prototype.save=function(){return{line:this.line,col:this.col,state:this.state,stack:this.stack.slice(),queuedToken:this.queuedToken,queuedText:this.queuedText,queuedThrow:this.queuedThrow}},S.prototype.setState=function(D){if(!(!D||this.state===D)){this.state=D;var B=this.states[D];this.groups=B.groups,this.error=B.error,this.re=B.regexp,this.fast=B.fast}},S.prototype.popState=function(){this.setState(this.stack.pop())},S.prototype.pushState=function(D){this.stack.push(this.state),this.setState(D)};var R=i?function(D,B){return D.exec(B)}:function(D,B){var q=D.exec(B);return q[0].length===0?null:q};S.prototype._getGroup=function(D){for(var B=this.groups.length,q=0;q<B;q++)if(D[q+1]!==void 0)return this.groups[q];throw new Error("Cannot find token type for matched text")};function O(){return this.value}if(S.prototype.next=function(){var D=this.index;if(this.queuedGroup){var B=this._token(this.queuedGroup,this.queuedText,D);return this.queuedGroup=null,this.queuedText="",B}var q=this.buffer;if(D!==q.length){var fe=this.fast[q.charCodeAt(D)];if(fe)return this._token(fe,q.charAt(D),D);var K=this.re;K.lastIndex=D;var H=R(K,q),X=this.error;if(H==null)return this._token(X,q.slice(D,q.length),D);var fe=this._getGroup(H),xe=H[0];return X.fallback&&H.index!==D?(this.queuedGroup=fe,this.queuedText=xe,this._token(X,q.slice(D,H.index),D)):this._token(fe,xe,D)}},S.prototype._token=function(D,B,q){var K=0;if(D.lineBreaks){var H=/\n/g,X=1;if(B===`
|
|
1043
1043
|
`)K=1;else for(;H.exec(B);)K++,X=H.lastIndex}var fe={type:typeof D.type=="function"&&D.type(B)||D.defaultType,value:typeof D.value=="function"?D.value(B):B,text:B,toString:O,offset:q,lineBreaks:K,line:this.line,col:this.col},xe=B.length;if(this.index+=xe,this.line+=K,K!==0?this.col=xe-X+1:this.col+=xe,D.shouldThrow){var te=new Error(this.formatError(fe,"invalid syntax"));throw te}return D.pop?this.popState():D.push?this.pushState(D.push):D.next&&this.setState(D.next),fe},typeof Symbol<"u"&&Symbol.iterator){var $=function(D){this.lexer=D};$.prototype.next=function(){var D=this.lexer.next();return{value:D,done:!D}},$.prototype[Symbol.iterator]=function(){return this},S.prototype[Symbol.iterator]=function(){return new $(this)}}return S.prototype.formatError=function(D,B){if(D==null)var q=this.buffer.slice(this.index),D={text:q,offset:this.index,lineBreaks:q.indexOf(`
|
|
1044
1044
|
`)===-1?0:1,line:this.line,col:this.col};var K=2,H=Math.max(D.line-K,1),X=D.line+K,fe=String(X).length,xe=h(this.buffer,this.line-D.line+K+1).slice(0,5),te=[];te.push(B+" at line "+D.line+" col "+D.col+":"),te.push("");for(var ue=0;ue<xe.length;ue++){var de=xe[ue],Se=H+ue;te.push(x(String(Se),fe)+" "+de),Se===D.line&&te.push(x("",fe+D.col+1)+"^")}return te.join(`
|
|
1045
|
-
`)},S.prototype.clone=function(){return new S(this.states,this.state)},S.prototype.has=function(D){return!0},{compile:_,states:C,error:Object.freeze({error:!0}),fallback:Object.freeze({fallback:!0}),keywords:b}})})(mae);var eB=mae.exports,qt={};Object.defineProperty(qt,"__esModule",{value:!0}),qt.mkUnits=qt.timeLiteral=qt.joinTemporal=qt.temporalNot=qt.numNot=qt.mkValues=qt.mkRange=qt.joinNumbers=qt.conjoin=qt.matchOp=qt.escape=qt.unescape=qt.maybeNot=void 0;const Sa=Tn;function PJe(t){const[e,r]=t;return e&&r&&(0,Sa.isStringFilter)(r)?{...r,not:!0}:r}qt.maybeNot=PJe;function vy(t){return t.replace(/\\(.)/g,"$1")}qt.unescape=vy;function UJe(t){const e=t.toLowerCase();return e==="null"||e==="empty"?"\\"+t:t.replace(/([,; |()\\%_-])/g,"\\$1")}qt.escape=UJe;function j4(t){let e=!1,r=!1,i=0,s=!1;const o=t.length;for(let u=0;u<o;u+=1){const a=t[u];if(a===" "||a===" "){i+=1;continue}i=0,a==="%"?(s=!0,u===0&&(e=!0),r=!0):(r=!1,a==="\\"?u+=1:a==="_"&&(s=!0))}return{hasLike:s,percentEnd:r&&o>1,percentStart:e&&o>1,endSpace:i}}function jJe(t){let e=t.trimStart();const{hasLike:r,percentEnd:i,percentStart:s,endSpace:o}=j4(e);if(o>0&&(e=e.slice(0,-o)),r){if(s&&i){const u=e.slice(1,-1);if(!j4(u).hasLike&&u.length>0)return{operator:"contains",values:[vy(u)]}}else if(i){const u=e.slice(0,-1);if(!j4(u).hasLike)return{operator:"starts",values:[vy(u)]}}else if(s){const u=e.slice(1);if(!j4(u).hasLike)return{operator:"ends",values:[vy(u)]}}return{operator:"~",escaped_values:[e]}}return e.toLowerCase()==="null"||e==="NULL"?{operator:"null"}:e==="empty"||e==="EMPTY"?{operator:"empty"}:{operator:"=",values:[vy(e)]}}qt.matchOp=jJe;function tB(t,e){var r,i;return t.operator===e.operator&&((r=t.not)!==null&&r!==void 0?r:!1)===((i=e.not)!==null&&i!==void 0?i:!1)}function qJe(t,e,r){if((0,Sa.isStringFilter)(t)&&(0,Sa.isStringFilter)(r)){if(e===","){if(t.operator==="~"&&tB(t,r))return{...t,escaped_values:[...t.escaped_values,...r.escaped_values]};if((0,Sa.isStringCondition)(t)&&tB(t,r))return{...t,values:[...t.values,...r.values]}}const i=e===","?",":e==="|"?"or":e===";"?"and":void 0;if(i)return t.operator===i?{...t,members:[...t.members,r]}:{operator:i,members:[t,r]}}return null}qt.conjoin=qJe;function QJe(t,e,r){if((0,Sa.isNumberFilter)(t)&&(0,Sa.isNumberFilter)(r)){if(e==="or"&&t.operator==="="&&tB(t,r)){const i={operator:"=",values:[...t.values,...r.values]};return t.not&&(i.not=!0),i}if(e==="and"||e==="or")return t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}}return null}qt.joinNumbers=QJe;function HJe(t,e,r,i){return{operator:"range",startValue:e,startOperator:t==="("?">":">=",endValue:r,endOperator:i===")"?"<":"<="}}qt.mkRange=HJe;function zJe(t,e){return{values:[t,...e]}}qt.mkValues=zJe;function GJe(t,e){return(0,Sa.isNumberFilter)(t)&&e?t.operator==="="?{operator:"!=",values:t.values}:t.operator==="!="?{operator:"=",values:t.values}:{...t,not:!0}:t}qt.numNot=GJe;function WJe(t,e){return(0,Sa.isTemporalFilter)(t)&&e?{...t,not:!0}:t}qt.temporalNot=WJe;function VJe(t,e,r){return(0,Sa.isTemporalFilter)(t)&&(0,Sa.isTemporalFilter)(r)&&(e==="and"||e==="or")?t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}:null}qt.joinTemporal=VJe;function YJe(t,e){const r={moment:"literal",literal:t};return e&&(r.units=e),r}qt.timeLiteral=YJe;function KJe(t){switch(t.toLowerCase()){case"second":case"seconds":return"second";case"minute":case"minutes":return"minute";case"hour":case"hours":return"hour";case"day":case"days":return"day";case"week":case"weeks":return"week";case"month":case"months":return"month";case"quarter":case"quarters":return"quarter";case"year":case"years":return"year"}}qt.mkUnits=KJe;var JJe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Z$,"__esModule",{value:!0});function XJe(t){return t[0]}const gae=JJe(eB),Hp=qt,In=gae.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:gae.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to"})},oparen:"(",cparen:")",obrack:"[",cbrack:"]",comma:",",op:/<=|>=|<|>/,ne:"!=",eq:"=",float:/-?(?:\d+)?\.\d+(?:[Ee][+-]?\d+)?/,numberE:/-?\d+[Ee][+-]?\d+/,integer:/-?\d+/}),ZJe=In.next;In.next=(t=>()=>{for(;;){const e=t.call(In);if(e===void 0||e.type!=="WS")return e}})(ZJe);const eXe={Lexer:In,ParserRules:[{name:"numberFilter",symbols:["numberFilter","conjunction","numberUnary"],postprocess:([t,e,r])=>(0,Hp.joinNumbers)(t,e[0].text,r)},{name:"numberFilter",symbols:["numberUnary"],postprocess:t=>t[0]},{name:"numberUnary$ebnf$1",symbols:[In.has("NOT")?{type:"NOT"}:NOT],postprocess:XJe},{name:"numberUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"numberUnary",symbols:["numberUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,Hp.numNot)(e,t)},{name:"clause",symbols:[In.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause$ebnf$1",symbols:[]},{name:"clause$ebnf$1",symbols:["clause$ebnf$1","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:["N","clause$ebnf$1"],postprocess:([t,e])=>({operator:"=",...(0,Hp.mkValues)(t,e)})},{name:"clause$ebnf$2",symbols:[]},{name:"clause$ebnf$2",symbols:["clause$ebnf$2","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[In.has("eq")?{type:"eq"}:eq,"N","clause$ebnf$2"],postprocess:([t,e,r])=>({operator:"=",...(0,Hp.mkValues)(e,r)})},{name:"clause$ebnf$3",symbols:[]},{name:"clause$ebnf$3",symbols:["clause$ebnf$3","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[In.has("ne")?{type:"ne"}:ne,"N","clause$ebnf$3"],postprocess:([t,e,r])=>({operator:"!=",...(0,Hp.mkValues)(e,r)})},{name:"clause",symbols:[In.has("op")?{type:"op"}:op,"N"],postprocess:([t,e])=>({operator:t.text,values:[e]})},{name:"clause",symbols:[In.has("oparen")?{type:"oparen"}:oparen,"numberFilter",In.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:["openInterval","N",In.has("TO")?{type:"TO"}:TO,"N","closeInterval"],postprocess:([t,e,r,i,s])=>(0,Hp.mkRange)(t[0].text,e,i,s[0].text)},{name:"numberList",symbols:[In.has("comma")?{type:"comma"}:comma,"N"],postprocess:([t,e])=>e},{name:"closeInterval",symbols:[In.has("cbrack")?{type:"cbrack"}:cbrack]},{name:"closeInterval",symbols:[In.has("cparen")?{type:"cparen"}:cparen]},{name:"openInterval",symbols:[In.has("obrack")?{type:"obrack"}:obrack]},{name:"openInterval",symbols:[In.has("oparen")?{type:"oparen"}:oparen]},{name:"N$subexpression$1",symbols:[In.has("float")?{type:"float"}:float]},{name:"N$subexpression$1",symbols:[In.has("numberE")?{type:"numberE"}:numberE]},{name:"N$subexpression$1",symbols:[In.has("integer")?{type:"integer"}:integer]},{name:"N",symbols:["N$subexpression$1"],postprocess:([t])=>t[0].text},{name:"conjunction",symbols:[In.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[In.has("AND")?{type:"AND"}:AND]}],ParserStart:"numberFilter"};Z$.default=eXe;var zp={};Object.defineProperty(zp,"__esModule",{value:!0}),zp.run_parser=void 0;const tXe=Tn;function nXe(t,e){try{e.feed(t);const i=e.finish()[0];return(0,tXe.isFilterExpression)(i)?{parsed:i,log:[]}:{parsed:null,log:[]}}catch(r){let i=r.message,s=1,o=t.length;if(r.token){const u=r.token;s=u.col,o=u.text.length;const l=r.message.match(new RegExp("(?<=A ).*(?= based on:)","g")).map(c=>c.replace(/\s+token/i,""));i=`Unexpected ${u.type} token "${u.value}"`,l&&l.length&&(i+=` Tokens expected: ${[...new Set(l)]}`)}return{parsed:null,log:[{message:i,startIndex:s-1,endIndex:s-1+o-1,severity:"error"}]}}}zp.run_parser=nXe,function(t){var e=T&&T.__createBinding||(Object.create?function(c,f,x,h){h===void 0&&(h=x);var p=Object.getOwnPropertyDescriptor(f,x);(!p||("get"in p?!f.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return f[x]}}),Object.defineProperty(c,h,p)}:function(c,f,x,h){h===void 0&&(h=x),c[h]=f[x]}),r=T&&T.__setModuleDefault||(Object.create?function(c,f){Object.defineProperty(c,"default",{enumerable:!0,value:f})}:function(c,f){c.default=f}),i=T&&T.__importStar||function(c){if(c&&c.__esModule)return c;var f={};if(c!=null)for(var x in c)x!=="default"&&Object.prototype.hasOwnProperty.call(c,x)&&e(f,c,x);return r(f,c),f},s=T&&T.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.NumberFilterExpression=void 0;const o=Tn,u=i(X$),a=s(Z$),l=zp;t.NumberFilterExpression={parse(c){const f=new u.Parser(u.Grammar.fromCompiled(a.default)),x=(0,l.run_parser)(c,f);return x.parsed&&(0,o.isNumberFilter)(x.parsed)?{parsed:x.parsed,log:[]}:{parsed:null,log:x.log}},unparse(c){if(c===null)return"";switch(c.operator){case"=":return c.values.join(", ");case"!=":return"!= "+c.values.join(", ");case">":case"<":case"<=":case">=":return c.not?c.values.map(f=>c.operator==="="?`not ${f}`:`not ${c.operator} ${f}`).join(", "):c.values.map(f=>`${c.operator} ${f}`).join(", ");case"range":{const f=c.startOperator===">"?"(":"[",x=c.endOperator==="<"?")":"]",h=`${f}${c.startValue} to ${c.endValue}${x}`;return c.not?`not ${h}`:h}case"null":return c.not?"not null":"null";case"and":case"or":return c.members.map(f=>t.NumberFilterExpression.unparse(f)).join(` ${c.operator} `);case"()":{const f="("+t.NumberFilterExpression.unparse(c.expr)+")";return c.not?"not "+f:f}}return`no unparse for ${JSON.stringify(c)}`}}}(hae);var yae={},nB={},rXe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(nB,"__esModule",{value:!0});function iXe(t){return t[0]}const sXe=rXe(eB),rB=qt,fu=sXe.default.compile({WS:/[ \t]+/,comma:",",semi:";",or:"|",open:"(",close:")",minus:"-",matchStr:/(?:\\[^\n]|[^\n,;()|])+/}),oXe=fu.next;fu.next=(t=>()=>{for(;;){const e=t.call(fu);if(e==null||e.type!=="WS")return e}})(oXe);const uXe={Lexer:fu,ParserRules:[{name:"stringFilter",symbols:["stringFilter","conjunction","sfUnary"],postprocess:([t,e,r])=>(0,rB.conjoin)(t,e[0].text,r)},{name:"stringFilter",symbols:["sfUnary"],postprocess:t=>t[0]},{name:"sfUnary$ebnf$1",symbols:[fu.has("minus")?{type:"minus"}:minus],postprocess:iXe},{name:"sfUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"sfUnary",symbols:["sfUnary$ebnf$1","clause"],postprocess:t=>(0,rB.maybeNot)(t)},{name:"parens",symbols:[fu.has("open")?{type:"open"}:open,"stringFilter",fu.has("close")?{type:"close"}:close],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:[fu.has("matchStr")?{type:"matchStr"}:matchStr],postprocess:([t])=>(0,rB.matchOp)(t.text)},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"conjunction",symbols:[fu.has("comma")?{type:"comma"}:comma]},{name:"conjunction",symbols:[fu.has("semi")?{type:"semi"}:semi]},{name:"conjunction",symbols:[fu.has("or")?{type:"or"}:or]}],ParserStart:"stringFilter"};nB.default=uXe,function(t){var e=T&&T.__createBinding||(Object.create?function(f,x,h,p){p===void 0&&(p=h);var m=Object.getOwnPropertyDescriptor(x,h);(!m||("get"in m?!x.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return x[h]}}),Object.defineProperty(f,p,m)}:function(f,x,h,p){p===void 0&&(p=h),f[p]=x[h]}),r=T&&T.__setModuleDefault||(Object.create?function(f,x){Object.defineProperty(f,"default",{enumerable:!0,value:x})}:function(f,x){f.default=x}),i=T&&T.__importStar||function(f){if(f&&f.__esModule)return f;var x={};if(f!=null)for(var h in f)h!=="default"&&Object.prototype.hasOwnProperty.call(f,h)&&e(x,f,h);return r(x,f),x},s=T&&T.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.StringFilterExpression=void 0;const o=Tn,u=i(X$),a=s(nB),l=qt,c=zp;t.StringFilterExpression={parse(f){const x=new u.Parser(u.Grammar.fromCompiled(a.default)),h=(0,c.run_parser)(f,x);return h.parsed&&(0,o.isStringFilter)(h.parsed)?{parsed:h.parsed,log:[]}:{parsed:null,log:h.log}},unparse(f){if(f===null)return"";switch(f.operator){case"=":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)).join(", "):f.values.map(x=>(0,l.escape)(x)).join(", ");case"~":return f.not?f.escaped_values.map(x=>"-"+x).join(", "):f.escaped_values.join(", ");case"starts":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>(0,l.escape)(x)+"%").join(", ");case"ends":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)).join(", "):f.values.map(x=>"%"+(0,l.escape)(x)).join(", ");case"contains":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>"%"+(0,l.escape)(x)+"%").join(", ");case"or":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(" | ");case"and":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join("; ");case",":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(", ");case"()":{const x="("+t.StringFilterExpression.unparse(f.expr)+")";return f.not?"-"+x:x}case"null":return f.not?"-null":"null";case"empty":return f.not?"-empty":"empty"}}}}(yae);var Eae={},iB={},aXe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(iB,"__esModule",{value:!0});function lXe(t){return t[0]}const Aae=aXe(eB),xu=qt,Ke=Aae.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:Aae.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to",NOW:"now",LAST:"last",THIS:"this",NEXT:"next",AGO:"ago",FROM:"from",BEFORE:"before",AFTER:"after",FOR:"for",TODAY:"today",YESTERDAY:"yesterday",TOMORROW:"tomorrow",SECOND:"second",MINUTE:"minute",HOUR:"hour",DAY:"day",WEEK:"week",MONTH:"month",QUARTER:"quarter",YEAR:"year",SECONDS:"seconds",MINUTES:"minutes",HOURS:"hours",DAYS:"days",WEEKS:"weeks",MONTHS:"months",QUARTERS:"quarters",YEARS:"years",MONDAY:"monday",TUESDAY:"tuesday",WEDNESDAY:"wednesday",THURSDAY:"thursday",FRIDAY:"friday",SATURDAY:"saturday",SUNDAY:"sunday"})},oparen:"(",cparen:")",comma:",",literal:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d(?::\d\d(?:[.,]\d*))/,lit_week:/\d\d\d\d-\d\d-\d\d-[Ww][Kk]/,lit_quarter:/\d\d\d\d-[qQ][1234]/,lit_min:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d/,lit_hour:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d/,lit_day:/\d\d\d\d-\d\d-\d\d/,lit_month:/\d\d\d\d-\d\d/,lit_year:/\d\d\d\d/,n:/\d+/}),cXe=Ke.next;Ke.next=(t=>()=>{for(;;){const e=t.call(Ke);if(e===void 0||e.type!=="WS")return e}})(cXe);const fXe={Lexer:Ke,ParserRules:[{name:"temporalFilter",symbols:["temporalFilter","conjunction","temporalUnary"],postprocess:([t,e,r])=>(0,xu.joinTemporal)(t,e[0].text,r)},{name:"temporalFilter",symbols:["temporalUnary"],postprocess:t=>t[0]},{name:"temporalUnary$ebnf$1",symbols:[Ke.has("NOT")?{type:"NOT"}:NOT],postprocess:lXe},{name:"temporalUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"temporalUnary",symbols:["temporalUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,xu.temporalNot)(e,t)},{name:"duration",symbols:["number","unit"],postprocess:([t,e])=>({units:e,n:t})},{name:"number",symbols:[Ke.has("n")?{type:"n"}:n],postprocess:([t])=>t.text},{name:"number",symbols:[Ke.has("lityear")?{type:"lityear"}:lityear],postprocess:([t])=>t.text},{name:"unit$subexpression$1",symbols:[Ke.has("SECOND")?{type:"SECOND"}:SECOND]},{name:"unit$subexpression$1",symbols:[Ke.has("MINUTE")?{type:"MINUTE"}:MINUTE]},{name:"unit$subexpression$1",symbols:[Ke.has("HOUR")?{type:"HOUR"}:HOUR]},{name:"unit$subexpression$1",symbols:[Ke.has("DAY")?{type:"DAY"}:DAY]},{name:"unit$subexpression$1",symbols:[Ke.has("WEEK")?{type:"WEEK"}:WEEK]},{name:"unit$subexpression$1",symbols:[Ke.has("MONTH")?{type:"MONTH"}:MONTH]},{name:"unit$subexpression$1",symbols:[Ke.has("QUARTER")?{type:"QUARTER"}:QUARTER]},{name:"unit$subexpression$1",symbols:[Ke.has("YEAR")?{type:"YEAR"}:YEAR]},{name:"unit$subexpression$1",symbols:[Ke.has("SECONDS")?{type:"SECONDS"}:SECONDS]},{name:"unit$subexpression$1",symbols:[Ke.has("MINUTES")?{type:"MINUTES"}:MINUTES]},{name:"unit$subexpression$1",symbols:[Ke.has("HOURS")?{type:"HOURS"}:HOURS]},{name:"unit$subexpression$1",symbols:[Ke.has("DAYS")?{type:"DAYS"}:DAYS]},{name:"unit$subexpression$1",symbols:[Ke.has("WEEKS")?{type:"WEEKS"}:WEEKS]},{name:"unit$subexpression$1",symbols:[Ke.has("MONTHS")?{type:"MONTHS"}:MONTHS]},{name:"unit$subexpression$1",symbols:[Ke.has("QUARTERS")?{type:"QUARTERS"}:QUARTERS]},{name:"unit$subexpression$1",symbols:[Ke.has("YEARS")?{type:"YEARS"}:YEARS]},{name:"unit",symbols:["unit$subexpression$1"],postprocess:([t])=>(0,xu.mkUnits)(t[0].text)},{name:"clause",symbols:[Ke.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"clause",symbols:["duration"],postprocess:([t])=>({operator:"in_last",...t})},{name:"clause",symbols:[Ke.has("BEFORE")?{type:"BEFORE"}:BEFORE,"moment"],postprocess:([t,e])=>({operator:"before",before:e})},{name:"clause",symbols:[Ke.has("AFTER")?{type:"AFTER"}:AFTER,"moment"],postprocess:([t,e])=>({operator:"after",after:e})},{name:"clause",symbols:["moment",Ke.has("TO")?{type:"TO"}:TO,"moment"],postprocess:([t,e,r])=>({operator:"to",fromMoment:t,toMoment:r})},{name:"clause",symbols:["moment",Ke.has("FOR")?{type:"FOR"}:FOR,"duration"],postprocess:([t,e,r])=>({...r,operator:"for",begin:t})},{name:"clause$subexpression$1",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST]},{name:"clause$subexpression$1",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT]},{name:"clause",symbols:["clause$subexpression$1","duration"],postprocess:([t,e])=>({operator:t[0].text,...e})},{name:"clause",symbols:["moment"],postprocess:([t])=>({operator:"in",in:t})},{name:"lastNextThis",symbols:[Ke.has("THIS")?{type:"THIS"}:THIS],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST],postprocess:([t])=>t.text.toLowerCase()},{name:"moment",symbols:[Ke.has("NOW")?{type:"NOW"}:NOW],postprocess:()=>({moment:"now"})},{name:"moment",symbols:["lastNextThis","unit"],postprocess:([t,e])=>({moment:t,units:e})},{name:"moment",symbols:[Ke.has("TODAY")?{type:"TODAY"}:TODAY],postprocess:()=>({moment:"today"})},{name:"moment",symbols:[Ke.has("YESTERDAY")?{type:"YESTERDAY"}:YESTERDAY],postprocess:()=>({moment:"yesterday"})},{name:"moment",symbols:[Ke.has("TOMORROW")?{type:"TOMORROW"}:TOMORROW],postprocess:()=>({moment:"tomorrow"})},{name:"moment",symbols:["duration",Ke.has("AGO")?{type:"AGO"}:AGO],postprocess:([t,e])=>({moment:"ago",...t})},{name:"moment",symbols:["duration",Ke.has("FROM")?{type:"FROM"}:FROM,Ke.has("NOW")?{type:"NOW"}:NOW],postprocess:([t,e])=>({moment:"from_now",...t})},{name:"moment",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"next"})},{name:"moment",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"last"})},{name:"moment",symbols:["weekday"],postprocess:([t])=>({moment:t.toLowerCase(),which:"last"})},{name:"moment",symbols:["timeLiteral"],postprocess:t=>t[0]},{name:"timeLiteral",symbols:[Ke.has("literal")?{type:"literal"}:literal],postprocess:([t])=>(0,xu.timeLiteral)(t.text)},{name:"timeLiteral",symbols:[Ke.has("lit_day")?{type:"lit_day"}:lit_day],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"day")},{name:"timeLiteral",symbols:[Ke.has("lit_min")?{type:"lit_min"}:lit_min],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"minute")},{name:"timeLiteral",symbols:[Ke.has("lit_hour")?{type:"lit_hour"}:lit_hour],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"hour")},{name:"timeLiteral",symbols:[Ke.has("lit_month")?{type:"lit_month"}:lit_month],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"month")},{name:"timeLiteral",symbols:[Ke.has("lit_quarter")?{type:"lit_quarter"}:lit_quarter],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"quarter")},{name:"timeLiteral",symbols:[Ke.has("lit_week")?{type:"lit_week"}:lit_week],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"week")},{name:"timeLiteral",symbols:[Ke.has("lit_year")?{type:"lit_year"}:lit_year],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"year")},{name:"weekday$subexpression$1",symbols:[Ke.has("MONDAY")?{type:"MONDAY"}:MONDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("TUESDAY")?{type:"TUESDAY"}:TUESDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("WEDNESDAY")?{type:"WEDNESDAY"}:WEDNESDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("THURSDAY")?{type:"THURSDAY"}:THURSDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("FRIDAY")?{type:"FRIDAY"}:FRIDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("SATURDAY")?{type:"SATURDAY"}:SATURDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("SUNDAY")?{type:"SUNDAY"}:SUNDAY]},{name:"weekday",symbols:["weekday$subexpression$1"],postprocess:([t])=>t[0].text},{name:"parens",symbols:[Ke.has("oparen")?{type:"oparen"}:oparen,"temporalFilter",Ke.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"conjunction",symbols:[Ke.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Ke.has("AND")?{type:"AND"}:AND]}],ParserStart:"temporalFilter"};iB.default=fXe,function(t){var e=T&&T.__createBinding||(Object.create?function(h,p,m,y){y===void 0&&(y=m);var g=Object.getOwnPropertyDescriptor(p,m);(!g||("get"in g?!p.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(h,y,g)}:function(h,p,m,y){y===void 0&&(y=m),h[y]=p[m]}),r=T&&T.__setModuleDefault||(Object.create?function(h,p){Object.defineProperty(h,"default",{enumerable:!0,value:p})}:function(h,p){h.default=p}),i=T&&T.__importStar||function(h){if(h&&h.__esModule)return h;var p={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&e(p,h,m);return r(p,h),p},s=T&&T.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=void 0;const o=Tn,u=s(iB),a=i(X$),l=zp;t.TemporalFilterExpression={parse(h){const p=new a.Parser(a.Grammar.fromCompiled(u.default)),m=(0,l.run_parser)(h,p);return m.parsed&&(0,o.isTemporalFilter)(m.parsed)?{parsed:m.parsed,log:[]}:{parsed:null,log:m.log}},unparse(h){if(h===null)return"";switch(h.operator){case"null":return c(h,"null");case"in":return c(h,x(h.in));case"()":return"("+t.TemporalFilterExpression.unparse(h.expr)+")";case"in_last":return c(h,f(h));case"last":case"next":return c(h,`${h.operator} ${f(h)}`);case"before":return c(h,`before ${x(h.before)}`);case"after":return c(h,`after ${x(h.after)}`);case"to":return c(h,`${x(h.fromMoment)} to ${x(h.toMoment)}`);case"for":return c(h,`${x(h.begin)} for ${f(h)}`);case"or":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" or ");case"and":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" and ")}}};function c(h,p){return"not"in h&&h.not?"not "+p:p}function f(h){return h.n==="1"?`1 ${h.units}`:`${h.n} ${h.units}s`}function x(h){switch(h.moment){case"literal":return h.literal;case"now":case"today":case"yesterday":case"tomorrow":return h.moment;case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":return h.which==="next"?"next "+h.moment:h.moment;case"this":case"next":case"last":return`${h.moment} ${h.units}`;case"ago":return`${f(h)} ago`;case"from_now":return`${f(h)} from now`}}}(Eae),function(t){var e=T&&T.__createBinding||(Object.create?function(a,l,c,f){f===void 0&&(f=c);var x=Object.getOwnPropertyDescriptor(l,c);(!x||("get"in x?!l.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return l[c]}}),Object.defineProperty(a,f,x)}:function(a,l,c,f){f===void 0&&(f=c),a[f]=l[c]}),r=T&&T.__exportStar||function(a,l){for(var c in a)c!=="default"&&!Object.prototype.hasOwnProperty.call(l,c)&&e(l,a,c)};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=t.StringFilterExpression=t.NumberFilterExpression=t.BooleanFilterExpression=void 0,r(Tn,t);var i=U4;Object.defineProperty(t,"BooleanFilterExpression",{enumerable:!0,get:function(){return i.BooleanFilterExpression}});var s=hae;Object.defineProperty(t,"NumberFilterExpression",{enumerable:!0,get:function(){return s.NumberFilterExpression}});var o=yae;Object.defineProperty(t,"StringFilterExpression",{enumerable:!0,get:function(){return o.StringFilterExpression}});var u=Eae;Object.defineProperty(t,"TemporalFilterExpression",{enumerable:!0,get:function(){return u.TemporalFilterExpression}})}(P4);var q4={};const Cy=AP(V1e);Object.defineProperty(q4,"__esModule",{value:!0}),q4.TemporalFilterCompiler=void 0;const sB=Xe,Zx=Cy,_ae="yyyy",vae=`${_ae}-LL`,oB=`${vae}-dd`,Cae=`${oB} HH`,Sae=`${Cae}:mm`,xs=`${Sae}:ss`;class xXe{constructor(e,r,i="timestamp"){this.expr=e,this.timetype=i,this.d=r}time(e){return this.timetype==="timestamp"?e:this.d.sqlCast({},{node:"cast",e:{node:"genericSQLExpr",src:["",e],kids:{args:[]},sql:e},srcType:{type:"timestamp"},dstType:{type:"date"},safe:!1})}compile(e){const r=this.expr;switch(e.operator){case"after":return`${r} ${e.not?"<":">="} ${this.time(this.moment(e.after).end)}`;case"before":return`${r} ${e.not?">=":"<"} ${this.time(this.moment(e.before).begin.sql)}`;case"in":{const i=this.moment(e.in);return i.begin.sql===i.end?e.not?`${r} != ${this.time(i.end)} OR ${r} IS NULL`:`${r} = ${this.time(i.end)}`:this.isIn(e.not,i.begin.sql,i.end)}case"for":{const i=this.moment(e.begin),s=this.delta(i.begin,"+",e.n,e.units);return this.isIn(e.not,i.begin.sql,s.sql)}case"in_last":{const i=Number(e.n)-1,s=this.nowDot(e.units),o=i>0?this.delta(s,"-",i.toString(),e.units):s,u=this.delta(s,"+","1",e.units);return this.isIn(e.not,o.sql,u.sql)}case"to":{const i=this.moment(e.fromMoment),s=this.moment(e.toMoment);return this.isIn(e.not,i.begin.sql,s.begin.sql)}case"last":{const i=this.nowDot(e.units),s=this.delta(i,"-",e.n,e.units);return this.isIn(e.not,s.sql,i.sql)}case"next":{const i=this.nowDot(e.units),s=this.delta(i,"+","1",e.units),o=this.delta(i,"+",(Number(e.n)+1).toString(),e.units);return this.isIn(e.not,s.sql,o.sql)}case"null":return e.not?`${r} IS NOT NULL`:`${r} IS NULL`;case"()":{const i="("+this.compile(e.expr)+")";return e.not?`NOT ${i}`:i}case"and":case"or":return e.members.map(i=>this.compile(i)).join(` ${e.operator.toUpperCase()} `)}}expandLiteral(e){let r=e.literal;switch(e.units){case"year":{const i=Zx.DateTime.fromFormat(r,_ae),s=this.literalNode(i.toFormat(xs)),o=i.plus({year:1});return{begin:s,end:this.literalNode(o.toFormat(xs)).sql}}case"month":{const i=Zx.DateTime.fromFormat(r,vae),s=this.literalNode(i.toFormat(xs)),o=i.plus({month:1});return{begin:s,end:this.literalNode(o.toFormat(xs)).sql}}case"day":{const i=Zx.DateTime.fromFormat(r,oB),s=this.literalNode(i.toFormat(xs)),o=i.plus({day:1});return{begin:s,end:this.literalNode(o.toFormat(xs)).sql}}case"hour":{const i=Zx.DateTime.fromFormat(r,Cae),s=this.literalNode(i.toFormat(xs)),o=i.plus({hour:1});return{begin:s,end:this.literalNode(o.toFormat(xs)).sql}}case"minute":{const i=Zx.DateTime.fromFormat(r,Sae),s=this.literalNode(i.toFormat(xs)),o=i.plus({minute:1});return{begin:s,end:this.literalNode(o.toFormat(xs)).sql}}case"week":{const o=Zx.DateTime.fromFormat(r.slice(0,10),oB).plus({day:1}).startOf("week").minus({day:1}),u=this.literalNode(o.toFormat(xs)),a=o.plus({days:7});return{begin:u,end:this.literalNode(a.toFormat(xs)).sql}}case"quarter":{const i=r.slice(0,4),s=r.slice(6);s==="1"?r=`${i}-01-01 00:00:00`:s==="2"?r=`${i}-03-01 00:00:00`:s==="3"?r=`${i}-06-01 00:00:00`:r=`${i}-09-01 00:00:00`;const o=this.literalNode(r),a=Zx.DateTime.fromFormat(r,xs).plus({months:3});return{begin:o,end:this.literalNode(a.toFormat(xs)).sql}}case void 0:case"second":return{begin:this.literalNode(r),end:r}}}literalNode(e){const r={node:"timeLiteral",typeDef:{type:"timestamp"},literal:e};return{...r,sql:this.d.sqlLiteralTime({},r)}}nowExpr(){return{node:"now",typeDef:{type:"timestamp"},sql:this.d.sqlNowExpr()}}n(e){return{node:"numberLiteral",literal:e,sql:e}}delta(e,r,i,s){const o={node:"delta",op:r,units:s,kids:{base:(0,sB.mkTemporal)(e,"timestamp"),delta:this.n(i)}};return{...o,sql:this.d.sqlAlterTimeExpr(o)}}dayofWeek(e){const r={node:"extract",e:(0,sB.mkTemporal)(e,"timestamp"),units:"day_of_week"};return{...r,sql:this.d.sqlTimeExtractExpr({},r)}}nowDot(e){const r={node:"trunc",e:this.nowExpr(),units:e};return{...r,sql:this.d.sqlTruncExpr({},r)}}thisUnit(e){const r=this.nowDot(e),i=this.delta(r,"+","1",e);return{begin:r,end:i.sql}}lastUnit(e){const r=this.nowDot(e);return{begin:this.delta(r,"-","1",e),end:r.sql}}nextUnit(e){const r=this.nowDot(e),i=this.delta(r,"+","1",e),s=this.delta(r,"+","2",e);return{begin:i,end:s.sql}}mod7(e){return this.d.hasModOperator?`(${e})%7`:`MOD(${e},7)`}moment(e){switch(e.moment){case"now":{const r=this.nowExpr();return{begin:r,end:r.sql}}case"literal":return this.expandLiteral(e);case"ago":case"from_now":{const r=this.nowDot(e.units),i=(0,sB.mkTemporal)(r,"timestamp"),s=this.delta(i,e.moment==="ago"?"-":"+",e.n,e.units);if(e.moment==="ago"&&e.n==="1")return{begin:s,end:r.sql};const o=Number(e.n)+(e.moment==="ago"?-1:1),u={...s,kids:{base:i,delta:this.n(o.toString())}};return{begin:s,end:this.d.sqlAlterTimeExpr(u)}}case"today":return this.thisUnit("day");case"yesterday":return this.lastUnit("day");case"tomorrow":return this.nextUnit("day");case"this":return this.thisUnit(e.units);case"last":return this.lastUnit(e.units);case"next":return this.nextUnit(e.units);case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":{const r=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].indexOf(e.moment),i=this.dayofWeek(this.nowExpr()).sql;if(e.which==="next"){const a=`${this.mod7(`${r}-(${i}-1)+6`)}+1`,l=this.delta(this.thisUnit("day").begin,"+",a,"day"),c=this.delta(this.thisUnit("day").begin,"+",`${a}+1`,"day");return{begin:l,end:c.sql}}const s=`${this.mod7(`(${i}-1)-${r}+6`)}+1`,o=this.delta(this.thisUnit("day").begin,"-",s,"day"),u=this.delta(this.thisUnit("day").begin,"-",`(${s})-1`,"day");return{begin:o,end:u.sql}}}}isIn(e,r,i){let s=">=",o="<",u="AND";return e&&(u="OR",s="<",o=">="),r=this.time(r),i=this.time(i),`${this.expr} ${s} ${r} ${u} ${this.expr} ${o} ${i}`}}q4.TemporalFilterCompiler=xXe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.FilterCompilers=void 0;const e=P4,r=q4;function i(u){return u.replace(/([%_\\])/g,"\\$1")}function s(u){return u===">"?"<=":u==="<"?">=":u===">="?"<":">"}function o(u,a){const l=` OR ${a} IS NULL`;return u.length===1?`${u[0]}${l}`:`(${u.join(" AND ")})${l}`}t.FilterCompilers={compile(u,a,l,c){if(u==="string"&&(0,e.isStringFilter)(a))return t.FilterCompilers.stringCompile(a,l,c);if(u==="number"&&(0,e.isNumberFilter)(a))return t.FilterCompilers.numberCompile(a,l,c);if(u==="boolean"&&(0,e.isBooleanFilter)(a))return t.FilterCompilers.booleanCompile(a,l,c);if((u==="date"||u==="timestamp")&&(0,e.isTemporalFilter)(a))return t.FilterCompilers.temporalCompile(a,l,c,u);throw new Error("INTERNAL ERROR: No filter compiler for "+u)},numberCompile(u,a,l){switch(u.operator){case"!=":case"=":{const c=u.operator==="="&&u.not||u.operator==="!="&&!u.not,f=u.values.join(", ");return u.values.length===1?c?`${a} != ${f} OR ${a} IS NULL`:`${a} = ${f}`:c?`${a} NOT IN (${f}) OR ${a} IS NULL`:`${a} IN (${f})`}case">":case"<":case">=":case"<=":return u.values.map(c=>`${a} ${u.operator} ${c}`).join(u.not?" AND ":" OR ");case"range":{let c=u.startOperator,f=u.endOperator,x=" AND ";return u.not&&(c=s(c),f=s(f),x=" OR "),`${a} ${c} ${u.startValue} ${x} ${a} ${f} ${u.endValue}`}case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"()":{const c="("+t.FilterCompilers.numberCompile(u.expr,a,l)+")";return u.not?`NOT ${c}`:c}case"and":case"or":return u.members.map(c=>t.FilterCompilers.numberCompile(c,a,l)).join(` ${u.operator.toUpperCase()} `)}},booleanCompile(u,a,l){switch(u.operator){case"false":return`${a} = false`;case"false_or_null":return`${a} IS NULL OR ${a} = false`;case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"true":return a}},stringCompile(u,a,l){switch(u.operator){case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"empty":return u.not?`COALESCE(${a},'') != ''`:`COALESCE(${a},'') = ''`;case"=":{if(u.values.length===1){const f=u.not?"!=":"=",x=`${a} ${f} ${l.sqlLiteralString(u.values[0])}`;return u.not?`(${x} OR ${a} IS NULL)`:x}const c="("+u.values.map(f=>l.sqlLiteralString(f)).join(", ")+")";return u.not?`(${a} NOT IN ${c} OR ${a} IS NULL)`:`${a} IN ${c}`}case"()":{const c="("+t.FilterCompilers.stringCompile(u.expr,a,l)+")";return u.not?`not ${c}`:c}case"contains":{const c=u.values.map(f=>"%"+i(f)+"%");return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"starts":{const c=u.values.map(f=>i(f)+"%");return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"ends":{const c=u.values.map(f=>"%"+i(f));return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"~":return u.not?o(u.escaped_values.map(c=>l.sqlLike("NOT LIKE",a,c)),a):u.escaped_values.map(c=>l.sqlLike("LIKE",a,c)).join(" OR ");case"and":return u.members.map(f=>t.FilterCompilers.stringCompile(f,a,l)).join(" AND ");case"or":return u.members.map(f=>t.FilterCompilers.stringCompile(f,a,l)).join(" AND ");case",":{const c=[],f=[];let x=!1,h=!1,p=!1,m=!1;for(const E of u.members)switch(E.operator){case"or":case"and":case",":c.push(E);break;case"null":E.not?h=!0:x=!0;break;case"empty":E.not?(m=!0,h=!0):(p=!0,x=!0);break;default:(E.not?f:c).push(E)}if(p&&m||x&&h)return"false";let y="";if(c.length>0||x||p){m=!1,h=!1;const E=c.map(A=>t.FilterCompilers.stringCompile(A,a,l));p&&E.push(`${a} = ''`),x&&E.push(`${a} IS NULL`),y=E.join(" OR ")}let g="";if(f.length>0||m||h){const E=f.map(A=>t.FilterCompilers.stringCompile(A,a,l));m&&E.push(`${a} != ''`),h&&E.push(`${a} IS NOT NULL`),g=E.join(" AND ")}return y?g!==""?`(${y}) AND (${g})`:y:g!==""?g:"true"}}},temporalCompile(u,a,l,c){return new r.TemporalFilterCompiler(a,l,c).compile(u)}}}(dae),Object.defineProperty($s,"__esModule",{value:!0}),$s.QueryModel=$s.getResultStructDefForQuery=$s.getResultStructDefForView=$s.Segment=void 0;const dXe=Up,hXe=Mp,pXe=Ey,ke=Xe,Rn=$t,Q4=Qp,mXe=ai,gXe=dae,yXe=P4;function bae(t){return t.map(e=>encodeURIComponent(e)).join("/")}function uB(t){return`'${t}'`}function EXe(t){return t.replace(/[^a-zA-Z0-9_]/g,"_o_")}function Gp(t){const e=[];for(const r of t.fields.filter(ke.fieldIsIntrinsic))e.push({type:r.type,sqlExpression:(0,ke.getIdentifier)(r),rawName:(0,ke.getIdentifier)(r),sqlOutputName:(0,ke.getIdentifier)(r)});return e}class AXe extends Set{add_use(e){if(e!==void 0)return this.add(e)}hasAsymetricFunctions(){return this.has("sum")||this.has("avg")||this.has("count")||this.has("generic_asymmetric_aggregate")}}class Sy{constructor(e=!0,r){this.parent=r,this.withs=[],this.udfs=[],this.pdts=[],this.dependenciesToMaterialize={},this.stagePrefix="__stage",this.useCTE=e}getName(e){return`${this.stagePrefix}${e}`}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){return this.useCTE?(this.withs.push(e),this.getName(this.withs.length-1)):(this.withs[0]=e,(0,Rn.indent)(`
|
|
1045
|
+
`)},S.prototype.clone=function(){return new S(this.states,this.state)},S.prototype.has=function(D){return!0},{compile:_,states:C,error:Object.freeze({error:!0}),fallback:Object.freeze({fallback:!0}),keywords:b}})})(mae);var eB=mae.exports,qt={};Object.defineProperty(qt,"__esModule",{value:!0}),qt.mkUnits=qt.timeLiteral=qt.joinTemporal=qt.temporalNot=qt.numNot=qt.mkValues=qt.mkRange=qt.joinNumbers=qt.conjoin=qt.matchOp=qt.escape=qt.unescape=qt.maybeNot=void 0;const Sa=Tn;function PJe(t){const[e,r]=t;return e&&r&&(0,Sa.isStringFilter)(r)?{...r,not:!0}:r}qt.maybeNot=PJe;function vy(t){return t.replace(/\\(.)/g,"$1")}qt.unescape=vy;function UJe(t){const e=t.toLowerCase();return e==="null"||e==="empty"?"\\"+t:t.replace(/([,; |()\\%_-])/g,"\\$1")}qt.escape=UJe;function j4(t){let e=!1,r=!1,i=0,s=!1;const o=t.length;for(let u=0;u<o;u+=1){const a=t[u];if(a===" "||a===" "){i+=1;continue}i=0,a==="%"?(s=!0,u===0&&(e=!0),r=!0):(r=!1,a==="\\"?u+=1:a==="_"&&(s=!0))}return{hasLike:s,percentEnd:r&&o>1,percentStart:e&&o>1,endSpace:i}}function jJe(t){let e=t.trimStart();const{hasLike:r,percentEnd:i,percentStart:s,endSpace:o}=j4(e);if(o>0&&(e=e.slice(0,-o)),r){if(s&&i){const u=e.slice(1,-1);if(!j4(u).hasLike&&u.length>0)return{operator:"contains",values:[vy(u)]}}else if(i){const u=e.slice(0,-1);if(!j4(u).hasLike)return{operator:"starts",values:[vy(u)]}}else if(s){const u=e.slice(1);if(!j4(u).hasLike)return{operator:"ends",values:[vy(u)]}}return{operator:"~",escaped_values:[e]}}return e.toLowerCase()==="null"||e==="NULL"?{operator:"null"}:e==="empty"||e==="EMPTY"?{operator:"empty"}:{operator:"=",values:[vy(e)]}}qt.matchOp=jJe;function tB(t,e){var r,i;return t.operator===e.operator&&((r=t.not)!==null&&r!==void 0?r:!1)===((i=e.not)!==null&&i!==void 0?i:!1)}function qJe(t,e,r){if((0,Sa.isStringFilter)(t)&&(0,Sa.isStringFilter)(r)){if(e===","){if(t.operator==="~"&&tB(t,r))return{...t,escaped_values:[...t.escaped_values,...r.escaped_values]};if((0,Sa.isStringCondition)(t)&&tB(t,r))return{...t,values:[...t.values,...r.values]}}const i=e===","?",":e==="|"?"or":e===";"?"and":void 0;if(i)return t.operator===i?{...t,members:[...t.members,r]}:{operator:i,members:[t,r]}}return null}qt.conjoin=qJe;function QJe(t,e,r){if((0,Sa.isNumberFilter)(t)&&(0,Sa.isNumberFilter)(r)){if(e==="or"&&t.operator==="="&&tB(t,r)){const i={operator:"=",values:[...t.values,...r.values]};return t.not&&(i.not=!0),i}if(e==="and"||e==="or")return t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}}return null}qt.joinNumbers=QJe;function HJe(t,e,r,i){return{operator:"range",startValue:e,startOperator:t==="("?">":">=",endValue:r,endOperator:i===")"?"<":"<="}}qt.mkRange=HJe;function zJe(t,e){return{values:[t,...e]}}qt.mkValues=zJe;function GJe(t,e){return(0,Sa.isNumberFilter)(t)&&e?t.operator==="="?{operator:"!=",values:t.values}:t.operator==="!="?{operator:"=",values:t.values}:{...t,not:!0}:t}qt.numNot=GJe;function WJe(t,e){return(0,Sa.isTemporalFilter)(t)&&e?{...t,not:!0}:t}qt.temporalNot=WJe;function VJe(t,e,r){return(0,Sa.isTemporalFilter)(t)&&(0,Sa.isTemporalFilter)(r)&&(e==="and"||e==="or")?t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}:null}qt.joinTemporal=VJe;function YJe(t,e){const r={moment:"literal",literal:t};return e&&(r.units=e),r}qt.timeLiteral=YJe;function KJe(t){switch(t.toLowerCase()){case"second":case"seconds":return"second";case"minute":case"minutes":return"minute";case"hour":case"hours":return"hour";case"day":case"days":return"day";case"week":case"weeks":return"week";case"month":case"months":return"month";case"quarter":case"quarters":return"quarter";case"year":case"years":return"year"}}qt.mkUnits=KJe;var JJe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Z$,"__esModule",{value:!0});function XJe(t){return t[0]}const gae=JJe(eB),Hp=qt,In=gae.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:gae.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to"})},oparen:"(",cparen:")",obrack:"[",cbrack:"]",comma:",",op:/<=|>=|<|>/,ne:"!=",eq:"=",float:/-?(?:\d+)?\.\d+(?:[Ee][+-]?\d+)?/,numberE:/-?\d+[Ee][+-]?\d+/,integer:/-?\d+/}),ZJe=In.next;In.next=(t=>()=>{for(;;){const e=t.call(In);if(e===void 0||e.type!=="WS")return e}})(ZJe);const eXe={Lexer:In,ParserRules:[{name:"numberFilter",symbols:["numberFilter","conjunction","numberUnary"],postprocess:([t,e,r])=>(0,Hp.joinNumbers)(t,e[0].text,r)},{name:"numberFilter",symbols:["numberUnary"],postprocess:t=>t[0]},{name:"numberUnary$ebnf$1",symbols:[In.has("NOT")?{type:"NOT"}:NOT],postprocess:XJe},{name:"numberUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"numberUnary",symbols:["numberUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,Hp.numNot)(e,t)},{name:"clause",symbols:[In.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause$ebnf$1",symbols:[]},{name:"clause$ebnf$1",symbols:["clause$ebnf$1","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:["N","clause$ebnf$1"],postprocess:([t,e])=>({operator:"=",...(0,Hp.mkValues)(t,e)})},{name:"clause$ebnf$2",symbols:[]},{name:"clause$ebnf$2",symbols:["clause$ebnf$2","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[In.has("eq")?{type:"eq"}:eq,"N","clause$ebnf$2"],postprocess:([t,e,r])=>({operator:"=",...(0,Hp.mkValues)(e,r)})},{name:"clause$ebnf$3",symbols:[]},{name:"clause$ebnf$3",symbols:["clause$ebnf$3","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[In.has("ne")?{type:"ne"}:ne,"N","clause$ebnf$3"],postprocess:([t,e,r])=>({operator:"!=",...(0,Hp.mkValues)(e,r)})},{name:"clause",symbols:[In.has("op")?{type:"op"}:op,"N"],postprocess:([t,e])=>({operator:t.text,values:[e]})},{name:"clause",symbols:[In.has("oparen")?{type:"oparen"}:oparen,"numberFilter",In.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:["openInterval","N",In.has("TO")?{type:"TO"}:TO,"N","closeInterval"],postprocess:([t,e,r,i,s])=>(0,Hp.mkRange)(t[0].text,e,i,s[0].text)},{name:"numberList",symbols:[In.has("comma")?{type:"comma"}:comma,"N"],postprocess:([t,e])=>e},{name:"closeInterval",symbols:[In.has("cbrack")?{type:"cbrack"}:cbrack]},{name:"closeInterval",symbols:[In.has("cparen")?{type:"cparen"}:cparen]},{name:"openInterval",symbols:[In.has("obrack")?{type:"obrack"}:obrack]},{name:"openInterval",symbols:[In.has("oparen")?{type:"oparen"}:oparen]},{name:"N$subexpression$1",symbols:[In.has("float")?{type:"float"}:float]},{name:"N$subexpression$1",symbols:[In.has("numberE")?{type:"numberE"}:numberE]},{name:"N$subexpression$1",symbols:[In.has("integer")?{type:"integer"}:integer]},{name:"N",symbols:["N$subexpression$1"],postprocess:([t])=>t[0].text},{name:"conjunction",symbols:[In.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[In.has("AND")?{type:"AND"}:AND]}],ParserStart:"numberFilter"};Z$.default=eXe;var zp={};Object.defineProperty(zp,"__esModule",{value:!0}),zp.run_parser=void 0;const tXe=Tn;function nXe(t,e){try{e.feed(t);const i=e.finish()[0];return(0,tXe.isFilterExpression)(i)?{parsed:i,log:[]}:{parsed:null,log:[]}}catch(r){let i=r.message,s=1,o=t.length;if(r.token){const u=r.token;s=u.col,o=u.text.length;const l=r.message.match(new RegExp("(?<=A ).*(?= based on:)","g")).map(c=>c.replace(/\s+token/i,""));i=`Unexpected ${u.type} token "${u.value}"`,l&&l.length&&(i+=` Tokens expected: ${[...new Set(l)]}`)}return{parsed:null,log:[{message:i,startIndex:s-1,endIndex:s-1+o-1,severity:"error"}]}}}zp.run_parser=nXe,function(t){var e=T&&T.__createBinding||(Object.create?function(c,f,x,h){h===void 0&&(h=x);var p=Object.getOwnPropertyDescriptor(f,x);(!p||("get"in p?!f.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return f[x]}}),Object.defineProperty(c,h,p)}:function(c,f,x,h){h===void 0&&(h=x),c[h]=f[x]}),r=T&&T.__setModuleDefault||(Object.create?function(c,f){Object.defineProperty(c,"default",{enumerable:!0,value:f})}:function(c,f){c.default=f}),i=T&&T.__importStar||function(c){if(c&&c.__esModule)return c;var f={};if(c!=null)for(var x in c)x!=="default"&&Object.prototype.hasOwnProperty.call(c,x)&&e(f,c,x);return r(f,c),f},s=T&&T.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.NumberFilterExpression=void 0;const o=Tn,u=i(X$),a=s(Z$),l=zp;t.NumberFilterExpression={parse(c){if(c.match(/^\s*$/))return{parsed:null,log:[]};const f=new u.Parser(u.Grammar.fromCompiled(a.default)),x=(0,l.run_parser)(c,f);return x.parsed&&(0,o.isNumberFilter)(x.parsed)?{parsed:x.parsed,log:[]}:{parsed:null,log:x.log}},unparse(c){if(c===null)return"";switch(c.operator){case"=":return c.values.join(", ");case"!=":return"!= "+c.values.join(", ");case">":case"<":case"<=":case">=":return c.not?c.values.map(f=>c.operator==="="?`not ${f}`:`not ${c.operator} ${f}`).join(", "):c.values.map(f=>`${c.operator} ${f}`).join(", ");case"range":{const f=c.startOperator===">"?"(":"[",x=c.endOperator==="<"?")":"]",h=`${f}${c.startValue} to ${c.endValue}${x}`;return c.not?`not ${h}`:h}case"null":return c.not?"not null":"null";case"and":case"or":return c.members.map(f=>t.NumberFilterExpression.unparse(f)).join(` ${c.operator} `);case"()":{const f="("+t.NumberFilterExpression.unparse(c.expr)+")";return c.not?"not "+f:f}}return`no unparse for ${JSON.stringify(c)}`}}}(hae);var yae={},nB={},rXe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(nB,"__esModule",{value:!0});function iXe(t){return t[0]}const sXe=rXe(eB),rB=qt,fu=sXe.default.compile({WS:/[ \t]+/,comma:",",semi:";",or:"|",open:"(",close:")",minus:"-",matchStr:/(?:\\[^\n]|[^\n,;()|])+/}),oXe=fu.next;fu.next=(t=>()=>{for(;;){const e=t.call(fu);if(e==null||e.type!=="WS")return e}})(oXe);const uXe={Lexer:fu,ParserRules:[{name:"stringFilter",symbols:["stringFilter","conjunction","sfUnary"],postprocess:([t,e,r])=>(0,rB.conjoin)(t,e[0].text,r)},{name:"stringFilter",symbols:["sfUnary"],postprocess:t=>t[0]},{name:"sfUnary$ebnf$1",symbols:[fu.has("minus")?{type:"minus"}:minus],postprocess:iXe},{name:"sfUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"sfUnary",symbols:["sfUnary$ebnf$1","clause"],postprocess:t=>(0,rB.maybeNot)(t)},{name:"parens",symbols:[fu.has("open")?{type:"open"}:open,"stringFilter",fu.has("close")?{type:"close"}:close],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:[fu.has("matchStr")?{type:"matchStr"}:matchStr],postprocess:([t])=>(0,rB.matchOp)(t.text)},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"conjunction",symbols:[fu.has("comma")?{type:"comma"}:comma]},{name:"conjunction",symbols:[fu.has("semi")?{type:"semi"}:semi]},{name:"conjunction",symbols:[fu.has("or")?{type:"or"}:or]}],ParserStart:"stringFilter"};nB.default=uXe,function(t){var e=T&&T.__createBinding||(Object.create?function(f,x,h,p){p===void 0&&(p=h);var m=Object.getOwnPropertyDescriptor(x,h);(!m||("get"in m?!x.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return x[h]}}),Object.defineProperty(f,p,m)}:function(f,x,h,p){p===void 0&&(p=h),f[p]=x[h]}),r=T&&T.__setModuleDefault||(Object.create?function(f,x){Object.defineProperty(f,"default",{enumerable:!0,value:x})}:function(f,x){f.default=x}),i=T&&T.__importStar||function(f){if(f&&f.__esModule)return f;var x={};if(f!=null)for(var h in f)h!=="default"&&Object.prototype.hasOwnProperty.call(f,h)&&e(x,f,h);return r(x,f),x},s=T&&T.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.StringFilterExpression=void 0;const o=Tn,u=i(X$),a=s(nB),l=qt,c=zp;t.StringFilterExpression={parse(f){if(f.match(/^\s*$/))return{parsed:null,log:[]};const x=new u.Parser(u.Grammar.fromCompiled(a.default)),h=(0,c.run_parser)(f,x);return h.parsed&&(0,o.isStringFilter)(h.parsed)?{parsed:h.parsed,log:[]}:{parsed:null,log:h.log}},unparse(f){if(f===null)return"";switch(f.operator){case"=":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)).join(", "):f.values.map(x=>(0,l.escape)(x)).join(", ");case"~":return f.not?f.escaped_values.map(x=>"-"+x).join(", "):f.escaped_values.join(", ");case"starts":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>(0,l.escape)(x)+"%").join(", ");case"ends":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)).join(", "):f.values.map(x=>"%"+(0,l.escape)(x)).join(", ");case"contains":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>"%"+(0,l.escape)(x)+"%").join(", ");case"or":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(" | ");case"and":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join("; ");case",":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(", ");case"()":{const x="("+t.StringFilterExpression.unparse(f.expr)+")";return f.not?"-"+x:x}case"null":return f.not?"-null":"null";case"empty":return f.not?"-empty":"empty"}}}}(yae);var Eae={},iB={},aXe=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(iB,"__esModule",{value:!0});function lXe(t){return t[0]}const Aae=aXe(eB),xu=qt,Ke=Aae.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:Aae.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to",NOW:"now",LAST:"last",THIS:"this",NEXT:"next",AGO:"ago",FROM:"from",BEFORE:"before",AFTER:"after",FOR:"for",TODAY:"today",YESTERDAY:"yesterday",TOMORROW:"tomorrow",SECOND:"second",MINUTE:"minute",HOUR:"hour",DAY:"day",WEEK:"week",MONTH:"month",QUARTER:"quarter",YEAR:"year",SECONDS:"seconds",MINUTES:"minutes",HOURS:"hours",DAYS:"days",WEEKS:"weeks",MONTHS:"months",QUARTERS:"quarters",YEARS:"years",MONDAY:"monday",TUESDAY:"tuesday",WEDNESDAY:"wednesday",THURSDAY:"thursday",FRIDAY:"friday",SATURDAY:"saturday",SUNDAY:"sunday"})},oparen:"(",cparen:")",comma:",",literal:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d(?::\d\d(?:[.,]\d*))/,lit_week:/\d\d\d\d-\d\d-\d\d-[Ww][Kk]/,lit_quarter:/\d\d\d\d-[qQ][1234]/,lit_min:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d/,lit_hour:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d/,lit_day:/\d\d\d\d-\d\d-\d\d/,lit_month:/\d\d\d\d-\d\d/,lit_year:/\d\d\d\d/,n:/\d+/}),cXe=Ke.next;Ke.next=(t=>()=>{for(;;){const e=t.call(Ke);if(e===void 0||e.type!=="WS")return e}})(cXe);const fXe={Lexer:Ke,ParserRules:[{name:"temporalFilter",symbols:["temporalFilter","conjunction","temporalUnary"],postprocess:([t,e,r])=>(0,xu.joinTemporal)(t,e[0].text,r)},{name:"temporalFilter",symbols:["temporalUnary"],postprocess:t=>t[0]},{name:"temporalUnary$ebnf$1",symbols:[Ke.has("NOT")?{type:"NOT"}:NOT],postprocess:lXe},{name:"temporalUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"temporalUnary",symbols:["temporalUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,xu.temporalNot)(e,t)},{name:"duration",symbols:["number","unit"],postprocess:([t,e])=>({units:e,n:t})},{name:"number",symbols:[Ke.has("n")?{type:"n"}:n],postprocess:([t])=>t.text},{name:"number",symbols:[Ke.has("lityear")?{type:"lityear"}:lityear],postprocess:([t])=>t.text},{name:"unit$subexpression$1",symbols:[Ke.has("SECOND")?{type:"SECOND"}:SECOND]},{name:"unit$subexpression$1",symbols:[Ke.has("MINUTE")?{type:"MINUTE"}:MINUTE]},{name:"unit$subexpression$1",symbols:[Ke.has("HOUR")?{type:"HOUR"}:HOUR]},{name:"unit$subexpression$1",symbols:[Ke.has("DAY")?{type:"DAY"}:DAY]},{name:"unit$subexpression$1",symbols:[Ke.has("WEEK")?{type:"WEEK"}:WEEK]},{name:"unit$subexpression$1",symbols:[Ke.has("MONTH")?{type:"MONTH"}:MONTH]},{name:"unit$subexpression$1",symbols:[Ke.has("QUARTER")?{type:"QUARTER"}:QUARTER]},{name:"unit$subexpression$1",symbols:[Ke.has("YEAR")?{type:"YEAR"}:YEAR]},{name:"unit$subexpression$1",symbols:[Ke.has("SECONDS")?{type:"SECONDS"}:SECONDS]},{name:"unit$subexpression$1",symbols:[Ke.has("MINUTES")?{type:"MINUTES"}:MINUTES]},{name:"unit$subexpression$1",symbols:[Ke.has("HOURS")?{type:"HOURS"}:HOURS]},{name:"unit$subexpression$1",symbols:[Ke.has("DAYS")?{type:"DAYS"}:DAYS]},{name:"unit$subexpression$1",symbols:[Ke.has("WEEKS")?{type:"WEEKS"}:WEEKS]},{name:"unit$subexpression$1",symbols:[Ke.has("MONTHS")?{type:"MONTHS"}:MONTHS]},{name:"unit$subexpression$1",symbols:[Ke.has("QUARTERS")?{type:"QUARTERS"}:QUARTERS]},{name:"unit$subexpression$1",symbols:[Ke.has("YEARS")?{type:"YEARS"}:YEARS]},{name:"unit",symbols:["unit$subexpression$1"],postprocess:([t])=>(0,xu.mkUnits)(t[0].text)},{name:"clause",symbols:[Ke.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"clause",symbols:["duration"],postprocess:([t])=>({operator:"in_last",...t})},{name:"clause",symbols:[Ke.has("BEFORE")?{type:"BEFORE"}:BEFORE,"moment"],postprocess:([t,e])=>({operator:"before",before:e})},{name:"clause",symbols:[Ke.has("AFTER")?{type:"AFTER"}:AFTER,"moment"],postprocess:([t,e])=>({operator:"after",after:e})},{name:"clause",symbols:["moment",Ke.has("TO")?{type:"TO"}:TO,"moment"],postprocess:([t,e,r])=>({operator:"to",fromMoment:t,toMoment:r})},{name:"clause",symbols:["moment",Ke.has("FOR")?{type:"FOR"}:FOR,"duration"],postprocess:([t,e,r])=>({...r,operator:"for",begin:t})},{name:"clause$subexpression$1",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST]},{name:"clause$subexpression$1",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT]},{name:"clause",symbols:["clause$subexpression$1","duration"],postprocess:([t,e])=>({operator:t[0].text,...e})},{name:"clause",symbols:["moment"],postprocess:([t])=>({operator:"in",in:t})},{name:"lastNextThis",symbols:[Ke.has("THIS")?{type:"THIS"}:THIS],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST],postprocess:([t])=>t.text.toLowerCase()},{name:"moment",symbols:[Ke.has("NOW")?{type:"NOW"}:NOW],postprocess:()=>({moment:"now"})},{name:"moment",symbols:["lastNextThis","unit"],postprocess:([t,e])=>({moment:t,units:e})},{name:"moment",symbols:[Ke.has("TODAY")?{type:"TODAY"}:TODAY],postprocess:()=>({moment:"today"})},{name:"moment",symbols:[Ke.has("YESTERDAY")?{type:"YESTERDAY"}:YESTERDAY],postprocess:()=>({moment:"yesterday"})},{name:"moment",symbols:[Ke.has("TOMORROW")?{type:"TOMORROW"}:TOMORROW],postprocess:()=>({moment:"tomorrow"})},{name:"moment",symbols:["duration",Ke.has("AGO")?{type:"AGO"}:AGO],postprocess:([t,e])=>({moment:"ago",...t})},{name:"moment",symbols:["duration",Ke.has("FROM")?{type:"FROM"}:FROM,Ke.has("NOW")?{type:"NOW"}:NOW],postprocess:([t,e])=>({moment:"from_now",...t})},{name:"moment",symbols:[Ke.has("NEXT")?{type:"NEXT"}:NEXT,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"next"})},{name:"moment",symbols:[Ke.has("LAST")?{type:"LAST"}:LAST,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"last"})},{name:"moment",symbols:["weekday"],postprocess:([t])=>({moment:t.toLowerCase(),which:"last"})},{name:"moment",symbols:["timeLiteral"],postprocess:t=>t[0]},{name:"timeLiteral",symbols:[Ke.has("literal")?{type:"literal"}:literal],postprocess:([t])=>(0,xu.timeLiteral)(t.text)},{name:"timeLiteral",symbols:[Ke.has("lit_day")?{type:"lit_day"}:lit_day],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"day")},{name:"timeLiteral",symbols:[Ke.has("lit_min")?{type:"lit_min"}:lit_min],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"minute")},{name:"timeLiteral",symbols:[Ke.has("lit_hour")?{type:"lit_hour"}:lit_hour],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"hour")},{name:"timeLiteral",symbols:[Ke.has("lit_month")?{type:"lit_month"}:lit_month],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"month")},{name:"timeLiteral",symbols:[Ke.has("lit_quarter")?{type:"lit_quarter"}:lit_quarter],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"quarter")},{name:"timeLiteral",symbols:[Ke.has("lit_week")?{type:"lit_week"}:lit_week],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"week")},{name:"timeLiteral",symbols:[Ke.has("lit_year")?{type:"lit_year"}:lit_year],postprocess:([t])=>(0,xu.timeLiteral)(t.text,"year")},{name:"weekday$subexpression$1",symbols:[Ke.has("MONDAY")?{type:"MONDAY"}:MONDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("TUESDAY")?{type:"TUESDAY"}:TUESDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("WEDNESDAY")?{type:"WEDNESDAY"}:WEDNESDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("THURSDAY")?{type:"THURSDAY"}:THURSDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("FRIDAY")?{type:"FRIDAY"}:FRIDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("SATURDAY")?{type:"SATURDAY"}:SATURDAY]},{name:"weekday$subexpression$1",symbols:[Ke.has("SUNDAY")?{type:"SUNDAY"}:SUNDAY]},{name:"weekday",symbols:["weekday$subexpression$1"],postprocess:([t])=>t[0].text},{name:"parens",symbols:[Ke.has("oparen")?{type:"oparen"}:oparen,"temporalFilter",Ke.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"conjunction",symbols:[Ke.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Ke.has("AND")?{type:"AND"}:AND]}],ParserStart:"temporalFilter"};iB.default=fXe,function(t){var e=T&&T.__createBinding||(Object.create?function(h,p,m,y){y===void 0&&(y=m);var g=Object.getOwnPropertyDescriptor(p,m);(!g||("get"in g?!p.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(h,y,g)}:function(h,p,m,y){y===void 0&&(y=m),h[y]=p[m]}),r=T&&T.__setModuleDefault||(Object.create?function(h,p){Object.defineProperty(h,"default",{enumerable:!0,value:p})}:function(h,p){h.default=p}),i=T&&T.__importStar||function(h){if(h&&h.__esModule)return h;var p={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&e(p,h,m);return r(p,h),p},s=T&&T.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=void 0;const o=Tn,u=s(iB),a=i(X$),l=zp;t.TemporalFilterExpression={parse(h){if(h.match(/^\s*$/))return{parsed:null,log:[]};const p=new a.Parser(a.Grammar.fromCompiled(u.default)),m=(0,l.run_parser)(h,p);return m.parsed&&(0,o.isTemporalFilter)(m.parsed)?{parsed:m.parsed,log:[]}:{parsed:null,log:m.log}},unparse(h){if(h===null)return"";switch(h.operator){case"null":return c(h,"null");case"in":return c(h,x(h.in));case"()":return"("+t.TemporalFilterExpression.unparse(h.expr)+")";case"in_last":return c(h,f(h));case"last":case"next":return c(h,`${h.operator} ${f(h)}`);case"before":return c(h,`before ${x(h.before)}`);case"after":return c(h,`after ${x(h.after)}`);case"to":return c(h,`${x(h.fromMoment)} to ${x(h.toMoment)}`);case"for":return c(h,`${x(h.begin)} for ${f(h)}`);case"or":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" or ");case"and":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" and ")}}};function c(h,p){return"not"in h&&h.not?"not "+p:p}function f(h){return h.n==="1"?`1 ${h.units}`:`${h.n} ${h.units}s`}function x(h){switch(h.moment){case"literal":return h.literal;case"now":case"today":case"yesterday":case"tomorrow":return h.moment;case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":return h.which==="next"?"next "+h.moment:h.moment;case"this":case"next":case"last":return`${h.moment} ${h.units}`;case"ago":return`${f(h)} ago`;case"from_now":return`${f(h)} from now`}}}(Eae),function(t){var e=T&&T.__createBinding||(Object.create?function(a,l,c,f){f===void 0&&(f=c);var x=Object.getOwnPropertyDescriptor(l,c);(!x||("get"in x?!l.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return l[c]}}),Object.defineProperty(a,f,x)}:function(a,l,c,f){f===void 0&&(f=c),a[f]=l[c]}),r=T&&T.__exportStar||function(a,l){for(var c in a)c!=="default"&&!Object.prototype.hasOwnProperty.call(l,c)&&e(l,a,c)};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=t.StringFilterExpression=t.NumberFilterExpression=t.BooleanFilterExpression=void 0,r(Tn,t);var i=U4;Object.defineProperty(t,"BooleanFilterExpression",{enumerable:!0,get:function(){return i.BooleanFilterExpression}});var s=hae;Object.defineProperty(t,"NumberFilterExpression",{enumerable:!0,get:function(){return s.NumberFilterExpression}});var o=yae;Object.defineProperty(t,"StringFilterExpression",{enumerable:!0,get:function(){return o.StringFilterExpression}});var u=Eae;Object.defineProperty(t,"TemporalFilterExpression",{enumerable:!0,get:function(){return u.TemporalFilterExpression}})}(P4);var q4={};const Cy=AP(V1e);Object.defineProperty(q4,"__esModule",{value:!0}),q4.TemporalFilterCompiler=void 0;const sB=Xe,Zx=Cy,_ae="yyyy",vae=`${_ae}-LL`,oB=`${vae}-dd`,Cae=`${oB} HH`,Sae=`${Cae}:mm`,xs=`${Sae}:ss`;class xXe{constructor(e,r,i="timestamp"){this.expr=e,this.timetype=i,this.d=r}time(e){return this.timetype==="timestamp"?e:this.d.sqlCast({},{node:"cast",e:{node:"genericSQLExpr",src:["",e],kids:{args:[]},sql:e},srcType:{type:"timestamp"},dstType:{type:"date"},safe:!1})}compile(e){const r=this.expr;switch(e.operator){case"after":return`${r} ${e.not?"<":">="} ${this.time(this.moment(e.after).end)}`;case"before":return`${r} ${e.not?">=":"<"} ${this.time(this.moment(e.before).begin.sql)}`;case"in":{const i=this.moment(e.in);return i.begin.sql===i.end?e.not?`${r} != ${this.time(i.end)} OR ${r} IS NULL`:`${r} = ${this.time(i.end)}`:this.isIn(e.not,i.begin.sql,i.end)}case"for":{const i=this.moment(e.begin),s=this.delta(i.begin,"+",e.n,e.units);return this.isIn(e.not,i.begin.sql,s.sql)}case"in_last":{const i=Number(e.n)-1,s=this.nowDot(e.units),o=i>0?this.delta(s,"-",i.toString(),e.units):s,u=this.delta(s,"+","1",e.units);return this.isIn(e.not,o.sql,u.sql)}case"to":{const i=this.moment(e.fromMoment),s=this.moment(e.toMoment);return this.isIn(e.not,i.begin.sql,s.begin.sql)}case"last":{const i=this.nowDot(e.units),s=this.delta(i,"-",e.n,e.units);return this.isIn(e.not,s.sql,i.sql)}case"next":{const i=this.nowDot(e.units),s=this.delta(i,"+","1",e.units),o=this.delta(i,"+",(Number(e.n)+1).toString(),e.units);return this.isIn(e.not,s.sql,o.sql)}case"null":return e.not?`${r} IS NOT NULL`:`${r} IS NULL`;case"()":{const i="("+this.compile(e.expr)+")";return e.not?`NOT ${i}`:i}case"and":case"or":return e.members.map(i=>this.compile(i)).join(` ${e.operator.toUpperCase()} `)}}expandLiteral(e){let r=e.literal;switch(e.units){case"year":{const i=Zx.DateTime.fromFormat(r,_ae),s=this.literalNode(i.toFormat(xs)),o=i.plus({year:1});return{begin:s,end:this.literalNode(o.toFormat(xs)).sql}}case"month":{const i=Zx.DateTime.fromFormat(r,vae),s=this.literalNode(i.toFormat(xs)),o=i.plus({month:1});return{begin:s,end:this.literalNode(o.toFormat(xs)).sql}}case"day":{const i=Zx.DateTime.fromFormat(r,oB),s=this.literalNode(i.toFormat(xs)),o=i.plus({day:1});return{begin:s,end:this.literalNode(o.toFormat(xs)).sql}}case"hour":{const i=Zx.DateTime.fromFormat(r,Cae),s=this.literalNode(i.toFormat(xs)),o=i.plus({hour:1});return{begin:s,end:this.literalNode(o.toFormat(xs)).sql}}case"minute":{const i=Zx.DateTime.fromFormat(r,Sae),s=this.literalNode(i.toFormat(xs)),o=i.plus({minute:1});return{begin:s,end:this.literalNode(o.toFormat(xs)).sql}}case"week":{const o=Zx.DateTime.fromFormat(r.slice(0,10),oB).plus({day:1}).startOf("week").minus({day:1}),u=this.literalNode(o.toFormat(xs)),a=o.plus({days:7});return{begin:u,end:this.literalNode(a.toFormat(xs)).sql}}case"quarter":{const i=r.slice(0,4),s=r.slice(6);s==="1"?r=`${i}-01-01 00:00:00`:s==="2"?r=`${i}-03-01 00:00:00`:s==="3"?r=`${i}-06-01 00:00:00`:r=`${i}-09-01 00:00:00`;const o=this.literalNode(r),a=Zx.DateTime.fromFormat(r,xs).plus({months:3});return{begin:o,end:this.literalNode(a.toFormat(xs)).sql}}case void 0:case"second":return{begin:this.literalNode(r),end:r}}}literalNode(e){const r={node:"timeLiteral",typeDef:{type:"timestamp"},literal:e};return{...r,sql:this.d.sqlLiteralTime({},r)}}nowExpr(){return{node:"now",typeDef:{type:"timestamp"},sql:this.d.sqlNowExpr()}}n(e){return{node:"numberLiteral",literal:e,sql:e}}delta(e,r,i,s){const o={node:"delta",op:r,units:s,kids:{base:(0,sB.mkTemporal)(e,"timestamp"),delta:this.n(i)}};return{...o,sql:this.d.sqlAlterTimeExpr(o)}}dayofWeek(e){const r={node:"extract",e:(0,sB.mkTemporal)(e,"timestamp"),units:"day_of_week"};return{...r,sql:this.d.sqlTimeExtractExpr({},r)}}nowDot(e){const r={node:"trunc",e:this.nowExpr(),units:e};return{...r,sql:this.d.sqlTruncExpr({},r)}}thisUnit(e){const r=this.nowDot(e),i=this.delta(r,"+","1",e);return{begin:r,end:i.sql}}lastUnit(e){const r=this.nowDot(e);return{begin:this.delta(r,"-","1",e),end:r.sql}}nextUnit(e){const r=this.nowDot(e),i=this.delta(r,"+","1",e),s=this.delta(r,"+","2",e);return{begin:i,end:s.sql}}mod7(e){return this.d.hasModOperator?`(${e})%7`:`MOD(${e},7)`}moment(e){switch(e.moment){case"now":{const r=this.nowExpr();return{begin:r,end:r.sql}}case"literal":return this.expandLiteral(e);case"ago":case"from_now":{const r=this.nowDot(e.units),i=(0,sB.mkTemporal)(r,"timestamp"),s=this.delta(i,e.moment==="ago"?"-":"+",e.n,e.units);if(e.moment==="ago"&&e.n==="1")return{begin:s,end:r.sql};const o=Number(e.n)+(e.moment==="ago"?-1:1),u={...s,kids:{base:i,delta:this.n(o.toString())}};return{begin:s,end:this.d.sqlAlterTimeExpr(u)}}case"today":return this.thisUnit("day");case"yesterday":return this.lastUnit("day");case"tomorrow":return this.nextUnit("day");case"this":return this.thisUnit(e.units);case"last":return this.lastUnit(e.units);case"next":return this.nextUnit(e.units);case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":{const r=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].indexOf(e.moment),i=this.dayofWeek(this.nowExpr()).sql;if(e.which==="next"){const a=`${this.mod7(`${r}-(${i}-1)+6`)}+1`,l=this.delta(this.thisUnit("day").begin,"+",a,"day"),c=this.delta(this.thisUnit("day").begin,"+",`${a}+1`,"day");return{begin:l,end:c.sql}}const s=`${this.mod7(`(${i}-1)-${r}+6`)}+1`,o=this.delta(this.thisUnit("day").begin,"-",s,"day"),u=this.delta(this.thisUnit("day").begin,"-",`(${s})-1`,"day");return{begin:o,end:u.sql}}}}isIn(e,r,i){let s=">=",o="<",u="AND";return e&&(u="OR",s="<",o=">="),r=this.time(r),i=this.time(i),`${this.expr} ${s} ${r} ${u} ${this.expr} ${o} ${i}`}}q4.TemporalFilterCompiler=xXe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.FilterCompilers=void 0;const e=P4,r=q4;function i(u){return u.replace(/([%_\\])/g,"\\$1")}function s(u){return u===">"?"<=":u==="<"?">=":u===">="?"<":">"}function o(u,a){const l=` OR ${a} IS NULL`;return u.length===1?`${u[0]}${l}`:`(${u.join(" AND ")})${l}`}t.FilterCompilers={compile(u,a,l,c){if(a===null)return"true";if(u==="string"&&(0,e.isStringFilter)(a))return t.FilterCompilers.stringCompile(a,l,c);if(u==="number"&&(0,e.isNumberFilter)(a))return t.FilterCompilers.numberCompile(a,l,c);if(u==="boolean"&&(0,e.isBooleanFilter)(a))return t.FilterCompilers.booleanCompile(a,l,c);if((u==="date"||u==="timestamp")&&(0,e.isTemporalFilter)(a))return t.FilterCompilers.temporalCompile(a,l,c,u);throw new Error("INTERNAL ERROR: No filter compiler for "+u)},numberCompile(u,a,l){switch(u.operator){case"!=":case"=":{const c=u.operator==="="&&u.not||u.operator==="!="&&!u.not,f=u.values.join(", ");return u.values.length===1?c?`${a} != ${f} OR ${a} IS NULL`:`${a} = ${f}`:c?`${a} NOT IN (${f}) OR ${a} IS NULL`:`${a} IN (${f})`}case">":case"<":case">=":case"<=":return u.values.map(c=>`${a} ${u.operator} ${c}`).join(u.not?" AND ":" OR ");case"range":{let c=u.startOperator,f=u.endOperator,x=" AND ";return u.not&&(c=s(c),f=s(f),x=" OR "),`${a} ${c} ${u.startValue} ${x} ${a} ${f} ${u.endValue}`}case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"()":{const c="("+t.FilterCompilers.numberCompile(u.expr,a,l)+")";return u.not?`NOT ${c}`:c}case"and":case"or":return u.members.map(c=>t.FilterCompilers.numberCompile(c,a,l)).join(` ${u.operator.toUpperCase()} `)}},booleanCompile(u,a,l){switch(u.operator){case"false":return`${a} = false`;case"false_or_null":return`${a} IS NULL OR ${a} = false`;case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"true":return a}},stringCompile(u,a,l){switch(u.operator){case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"empty":return u.not?`COALESCE(${a},'') != ''`:`COALESCE(${a},'') = ''`;case"=":{if(u.values.length===1){const f=u.not?"!=":"=",x=`${a} ${f} ${l.sqlLiteralString(u.values[0])}`;return u.not?`(${x} OR ${a} IS NULL)`:x}const c="("+u.values.map(f=>l.sqlLiteralString(f)).join(", ")+")";return u.not?`(${a} NOT IN ${c} OR ${a} IS NULL)`:`${a} IN ${c}`}case"()":{const c="("+t.FilterCompilers.stringCompile(u.expr,a,l)+")";return u.not?`not ${c}`:c}case"contains":{const c=u.values.map(f=>"%"+i(f)+"%");return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"starts":{const c=u.values.map(f=>i(f)+"%");return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"ends":{const c=u.values.map(f=>"%"+i(f));return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"~":return u.not?o(u.escaped_values.map(c=>l.sqlLike("NOT LIKE",a,c)),a):u.escaped_values.map(c=>l.sqlLike("LIKE",a,c)).join(" OR ");case"and":return u.members.map(f=>t.FilterCompilers.stringCompile(f,a,l)).join(" AND ");case"or":return u.members.map(f=>t.FilterCompilers.stringCompile(f,a,l)).join(" AND ");case",":{const c=[],f=[];let x=!1,h=!1,p=!1,m=!1;for(const E of u.members)switch(E.operator){case"or":case"and":case",":c.push(E);break;case"null":E.not?h=!0:x=!0;break;case"empty":E.not?(m=!0,h=!0):(p=!0,x=!0);break;default:(E.not?f:c).push(E)}if(p&&m||x&&h)return"false";let y="";if(c.length>0||x||p){m=!1,h=!1;const E=c.map(A=>t.FilterCompilers.stringCompile(A,a,l));p&&E.push(`${a} = ''`),x&&E.push(`${a} IS NULL`),y=E.join(" OR ")}let g="";if(f.length>0||m||h){const E=f.map(A=>t.FilterCompilers.stringCompile(A,a,l));m&&E.push(`${a} != ''`),h&&E.push(`${a} IS NOT NULL`),g=E.join(" AND ")}return y?g!==""?`(${y}) AND (${g})`:y:g!==""?g:"true"}}},temporalCompile(u,a,l,c){return new r.TemporalFilterCompiler(a,l,c).compile(u)}}}(dae),Object.defineProperty($s,"__esModule",{value:!0}),$s.QueryModel=$s.getResultStructDefForQuery=$s.getResultStructDefForView=$s.Segment=void 0;const dXe=Up,hXe=Mp,pXe=Ey,ke=Xe,Rn=$t,Q4=Qp,mXe=ai,gXe=dae,yXe=P4;function bae(t){return t.map(e=>encodeURIComponent(e)).join("/")}function uB(t){return`'${t}'`}function EXe(t){return t.replace(/[^a-zA-Z0-9_]/g,"_o_")}function Gp(t){const e=[];for(const r of t.fields.filter(ke.fieldIsIntrinsic))e.push({type:r.type,sqlExpression:(0,ke.getIdentifier)(r),rawName:(0,ke.getIdentifier)(r),sqlOutputName:(0,ke.getIdentifier)(r)});return e}class AXe extends Set{add_use(e){if(e!==void 0)return this.add(e)}hasAsymetricFunctions(){return this.has("sum")||this.has("avg")||this.has("count")||this.has("generic_asymmetric_aggregate")}}class Sy{constructor(e=!0,r){this.parent=r,this.withs=[],this.udfs=[],this.pdts=[],this.dependenciesToMaterialize={},this.stagePrefix="__stage",this.useCTE=e}getName(e){return`${this.stagePrefix}${e}`}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){return this.useCTE?(this.withs.push(e),this.getName(this.withs.length-1)):(this.withs[0]=e,(0,Rn.indent)(`
|
|
1046
1046
|
(${e})
|
|
1047
1047
|
`))}addUDF(e,r,i){var s;let{sql:o,lastStageName:u}=e.combineStages(!0);if(u===void 0)throw new Error("Internal Error: no stage to combine");o+=r.sqlCreateFunctionCombineLastStage(u,Gp(i),(s=i.resultMetadata)===null||s===void 0?void 0:s.orderBy);const a=`${r.udfPrefix}${this.root().udfs.length}`;return o=r.sqlCreateFunction(a,o),this.root().udfs.push(o),a}addMaterializedQuery(e,r,i){var s;const o=r.name;if(!o)throw new Error(`Source ${e} on a unnamed query that is tagged as materialize, only named queries can be materialized.`);const u=(s=r.location)===null||s===void 0?void 0:s.url;if(!u)throw new Error(`Trying to materialize query ${o}, but its path is not set.`);const a=(0,Q4.buildQueryMaterializationSpec)(u,o,i);return this.root().dependenciesToMaterialize[a.id]=a,a.id}addPDT(e,r){const i=this.combineStages(!1).sql+this.withs[this.withs.length-1],o=`scratch.${e+(0,Rn.generateHash)(i)}`;return this.root().pdts.push(r.sqlCreateTableAsSelect(o,i)),o}combineStages(e){if(!this.useCTE)return{sql:this.withs[0],lastStageName:this.withs[0]};let r=this.getName(0),i="WITH ",s="";for(let o=0;o<this.withs.length-(e?0:1);o++){const u=this.withs[o];if(r=this.getName(o),u===void 0)throw new Error(`Expected sql WITH to be present for stage ${r}.`);s+=`${i}${r} AS (
|
|
1048
1048
|
${(0,Rn.indent)(u)})
|
|
@@ -1050,7 +1050,7 @@ ${(0,Rn.indent)(u)})
|
|
|
1050
1050
|
`),i=this.pdts.join(`
|
|
1051
1051
|
`),s=this.combineStages(!1).sql;return r+i+s+this.withs[e]}generateCoorelatedSubQuery(e,r){var i,s;return this.useCTE?this.combineStages(!0).sql+e.sqlCreateFunctionCombineLastStage(this.getName(this.withs.length-1),Gp(r),(s=r.resultMetadata)===null||s===void 0?void 0:s.orderBy):e.sqlCreateFunctionCombineLastStage(`(${this.withs[0]})`,Gp(r),(i=r.resultMetadata)===null||i===void 0?void 0:i.orderBy)}}class by{constructor(){this.totalGroupSet=-1}withWhere(e){const r=new by;return r.whereSQL=e,r.applyValue=this.applyValue,r.totalGroupSet=this.totalGroupSet,r}withApply(e){const r=new by;return r.whereSQL=this.whereSQL,r.applyValue=e,r.totalGroupSet=this.totalGroupSet,r}withTotal(e){const r=new by;return r.whereSQL=this.whereSQL,r.applyValue=this.applyValue,r.totalGroupSet=e,r}}class _Xe{constructor(e){this.referenceId=e??(0,dXe.v4)()}getChildByName(e){}}let aB=class extends _Xe{constructor(e,r,i){super(i),this.fieldDef=e,this.parent=r,this.fieldDef=e}getIdentifier(){return(0,ke.getIdentifier)(this.fieldDef)}uniqueKeyPossibleUse(){}getJoinableParent(){const e=this.parent;return e.structDef.type==="record"?e.getJoinableParent():e}isAtomic(){return(0,ke.isAtomic)(this.fieldDef)}caseGroup(e,r){return e.length===0?r:`CASE WHEN group_set${e.length===1?`=${e[0]}`:` IN (${e.join(",")})`} THEN
|
|
1052
1052
|
${r}
|
|
1053
|
-
END`}getFullOutputName(){return this.parent.getFullOutputName()+this.getIdentifier()}generateFieldFragment(e,r,i,s){const o=r.getFieldByName(i.path);return(0,ke.hasExpression)(o.fieldDef)?`(${this.exprToSQL(e,o.parent,o.fieldDef.e,s)})`:o.generateExpression(e)}generateOutputFieldFragment(e,r,i,s){return`(${e.getField(i.name).getAnalyticalSQL(!1)})`}*stringsFromSQLExpression(e,r,i,s){const o=[...i.kids.args];for(const u of i.src){yield u;const a=o.shift();a&&(yield this.exprToSQL(e,r,a,s))}}getParameterMap(e,r){return new Map(e.params.map((i,s)=>{const o=i.isVariadic?(0,Rn.range)(s,r):[s];return[i.name,{param:i,argIndexes:o}]}))}expandFunctionCall(e,r,i,s,o){function u(c){const f=[];for(let x=0;x<c.length;)f.push(c[x]),x+=1,x<c.length&&f.push(",");return f}const a=this.getParameterMap(r,i.length);if(r.dialect[e]===void 0)throw new Error(`Function is not defined for '${e}' dialect`);return(0,Rn.exprMap)(r.dialect[e].e,c=>{var f,x;if(c.node==="spread"){const h=c.e;if(h.node!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const p=a.get(h.name);if(p===void 0)return c;const m=p.argIndexes.map(y=>i[y]);return(0,Rn.composeSQLExpr)(u(m))}else if(c.node==="function_parameter"){const h=a.get(c.name);if(h===void 0)return c;if(h.param.isVariadic){const p=h.argIndexes.map(m=>i[m]);return(0,Rn.composeSQLExpr)(u(p))}else return i[h.argIndexes[0]]}else{if(c.node==="aggregate_order_by")return s?(0,Rn.composeSQLExpr)([` ${(f=c.prefix)!==null&&f!==void 0?f:""}${s}${(x=c.suffix)!==null&&x!==void 0?x:""}`]):{node:""};if(c.node==="aggregate_limit")return o?(0,Rn.composeSQLExpr)([` ${o}`]):{node:""}}return c})}getFunctionOrderBy(e,r,i,s,o,u){if(s.length!==0)return"ORDER BY "+s.map(a=>{var l;const c=(l=u.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&l!==void 0?l:0,f=a.node==="functionOrderBy"?a.e:o[c],x=this.generateDimFragment(e,r,f,i),h=a.dir==="asc"?" ASC":a.dir==="desc"?" DESC":"";return`${x}${h}`}).join(", ")}generateAsymmetricStringAggExpression(e,r,i,s,o,u,a,l){if(u)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${a}`);const c=this.generateDimFragment(e,r,i,l),f=s?this.generateDimFragment(e,r,s,l):"";return this.parent.dialect.sqlStringAggDistinct(o,c,f)}getParamForArgIndex(e,r){const i=e.slice(0,r).find(s=>s.isVariadic);return i??e[r]}generateFunctionCallExpression(e,r,i,s){var o,u,a;const l=i.overload,c=i.kids.args,f=(o=i.overload.isSymmetric)!==null&&o!==void 0?o:!1,x=(0,ke.expressionIsAggregate)(l.returnType.expressionType)&&!f&&this.generateDistinctKeyIfNecessary(e,r,i.structPath),h=i.limit?`LIMIT ${i.limit}`:void 0;if(i.name==="string_agg"&&x&&!r.dialect.supportsAggDistinct&&r.dialect.name!=="snowflake")return this.generateAsymmetricStringAggExpression(e,r,c[0],c[1],x,i.kids.orderBy,r.dialect.name,s);if(x){if(!r.dialect.supportsAggDistinct)throw new Error(`Function \`${i.name}\` does not support fanning out in ${r.dialect.name}`);const p=c.map(g=>this.generateDimFragment(e,r,g,s)),m=(u=i.kids.orderBy)!==null&&u!==void 0?u:[],y=m.map(g=>{var E;const A=(E=l.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&E!==void 0?E:0,_=g.node==="functionOrderBy"?g.e:c[A];return this.generateDimFragment(e,r,_,s)});return r.dialect.sqlAggDistinct(x,[...p,...y],g=>{const E=g.map((b,S)=>S<c.length&&this.getParamForArgIndex(l.params,S).allowedTypes.every(O=>(0,ke.isLiteral)(O.evalSpace))?c[S]:(0,Rn.composeSQLExpr)([b])),A=E.slice(0,p.length),_=E.slice(p.length).map((b,S)=>({node:"functionOrderBy",e:b,dir:m[S].dir})),v=this.getFunctionOrderBy(e,r,s,_,A,l),C=this.expandFunctionCall(r.dialect.name,l,A,v,h);return this.exprToSQL(e,r,C,s)})}else{const p=(0,ke.expressionIsAggregate)(l.returnType.expressionType)?c.map((g,E)=>this.getParamForArgIndex(l.params,E).allowedTypes.every(_=>(0,ke.isLiteral)(_.evalSpace))?g:(0,Rn.composeSQLExpr)([this.generateDimFragment(e,r,g,s)])):c,m=i.kids.orderBy?this.getFunctionOrderBy(e,r,s,i.kids.orderBy,c,l):"",y=this.expandFunctionCall(r.dialect.name,l,p,m,h);if((0,ke.expressionIsAnalytic)(l.returnType.expressionType)){const g=((a=i.partitionBy)!==null&&a!==void 0?a:[]).map(E=>`(${e.getField(E).getAnalyticalSQL(!1)})`);return this.generateAnalyticFragment(r.dialect.name,e,r,y,l,s,c,g,m)}return this.exprToSQL(e,r,y,s)}}generateSpread(e,r,i,s){throw new Error("Unexpanded spread encountered during SQL generation")}generateParameterFragment(e,r,i,s){var o;const u=i.path[0];(o=r.eventStream)===null||o===void 0||o.emit("source-argument-compiled",{name:u});const a=r.arguments()[u];if(a.value)return this.exprToSQL(e,r,a.value,s);throw new Error(`Can't generate SQL, no value for ${i.path}`)}generateFilterFragment(e,r,i,s){const o=new Rn.AndChain(s.whereSQL);for(const u of i.kids.filterList)o.add(this.exprToSQL(e,r,u.e,s.withWhere()));return this.exprToSQL(e,r,i.kids.e,s.withWhere(o.sql()))}generateDimFragment(e,r,i,s){let o=this.exprToSQL(e,r,i,s);return s.whereSQL&&(o=`CASE WHEN ${s.whereSQL} THEN ${o} END`),o}generateUngroupedFragment(e,r,i,s){if(s.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let o,u;if(i.fields&&i.fields.length>0){const x=i.fields.sort().join("|")+i.node;if(u=e.ungroupedSets.get(x),u===void 0)throw new Error(`Internal Error, cannot find groupset with key ${x}`);o=u.groupSet}else o=e.parent?e.parent.groupSet:0;const a=this.exprToSQL(e,r,i.e,s.withTotal(o)),l=e.getUngroupPartitions(u);let c="";const f=l.map(x=>x.getAnalyticalSQL(!0)).join(", ");return f.length>0&&(c=`PARTITION BY ${f}`),`MAX(${a}) OVER (${c})`}generateDistinctKeyIfNecessary(e,r,i){let s=r;if(i&&(s=this.parent.root().getStructByName(i)),s.needsSymetricCalculation(e))return s.getDistinctKey().generateExpression(e)}generateSumFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);let a;return u?this.parent.dialect.supportsSumDistinctFunction?a=this.parent.dialect.sqlSumDistinct(u,o,"SUM"):a=Dae(this.parent.dialect,o,u):a=`SUM(${o})`,`COALESCE(${a},0)`}generateSymmetricFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s);return`${i.function==="distinct"?"count(distinct ":i.function+"("}${o})`}generateAvgFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);if(u){let a=u;s.whereSQL&&(a=`CASE WHEN ${s.whereSQL} THEN ${u} END`);let l,c;return this.parent.dialect.supportsSumDistinctFunction?c=this.parent.dialect.sqlSumDistinct(u,o,"AVG"):(l=Dae(this.parent.dialect,o,u),c=`(${l})/NULLIF(COUNT(DISTINCT CASE WHEN ${o} IS NOT NULL THEN ${a} END),0)`),c}else return`AVG(${o})`}generateCountFragment(e,r,i,s){let o="COUNT(",u="1",a=r;i.structPath&&(a=this.parent.root().getStructByName(i.structPath));const l=a.getJoinableParent().getIdentifier(),c=e.root().joins.get(l);if(!c)throw new Error(`Join ${l} not found in result set`);return(!c.leafiest||c.makeUniqueKey)&&(o="COUNT(DISTINCT ",u=a.getDistinctKey().generateExpression(e)),s.whereSQL?`${o}CASE WHEN ${s.whereSQL} THEN ${u} END)`:`${o}${u})`}generateSourceReference(e,r,i){return i.path===void 0?r.getSQLIdentifier():r.getFieldByName(i.path).getIdentifier()}getAnalyticPartitions(e,r){const i=[];let s=e.parent;for(;s!==void 0;){const u=s.fields(a=>kr(a.f)&&a.fieldUsage.type==="result").map(a=>a.getAnalyticalSQL(!0));i.push(...u),s=s.parent}return r&&i.push(...r),i}generateAnalyticFragment(e,r,i,s,o,u,a,l,c){const f=r.root().isComplexQuery,x=this.getAnalyticPartitions(r,l),h=[...f?["group_set"]:[],...x],p=h.length>0?`PARTITION BY ${h.join(", ")}`:"";let m=c??"";const y=o.dialect[e];if(!c&&y.needsWindowOrderBy){const _=[];let v;const C=r.firstSegment.orderBy||r.calculateDefaultOrderBy();for(const b of C){typeof b.field=="string"?v={name:b.field,fif:r.getField(b.field)}:v=r.getFieldByNumber(b.field);const S=v.fif.f.fieldDef.expressionType;if(!(0,ke.expressionIsAnalytic)(S))if(r.firstSegment.type==="reduce"){const R=v.fif.getAnalyticalSQL(!1);_.push(` ${R} ${b.dir||"ASC"}`)}else r.firstSegment.type==="project"&&_.push(` ${v.fif.f.generateExpression(r)} ${b.dir||"ASC"}`)}_.length>0&&(m=" "+this.parent.dialect.sqlOrderBy(_,"analytical"))}let g="";if(y.between){const[_,v]=[y.between.preceding,y.between.following].map(C=>{if(C===-1)return"UNBOUNDED";if(typeof C=="number")return C;const b=o.params.findIndex(R=>R.name===C),S=a[b];if(S.node!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return S.literal});g=`ROWS BETWEEN ${_} PRECEDING AND ${v} FOLLOWING`}let A=`${this.exprToSQL(r,i,s,u)} OVER(${p} ${m} ${g})`;return f&&(A=`CASE WHEN group_set=${r.groupSet} THEN ${A} END`),A}generateCaseSQL(e){const r=["CASE"];e.kids.caseValue!==void 0&&r.push(`${e.kids.caseValue.sql}`);for(let i=0;i<e.kids.caseWhen.length;i+=1)r.push(`WHEN ${e.kids.caseWhen[i].sql} THEN ${e.kids.caseThen[i].sql}`);return e.kids.caseElse!==void 0&&r.push(`ELSE ${e.kids.caseElse.sql}`),r.push("END"),r.join(" ")}exprToSQL(e,r,i,s=new by){var o;const u=function(f,x){const h=f.exprToSQL(e,r,x,s);return(0,ke.exprHasKids)(x)?`(${h})`:h};let a=i;if((0,ke.exprHasE)(i)){a={...i};const f=u(this,a.e);a.e={...a.e,sql:f}}else if((0,ke.exprHasKids)(i)){a={...i};const f=i.kids;for(const[x,h]of Object.entries(f))h!==null&&(Array.isArray(h)?a.kids[x]=h.map(p=>({...p,sql:u(this,p)})):a.kids[x]={...f[x],sql:u(this,h)})}const l=e.getQueryInfo(),c=this.parent.dialect.exprToSQL(l,a);if(c)return c;switch(a.node){case"field":return this.generateFieldFragment(e,r,a,s);case"parameter":return this.generateParameterFragment(e,r,a,s);case"filteredExpr":return this.generateFilterFragment(e,r,a,s);case"all":case"exclude":return this.generateUngroupedFragment(e,r,a,s);case"genericSQLExpr":return Array.from(this.stringsFromSQLExpression(e,r,a,s)).join("");case"aggregate":{let f="";if(a.function==="sum")f=this.generateSumFragment(e,r,a,s);else if(a.function==="avg")f=this.generateAvgFragment(e,r,a,s);else if(a.function==="count")f=this.generateCountFragment(e,r,a,s);else if(a.function==="min"||a.function==="max"||a.function==="distinct")f=this.generateSymmetricFragment(e,r,a,s);else throw new Error(`Internal Error: Unknown aggregate function ${a.function}`);if(e.root().isComplexQuery){let x=e.groupSet;return s.totalGroupSet!==-1&&(x=s.totalGroupSet),this.caseGroup([x],f)}return f}case"function_parameter":throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");case"outputField":return this.generateOutputFieldFragment(e,r,a,s);case"function_call":return this.generateFunctionCallExpression(e,r,a,s);case"spread":return this.generateSpread(e,r,a,s);case"source-reference":return this.generateSourceReference(e,r,a);case"+":case"-":case"*":case"%":case"/":case">":case"<":case">=":case"<=":case"=":return`${a.kids.left.sql}${a.node}${a.kids.right.sql}`;case"!=":return`COALESCE(${`${a.kids.left.sql}!=${a.kids.right.sql}`},true)`;case"and":case"or":return`${a.kids.left.sql} ${a.node} ${a.kids.right.sql}`;case"coalesce":return`COALESCE(${a.kids.left.sql},${a.kids.right.sql})`;case"in":{const f=a.kids.oneOf.map(x=>x.sql).join(",");return`${a.kids.e.sql} ${a.not?"NOT IN":"IN"} (${f})`}case"like":case"!like":{const f=a.node==="like"?"LIKE":"NOT LIKE",x=a.kids.right.node==="stringLiteral"?this.parent.dialect.sqlLike(f,(o=a.kids.left.sql)!==null&&o!==void 0?o:"",a.kids.right.literal):`${a.kids.left.sql} ${f} ${a.kids.right.sql}`;return a.node==="like"?x:`COALESCE(${x},true)`}case"()":return`(${a.e.sql})`;case"not":return`COALESCE(NOT ${a.e.sql},TRUE)`;case"unary-":return`-${a.e.sql}`;case"is-null":return`${a.e.sql} IS NULL`;case"is-not-null":return`${a.e.sql} IS NOT NULL`;case"true":case"false":return a.node;case"null":return"NULL";case"case":return this.generateCaseSQL(a);case"":return"";case"filterCondition":return a.e.sql?(a.sql=a.e.sql,a.sql):"";case"functionDefaultOrderBy":case"functionOrderBy":return"";case"compositeField":return"{COMPOSITE_FIELD}";case"filterMatch":if((a.dataType==="string"||a.dataType==="number"||a.dataType==="date"||a.dataType==="timestamp"||a.dataType==="boolean")&&(0,yXe.isFilterExpression)(a.filter))return gXe.FilterCompilers.compile(a.dataType,a.filter,a.e.sql||"",this.parent.dialect);throw new Error(`Internal Error: Filter Compiler Undefined Type '${a.dataType}'`);default:throw new Error(`Internal Error: Unknown expression node '${a.node}' ${JSON.stringify(a,void 0,2)}`)}}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"}generateExpression(e){if((0,ke.hasExpression)(this.fieldDef))return this.exprToSQL(e,this.parent,this.fieldDef.e);for(let r=this.parent;r!==void 0;r=r.parent)if(r.structDef.type==="record"&&(0,ke.hasExpression)(r.structDef)&&r.recordAlias===void 0){if(!r.parent)throw new Error("Inconcievable record ancestor with expression but no parent");const i=this.exprToSQL(e,r.parent,r.structDef.e);r.informOfAliasValue(i)}return this.parent.sqlChildReference(this.fieldDef.name,this.parent.structDef.type==="record"?{result:e,field:this}:void 0)}};function H4(t){return t instanceof Bs&&t.isCalculated()}function Tae(t){return t instanceof Bs&&t.isAggregate()}function kr(t){return t instanceof Bs&&!t.isCalculated()&&!t.isAggregate()}class Bs extends aB{constructor(e,r,i){super(e,r,i),this.fieldDef=e}includeInWildcard(){return!0}isCalculated(){return(0,ke.hasExpression)(this.fieldDef)&&(0,ke.expressionIsCalculation)(this.fieldDef.expressionType)}isAggregate(){return(0,ke.hasExpression)(this.fieldDef)&&(0,ke.expressionIsAggregate)(this.fieldDef.expressionType)}getFilterList(){return[]}hasExpression(){return(0,ke.hasExpression)(this.fieldDef)}isAtomic(){return!0}}class vXe extends Bs{}class CXe extends Bs{}class lB extends Bs{}class SXe extends Bs{}class bXe extends Bs{}class cB extends Bs{generateExpression(e){const r=this.fieldDef,i=super.generateExpression(e);if(r.timeframe){const s={node:"trunc",e:(0,ke.mkTemporal)({node:"genericSQLExpr",src:[i],kids:{args:[]}},"date"),units:r.timeframe};return this.exprToSQL(e,this.parent,s)}else return i}getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new cB(r,this.parent)}}class fB extends Bs{getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new fB(r,this.parent)}}class TXe extends Bs{generateExpression(e){var r;if(this.parent.primaryKey())return this.parent.getPrimaryKeyField(this.fieldDef).generateExpression(e);if(this.parent.structDef.type==="array"){const i=(r=this.parent.parent)===null||r===void 0?void 0:r.getDistinctKey().generateExpression(e);return this.parent.dialect.sqlMakeUnnestKey(i||"",this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__row_id","string"))}else return this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__distinct_key","string")}includeInWildcard(){return!1}}const Rae=9;function Dae(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-Rae);let a=`(${`
|
|
1053
|
+
END`}getFullOutputName(){return this.parent.getFullOutputName()+this.getIdentifier()}generateFieldFragment(e,r,i,s){const o=r.getFieldByName(i.path);return(0,ke.hasExpression)(o.fieldDef)?`(${this.exprToSQL(e,o.parent,o.fieldDef.e,s)})`:o.generateExpression(e)}generateOutputFieldFragment(e,r,i,s){return`(${e.getField(i.name).getAnalyticalSQL(!1)})`}*stringsFromSQLExpression(e,r,i,s){const o=[...i.kids.args];for(const u of i.src){yield u;const a=o.shift();a&&(yield this.exprToSQL(e,r,a,s))}}getParameterMap(e,r){return new Map(e.params.map((i,s)=>{const o=i.isVariadic?(0,Rn.range)(s,r):[s];return[i.name,{param:i,argIndexes:o}]}))}expandFunctionCall(e,r,i,s,o){function u(c){const f=[];for(let x=0;x<c.length;)f.push(c[x]),x+=1,x<c.length&&f.push(",");return f}const a=this.getParameterMap(r,i.length);if(r.dialect[e]===void 0)throw new Error(`Function is not defined for '${e}' dialect`);return(0,Rn.exprMap)(r.dialect[e].e,c=>{var f,x;if(c.node==="spread"){const h=c.e;if(h.node!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const p=a.get(h.name);if(p===void 0)return c;const m=p.argIndexes.map(y=>i[y]);return(0,Rn.composeSQLExpr)(u(m))}else if(c.node==="function_parameter"){const h=a.get(c.name);if(h===void 0)return c;if(h.param.isVariadic){const p=h.argIndexes.map(m=>i[m]);return(0,Rn.composeSQLExpr)(u(p))}else return i[h.argIndexes[0]]}else{if(c.node==="aggregate_order_by")return s?(0,Rn.composeSQLExpr)([` ${(f=c.prefix)!==null&&f!==void 0?f:""}${s}${(x=c.suffix)!==null&&x!==void 0?x:""}`]):{node:""};if(c.node==="aggregate_limit")return o?(0,Rn.composeSQLExpr)([` ${o}`]):{node:""}}return c})}getFunctionOrderBy(e,r,i,s,o,u){if(s.length!==0)return"ORDER BY "+s.map(a=>{var l;const c=(l=u.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&l!==void 0?l:0,f=a.node==="functionOrderBy"?a.e:o[c],x=this.generateDimFragment(e,r,f,i),h=a.dir==="asc"?" ASC":a.dir==="desc"?" DESC":"";return`${x}${h}`}).join(", ")}generateAsymmetricStringAggExpression(e,r,i,s,o,u,a,l){if(u)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${a}`);const c=this.generateDimFragment(e,r,i,l),f=s?this.generateDimFragment(e,r,s,l):"";return this.parent.dialect.sqlStringAggDistinct(o,c,f)}getParamForArgIndex(e,r){const i=e.slice(0,r).find(s=>s.isVariadic);return i??e[r]}generateFunctionCallExpression(e,r,i,s){var o,u,a;const l=i.overload,c=i.kids.args,f=(o=i.overload.isSymmetric)!==null&&o!==void 0?o:!1,x=(0,ke.expressionIsAggregate)(l.returnType.expressionType)&&!f&&this.generateDistinctKeyIfNecessary(e,r,i.structPath),h=i.limit?`LIMIT ${i.limit}`:void 0;if(i.name==="string_agg"&&x&&!r.dialect.supportsAggDistinct&&r.dialect.name!=="snowflake")return this.generateAsymmetricStringAggExpression(e,r,c[0],c[1],x,i.kids.orderBy,r.dialect.name,s);if(x){if(!r.dialect.supportsAggDistinct)throw new Error(`Function \`${i.name}\` does not support fanning out in ${r.dialect.name}`);const p=c.map(g=>this.generateDimFragment(e,r,g,s)),m=(u=i.kids.orderBy)!==null&&u!==void 0?u:[],y=m.map(g=>{var E;const A=(E=l.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&E!==void 0?E:0,_=g.node==="functionOrderBy"?g.e:c[A];return this.generateDimFragment(e,r,_,s)});return r.dialect.sqlAggDistinct(x,[...p,...y],g=>{const E=g.map((b,S)=>S<c.length&&this.getParamForArgIndex(l.params,S).allowedTypes.every(O=>(0,ke.isLiteral)(O.evalSpace))?c[S]:(0,Rn.composeSQLExpr)([b])),A=E.slice(0,p.length),_=E.slice(p.length).map((b,S)=>({node:"functionOrderBy",e:b,dir:m[S].dir})),v=this.getFunctionOrderBy(e,r,s,_,A,l),C=this.expandFunctionCall(r.dialect.name,l,A,v,h);return this.exprToSQL(e,r,C,s)})}else{const p=(0,ke.expressionIsAggregate)(l.returnType.expressionType)?c.map((g,E)=>this.getParamForArgIndex(l.params,E).allowedTypes.every(_=>(0,ke.isLiteral)(_.evalSpace))?g:(0,Rn.composeSQLExpr)([this.generateDimFragment(e,r,g,s)])):c,m=i.kids.orderBy?this.getFunctionOrderBy(e,r,s,i.kids.orderBy,c,l):"",y=this.expandFunctionCall(r.dialect.name,l,p,m,h);if((0,ke.expressionIsAnalytic)(l.returnType.expressionType)){const g=((a=i.partitionBy)!==null&&a!==void 0?a:[]).map(E=>`(${e.getField(E).getAnalyticalSQL(!1)})`);return this.generateAnalyticFragment(r.dialect.name,e,r,y,l,s,c,g,m)}return this.exprToSQL(e,r,y,s)}}generateSpread(e,r,i,s){throw new Error("Unexpanded spread encountered during SQL generation")}generateParameterFragment(e,r,i,s){var o;const u=i.path[0];(o=r.eventStream)===null||o===void 0||o.emit("source-argument-compiled",{name:u});const a=r.arguments()[u];if(a.value)return this.exprToSQL(e,r,a.value,s);throw new Error(`Can't generate SQL, no value for ${i.path}`)}generateFilterFragment(e,r,i,s){const o=new Rn.AndChain(s.whereSQL);for(const u of i.kids.filterList)o.add(this.exprToSQL(e,r,u.e,s.withWhere()));return this.exprToSQL(e,r,i.kids.e,s.withWhere(o.sql()))}generateDimFragment(e,r,i,s){let o=this.exprToSQL(e,r,i,s);return s.whereSQL&&(o=`CASE WHEN ${s.whereSQL} THEN ${o} END`),o}generateUngroupedFragment(e,r,i,s){if(s.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let o,u;if(i.fields&&i.fields.length>0){const x=i.fields.sort().join("|")+i.node;if(u=e.ungroupedSets.get(x),u===void 0)throw new Error(`Internal Error, cannot find groupset with key ${x}`);o=u.groupSet}else o=e.parent?e.parent.groupSet:0;const a=this.exprToSQL(e,r,i.e,s.withTotal(o)),l=e.getUngroupPartitions(u);let c="";const f=l.map(x=>x.getAnalyticalSQL(!0)).join(", ");return f.length>0&&(c=`PARTITION BY ${f}`),`MAX(${a}) OVER (${c})`}generateDistinctKeyIfNecessary(e,r,i){let s=r;if(i&&(s=this.parent.root().getStructByName(i)),s.needsSymetricCalculation(e))return s.getDistinctKey().generateExpression(e)}generateSumFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);let a;return u?this.parent.dialect.supportsSumDistinctFunction?a=this.parent.dialect.sqlSumDistinct(u,o,"SUM"):a=Dae(this.parent.dialect,o,u):a=`SUM(${o})`,`COALESCE(${a},0)`}generateSymmetricFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s);return`${i.function==="distinct"?"count(distinct ":i.function+"("}${o})`}generateAvgFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);if(u){let a=u;s.whereSQL&&(a=`CASE WHEN ${s.whereSQL} THEN ${u} END`);let l,c;return this.parent.dialect.supportsSumDistinctFunction?c=this.parent.dialect.sqlSumDistinct(u,o,"AVG"):(l=Dae(this.parent.dialect,o,u),c=`(${l})/NULLIF(COUNT(DISTINCT CASE WHEN ${o} IS NOT NULL THEN ${a} END),0)`),c}else return`AVG(${o})`}generateCountFragment(e,r,i,s){let o="COUNT(",u="1",a=r;i.structPath&&(a=this.parent.root().getStructByName(i.structPath));const l=a.getJoinableParent().getIdentifier(),c=e.root().joins.get(l);if(!c)throw new Error(`Join ${l} not found in result set`);return(!c.leafiest||c.makeUniqueKey)&&(o="COUNT(DISTINCT ",u=a.getDistinctKey().generateExpression(e)),s.whereSQL?`${o}CASE WHEN ${s.whereSQL} THEN ${u} END)`:`${o}${u})`}generateSourceReference(e,r,i){return i.path===void 0?r.getSQLIdentifier():r.getFieldByName(i.path).getIdentifier()}getAnalyticPartitions(e,r){const i=[];let s=e.parent;for(;s!==void 0;){const u=s.fields(a=>kr(a.f)&&a.fieldUsage.type==="result").map(a=>a.getAnalyticalSQL(!0));i.push(...u),s=s.parent}return r&&i.push(...r),i}generateAnalyticFragment(e,r,i,s,o,u,a,l,c){const f=r.root().isComplexQuery,x=this.getAnalyticPartitions(r,l),h=[...f?["group_set"]:[],...x],p=h.length>0?`PARTITION BY ${h.join(", ")}`:"";let m=c??"";const y=o.dialect[e];if(!c&&y.needsWindowOrderBy){const _=[];let v;const C=r.firstSegment.orderBy||r.calculateDefaultOrderBy();for(const b of C){typeof b.field=="string"?v={name:b.field,fif:r.getField(b.field)}:v=r.getFieldByNumber(b.field);const S=v.fif.f.fieldDef.expressionType;if(!(0,ke.expressionIsAnalytic)(S))if(r.firstSegment.type==="reduce"){const R=v.fif.getAnalyticalSQL(!1);_.push(` ${R} ${b.dir||"ASC"}`)}else r.firstSegment.type==="project"&&_.push(` ${v.fif.f.generateExpression(r)} ${b.dir||"ASC"}`)}_.length>0&&(m=" "+this.parent.dialect.sqlOrderBy(_,"analytical"))}let g="";if(y.between){const[_,v]=[y.between.preceding,y.between.following].map(C=>{if(C===-1)return"UNBOUNDED";if(typeof C=="number")return C;const b=o.params.findIndex(R=>R.name===C),S=a[b];if(S.node!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return S.literal});g=`ROWS BETWEEN ${_} PRECEDING AND ${v} FOLLOWING`}let A=`${this.exprToSQL(r,i,s,u)} OVER(${p} ${m} ${g})`;return f&&(A=`CASE WHEN group_set=${r.groupSet} THEN ${A} END`),A}generateCaseSQL(e){const r=["CASE"];e.kids.caseValue!==void 0&&r.push(`${e.kids.caseValue.sql}`);for(let i=0;i<e.kids.caseWhen.length;i+=1)r.push(`WHEN ${e.kids.caseWhen[i].sql} THEN ${e.kids.caseThen[i].sql}`);return e.kids.caseElse!==void 0&&r.push(`ELSE ${e.kids.caseElse.sql}`),r.push("END"),r.join(" ")}exprToSQL(e,r,i,s=new by){var o;const u=function(f,x){const h=f.exprToSQL(e,r,x,s);return(0,ke.exprHasKids)(x)?`(${h})`:h};let a=i;if((0,ke.exprHasE)(i)){a={...i};const f=u(this,a.e);a.e={...a.e,sql:f}}else if((0,ke.exprHasKids)(i)){a={...i};const f=i.kids;for(const[x,h]of Object.entries(f))h!==null&&(Array.isArray(h)?a.kids[x]=h.map(p=>({...p,sql:u(this,p)})):a.kids[x]={...f[x],sql:u(this,h)})}const l=e.getQueryInfo(),c=this.parent.dialect.exprToSQL(l,a);if(c)return c;switch(a.node){case"field":return this.generateFieldFragment(e,r,a,s);case"parameter":return this.generateParameterFragment(e,r,a,s);case"filteredExpr":return this.generateFilterFragment(e,r,a,s);case"all":case"exclude":return this.generateUngroupedFragment(e,r,a,s);case"genericSQLExpr":return Array.from(this.stringsFromSQLExpression(e,r,a,s)).join("");case"aggregate":{let f="";if(a.function==="sum")f=this.generateSumFragment(e,r,a,s);else if(a.function==="avg")f=this.generateAvgFragment(e,r,a,s);else if(a.function==="count")f=this.generateCountFragment(e,r,a,s);else if(a.function==="min"||a.function==="max"||a.function==="distinct")f=this.generateSymmetricFragment(e,r,a,s);else throw new Error(`Internal Error: Unknown aggregate function ${a.function}`);if(e.root().isComplexQuery){let x=e.groupSet;return s.totalGroupSet!==-1&&(x=s.totalGroupSet),this.caseGroup([x],f)}return f}case"function_parameter":throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");case"outputField":return this.generateOutputFieldFragment(e,r,a,s);case"function_call":return this.generateFunctionCallExpression(e,r,a,s);case"spread":return this.generateSpread(e,r,a,s);case"source-reference":return this.generateSourceReference(e,r,a);case"+":case"-":case"*":case"%":case"/":case">":case"<":case">=":case"<=":case"=":return`${a.kids.left.sql}${a.node}${a.kids.right.sql}`;case"!=":return`COALESCE(${`${a.kids.left.sql}!=${a.kids.right.sql}`},true)`;case"and":case"or":return`${a.kids.left.sql} ${a.node} ${a.kids.right.sql}`;case"coalesce":return`COALESCE(${a.kids.left.sql},${a.kids.right.sql})`;case"in":{const f=a.kids.oneOf.map(x=>x.sql).join(",");return`${a.kids.e.sql} ${a.not?"NOT IN":"IN"} (${f})`}case"like":case"!like":{const f=a.node==="like"?"LIKE":"NOT LIKE",x=a.kids.right.node==="stringLiteral"?this.parent.dialect.sqlLike(f,(o=a.kids.left.sql)!==null&&o!==void 0?o:"",a.kids.right.literal):`${a.kids.left.sql} ${f} ${a.kids.right.sql}`;return a.node==="like"?x:`COALESCE(${x},true)`}case"()":return`(${a.e.sql})`;case"not":return`COALESCE(NOT ${a.e.sql},TRUE)`;case"unary-":return`-${a.e.sql}`;case"is-null":return`${a.e.sql} IS NULL`;case"is-not-null":return`${a.e.sql} IS NOT NULL`;case"true":case"false":return a.node;case"null":return"NULL";case"case":return this.generateCaseSQL(a);case"":return"";case"filterCondition":return a.e.sql?(a.sql=a.e.sql,a.sql):"";case"functionDefaultOrderBy":case"functionOrderBy":return"";case"compositeField":return"{COMPOSITE_FIELD}";case"filterMatch":if((a.dataType==="string"||a.dataType==="number"||a.dataType==="date"||a.dataType==="timestamp"||a.dataType==="boolean")&&(a.filter===null||(0,yXe.isFilterExpression)(a.filter)))return gXe.FilterCompilers.compile(a.dataType,a.filter,a.e.sql||"",this.parent.dialect);throw new Error(`Internal Error: Filter Compiler Undefined Type '${a.dataType}'`);default:throw new Error(`Internal Error: Unknown expression node '${a.node}' ${JSON.stringify(a,void 0,2)}`)}}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"}generateExpression(e){if((0,ke.hasExpression)(this.fieldDef))return this.exprToSQL(e,this.parent,this.fieldDef.e);for(let r=this.parent;r!==void 0;r=r.parent)if(r.structDef.type==="record"&&(0,ke.hasExpression)(r.structDef)&&r.recordAlias===void 0){if(!r.parent)throw new Error("Inconcievable record ancestor with expression but no parent");const i=this.exprToSQL(e,r.parent,r.structDef.e);r.informOfAliasValue(i)}return this.parent.sqlChildReference(this.fieldDef.name,this.parent.structDef.type==="record"?{result:e,field:this}:void 0)}};function H4(t){return t instanceof Bs&&t.isCalculated()}function Tae(t){return t instanceof Bs&&t.isAggregate()}function kr(t){return t instanceof Bs&&!t.isCalculated()&&!t.isAggregate()}class Bs extends aB{constructor(e,r,i){super(e,r,i),this.fieldDef=e}includeInWildcard(){return!0}isCalculated(){return(0,ke.hasExpression)(this.fieldDef)&&(0,ke.expressionIsCalculation)(this.fieldDef.expressionType)}isAggregate(){return(0,ke.hasExpression)(this.fieldDef)&&(0,ke.expressionIsAggregate)(this.fieldDef.expressionType)}getFilterList(){return[]}hasExpression(){return(0,ke.hasExpression)(this.fieldDef)}isAtomic(){return!0}}class vXe extends Bs{}class CXe extends Bs{}class lB extends Bs{}class SXe extends Bs{}class bXe extends Bs{}class cB extends Bs{generateExpression(e){const r=this.fieldDef,i=super.generateExpression(e);if(r.timeframe){const s={node:"trunc",e:(0,ke.mkTemporal)({node:"genericSQLExpr",src:[i],kids:{args:[]}},"date"),units:r.timeframe};return this.exprToSQL(e,this.parent,s)}else return i}getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new cB(r,this.parent)}}class fB extends Bs{getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new fB(r,this.parent)}}class TXe extends Bs{generateExpression(e){var r;if(this.parent.primaryKey())return this.parent.getPrimaryKeyField(this.fieldDef).generateExpression(e);if(this.parent.structDef.type==="array"){const i=(r=this.parent.parent)===null||r===void 0?void 0:r.getDistinctKey().generateExpression(e);return this.parent.dialect.sqlMakeUnnestKey(i||"",this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__row_id","string"))}else return this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__distinct_key","string")}includeInWildcard(){return!1}}const Rae=9;function Dae(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-Rae);let a=`(${`
|
|
1054
1054
|
(
|
|
1055
1055
|
SUM(DISTINCT
|
|
1056
1056
|
(CAST(ROUND(COALESCE(${e},0)*(${o}*1.0), ${Rae}) AS ${t.defaultDecimalType}) +
|
|
@@ -1157,7 +1157,7 @@ ${i} ${o}: [`,u.length>0&&(s+=`
|
|
|
1157
1157
|
${i} `),s+="]")}return s}*walk(){for(const e of Object.keys(this.children)){const r=this.children[e];if(r instanceof Ta)yield r;else for(const i of r)yield i}}varInfo(){let e="";for(const[r,i]of Object.entries(this))r!=="elementType"&&(typeof i=="boolean"?e+=i?` ${r}`:` !${r}`:(typeof i=="string"||typeof i=="number")&&(e+=` ${r}=${i}`));return e}internalError(e){return new Error(`INTERNAL ERROR IN TRANSLATION: ${e}`)}needs(e){for(const r of this.walk()){const i=r.needs(e);if(i)return i}}inExperiment(e,r=!1){var i;const s=(i=this.translator())===null||i===void 0?void 0:i.compilerFlags.tag("experimental");return s&&(s.bare()||s.has(e))?!0:(r||this.logError("experiment-not-enabled",{experimentId:e}),!1)}}Je.MalloyElement=Ta;class mZe extends Ta{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}}Je.Unimplemented=mZe;class mB extends Ta{constructor(e){super(),this.name=e,this.elementType="modelEntryReference"}get refString(){return this.name}toString(){return this.refString}getNamed(){var e;return(e=this.modelEntry(this))===null||e===void 0?void 0:e.entry}}Je.ModelEntryReference=mB;class gZe extends Ta{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}}Je.ExperimentalExperiment=gZe;function jae(t){return t.execute!==void 0}Je.isDocStatement=jae;function yZe(t){return t instanceof Dy||jae(t)}Je.isDocStatementOrDocStatementList=yZe;class qae extends Ta{constructor(e){super(),this.elements=e,this.newContents()}newContents(){this.has({listOf:this.elements})}get list(){return this.elements}empty(){return this.elements.length===0}notEmpty(){return this.elements.length>0}push(...e){return this.elements.push(...e),this.newContents(),this.elements}needs(e){for(const r of this.elements){const i=r.needs(e);if(i)return i}}}Je.ListOf=qae;class Dy extends qae{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=Uae.extendNoteMethod,this.noteCursor=0}executeList(e){for(;this.execCursor<this.elements.length;){const r=this.elements[this.execCursor];if(this.noteCursor===this.execCursor&&(this.note&&(0,Uae.isNoteable)(r)&&r.extendNote(this.note),this.noteCursor+=1),r instanceof Dy){const i=r.executeList(e);if(i)return i}else{const i=r.needs(e);if(i)return i;r.execute(e)}this.execCursor+=1}}}Je.DocStatementList=Dy;const EZe="5a79a191-06bc-43cf-9b12-58741cd82970";function Qae(t){const e=t.inherits?Qae(t.inherits):[];return t.blockNotes&&e.push(...t.blockNotes.map(r=>r.text)),t.notes&&e.push(...t.notes.map(r=>r.text)),e}function AZe(t){const e=Qae(t).join("");return(0,pZe.v5)(e,EZe)}class gB extends Ta{constructor(e){super(),this.elementType="document",this.globalNameSpace=new hZe.GlobalNameSpace,this.documentModel={},this.queryList=[],this.didInitModel=!1,this.annotation={},this.experiments=new cZe.Tag({}),this.modelAnnotationTodoList=[],this.dialectNameSpaces=new Map,this.statements=new Dy(e),this.has({statements:e})}initModelDef(e){if(!this.didInitModel){if(this.documentModel={},this.queryList=[],e){e.annotation&&(this.annotation.inherits=e.annotation);for(const[r,i]of Object.entries(e.contents)){const s=structuredClone(i);if((0,K4.isSourceDef)(s)||s.type==="query"||s.type==="function"){const o=e.exports.includes(r);this.setEntry(r,{entry:s,exported:o})}}}this.didInitModel=!0}}compile(){const e=this.statements.executeList(this),r=this.modelDef();if(e===void 0)for(const s of this.queryList)s.modelAnnotation===void 0&&r.annotation&&(s.modelAnnotation=r.annotation);if(r.annotation)for(const s of this.modelAnnotationTodoList)s.modelAnnotation||(s.modelAnnotation=r.annotation);return{modelDef:{...r,queryList:this.queryList},needs:e}}rememberToAddModelAnnotations(e){this.modelAnnotationTodoList.push(e)}hasAnnotation(){return this.annotation.notes&&this.annotation.notes.length>0||this.annotation.inherits!==void 0}currentModelAnnotation(){if(this.hasAnnotation()){const e={...this.annotation,id:""};return e.id=AZe(e),e}}modelDef(){const e={name:"",exports:[],contents:{},queryList:[],dependencies:{}};this.hasAnnotation()&&(e.annotation=this.currentModelAnnotation());for(const r in this.documentModel){const i=this.documentModel[r].entry;if((0,K4.isSourceDef)(i)||i.type==="query"){this.documentModel[r].exported&&e.exports.push(r);const s=structuredClone(i);s.modelAnnotation===void 0&&e.annotation&&(s.modelAnnotation=e.annotation),e.contents[r]=s}}return e}getEntry(e){var r;return(r=this.globalNameSpace.getEntry(e))!==null&&r!==void 0?r:this.documentModel[e]}setEntry(e,r){this.globalNameSpace.getEntry(e)!==void 0&&this.logError("name-conflict-with-global",`Cannot redefine '${e}', which is in global namespace`),(0,K4.isSourceDef)(r.entry)&&this.checkExperimentalDialect(this,r.entry.dialect),this.documentModel[e]=r}checkExperimentalDialect(e,r){const i=this.translator();i&&i.firstReferenceToDialect(r)&&(0,Pae.getDialect)(r).experimental&&!i.experimentalDialectEnabled(r)&&e.logError("experimental-dialect-not-enabled",{dialect:r})}getDialectNamespace(e){if(this.dialectNameSpaces.has(e))return this.dialectNameSpaces.get(e);const r=(0,Pae.getDialect)(e),i=new dZe.DialectNameSpace(r);return this.dialectNameSpaces.set(e,i),i}}Je.Document=gB;var J4={},Kp={},Zt={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.atomicDef=t.inspect=t.typeEq=t.typeIn=t.eq=t.any=t.anyAtomicT=t.aggregateBoolT=t.viewT=t.errorT=t.boolT=t.timestampT=t.dateT=t.stringT=t.numberT=t.nullT=void 0;const e=ji,r=lt;function i(f,x="scalar",h="constant"){return{type:f,expressionType:x,evalSpace:h,compositeFieldUsage:(0,r.emptyCompositeFieldUsage)()}}t.nullT=i("null"),t.numberT=i("number"),t.stringT=i("string"),t.dateT=i("date"),t.timestampT=i("timestamp"),t.boolT=i("boolean"),t.errorT=i("error"),t.viewT=i("turtle"),t.aggregateBoolT=i("boolean","aggregate"),t.anyAtomicT=[t.numberT,t.stringT,t.dateT,t.timestampT,t.boolT];function s(f,x){return f?x.find(p=>o(p,f))!==void 0:!1}t.any=s;function o(f,x){return x!==void 0&&e.TD.eq(f,x)&&f.expressionType===x.expressionType}t.eq=o;function u(f,x){return f?x.find(p=>a(p,f))!==void 0:!1}t.typeIn=u;function a(f,x,h=!1,p=!0){const m=e.TD.eq(f,x),y=h&&(f.type==="null"||x.type==="null"),g=p&&(f.type==="error"||x.type==="error");return m||y||g}t.typeEq=a;function l(...f){return f.map(h=>{if(h){let p=h.type;return(0,e.expressionIsScalar)(h.expressionType)||(p=`${h.expressionType} ${p}`),p}return"undefined"}).join(",")}t.inspect=l;function c(f){if(e.TD.isAtomic(f))switch(f.type){case"array":return(0,e.isRepeatedRecord)(f)?{type:"array",elementTypeDef:f.elementTypeDef,fields:f.fields}:{type:"array",elementTypeDef:f.elementTypeDef};case"record":return{type:"record",fields:f.fields};case"number":return f.numberType?{type:"number",numberType:f.numberType}:{type:"number"};case"sql native":return f.rawType?{type:"sql native",rawType:f.rawType}:{type:"sql native"};default:return{type:f.type}}return{type:"error"}}t.atomicDef=c})(Zt);var Pr={},Oc={};Object.defineProperty(Oc,"__esModule",{value:!0}),Oc.canMakeEntry=Oc.SpaceEntry=void 0;class _Ze{}Oc.SpaceEntry=_Ze;function vZe(t){return"makeEntry"in t}Oc.canMakeEntry=vZe,Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.SpaceField=void 0;const CZe=Oc,SZe=lt;class bZe extends CZe.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){var r,i,s;const o=e.expressionType||"scalar";return{...e,expressionType:o,evalSpace:"input",compositeFieldUsage:(r=e.compositeFieldUsage)!==null&&r!==void 0?r:((i=e.e)===null||i===void 0?void 0:i.node)==="compositeField"?{fields:[(s=e.as)!==null&&s!==void 0?s:e.name],joinedUsage:{}}:(0,SZe.emptyCompositeFieldUsage)()}}getQueryFieldDef(e){}fieldDef(){}constructorFieldDef(){}}Pr.SpaceField=bZe;var TZe=T&&T.__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]}),RZe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),DZe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&TZe(e,t,r);return RZe(e,t),e};Object.defineProperty(Kp,"__esModule",{value:!0}),Kp.ViewField=void 0;const OZe=lt,FZe=DZe(Zt),wZe=Pr;class NZe extends wZe.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){var e;const r=this.fieldDef();return{...FZe.viewT,compositeFieldUsage:(e=r.compositeFieldUsage)!==null&&e!==void 0?e:(0,OZe.emptyCompositeFieldUsage)()}}}Kp.ViewField=NZe,Object.defineProperty(J4,"__esModule",{value:!0}),J4.ASTViewField=void 0;const LZe=Kp;class IZe extends LZe.ViewField{constructor(e,r,i){super(e),this.view=r,this.name=i,this.turtleDef=void 0}getQueryFieldDef(e){return this.view.getFieldDef(e)}fieldDef(){return this.turtleDef===void 0&&(this.turtleDef=this.view.getFieldDef(this.inSpace)),this.turtleDef}}J4.ASTViewField=IZe,Object.defineProperty(Ry,"__esModule",{value:!0}),Ry.ViewFieldDeclaration=void 0;const $Ze=Je,BZe=Mr,kZe=Wp,MZe=J4;class PZe extends $Ze.MalloyElement{constructor(e,r){super({view:r}),this.name=e,this.view=r,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=BZe.extendNoteMethod}makeEntry(e){const r=new MZe.ASTViewField(e,this,this.name);e.newEntry(this.name,this,r)}getName(){return this.name}getFieldDef(e){const{pipeline:r,annotation:i}=this.view.pipelineComp(e),s=(0,kZe.detectAndRemovePartialStages)(r,this);return{type:"turtle",name:this.name,pipeline:s,annotation:{...this.note,inherits:i},location:this.location}}}Ry.ViewFieldDeclaration=PZe;var qn={};Object.defineProperty(qn,"__esModule",{value:!0}),qn.LegalRefinementStage=qn.QueryClass=void 0;var Hae;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(Hae||(qn.QueryClass=Hae={}));var zae;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(zae||(qn.LegalRefinementStage=zae={}));var UZe=T&&T.__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]}),jZe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),qZe=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&UZe(e,t,r);return jZe(e,t),e};Object.defineProperty(Ty,"__esModule",{value:!0}),Ty.NestFieldDeclaration=void 0;const QZe=qZe(Xe),HZe=Wp,zZe=Ry,Gae=qn;class GZe extends zZe.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=Gae.LegalRefinementStage.Single,this.forceQueryClass=Gae.QueryClass.Grouping,this.turtleDef=void 0}queryExecute(e){e.resultFS.pushFields(this)}getFieldDef(e){if(this.turtleDef)return this.turtleDef;if(e.isQueryFieldSpace()){const{pipeline:r,annotation:i}=this.view.pipelineComp(e,e.outputSpace()),s=r[0]&&QZe.isQuerySegment(r[0])?r[0].compositeFieldUsage:void 0,o=(0,HZe.detectAndRemovePartialStages)(r,this);return this.turtleDef={type:"turtle",name:this.name,pipeline:o,annotation:{...this.note,inherits:i},location:this.location,compositeFieldUsage:s},this.turtleDef}throw this.internalError("Unexpected namespace for nest")}}Ty.NestFieldDeclaration=GZe;var Jp={},li={};Object.defineProperty(li,"__esModule",{value:!0}),li.ErrorFactory=void 0;const Wae="~malformed~";class yB{static get structDef(){return{type:"table",name:Wae,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],errorFactory:!0}}static get joinDef(){return{type:"table",name:Wae,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],join:"one",matrixOperation:"left",errorFactory:!0}}static didCreate(e){return e.type==="table"&&"errorFactory"in e}static get query(){return{structRef:yB.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}}li.ErrorFactory=yB,Object.defineProperty(Jp,"__esModule",{value:!0}),Jp.DefineSourceList=Jp.DefineSource=void 0;const WZe=li,Vae=Je,VZe=Mr;class YZe extends Vae.MalloyElement{constructor(e,r,i,s){super(),this.name=e,this.sourceExpr=r,this.exported=i,this.parameters=s,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=VZe.extendNoteMethod,r&&this.has({sourceExpr:r}),s&&this.has({parameters:s})}execute(e){var r;if(e.modelEntry(this.name))this.logError("source-definition-name-conflict",`Cannot redefine '${this.name}'`);else{const i=(r=this.sourceExpr)===null||r===void 0?void 0:r.getSource();if(i===void 0)return;const s=this.deduplicatedParameters(),o=i.withParameters(void 0,this.parameters);if(this.validateParameterShadowing(s,o),WZe.ErrorFactory.didCreate(o))return;const u={...o,as:this.name,location:this.location};this.note&&(u.annotation=o.annotation?{...this.note,inherits:o.annotation}:this.note),e.setEntry(this.name,{entry:u,exported:this.exported})}}deduplicatedParameters(){if(this.parameters===void 0)return[];const e={},r=[];for(const i of this.parameters)i.name in e&&i.logError("parameter-name-conflict",`Cannot redefine parameter \`${i.name}\``),e[i.name]=!0,r.push(i);return r}validateParameterShadowing(e,r){for(const i of e)r.fields.find(s=>{var o;return((o=s.as)!==null&&o!==void 0?o:s.name)===i.name})&&i.logError("parameter-shadowing-field",`Illegal shadowing of field \`${i.name}\` by parameter with the same name`)}}Jp.DefineSource=YZe;class KZe extends Vae.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}}Jp.DefineSourceList=KZe;var Xp={};Object.defineProperty(Xp,"__esModule",{value:!0}),Xp.DefineQueryList=Xp.DefineQuery=void 0;const Yae=Je,JZe=Mr;class XZe extends Yae.MalloyElement{constructor(e,r){super({queryExpr:r}),this.name=e,this.queryExpr=r,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=JZe.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.logError("query-definition-name-conflict",`'${this.name}' is already defined, cannot redefine`);return}const i=this.queryExpr.getQuery();if(!i){this.queryExpr.sqLog("query-definition-from-non-query","Cannot define a query from this expression");return}const s={...i.query(),type:"query",name:this.name,location:this.location};this.note&&(s.annotation=s.annotation?{...this.note,inherits:s.annotation}:this.note),e.setEntry(this.name,{entry:s,exported:!0})}}Xp.DefineQuery=XZe;class ZZe extends Yae.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}}Xp.DefineQueryList=ZZe;var Eo={};Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.Source=void 0;const eet=Je;class tet extends eet.MalloyElement{structRef(e){return{structRef:this.getSourceDef(e)}}packParameters(e){if(e===void 0)return;const r={};for(const i of e){const s=i.parameter();r[s.name]=s}return r}withParameters(e,r){return{...this.getSourceDef(e),parameters:this.packParameters(r)}}}Eo.Source=tet;var Oy={},Zp={},X4={},Fc={};Object.defineProperty(Fc,"__esModule",{value:!0}),Fc.mergeFields=Fc.nameFromDef=void 0;function EB(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}Fc.nameFromDef=EB;function net(t,e){if(t===void 0)return e;const r=new Set(e.map(s=>EB(s))),i=t.filter(s=>!r.has(EB(s)));return i.push(...e),i}Fc.mergeFields=net;var Fy={},Ur={},Ra={},ret=T&&T.__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]}),iet=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),set=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ret(e,t,r);return iet(e,t),e};Object.defineProperty(Ra,"__esModule",{value:!0}),Ra.DefinedParameter=Ra.AbstractParameter=Ra.SpaceParam=void 0;const oet=Oc,Kae=set(Zt),Jae=lt;class AB extends oet.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}}Ra.SpaceParam=AB;class uet extends AB{constructor(e){super(),this.astParam=e,this._parameter=void 0}parameter(){return this._parameter!==void 0?this._parameter:(this._parameter=this.astParam.parameter(),this._parameter)}typeDesc(){return{...Kae.atomicDef(this.parameter()),expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:(0,Jae.emptyCompositeFieldUsage)()}}entryType(){return this.parameter().type}}Ra.AbstractParameter=uet;class aet extends AB{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){return{...Kae.atomicDef(this.paramDef),expressionType:"scalar",evalSpace:"input",compositeFieldUsage:(0,Jae.emptyCompositeFieldUsage)()}}entryType(){return this.paramDef.type}}Ra.DefinedParameter=aet;var ed={},cet=T&&T.__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]}),fet=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xet=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&cet(e,t,r);return fet(e,t),e};Object.defineProperty(ed,"__esModule",{value:!0}),ed.StructSpaceFieldBase=void 0;const Xae=lt,det=Xe,het=xet(Zt),pet=Pr;class met extends pet.SpaceField{constructor(e){super(),this.structDef=e}fieldDef(){return this.structDef}get joinPathElement(){return{name:this.structDef.as||this.structDef.name,joinType:this.structDef.join,joinElementType:this.structDef.type}}typeDesc(){var e,r;return(0,det.isSourceDef)(this.structDef)?{type:this.structDef.type,evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(e=this.structDef.onCompositeFieldUsage)!==null&&e!==void 0?e:(0,Xae.emptyCompositeFieldUsage)()}:{...het.atomicDef(this.structDef),evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(r=this.structDef.onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Xae.emptyCompositeFieldUsage)()}}}ed.StructSpaceFieldBase=met;var wy={};Object.defineProperty(wy,"__esModule",{value:!0}),wy.ColumnSpaceField=void 0;const get=Pr;class yet extends get.SpaceField{constructor(e){super(),this.sourceFieldDef=e}fieldDef(){return this.sourceFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.sourceFieldDef)}constructorFieldDef(){return this.sourceFieldDef}}wy.ColumnSpaceField=yet;var Z4={};Object.defineProperty(Z4,"__esModule",{value:!0}),Z4.IRViewField=void 0;const Eet=Kp;class Aet extends Eet.ViewField{constructor(e,r){super(e),this.turtleDef=r}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}constructorFieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}}Z4.IRViewField=Aet,Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.StaticSourceSpace=Ur.StructSpaceField=Ur.StaticSpace=void 0;const _et=Ca,e2=Xe,vet=Ra,Cet=Pr,Ny=ed,bet=wy,Tet=Z4;class _B{constructor(e,r){this.type="fieldSpace",this.fromStruct=e,this.structDialect=r}dialectName(){return this.structDialect}dialectObj(){try{return(0,_et.getDialect)(this.structDialect)}catch{return}}defToSpaceField(e){return(0,e2.isJoined)(e)?new vB(e,this.structDialect):(0,e2.isTurtle)(e)?new Tet.IRViewField(this,e):new bet.ColumnSpaceField(e)}get map(){if(this.memoMap===void 0){this.memoMap={};for(const e of this.fromStruct.fields){const r=e.as||e.name;this.memoMap[r]=this.defToSpaceField(e)}if((0,e2.isSourceDef)(this.fromStruct)&&this.fromStruct.parameters)for(const[e,r]of Object.entries(this.fromStruct.parameters))e in this.memoMap||(this.memoMap[e]=new vet.DefinedParameter(r))}return this.memoMap}isProtectedAccessSpace(){return!1}dropEntries(){this.memoMap={}}dropEntry(e){delete this.map[e]}entry(e){return this.map[e]}setEntry(e,r){this.map[e]=r}entries(){return Object.entries(this.map)}structDef(){return this.fromStruct}emptyStructDef(){const e={...this.fromStruct};return(0,e2.isSourceDef)(e)&&(e.parameters={}),e.fields=[],e}lookup(e){const r=e[0],i=e.slice(1);let s=this.entry(r.refString);if(!s)return{error:{message:`'${r}' is not defined`,code:"field-not-found"},found:s};if(s instanceof Cet.SpaceField){const u=s.fieldDef();if(u&&(!(s instanceof Ny.StructSpaceFieldBase)&&(0,e2.isJoined)(u)&&(s=new vB(u,this.structDialect)),r.addReference({type:s instanceof Ny.StructSpaceFieldBase?"joinReference":"fieldReference",definition:u,location:r.location,text:r.refString})),u!=null&&u.accessModifier&&!(this.isProtectedAccessSpace()&&u.accessModifier==="internal"&&e.length===1))return{error:{message:`'${r}' is ${u==null?void 0:u.accessModifier}`,code:"field-not-accessible"},found:void 0}}const o=s instanceof Ny.StructSpaceFieldBase?[{...s.joinPathElement,name:r.refString}]:[];if(i.length){if(s instanceof Ny.StructSpaceFieldBase){const u=s.fieldSpace.lookup(i);return u.found?{...u,joinPath:[...o,...u.joinPath]}:u}return{error:{message:`'${r}' cannot contain a '${i[0]}'`,code:"invalid-property-access-in-field-reference"},found:void 0}}return{found:s,error:void 0,joinPath:o,isOutputField:!1}}isQueryFieldSpace(){return!1}}Ur.StaticSpace=_B;class vB extends Ny.StructSpaceFieldBase{constructor(e,r){super(e),this.forDialect=r}get fieldSpace(){return(0,e2.isSourceDef)(this.structDef)?new Zae(this.structDef):new _B(this.structDef,this.forDialect)}}Ur.StructSpaceField=vB;class Zae extends _B{constructor(e){super(e,e.dialect),this.source=e}structDef(){return this.source}emptyStructDef(){const e={...this.source};return e.parameters={},e.fields=[],e}}Ur.StaticSourceSpace=Zae,Object.defineProperty(Fy,"__esModule",{value:!0}),Fy.JoinSpaceField=void 0;const Ret=Ur;class Det extends Ret.StructSpaceField{constructor(e,r,i){super(r.structDef(e),i),this.parameterSpace=e,this.join=r}}Fy.JoinSpaceField=Det;var t2={};Object.defineProperty(t2,"__esModule",{value:!0}),t2.ParameterSpace=void 0;const Oet=Ra;class Fet{constructor(e){this.type="fieldSpace",this._map={};for(const r of e)this._map[r.name]=new Oet.AbstractParameter(r)}structDef(){throw new Error("Parameter space does not have a structDef")}emptyStructDef(){throw new Error("Parameter space does not have an emptyStructDef")}entry(e){return this._map[e]}lookup(e){const r=e[0];if(r===void 0)return{error:{message:"Invalid reference",code:"invalid-parameter-reference"},found:void 0};const i=this.entry(r.refString);return i===void 0?{error:{message:`\`${r}\` is not defined`,code:"parameter-not-found"},found:void 0}:e.length>1?{error:{message:`\`${r}\` cannot contain a \`${e.slice(1).join(".")}\``,code:"invalid-parameter-reference"},found:void 0}:{found:i,error:void 0,joinPath:[],isOutputField:!1}}entries(){return Object.entries(this._map)}dialectName(){return"~parameter-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}t2.ParameterSpace=Fet;var wet=T&&T.__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]}),Net=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Let=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&wet(e,t,r);return Net(e,t),e};Object.defineProperty(X4,"__esModule",{value:!0}),X4.DynamicSpace=void 0;const Iet=Let(Xe),$et=Fc,Bet=li,ket=Pr,Met=Fy,Pet=Kp,ele=Ra,Uet=Ur,jet=ed,qet=t2;class Qet extends Uet.StaticSpace{constructor(e){super(structuredClone(e),e.dialect),this.complete=!1,this.parameters=[],this.newAccessModifiers=new Map,this.newNotes=new Map,this.fromSource=e,this.sourceDef=void 0}setEntry(e,r){if(this.complete)throw new Error("Space already final");super.setEntry(e,r)}addParameters(e){for(const r of e)this.entry(r.name)===void 0&&(this.parameters.push(r),this.setEntry(r.name,new ele.AbstractParameter(r)));return this}parameterSpace(){return new qet.ParameterSpace(this.parameters)}newEntry(e,r,i){if(this.entry(e)){r.logError("definition-name-conflict",`Cannot redefine '${e}'`);return}this.setEntry(e,i)}renameEntry(e,r,i){this.dropEntry(e),this.setEntry(r,i)}addFieldDef(e){this.setEntry((0,$et.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){if(this.complete=!0,this.sourceDef===void 0){const e={};for(const[l,c]of this.entries())c instanceof ele.SpaceParam&&(e[l]=c.parameter());this.sourceDef={...this.fromSource,fields:[]},this.sourceDef.parameters=e;const r=new Map,i=[],s=[],o=[];for(const[l,c]of this.entries())c instanceof jet.StructSpaceFieldBase?s.push([l,c]):c instanceof Pet.ViewField?o.push([l,c]):c instanceof ket.SpaceField&&i.push([l,c]);const u=[...i,...s,...o],a=this.parameterSpace();for(const[l,c]of u)if(c instanceof Met.JoinSpaceField){const f=c.join.structDef(a);Bet.ErrorFactory.didCreate(f)||(r.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f),c.join.fixupJoinOn(this,f))}else{const f=c.fieldDef();f&&(r.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f))}for(const[l,c]of this.newAccessModifiers){const f=this.sourceDef.fields.findIndex(x=>{var h;return(h=x.as)!==null&&h!==void 0?h:x.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);c==="public"?delete this.sourceDef.fields[f].accessModifier:this.sourceDef.fields[f]={...this.sourceDef.fields[f],accessModifier:c}}for(const[l,c]of this.newNotes){const f=this.sourceDef.fields.findIndex(h=>{var p;return(p=h.as)!==null&&p!==void 0?p:h.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);const x=this.sourceDef.fields[f];this.sourceDef.fields[f]={...x,annotation:{...c,inherits:x.annotation}}}}return this.newTimezone&&Iet.isSourceDef(this.sourceDef)&&(this.sourceDef.queryTimezone=this.newTimezone),this.sourceDef}emptyStructDef(){const e={...this.fromSource};return e.fields=[],e}}X4.DynamicSpace=Qet;var Ly={};Object.defineProperty(Ly,"__esModule",{value:!0}),Ly.RenameSpaceField=void 0;const Het=Pr;class zet extends Het.SpaceField{constructor(e,r,i){super(),this.otherField=e,this.newName=r,this.location=i}fieldDef(){const e=this.otherField.fieldDef();if(e!==void 0)return{...e,as:this.newName,location:this.location}}typeDesc(){return this.otherField.typeDesc()}}Ly.RenameSpaceField=zet,Object.defineProperty(Zp,"__esModule",{value:!0}),Zp.RefinedSpace=void 0;const Get=X4,Wet=Oc,Vet=Ly,Yet=Pr;class CB extends Get.DynamicSpace{static filteredFrom(e,r,i,s,o){const u=new CB(e),a=new Map;for(const l of s??[])a.has(l.name.refString)?l.name.logError("already-renamed",`${l.name.refString} already renamed to ${l.as}`):a.set(l.name.refString,{as:l.as,location:l.location,logTo:l.name});if(i!==void 0){const l=u.entries();u.dropEntries();for(const[c,f]of l)if(i.has(c)){const x=a.get(c);x?f instanceof Yet.SpaceField?u.setEntry(x.as,new Vet.RenameSpaceField(f,x.as,x.location)):x.logTo.logError("cannot-rename-non-field",`Cannot rename \`${c}\` which is not a field`):u.setEntry(c,f)}r!==void 0&&r.logError("accept-except-not-compatible-with-include","Can't use `accept:` or `except:` with `include`")}else if(r){const l=r.refs.list,c=u.entries();for(const f of l)c.find(([h])=>h===f.refString)===void 0&&(o!=null&&o.entry(f.refString)?f.logError(`${r.edit}-parameter`,`Illegal \`${r.edit}:\` of parameter`):f.logError("field-list-edit-not-found",`\`${f.refString}\` is not defined`));u.dropEntries();for(const[f,x]of c){const h=!!l.find(m=>m.refString===f),p=r.edit==="accept";h===p&&u.setEntry(f,x)}}return u}pushFields(...e){for(const r of e)this.addField(r)}addField(e){(0,Wet.canMakeEntry)(e)?e.makeEntry(this):e.logError("unexpected-element-type",`Internal error, ${e.elementType} not expected in this context`)}addAccessModifiers(e){for(const[r,i]of e)this.newAccessModifiers.set(r,i)}addNotes(e){for(const[r,i]of e)this.newNotes.set(r,i)}isProtectedAccessSpace(){return!0}}Zp.RefinedSpace=CB;var wc={},Ms={};Object.defineProperty(Ms,"__esModule",{value:!0}),Ms.DefinitionList=void 0;const Ket=Je,tle=Mr;class Jet extends Ket.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,tle.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(const e of this.elements)(0,tle.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}}Ms.DefinitionList=Jet,Object.defineProperty(wc,"__esModule",{value:!0}),wc.DeclareFields=void 0;const Xet=Ms,Zet=qn;class ett extends Xet.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="declareFields",this.queryRefinementStage=Zet.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(const r of this.list)e.inputFS.extendSource(r)}get delarationNames(){return this.list.map(e=>e.defineName)}}wc.DeclareFields=ett;var Da={};Object.defineProperty(Da,"__esModule",{value:!0}),Da.Filter=Da.FilterElement=void 0;const nle=Xe,ttt=Vn,rle=Je,SB=qn;class ntt extends rle.MalloyElement{constructor(e,r){super({expr:e}),this.expr=e,this.exprSrc=r,this.elementType="filterElement"}filterCondition(e){const r=this.expr.getExpression(e);return r.type!=="boolean"?(this.expr.logError("non-boolean-filter","Filter expression must have boolean value"),{node:"filterCondition",code:this.exprSrc,e:{node:"false"},expressionType:"scalar",compositeFieldUsage:r.compositeFieldUsage}):{node:"filterCondition",code:this.exprSrc,e:r.value,expressionType:r.expressionType,compositeFieldUsage:r.compositeFieldUsage}}}Da.FilterElement=ntt;class rtt extends rle.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=SB.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?SB.LegalRefinementStage.Tail:SB.LegalRefinementStage.Head}checkedFilterCondition(e,r){const i=r.filterCondition(e);if(this.havingClause!==void 0){const s=(0,nle.expressionIsAggregate)(i.expressionType),o=(0,nle.expressionIsAnalytic)(i.expressionType);if(this.havingClause){if(o){r.logError("analytic-in-having","Analytic expressions are not allowed in `having:`");return}}else if(o){r.logError("analytic-in-where","Analytic expressions are not allowed in `where:`");return}else s&&r.logError("aggregate-in-where","Aggregate expressions are not allowed in `where:`; use `having:`")}return i}getFilterList(e){return this.list.map(r=>this.checkedFilterCondition(e,r)).filter(ttt.isNotUndefined)}queryExecute(e){const r=this.havingClause?e.resultFS:e.inputFS;for(const i of this.list){const s=this.checkedFilterCondition(r,i);s!==void 0&&(e.filters.push(s),e.resultFS.addCompositeFieldUserFromFilter(s,i))}}}Da.Filter=rtt;var n2={};Object.defineProperty(n2,"__esModule",{value:!0}),n2.FieldListEdit=void 0;const itt=Je;class stt extends itt.MalloyElement{constructor(e,r){super({refs:r}),this.edit=e,this.refs=r,this.elementType="fieldListEdit"}}n2.FieldListEdit=stt;var r2={};Object.defineProperty(r2,"__esModule",{value:!0}),r2.PrimaryKey=void 0;const ott=Je;class utt extends ott.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}}r2.PrimaryKey=utt;var i2={};Object.defineProperty(i2,"__esModule",{value:!0}),i2.Views=void 0;const att=Ms;class ltt extends att.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="turtleDefList"}get delarationNames(){return this.list.map(e=>e.name)}}i2.Views=ltt;var s2={};Object.defineProperty(s2,"__esModule",{value:!0}),s2.TimezoneStatement=void 0;const ctt=Je,ftt=Cy;class xtt extends ctt.MalloyElement{constructor(e){super(),this.tz=e,this.elementType="timezone",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}get isValid(){try{return ftt.DateTime.fromISO("2020-02-19T00:00:00",{zone:this.tz}),!0}catch{return!1}}queryExecute(e){e.resultFS.setTimezone(this.tz)}}s2.TimezoneStatement=xtt;var Nc={};Object.defineProperty(Nc,"__esModule",{value:!0}),Nc.ModelAnnotation=Nc.ObjectAnnotation=void 0;const dtt=Je,htt=ai;class ile extends dtt.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}}Nc.ObjectAnnotation=ile;class ptt extends ile{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,r){const i=(0,htt.annotationToTag)({notes:this.notes},{prefix:/^##! /,extending:e});return i.log.forEach(s=>r.log(s)),i.tag}execute(e){e.annotation.notes===void 0&&(e.annotation.notes=[]),e.annotation.notes.push(...this.notes)}}Nc.ModelAnnotation=ptt;var Lc={};Object.defineProperty(Lc,"__esModule",{value:!0}),Lc.Renames=Lc.RenameField=void 0;const mtt=Ly,sle=Je,gtt=Pr;class ytt extends sle.MalloyElement{constructor(e,r){super(),this.newName=e,this.oldName=r,this.elementType="renameField",this.has({oldName:r})}makeEntry(e){if(this.oldName.refString===this.newName){this.logError("invalid-rename-with-same-name","Can't rename field to itself");return}const r=this.oldName.getField(e);r.found?r.found instanceof gtt.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new mtt.RenameSpaceField(r.found,this.newName,this.location)):this.logError("failed-rename",`'${this.oldName}' cannot be renamed`):this.logError("rename-field-not-found",`Can't rename '${this.oldName}', no such field`)}getName(){return this.newName}}Lc.RenameField=ytt;class Ett extends sle.ListOf{constructor(e,r){super(e),this.accessModifier=r,this.elementType="renameFields"}get delarationNames(){return this.list.map(e=>e.getName())}}Lc.Renames=Ett;var hs={};Object.defineProperty(hs,"__esModule",{value:!0}),hs.JoinStatement=hs.ExpressionJoin=hs.KeyJoin=hs.Join=void 0;const bB=Xe,Att=Fy,_tt=Ms,vtt=Je,Ctt=Mr,ole=li,Stt=qn;class TB extends vtt.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=Ctt.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new Att.JoinSpaceField(e.parameterSpace(),this,e.dialectName()))}getName(){return this.name.refString}getStructDefFromExpr(e){const r=this.sourceExpr.getSource();return r?r.getSourceDef(e):(this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),ole.ErrorFactory.structDef)}}hs.Join=TB;class btt extends TB{constructor(e,r,i){super({name:e,sourceExpr:r,keyExpr:i}),this.name=e,this.sourceExpr=r,this.keyExpr=i,this.elementType="joinOnKey"}structDef(e){var r;const i=this.getStructDefFromExpr(e);if(!(0,bB.isJoinable)(i))throw this.internalError(`Cannot join struct type '${i.type}'`);const s={...i,name:this.name.refString,join:"one",matrixOperation:"left",onExpression:{node:"error",message:"('join fixup'='not done yet')"},location:this.location};return delete s.as,this.note&&(s.annotation=this.note),(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(s),s}fixupJoinOn(e,r){const i=this.keyExpr.getExpression(e);if((0,bB.isSourceDef)(r)&&r.primaryKey){const s=r.fields.find(o=>(o.as||o.name)===r.primaryKey);if(s)if(s.type===i.type){r.join="one",r.onExpression={node:"=",kids:{left:{node:"field",path:[this.name.refString,r.primaryKey]},right:i.value}},r.onCompositeFieldUsage=i.compositeFieldUsage;return}else this.logError("join-on-primary-key-type-mismatch",`join_one: with type mismatch with primary key: ${i.type}/${s.type}`);else this.logError("join-primary-key-not-found",`join_one: Primary key '${s}' not found in source`)}else this.logError("join-with-without-primary-key","join_one: Cannot use with unless source has a primary key")}}hs.KeyJoin=btt;class Ttt extends TB{constructor(e,r){super({name:e,sourceExpr:r}),this.name=e,this.sourceExpr=r,this.elementType="joinOnExpr",this.joinType="one",this.matrixOperation="left"}set joinOn(e){this.expr=e,this.has({on:e})}get joinOn(){return this.expr}fixupJoinOn(e,r){if(this.expr===void 0)return;const i=this.expr.getExpression(e);if(i.type!=="boolean"){this.logError("non-boolean-join-on","join conditions must be boolean expressions");return}r.onExpression=i.value,r.onCompositeFieldUsage=i.compositeFieldUsage}structDef(e){var r;const i=this.sourceExpr.getSource();if(!i)return this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),ole.ErrorFactory.joinDef;const s=i.getSourceDef(e);let o="left";if(this.inExperiment("join_types",!0)&&(o=this.matrixOperation),!(0,bB.isJoinable)(s))throw this.internalError(`Can't join struct type ${s.type}`);const u={...s,name:this.name.refString,join:this.joinType,matrixOperation:o,location:this.location};return delete u.as,this.note&&(u.annotation=this.note),(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(u),u}}hs.ExpressionJoin=Ttt;class Rtt extends _tt.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="joinStatement",this.forceQueryClass=void 0,this.queryRefinementStage=Stt.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)e.inputFS.extendSource(r),e.alwaysJoins.push(r.name.refString)}get delarationNames(){return this.list.map(e=>e.name.refString)}}hs.JoinStatement=Rtt;var du={};Object.defineProperty(du,"__esModule",{value:!0}),du.IncludeListItem=du.IncludeExceptItem=du.IncludeAccessItem=du.IncludeItem=void 0;const ule=Je,ale=Mr;class RB extends ule.MalloyElement{}du.IncludeItem=RB;class Dtt extends RB{constructor(e,r){super(),this.kind=e,this.fields=r,this.elementType="include-access-item",this.isNoteableObj=!0,this.extendNote=ale.extendNoteMethod,this.has({fields:r})}}du.IncludeAccessItem=Dtt;class Ott extends RB{constructor(e){super(),this.fields=e,this.elementType="include-except-item",this.kind="except",this.has({fields:e})}}du.IncludeExceptItem=Ott;class Ftt extends ule.MalloyElement{constructor(e,r){super({name:e}),this.name=e,this.as=r,this.elementType="include-list-item",this.isNoteableObj=!0,this.extendNote=ale.extendNoteMethod}}du.IncludeListItem=Ftt;var yt={},Iy={},wtt=T&&T.__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]}),Ntt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ltt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&wtt(e,t,r);return Ntt(e,t),e};Object.defineProperty(Iy,"__esModule",{value:!0}),Iy.ReferenceField=void 0;const lle=Xe,cle=Ltt(Zt),fle=Pr,Itt=lt;class $tt extends fle.SpaceField{constructor(e,r){super(),this.fieldRef=e,this.inFS=r,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){if(!this.queryFieldDef){const r=this.fieldRef.getField(e);r.error&&this.fieldRef.logError(r.error.code,r.error.message);const i=this.fieldRef.path;if(r.found&&r.found.refType==="parameter"){const o=r.found.typeDesc();if(lle.TD.isAtomic(o))this.queryFieldDef={...(0,lle.mkFieldDef)(cle.atomicDef(o),i[0]),e:{node:"parameter",path:i}};else throw new Error("impossible turtle/join parameter")}else this.queryFieldDef={type:"fieldref",path:i};const s=this.referenceTo;if(s instanceof fle.SpaceField){const o=s.constructorFieldDef();if(o){const u=this.fieldRef.note;if(o.annotation||u){const a=u||{};o.annotation&&(a.inherits=o.annotation),this.queryFieldDef.annotation=a}}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;const e=this.referenceTo;if(e){const r=this.fieldRef.list.slice(0,-1).map(s=>s.refString),i=e.typeDesc();return this.memoTypeDesc={...i,compositeFieldUsage:(0,Itt.joinedCompositeFieldUsage)(r,i.compositeFieldUsage)},this.memoTypeDesc}return cle.errorT}}Iy.ReferenceField=$tt;var sr={};Object.defineProperty(sr,"__esModule",{value:!0}),sr.typecheckGroupBy=sr.typecheckAggregate=sr.typecheckCalculate=sr.typecheckDeclare=sr.typecheckMeasure=sr.typecheckDimension=sr.typecheckIndex=sr.typecheckProject=void 0;const $n=ji;function Btt(t,e){if(t.type==="turtle"||!(0,$n.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="select-of-view";else if((0,$n.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="select-of-analytic";else if((0,$n.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="select-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a select operation, did you mean to use ${r} operation instead?`)}}sr.typecheckProject=Btt;function ktt(t,e){if(t.type==="turtle"||!(0,$n.expressionIsScalar)(t.expressionType)){let r,i;if(t.type==="turtle")r="a view",i="index-of-view";else if((0,$n.expressionIsAnalytic)(t.expressionType))r="an analytic",i="index-of-analytic";else if((0,$n.expressionIsAggregate)(t.expressionType))r="an aggregate",i="index-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in an index operation`)}}sr.typecheckIndex=ktt;function Mtt(t,e){if(!(0,$n.expressionIsScalar)(t.expressionType))if((0,$n.expressionIsAggregate)(t.expressionType))e.logError("aggregate-in-dimension","Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,$n.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-dimension","Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}sr.typecheckDimension=Mtt;function Ptt(t,e){if(!(0,$n.expressionIsAggregate)(t.expressionType))if((0,$n.expressionIsScalar)(t.expressionType))e.logError("scalar-in-measure","Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,$n.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-measure","Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}sr.typecheckMeasure=Ptt;function Utt(t,e){t.type==="turtle"?e.logError("view-in-declare","Views cannot be used in a declare block"):(0,$n.expressionIsAnalytic)(t.expressionType)&&e.logError("analytic-in-declare","Analytic expressions can not be used in a declare block")}sr.typecheckDeclare=Utt;function jtt(t,e){if(t.type==="turtle"||!(0,$n.expressionIsAnalytic)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="calculate-of-view";else if((0,$n.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="calculate-of-aggregate";else if((0,$n.expressionIsScalar)(t.expressionType))r="a group_by or select",i="a scalar",s="calculate-of-scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a calculate operation, did you mean to use ${r} operation instead?`)}}sr.typecheckCalculate=jtt;function qtt(t,e){if(t.type==="turtle"||!(0,$n.expressionIsAggregate)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="aggregate-of-view";else if((0,$n.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="aggregate-of-analytic";else if((0,$n.expressionIsScalar)(t.expressionType))r="a group_by or select",i="a scalar",s="aggregate-of-scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.logError(s,`Cannot use ${i} field in an aggregate operation, did you mean to use ${r} operation instead?`)}}sr.typecheckAggregate=qtt;function Qtt(t,e){if(t.type==="turtle"||!(0,$n.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="group-by-view";else if((0,$n.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="group-by-analytic";else if((0,$n.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="group-by-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a group_by operation, did you mean to use ${r} operation instead?`)}}sr.typecheckGroupBy=Qtt,Object.defineProperty(yt,"__esModule",{value:!0}),yt.FieldReferences=yt.WildcardFieldReference=yt.ViewOrScalarFieldReference=yt.DimensionFieldReference=yt.MeasureFieldReference=yt.DeclareFieldReference=yt.ProjectFieldReference=yt.GroupByFieldReference=yt.AggregateFieldReference=yt.IndexFieldReference=yt.CalculateFieldReference=yt.ParameterFieldReference=yt.PartitionByFieldReference=yt.ExpressionFieldReference=yt.AccessModifierFieldReference=yt.AcceptExceptFieldReference=yt.FieldReference=void 0;const Htt=Iy,ztt=Ms,xle=Je,dle=Mr,Ic=sr;class Hi extends xle.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=dle.extendNoteMethod}makeEntry(e){const r=this.outputName;if(e.entry(r))this.logError("output-name-conflict",`Output already has a field named '${r}'`);else{const i=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(r,this,new Htt.ReferenceField(this,i))}}getName(){return this.nameString}get refToField(){return{type:"fieldref",path:this.list.map(e=>e.refString)}}get refString(){return this.path.join(".")}get path(){return this.list.map(e=>e.refString)}get outputName(){return this.list[this.list.length-1].refString}get sourceString(){if(this.list.length>1)return this.list.slice(0,-1).map(e=>e.refString).join(".")}get nameString(){return this.list[this.list.length-1].refString}getField(e){const r=e.lookup(this.list);if(r.found){const i=r.found.typeDesc();this.typecheck(i)}return r}}yt.FieldReference=Hi;class Gtt extends Hi{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}yt.AcceptExceptFieldReference=Gtt;class Wtt extends Hi{constructor(){super(...arguments),this.elementType="accessModifierFieldReference"}typecheck(){}}yt.AccessModifierFieldReference=Wtt;class Vtt extends Hi{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}yt.ExpressionFieldReference=Vtt;class Ytt extends Hi{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}yt.PartitionByFieldReference=Ytt;class Ktt extends Hi{constructor(){super(...arguments),this.elementType="parameterFieldReference"}typecheck(){}}yt.ParameterFieldReference=Ktt;class Jtt extends Hi{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,Ic.typecheckCalculate)(e,this)}}yt.CalculateFieldReference=Jtt;class DB extends Hi{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,Ic.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return DB.indexOutputName(this.path)}}yt.IndexFieldReference=DB;class Xtt extends Hi{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,Ic.typecheckAggregate)(e,this)}}yt.AggregateFieldReference=Xtt;class Ztt extends Hi{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,Ic.typecheckGroupBy)(e,this)}}yt.GroupByFieldReference=Ztt;class ent extends Hi{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,Ic.typecheckProject)(e,this)}}yt.ProjectFieldReference=ent;class tnt extends Hi{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,Ic.typecheckDeclare)(e,this)}}yt.DeclareFieldReference=tnt;class nnt extends Hi{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,Ic.typecheckMeasure)(e,this)}}yt.MeasureFieldReference=nnt;class rnt extends Hi{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,Ic.typecheckDimension)(e,this)}}yt.DimensionFieldReference=rnt;class int extends Hi{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}yt.ViewOrScalarFieldReference=int;class snt extends xle.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=dle.extendNoteMethod,this.except=new Set,this.has({joinPath:e})}getFieldDef(){throw this.internalError("fielddef request from wildcard reference")}get refString(){return this.joinPath?`${this.joinPath.refString}.*`:"*"}}yt.WildcardFieldReference=snt;class ont extends ztt.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}yt.FieldReferences=ont,Object.defineProperty(Oy,"__esModule",{value:!0}),Oy.RefinedSource=void 0;const unt=Xe,ant=Zp,lnt=wc,cnt=Da,fnt=n2,xnt=r2,dnt=i2,hnt=Eo,pnt=s2,mnt=Nc,gnt=Lc,ynt=t2,Ent=hs,hle=du,OB=yt;class Ant extends hnt.Source{constructor(e,r,i){super({source:e,refinement:r}),this.source=e,this.refinement=r,this.includeList=i,this.elementType="refinedSource",i&&this.has({includeList:i})}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){var i;let s,o;const u=[],a=[];let l;const c=[];for(const v of this.refinement.list){if(v instanceof mnt.ObjectAnnotation)continue;const C=v;if(v instanceof xnt.PrimaryKey){if(s){const b="multiple-primary-keys";s.logError(b,"Primary key already defined"),v.logError(b,"Primary key redefined")}s=v}else if(v instanceof fnt.FieldListEdit){if(o){const b="multiple-field-list-edits";o.logError(b,"Too many accept/except statements"),v.logError(b,"Too many accept/except statements")}o=v}else v instanceof lnt.DeclareFields||v instanceof Ent.JoinStatement||v instanceof dnt.Views||v instanceof gnt.Renames?(u.push(...v.list),v.accessModifier&&c.push({fields:v.delarationNames,access:v.accessModifier})):v instanceof cnt.Filter?a.push(v):v instanceof pnt.TimezoneStatement?l=v.tz:C.logError("unexpected-source-property",`Unexpected source property: '${C.elementType}'`)}const f=r?new ynt.ParameterSpace(r):void 0,x=structuredClone(this.source.getSourceDef(f)),{fieldsToInclude:h,modifiers:p,renames:m,notes:y}=_nt(this.includeList,x);for(const v of c)for(const C of v.fields)p.set(C,v.access);s&&(x.primaryKey=s.field.name);const g=ant.RefinedSpace.filteredFrom(x,o,h,m,f);if(l&&g.setTimezone(l),r&&g.addParameters(r),g.pushFields(...u),s){const v=s.field.getField(g);v.error&&s.logError(v.error.code,v.error.message)}g.addAccessModifiers(p),g.addNotes(y);const E=g.structDef(),A=E.filterList||[];let _=!1;for(const v of a)for(const C of v.list){const b=C.filterCondition(g);(0,unt.expressionIsCalculation)(b.expressionType)?C.logError("aggregate-in-source-filter","Can't use aggregate computations in top level filters"):(A.push(b),_=!0)}return _?{...E,filterList:A}:((i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(E),E)}}Oy.RefinedSource=Ant;function _nt(t,e){var r,i,s,o,u,a,l,c,f;const x=new Set(e.fields.map(b=>b.name)),h=new Set(e.fields.filter(b=>b.accessModifier==="private").map(b=>b.name));let p;const m=new Set;let y,g;const E=new Map,A=[],_=new Map;if(t===void 0)return{fieldsToInclude:void 0,modifiers:E,renames:A,notes:_};for(const b of t)if(b instanceof hle.IncludeAccessItem)for(const S of b.fields)if(S.name instanceof OB.WildcardFieldReference)S.name.joinPath&&S.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"),y!==void 0?b.logError("already-used-star-in-include","Wildcard already used in this include block"):(y=(r=b.kind)!==null&&r!==void 0?r:"inherit",g={notes:(s=(i=S.note)===null||i===void 0?void 0:i.notes)!==null&&s!==void 0?s:[],blockNotes:(u=(o=b.note)===null||o===void 0?void 0:o.blockNotes)!==null&&u!==void 0?u:[]});else{if(p==="exclude"){b.logError("include-after-exclude","Cannot include specific fields if specific fields are already excluded");continue}p="include";const R=S.name.refString;h.has(R)&&S.logError("cannot-expand-access",`Cannot expand access of \`${R}\` from private to ${b.kind}`),E.has(R)?S.logError("duplicate-include",`Field \`${R}\` already referenced in include list`):(b.kind!==void 0&&E.set(R,b.kind),m.add(R),(S.note||b.note)&&_.set(R,{notes:(l=(a=S.note)===null||a===void 0?void 0:a.notes)!==null&&l!==void 0?l:[],blockNotes:(f=(c=b.note)===null||c===void 0?void 0:c.blockNotes)!==null&&f!==void 0?f:[]})),S.as&&(S.name instanceof OB.WildcardFieldReference?S.logError("wildcard-include-rename","Cannot rename a wildcard field in an `include` block"):A.push({name:S.name,as:S.as,location:S.location}))}else if(b instanceof hle.IncludeExceptItem)for(const S of b.fields)S instanceof OB.WildcardFieldReference?S.joinPath?S.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"):S.logWarning("wildcard-except-redundant","`except: *` is implied, unless another clause uses *"):p==="include"?b.logError("exclude-after-include","Cannot exclude specific fields if specific fields are already included"):(p="exclude",y="inherit",m.add(S.refString));const v=new Set(x);m.forEach(b=>v.delete(b)),h.forEach(b=>v.delete(b));let C;if(y!==void 0)for(const b of v)y!=="inherit"&&E.set(b,y),g&&_.set(b,{...g});return p!=="exclude"?y!==void 0?C=x:C=m:C=v,{fieldsToInclude:C,modifiers:E,renames:A,notes:_}}var hu={};Object.defineProperty(hu,"__esModule",{value:!0}),hu.SourceQueryElement=void 0;const vnt=Je;class FB extends vnt.MalloyElement{constructor(){super(...arguments),this.errored=!1}getSource(){}getQuery(){}isSource(){return!1}sqLog(e,r,i){return this.isErrorFree()&&this.logError(e,r,i),this.errored=!0,e}isErrorFree(){if(this.errored)return!1;let e=!0;for(const r of this.walk())if(r instanceof FB&&r.errored){e=!1;break}return e}}hu.SourceQueryElement=FB;var eb={},td={};Object.defineProperty(td,"__esModule",{value:!0}),td.QuerySource=void 0;const Cnt=Eo,Snt=Up;class bnt extends Cnt.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}getSourceDef(e){return this.withParameters(e,void 0)}withParameters(e,r){var i;const s=this.query.queryComp(!1),o={...s.outputStruct,name:`QuerySource-${(0,Snt.v4)()}`,type:"query_source",query:s.query};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(o),{...o,parameters:this.packParameters(r)}}}td.QuerySource=bnt;var o2={},$y={};Object.defineProperty($y,"__esModule",{value:!0}),$y.QueryBase=void 0;const wB=lt,ple=Xe,Tnt=Wp,Rnt=Je;class Dnt extends Rnt.MalloyElement{resolveCompositeSource(e,r){var i;const s=r.pipeline[0];if(s&&((0,ple.isQuerySegment)(s)||(0,ple.isIndexSegment)(s))){const o=(i=s.compositeFieldUsage)!==null&&i!==void 0?i:(0,wB.emptyCompositeFieldUsage)();if(!(0,wB.isEmptyCompositeFieldUsage)(o)||e.type==="composite")return(0,wB.resolveCompositeSources)(e,o).sourceDef}}query(){const{query:e}=this.queryComp(!0);return{...e,pipeline:(0,Tnt.detectAndRemovePartialStages)(e.pipeline,this)}}}$y.QueryBase=Dnt,Object.defineProperty(o2,"__esModule",{value:!0}),o2.QueryArrow=void 0;const Ont=Xe,Fnt=Eo,mle=Ur,wnt=$y;class Nnt extends wnt.QueryBase{constructor(e,r){super({source:e,view:r}),this.source=e,this.view=r,this.elementType="arrow"}queryComp(e){var r;let i,s,o;if(this.source instanceof Fnt.Source){const h=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)};s={type:"query",...h,pipeline:[],location:this.location},i=(0,Ont.refIsStructDef)(h.structRef)?h.structRef:this.source.getSourceDef(void 0),o=new mle.StaticSourceSpace(i)}else{const h=this.source.queryComp(e);s=h.query,i=h.outputStruct,o=new mle.StaticSourceSpace(h.outputStruct)}const{pipeline:u,annotation:a,outputStruct:l,name:c}=this.view.pipelineComp(o),f={...s,name:c,annotation:a,pipeline:[...s.pipeline,...u]},x=(r=f.compositeResolvedSourceDef)!==null&&r!==void 0?r:this.resolveCompositeSource(i,f);return{query:{...f,compositeResolvedSourceDef:x},outputStruct:l,inputStruct:i}}}o2.QueryArrow=Nnt,Object.defineProperty(eb,"__esModule",{value:!0}),eb.SQArrow=void 0;const Lnt=hu,Int=td,$nt=o2;class Bnt extends Lnt.SourceQueryElement{constructor(e,r){super({applyTo:e,operation:r}),this.applyTo=e,this.operation=r,this.elementType="sq-arrow"}getQuery(){const e=this.applyTo.isSource()?this.applyTo.getSource():this.applyTo.getQuery();if(e===void 0){this.sqLog("failed-to-compute-arrow-source","Could not get LHS of arrow operation");return}const r=new $nt.QueryArrow(e,this.operation);return this.has({query:r}),r}getSource(){const e=this.getQuery();if(!e){this.sqLog("failed-to-compute-source-from-query","Couldn't comprehend query well enough to make a source");return}const r=new Int.QuerySource(e);return this.has({asSource:r}),r}}eb.SQArrow=Bnt;var tb={},u2={},Ps={};Object.defineProperty(Ps,"__esModule",{value:!0}),Ps.getStructFieldDef=Ps.getFinalStruct=Ps.opOutputStruct=void 0;const gle=cc,knt=$s,nb=Xe,yle=li;function Ele(t,e,r){const i=yle.ErrorFactory.didCreate(e)||(0,nb.structHasErrors)(e);(0,nb.isPartialSegment)(r)&&(r={...r,type:"reduce"});const s=(0,nb.segmentHasErrors)(r);if(!i&&!s)try{const o=knt.Segment.nextStructDef(e,r);if((0,nb.isSourceDef)(o))return o;t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: RETURNED A NON SOURCE
|
|
1158
1158
|
STRUCTDEF: ${(0,gle.inspect)(o,{breakLength:72,depth:1/0})}`)}catch(o){t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: ${o.message}
|
|
1159
1159
|
QUERY: ${(0,gle.inspect)(r,{breakLength:72,depth:1/0})}`)}return yle.ErrorFactory.structDef}Ps.opOutputStruct=Ele;function Mnt(t,e,r){for(const i of r)e=Ele(t,e,i);return e}Ps.getFinalStruct=Mnt;function Pnt(t,e){return t.fields.find(r=>(r.as||r.name)===e)}Ps.getStructFieldDef=Pnt,Object.defineProperty(u2,"__esModule",{value:!0}),u2.QueryRefine=void 0;const Unt=Ur,jnt=Ps,qnt=$y;class Qnt extends qnt.QueryBase{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="query-refine"}queryComp(e){const r=this.base.queryComp(e),i=new Unt.StaticSourceSpace(r.inputStruct),s=this.refinement.refine(i,r.query.pipeline,void 0),o={...r.query,pipeline:s},u=this.resolveCompositeSource(r.inputStruct,o);return{query:{...o,compositeResolvedSourceDef:u},outputStruct:(0,jnt.getFinalStruct)(this.refinement,r.inputStruct,s),inputStruct:r.inputStruct}}}u2.QueryRefine=Qnt;var By={},a2={},ps={};Object.defineProperty(ps,"__esModule",{value:!0}),ps.mkTimeResult=ps.resolution=ps.castTo=ps.timeOffset=void 0;const NB=Xe;function Hnt(t,e,r,i,s){return{node:"delta",kids:{base:(0,NB.mkTemporal)(e,t),delta:i},op:r,units:s}}ps.timeOffset=Hnt;function znt(t,e,r,i=!1){let s;return typeof t!="string"?s={node:"cast",dstSQLType:t.raw,e,safe:i}:s={node:"cast",dstType:{type:t},e,safe:i},(0,NB.isCastType)(r)&&(s.srcType={type:r}),s}ps.castTo=znt;function Gnt(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}ps.resolution=Gnt;function Wnt(t,e){if(e){if(t.type==="timestamp")return{...t,timeframe:e};if((0,NB.isDateUnit)(e))return{...t,timeframe:e}}return t}ps.mkTimeResult=Wnt;var nd={},xt={},Qt={};Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.literalTimeResult=Qt.literalExprValue=Qt.computedErrorExprValue=Qt.computedTimeResult=Qt.computedExprValue=void 0;const Ale=ji,LB=lt;function ky({value:t,dataType:e,from:r}){return{...e,value:t,expressionType:(0,Ale.maxOfExpressionTypes)(r.map(i=>i.expressionType)),evalSpace:(0,Ale.mergeEvalSpaces)(...r.map(i=>i.evalSpace)),compositeFieldUsage:(0,LB.mergeCompositeFieldUsage)(...r.map(i=>i.compositeFieldUsage))}}Qt.computedExprValue=ky;function Vnt({value:t,dataType:e,from:r,timeframe:i}){const s=ky({value:t,dataType:e,from:r}),o={...e,expressionType:s.expressionType,evalSpace:s.evalSpace,value:s.value,compositeFieldUsage:(0,LB.mergeCompositeFieldUsage)(...r.map(u=>u.compositeFieldUsage))};return i&&(o.timeframe=i),o}Qt.computedTimeResult=Vnt;function Ynt({dataType:t,from:e,error:r}){return ky({dataType:t??{type:"error"},value:{node:"error",message:r},from:e})}Qt.computedErrorExprValue=Ynt;function Knt(t){return ky({...t,from:[]})}Qt.literalExprValue=Knt;function Jnt({value:t,dataType:e,timeframe:r}){const i=ky({value:t,dataType:e,from:[]}),s={...e,expressionType:i.expressionType,evalSpace:i.evalSpace,value:i.value,compositeFieldUsage:(0,LB.emptyCompositeFieldUsage)()};return r&&(s.timeframe=r),s}Qt.literalTimeResult=Jnt;var l2={};Object.defineProperty(l2,"__esModule",{value:!0}),l2.isGranularResult=void 0;function Xnt(t){return t.type==="date"||t.type==="timestamp"?t.timeframe!==void 0:!1}l2.isGranularResult=Xnt;var pu={};Object.defineProperty(pu,"__esModule",{value:!0}),pu.isComparison=pu.isEquality=pu.getExprNode=void 0;function Znt(t){switch(t){case"~":return"like";case"!~":return"!like"}return t}pu.getExprNode=Znt;function _le(t){return t==="="||t==="!="||t==="~"||t==="!~"}pu.isEquality=_le;function ert(t){return _le(t)||t===">="||t==="<="||t===">"||t==="<"}pu.isComparison=ert;var trt=T&&T.__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]}),nrt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),rrt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&trt(e,t,r);return nrt(e,t),e};Object.defineProperty(xt,"__esModule",{value:!0}),xt.applyBinary=xt.getMorphicValue=xt.ExprDuration=xt.ExpressionDef=xt.ATNodeType=void 0;const $c=Xe,rd=rrt(Zt),IB=ks,Vl=Qt,irt=ps,vle=l2,srt=Je,My=pu;class ort extends Error{}var $B;(function(t){t[t.And=0]="And",t[t.Or=1]="Or",t[t.Value=2]="Value",t[t.Partial=3]="Partial"})($B||(xt.ATNodeType=$B={}));class Cle extends srt.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=rd.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.type!=="error"&&!rd.any(r,this.legalChildTypes)?(r.type==="sql native"?e.logError("sql-native-not-allowed-in-expression",{rawType:r.rawType}):e.logError("expression-type-error",`'${this.elementType}' Can't use type ${rd.inspect(r)}`),!1):!0}apply(e,r,i,s=!1){return Rle(e,i,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,$c.expressionIsAggregate)(e.expressionType)}atNodeType(){return $B.Value}atExpr(){return this}}xt.ExpressionDef=Cle;class BB extends Cle{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[rd.timestampT,rd.dateT]}apply(e,r,i){const s=i.getExpression(e);if(this.typeCheck(this,s),(0,$c.isTemporalType)(s.type)&&(r==="+"||r==="-")){const o=this.n.getExpression(e);if(!rd.typeEq(o,rd.numberT))return this.logError("invalid-duration-quantity",`Duration quantity needs number not '${o.type}`),(0,IB.errorFor)("illegal unit expression");let u;return(0,vle.isGranularResult)(s)&&s.timeframe===this.timeframe&&(u=s.timeframe),s.type==="date"&&!(0,$c.isDateUnit)(this.timeframe)?this.loggedErrorExpr("invalid-timeframe-for-time-offset",`Cannot offset date by ${this.timeframe}`):(0,Vl.computedTimeResult)({dataType:{type:s.type},value:(0,irt.timeOffset)(s.type,s.value,r,o.value,this.timeframe),timeframe:u,from:[s,o]})}return super.apply(e,r,i)}getExpression(e){const r=this.n.getExpression(e);return(0,Vl.computedErrorExprValue)({dataType:{type:"duration"},error:"Duration is not a value",from:[r]})}}xt.ExprDuration=BB;function Sle(t,e){return t.type===e?t.value:t.morphic&&t.morphic[e]}function urt(t,e){if(t.type===e)return t;if(t.morphic&&t.morphic[e])return(0,Vl.computedExprValue)({dataType:{type:e},value:t.morphic[e],from:[t]})}xt.getMorphicValue=urt;function ble(t,e,r,i){const s=(0,$c.isTemporalType)(e.type),o=(0,$c.isTemporalType)(i.type),u=(0,My.getExprNode)(r);if(s&&o)if(e.type!==i.type){const a=Sle(e,"timestamp"),l=Sle(i,"timestamp");if(a&&l)return{node:u,kids:{left:a,right:a}}}else return{node:u,kids:{left:e.value,right:i.value}};if((s||o)&&e.type!=="null"&&i.type!=="null")return t.logError("time-comparison-type-mismatch",`Cannot compare a ${e.type} to a ${i.type}`),{node:"false"}}function art(t,e){if(t.type==="string"){if(e.type==="regular expression")return{node:"regexpMatch",kids:{expr:t.value,regex:e.value}}}else if(e.type==="string"&&t.type==="regular expression")return{node:"regexpMatch",kids:{expr:e.value,regex:t.value}}}function lrt(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=(0,My.getExprNode)(r),a=Py("boolean",s,o);if(a)return a;const l=$c.TD.isSQL(s)?s.rawType||"typeless-left":void 0,c=$c.TD.isSQL(o)?o.rawType||"typeless-right":void 0;if((l||c)&&!(s.type==="null"||o.type==="null"||l===c)){const h=Uy(e,s,i,o);if(h)return{...h,type:"boolean"}}let f=ble(e,s,r,o)||{node:u,kids:{left:s.value,right:o.value}};if(s.type!=="error"&&o.type!=="error"&&(r==="~"||r==="!~")&&(s.type!=="string"||o.type!=="string")){let x=art(s,o);if(x)r[0]==="!"&&(x={node:"not",e:{...x}});else throw new ort("Incompatible types for match('~') operator");f=x}return(0,Vl.computedExprValue)({dataType:{type:"boolean"},value:f,from:[s,o]})}function crt(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=Py("boolean",s,o);if(u)return u;const a=Uy(e,s,i,o);if(a)return{...a,type:"boolean"};const l=ble(e,s,r,o)||{node:(0,My.getExprNode)(r),kids:{left:s.value,right:o.value}};return(0,Vl.computedExprValue)({dataType:{type:"boolean"},value:l,from:[s,o]})}function Tle(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=Py("number",s,o);if(u)return u;const a=Uy(e,s,i,o);if(a)return a;if(s.type!=="number")e.logError("arithmetic-operation-type-mismatch",`The '${r}' operator requires a number, not a '${s.type}'`);else if(o.type!=="number")i.logError("arithmetic-operation-type-mismatch",`The '${r}' operator requires a number, not a '${o.type}'`);else return(0,Vl.computedExprValue)({dataType:{type:"number"},value:{node:r,kids:{left:s.value,right:o.value}},from:[s,o]});return(0,IB.errorFor)("numbers required")}function frt(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=Uy(e,s,i,o);if(u)return u;const a=(0,$c.isTemporalType)(s.type),l=Py(a?"error":"number",s,o);if(l)return l;if(a){let c=i;if(o.type!=="duration")if((0,vle.isGranularResult)(s))c=new BB(i,s.timeframe);else if(s.type==="date")c=new BB(i,"day");else return e.loggedErrorExpr("time-offset-type-mismatch",`Can not offset time by '${o.type}'`);return c.apply(t,r,e)}return Tle(t,e,r,i)}function Rle(t,e,r,i){if((0,My.isEquality)(r))return lrt(t,e,r,i);if((0,My.isComparison)(r))return crt(t,e,r,i);if(r==="+"||r==="-")return frt(t,e,r,i);if(r==="*")return Tle(t,e,r,i);if(r==="/"||r==="%"){const s=e.getExpression(t),o=i.getExpression(t),u=Uy(e,s,i,o);if(u)return u;const a=Py("number",s,o);if(a)return a;if(s.type!=="number")e.logError("arithmetic-operation-type-mismatch","Numerator must be a number");else if(o.type!=="number")i.logError("arithmetic-operation-type-mismatch","Denominator must be a number");else{const l={node:r,kids:{left:s.value,right:o.value}};return(0,Vl.computedExprValue)({dataType:{type:"number"},value:l,from:[s,o]})}return(0,IB.errorFor)("divide type mismatch")}return e.loggedErrorExpr("unexpected-binary-operator",`Cannot use ${r} operator here`)}xt.applyBinary=Rle;function Py(t,...e){if(e.some(r=>r.type==="error"))return(0,Vl.computedExprValue)({dataType:{type:t},value:{node:"error",message:"cascading error"},from:e})}function Uy(t,e,r,i){const s=(0,Vl.computedExprValue)({dataType:e,value:{node:"error",message:"sql-native unsupported"},from:[e,i]});if(e.type==="sql native")return t.logError("sql-native-not-allowed-in-expression",{rawType:e.rawType}),s.type=i.type,s;if(i.type==="sql native")return r.logError("sql-native-not-allowed-in-expression",{rawType:i.rawType}),s}Object.defineProperty(nd,"__esModule",{value:!0}),nd.ExprIdReference=void 0;const xrt=Xe,drt=xt,hrt=lt;class prt extends drt.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){const r=this.fieldReference.getField(e),i=this.fieldReference.list.map(s=>s.name).slice(0,-1);if(r.found){const s=r.found.typeDesc(),o=(0,hrt.joinedCompositeFieldUsage)(i,s.compositeFieldUsage);if(r.isOutputField)return{...s,evalSpace:s.evalSpace==="constant"?"constant":"output",value:{node:"outputField",name:this.refString},compositeFieldUsage:o};const u={node:r.found.refType,path:this.fieldReference.path},a=(0,xrt.expressionIsAggregate)(s.expressionType)?"output":s.evalSpace;return{...s,value:u,evalSpace:a,compositeFieldUsage:o}}return this.loggedErrorExpr(r.error.code,r.error.message)}}nd.ExprIdReference=prt,Object.defineProperty(a2,"__esModule",{value:!0}),a2.NamedSource=void 0;const kB=Xe,mrt=Eo,grt=li,yrt=ps,Dle=Je,Ert=nd,Art=t2;class _rt extends mrt.Source{constructor(e,r,i){super(),this.ref=e,this.sourceArguments=r,this.args=i,this.elementType="namedSource",i&&this.has({args:i}),e instanceof Dle.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof Dle.ModelEntryReference?this.ref.name:this.ref}structRef(e){const r=this.modelEntry(this.ref);return r&&!r.exported?{structRef:this.getSourceDef(e)}:{structRef:this.refName,sourceArguments:this.evaluateArgumentsForRef(e)}}refLogError(e,r,i){typeof this.ref=="string"?this.logError(e,r,i):this.ref.logError(e,r,i)}modelStruct(){var e;const r=this.modelEntry(this.ref),i=r==null?void 0:r.entry;if(!i){this.refLogError("source-not-found",`Undefined source '${this.refName}'`);return}if(i.type==="query"){this.logError("invalid-source-from-query",`Cannot construct a source from query '${this.refName}'`);return}else if(i.type==="function"){this.logError("invalid-source-from-function",`Cannot construct a source from a function '${this.refName}'`);return}else if(i.type==="connection"){this.logError("invalid-source-from-connection",`Cannot construct a source from a connection '${this.refName}'`);return}else if((e=this.document())===null||e===void 0||e.checkExperimentalDialect(this,i.dialect),(0,kB.isSourceDef)(i))return{...i};this.logError("invalid-source-source","Cannot construct a source from a never type")}evaluateArgumentsForRef(e){const r=this.modelStruct();return r===void 0?{}:this.evaluateArguments(e,r.parameters,[])}evaluateArguments(e,r,i){var s,o;const u={...this.sourceArguments},a=new Set;for(const l of(s=this.args)!==null&&s!==void 0?s:[]){const c=(o=l.id)!==null&&o!==void 0?o:l.value instanceof Ert.ExprIdReference?l.value.fieldReference:void 0;if(c===void 0){l.value.logError("unnamed-source-argument","Parameterized source arguments must be named with `parameter_name is`");continue}const f=c.outputName;if(a.has(f)){l.logError("duplicate-source-argument",`Cannot pass argument for \`${f}\` more than once`);continue}a.add(f);const x=(r??{})[f];if(!x)c.logError("source-parameter-not-found",`\`${this.refName}\` has no declared parameter named \`${c.refString}\``);else{const h=e??new Art.ParameterSpace(i??[]),p=l.value.getExpression(h);let m=p.value;p.type!==x.type&&(0,kB.isCastType)(x.type)&&(m=(0,yrt.castTo)(x.type,p.value,p.type,!0)),u[f]={...x,value:m}}}for(const l in r)l in u||((0,kB.paramHasValue)(r[l])?u[l]={...r[l]}:this.refLogError("missing-source-argument",`Argument not provided for required parameter \`${l}\``));return u}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){var i;const s=this.modelStruct();if(!s){const l=grt.ErrorFactory.structDef,c=`${this.refName}-undefined`;return l.name=l.name+c,l.dialect=l.dialect+c,l}const o={};for(const l of r??[]){const c=l.parameter();o[c.name]=c}const u=this.evaluateArguments(e,s.parameters,r),a={...s,parameters:o,arguments:u};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(a),a}}a2.NamedSource=_rt;var jy={},rb={};Object.defineProperty(rb,"__esModule",{value:!0}),rb.QueryHeadStruct=void 0;const vrt=Xe,Crt=Eo,Srt=a2;class brt extends Crt.Source{constructor(e,r){super(),this.fromRef=e,this.sourceArguments=r,this.elementType="internalOnlyQueryHead"}structRef(){return{structRef:this.fromRef}}getSourceDef(e){if((0,vrt.refIsStructDef)(this.fromRef))return this.fromRef;const r=new Srt.NamedSource(this.fromRef,this.sourceArguments,void 0);return this.has({exploreReference:r}),r.getSourceDef(e)}}rb.QueryHeadStruct=brt,Object.defineProperty(jy,"__esModule",{value:!0}),jy.QueryReference=void 0;const MB=li,Trt=Je,Rrt=rb,Drt=Xe,Ort=Ps;class Frt extends Trt.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){const r=this.modelEntry(this.name),i=r==null?void 0:r.entry,s=function(){return{inputStruct:MB.ErrorFactory.structDef,outputStruct:MB.ErrorFactory.structDef,query:MB.ErrorFactory.query}};if(!i)return this.logError("query-reference-not-found",`Reference to undefined query '${this.name.refString}'`),s();if(i.type==="query"){const o=new Rrt.QueryHeadStruct(i.structRef,i.sourceArguments);this.has({queryHead:o});const u=o.getSourceDef(void 0),a=(0,Ort.getFinalStruct)(this,u,i.pipeline);return{query:e||(0,Drt.refIsStructDef)(i.structRef)?i:{...i,structRef:u},outputStruct:a,inputStruct:u}}return this.logError("non-query-used-as-query",`Illegal reference to '${this.name}', query expected`),s()}query(){return this.queryComp(!0).query}}jy.QueryReference=Frt,Object.defineProperty(By,"__esModule",{value:!0}),By.SQReference=void 0;const wrt=hu,Nrt=td,Lrt=a2,Ole=jy,Fle=ji;class Irt extends wrt.SourceQueryElement{constructor(e,r){super({ref:e}),this.ref=e,this.args=r,this.elementType="sq-reference",r!==void 0&&this.has({args:r})}getQuery(){const e=this.ref.getNamed();if(e)if(e.type==="query"){const r=new Ole.QueryReference(this.ref);return this.has({query:r}),r}else this.sqLog("cannot-use-as-query",`Illegal reference to '${e.as||e.name}', query expected`);else this.ref.logError("source-or-query-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0}isSource(){const e=this.ref.getNamed();return e!==void 0&&(0,Fle.isSourceDef)(e)}getSource(){if(this.asSource)return this.asSource;const e=this.ref.getNamed();if(!e){this.ref.logError("source-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){this.args!==void 0&&this.ref.logError("illegal-query-argument","Arguments cannot be passed to queries");const r=new Ole.QueryReference(this.ref);this.asSource=new Nrt.QuerySource(r)}else if((0,Fle.isSourceDef)(e))this.asSource=new Lrt.NamedSource(this.ref,void 0,this.args);else{this.sqLog("cannot-use-struct-as-source",`Expected '${this.ref.refString}' to be of type query or source, not '${e.type}'`);return}return this.has({asSource:this.asSource}),this.asSource}}By.SQReference=Irt,Object.defineProperty(tb,"__esModule",{value:!0}),tb.SQRefine=void 0;const $rt=hu,Brt=td,krt=u2,Mrt=By;class Prt extends $rt.SourceQueryElement{constructor(e,r){super({toRefine:e,refine:r}),this.toRefine=e,this.refine=r,this.elementType="sq-refine"}getQuery(){if(this.toRefine.isSource()){this.toRefine instanceof Mrt.SQReference?this.sqLog("illegal-refinement-of-source",`Cannot add view refinements to '${this.toRefine.ref.refString}' because it is a source`):this.sqLog("illegal-refinement-of-source","Cannot add view refinements to a source");return}const e=this.toRefine.getQuery();if(e){const r=new krt.QueryRefine(e,this.refine);return this.has({query:r}),r}}getSource(){const e=this.getQuery();if(e){const r=new Brt.QuerySource(e);return this.has({queryAsSource:r}),r}}}tb.SQRefine=Prt;var ib={},qy={};Object.defineProperty(qy,"__esModule",{value:!0}),qy.QueryRaw=void 0;const Urt=Xe,jrt=Je;class qrt extends jrt.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){const r=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)},i=(0,Urt.refIsStructDef)(r.structRef)?r.structRef:this.source.getSourceDef(void 0);return{query:{type:"query",...r,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:i,inputStruct:i}}query(){return this.queryComp(!0).query}}qy.QueryRaw=qrt;var Qy={},Yl={};Object.defineProperty(Yl,"__esModule",{value:!0}),Yl.sqlKey=Yl.compileSQLInterpolation=void 0;const Qrt=$s,Hrt=Xe,zrt=$t;function Grt(t,e,r){let i,s="",o=!1;for(const u of t)if((0,Hrt.isSegmentSQL)(u))s+=u.sql,o=u.sql.match(/\(\s*$/)!==null;else{if(!i){if(!r)throw new Error("Internal error: Partial model missing when compiling SQL block");i=new Qrt.QueryModel(r)}const a=i.compileQuery(u,{defaultRowLimit:void 0},!1).sql;s+=o?a:`(${a})`,o=!1}return{connection:e,selectStr:s}}Yl.compileSQLInterpolation=Grt;function Wrt(t,e){return`sql://${t}/${(0,zrt.generateHash)(e)}`}Yl.sqlKey=Wrt,Object.defineProperty(Qy,"__esModule",{value:!0}),Qy.SQLSource=void 0;const PB=Yl,Vrt=Eo,Hy=li;class Yrt extends Vrt.Source{constructor(e,r){super({connectionName:e,select:r}),this.connectionName=e,this.select=r,this.elementType="sqlSource",this.connectionNameInvalid=!1}sqlSourceRequest(e){const r=this.select.containsQueries?e.modelDef():void 0;return(0,PB.compileSQLInterpolation)(this.select.sqlPhrases(),this.connectionName.refString,r)}structRef(){return{structRef:this.getSourceDef()}}validateConnectionName(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection")return this.connectionName.logError("invalid-connection-for-sql-source",`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var r;if(!this.validateConnectionName())return;const i=super.needs(e);if(i)return i;this.requestBlock===void 0&&(this.requestBlock=this.sqlSourceRequest(e));const s=this.requestBlock,o=(r=this.translator())===null||r===void 0?void 0:r.root.sqlQueryZone;if(!o){this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block");return}const u=(0,PB.sqlKey)(s.connection,s.selectStr);o.reference(u,this.location);const a=o.getEntry(u);if(a.status==="reference")return{compileSQL:s};a.status==="present"&&e.checkExperimentalDialect(this,a.value.dialect)}getSourceDef(){var e;if(!this.validateConnectionName())return Hy.ErrorFactory.structDef;const r=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!r)return this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block"),Hy.ErrorFactory.structDef;if(this.requestBlock===void 0)return this.logError("failed-to-fetch-sql-source-schema","Expected to have already compiled the sql block"),Hy.ErrorFactory.structDef;const i=this.requestBlock,s=(0,PB.sqlKey)(i.connection,i.selectStr);r.reference(s,this.location);const o=r.getEntry(s);if(o.status==="error"){const u=o.message.split(/\r?\n/);return this.select.logError("invalid-sql-source","Invalid SQL, "+u.join(`
|
|
1160
|
-
`)),Hy.ErrorFactory.structDef}else if(o.status==="present"){const u=this.select.location,a={...o.value,fields:o.value.fields.map(f=>({...f,location:u})),location:this.location},l=this.document(),c=l==null?void 0:l.currentModelAnnotation();return c&&(a.modelAnnotation=c),a}else return this.logError("non-top-level-sql-source","`connection_name.sql(...)` can currently only be used in top level source/query definitions"),Hy.ErrorFactory.structDef}}Qy.SQLSource=Yrt,Object.defineProperty(ib,"__esModule",{value:!0}),ib.SQSource=void 0;const Krt=hu,Jrt=qy,Xrt=Qy;class Zrt extends Krt.SourceQueryElement{constructor(e){super({theSource:e}),this.theSource=e,this.elementType="sq-source"}isSource(){return!0}getSource(){return this.theSource}getQuery(){if(this.theSource instanceof Xrt.SQLSource){const e=new Jrt.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}ib.SQSource=Zrt;var sb={};Object.defineProperty(sb,"__esModule",{value:!0}),sb.SQExtend=void 0;const eit=Oy,tit=hu;class nit extends tit.SourceQueryElement{constructor(e,r,i){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.includeList=i,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new eit.RefinedSource(e,this.extend,this.includeList),this.has({asSource:this.asSource}),this.asSource;this.sqLog("failed-to-compute-source-to-extend","Could not compute source to extend")}isSource(){return!0}}sb.SQExtend=nit;var ob={},ub={};Object.defineProperty(ub,"__esModule",{value:!0}),ub.CompositeSource=void 0;const rit=Xe,iit=Eo;class sit extends iit.Source{constructor(e){super({sources:e}),this.sources=e,this.elementType="compositeSource"}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){const i=this.sources.map(c=>c.withParameters(e,r)),s=i[0].connection,o=i[0].dialect,u="composite_source",a=[],l=new Map;return this.sources.forEach((c,f)=>{var x;const h=i[f];h.connection!==s&&c.logError("composite-source-connection-mismatch",`All sources in a composite source must share the same connection; connection \`${h.connection}\` differs from previous connection \`${s}\``);for(const p of h.fields){if(!(0,rit.isAtomic)(p)){c.logWarning("composite-source-atomic-fields-only",`Only atomic fields are supported in composite sources; field \`${p.name}\` is not atomic and will be ignored`);continue}if(p.accessModifier==="private")continue;const m=(x=p.as)!==null&&x!==void 0?x:p.name,y=l.get(m);if(y===void 0){const g={...p,name:m,as:void 0,e:{node:"compositeField"},compositeFieldUsage:{fields:[m],joinedUsage:{}},code:this.code,location:this.codeLocation};l.set(m,g),a.push(g)}else p.accessModifier==="internal"&&(y.accessModifier="internal")}}),{type:"composite",sources:i,connection:s,fields:a,dialect:o,name:u,parameters:i[0].parameters}}}ub.CompositeSource=sit,Object.defineProperty(ob,"__esModule",{value:!0}),ob.SQCompose=void 0;const oit=ub,uit=hu;class ait extends uit.SourceQueryElement{constructor(e){super({sources:e}),this.sources=e,this.elementType="sq-compose"}getSource(){if(this.asSource)return this.asSource;const e=this.sources.map(r=>r.getSource());if(e.length===0){this.sqLog("empty-composite-source","Composite source must have at least one input source");return}else e.length===1&&this.sqLog("unnecessary-composite-source","A composite source with one input is equivalent to that input",{severity:"warn"});if(lit(e))return this.asSource=new oit.CompositeSource(e),this.has({asSource:this.asSource}),this.asSource;this.sqLog("invalid-composite-source-input","All composite source inputs must be valid sources")}isSource(){return!0}}ob.SQCompose=ait;function lit(t){return t.every(e=>e!==void 0)}var ab={},Kl={},zy={},cit=T&&T.__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]}),fit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&cit(e,t,r);return fit(e,t),e};Object.defineProperty(zy,"__esModule",{value:!0}),zy.BinaryBoolean=void 0;const dit=ks,hit=xit(Zt),pit=pu,mit=Qt,git=xt;class yit extends git.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="abstract boolean binary",this.legalChildTypes=[hit.boolT]}getExpression(e){const r=this.left.getExpression(e),i=this.right.getExpression(e);return this.typeCheck(this.left,r)&&this.typeCheck(this.right,i)?(0,mit.computedExprValue)({dataType:{type:"boolean"},value:{node:(0,pit.getExprNode)(this.op),kids:{left:r.value,right:i.value}},from:[r,i]}):(0,dit.errorFor)("logical-op expected boolean")}}zy.BinaryBoolean=yit;var Eit=T&&T.__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]}),Ait=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_it=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Eit(e,t,r);return Ait(e,t),e};Object.defineProperty(Kl,"__esModule",{value:!0}),Kl.ExprLegacyIn=Kl.ExprEquality=Kl.ExprCompare=void 0;const fn=_it(Zt),vit=Qt,Cit=xt,Sit=zy,bit={"~":[fn.stringT],"!~":[fn.stringT],"<":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"<=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"!=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],">=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],">":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT]};class wle extends Sit.BinaryBoolean{constructor(e,r,i){super(e,r,i),this.elementType="a<=>b",this.legalChildTypes=bit[r]}getExpression(e){return this.right.apply(e,this.op,this.left)}}Kl.ExprCompare=wle;class Tit extends wle{constructor(e,r,i){super(e,r,i),this.elementType="a~=b"}getExpression(e){return this.right.apply(e,this.op,this.left,!0)}apply(e,r,i){return super.apply(e,r,i,!0)}}Kl.ExprEquality=Tit;class Rit extends Cit.ExpressionDef{constructor(e,r,i){super(),this.expr=e,this.notIn=r,this.choices=i,this.elementType="in",this.has({expr:e,choices:i})}getExpression(e){const r=this.expr.getExpression(e),i=this.choices.map(s=>s.getExpression(e));return(0,vit.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:this.notIn,kids:{e:r.value,oneOf:i.map(s=>s.value)}},from:[r,...i]})}}Kl.ExprLegacyIn=Rit;var Gy={},c2={};Object.defineProperty(c2,"__esModule",{value:!0}),c2.ExprTime=void 0;const Dit=Xe,Oit=Qt,Fit=xt;class UB extends Fit.ExpressionDef{constructor(e,r,i){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue=(0,Oit.computedExprValue)({dataType:{type:e},value:r,from:i??[]})}getExpression(e){return this.translationValue}static fromValue(e,r){let i=r.value;if(e!==r.type){const s={node:"cast",safe:!1,dstType:{type:e},e:r.value};(0,Dit.isTemporalType)(r.type)&&(s.srcType={type:r.type}),i=s}return new UB(e,i,[r])}}c2.ExprTime=UB;var Bc={};Object.defineProperty(Bc,"__esModule",{value:!0}),Bc.Range=void 0;const wit=ks,Nit=Qt,Lit=xt;class Iit extends Lit.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,i){switch(r){case"=":case"!=":{const s=r==="="?">=":"<",o=r==="="?"and":"or",u=r==="="?"<":">=",a=this.first.apply(e,s,i),l=this.last.apply(e,u,i);return(0,Nit.computedExprValue)({dataType:{type:"boolean"},value:{node:o,kids:{left:a.value,right:l.value}},from:[a,l]})}case">":return this.last.apply(e,">=",i);case">=":return this.first.apply(e,">=",i);case"<":return this.first.apply(e,"<",i);case"<=":return this.last.apply(e,"<",i)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.logError("range-as-value","A Range is not a value"),(0,wit.errorFor)("a range is not a value")}}Bc.Range=Iit;var $it=T&&T.__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]}),Bit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),kit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$it(e,t,r);return Bit(e,t),e};Object.defineProperty(Gy,"__esModule",{value:!0}),Gy.ExprGranularTime=void 0;const jB=Xe,Mit=ks,Nle=kit(Zt),Lle=ps,Pit=xt,lb=c2,Ile=Bc;class Uit extends Pit.ExpressionDef{constructor(e,r,i){super({expr:e}),this.expr=e,this.units=r,this.truncate=i,this.elementType="granularTime",this.legalChildTypes=[Nle.timestampT,Nle.dateT]}granular(){return!0}getExpression(e){const r=this.units,i=this.expr.getExpression(e);if(jB.TD.isTemporal(i)){const o={...i,timeframe:r};return this.truncate&&(o.value={node:"trunc",e:(0,jB.mkTemporal)(i.value,i.type),units:r}),o}i.type!=="error"&&this.logError("unsupported-type-for-time-truncation",`Cannot do time truncation on type '${i.type}'`);const s={...i};return i.type==="error"&&(s.type=(0,jB.isDateUnit)(r)?"date":"timestamp"),{...s,value:(0,Mit.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const r=this.getExpression(e),i={node:"numberLiteral",literal:"1"};if(r.type==="timestamp"){const a=lb.ExprTime.fromValue("timestamp",r),l=new lb.ExprTime("timestamp",(0,Lle.timeOffset)("timestamp",r.value,"+",i,this.units),[r]);return new Ile.Range(a,l)}const s=new lb.ExprTime("date",r.value,[r]),o=(0,Lle.timeOffset)("date",r.value,"+",i,this.units),u=new lb.ExprTime("date",o,[r]);return new Ile.Range(s,u)}}Gy.ExprGranularTime=Uit,Object.defineProperty(ab,"__esModule",{value:!0}),ab.Apply=void 0;const jit=Kl,qit=l2,$le=Gy;class Qit extends jit.ExprCompare{constructor(e,r){super(e,"=",r),this.left=e,this.right=r,this.elementType="apply"}getExpression(e){let r=this.right;if(!this.right.granular()){const i=this.right.requestExpression(e);i&&(0,qit.isGranularResult)(i)&&(r=new $le.ExprGranularTime(this.right,i.timeframe,!1))}return r instanceof $le.ExprGranularTime?r.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}ab.Apply=Qit;var f2={},Hit=T&&T.__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]}),zit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Git=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Hit(e,t,r);return zit(e,t),e};Object.defineProperty(f2,"__esModule",{value:!0}),f2.BinaryNumeric=void 0;const Wit=Git(Zt),Vit=xt;class Yit extends Vit.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="numeric binary abstract",this.legalChildTypes=[Wit.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}f2.BinaryNumeric=Yit;var cb={},Kit=T&&T.__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]}),Jit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Kit(e,t,r);return Jit(e,t),e};Object.defineProperty(cb,"__esModule",{value:!0}),cb.Boolean=void 0;const Zit=xt,est=Xit(Zt);let tst=class extends Zit.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...est.boolT,value:{node:this.value}}}};cb.Boolean=tst;var kc={};Object.defineProperty(kc,"__esModule",{value:!0}),kc.FunctionOrdering=kc.FunctionOrderBy=void 0;const qB=Xe,Ble=Je,nst=nd;class rst extends Ble.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.logError("analytic-order-by-missing-field","analytic `order_by` must specify an aggregate expression or output field reference"),{node:"functionOrderBy",e:{node:"error"},dir:this.dir};const r=this.field.getExpression(e);return(0,qB.expressionIsAggregate)(r.expressionType)||((0,qB.expressionIsScalar)(r.expressionType)?(!(this.field instanceof nst.ExprIdReference)||r.evalSpace==="input")&&this.field.logError("analytic-order-by-not-output","analytic `order_by` must be an aggregate or an output field reference"):this.field.logError("analytic-order-by-not-aggregate-or-output","analytic `order_by` must be scalar or aggregate")),{node:"functionOrderBy",e:r.value,dir:this.dir}}getAggregateOrderBy(e,r){if(this.field){const i=this.field.getExpression(e);return(0,qB.expressionIsScalar)(i.expressionType)||this.field.logError("aggregate-order-by-not-scalar","aggregate `order_by` must be scalar"),r||this.field.logError("aggregate-order-by-expression-not-allowed","`order_by` must be only `asc` or `desc` with no expression"),{node:"functionOrderBy",e:i.value,dir:this.dir}}else return this.dir===void 0?(this.logError("aggregate-order-by-without-field-or-direction","field or order direction must be specified"),{node:"functionDefaultOrderBy",dir:"asc"}):{node:"functionDefaultOrderBy",dir:this.dir}}}kc.FunctionOrderBy=rst;class ist extends Ble.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e,r){return this.list.map(i=>i.getAggregateOrderBy(e,r))}}kc.FunctionOrdering=ist;var fb={};Object.defineProperty(fb,"__esModule",{value:!0}),fb.ExprAddSub=void 0;const sst=f2;class ost extends sst.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}fb.ExprAddSub=ost;var Jl={},ust=T&&T.__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]}),ast=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),lst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ust(e,t,r);return ast(e,t),e};Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.ExprAggregateFunction=void 0;const Wy=Xe,cst=$t,fst=ks,kle=Ur,Mle=lst(Zt),xst=yt,dst=xt,hst=Pr,pst=nd;class mst extends dst.ExpressionDef{constructor(e,r,i){super(),this.func=e,this.legalChildTypes=[Mle.numberT],this.elementType=e,this.explicitSource=i,r&&(this.expr=r,this.has({expr:r}))}getExpression(e){var r,i,s;const o=e.isQueryFieldSpace()?e.inputSpace():e;let u=this.expr,a=(r=this.expr)===null||r===void 0?void 0:r.getExpression(o),l=(i=this.source)===null||i===void 0?void 0:i.path,c=[];if(this.source){const x=this.source.getField(o);if(x.found){c=x.joinPath;const h=x.found,p=h.typeDesc();if(!(h instanceof kle.StructSpaceField))if((0,Wy.isAtomicFieldType)(p.type)){u=this.source,a={...Mle.atomicDef(p),expressionType:p.expressionType,value:p.evalSpace==="output"?{node:"outputField",name:this.source.refString}:{node:"field",path:this.source.path},evalSpace:p.evalSpace,compositeFieldUsage:p.compositeFieldUsage},l=this.source.path.slice(0,-1);const m=this.getJoinUsage(o);(m.length===1||m.length>1&&m.slice(1).every(g=>gst(g,m[0])))&&(l=m[0].map(g=>g.name),c=m[0])}else return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${p.type}`)}else return this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}if(a===void 0)return this.loggedErrorExpr("missing-aggregate-expression","Missing expression for aggregate function");if((0,Wy.expressionIsAggregate)(a.expressionType))return this.loggedErrorExpr("aggregate-of-aggregate","Aggregate expression cannot be aggregate");if(!(a.type==="error")){const x=this.getJoinUsage(o),h=this.source!==void 0||this.explicitSource;if(u&&!(!this.source&&x.every(m=>m.length===0))&&!this.isSymmetricFunction()){const m=HB(c,x),y=zB(this.elementType,m),g=h?y==null?void 0:y.message:"Join path is required for this calculation";if(g){const E=yst(g,x,u,this.elementType),A=(s=y==null?void 0:y.code)!==null&&s!==void 0?s:"bad-join-usage";y?this.logError(A,E):this.logWarning(A,E)}}}if(this.typeCheck(this.expr||this,{...a,expressionType:"scalar"})){const x={node:"aggregate",function:this.func,e:a.value};return l&&l.length>0&&(x.structPath=l),{...this.returns(a),expressionType:"aggregate",value:x,evalSpace:"output"}}return(0,fst.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const r=[];if(this.source&&this.source.getField(e).found){const s={node:"field",path:this.source.path};r.push(...QB(e,s))}if(this.expr){const i=this.expr.getExpression(e).value;r.push(...QB(e,i))}return r}}Jl.ExprAggregateFunction=mst;function gst(t,e){let r=t.length;if(r!==e.length)return!1;for(;r>0;)if(r-=1,t[r].name!==e[r].name)return!1;return!0}function QB(t,e){const r=[],i=(s,o)=>{const u=o[0],a=o.slice(1),l=s.entry(u);if(l===void 0)throw new Error(`Invalid field lookup ${u}`);if(l instanceof kle.StructSpaceField&&a.length>0){const c=i(l.fieldSpace,a);return{...c,joinPath:[{...l.joinPathElement,name:u},...c.joinPath]}}else if(l instanceof hst.SpaceField){if(a.length!==0)throw new Error(`${u} cannot contain a ${a.join(".")}`);const c=l.fieldDef();if(c)return{fs:s,def:c,joinPath:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};for(const s of(0,cst.exprWalk)(e))if(s.node==="field"){const o=i(t,s.path),u=o.def;if((0,Wy.isAtomic)(u)&&!(0,Wy.isJoined)(u))if((0,Wy.hasExpression)(u)){const a=QB(o.fs,u.e);r.push(...a.map(l=>[...o.joinPath,...l]))}else r.push(o.joinPath)}else if(s.node==="source-reference")if(s.path){const o=i(t,s.path);r.push(o.joinPath)}else r.push([]);return r}function HB(t,e){const r=[];for(const i of e){let s=0;for(let l=0;l<t.length&&l<i.length&&t[l].name===i[l].name;l++)s=l+1;const o=t.slice(s),u=i.slice(s),a=[...o.map(l=>({...l,reverse:!0})),...u.map(l=>({...l,reverse:!1}))];r.push(a)}return r}function zB(t,e){for(const r of e)for(const i of r){if(i.joinType==="cross")return{code:"aggregate-traverses-join-cross",message:`Cannot compute \`${t}\` across \`join_cross\` relationship \`${i.name}\``};if(i.joinElementType==="array"&&!i.reverse)return{code:"aggregate-traverses-repeated-relationship",message:`Cannot compute \`${t}\` across repeated relationship \`${i.name}\``};if(i.joinType==="many"&&!i.reverse)return{code:"aggregate-traverses-join-many",message:`Cannot compute \`${t}\` across \`join_many\` relationship \`${i.name}\``}}}function yst(t,e,r,i){if(e.length===0)return t;let s=e[0];for(const m of e.slice(1))for(let y=0;y<s.length;y++){const g=s[y],E=m[y];if(g.name!==E.name){s=s.slice(0,y);break}}const o=HB(s,e),u=zB(i,o),a=s.slice().reverse().findIndex(m=>m.joinType==="many"||m.joinType==="cross"),l=a===-1?0:s.length-a,c=s.slice(0,l),f=HB(c,e),x=zB(i,f),h=s.length>0?s.map(m=>m.name).join("."):"source",p=c.length>0?c.map(m=>m.name).join("."):"source";if(u)return"Aggregated dimensional expression contains multiple join paths; rewrite, for example `sum(first_join.field + second_join.field)` as `first_join.field.sum() + second_join.field.sum()`";{const m=r instanceof xst.FieldReference?`${r.refString}.${i}()`:r instanceof pst.ExprIdReference?`${r.fieldReference.refString}.${i}()`:`${h}.${i}(${r.code})`,y=`${p}.${i}(${r.code})`;let g=`${t}; use \`${m}\``;return x===void 0&&p!==h&&(g+=` or \`${y}\` to get a result weighted with respect to \`${p}\``),g}}var xb={};Object.defineProperty(xb,"__esModule",{value:!0}),xb.ExprAlternationTree=void 0;const Ple=Qt,x2=xt,Est=pu;function GB(t){const e=t.atExpr();switch(e.atNodeType()){case x2.ATNodeType.And:case x2.ATNodeType.Partial:return;case x2.ATNodeType.Or:{if(e instanceof Ule){const r=GB(e.left);if(r){const i=GB(e.right);if(i)return[...r,...i]}}return}default:return e.granular()?void 0:[e]}}class Ule extends x2.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="alternation",this.elementType=`${r}alternation${r}`}equalityList(){return this.inList===void 0&&(this.inList=GB(this)||[]),this.inList}apply(e,r,i,s){if((0,Est.isEquality)(r)){const a=this.equalityList();if(a.length>0&&(r==="="||r==="!=")){const l=i.getExpression(e),c=a.map(f=>f.getExpression(e));return(0,Ple.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:r==="!=",kids:{e:l.value,oneOf:c.map(f=>f.value)}},from:[l,...c]})}a.length===0&&s&&this.logWarning("or-choices-only",`Only | seperated values are legal when used with ${r} operator`)}const o=this.left.apply(e,r,i),u=this.right.apply(e,r,i);return(0,Ple.computedExprValue)({dataType:{type:"boolean"},value:{node:this.op==="&"?"and":"or",kids:{left:o.value,right:u.value}},from:[o,u]})}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("alternation-as-value","Alternation tree has no value")}atNodeType(){return this.op==="|"?x2.ATNodeType.Or:x2.ATNodeType.And}}xb.ExprAlternationTree=Ule;var d2={};Object.defineProperty(d2,"__esModule",{value:!0}),d2.ExprAsymmetric=void 0;const Ast=Jl;class _st extends Ast.ExprAggregateFunction{constructor(e,r,i,s){super(e,r,s),this.func=e,this.expr=r,this.source=i,this.has({source:i})}isSymmetricFunction(){return!1}returns(e){return e}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}d2.ExprAsymmetric=_st;var db={};Object.defineProperty(db,"__esModule",{value:!0}),db.ExprAvg=void 0;const vst=d2;class Cst extends vst.ExprAsymmetric{constructor(e,r,i){super("avg",e,r,i),this.has({source:r})}}db.ExprAvg=Cst;var hb={};Object.defineProperty(hb,"__esModule",{value:!0}),hb.ExprCast=void 0;const Sst=ps,bst=Qt,Tst=xt;class Rst extends Tst.ExpressionDef{constructor(e,r,i=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=i,this.elementType="cast"}getExpression(e){const r=this.expr.getExpression(e);let i={type:"error"};if(typeof this.castType=="string")i={type:this.castType};else{const s=e.dialectObj();s&&(s.validateTypeName(this.castType.raw)?i=s.sqlTypeToMalloyType(this.castType.raw):this.logError("invalid-sql-native-type",`Cast type \`${this.castType.raw}\` is invalid for ${s.name} dialect`),this.safe&&!s.supportsSafeCast&&this.logError("dialect-cast-unsafe-only",`The SQL dialect '${e.dialectName()}' does not supply a safe cast operator`))}return(0,bst.computedExprValue)({dataType:i,value:(0,Sst.castTo)(this.castType,r.value,r.type,this.safe),from:[r]})}}hb.ExprCast=Rst;var pb={},Dst=T&&T.__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]}),Ost=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Fst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Dst(e,t,r);return Ost(e,t),e};Object.defineProperty(pb,"__esModule",{value:!0}),pb.ExprCoalesce=void 0;const jle=ji,qle=Fst(Zt),wst=xt;class Nst extends wst.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=qle.anyAtomicT}getExpression(e){const r=this.expr.getExpression(e),i=this.altExpr.getExpression(e);return r.type==="null"?i:(qle.typeEq(r,i)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${r.type}, ${i.type})`),{...r.type==="error"?i:r,expressionType:(0,jle.maxExpressionType)(r.expressionType,i.expressionType),value:{node:"coalesce",kids:{left:r.value,right:i.value}},evalSpace:(0,jle.mergeEvalSpaces)(r.evalSpace,i.evalSpace)})}}pb.ExprCoalesce=Nst;var mb={};Object.defineProperty(mb,"__esModule",{value:!0}),mb.ExprCount=void 0;const Lst=lt,Ist=Jl;class $st extends Ist.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}getExpression(e){const r={node:"aggregate",function:"count",e:{node:""}};return this.source&&(r.structPath=this.source.path),{type:"number",numberType:"integer",expressionType:"aggregate",value:r,evalSpace:"output",compositeFieldUsage:(0,Lst.emptyCompositeFieldUsage)()}}}mb.ExprCount=$st;var gb={},Bst=T&&T.__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]}),kst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Bst(e,t,r);return kst(e,t),e};Object.defineProperty(gb,"__esModule",{value:!0}),gb.ExprCountDistinct=void 0;const yb=Mst(Zt),Pst=Jl;class Ust extends Pst.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[yb.numberT,yb.stringT,yb.dateT,yb.timestampT]}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}}gb.ExprCountDistinct=Ust;var Eb={},Mc={};Object.defineProperty(Mc,"__esModule",{value:!0}),Mc.Limit=void 0;const jst=Je,qst=qn;class Qst extends jst.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=qst.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}Mc.Limit=Qst;var h2={};Object.defineProperty(h2,"__esModule",{value:!0}),h2.PartitionBy=void 0;const Hst=Je;class zst extends Hst.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}h2.PartitionBy=zst;var Vy={},Pc={};Object.defineProperty(Pc,"__esModule",{value:!0}),Pc.FieldName=void 0;const Gst=Je;class Wst extends Gst.MalloyElement{constructor(e){super(),this.name=e,this.elementType="fieldName"}get refString(){return this.name}toString(){return this.refString}getField(e){return e.lookup([this])}}Pc.FieldName=Wst;var Vst=T&&T.__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]}),Yst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Kst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Vst(e,t,r);return Yst(e,t),e};Object.defineProperty(Vy,"__esModule",{value:!0}),Vy.ExprFunc=void 0;const Cr=Xe,Jst=ks,Xst=ed,Zst=Qt,eot=xt,tot=Pc,Qle=$t,Hle=Kst(Zt),not=lt;class rot extends eot.ExpressionDef{constructor(e,r,i,s,o){super({args:r}),this.name=e,this.args=r,this.isRaw=i,this.rawType=s,this.source=o,this.elementType="function call()",this.has({source:o})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}findFunctionDef(e){var r,i,s;const o=this.name.toLowerCase(),u=e?(i=(r=this.getDialectNamespace(e))===null||r===void 0?void 0:r.getEntry(o))===null||i===void 0?void 0:i.entry:void 0,a=u??((s=this.modelEntry(o))===null||s===void 0?void 0:s.entry);return a===void 0?(this.logError("function-not-found",`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),{found:void 0,error:"unknown function"}):a.type!=="function"?(this.logError("call-of-non-function",`'${this.name}' (with type ${a.type}) is not a function`),{found:void 0,error:"called non function"}):(a.name!==this.name&&this.logWarning("case-insensitive-function",`Case insensitivity for function names is deprecated, use '${a.name}' instead`),{found:a,error:void 0})}getPropsExpression(e,r){var i,s,o,u;const a=this.args.map($=>$.getExpression(e));if(this.isRaw){const $=[`${this.name}(`];a.forEach((q,K)=>{K!==0&&$.push(","),$.push(q.value)}),$.push(")");const D=(i=a[0])!==null&&i!==void 0?i:{type:"number"},B=this.rawType?{type:this.rawType}:D;return(0,Zst.computedExprValue)({dataType:B,value:(0,Qle.composeSQLExpr)($),from:a})}const l=(s=e.dialectObj())===null||s===void 0?void 0:s.name,{found:c,error:f}=this.findFunctionDef(l);if(c===void 0)return(0,Jst.errorFor)(f);let x,h=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const D=this.source.getField(e).found;if(D){const B=D.typeDesc();if((0,Cr.isAtomicFieldType)(B.type))x={...Hle.atomicDef(B),expressionType:B.expressionType,value:{node:"field",path:this.source.path},evalSpace:B.evalSpace,compositeFieldUsage:B.compositeFieldUsage},h=this.source.path.slice(0,-1);else if(!(D instanceof Xst.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${B.type}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const p=[...x?[x]:[],...a],m=iot(c,p);if(m===void 0)return this.loggedErrorExpr("no-matching-function-overload",`No matching overload for function ${this.name}(${p.map($=>$.type).join(", ")})`);const{overload:y,expressionTypeErrors:g,evalSpaceErrors:E,nullabilityErrors:A,returnType:_}=m;for(const $ of g){const D=$.argIndex-(x?1:0),B=(0,Cr.expressionIsScalar)($.maxExpressionType)?"scalar":"scalar or aggregate";this.args[D].logError("invalid-function-argument-expression-type",`Parameter ${$.argIndex+1} ('${$.param.name}') of ${this.name} must be ${B}, but received ${$.actualExpressionType}`)}for(const $ of E){const D=$.argIndex-(x?1:0),B=$.maxEvalSpace==="literal"?"literal":$.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[D].logError("invalid-function-argument-evaluation-space",`Parameter ${$.argIndex+1} ('${$.param.name}') of ${this.name} must be ${B}, but received ${$.actualEvalSpace}`)}for(const $ of A){const D=$.argIndex-(x?1:0);this.args[D].logError("literal-null-function-argument",`Parameter ${$.argIndex+1} ('${$.param.name}') of ${this.name} must not be a literal null`)}m.returnTypeError&&this.logError(m.returnTypeError.code,m.returnTypeError.parameters);const v=y.returnType,C=(0,Cr.maxOfExpressionTypes)([(u=v.expressionType)!==null&&u!==void 0?u:"scalar",...p.map($=>$.expressionType)]);if(!(0,Cr.expressionIsAggregate)(y.returnType.expressionType)&&this.source!==void 0)return this.loggedErrorExpr("non-aggregate-function-with-source",`Cannot call function ${this.name}(${p.map($=>$.type).join(", ")}) with source`);const b={node:"function_call",overload:y,name:this.name,kids:{args:p.map($=>$.value)},expressionType:C,structPath:h};let S=b;if(r!=null&&r.orderBys&&r.orderBys.length>0){const $=(0,Cr.expressionIsAnalytic)(y.returnType.expressionType);if($||this.inExperiment("aggregate_order_by",!0)||r.orderBys[0].logError("aggregate-order-by-experiment-not-enabled","Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),y.supportsOrderBy||$){const D=y.supportsOrderBy!=="only_default",B=r.orderBys.flatMap(q=>$?q.getAnalyticOrderBy(e):q.getAggregateOrderBy(e,D));b.kids.orderBy=B}else r.orderBys[0].logError("function-does-not-support-order-by",`Function \`${this.name}\` does not support \`order_by\``)}if((r==null?void 0:r.limit)!==void 0&&(y.supportsLimit?b.limit=r.limit.limit:this.logError("function-does-not-support-limit",`Function ${this.name} does not support limit`)),r!=null&&r.partitionBys&&r.partitionBys.length>0){const $=[];for(const D of r.partitionBys)for(const B of D.partitionFields){const q=B.getField(e);q.found===void 0?B.logError("partition-by-not-found",`${B.refString} is not defined`):(0,Cr.expressionIsAnalytic)(q.found.typeDesc().expressionType)||(0,Cr.expressionIsUngroupedAggregate)(q.found.typeDesc().expressionType)?B.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):$.push(B.nameString)}b.partitionBy=$}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(c.name)){if(!this.inExperiment("sql_functions",!0))return this.loggedErrorExpr("sql-functions-experiment-not-enabled",`Cannot use sql_function \`${c.name}\`; use \`sql_functions\` experiment to enable this behavior`);const $=p[0].value;if($.node!=="stringLiteral")this.logError("invalid-sql-function-argument",`Invalid string literal for \`${c.name}\``);else{const D=$.literal,B=sot(D),q=B.filter(H=>H.type==="interpolation"&&H.name.includes(".")).map(H=>H.type==="interpolation"?`\${${H.name}}`:`\${${H.value}}`);if(q.length>0){const H=q.length===1?`'.' paths are not yet supported in sql interpolations, found ${q.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${q.join(", ")})`;return this.loggedErrorExpr("unsupported-sql-function-interpolation",H)}const K=[];for(const H of B)if(H.type==="string")K.push(H.value);else if(H.name==="TABLE")K.push({node:"source-reference"});else{const X=new tot.FieldName(H.name);this.has({name:X});const fe=e.lookup([X]);if(fe.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${fe.error.message}`);fe.found.refType==="parameter"?K.push({node:"parameter",path:[H.name]}):K.push({node:"field",path:[H.name]})}S=(0,Qle.composeSQLExpr)(K)}}const R=(0,Cr.mergeEvalSpaces)(...p.map($=>$.evalSpace)),O=R==="constant"?"constant":(0,Cr.expressionIsScalar)(C)?R:"output";return{...(0,Cr.isAtomic)(_)?Hle.atomicDef(_):_,expressionType:C,value:S,evalSpace:O,compositeFieldUsage:(0,not.mergeCompositeFieldUsage)(...p.map($=>$.compositeFieldUsage))}}}Vy.ExprFunc=rot;function iot(t,e){var r;for(const i of t.overloads){const s=new Map;let o=0,u=!0,a=!1;const l=[],c=[],f=[];for(let p=0;p<e.length;p++){const m=e[p],y=i.params[o];if(y===void 0){u=!1;break}if(!y.allowedTypes.some(E=>{var A;const{dataTypeMatch:_,genericsSet:v}=p2(s,(A=i.genericTypes)!==null&&A!==void 0?A:[],m,E);for(const C of v)s.set(C.name,C.type);return E.expressionType&&((0,Cr.isExpressionTypeLEQ)(m.expressionType,E.expressionType)||l.push({argIndex:p,maxExpressionType:E.expressionType,actualExpressionType:m.expressionType,param:y})),(E.evalSpace==="literal"&&m.evalSpace!=="literal"||E.evalSpace==="constant"&&(m.evalSpace==="input"||m.evalSpace==="output")||(0,Cr.expressionIsAnalytic)(i.returnType.expressionType)&&m.evalSpace==="input")&&c.push({argIndex:p,param:y,maxEvalSpace:E.evalSpace,actualEvalSpace:m.evalSpace}),E.evalSpace==="literal"&&m.type==="null"&&f.push({argIndex:p,param:y}),_})){u=!1;break}y.isVariadic?p===e.length-1&&(a=!0):o++}if(!a&&(o!==e.length||o!==i.params.length))continue;const x=Ab(i.returnType,s),h=(r=x.returnType)!==null&&r!==void 0?r:{type:"number"};if(u)return{overload:i,expressionTypeErrors:l,evalSpaceErrors:c,nullabilityErrors:f,returnTypeError:x.error,returnType:h}}}function sot(t){const e=[];let r=t;for(;r.length;){const i=r.indexOf("${");if(i===-1){e.push({type:"string",value:r});break}else{const s=r.slice(i).indexOf("}");if(s===-1){e.push({type:"string",value:r});break}i>0&&e.push({type:"string",value:r.slice(0,i)}),e.push({type:"interpolation",name:r.slice(i+2,s+i)}),r=r.slice(s+i+1)}}return e}function p2(t,e,r,i){var s,o,u,a;if(Cr.TD.eq(i,r)||i.type==="any"||i.type!=="generic"&&(r.type==="null"||r.type==="error"))return{dataTypeMatch:!0,genericsSet:[]};if(i.type==="array"&&r.type==="array"){if((0,Cr.isScalarArray)(r))return(0,Cr.isRepeatedRecordFunctionParam)(i)?{dataTypeMatch:!1,genericsSet:[]}:p2(t,e,r.elementTypeDef,i.elementTypeDef);if((0,Cr.isRepeatedRecordFunctionParam)(i)){const l={type:"record",fields:i.fields},c={type:"record",fields:r.fields};return p2(t,e,c,l)}else return{dataTypeMatch:!1,genericsSet:[]}}else if(i.type==="record"&&r.type==="record"){const l=[],c=new Map;for(const f of i.fields)c.set((s=f.as)!==null&&s!==void 0?s:f.name,f);for(const f of r.fields){const x=c.get((o=f.as)!==null&&o!==void 0?o:f.name);if(x===void 0)return{dataTypeMatch:!1,genericsSet:[]};const h=p2(new Map([...t.entries(),...l.map(p=>[p.name,p.type])]),e,f,x);l.push(...h.genericsSet)}return{dataTypeMatch:!0,genericsSet:l}}else if(i.type==="generic"){const l=t.get(i.generic);if(l!==void 0&&l.type!=="null"&&l.type!=="error")return p2(t,e,r,l);const c=(a=(u=e.find(f=>f.name===i.generic))===null||u===void 0?void 0:u.acceptibleTypes)!==null&&a!==void 0?a:[];for(const f of c){const x=p2(t,e,r,f);if(x.dataTypeMatch){if(!(0,Cr.isAtomic)(r)&&r.type!=="null")continue;const h={name:i.generic,type:r};return{dataTypeMatch:!0,genericsSet:[...x.genericsSet,h]}}}}return{dataTypeMatch:!1,genericsSet:[]}}function Ab(t,e){switch(t.type){case"array":{if("fields"in t){const s=t.fields.map(o=>{const u=Ab(o,e);return{...o,...u}});return{error:void 0,returnType:{type:"array",elementTypeDef:t.elementTypeDef,fields:s}}}const r=Ab(t.elementTypeDef,e);if(r.error)return r;const i=r.returnType;return i.type==="record"?{error:void 0,returnType:{type:"array",elementTypeDef:{type:"record_element"},fields:i.fields}}:(0,Cr.isAtomic)(i)?{error:void 0,returnType:{type:"array",elementTypeDef:i}}:{error:{code:"invalid-resolved-type-for-array",parameters:"Invalid resolved type for array; cannot be non-atomic"},returnType:void 0}}case"record":return{error:void 0,returnType:{type:"record",fields:t.fields.map(i=>{const s=Ab(i,e);return{...i,...s}})}};case"generic":{const r=e.get(t.generic);return r===void 0?{error:{code:"generic-not-resolved",parameters:`Generic ${t.generic} in return type could not be resolved`},returnType:void 0}:{error:void 0,returnType:r}}default:return{error:void 0,returnType:t}}}var oot=T&&T.__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]}),uot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),aot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&oot(e,t,r);return uot(e,t),e};Object.defineProperty(Eb,"__esModule",{value:!0}),Eb.ExprProps=void 0;const lot=Xe,cot=ks,fot=aot(Zt),xot=kc,dot=Mc,hot=h2,pot=xt,mot=Vy,got=lt;class yot extends pot.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=fot.anyAtomicT}getFilteredExpression(e,r,i){if(i.length>0){if(!this.expr.supportsWhere(r))return this.expr.logError("filter-of-non-aggregate","Filtered expression requires an aggregate computation"),r;const s=[];for(const o of i){const u=o.getFilterList(e);if(u.find(a=>(0,lot.expressionIsCalculation)(a.expressionType)))return o.logError("aggregate-filter-expression-not-scalar","Cannot filter an expresion with an aggregate or analytical computation"),r;s.push(...u)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,compositeFieldUsage:(0,got.mergeCompositeFieldUsage)(r.compositeFieldUsage,...s.map(o=>o.compositeFieldUsage)),value:{node:"filteredExpr",kids:{e:r.value,filterList:s}}}:(this.expr.logError("filter-of-non-aggregate",`Cannot filter '${r.expressionType}' data`),(0,cot.errorFor)("cannot filter type"))}return r}getExpression(e){const r=[];let i;const s=[],o=[];for(const a of this.statements)a instanceof hot.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.logError("partition-by-of-non-window-function","`partition_by` is not supported for this kind of expression"):a instanceof dot.Limit?i?a.logError("expression-limit-already-specified","limit already specified"):this.expr.canSupportLimit()?i=a:a.logError("limit-of-non-aggregate-function","`limit` is not supported for this kind of expression"):a instanceof xot.FunctionOrdering?this.expr.canSupportOrderBy()?s.push(a):a.logError("order-by-of-non-aggregate-function","`order_by` is not supported for this kind of expression"):o.push(a);const u=this.expr instanceof mot.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:i,orderBys:s}):this.expr.getExpression(e);return this.getFilteredExpression(e,u,o)}}Eb.ExprProps=yot;var _b={},Eot=T&&T.__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]}),Aot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_ot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Eot(e,t,r);return Aot(e,t),e};Object.defineProperty(_b,"__esModule",{value:!0}),_b.ExprLogicalOp=void 0;const vot=zy,zle=_ot(Zt);class Cot extends vot.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[zle.boolT,zle.aggregateBoolT]}}_b.ExprLogicalOp=Cot;var vb={},Sot=T&&T.__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]}),bot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Tot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Sot(e,t,r);return bot(e,t),e};Object.defineProperty(vb,"__esModule",{value:!0}),vb.ExprMax=void 0;const Cb=Tot(Zt),Rot=Jl;class Dot extends Rot.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[Cb.numberT,Cb.stringT,Cb.dateT,Cb.timestampT]}returns(e){return e}}vb.ExprMax=Dot;var Sb={},Oot=T&&T.__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]}),Fot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),wot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Oot(e,t,r);return Fot(e,t),e};Object.defineProperty(Sb,"__esModule",{value:!0}),Sb.ExprMin=void 0;const bb=wot(Zt),Not=Jl;class Lot extends Not.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[bb.numberT,bb.stringT,bb.dateT,bb.timestampT]}returns(e){return e}}Sb.ExprMin=Lot;var Tb={},Iot=T&&T.__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]}),$ot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Bot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Iot(e,t,r);return $ot(e,t),e};Object.defineProperty(Tb,"__esModule",{value:!0}),Tb.ExprMinus=void 0;const kot=ks,Gle=Bot(Zt),Mot=xt;class Pot extends Mot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[Gle.numberT]}getExpression(e){const r=this.expr.getExpression(e);return Gle.typeIn(r,this.legalChildTypes)?{...r,type:"number",value:{node:"unary-",e:r.value}}:(0,kot.errorFor)("negate requires number")}}Tb.ExprMinus=Pot;var Rb={};Object.defineProperty(Rb,"__esModule",{value:!0}),Rb.ExprMulDiv=void 0;const Uot=f2;class jot extends Uot.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}Rb.ExprMulDiv=jot;var Db={},Yy={};Object.defineProperty(Yy,"__esModule",{value:!0}),Yy.Unary=void 0;const qot=xt;class Qot extends qot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}Yy.Unary=Qot;var Hot=T&&T.__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]}),zot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Got=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Hot(e,t,r);return zot(e,t),e};Object.defineProperty(Db,"__esModule",{value:!0}),Db.ExprNot=void 0;const WB=Got(Zt),Wot=Yy;class Vot extends Wot.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[WB.boolT,WB.nullT]}getExpression(e){var r;const i=this.expr.getExpression(e);!((r=e.dialectObj())===null||r===void 0)&&r.booleanAsNumbers&&this.legalChildTypes.find(o=>o.type==="number")===void 0&&this.legalChildTypes.push(WB.numberT);const s=this.typeCheck(this.expr,i);return{...i,type:"boolean",value:{node:"not",e:s?i.value:{node:"false"}}}}}Db.ExprNot=Vot;var Ob={};Object.defineProperty(Ob,"__esModule",{value:!0}),Ob.ExprNow=void 0;const Yot=xt,Kot=lt;class Jot extends Yot.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{type:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now",typeDef:{type:"timestamp"}},compositeFieldUsage:(0,Kot.emptyCompositeFieldUsage)()}}}Ob.ExprNow=Jot;var Uc={};Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.ExprIsNull=Uc.PartialIsNull=Uc.ExprNULL=void 0;const Xot=Qt,Fb=xt;function VB(t,e,r){const i=r.getExpression(t);return i.type="boolean",i.value={node:e==="="?"is-null":"is-not-null",e:i.value},i}class Zot extends Fb.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return(0,Xot.literalExprValue)({dataType:{type:"null"},value:{node:"null"}})}apply(e,r,i){return r==="!="||r==="="?VB(e,r,i):super.apply(e,r,i,!0)}}Uc.ExprNULL=Zot;class eut extends Fb.ExpressionDef{constructor(e){super(),this.op=e,this.elementType="<=> NULL"}apply(e,r,i){return VB(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial null check does not have a value")}atNodeType(){return Fb.ATNodeType.Partial}}Uc.PartialIsNull=eut;class tut extends Fb.ExpressionDef{constructor(e,r){super(),this.expr=e,this.op=r,this.elementType="is null",this.has({expr:e})}getExpression(e){return VB(e,this.op,this.expr)}}Uc.ExprIsNull=tut;var wb={};Object.defineProperty(wb,"__esModule",{value:!0}),wb.ExprNumber=void 0;const nut=Qt,rut=xt;class iut extends rut.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){const e=Number(this.n),r=Number.isNaN(e)?{type:"number"}:{type:"number",numberType:Number.isInteger(e)?"integer":"float"};return(0,nut.literalExprValue)({dataType:r,value:{node:"numberLiteral",literal:this.n}})}}wb.ExprNumber=iut;var Nb={};Object.defineProperty(Nb,"__esModule",{value:!0}),Nb.ExprParens=void 0;const YB=xt;class sut extends YB.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const r=this.expr.getExpression(e);return{...r,value:{node:"()",e:r.value}}}apply(e,r,i,s){return this.expr.atNodeType()===YB.ATNodeType.Or?this.expr.apply(e,r,i,s):(0,YB.applyBinary)(e,i,r,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}Nb.ExprParens=sut;var Lb={};Object.defineProperty(Lb,"__esModule",{value:!0}),Lb.ExprFilterExpression=void 0;const out=Qt,uut=xt,Ib=P4;class aut extends uut.ExpressionDef{constructor(e){super(),this.filterText=e,this.elementType="filter expression literal"}getExpression(){return this.loggedErrorExpr("filter-expression-type","Filter expression illegal here")}apply(e,r,i,s=!1){var o;if(r==="~"||r==="!~"){const u=i.getExpression(e);if(u.type==="error")return u;let a;switch(u.type){case"string":a=Ib.StringFilterExpression.parse(this.filterText);break;case"number":a=Ib.NumberFilterExpression.parse(this.filterText);break;case"boolean":if(!((o=e.dialectObj())===null||o===void 0)&&o.booleanAsNumbers)return this.loggedErrorExpr("filter-expression-type","Boolean filters not supported on this connection type");a=Ib.BooleanFilterExpression.parse(this.filterText);break;case"date":case"timestamp":a=Ib.TemporalFilterExpression.parse(this.filterText);break;default:return i.loggedErrorExpr("filter-expression-type",`Cannot use filter expressions with type '${u.type}'`)}if(a.log.length>0)for(const c of a.log)return this.loggedErrorExpr("filter-expression-error",`Filter parse error: ${c.message}`);if(!a.parsed)return this.loggedErrorExpr("filter-expression-type","FJKLD:JDKSL: expression parsed to null");const l={node:"filterMatch",dataType:u.type,filter:a.parsed,e:u.value};return r==="!~"&&(l.notMatch=!0),(0,out.computedExprValue)({value:l,dataType:{type:"boolean"},from:[u]})}return this.loggedErrorExpr("filter-expression-type",`Cannot use the '${r}' operator with a filter expression`)}}Lb.ExprFilterExpression=aut;var $b={};Object.defineProperty($b,"__esModule",{value:!0}),$b.ExprRegEx=void 0;const lut=Qt,cut=xt;class fut extends cut.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return(0,lut.literalExprValue)({dataType:{type:"regular expression"},value:{node:"regexpLiteral",literal:this.regex}})}}$b.ExprRegEx=fut;var Bb={};Object.defineProperty(Bb,"__esModule",{value:!0}),Bb.ExprString=void 0;const xut=xt,dut=Qt;class hut extends xut.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return(0,dut.literalExprValue)({dataType:{type:"string"},value:{node:"stringLiteral",literal:this.value}})}}Bb.ExprString=hut;var kb={};Object.defineProperty(kb,"__esModule",{value:!0}),kb.ExprSum=void 0;const put=d2;class mut extends put.ExprAsymmetric{constructor(e,r,i){super("sum",e,r,i),this.has({source:r})}}kb.ExprSum=mut;var Mb={};Object.defineProperty(Mb,"__esModule",{value:!0}),Mb.ExprTimeExtract=void 0;const Xl=Xe,Pb=Qt,KB=xt,gut=Bc;class Ky extends KB.ExpressionDef{static extractor(e){const r=Ky.pluralMap[e];if(r)return r;if((0,Xl.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){const r=Ky.extractor(this.extractText);if(r){if(this.args.length!==1)return this.loggedErrorExpr("too-many-arguments-for-time-extraction",`Extraction function ${r} requires one argument`);const i=this.args[0];if(i instanceof gut.Range){let s=i.first.getExpression(e),o=i.last.getExpression(e);if(s.type==="error"||o.type==="error")return(0,Pb.computedErrorExprValue)({dataType:{type:"number"},error:"extract from error",from:[s,o]});if(!(0,Xl.isTemporalType)(s.type))return i.first.loggedErrorExpr("invalid-type-for-time-extraction",`Can't extract ${r} from '${s.type}'`);if(!(0,Xl.isTemporalType)(o.type))return i.last.loggedErrorExpr("invalid-type-for-time-extraction",`Cannot extract ${r} from '${o.type}'`);let u=s.type;if(!Xl.TD.eq(s,o)){let a=!0;if(u="timestamp",s.type==="date"){const l=(0,KB.getMorphicValue)(s,"timestamp");l&&(s=l,a=!1)}else{const l=(0,KB.getMorphicValue)(o,"timestamp");l&&(o=l,a=!1)}if(a)return i.first.loggedErrorExpr("invalid-types-for-time-measurement",`Cannot measure from ${s.type} to ${o.type}`)}return["week","month","quarter","year"].includes(r)?this.loggedErrorExpr("invalid-timeframe-for-time-measurement",`Cannot measure interval using '${r}'`):(0,Xl.isTimestampUnit)(r)?(0,Pb.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"timeDiff",units:r,kids:{left:(0,Xl.mkTemporal)(s.value,u),right:(0,Xl.mkTemporal)(o.value,u)}},from:[s,o]}):this.loggedErrorExpr("invalid-time-extraction-unit",`Cannot extract ${r} from a range`)}else{const s=i.getExpression(e);return(0,Xl.isTemporalType)(s.type)?(0,Pb.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"extract",e:(0,Xl.mkTemporal)(s.value,s.type),units:r},from:[s]}):(s.type!=="error"&&this.logError("unsupported-type-for-time-extraction",`${this.extractText}() requires time type, not '${s.type}'`),(0,Pb.computedErrorExprValue)({dataType:{type:"number",numberType:"integer"},error:`${this.extractText} bad type ${s.type}`,from:[s]}))}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}Mb.ExprTimeExtract=Ky,Ky.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var Ub={},mu={},jb={};Object.defineProperty(jb,"__esModule",{value:!0}),jb.QueryInputSpace=void 0;const yut=hs,Eut=Zp;class Aut extends Eut.RefinedSpace{constructor(e,r,i){super(e),this.queryOutput=r,this._isProtectedAccessSpace=i,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof yut.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}isProtectedAccessSpace(){return this._isProtectedAccessSpace}}jb.QueryInputSpace=Aut;var _ut=T&&T.__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]}),vut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Cut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&_ut(e,t,r);return vut(e,t),e};Object.defineProperty(mu,"__esModule",{value:!0}),mu.ReduceFieldSpace=mu.QuerySpace=mu.QueryOperationSpace=void 0;const qb=Cut(Xe),JB=Fc,Wle=Pc,Vle=Pr,Sut=yt,but=Zp,Tut=wy,Rut=Ur,Dut=jb,Oa=lt,Out=ed;class Yle extends but.RefinedSpace{get compositeFieldUsage(){if(this._compositeFieldUsage===void 0)throw new Error("Composite field usage accessed before computed");return this._compositeFieldUsage}constructor(e,r,i,s){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=i,this.astEl=s,this.expandedWild={},this.compositeFieldUsers=[],this._compositeFieldUsage=void 0,this.exprSpace=new Dut.QueryInputSpace(e.structDef(),this,e.isProtectedAccessSpace()),r&&this.addRefineFromFields(r)}logError(e,r,i){return this.astEl&&this.astEl.logError(e,r,i),e}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof Rut.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-defined",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries())if(!e.except.has(a)&&l.refType!=="parameter")if(this.entry(a)){const c=(r=this.expandedWild[a])===null||r===void 0?void 0:r.path.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=l.typeDesc();qb.TD.isAtomic(c)&&qb.expressionIsScalar(c.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:a,entry:l}),this.expandedWild[a]={path:s.concat(a),entry:l})}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.newEntry(a.name,e,a.entry)}addValidatedCompositeFieldUserFromEntry(e,r){r instanceof Vle.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:r,logTo:void 0})}getJoinOnCompositeFieldUsage(e){var r;const i=e.map(o=>new Wle.FieldName(o));this.astEl.has({reference:i});const s=this.exprSpace.lookup(i);if(s.found&&s.found instanceof Out.StructSpaceFieldBase)return(0,Oa.joinedCompositeFieldUsage)(e.slice(0,-1),(r=s.found.fieldDef().onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Oa.emptyCompositeFieldUsage)());throw new Error("Unexpected join lookup was not found or not a struct")}getCompositeFieldUsageIncludingJoinOns(e){let r=e;const i=(0,Oa.compositeFieldUsageJoinPaths)(e);for(const s of i)r=(0,Oa.mergeCompositeFieldUsage)(this.getJoinOnCompositeFieldUsage(s),r);return r}addCompositeFieldUserFromFilter(e,r){e.compositeFieldUsage!==void 0&&this.compositeFieldUsers.push({type:"filter",filter:e,logTo:r})}newEntry(e,r,i){i instanceof Vle.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:i,logTo:r}),super.newEntry(e,r,i)}applyNextCompositeFieldUsage(e,r,i,s,o){if(s){const u=this.getCompositeFieldUsageIncludingJoinOns((0,Oa.compositeFieldUsageDifference)(s,r));if(r=(0,Oa.mergeCompositeFieldUsage)(r,u),!(0,Oa.isEmptyCompositeFieldUsage)(u)){const a=(0,Oa.narrowCompositeFieldResolution)(e,r,i);a.error?(o??this).logError("invalid-composite-field-usage",{newUsage:u,allUsage:r}):i=a.narrowedCompositeFieldResolution}}return{compositeFieldUsage:r,narrowedCompositeFieldResolution:i}}}mu.QueryOperationSpace=Yle;class Kle extends Yle{addRefineFromFields(e){var r;if(qb.isQuerySegment(e)){if(e!=null&&e.extendSource)for(const i of e.extendSource)this.exprSpace.addFieldDef(i);for(const i of e.queryFields)if(i.type==="fieldref"){const s=this.exprSpace.lookup(i.path.map(o=>new Wle.FieldName(o)));if(s.found){const o=i.path[i.path.length-1];this.setEntry(o,s.found),this.addValidatedCompositeFieldUserFromEntry(o,s.found)}}else if(i.type!=="turtle"){const s=new Tut.ColumnSpaceField(i),o=(r=i.as)!==null&&r!==void 0?r:i.name;this.setEntry(o,s),this.addValidatedCompositeFieldUserFromEntry(o,s)}}}pushFields(...e){for(const r of e)r instanceof Sut.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){const e=[];let r=(0,Oa.emptyCompositeFieldUsage)(),i=(0,Oa.emptyNarrowedCompositeFieldResolution)();const s=this.inputSpace().structDef();for(const o of this.compositeFieldUsers){let u;if(o.type==="filter")o.filter.compositeFieldUsage&&(u=o.filter.compositeFieldUsage);else{const{name:l,field:c}=o,f=this.expandedWild[l];if(f)e.push({type:"fieldref",path:f.path}),u=f.entry.typeDesc().compositeFieldUsage;else{const x=c.getQueryFieldDef(this.exprSpace);if(x){const h=c.typeDesc();u=h.compositeFieldUsage,h&&h.type!=="error"&&this.canContain(h)&&!wut(x)&&e.push(x)}}}const a=this.applyNextCompositeFieldUsage(s,r,i,u,o.logTo);r=a.compositeFieldUsage,i=a.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,e}getQuerySegment(e){const r=this.getPipeSegment(e);if(qb.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.logError("unexpected-index-segment","internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};const r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,JB.mergeFields)(e==null?void 0:e.queryFields,r.queryFields),e!=null&&e.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const i=[],s=this.exprSpace.structDef();for(const o of this.exprSpace.extendList){const u=s.fields.find(a=>(0,JB.nameFromDef)(a)===o);u&&i.push(u)}r.extendSource=(0,JB.mergeFields)(r.extendSource,i)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),r}lookup(e){const r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}mu.QuerySpace=Kle;class Fut extends Kle{constructor(){super(...arguments),this.segmentType="reduce"}}mu.ReduceFieldSpace=Fut;function wut(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}var Nut=T&&T.__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]}),Lut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Iut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Nut(e,t,r);return Lut(e,t),e};Object.defineProperty(Ub,"__esModule",{value:!0}),Ub.ExprUngroup=void 0;const Jle=Xe,$ut=mu,Xle=Iut(Zt),But=xt;class kut extends But.ExpressionDef{constructor(e,r,i){super({expr:r,fields:i}),this.control=e,this.expr=r,this.fields=i,this.legalChildTypes=Xle.anyAtomicT,this.elementType="ungroup"}getExpression(e){const r=this.expr.getExpression(e);if(!(0,Jle.expressionIsAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,Jle.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-ungrouped-aggregate",`${this.control}() expression must not already be ungrouped`);const i={node:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const s=[],o=this.control==="exclude";for(const u of this.fields){let a=e.outputSpace(),l=!0;for(;a;){const c=a.lookup([u]);if(c.found&&c.isOutputField)s.push(u.refString),l=!1;else if(a instanceof $ut.QuerySpace){a=a.nestParent;continue}break}if(l){const c=o?"exclude()":"all()";u.logError("ungroup-field-not-in-output",`${c} '${u.refString}' is missing from query output`)}}i.fields=s}return{...Xle.atomicDef(r),expressionType:"ungrouped_aggregate",value:i,evalSpace:"output",compositeFieldUsage:r.compositeFieldUsage}}return this.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}Ub.ExprUngroup=kut;var Qb={},Mut=T&&T.__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]}),Put=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Uut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Mut(e,t,r);return Put(e,t),e};Object.defineProperty(Qb,"__esModule",{value:!0}),Qb.ForRange=void 0;const jut=ks,Zle=Uut(Zt),Hb=ps,qut=Qt,Qut=xt,zb=c2,e0e=Bc;class Hut extends Qut.ExpressionDef{constructor(e,r,i){super({from:e,duration:r,timeframe:i}),this.from=e,this.duration=r,this.timeframe=i,this.elementType="forRange",this.legalChildTypes=[Zle.timestampT,Zle.dateT]}apply(e,r,i){const s=this.from.getExpression(e),o=i.getExpression(e);if(!this.typeCheck(i,o))return(0,jut.errorFor)("no time for range");const u=this.duration.getExpression(e);if(u.type!=="number")return u.type!=="error"&&this.logError("invalid-duration-quantity",`FOR duration count must be a number, not '${u.type}'`),(0,qut.computedErrorExprValue)({dataType:{type:"boolean"},error:"for not number",from:[s,o]});const a=this.timeframe.text;let l=(0,Hb.resolution)(a);if(s.type==="timestamp"&&(l="timestamp"),o.type==="date"&&l==="date"){const m=this.from,y=(0,Hb.timeOffset)("date",s.value,"+",u.value,a),g=new zb.ExprTime("date",y);return new e0e.Range(m,g).apply(e,r,i)}const c=zb.ExprTime.fromValue("timestamp",o);let f=this.from,x=s.value;if(s.type==="date"){const m=s.morphic&&s.morphic.timestamp;m?x=m:x=(0,Hb.castTo)("timestamp",x,"date"),f=new zb.ExprTime("timestamp",x,[s])}const h=(0,Hb.timeOffset)("timestamp",x,"+",u.value,a),p=new zb.ExprTime("timestamp",h,[s,u]);return new e0e.Range(f,p).apply(e,r,c)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}Qb.ForRange=Hut;var Sr={};Object.defineProperty(Sr,"__esModule",{value:!0}),Sr.LiteralYear=Sr.LiteralQuarter=Sr.LiteralMonth=Sr.LiteralWeek=Sr.LiteralDay=Sr.LiteralHour=Sr.LiteralTimestamp=Sr.TimeFormatError=void 0;const jc=Cy,zut=Xe,Gut=Qt,Wut=Bc,t0e=c2,XB=xt;class Vut extends Error{}Sr.TimeFormatError=Vut;function id(t,e){const r=t.slice(1);if(e){const i=r.match(/\[[^\]]+]$/);if(i)return{tzSpec:i[0].slice(1,-1),text:r.slice(0,-i[0].length)}}return{text:r}}const n0e="yyyy",r0e=`${n0e}-LL`,Ao=`${r0e}-dd`,i0e=`${Ao} HH`,s0e=`${i0e}:mm`,ZB=`${s0e}:ss`;class o0e extends XB.ExpressionDef{constructor(e,r,i){super(),this.units=r,this.timeType=i,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){const i={node:"timeLiteral",literal:e,typeDef:{type:r}};return this.timeZone&&(i.timezone=this.timeZone),i}makeValue(e,r){const i=this.makeLiteral(e,r);return(0,Gut.literalTimeResult)({value:i,dataType:{type:r},timeframe:this.units})}getExpression(e){return this.makeValue(this.literalPart,this.timeType)}getNext(){if(this.nextLit)return this.makeValue(this.nextLit,this.timeType)}granular(){return this.nextLit!==void 0}}class ek extends o0e{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r;const i=id(e,!0);e=i.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),i.text=e);const s=e.match(/^([^.,]+)[,.](\d+)$/);s&&(e=s[1]);let o=jc.DateTime.fromFormat(e,ZB);if(o.isValid)return new ek(i,r);if(o=jc.DateTime.fromFormat(e,s0e),o.isValid){i.text=i.text+":00",r="minute";const u=o.plus({minute:1}).toFormat(ZB);return new tk(i,r,"timestamp",u)}}}Sr.LiteralTimestamp=ek;class tk extends o0e{constructor(e,r,i,s){super(e,r,i),this.nextLit=s,this.elementType="granularTimeLiteral"}apply(e,r,i){let s=this.getExpression(e),o=this.getNext();if(o){const u=i.getExpression(e);if(u.type==="timestamp"){const a=(0,XB.getMorphicValue)(s,"timestamp"),l=(0,XB.getMorphicValue)(o,"timestamp");if(a&&l)s=a,o=l;else return super.apply(e,r,i)}if(o&&(0,zut.isTemporalType)(u.type)){const a=u.type;return new Wut.Range(new t0e.ExprTime(a,s.value),new t0e.ExprTime(a,o.value)).apply(e,r,i)}}return super.apply(e,r,i)}}class nk extends tk{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){const r=id(e,!1);let i=r.text;const s=jc.DateTime.fromFormat(r.text,i0e);if(s.isValid)return r.text=r.text+":00:00",i=s.plus({hour:1}).toFormat(ZB),new nk(r,i)}}Sr.LiteralHour=nk;class Jy extends tk{constructor(e,r,i){super(e,r,"date",i)}getExpression(e){const r=this.makeValue(this.literalPart,"date"),i=this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp");return{...r,morphic:{timestamp:i},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),r=this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp");return{...e,morphic:{timestamp:r}}}}class rk extends Jy{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){const r=id(e,!1);let i=r.text;const s=jc.DateTime.fromFormat(r.text,Ao);if(s.isValid)return i=s.plus({day:1}).toFormat(Ao),new rk(r,i)}}Sr.LiteralDay=rk;class ik extends Jy{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){const r=id(e,!1);let i=r.text;const s=r.text.slice(0,10),o=jc.DateTime.fromFormat(s,Ao);if(o.isValid&&o.weekday===7){const a=o.plus({days:7});return r.text=o.toFormat(Ao),i=a.toFormat(Ao),new ik(r,i)}}}Sr.LiteralWeek=ik;class sk extends Jy{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){const r=id(e,!1);let i=r.text;const s=jc.DateTime.fromFormat(r.text,r0e);if(s.isValid){const o=s.plus({months:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new sk(r,i)}}}Sr.LiteralMonth=sk;class ok extends Jy{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){const r=id(e,!1);let i=r.text;const s=r.text.match(/(^\d{4})-[qQ](\d)$/);if(s){const o=Number.parseInt(s[2])-1;let u=jc.DateTime.fromFormat(s[1],"yyyy");o>0&&(u=u.plus({quarters:o}));const a=u.plus({quarter:1});return r.text=u.toFormat(Ao),i=a.toFormat(Ao),new ok(r,i)}}}Sr.LiteralQuarter=ok;class uk extends Jy{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){const r=id(e,!1);let i=r.text;const s=jc.DateTime.fromFormat(r.text,n0e);if(s.isValid){const o=s.plus({year:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new uk(r,i)}}}Sr.LiteralYear=uk;var Gb={};Object.defineProperty(Gb,"__esModule",{value:!0}),Gb.PartialCompare=void 0;const u0e=xt;class Yut extends u0e.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,i){return this.right.apply(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial comparison does not have a value")}atNodeType(){return u0e.ATNodeType.Partial}}Gb.PartialCompare=Yut;var m2={},Kut=T&&T.__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]}),Jut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Kut(e,t,r);return Jut(e,t),e};Object.defineProperty(m2,"__esModule",{value:!0}),m2.PickWhen=m2.Pick=void 0;const g2=Xut(Zt),a0e=Qt,Zut=xt,eat=Je;function Wb(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class tat extends Zut.ExpressionDef{constructor(e,r){super({choices:e}),this.choices=e,this.elsePick=r,this.elementType="pick",this.has({elsePick:r})}requestExpression(e){if(this.elsePick!==void 0){for(const r of this.choices){if(r.pick===void 0)return;const i=r.when.requestExpression(e);if(i===void 0||i.type!=="boolean")return}return this.getExpression(e)}}apply(e,r,i){var s;const o={node:"case",kids:{caseWhen:[],caseThen:[]}};let u;const a=[];for(const h of this.choices){const p=h.when.apply(e,"=",i),m=h.pick?h.pick.getExpression(e):i.getExpression(e);if(a.push(p,m),u&&!g2.typeEq(u,m,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:m.type,returnType:u.type});u=Wb(u,m),o.kids.caseWhen.push(p.value),o.kids.caseThen.push(m.value)}const l=(s=this.elsePick)===null||s===void 0?void 0:s.getExpression(e),c=i.getExpression(e);a.push(c),l&&a.push(l);const f=l??c,x=Wb(u,f);return g2.typeEq(x,f,!0)?(o.kids.caseElse=f.value,(0,a0e.computedExprValue)({dataType:x,value:o,from:a})):this.elsePick?this.loggedErrorExpr("pick-else-type-does-not-match",{elseType:f.type,returnType:x.type}):this.loggedErrorExpr("pick-default-type-does-not-match",{defaultType:f.type,returnType:x.type})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}};if(this.elsePick===void 0)return this.loggedErrorExpr("pick-missing-else","pick incomplete, missing 'else'");const i=[],s=[];for(const l of this.choices){if(l.pick===void 0)return this.loggedErrorExpr("pick-missing-value","pick with no value can only be used with apply");l.when.requestExpression(e)===void 0&&this.loggedErrorExpr("pick-illegal-partial","pick with partial when can only be used with apply");const f=l.pick.getExpression(e),x=l.when.getExpression(e);i.push({pick:f,when:x}),s.push(f,x)}let o;for(const l of i){if(!g2.typeEq(l.when,g2.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:l.when.type});if(o&&!g2.typeEq(o,l.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:l.pick.type,returnType:o.type});o=Wb(o,l.pick),r.kids.caseWhen.push(l.when.value),r.kids.caseThen.push(l.pick.value)}const u=this.elsePick.getExpression(e);s.push(u);const a=Wb(o,u);return g2.typeEq(a,u,!0)?(r.kids.caseElse=u.value,(0,a0e.computedExprValue)({dataType:a,value:r,from:s})):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.type,returnType:a.type})}}m2.Pick=tat;class nat extends eat.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="caseWhen",this.has({pick:e})}}m2.PickWhen=nat;var y2={},rat=T&&T.__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]}),iat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rat(e,t,r);return iat(e,t),e};Object.defineProperty(y2,"__esModule",{value:!0}),y2.CaseWhen=y2.Case=void 0;const oat=Qt,uat=xt,aat=Je,E2=sat(Zt);function l0e(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class lat extends uat.ExpressionDef{constructor(e,r,i){super({choices:r}),this.value=e,this.choices=r,this.elseValue=i,this.elementType="case",this.has({elseValue:i,value:e})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}},i=[];let s;if(this.value){const a=this.value.getExpression(e);i.push(a),r.kids.caseValue=a.value,s=a}const o=[];for(const a of this.choices){const l=a.when.getExpression(e),c=a.then.getExpression(e);o.push({when:l,then:c}),i.push(l,c)}let u;for(const a of o){if(s!==void 0){if(!E2.typeEq(a.when,s))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:a.when.type,valueType:s.type})}else if(!E2.typeEq(a.when,E2.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:a.when.type});if(u&&!E2.typeEq(u,a.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:a.then.type,returnType:u.type});u=l0e(u,a.then),r.kids.caseWhen.push(a.when.value),r.kids.caseThen.push(a.then.value)}if(this.elseValue){const a=this.elseValue.getExpression(e);if(u&&!E2.typeEq(u,a,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:a.type,returnType:u.type});u=l0e(u,a),i.push(a),r.kids.caseElse=a.value}return(0,oat.computedExprValue)({value:r,dataType:u?E2.atomicDef(u):{type:"null"},from:i})}}y2.Case=lat;class cat extends aat.MalloyElement{constructor(e,r){super({when:e,then:r}),this.when=e,this.then=r,this.elementType="caseWhen"}}y2.CaseWhen=cat;var Vb={},sd={},fat=T&&T.__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]}),xat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&fat(e,t,r);return xat(e,t),e};Object.defineProperty(sd,"__esModule",{value:!0}),sd.RecordLiteral=sd.RecordElement=void 0;const c0e=ji,hat=Qt,pat=xt,mat=Je,gat=dat(Zt);class yat extends mat.MalloyElement{constructor(e){if(super(),this.elementType="record element","value"in e)this.value=e.value,this.has({value:e.value}),e.key&&(this.key=e.key);else{this.has({path:e.path}),this.value=e.path;const r=e.path.fieldReference.path;this.key=r[r.length-1]}}}sd.RecordElement=yat;class Eat extends pat.ExpressionDef{constructor(e){super(),this.pairs=e,this.elementType="record literal",this.has({pairs:e})}getExpression(e){return this.getRecord(e,[])}getRecord(e,r){var i;const s={node:"recordLiteral",kids:{},typeDef:{type:"record",fields:[]}},o=[];let u=0;for(const a of this.pairs){const l=(i=a.key)!==null&&i!==void 0?i:r[u];if(u+=1,l===void 0){a.logError("record-literal-needs-keys","Anonymous record element not legal here");continue}const c=a.value.getExpression(e);c0e.TD.isAtomic(c)?(o.push(c),s.kids[l]=c.value,s.typeDef.fields.push((0,c0e.mkFieldDef)(gat.atomicDef(c),l))):a.value.logError("illegal-record-property-type",`Record property '${a.key} is type '${c.type}', which is not a legal property value type`)}return(0,hat.computedExprValue)({value:s,dataType:s.typeDef,from:o})}getNextElement(e,r){const i=r.value;return i.node==="recordLiteral"?this.getRecord(e,Object.keys(i.kids)):this.getRecord(e,[])}}sd.RecordLiteral=Eat;var Aat=T&&T.__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]}),_at=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Aat(e,t,r);return _at(e,t),e};Object.defineProperty(Vb,"__esModule",{value:!0}),Vb.ArrayLiteral=void 0;const Cat=Qt,Sat=xt,f0e=vat(Zt),bat=sd;class Tat extends Sat.ExpressionDef{constructor(e){super(),this.elements=e,this.elementType="array literal",this.has({elements:e})}getExpression(e){const r=[],i=[];let s;if(this.elements.length>0)for(const l of this.elements){const c=s&&l instanceof bat.RecordLiteral?l.getNextElement(e,s):l.getExpression(e);if(i.push(c),c.type!=="error"){if(s){if(c.type!=="null"&&!f0e.typeEq(s,c)){l.logError("array-values-incompatible","All array elements must be same type");continue}}else c.type!=="null"&&(s=c);r.push(c.value)}}const o=f0e.atomicDef(s||{type:"number"}),u=o.type==="record"?{type:"array",elementTypeDef:{type:"record_element"},fields:o.fields}:{type:"array",elementTypeDef:o},a={node:"arrayLiteral",kids:{values:r},typeDef:u};return(0,Cat.computedExprValue)({dataType:u,value:a,from:i})}}Vb.ArrayLiteral=Tat;var Yb={};Object.defineProperty(Yb,"__esModule",{value:!0}),Yb.Timeframe=void 0;const Rat=Xe,Dat=Je;class Oat extends Dat.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,Rat.isTimestampUnit)(r)?r:"second"}}Yb.Timeframe=Oat;var qc={};Object.defineProperty(qc,"__esModule",{value:!0}),qc.ImportStatement=qc.ImportSelect=qc.ImportSourceName=void 0;const ak=Je;class Fat extends ak.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}qc.ImportSourceName=Fat;class wat extends ak.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}}qc.ImportSelect=wat;class Nat extends ak.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.logError("invalid-import-url","Invalid URL in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const i=e.childRequest(this.fullURL);if(i)return i}}execute(e){const r=this.translator();if(!r)this.logError("no-translator-for-import","Cannot import without translation context");else if(this.fullURL){const i=r.root.pretranslatedModels.get(this.fullURL),s=r.root.importZone.getEntry(this.fullURL);if(i||s.status==="present"){const o=r.getChildExports(this.fullURL);if(this.notEmpty())for(const u of this.list){const a=u.from||u;if(e.getEntry(u.text))u.logError("name-conflict-on-selective-import",`Cannot redefine '${u.text}'`);else if(o[a.text]){const l={...o[a.text]};u.from&&(l.as=u.text),e.setEntry(u.text,{entry:l,exported:!1})}else a.logError("selective-import-not-found",`Cannot find '${a.text}', not imported`)}else for(const[u,a]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(u)?this.logError("name-conflict-on-indiscriminate-import",`Cannot redefine '${u}'`):e.setEntry(u,{entry:a,exported:!1})}else s.status==="error"?this.logError("failed-import",`import failed: '${s.message}'`):this.logError("failed-import",`import failed with status: '${s.status}'`)}}}qc.ImportStatement=Nat;var Xy={};Object.defineProperty(Xy,"__esModule",{value:!0}),Xy.ExtendBlock=void 0;const Lat=Je,Iat=qn;class $at extends Lat.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Iat.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)for(const i of r.list)e.inputFS.extendSource(i)}}Xy.ExtendBlock=$at;var Kb={};Object.defineProperty(Kb,"__esModule",{value:!0}),Kb.Argument=void 0;const Bat=Je;class kat extends Bat.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}Kb.Argument=kat;var Jb={};Object.defineProperty(Jb,"__esModule",{value:!0}),Jb.HasParameter=void 0;const x0e=Xe,Mat=Je;class Pat extends Mat.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,x0e.isCastType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default}))}parameter(){var e;if(this.default!==void 0){const r=this.default.constantValue();return this.type&&this.type!==r.type&&r.type!=="null"&&r.type!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),r.type==="null"?this.type?{type:this.type,value:r.value,name:this.name}:(this.default.logError("parameter-null-default-without-declared-type","Default value cannot have type `null` unless parameter type is also specified"),{value:r.value,name:this.name,type:"error"}):!(0,x0e.isCastType)(r.type)&&r.type!=="error"?(this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${r.type}\``),{value:r.value,name:this.name,type:"error"}):{value:r.value,name:this.name,type:r.type}}return this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),{value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"}}}Jb.HasParameter=Pat;var Xb={};Object.defineProperty(Xb,"__esModule",{value:!0}),Xb.AnonymousQuery=void 0;const Uat=Je,jat=Mr;class qat extends Uat.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=jat.extendNoteMethod,this.has({queryExpr:e})}execute(e){const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("non-query-used-as-query","Cannot run this object as a query");return}const i={...r.query()},s=this.note||{};i.annotation&&(s.inherits=i.annotation),(s.notes||s.blockNotes||s.inherits)&&(i.annotation=s),e.queryList.push(i)}}Xb.AnonymousQuery=qat;var Qc={};Object.defineProperty(Qc,"__esModule",{value:!0}),Qc.View=void 0;const Qat=Je;class Hat extends Qat.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}}Qc.View=Hat;var Zb={};Object.defineProperty(Zb,"__esModule",{value:!0}),Zb.ViewArrow=void 0;const zat=Ur,Gat=Qc;class Wat extends Gat.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){const r=this.base.pipelineComp(e),i=new zat.StaticSourceSpace(r.outputStruct),s=this.operation.pipelineComp(i);return{pipeline:[...r.pipeline,...s.pipeline],outputStruct:s.outputStruct}}refine(e,r,i){return this.logError("refinement-with-multistage-view","A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}Zb.ViewArrow=Wat;var eT={},Zy={};Object.defineProperty(Zy,"__esModule",{value:!0}),Zy.refine=void 0;const lk=ji,Vat=lt,ck=Fc;function Yat(t,e,r){var i,s;if(e.length!==1)return t.logError("refinement-with-multistage-view","Named refinements of multi-stage views are not supported"),e;const o={...e[0]},u=r;if((0,lk.isRawSegment)(o))t.logError("refinement-of-raw-query","Cannot refine raw query, must add an explicit query stage");else if(o.type==="partial"&&u.type!=="index"&&u.type!=="raw"?o.type=u.type:u.type!==o.type&&t.logError("mismatched-view-types-for-refinement",`cannot refine ${o.type} view with ${u.type} view`),u.type!=="index"&&o.type!=="index"&&u.type!=="raw"&&(u.orderBy!==void 0&&!u.defaultOrderBy&&(o.orderBy===void 0||o.defaultOrderBy?o.orderBy=u.orderBy:t.logError("ordering-overridden-in-refinement","refinement cannot override existing ordering")),u.limit!==void 0&&(o.limit===void 0?o.limit=u.limit:t.logError("limit-overridden-in-refinement","refinement cannot override existing limit"))),o.filterList=o.filterList!==void 0||u.filterList!==void 0?[...(i=o.filterList)!==null&&i!==void 0?i:[],...(s=u.filterList)!==null&&s!==void 0?s:[]]:void 0,(0,lk.isQuerySegment)(u)&&(0,lk.isQuerySegment)(o)){const a=[],l=[],c=new Map(o.queryFields.map(f=>[(0,ck.nameFromDef)(f),f]));for(const f of u.queryFields)c.has((0,ck.nameFromDef)(f))?a.push(f):l.push(f);o.queryFields=[...o.queryFields,...l],a.length>0&&t.logError("name-conflict-in-refinement",`overlapping fields in refinement: ${a.map(ck.nameFromDef)}`),o.compositeFieldUsage=(0,Vat.mergeCompositeFieldUsage)(o.compositeFieldUsage,u.compositeFieldUsage)}else u.type==="index"&&o.type==="index"&&(o.indexFields=[...u.indexFields,...o.indexFields]);return[o]}Zy.refine=Yat,Object.defineProperty(eT,"__esModule",{value:!0}),eT.ViewRefine=void 0;const Kat=li,Jat=Ps,Xat=Zy,Zat=Qc;class elt extends Zat.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){const i=this.base.pipelineComp(e),s=this.refinement.refine(e,i.pipeline,r);return{pipeline:s,annotation:i.annotation,outputStruct:s.length>0?(0,Jat.getFinalStruct)(this.refinement,e.structDef(),s):Kat.ErrorFactory.structDef}}refine(e,r,i){const s=this.pipeline(e,i);return s.length!==1?(this.refinement.logError("refinement-with-multistage-view","refinement must have exactly one stage"),r):(0,Xat.refine)(this,r,s[0])}getImplicitName(){return this.base.getImplicitName()}}eT.ViewRefine=elt;var tT={};Object.defineProperty(tT,"__esModule",{value:!0}),tT.ReferenceView=void 0;const fk=Xe,d0e=li,tlt=Ps,nlt=Pr,rlt=Zy,ilt=Qc;class slt extends ilt.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,r){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:r}={forRefinement:!1}){const i=this.reference.getField(e),s=function(){return{inputStruct:d0e.ErrorFactory.structDef,outputStruct:d0e.ErrorFactory.structDef,pipeline:[],error:!0}};if(!i.found)return this.reference.logError(i.error.code,i.error.message),s();if(!(i.found instanceof nlt.SpaceField))throw new Error("Expected space field");const o=i.found.fieldDef();if(o===void 0)throw new Error("Expected field to have definition");if((0,fk.isAtomic)(o)){const u={type:"reduce",queryFields:[this.reference.refToField],compositeFieldUsage:o.compositeFieldUsage},a=this.reference.nameString,l={...(0,fk.sourceBase)(e.structDef()),type:"query_result",name:a,fields:[o]};return{pipeline:[u],name:a,outputStruct:l}}else return(0,fk.isTurtle)(o)?this.reference.list.length>1?(r?this.logError("refinement-with-joined-view","Cannot use view from join as refinement"):this.logError("nest-of-joined-view","Cannot use view from join"),s()):{pipeline:[...o.pipeline],name:o.name,annotation:o.annotation,outputStruct:(0,tlt.getFinalStruct)(this.reference,e.structDef(),o.pipeline)}:(r?this.reference.logError("refinement-with-source",`named refinement \`${this.reference.refString}\` must be a view, found a ${o.type}`):this.reference.logError("nest-of-source","This operation is not supported"),s())}getRefinementSegment(e){const{pipeline:r,error:i}=this._pipelineComp(e,{forRefinement:!0});if(!i){if(r.length!==1){this.reference.logError("refinement-with-multistage-view",`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,i){const s=this.getRefinementSegment(e);return s?(0,rlt.refine)(this,r,s):r}getImplicitName(){return this.reference.nameString}}tT.ReferenceView=slt;var nT={},eE={},rT={},tE={};Object.defineProperty(tE,"__esModule",{value:!0}),tE.Index=void 0;const olt=Je,ult=qn;class alt extends olt.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=ult.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}}tE.Index=alt;var nE={};Object.defineProperty(nE,"__esModule",{value:!0}),nE.SampleProperty=void 0;const llt=Je,h0e=qn;class clt extends llt.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=h0e.LegalRefinementStage.Tail,this.forceQueryClass=h0e.QueryClass.Index}sampling(){return this.sample}}nE.SampleProperty=clt;var iT={};Object.defineProperty(iT,"__esModule",{value:!0}),iT.IndexFieldSpace=void 0;const p0e=lt,m0e=Xe,xk=yt,flt=Pr,xlt=mu,dlt=Iy,hlt=Ur;class plt extends xlt.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const r of e)r instanceof xk.FieldReference?super.pushFields(r):r instanceof xk.WildcardFieldReference?this.addWild(r):r.logError("invalid-field-in-index-query","Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.logError("refinement-of-index-segment","index query operations cannot be refined"),{type:"index",indexFields:[]};let r=(0,p0e.emptyCompositeFieldUsage)(),i=(0,p0e.emptyNarrowedCompositeFieldResolution)();const s=[],o=this.inputSpace().structDef();for(const[u,a]of this.entries())if(a instanceof flt.SpaceField){let l,c;const f=this.expandedWild[u];if(f)s.push({type:"fieldref",path:f.path}),l=f.entry.typeDesc().compositeFieldUsage;else if(a instanceof dlt.ReferenceField){const h=a.fieldRef,p=h.getField(this.exprSpace);p.error?h.logError(p.error.code,p.error.message):(s.push(h.refToField),l=p.found.typeDesc().compositeFieldUsage,c=h)}const x=this.applyNextCompositeFieldUsage(o,r,i,l,c);r=x.compositeFieldUsage,i=x.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,{type:"index",indexFields:s}}addRefineFromFields(e){}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof hlt.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-found",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries()){if(e.except.has(a)||l.refType==="parameter")continue;const c=xk.IndexFieldReference.indexOutputName([...s,a]);if(this.entry(c)){const f=(r=this.expandedWild[c].path)===null||r===void 0?void 0:r.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${f?` (conflicts with ${f})`:""}`)}else{const f=l.typeDesc();m0e.TD.isLeafAtomic(f)&&(0,m0e.expressionIsScalar)(f.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:c,entry:l}),this.expandedWild[c]={path:s.concat(a),entry:l})}}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.setEntry(a.name,a.entry)}}iT.IndexFieldSpace=plt,Object.defineProperty(rT,"__esModule",{value:!0}),rT.IndexBuilder=void 0;const dk=Xe,mlt=li,glt=Da,ylt=tE,Elt=Mc,Alt=nE,_lt=iT,hk=lt;class vlt{constructor(e,r,i,s){this.filters=[],this.alwaysJoins=[],this.type="index",this.resultFS=new _lt.IndexFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof glt.Filter?e.queryExecute(this):e instanceof Elt.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof ylt.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.logError("index-by-already-specified","Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof Alt.SampleProperty?this.sample=e.sampling():e.logError("illegal-operation-for-index","Not legal in an index query operation")}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}finalize(e){var r;if(e&&!(0,dk.isIndexSegment)(e)&&!(0,dk.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),mlt.ErrorFactory.indexSegment;const i=this.resultFS.getPipeSegment(e),s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?i.filterList=this.filters:s&&(i.filterList=[...s,...this.filters]),e!=null&&e.limit&&(i.limit=e.limit),this.limit&&(i.limit=this.limit.limit),this.indexOn&&(i.weightMeasure=this.indexOn.refString),e&&(0,dk.isIndexSegment)(e)&&(e!=null&&e.sample)&&(i.sample=e.sample),this.sample&&(i.sample=this.sample),this.alwaysJoins.length>0&&(i.alwaysJoins=[...this.alwaysJoins]);const o=e&&e.type==="index"&&(r=e.compositeFieldUsage)!==null&&r!==void 0?r:(0,hk.emptyCompositeFieldUsage)();return i.compositeFieldUsage=(0,hk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage),i}}rT.IndexBuilder=vlt;var sT={},rE={};Object.defineProperty(rE,"__esModule",{value:!0}),rE.GroupBy=void 0;const Clt=Ms,g0e=qn;class Slt extends Clt.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=g0e.LegalRefinementStage.Single,this.forceQueryClass=g0e.QueryClass.Grouping}}rE.GroupBy=Slt;var oT={};Object.defineProperty(oT,"__esModule",{value:!0}),oT.ProjectFieldSpace=void 0;const uT=Xe,blt=mu;class Tlt extends blt.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e===void 0||!uT.TD.isAtomic(e)||(0,uT.expressionIsAggregate)(e.expressionType)?!1:(0,uT.expressionInvolvesAggregate)(e.expressionType)&&(0,uT.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}oT.ProjectFieldSpace=Tlt;var Hc={},od={};Object.defineProperty(od,"__esModule",{value:!0}),od.Ordering=od.OrderBy=void 0;const Rlt=Xe,y0e=Pc,E0e=Je,Dlt=qn;class Olt extends E0e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof y0e.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var r;if(this.field instanceof y0e.FieldName&&e.isQueryFieldSpace()){const s=e.outputSpace(),o=this.field.getField(s);o.error&&this.field.logError(o.error.code,o.error.message),(!o.found||!o.isOutputField)&&this.logError("order-by-not-found-in-output",`Unknown field ${this.field.refString} in output space`),(0,Rlt.expressionIsAnalytic)((r=o.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.logError("order-by-analytic",`Illegal order by of analytic field ${this.field.refString}`)}const i={field:this.modelField};return this.dir&&(i.dir=this.dir),i}}od.OrderBy=Olt;class Flt extends E0e.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Dlt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}}od.Ordering=Flt,Object.defineProperty(Hc,"__esModule",{value:!0}),Hc.ReduceBuilder=Hc.QuerySegmentBuilder=void 0;const gu=Xe,wlt=li,Nlt=Pc,Llt=Mc,Ilt=od,$lt=mu,Blt=Ms,pk=lt;function A0e(t){return t.type==="fieldref"?t.path[t.path.length-1]:t.name}class _0e{constructor(){this.alwaysJoins=[],this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}e instanceof Blt.DefinitionList?this.resultFS.pushFields(...e.list):e instanceof Llt.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof Ilt.Ordering&&(this.order?e.logError("ordering-already-specified","Query operation already sorted"):this.order=e)}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}refineFrom(e,r){var i;e&&e.type!=="index"&&e.type!=="raw"&&(!this.limit&&e.orderBy&&!e.defaultOrderBy&&(r.orderBy=e.orderBy),!this.limit&&e.limit&&(r.limit=e.limit)),this.order&&(r.orderBy=this.order.getOrderBy(this.inputFS),delete r.defaultOrderBy),this.limit&&(r.limit=this.limit);const s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?r.filterList=this.filters:s&&(r.filterList=[...s,...this.filters]),this.alwaysJoins.length>0&&(r.alwaysJoins=[...this.alwaysJoins]);const o=e&&(0,gu.isQuerySegment)(e)&&(i=e.compositeFieldUsage)!==null&&i!==void 0?i:(0,pk.emptyCompositeFieldUsage)();r.compositeFieldUsage=(0,pk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage)}}Hc.QuerySegmentBuilder=_0e;class klt extends _0e{constructor(e,r,i,s){super(),this.type="grouping",this.resultFS=new $lt.ReduceFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,gu.isReduceSegment)(e)||(0,gu.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-reduce-refinement",`Can't refine reduce with ${e.type}`),wlt.ErrorFactory.reduceSegment;const i=this.resultFS.getQuerySegment(r);if(this.refineFrom(r,i),i.orderBy){for(const s of i.orderBy)if(typeof s.field=="number"){const o=i.queryFields[s.field-1];s.field=A0e(o)}}if(i.orderBy===void 0||i.defaultOrderBy){let s;for(const o of i.queryFields){let u=!1,a=!1,l;const c=A0e(o);if(o.type==="fieldref"){const f=o.path.map(h=>new Nlt.FieldName(h)),x=this.inputFS.lookup(f).found;if(x){const h=x.typeDesc();l=h.type,u=(0,gu.expressionIsAggregate)(h.expressionType),a=(0,gu.expressionIsAnalytic)(h.expressionType)}else continue}else l=o.type,u=(0,gu.hasExpression)(o)&&(0,gu.expressionIsAggregate)(o.expressionType),a=(0,gu.hasExpression)(o)&&(0,gu.expressionIsAnalytic)(o.expressionType);if((0,gu.isTemporalType)(l)||u){i.defaultOrderBy=!0,i.orderBy=[{field:c,dir:"desc"}],s=void 0;break}(0,gu.canOrderBy)(l)&&!a&&!s&&(s=c)}s&&(i.defaultOrderBy=!0,i.orderBy=[{field:s,dir:"asc"}])}return i}}Hc.ReduceBuilder=klt,Object.defineProperty(sT,"__esModule",{value:!0}),sT.ProjectBuilder=void 0;const v0e=Xe,Mlt=li,Plt=rE,Ult=oT,jlt=Hc;class qlt extends jlt.QuerySegmentBuilder{constructor(e,r,i,s){super(),this.type="project",this.resultFS=new Ult.ProjectFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Plt.GroupBy?e.logError("illegal-operation-in-select-segment","Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,v0e.isProjectSegment)(e)||(0,v0e.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),Mlt.ErrorFactory.projectSegment;const i=this.resultFS.getQuerySegment(r);return this.refineFrom(r,i),i}}sT.ProjectBuilder=qlt;var aT={};Object.defineProperty(aT,"__esModule",{value:!0}),aT.PartialBuilder=void 0;const Qlt=ji,Hlt=Hc;class zlt extends Hlt.ReduceBuilder{finalize(e){const r=super.finalize(e);if((0,Qlt.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}}aT.PartialBuilder=zlt,Object.defineProperty(eE,"__esModule",{value:!0}),eE.QOpDesc=void 0;const Glt=rT,Wlt=sT,Vlt=Hc,Ylt=Je,Klt=Ps,Jlt=Ur,ud=qn,Xlt=aT;class Zlt extends Ylt.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,i=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=ud.QueryClass.Grouping:this.refineThis.type==="project"?r=ud.QueryClass.Project:this.refineThis.type==="index"&&(r=ud.QueryClass.Index));for(const s of this.list)s.forceQueryClass&&(r?r!==s.forceQueryClass&&s.logError(`illegal-${r}-operation`,`Not legal in ${r} query`):r=s.forceQueryClass),i||(i=(e=s.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&i&&(this.logError("ambiguous-view-type",{}),r=ud.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,i){switch(this.computeType()){case ud.QueryClass.Grouping:return new Vlt.ReduceBuilder(e,this.refineThis,r,i);case ud.QueryClass.Project:return new Wlt.ProjectBuilder(e,this.refineThis,r,i);case ud.QueryClass.Index:return new Glt.IndexBuilder(e,this.refineThis,r,i);case void 0:return new Xlt.PartialBuilder(e,this.refineThis,r,i)}}getOp(e,r){const i=this.getBuilder(e,r,this);for(const o of this.list)i.execute(o);const s=i.finalize(this.refineThis);return{segment:s,outputSpace:()=>new Jlt.StaticSourceSpace((0,Klt.opOutputStruct)(this,e.structDef(),s))}}}eE.QOpDesc=Zlt,Object.defineProperty(nT,"__esModule",{value:!0}),nT.QOpDescView=void 0;const e0t=Xe,t0t=Ur,C0e=eE,n0t=Ps,mk=qn,r0t=Qc;class i0t extends r0t.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){const i=this.operation.getOp(e,r);return{pipeline:[i.segment],outputStruct:i.outputSpace().structDef()}}getOp(e,r,i,s){return(0,e0t.isRawSegment)(s)?(this.logError("refinement-of-raw-query","A raw query cannot be refined"),s):(i.refineFrom(s),i.getOp(e,r).segment)}refine(e,r,i){const s=[...r];if(s.length===0)return s;if(s.length===1)return this.operation.refineFrom(s[0]),[this.getOp(e,i,this.operation,s[0])];const o=new C0e.QOpDesc([]),u=new C0e.QOpDesc([]);for(const a of this.operation.list)switch(a.queryRefinementStage){case mk.LegalRefinementStage.Head:o.push(a);break;case mk.LegalRefinementStage.Single:a.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case mk.LegalRefinementStage.Tail:u.push(a);break;default:a.logError("illegal-refinement-operation","Illegal query refinement")}if(o.notEmpty()&&(this.has({headRefinements:o}),s[0]=this.getOp(e,void 0,o,s[0])),u.notEmpty()){const a=s.length-1;this.has({tailRefinements:u});const l=(0,n0t.getFinalStruct)(this,e.structDef(),s.slice(-1));s[a]=this.getOp(new t0t.StaticSourceSpace(l),void 0,u,s[a])}return s}getImplicitName(){}}nT.QOpDescView=i0t;var Dn={},s0t=T&&T.__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]}),o0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),u0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&s0t(e,t,r);return o0t(e,t),e};Object.defineProperty(Dn,"__esModule",{value:!0}),Dn.FieldDefinitionValue=Dn.DefSpace=Dn.DimensionFieldDeclaration=Dn.MeasureFieldDeclaration=Dn.DeclareFieldDeclaration=Dn.ProjectFieldDeclaration=Dn.GroupByFieldDeclaration=Dn.AggregateFieldDeclaration=Dn.CalculateFieldDeclaration=Dn.AtomicFieldDeclaration=void 0;const gk=Xe,S0e=u0t(Zt),a0t=l2,l0t=Je,ad=sr,c0t=Mr,f0t=Pr;class zc extends l0t.MalloyElement{constructor(e,r,i){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=i,this.isNoteableObj=!0,this.extendNote=c0t.extendNoteMethod}getName(){return this.defineName}fieldDef(e,r){return this.queryFieldDef(new yk(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let i;function s(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const u=this.executesInOutputSpace()?s():e;i=this.expr.getExpression(u)}catch(u){return this.logError("failed-field-definition",`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}if(i.type==="null"&&(this.expr.logWarning("null-typed-field-definition",'null value defaults to type number, use "null::TYPE" to specify correct type'),i={type:"number",value:i.value,expressionType:i.expressionType,evalSpace:i.evalSpace,compositeFieldUsage:i.compositeFieldUsage}),(0,gk.isAtomicFieldType)(i.type)&&i.type!=="error"){this.typecheckExprValue(i);const u=(0,gk.mkFieldDef)(S0e.atomicDef(i),r);return(u.type==="date"||u.type==="timestamp")&&(0,a0t.isGranularResult)(i)&&(u.timeframe=i.timeframe),u.location=this.location,u.e=i.value,u.compositeFieldUsage=i.compositeFieldUsage,i.expressionType&&(u.expressionType=i.expressionType),this.exprSrc&&(u.code=this.exprSrc),this.note&&(u.annotation=this.note),u}if(!(e instanceof yk&&e.foundCircle)&&i.type!=="error"){const u=S0e.inspect(i);this.logError("invalid-type-for-field-definition",`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new b0e(e,this))}}Dn.AtomicFieldDeclaration=zc;class x0t extends zc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}Dn.CalculateFieldDeclaration=x0t;class d0t extends zc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckAggregate)(e,this)}}Dn.AggregateFieldDeclaration=d0t;class h0t extends zc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckGroupBy)(e,this)}}Dn.GroupByFieldDeclaration=h0t;class p0t extends zc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckProject)(e,this)}}Dn.ProjectFieldDeclaration=p0t;class m0t extends zc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckDeclare)(e,this)}}Dn.DeclareFieldDeclaration=m0t;class g0t extends zc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckMeasure)(e,this)}}Dn.MeasureFieldDeclaration=g0t;class y0t extends zc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckDimension)(e,this)}}Dn.DimensionFieldDeclaration=y0t;class yk{constructor(e,r){this.realFS=e,this.circular=r,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:{message:`Circular reference to '${this.circular.defineName}' in definition`,code:"circular-reference-in-field-definition"},found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectName(){return this.realFS.dialectName()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}isProtectedAccessSpace(){return!0}}Dn.DefSpace=yk;class b0e extends f0t.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){var e;const r=(e=this.defInSource)!==null&&e!==void 0?e:this.exprDef.fieldDef(this.space,this.name);return this.defInSource=r,r}getQueryFieldDef(e){if(!this.defInQuery){const r=this.exprDef.queryFieldDef(e,this.name);this.defInQuery=r}return this.defInQuery}typeDesc(){const e=this.defInQuery||this.fieldDef();if((0,gk.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}entryType(){return(this.defInQuery||this.fieldDef()).type}}Dn.FieldDefinitionValue=b0e;var lT={};Object.defineProperty(lT,"__esModule",{value:!0}),lT.Aggregate=void 0;const E0t=Ms,T0e=qn;class A0t extends E0t.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=T0e.LegalRefinementStage.Single,this.forceQueryClass=T0e.QueryClass.Grouping}}lT.Aggregate=A0t;var cT={};Object.defineProperty(cT,"__esModule",{value:!0}),cT.Calculate=void 0;const _0t=Ms,v0t=qn;class C0t extends _0t.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=v0t.LegalRefinementStage.Single}}cT.Calculate=C0t;var iE={};Object.defineProperty(iE,"__esModule",{value:!0}),iE.Dimensions=void 0;const S0t=wc;class b0t extends S0t.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}iE.Dimensions=b0t;var sE={};Object.defineProperty(sE,"__esModule",{value:!0}),sE.Measures=void 0;const T0t=wc;class R0t extends T0t.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}sE.Measures=R0t;var fT={};Object.defineProperty(fT,"__esModule",{value:!0}),fT.Nests=void 0;const D0t=Ms,R0e=qn;class O0t extends D0t.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=R0e.LegalRefinementStage.Single,this.forceQueryClass=R0e.QueryClass.Grouping}}fT.Nests=O0t;var xT={};Object.defineProperty(xT,"__esModule",{value:!0}),xT.ProjectStatement=void 0;const F0t=Ms,D0e=qn;class w0t extends F0t.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=D0e.QueryClass.Project,this.queryRefinementStage=D0e.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}xT.ProjectStatement=w0t;var Gc={},Zl={},Bn={};Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.getPlainString=Bn.unIndent=Bn.getOptionalId=Bn.idToStr=Bn.getId=Bn.getStringParts=Bn.getStringIfShort=Bn.getShortString=void 0;const O0e=Zo;function F0e(t){var e,r;const i=((e=t.DQ_STRING())===null||e===void 0?void 0:e.text)||((r=t.SQ_STRING())===null||r===void 0?void 0:r.text);return i?O0e.ParseUtil.parseString(i,i[0]):""}Bn.getShortString=F0e;function w0e(t){const e=t.string().shortString();if(e)return F0e(e)}Bn.getStringIfShort=w0e;function*N0e(t){var e;if(t){for(const i of t.sqlInterpolation()){const s=i.OPEN_CODE().text;s.length>2&&(yield s.slice(0,s.length-2)),i.sqExpr()&&(yield i.sqExpr())}const r=(e=t.SQL_END())===null||e===void 0?void 0:e.text.slice(0,-3);r&&r.length>0&&(yield r)}}Bn.getStringParts=N0e;function L0e(t){return I0e(t.id())}Bn.getId=L0e;function I0e(t){const e=t.BQ_STRING();return e?O0e.ParseUtil.parseString(e.text,"`"):t.text}Bn.idToStr=I0e;function N0t(t){function e(r){return"id"in r}if(e(t)&&t.id())return L0e(t)}Bn.getOptionalId=N0t;function*$0e(t){for(;t.length>0;){const e=t.match(/^.*?\r?\n/);let r=t;e&&(r=e[0]),yield r,t=t.slice(r.length)}}function L0t(t){let e;for(const r of $0e(t)){const i=r.match(/^( *).*[^\s]/);if(i){const s=i[1].length;(e===void 0||s<e)&&(e=s)}}return e}function B0e(t){let e;for(const r of t)if(typeof r=="string"){const i=L0t(r);i!==void 0&&(e===void 0||i<e)&&(e=i)}if(e)for(let r=0;r<=t.length;r+=1){const i=t[r];if(typeof i=="string"){let s="";for(let o of $0e(i))o[0]===" "&&(o=o.slice(e)),s+=o;t[r]=s}}}Bn.unIndent=B0e;function I0t(t,e=!1){const r=[],i=w0e(t);if(i)return[i,r];const s=[],o=t.string().sqlString();if(o){for(const u of N0e(o))if(typeof u=="string")s.push(u);else if(r.push(u),e)return[void 0,r];return B0e(s),[s.join(""),r]}return["",r]}Bn.getPlainString=I0t,Object.defineProperty(Zl,"__esModule",{value:!0}),Zl.findReferences=Zl.deprecatedParseTableURI=Zl.constructTableKey=void 0;const $0t=ac,Ek=Bn;function Ak(t){const e=(0,Ek.getStringIfShort)(t);if(e)return e;const r=[],i=t.string().sqlString();if(i){for(const s of(0,Ek.getStringParts)(i))typeof s=="string"&&r.push(s);return r.join("")}return""}class B0t{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,i){const s=k0e(e,r);this.needTables[s]||(this.needTables[s]={connectionName:e,tablePath:r,firstReference:i})}enterTableMethod(e){const r=(0,Ek.getId)(e.connectionId()),i=Ak(e.tablePath()),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterTableFunction(e){const r=Ak(e.tableURI()),{connectionName:i,tablePath:s}=M0e(r),o=this.trans.rangeFromContext(e);this.registerTableReference(i,s,o)}enterImportURL(e){const r=Ak(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}}function k0e(t,e){return t===void 0?e:`${t}:${e}`}Zl.constructTableKey=k0e;function M0e(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,r,i]=e;return{connectionName:r,tablePath:i}}else return{tablePath:t}}Zl.deprecatedParseTableURI=M0e;function k0t(t,e,r){const i=new B0t(t,e),s=i;return $0t.ParseTreeWalker.DEFAULT.walk(s,r),{tables:i.needTables,urls:i.needImports}}Zl.findReferences=k0t,Object.defineProperty(Gc,"__esModule",{value:!0}),Gc.TableFunctionSource=Gc.TableMethodSource=Gc.TableSource=void 0;const P0e=Zl,M0t=Eo,U0e=li;class _k extends M0t.Source{getSourceDef(){var e,r,i;const s=this.getTableInfo();if(s===void 0)return U0e.ErrorFactory.structDef;const{tablePath:o,connectionName:u}=s,a=(0,P0e.constructTableKey)(u,o),l=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(a);let c=`Schema read failure for table '${o}' for connection '${u}'`;if(l){if(l.status==="present"){(r=this.document())===null||r===void 0||r.checkExperimentalDialect(this,l.value.dialect),l.value.location=this.location,l.value.fields.forEach(x=>{x.location=this.location});const f={...l.value,fields:l.value.fields.map(x=>({...x,location:this.location})),location:this.location};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(f),f}l.status==="error"&&(c=l.message)}return this.logError("failed-to-fetch-table-schema",c),U0e.ErrorFactory.structDef}}Gc.TableSource=_k;class P0t extends _k{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.logError("invalid-connection-for-table-source",`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}Gc.TableMethodSource=P0t;class U0t extends _k{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,P0e.deprecatedParseTableURI)(this.tableURI)}}Gc.TableFunctionSource=U0t;var dT={};Object.defineProperty(dT,"__esModule",{value:!0}),dT.SQLString=void 0;const j0t=Je,j0e=hu;class q0t extends j0t.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(Q0t)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof j0e.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.logError("invalid-sql-source-interpolation","This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const r of this.elements)if(typeof r=="string")e.push({sql:r});else{const i=r.getQuery();i?e.push(i.query()):r.sqLog("failed-to-expand-sql-source","Cannot expand into a query")}return e}}dT.SQLString=q0t;function Q0t(t){return t instanceof j0e.SourceQueryElement}var hT={};Object.defineProperty(hT,"__esModule",{value:!0}),hT.SourceDesc=void 0;const H0t=Je;class z0t extends H0t.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}hT.SourceDesc=z0t;var pT={};Object.defineProperty(pT,"__esModule",{value:!0}),pT.isSourceProperty=void 0;const G0t=Da,W0t=wc,V0t=n2,Y0t=Lc,K0t=r2,J0t=i2,X0t=s2,Z0t=Nc,ect=hs;function tct(t){return t instanceof G0t.Filter||t instanceof ect.JoinStatement||t instanceof W0t.DeclareFields||t instanceof V0t.FieldListEdit||t instanceof Y0t.Renames||t instanceof K0t.PrimaryKey||t instanceof Z0t.ObjectAnnotation||t instanceof J0t.Views||t instanceof X0t.TimezoneStatement}pT.isSourceProperty=tct;var mT={};Object.defineProperty(mT,"__esModule",{value:!0}),mT.isFieldCollectionMember=void 0;const nct=Dn,q0e=yt;function rct(t){return t instanceof q0e.FieldReference||t instanceof q0e.WildcardFieldReference||t instanceof nct.AtomicFieldDeclaration}mT.isFieldCollectionMember=rct;var gT={};Object.defineProperty(gT,"__esModule",{value:!0}),gT.isQueryElement=void 0;const ict=o2,sct=u2,oct=jy,uct=qy;function act(t){return t instanceof ict.QueryArrow||t instanceof sct.QueryRefine||t instanceof oct.QueryReference||t instanceof uct.QueryRaw}gT.isQueryElement=act;var Q0e={};Object.defineProperty(Q0e,"__esModule",{value:!0});var yT={};Object.defineProperty(yT,"__esModule",{value:!0}),yT.isQueryProperty=void 0;function lct(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}yT.isQueryProperty=lct;var ET={};Object.defineProperty(ET,"__esModule",{value:!0}),ET.isQueryExtendProperty=void 0;const cct=iE,fct=hs,xct=sE;function dct(t){return t instanceof cct.Dimensions||t instanceof xct.Measures||t instanceof fct.JoinStatement}ET.isQueryExtendProperty=dct;var AT={};Object.defineProperty(AT,"__esModule",{value:!0}),AT.isFieldPropStatement=void 0;const hct=kc,pct=Da,mct=Mc,gct=h2;function yct(t){return t instanceof pct.Filter||t instanceof mct.Limit||t instanceof gct.PartitionBy||t instanceof hct.FunctionOrdering}AT.isFieldPropStatement=yct,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__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(Ty,t),r(Jp,t),r(Xp,t),r(Eo,t),r(Oy,t),r(hu,t),r(eb,t),r(tb,t),r(ib,t),r(By,t),r(sb,t),r(ob,t),r(du,t),r(n2,t),r(r2,t),r(Lc,t),r(i2,t),r(s2,t),r(ab,t),r(f2,t),r(cb,t),r(kc,t),r(fb,t),r(Jl,t),r(xb,t),r(d2,t),r(db,t),r(hb,t),r(pb,t),r(Kl,t),r(mb,t),r(gb,t),r(Eb,t),r(Vy,t),r(Gy,t),r(nd,t),r(_b,t),r(vb,t),r(Sb,t),r(Tb,t),r(Rb,t),r(Db,t),r(Ob,t),r(Uc,t),r(wb,t),r(Nb,t),r(Lb,t),r($b,t),r(Bb,t),r(kb,t),r(Mb,t),r(Ub,t),r(Qb,t),r(Sr,t),r(Gb,t),r(h2,t),r(m2,t),r(y2,t),r(Vb,t),r(sd,t),r(Bc,t),r(Yb,t),r(Yy,t),r(qc,t),r(Xy,t),r(Kb,t),r(Jb,t),r(Xb,t),r(u2,t),r(o2,t),r(Qc,t),r(Zb,t),r(eT,t),r(tT,t),r(nT,t),r(Dn,t),r(yt,t),r(lT,t),r(cT,t),r(wc,t),r(iE,t),r(Xy,t),r(Da,t),r(rE,t),r(tE,t),r(hs,t),r(Ry,t),r(Mc,t),r(sE,t),r(Ty,t),r(fT,t),r(od,t),r(xT,t),r(eE,t),r(nE,t),r(a2,t),r(td,t),r(Qy,t),r(Gc,t),r(dT,t),r(Nc,t),r(pu,t),r(hT,t),r(pT,t),r(xt,t),r(mT,t),r(Pc,t),r(Je,t),r(gT,t),r(Q0e,t),r(yT,t),r(ET,t),r(AT,t)}(W4);var _T={},A2={};Object.defineProperty(A2,"__esModule",{value:!0}),A2.ConstantExpression=A2.ConstantFieldSpace=void 0;const Ect=xt;class H0e{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:{message:"Only constants allowed in parameter default values",code:"illegal-reference-in-parameter-default"},found:void 0}}entries(){return[]}entry(){}dialectName(){return"~constant-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}A2.ConstantFieldSpace=H0e;class Act extends Ect.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new H0e),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}apply(e,r,i){return this.expr.apply(e,r,i)}requestExpression(e){return this.expr.requestExpression(e)}}A2.ConstantExpression=Act;var _ct=T&&T.__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]}),vct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Cct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&_ct(e,t,r);return vct(e,t),e};Object.defineProperty(_T,"__esModule",{value:!0}),_T.MalloyToAST=void 0;const z0e=hy,Sct=Jh,re=Cct(W4),vk=Vp,G0e=Er,bct=W4,Yn=Bn,Ck=Xe,Tct=Zo,Rct=A2,W0e=Vn;class V0e extends re.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class Sk extends re.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const Dct=["##! m4warnings=error"];class Oct extends Sct.AbstractParseTreeVisitor{constructor(e,r,i){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=i;for(const s of Dct){const o=Tct.Tag.fromTagLine(s,0,this.compilerFlags);this.compilerFlags=o.tag}}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}astError(e,r,i,s){this.msgLog.log((0,vk.makeLogMessage)(r,i,{at:e.location,...s}))}rangeFromContext(e){return(0,W0e.rangeFromContext)(this.parseInfo.sourceInfo,e)}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new G0e.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,r,i,s){this.msgLog.log((0,vk.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}warnWithReplacement(e,r,i,s){this.msgLog.log((0,vk.makeLogMessage)(e,r,{at:{url:this.parseInfo.sourceURL,range:i},severity:"warn",replacement:s}))}inExperiment(e,r){const i=this.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(this.contextError(r,"experiment-not-enabled",{experimentId:e}),!1)}m4Severity(){const e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,r,i){const s=this.m4Severity();s&&this.contextError(e,r,i,{severity:s})}only(e,r,i){const s=[];for(const o of e){const u=r(o);u?s.push(u):o instanceof Sk||this.astError(o,"unexpected-statement-in-translation",`Parser enountered unexpected statement type '${o.elementType}' when it needed '${i}'`)}return s}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new re.FieldName((0,Yn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new re.ModelEntryReference((0,Yn.getId)(e)),e.id())}defaultResult(){return new re.Unimplemented}astAt(e,r){return e.location={url:this.parseInfo.sourceURL,range:this.rangeFromContext(r)},e}getSourceCode(e){const r=e.start.startIndex,i=e.stop||e.start,s=new G0e.Interval(r,i.stopIndex);return this.parseInfo.sourceStream.getText(s)}getFilterElement(e){const r=this.getFieldExpr(e),i=new re.FilterElement(r,this.getSourceCode(e));return this.astAt(i,e)}getFieldDefs(e,r){return e.map(i=>this.getFieldDef(i,r))}getFieldExpr(e){const r=this.visit(e);if(r instanceof re.ExpressionDef)return this.astAt(r,e);throw this.internalError(e,`expression node unknown type '${r.elementType}'`)}getPlainStringFrom(e){const[r,i]=(0,Yn.getPlainString)(e);for(const s of i)s instanceof z0e.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return r||""}makeSqlString(e,r){for(const i of e.sqlInterpolation())i.CLOSE_CODE()&&this.m4advisory(i,"percent-terminated-query-interpolation","Use %{ ... } instead of %{ ... }%");for(const i of(0,Yn.getStringParts)(e))i instanceof z0e.ParserRuleContext?r.push(this.visit(i)):r.push(i);r.complete(),this.astAt(r,e)}parseTime(e,r){let i=r(e.text);return i||(this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),i=new re.LiteralTimestamp({text:e.text})),this.astAt(i,e)}getNotes(e){return e.ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const r=this.only(e.malloyStatement().map(i=>this.visit(i)),i=>re.isDocStatementOrDocStatementList(i)&&i,"statement");return new re.Document(r)}visitDefineSourceStatement(e){const i=e.sourcePropertyList().sourceDefinition().map(u=>this.visitSourceDefinition(u)),s=this.getNotes(e.tags()),o=new re.DefineSourceList(i);return o.extendNote({blockNotes:s}),o}getSourceParameter(e){const r=e.fieldExpr(),i=r?this.astAt(new Rct.ConstantExpression(this.getFieldExpr(r)),r):void 0,s=e.malloyType(),o=s?this.getMalloyType(s):void 0;return this.astAt(new re.HasParameter({name:(0,Yn.getId)(e.parameterNameDef()),type:o,default:i}),e)}getSourceParameters(e){return e===void 0?[]:(this.inExperiment("parameters",e),e.sourceParameter().map(r=>this.getSourceParameter(r)))}visitSourceDefinition(e){const r=this.visit(e.sqExplore()),i=this.getSourceParameters(e.sourceParameters()),s=new re.DefineSource((0,Yn.getId)(e.sourceNameDef()),r instanceof re.SourceQueryElement?r:void 0,!0,i),o=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return s.extendNote({notes:o}),this.astAt(s,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>re.isSourceProperty(s)&&s,"source property");return new re.SourceDesc(r)}visitTableFunction(e){const r=this.getPlainStringFrom(e.tableURI()),i=this.astAt(new re.TableFunctionSource(r),e);return this.m4advisory(e,"table-function","`table('connection_name:table_path')` is deprecated; use `connection_name.table('table_path')`"),i}visitTableMethod(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=this.getPlainStringFrom(e.tablePath());return this.astAt(new re.TableMethodSource(i,s),e)}visitSqlSource(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=new re.SQLString,o=e.sqlString();o&&this.makeSqlString(o,s);const u=e.shortString();u&&s.push((0,Yn.getShortString)(u));const a=new re.SQLSource(i,s);return this.astAt(a,e)}visitDefJoinMany(e){const r=this.getAccessLabel(e.accessLabel()),i=[];for(const o of e.joinList().joinDef()){const u=this.visit(o);u instanceof re.Join&&(i.push(u),u instanceof re.ExpressionJoin?(u.joinType="many",u.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):u instanceof re.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const s=new re.JoinStatement(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),s}visitDefJoinOne(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof re.Join&&(s.push(u),u instanceof re.ExpressionJoin&&(u.joinType="one"));const o=new re.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}visitDefJoinCross(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof re.Join&&(s.push(u),u instanceof re.ExpressionJoin?u.joinType="cross":u.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const o=new re.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}getJoinList(e){return this.only(e.joinDef().map(r=>this.visit(r)),r=>r instanceof re.Join&&r,"join")}getJoinFrom(e){const r=e.isExplore(),i=this.getModelEntryName(e.joinNameDef());if(r){const o=this.getSqExpr(r.sqExpr()),u=this.getNotes(r._before_is).concat(this.getNotes(r._after_is));return{joinFrom:o,notes:u,joinAs:i}}const s=e.sourceArguments();return s?{joinFrom:this.astAt(new re.SQReference(i,this.getSQArguments(s)),e),notes:[],joinAs:i}:{joinAs:i,joinFrom:new re.SQReference(i),notes:[]}}visitQueryJoinStatement(e){return this.astAt(this.visit(e.joinStatement()),e)}visitJoinOn(e){var r;const{joinAs:i,joinFrom:s,notes:o}=this.getJoinFrom(e.joinFrom()),u=new re.ExpressionJoin(i,s),a=e.joinExpression(),l=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,Ck.isMatrixOperation)(l)?u.matrixOperation=l:this.contextError(e,"unknown-matrix-operation","Internal Error: Unknown matrixOperation"),a&&(u.joinOn=this.getFieldExpr(a)),u.extendNote({notes:this.getNotes(e).concat(o)}),this.astAt(u,e)}visitJoinWith(e){const{joinAs:r,joinFrom:i,notes:s}=this.getJoinFrom(e.joinFrom()),o=this.getFieldExpr(e.fieldExpr()),u=new re.KeyJoin(r,i,o);return u.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(u,e)}getFieldDef(e,r){const i=e.fieldExpr(),s=(0,Yn.getId)(e.fieldNameDef()),o=this.getFieldExpr(i),u=new r(o,s,this.getSourceCode(i)),a=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return u.extendNote({notes:a}),this.astAt(u,e)}visitDefDimensions(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),re.DimensionFieldDeclaration),s=new re.Dimensions(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}getAccessLabel(e){if(e!==void 0){if(e.INTERNAL_KW())return"internal";if(e.PRIVATE_KW())return"private";if(e.PUBLIC_KW())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}getAccessLabelProp(e){if(e!==void 0){if(e.INTERNAL())return"internal";if(e.PRIVATE())return"private";if(e.PUBLIC())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}visitDefMeasures(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),re.MeasureFieldDeclaration),s=new re.Measures(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}visitQueryExtend(e){const r=[],i=e.queryExtendStatementList().queryExtendStatement().map(o=>this.visit(o));for(const o of i)if(re.isQueryExtendProperty(o))r.push(o);else throw this.internalError(e,`Query extend matched, but ${o.elementType} found`);const s=new re.ExtendBlock(r);return this.astAt(s,e)}visitDeclareStatement(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),re.DeclareFieldDeclaration),s=new re.DeclareFields(i,r),o=this.astAt(s,e);return this.m4advisory(e,"declare","`declare:` is deprecated; use `dimension:` or `measure:` inside a source or `extend:` block"),o}visitExploreRenameDef(e){const r=e.fieldName(0),i=e.fieldName(1),s=new re.RenameField((0,Yn.getId)(r),this.getFieldName(i));return this.astAt(s,e)}visitDefExploreRename(e){const r=this.getAccessLabel(e.accessLabel()),s=e.renameList().exploreRenameDef().map(u=>this.visitExploreRenameDef(u)),o=new re.Renames(s,r);return this.astAt(o,e)}visitFilterClauseList(e){return new re.Filter(e.fieldExpr().map(r=>this.getFilterElement(r)))}visitWhereStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!1,this.astAt(r,e)}visitHavingStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!0,this.astAt(r,e)}visitDefExploreQuery(e){const r=this.getAccessLabel(e.accessLabel()),i=e.subQueryDefList().exploreQueryDef().map(u=>this.visitExploreQueryDef(u)),s=new re.Views(i,r),o=this.getNotes(e.tags());return s.extendNote({blockNotes:o}),e.QUERY()&&this.m4advisory(e,"query-in-source","Use view: inside of a source instead of query:"),s}visitDefExplorePrimaryKey(e){const r=new re.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}getFieldNameList(e,r){const i=e.fieldName().map(s=>this.astAt(new r([this.getFieldName(s)]),s));return new re.FieldReferences(i)}visitDefExploreEditField(e){const r=e.ACCEPT()?"accept":"except";return new re.FieldListEdit(r,this.getFieldNameList(e.fieldNameList(),re.AcceptExceptFieldReference))}visitSQInclude(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new re.SQExtend(r,new re.SourceDesc([]),s);return this.astAt(o,e)}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const r=this.getPlainStringFrom(e),i=this.astAt(new re.TimezoneStatement(r),e.string());return i.isValid||this.astError(i,"invalid-timezone",{timezone:i.tz}),this.astAt(i,e)}visitQueryProperties(e){const r=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>re.isQueryProperty(i)&&i,"query statement");return new re.QOpDesc(r)}getFieldPath(e,r){const i=e.fieldName().map(s=>this.getFieldName(s));return this.astAt(new r(i),e)}getQueryFieldDef(e,r){const i=this.getFieldDef(e,r);return this.astAt(i,e)}getQueryFieldEntry(e,r,i){const s=e.taggedRef();if(s)return this.getTaggedRef(s,r,i);const o=e.fieldDef();if(o)return this.getQueryFieldDef(o,r);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,r,i){return this.only(e.queryFieldEntry().map(s=>this.getQueryFieldEntry(s,r,i)),s=>s instanceof re.FieldReference||s instanceof re.AtomicFieldDeclaration?s:!1,"view field")}visitAggregateStatement(e){const r=new re.Aggregate(this.getQueryItems(e.queryFieldList(),re.AggregateFieldDeclaration,re.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){const r=new re.GroupBy(this.getQueryItems(e.queryFieldList(),re.GroupByFieldDeclaration,re.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){const r=new re.Calculate(this.getQueryItems(e.queryFieldList(),re.CalculateFieldDeclaration,re.CalculateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}getTaggedRef(e,r,i){const s=e.refExpr();if(s){const u=this.getFieldPath(e.fieldPath(),re.ExpressionFieldReference);let a;const l=s.timeframe();l&&(a=new re.ExprGranularTime(new re.ExprIdReference(u),this.visitTimeframe(l).text,!0));const c=s.aggregate();if(c){const x=c.text.toLowerCase();if(x==="sum")a=new re.ExprSum(void 0,u);else return this.contextError(c,"invalid-reference-only-aggregation",`\`${x}\` is not legal in a reference-only aggregation`),u}const f=new r(a,u.outputName);return f.extendNote({notes:this.getNotes(e.tags())}),f}const o=this.getFieldPath(e.fieldPath(),i);return o.extendNote({notes:this.getNotes(e.tags())}),o}getFieldCollectionMember(e,r,i){const s=e.fieldDef();if(s)return this.getFieldDef(s,r);const o=e.taggedRef();if(o)return this.getTaggedRef(o,r,i);const u=e.collectionWildCard();if(u)return this.visitCollectionWildCard(u);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const r=e.collectionMember().map(i=>this.getFieldCollectionMember(i,re.ProjectFieldDeclaration,re.ProjectFieldReference));return this.astAt(new re.ProjectStatement(r),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project","project: keyword is deprecated, use select:");const r=this.visitFieldCollection(e.fieldCollection());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCollectionWildCard(e){var r;const i=e.fieldPath(),s=i?this.getFieldPath(i,re.ProjectFieldReference):void 0,o=this.astAt(new re.WildcardFieldReference(s),e),u=((r=e.starQualified())===null||r===void 0?void 0:r.fieldNameList())||[];for(const a of u)for(const l of a.fieldName())o.except.add((0,Yn.getId)(l));return o}visitIndexFields(e){const r=e.indexElement().map(i=>{const s=i.fieldPath();if(!s)return this.astAt(new re.WildcardFieldReference(void 0),e);const o=this.getFieldPath(s,re.IndexFieldReference);return i.STAR()?this.astAt(new re.WildcardFieldReference(o),e):this.astAt(o,e)});return new re.FieldReferences(r)}visitIndexStatement(e){const r=this.visitIndexFields(e.indexFields()),i=new re.Index(r),s=e.fieldName();return s&&i.useWeight(this.getFieldName(s)),this.astAt(i,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new re.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.fieldExpr(),s=i?this.getFieldExpr(i):void 0;return this.astAt(new re.FunctionOrderBy(s,r),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const r=e.aggregateOrderBySpec().map(i=>this.visitAggregateOrderBySpec(i));return this.astAt(new re.FunctionOrdering(r),e)}visitOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.INTEGER_LITERAL();if(i)return new re.OrderBy(this.getNumber(i),r);const s=e.fieldName();if(s)return new re.OrderBy(this.getFieldName(s),r);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const r=e.orderBySpec().map(i=>this.visitOrderBySpec(i));return this.astAt(new re.Ordering(r),e)}visitTopStatement(e){const r=this.getNumber(e.INTEGER_LITERAL());return this.astAt(new re.Limit(r),e)}visitTopLevelQueryDefs(e){const r=e.topLevelQueryDef().map(o=>this.visitTopLevelQueryDef(o)),i=this.getNotes(e.tags()),s=new re.DefineQueryList(r);return s.extendNote({blockNotes:i}),s}visitTopLevelQueryDef(e){const r=(0,Yn.getId)(e.queryName()),i=this.visit(e.sqExpr()),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(i instanceof re.SourceQueryElement){const o=new re.DefineQuery(r,i);return o.extendNote({notes:s}),this.astAt(o,e)}throw this.internalError(e,`Expected query definition, got a '${i.elementType}'`)}visitAnonymousQuery(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new re.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.m4advisory(r,"anonymous-query","Anonymous `query:` statements are deprecated, use `run:` instead"),this.astAt(s,e)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new re.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.astAt(s,e)}visitNestStatement(e){const r=this.visitNestedQueryList(e.nestedQueryList());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitNestedQueryList(e){return new re.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof re.NestFieldDeclaration&&r,"query"))}visitNestDef(e){const r=e.queryName();let i;const s=this.getVExpr(e.vExpr());if(r)i=(0,Yn.getId)(r);else{const a=s.getImplicitName();a===void 0&&this.contextError(e,"anonymous-nest","`nest:` view requires a name (add `nest_name is ...`)"),i=a??"__unnamed__"}const o=new re.NestFieldDeclaration(i,s),u=e.isDefine();return o.extendNote({notes:this.getNotes(e.tags()).concat(u?this.getIsNotes(u):[])}),this.astAt(o,e)}visitExploreQueryDef(e){const r=(0,Yn.getId)(e.exploreQueryNameDef()),i=new re.ViewFieldDeclaration(r,this.getVExpr(e.vExpr())),s=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,e)}visitExprNot(e){return new re.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new re.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(r=>this.getFieldExpr(r))}visitExprLogicalOr(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new re.ExprLogicalOp(r,"or",i)}visitExprLogicalAnd(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new re.ExprLogicalOp(r,"and",i)}visitExprOrTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new re.ExprAlternationTree(r,"|",i),e)}visitExprAndTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new re.ExprAlternationTree(r,"&",i),e)}visitExprCoalesce(e){const r=this.getFieldExpr(e.fieldExpr()[0]),i=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new re.ExprCoalesce(r,i),e)}visitPartialCompare(e){const r=e.compareOp().text;if(re.isComparison(r))return this.astAt(new re.PartialCompare(r,this.getFieldExpr(e.fieldExpr())),e);throw this.internalError(e,`partial comparison '${r}' not recognized`)}visitPartialTest(e){const r=e.partialCompare();return r?this.visitPartialCompare(r):this.astAt(new re.PartialIsNull(e.NOT()?"!=":"="),e)}visitPartialAllowedFieldExpr(e){const r=e.fieldExpr();if(r)return this.getFieldExpr(r);const i=e.partialTest();if(i)return this.visitPartialTest(i);throw this.internalError(e,"impossible partial")}visitExprString(e){const r=this.getPlainStringFrom(e);return new re.ExprString(r)}visitRawString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
|
|
1160
|
+
`)),Hy.ErrorFactory.structDef}else if(o.status==="present"){const u=this.select.location,a={...o.value,fields:o.value.fields.map(f=>({...f,location:u})),location:this.location},l=this.document(),c=l==null?void 0:l.currentModelAnnotation();return c&&(a.modelAnnotation=c),a}else return this.logError("non-top-level-sql-source","`connection_name.sql(...)` can currently only be used in top level source/query definitions"),Hy.ErrorFactory.structDef}}Qy.SQLSource=Yrt,Object.defineProperty(ib,"__esModule",{value:!0}),ib.SQSource=void 0;const Krt=hu,Jrt=qy,Xrt=Qy;class Zrt extends Krt.SourceQueryElement{constructor(e){super({theSource:e}),this.theSource=e,this.elementType="sq-source"}isSource(){return!0}getSource(){return this.theSource}getQuery(){if(this.theSource instanceof Xrt.SQLSource){const e=new Jrt.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}ib.SQSource=Zrt;var sb={};Object.defineProperty(sb,"__esModule",{value:!0}),sb.SQExtend=void 0;const eit=Oy,tit=hu;class nit extends tit.SourceQueryElement{constructor(e,r,i){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.includeList=i,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new eit.RefinedSource(e,this.extend,this.includeList),this.has({asSource:this.asSource}),this.asSource;this.sqLog("failed-to-compute-source-to-extend","Could not compute source to extend")}isSource(){return!0}}sb.SQExtend=nit;var ob={},ub={};Object.defineProperty(ub,"__esModule",{value:!0}),ub.CompositeSource=void 0;const rit=Xe,iit=Eo;class sit extends iit.Source{constructor(e){super({sources:e}),this.sources=e,this.elementType="compositeSource"}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){const i=this.sources.map(c=>c.withParameters(e,r)),s=i[0].connection,o=i[0].dialect,u="composite_source",a=[],l=new Map;return this.sources.forEach((c,f)=>{var x;const h=i[f];h.connection!==s&&c.logError("composite-source-connection-mismatch",`All sources in a composite source must share the same connection; connection \`${h.connection}\` differs from previous connection \`${s}\``);for(const p of h.fields){if(!(0,rit.isAtomic)(p)){c.logWarning("composite-source-atomic-fields-only",`Only atomic fields are supported in composite sources; field \`${p.name}\` is not atomic and will be ignored`);continue}if(p.accessModifier==="private")continue;const m=(x=p.as)!==null&&x!==void 0?x:p.name,y=l.get(m);if(y===void 0){const g={...p,name:m,as:void 0,e:{node:"compositeField"},compositeFieldUsage:{fields:[m],joinedUsage:{}},code:this.code,location:this.codeLocation};l.set(m,g),a.push(g)}else p.accessModifier==="internal"&&(y.accessModifier="internal")}}),{type:"composite",sources:i,connection:s,fields:a,dialect:o,name:u,parameters:i[0].parameters}}}ub.CompositeSource=sit,Object.defineProperty(ob,"__esModule",{value:!0}),ob.SQCompose=void 0;const oit=ub,uit=hu;class ait extends uit.SourceQueryElement{constructor(e){super({sources:e}),this.sources=e,this.elementType="sq-compose"}getSource(){if(this.asSource)return this.asSource;const e=this.sources.map(r=>r.getSource());if(e.length===0){this.sqLog("empty-composite-source","Composite source must have at least one input source");return}else e.length===1&&this.sqLog("unnecessary-composite-source","A composite source with one input is equivalent to that input",{severity:"warn"});if(lit(e))return this.asSource=new oit.CompositeSource(e),this.has({asSource:this.asSource}),this.asSource;this.sqLog("invalid-composite-source-input","All composite source inputs must be valid sources")}isSource(){return!0}}ob.SQCompose=ait;function lit(t){return t.every(e=>e!==void 0)}var ab={},Kl={},zy={},cit=T&&T.__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]}),fit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&cit(e,t,r);return fit(e,t),e};Object.defineProperty(zy,"__esModule",{value:!0}),zy.BinaryBoolean=void 0;const dit=ks,hit=xit(Zt),pit=pu,mit=Qt,git=xt;class yit extends git.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="abstract boolean binary",this.legalChildTypes=[hit.boolT]}getExpression(e){const r=this.left.getExpression(e),i=this.right.getExpression(e);return this.typeCheck(this.left,r)&&this.typeCheck(this.right,i)?(0,mit.computedExprValue)({dataType:{type:"boolean"},value:{node:(0,pit.getExprNode)(this.op),kids:{left:r.value,right:i.value}},from:[r,i]}):(0,dit.errorFor)("logical-op expected boolean")}}zy.BinaryBoolean=yit;var Eit=T&&T.__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]}),Ait=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_it=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Eit(e,t,r);return Ait(e,t),e};Object.defineProperty(Kl,"__esModule",{value:!0}),Kl.ExprLegacyIn=Kl.ExprEquality=Kl.ExprCompare=void 0;const fn=_it(Zt),vit=Qt,Cit=xt,Sit=zy,bit={"~":[fn.stringT],"!~":[fn.stringT],"<":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"<=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],"!=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],">=":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT],">":[fn.numberT,fn.stringT,fn.dateT,fn.timestampT]};class wle extends Sit.BinaryBoolean{constructor(e,r,i){super(e,r,i),this.elementType="a<=>b",this.legalChildTypes=bit[r]}getExpression(e){return this.right.apply(e,this.op,this.left)}}Kl.ExprCompare=wle;class Tit extends wle{constructor(e,r,i){super(e,r,i),this.elementType="a~=b"}getExpression(e){return this.right.apply(e,this.op,this.left,!0)}apply(e,r,i){return super.apply(e,r,i,!0)}}Kl.ExprEquality=Tit;class Rit extends Cit.ExpressionDef{constructor(e,r,i){super(),this.expr=e,this.notIn=r,this.choices=i,this.elementType="in",this.has({expr:e,choices:i})}getExpression(e){const r=this.expr.getExpression(e),i=this.choices.map(s=>s.getExpression(e));return(0,vit.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:this.notIn,kids:{e:r.value,oneOf:i.map(s=>s.value)}},from:[r,...i]})}}Kl.ExprLegacyIn=Rit;var Gy={},c2={};Object.defineProperty(c2,"__esModule",{value:!0}),c2.ExprTime=void 0;const Dit=Xe,Oit=Qt,Fit=xt;class UB extends Fit.ExpressionDef{constructor(e,r,i){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue=(0,Oit.computedExprValue)({dataType:{type:e},value:r,from:i??[]})}getExpression(e){return this.translationValue}static fromValue(e,r){let i=r.value;if(e!==r.type){const s={node:"cast",safe:!1,dstType:{type:e},e:r.value};(0,Dit.isTemporalType)(r.type)&&(s.srcType={type:r.type}),i=s}return new UB(e,i,[r])}}c2.ExprTime=UB;var Bc={};Object.defineProperty(Bc,"__esModule",{value:!0}),Bc.Range=void 0;const wit=ks,Nit=Qt,Lit=xt;class Iit extends Lit.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,i){switch(r){case"=":case"!=":{const s=r==="="?">=":"<",o=r==="="?"and":"or",u=r==="="?"<":">=",a=this.first.apply(e,s,i),l=this.last.apply(e,u,i);return(0,Nit.computedExprValue)({dataType:{type:"boolean"},value:{node:o,kids:{left:a.value,right:l.value}},from:[a,l]})}case">":return this.last.apply(e,">=",i);case">=":return this.first.apply(e,">=",i);case"<":return this.first.apply(e,"<",i);case"<=":return this.last.apply(e,"<",i)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.logError("range-as-value","A Range is not a value"),(0,wit.errorFor)("a range is not a value")}}Bc.Range=Iit;var $it=T&&T.__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]}),Bit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),kit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$it(e,t,r);return Bit(e,t),e};Object.defineProperty(Gy,"__esModule",{value:!0}),Gy.ExprGranularTime=void 0;const jB=Xe,Mit=ks,Nle=kit(Zt),Lle=ps,Pit=xt,lb=c2,Ile=Bc;class Uit extends Pit.ExpressionDef{constructor(e,r,i){super({expr:e}),this.expr=e,this.units=r,this.truncate=i,this.elementType="granularTime",this.legalChildTypes=[Nle.timestampT,Nle.dateT]}granular(){return!0}getExpression(e){const r=this.units,i=this.expr.getExpression(e);if(jB.TD.isTemporal(i)){const o={...i,timeframe:r};return this.truncate&&(o.value={node:"trunc",e:(0,jB.mkTemporal)(i.value,i.type),units:r}),o}i.type!=="error"&&this.logError("unsupported-type-for-time-truncation",`Cannot do time truncation on type '${i.type}'`);const s={...i};return i.type==="error"&&(s.type=(0,jB.isDateUnit)(r)?"date":"timestamp"),{...s,value:(0,Mit.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const r=this.getExpression(e),i={node:"numberLiteral",literal:"1"};if(r.type==="timestamp"){const a=lb.ExprTime.fromValue("timestamp",r),l=new lb.ExprTime("timestamp",(0,Lle.timeOffset)("timestamp",r.value,"+",i,this.units),[r]);return new Ile.Range(a,l)}const s=new lb.ExprTime("date",r.value,[r]),o=(0,Lle.timeOffset)("date",r.value,"+",i,this.units),u=new lb.ExprTime("date",o,[r]);return new Ile.Range(s,u)}}Gy.ExprGranularTime=Uit,Object.defineProperty(ab,"__esModule",{value:!0}),ab.Apply=void 0;const jit=Kl,qit=l2,$le=Gy;class Qit extends jit.ExprCompare{constructor(e,r){super(e,"=",r),this.left=e,this.right=r,this.elementType="apply"}getExpression(e){let r=this.right;if(!this.right.granular()){const i=this.right.requestExpression(e);i&&(0,qit.isGranularResult)(i)&&(r=new $le.ExprGranularTime(this.right,i.timeframe,!1))}return r instanceof $le.ExprGranularTime?r.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}ab.Apply=Qit;var f2={},Hit=T&&T.__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]}),zit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Git=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Hit(e,t,r);return zit(e,t),e};Object.defineProperty(f2,"__esModule",{value:!0}),f2.BinaryNumeric=void 0;const Wit=Git(Zt),Vit=xt;class Yit extends Vit.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="numeric binary abstract",this.legalChildTypes=[Wit.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}f2.BinaryNumeric=Yit;var cb={},Kit=T&&T.__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]}),Jit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Kit(e,t,r);return Jit(e,t),e};Object.defineProperty(cb,"__esModule",{value:!0}),cb.Boolean=void 0;const Zit=xt,est=Xit(Zt);let tst=class extends Zit.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...est.boolT,value:{node:this.value}}}};cb.Boolean=tst;var kc={};Object.defineProperty(kc,"__esModule",{value:!0}),kc.FunctionOrdering=kc.FunctionOrderBy=void 0;const qB=Xe,Ble=Je,nst=nd;class rst extends Ble.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.logError("analytic-order-by-missing-field","analytic `order_by` must specify an aggregate expression or output field reference"),{node:"functionOrderBy",e:{node:"error"},dir:this.dir};const r=this.field.getExpression(e);return(0,qB.expressionIsAggregate)(r.expressionType)||((0,qB.expressionIsScalar)(r.expressionType)?(!(this.field instanceof nst.ExprIdReference)||r.evalSpace==="input")&&this.field.logError("analytic-order-by-not-output","analytic `order_by` must be an aggregate or an output field reference"):this.field.logError("analytic-order-by-not-aggregate-or-output","analytic `order_by` must be scalar or aggregate")),{node:"functionOrderBy",e:r.value,dir:this.dir}}getAggregateOrderBy(e,r){if(this.field){const i=this.field.getExpression(e);return(0,qB.expressionIsScalar)(i.expressionType)||this.field.logError("aggregate-order-by-not-scalar","aggregate `order_by` must be scalar"),r||this.field.logError("aggregate-order-by-expression-not-allowed","`order_by` must be only `asc` or `desc` with no expression"),{node:"functionOrderBy",e:i.value,dir:this.dir}}else return this.dir===void 0?(this.logError("aggregate-order-by-without-field-or-direction","field or order direction must be specified"),{node:"functionDefaultOrderBy",dir:"asc"}):{node:"functionDefaultOrderBy",dir:this.dir}}}kc.FunctionOrderBy=rst;class ist extends Ble.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e,r){return this.list.map(i=>i.getAggregateOrderBy(e,r))}}kc.FunctionOrdering=ist;var fb={};Object.defineProperty(fb,"__esModule",{value:!0}),fb.ExprAddSub=void 0;const sst=f2;class ost extends sst.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}fb.ExprAddSub=ost;var Jl={},ust=T&&T.__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]}),ast=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),lst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ust(e,t,r);return ast(e,t),e};Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.ExprAggregateFunction=void 0;const Wy=Xe,cst=$t,fst=ks,kle=Ur,Mle=lst(Zt),xst=yt,dst=xt,hst=Pr,pst=nd;class mst extends dst.ExpressionDef{constructor(e,r,i){super(),this.func=e,this.legalChildTypes=[Mle.numberT],this.elementType=e,this.explicitSource=i,r&&(this.expr=r,this.has({expr:r}))}getExpression(e){var r,i,s;const o=e.isQueryFieldSpace()?e.inputSpace():e;let u=this.expr,a=(r=this.expr)===null||r===void 0?void 0:r.getExpression(o),l=(i=this.source)===null||i===void 0?void 0:i.path,c=[];if(this.source){const x=this.source.getField(o);if(x.found){c=x.joinPath;const h=x.found,p=h.typeDesc();if(!(h instanceof kle.StructSpaceField))if((0,Wy.isAtomicFieldType)(p.type)){u=this.source,a={...Mle.atomicDef(p),expressionType:p.expressionType,value:p.evalSpace==="output"?{node:"outputField",name:this.source.refString}:{node:"field",path:this.source.path},evalSpace:p.evalSpace,compositeFieldUsage:p.compositeFieldUsage},l=this.source.path.slice(0,-1);const m=this.getJoinUsage(o);(m.length===1||m.length>1&&m.slice(1).every(g=>gst(g,m[0])))&&(l=m[0].map(g=>g.name),c=m[0])}else return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${p.type}`)}else return this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}if(a===void 0)return this.loggedErrorExpr("missing-aggregate-expression","Missing expression for aggregate function");if((0,Wy.expressionIsAggregate)(a.expressionType))return this.loggedErrorExpr("aggregate-of-aggregate","Aggregate expression cannot be aggregate");if(!(a.type==="error")){const x=this.getJoinUsage(o),h=this.source!==void 0||this.explicitSource;if(u&&!(!this.source&&x.every(m=>m.length===0))&&!this.isSymmetricFunction()){const m=HB(c,x),y=zB(this.elementType,m),g=h?y==null?void 0:y.message:"Join path is required for this calculation";if(g){const E=yst(g,x,u,this.elementType),A=(s=y==null?void 0:y.code)!==null&&s!==void 0?s:"bad-join-usage";y?this.logError(A,E):this.logWarning(A,E)}}}if(this.typeCheck(this.expr||this,{...a,expressionType:"scalar"})){const x={node:"aggregate",function:this.func,e:a.value};return l&&l.length>0&&(x.structPath=l),{...this.returns(a),expressionType:"aggregate",value:x,evalSpace:"output"}}return(0,fst.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const r=[];if(this.source&&this.source.getField(e).found){const s={node:"field",path:this.source.path};r.push(...QB(e,s))}if(this.expr){const i=this.expr.getExpression(e).value;r.push(...QB(e,i))}return r}}Jl.ExprAggregateFunction=mst;function gst(t,e){let r=t.length;if(r!==e.length)return!1;for(;r>0;)if(r-=1,t[r].name!==e[r].name)return!1;return!0}function QB(t,e){const r=[],i=(s,o)=>{const u=o[0],a=o.slice(1),l=s.entry(u);if(l===void 0)throw new Error(`Invalid field lookup ${u}`);if(l instanceof kle.StructSpaceField&&a.length>0){const c=i(l.fieldSpace,a);return{...c,joinPath:[{...l.joinPathElement,name:u},...c.joinPath]}}else if(l instanceof hst.SpaceField){if(a.length!==0)throw new Error(`${u} cannot contain a ${a.join(".")}`);const c=l.fieldDef();if(c)return{fs:s,def:c,joinPath:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};for(const s of(0,cst.exprWalk)(e))if(s.node==="field"){const o=i(t,s.path),u=o.def;if((0,Wy.isAtomic)(u)&&!(0,Wy.isJoined)(u))if((0,Wy.hasExpression)(u)){const a=QB(o.fs,u.e);r.push(...a.map(l=>[...o.joinPath,...l]))}else r.push(o.joinPath)}else if(s.node==="source-reference")if(s.path){const o=i(t,s.path);r.push(o.joinPath)}else r.push([]);return r}function HB(t,e){const r=[];for(const i of e){let s=0;for(let l=0;l<t.length&&l<i.length&&t[l].name===i[l].name;l++)s=l+1;const o=t.slice(s),u=i.slice(s),a=[...o.map(l=>({...l,reverse:!0})),...u.map(l=>({...l,reverse:!1}))];r.push(a)}return r}function zB(t,e){for(const r of e)for(const i of r){if(i.joinType==="cross")return{code:"aggregate-traverses-join-cross",message:`Cannot compute \`${t}\` across \`join_cross\` relationship \`${i.name}\``};if(i.joinElementType==="array"&&!i.reverse)return{code:"aggregate-traverses-repeated-relationship",message:`Cannot compute \`${t}\` across repeated relationship \`${i.name}\``};if(i.joinType==="many"&&!i.reverse)return{code:"aggregate-traverses-join-many",message:`Cannot compute \`${t}\` across \`join_many\` relationship \`${i.name}\``}}}function yst(t,e,r,i){if(e.length===0)return t;let s=e[0];for(const m of e.slice(1))for(let y=0;y<s.length;y++){const g=s[y],E=m[y];if(g.name!==E.name){s=s.slice(0,y);break}}const o=HB(s,e),u=zB(i,o),a=s.slice().reverse().findIndex(m=>m.joinType==="many"||m.joinType==="cross"),l=a===-1?0:s.length-a,c=s.slice(0,l),f=HB(c,e),x=zB(i,f),h=s.length>0?s.map(m=>m.name).join("."):"source",p=c.length>0?c.map(m=>m.name).join("."):"source";if(u)return"Aggregated dimensional expression contains multiple join paths; rewrite, for example `sum(first_join.field + second_join.field)` as `first_join.field.sum() + second_join.field.sum()`";{const m=r instanceof xst.FieldReference?`${r.refString}.${i}()`:r instanceof pst.ExprIdReference?`${r.fieldReference.refString}.${i}()`:`${h}.${i}(${r.code})`,y=`${p}.${i}(${r.code})`;let g=`${t}; use \`${m}\``;return x===void 0&&p!==h&&(g+=` or \`${y}\` to get a result weighted with respect to \`${p}\``),g}}var xb={};Object.defineProperty(xb,"__esModule",{value:!0}),xb.ExprAlternationTree=void 0;const Ple=Qt,x2=xt,Est=pu;function GB(t){const e=t.atExpr();switch(e.atNodeType()){case x2.ATNodeType.And:case x2.ATNodeType.Partial:return;case x2.ATNodeType.Or:{if(e instanceof Ule){const r=GB(e.left);if(r){const i=GB(e.right);if(i)return[...r,...i]}}return}default:return e.granular()?void 0:[e]}}class Ule extends x2.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="alternation",this.elementType=`${r}alternation${r}`}equalityList(){return this.inList===void 0&&(this.inList=GB(this)||[]),this.inList}apply(e,r,i,s){if((0,Est.isEquality)(r)){const a=this.equalityList();if(a.length>0&&(r==="="||r==="!=")){const l=i.getExpression(e),c=a.map(f=>f.getExpression(e));return(0,Ple.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:r==="!=",kids:{e:l.value,oneOf:c.map(f=>f.value)}},from:[l,...c]})}a.length===0&&s&&this.logWarning("or-choices-only",`Only | seperated values are legal when used with ${r} operator`)}const o=this.left.apply(e,r,i),u=this.right.apply(e,r,i);return(0,Ple.computedExprValue)({dataType:{type:"boolean"},value:{node:this.op==="&"?"and":"or",kids:{left:o.value,right:u.value}},from:[o,u]})}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("alternation-as-value","Alternation tree has no value")}atNodeType(){return this.op==="|"?x2.ATNodeType.Or:x2.ATNodeType.And}}xb.ExprAlternationTree=Ule;var d2={};Object.defineProperty(d2,"__esModule",{value:!0}),d2.ExprAsymmetric=void 0;const Ast=Jl;class _st extends Ast.ExprAggregateFunction{constructor(e,r,i,s){super(e,r,s),this.func=e,this.expr=r,this.source=i,this.has({source:i})}isSymmetricFunction(){return!1}returns(e){return e}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}d2.ExprAsymmetric=_st;var db={};Object.defineProperty(db,"__esModule",{value:!0}),db.ExprAvg=void 0;const vst=d2;class Cst extends vst.ExprAsymmetric{constructor(e,r,i){super("avg",e,r,i),this.has({source:r})}}db.ExprAvg=Cst;var hb={};Object.defineProperty(hb,"__esModule",{value:!0}),hb.ExprCast=void 0;const Sst=ps,bst=Qt,Tst=xt;class Rst extends Tst.ExpressionDef{constructor(e,r,i=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=i,this.elementType="cast"}getExpression(e){const r=this.expr.getExpression(e);let i={type:"error"};if(typeof this.castType=="string")i={type:this.castType};else{const s=e.dialectObj();s&&(s.validateTypeName(this.castType.raw)?i=s.sqlTypeToMalloyType(this.castType.raw):this.logError("invalid-sql-native-type",`Cast type \`${this.castType.raw}\` is invalid for ${s.name} dialect`),this.safe&&!s.supportsSafeCast&&this.logError("dialect-cast-unsafe-only",`The SQL dialect '${e.dialectName()}' does not supply a safe cast operator`))}return(0,bst.computedExprValue)({dataType:i,value:(0,Sst.castTo)(this.castType,r.value,r.type,this.safe),from:[r]})}}hb.ExprCast=Rst;var pb={},Dst=T&&T.__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]}),Ost=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Fst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Dst(e,t,r);return Ost(e,t),e};Object.defineProperty(pb,"__esModule",{value:!0}),pb.ExprCoalesce=void 0;const jle=ji,qle=Fst(Zt),wst=xt;class Nst extends wst.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=qle.anyAtomicT}getExpression(e){const r=this.expr.getExpression(e),i=this.altExpr.getExpression(e);return r.type==="null"?i:(qle.typeEq(r,i)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${r.type}, ${i.type})`),{...r.type==="error"?i:r,expressionType:(0,jle.maxExpressionType)(r.expressionType,i.expressionType),value:{node:"coalesce",kids:{left:r.value,right:i.value}},evalSpace:(0,jle.mergeEvalSpaces)(r.evalSpace,i.evalSpace)})}}pb.ExprCoalesce=Nst;var mb={};Object.defineProperty(mb,"__esModule",{value:!0}),mb.ExprCount=void 0;const Lst=lt,Ist=Jl;class $st extends Ist.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}getExpression(e){const r={node:"aggregate",function:"count",e:{node:""}};return this.source&&(r.structPath=this.source.path),{type:"number",numberType:"integer",expressionType:"aggregate",value:r,evalSpace:"output",compositeFieldUsage:(0,Lst.emptyCompositeFieldUsage)()}}}mb.ExprCount=$st;var gb={},Bst=T&&T.__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]}),kst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Bst(e,t,r);return kst(e,t),e};Object.defineProperty(gb,"__esModule",{value:!0}),gb.ExprCountDistinct=void 0;const yb=Mst(Zt),Pst=Jl;class Ust extends Pst.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[yb.numberT,yb.stringT,yb.dateT,yb.timestampT]}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}}gb.ExprCountDistinct=Ust;var Eb={},Mc={};Object.defineProperty(Mc,"__esModule",{value:!0}),Mc.Limit=void 0;const jst=Je,qst=qn;class Qst extends jst.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=qst.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}Mc.Limit=Qst;var h2={};Object.defineProperty(h2,"__esModule",{value:!0}),h2.PartitionBy=void 0;const Hst=Je;class zst extends Hst.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}h2.PartitionBy=zst;var Vy={},Pc={};Object.defineProperty(Pc,"__esModule",{value:!0}),Pc.FieldName=void 0;const Gst=Je;class Wst extends Gst.MalloyElement{constructor(e){super(),this.name=e,this.elementType="fieldName"}get refString(){return this.name}toString(){return this.refString}getField(e){return e.lookup([this])}}Pc.FieldName=Wst;var Vst=T&&T.__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]}),Yst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Kst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Vst(e,t,r);return Yst(e,t),e};Object.defineProperty(Vy,"__esModule",{value:!0}),Vy.ExprFunc=void 0;const Cr=Xe,Jst=ks,Xst=ed,Zst=Qt,eot=xt,tot=Pc,Qle=$t,Hle=Kst(Zt),not=lt;class rot extends eot.ExpressionDef{constructor(e,r,i,s,o){super({args:r}),this.name=e,this.args=r,this.isRaw=i,this.rawType=s,this.source=o,this.elementType="function call()",this.has({source:o})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}findFunctionDef(e){var r,i,s;const o=this.name.toLowerCase(),u=e?(i=(r=this.getDialectNamespace(e))===null||r===void 0?void 0:r.getEntry(o))===null||i===void 0?void 0:i.entry:void 0,a=u??((s=this.modelEntry(o))===null||s===void 0?void 0:s.entry);return a===void 0?(this.logError("function-not-found",`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),{found:void 0,error:"unknown function"}):a.type!=="function"?(this.logError("call-of-non-function",`'${this.name}' (with type ${a.type}) is not a function`),{found:void 0,error:"called non function"}):(a.name!==this.name&&this.logWarning("case-insensitive-function",`Case insensitivity for function names is deprecated, use '${a.name}' instead`),{found:a,error:void 0})}getPropsExpression(e,r){var i,s,o,u;const a=this.args.map($=>$.getExpression(e));if(this.isRaw){const $=[`${this.name}(`];a.forEach((q,K)=>{K!==0&&$.push(","),$.push(q.value)}),$.push(")");const D=(i=a[0])!==null&&i!==void 0?i:{type:"number"},B=this.rawType?{type:this.rawType}:D;return(0,Zst.computedExprValue)({dataType:B,value:(0,Qle.composeSQLExpr)($),from:a})}const l=(s=e.dialectObj())===null||s===void 0?void 0:s.name,{found:c,error:f}=this.findFunctionDef(l);if(c===void 0)return(0,Jst.errorFor)(f);let x,h=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const D=this.source.getField(e).found;if(D){const B=D.typeDesc();if((0,Cr.isAtomicFieldType)(B.type))x={...Hle.atomicDef(B),expressionType:B.expressionType,value:{node:"field",path:this.source.path},evalSpace:B.evalSpace,compositeFieldUsage:B.compositeFieldUsage},h=this.source.path.slice(0,-1);else if(!(D instanceof Xst.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${B.type}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const p=[...x?[x]:[],...a],m=iot(c,p);if(m===void 0)return this.loggedErrorExpr("no-matching-function-overload",`No matching overload for function ${this.name}(${p.map($=>$.type).join(", ")})`);const{overload:y,expressionTypeErrors:g,evalSpaceErrors:E,nullabilityErrors:A,returnType:_}=m;for(const $ of g){const D=$.argIndex-(x?1:0),B=(0,Cr.expressionIsScalar)($.maxExpressionType)?"scalar":"scalar or aggregate";this.args[D].logError("invalid-function-argument-expression-type",`Parameter ${$.argIndex+1} ('${$.param.name}') of ${this.name} must be ${B}, but received ${$.actualExpressionType}`)}for(const $ of E){const D=$.argIndex-(x?1:0),B=$.maxEvalSpace==="literal"?"literal":$.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[D].logError("invalid-function-argument-evaluation-space",`Parameter ${$.argIndex+1} ('${$.param.name}') of ${this.name} must be ${B}, but received ${$.actualEvalSpace}`)}for(const $ of A){const D=$.argIndex-(x?1:0);this.args[D].logError("literal-null-function-argument",`Parameter ${$.argIndex+1} ('${$.param.name}') of ${this.name} must not be a literal null`)}m.returnTypeError&&this.logError(m.returnTypeError.code,m.returnTypeError.parameters);const v=y.returnType,C=(0,Cr.maxOfExpressionTypes)([(u=v.expressionType)!==null&&u!==void 0?u:"scalar",...p.map($=>$.expressionType)]);if(!(0,Cr.expressionIsAggregate)(y.returnType.expressionType)&&this.source!==void 0)return this.loggedErrorExpr("non-aggregate-function-with-source",`Cannot call function ${this.name}(${p.map($=>$.type).join(", ")}) with source`);const b={node:"function_call",overload:y,name:this.name,kids:{args:p.map($=>$.value)},expressionType:C,structPath:h};let S=b;if(r!=null&&r.orderBys&&r.orderBys.length>0){const $=(0,Cr.expressionIsAnalytic)(y.returnType.expressionType);if($||this.inExperiment("aggregate_order_by",!0)||r.orderBys[0].logError("aggregate-order-by-experiment-not-enabled","Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),y.supportsOrderBy||$){const D=y.supportsOrderBy!=="only_default",B=r.orderBys.flatMap(q=>$?q.getAnalyticOrderBy(e):q.getAggregateOrderBy(e,D));b.kids.orderBy=B}else r.orderBys[0].logError("function-does-not-support-order-by",`Function \`${this.name}\` does not support \`order_by\``)}if((r==null?void 0:r.limit)!==void 0&&(y.supportsLimit?b.limit=r.limit.limit:this.logError("function-does-not-support-limit",`Function ${this.name} does not support limit`)),r!=null&&r.partitionBys&&r.partitionBys.length>0){const $=[];for(const D of r.partitionBys)for(const B of D.partitionFields){const q=B.getField(e);q.found===void 0?B.logError("partition-by-not-found",`${B.refString} is not defined`):(0,Cr.expressionIsAnalytic)(q.found.typeDesc().expressionType)||(0,Cr.expressionIsUngroupedAggregate)(q.found.typeDesc().expressionType)?B.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):$.push(B.nameString)}b.partitionBy=$}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(c.name)){if(!this.inExperiment("sql_functions",!0))return this.loggedErrorExpr("sql-functions-experiment-not-enabled",`Cannot use sql_function \`${c.name}\`; use \`sql_functions\` experiment to enable this behavior`);const $=p[0].value;if($.node!=="stringLiteral")this.logError("invalid-sql-function-argument",`Invalid string literal for \`${c.name}\``);else{const D=$.literal,B=sot(D),q=B.filter(H=>H.type==="interpolation"&&H.name.includes(".")).map(H=>H.type==="interpolation"?`\${${H.name}}`:`\${${H.value}}`);if(q.length>0){const H=q.length===1?`'.' paths are not yet supported in sql interpolations, found ${q.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${q.join(", ")})`;return this.loggedErrorExpr("unsupported-sql-function-interpolation",H)}const K=[];for(const H of B)if(H.type==="string")K.push(H.value);else if(H.name==="TABLE")K.push({node:"source-reference"});else{const X=new tot.FieldName(H.name);this.has({name:X});const fe=e.lookup([X]);if(fe.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${fe.error.message}`);fe.found.refType==="parameter"?K.push({node:"parameter",path:[H.name]}):K.push({node:"field",path:[H.name]})}S=(0,Qle.composeSQLExpr)(K)}}const R=(0,Cr.mergeEvalSpaces)(...p.map($=>$.evalSpace)),O=R==="constant"?"constant":(0,Cr.expressionIsScalar)(C)?R:"output";return{...(0,Cr.isAtomic)(_)?Hle.atomicDef(_):_,expressionType:C,value:S,evalSpace:O,compositeFieldUsage:(0,not.mergeCompositeFieldUsage)(...p.map($=>$.compositeFieldUsage))}}}Vy.ExprFunc=rot;function iot(t,e){var r;for(const i of t.overloads){const s=new Map;let o=0,u=!0,a=!1;const l=[],c=[],f=[];for(let p=0;p<e.length;p++){const m=e[p],y=i.params[o];if(y===void 0){u=!1;break}if(!y.allowedTypes.some(E=>{var A;const{dataTypeMatch:_,genericsSet:v}=p2(s,(A=i.genericTypes)!==null&&A!==void 0?A:[],m,E);for(const C of v)s.set(C.name,C.type);return E.expressionType&&((0,Cr.isExpressionTypeLEQ)(m.expressionType,E.expressionType)||l.push({argIndex:p,maxExpressionType:E.expressionType,actualExpressionType:m.expressionType,param:y})),(E.evalSpace==="literal"&&m.evalSpace!=="literal"||E.evalSpace==="constant"&&(m.evalSpace==="input"||m.evalSpace==="output")||(0,Cr.expressionIsAnalytic)(i.returnType.expressionType)&&m.evalSpace==="input")&&c.push({argIndex:p,param:y,maxEvalSpace:E.evalSpace,actualEvalSpace:m.evalSpace}),E.evalSpace==="literal"&&m.type==="null"&&f.push({argIndex:p,param:y}),_})){u=!1;break}y.isVariadic?p===e.length-1&&(a=!0):o++}if(!a&&(o!==e.length||o!==i.params.length))continue;const x=Ab(i.returnType,s),h=(r=x.returnType)!==null&&r!==void 0?r:{type:"number"};if(u)return{overload:i,expressionTypeErrors:l,evalSpaceErrors:c,nullabilityErrors:f,returnTypeError:x.error,returnType:h}}}function sot(t){const e=[];let r=t;for(;r.length;){const i=r.indexOf("${");if(i===-1){e.push({type:"string",value:r});break}else{const s=r.slice(i).indexOf("}");if(s===-1){e.push({type:"string",value:r});break}i>0&&e.push({type:"string",value:r.slice(0,i)}),e.push({type:"interpolation",name:r.slice(i+2,s+i)}),r=r.slice(s+i+1)}}return e}function p2(t,e,r,i){var s,o,u,a;if(Cr.TD.eq(i,r)||i.type==="any"||i.type!=="generic"&&(r.type==="null"||r.type==="error"))return{dataTypeMatch:!0,genericsSet:[]};if(i.type==="array"&&r.type==="array"){if((0,Cr.isScalarArray)(r))return(0,Cr.isRepeatedRecordFunctionParam)(i)?{dataTypeMatch:!1,genericsSet:[]}:p2(t,e,r.elementTypeDef,i.elementTypeDef);if((0,Cr.isRepeatedRecordFunctionParam)(i)){const l={type:"record",fields:i.fields},c={type:"record",fields:r.fields};return p2(t,e,c,l)}else return{dataTypeMatch:!1,genericsSet:[]}}else if(i.type==="record"&&r.type==="record"){const l=[],c=new Map;for(const f of i.fields)c.set((s=f.as)!==null&&s!==void 0?s:f.name,f);for(const f of r.fields){const x=c.get((o=f.as)!==null&&o!==void 0?o:f.name);if(x===void 0)return{dataTypeMatch:!1,genericsSet:[]};const h=p2(new Map([...t.entries(),...l.map(p=>[p.name,p.type])]),e,f,x);l.push(...h.genericsSet)}return{dataTypeMatch:!0,genericsSet:l}}else if(i.type==="generic"){const l=t.get(i.generic);if(l!==void 0&&l.type!=="null"&&l.type!=="error")return p2(t,e,r,l);const c=(a=(u=e.find(f=>f.name===i.generic))===null||u===void 0?void 0:u.acceptibleTypes)!==null&&a!==void 0?a:[];for(const f of c){const x=p2(t,e,r,f);if(x.dataTypeMatch){if(!(0,Cr.isAtomic)(r)&&r.type!=="null")continue;const h={name:i.generic,type:r};return{dataTypeMatch:!0,genericsSet:[...x.genericsSet,h]}}}}return{dataTypeMatch:!1,genericsSet:[]}}function Ab(t,e){switch(t.type){case"array":{if("fields"in t){const s=t.fields.map(o=>{const u=Ab(o,e);return{...o,...u}});return{error:void 0,returnType:{type:"array",elementTypeDef:t.elementTypeDef,fields:s}}}const r=Ab(t.elementTypeDef,e);if(r.error)return r;const i=r.returnType;return i.type==="record"?{error:void 0,returnType:{type:"array",elementTypeDef:{type:"record_element"},fields:i.fields}}:(0,Cr.isAtomic)(i)?{error:void 0,returnType:{type:"array",elementTypeDef:i}}:{error:{code:"invalid-resolved-type-for-array",parameters:"Invalid resolved type for array; cannot be non-atomic"},returnType:void 0}}case"record":return{error:void 0,returnType:{type:"record",fields:t.fields.map(i=>{const s=Ab(i,e);return{...i,...s}})}};case"generic":{const r=e.get(t.generic);return r===void 0?{error:{code:"generic-not-resolved",parameters:`Generic ${t.generic} in return type could not be resolved`},returnType:void 0}:{error:void 0,returnType:r}}default:return{error:void 0,returnType:t}}}var oot=T&&T.__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]}),uot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),aot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&oot(e,t,r);return uot(e,t),e};Object.defineProperty(Eb,"__esModule",{value:!0}),Eb.ExprProps=void 0;const lot=Xe,cot=ks,fot=aot(Zt),xot=kc,dot=Mc,hot=h2,pot=xt,mot=Vy,got=lt;class yot extends pot.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=fot.anyAtomicT}getFilteredExpression(e,r,i){if(i.length>0){if(!this.expr.supportsWhere(r))return this.expr.logError("filter-of-non-aggregate","Filtered expression requires an aggregate computation"),r;const s=[];for(const o of i){const u=o.getFilterList(e);if(u.find(a=>(0,lot.expressionIsCalculation)(a.expressionType)))return o.logError("aggregate-filter-expression-not-scalar","Cannot filter an expresion with an aggregate or analytical computation"),r;s.push(...u)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,compositeFieldUsage:(0,got.mergeCompositeFieldUsage)(r.compositeFieldUsage,...s.map(o=>o.compositeFieldUsage)),value:{node:"filteredExpr",kids:{e:r.value,filterList:s}}}:(this.expr.logError("filter-of-non-aggregate",`Cannot filter '${r.expressionType}' data`),(0,cot.errorFor)("cannot filter type"))}return r}getExpression(e){const r=[];let i;const s=[],o=[];for(const a of this.statements)a instanceof hot.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.logError("partition-by-of-non-window-function","`partition_by` is not supported for this kind of expression"):a instanceof dot.Limit?i?a.logError("expression-limit-already-specified","limit already specified"):this.expr.canSupportLimit()?i=a:a.logError("limit-of-non-aggregate-function","`limit` is not supported for this kind of expression"):a instanceof xot.FunctionOrdering?this.expr.canSupportOrderBy()?s.push(a):a.logError("order-by-of-non-aggregate-function","`order_by` is not supported for this kind of expression"):o.push(a);const u=this.expr instanceof mot.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:i,orderBys:s}):this.expr.getExpression(e);return this.getFilteredExpression(e,u,o)}}Eb.ExprProps=yot;var _b={},Eot=T&&T.__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]}),Aot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_ot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Eot(e,t,r);return Aot(e,t),e};Object.defineProperty(_b,"__esModule",{value:!0}),_b.ExprLogicalOp=void 0;const vot=zy,zle=_ot(Zt);class Cot extends vot.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[zle.boolT,zle.aggregateBoolT]}}_b.ExprLogicalOp=Cot;var vb={},Sot=T&&T.__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]}),bot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Tot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Sot(e,t,r);return bot(e,t),e};Object.defineProperty(vb,"__esModule",{value:!0}),vb.ExprMax=void 0;const Cb=Tot(Zt),Rot=Jl;class Dot extends Rot.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[Cb.numberT,Cb.stringT,Cb.dateT,Cb.timestampT]}returns(e){return e}}vb.ExprMax=Dot;var Sb={},Oot=T&&T.__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]}),Fot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),wot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Oot(e,t,r);return Fot(e,t),e};Object.defineProperty(Sb,"__esModule",{value:!0}),Sb.ExprMin=void 0;const bb=wot(Zt),Not=Jl;class Lot extends Not.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[bb.numberT,bb.stringT,bb.dateT,bb.timestampT]}returns(e){return e}}Sb.ExprMin=Lot;var Tb={},Iot=T&&T.__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]}),$ot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Bot=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Iot(e,t,r);return $ot(e,t),e};Object.defineProperty(Tb,"__esModule",{value:!0}),Tb.ExprMinus=void 0;const kot=ks,Gle=Bot(Zt),Mot=xt;class Pot extends Mot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[Gle.numberT]}getExpression(e){const r=this.expr.getExpression(e);return Gle.typeIn(r,this.legalChildTypes)?{...r,type:"number",value:{node:"unary-",e:r.value}}:(0,kot.errorFor)("negate requires number")}}Tb.ExprMinus=Pot;var Rb={};Object.defineProperty(Rb,"__esModule",{value:!0}),Rb.ExprMulDiv=void 0;const Uot=f2;class jot extends Uot.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}Rb.ExprMulDiv=jot;var Db={},Yy={};Object.defineProperty(Yy,"__esModule",{value:!0}),Yy.Unary=void 0;const qot=xt;class Qot extends qot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}Yy.Unary=Qot;var Hot=T&&T.__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]}),zot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Got=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Hot(e,t,r);return zot(e,t),e};Object.defineProperty(Db,"__esModule",{value:!0}),Db.ExprNot=void 0;const WB=Got(Zt),Wot=Yy;class Vot extends Wot.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[WB.boolT,WB.nullT]}getExpression(e){var r;const i=this.expr.getExpression(e);!((r=e.dialectObj())===null||r===void 0)&&r.booleanAsNumbers&&this.legalChildTypes.find(o=>o.type==="number")===void 0&&this.legalChildTypes.push(WB.numberT);const s=this.typeCheck(this.expr,i);return{...i,type:"boolean",value:{node:"not",e:s?i.value:{node:"false"}}}}}Db.ExprNot=Vot;var Ob={};Object.defineProperty(Ob,"__esModule",{value:!0}),Ob.ExprNow=void 0;const Yot=xt,Kot=lt;class Jot extends Yot.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{type:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now",typeDef:{type:"timestamp"}},compositeFieldUsage:(0,Kot.emptyCompositeFieldUsage)()}}}Ob.ExprNow=Jot;var Uc={};Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.ExprIsNull=Uc.PartialIsNull=Uc.ExprNULL=void 0;const Xot=Qt,Fb=xt;function VB(t,e,r){const i=r.getExpression(t);return i.type="boolean",i.value={node:e==="="?"is-null":"is-not-null",e:i.value},i}class Zot extends Fb.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return(0,Xot.literalExprValue)({dataType:{type:"null"},value:{node:"null"}})}apply(e,r,i){return r==="!="||r==="="?VB(e,r,i):super.apply(e,r,i,!0)}}Uc.ExprNULL=Zot;class eut extends Fb.ExpressionDef{constructor(e){super(),this.op=e,this.elementType="<=> NULL"}apply(e,r,i){return VB(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial null check does not have a value")}atNodeType(){return Fb.ATNodeType.Partial}}Uc.PartialIsNull=eut;class tut extends Fb.ExpressionDef{constructor(e,r){super(),this.expr=e,this.op=r,this.elementType="is null",this.has({expr:e})}getExpression(e){return VB(e,this.op,this.expr)}}Uc.ExprIsNull=tut;var wb={};Object.defineProperty(wb,"__esModule",{value:!0}),wb.ExprNumber=void 0;const nut=Qt,rut=xt;class iut extends rut.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){const e=Number(this.n),r=Number.isNaN(e)?{type:"number"}:{type:"number",numberType:Number.isInteger(e)?"integer":"float"};return(0,nut.literalExprValue)({dataType:r,value:{node:"numberLiteral",literal:this.n}})}}wb.ExprNumber=iut;var Nb={};Object.defineProperty(Nb,"__esModule",{value:!0}),Nb.ExprParens=void 0;const YB=xt;class sut extends YB.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const r=this.expr.getExpression(e);return{...r,value:{node:"()",e:r.value}}}apply(e,r,i,s){return this.expr.atNodeType()===YB.ATNodeType.Or?this.expr.apply(e,r,i,s):(0,YB.applyBinary)(e,i,r,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}Nb.ExprParens=sut;var Lb={};Object.defineProperty(Lb,"__esModule",{value:!0}),Lb.ExprFilterExpression=void 0;const out=Qt,uut=xt,Ib=P4;class aut extends uut.ExpressionDef{constructor(e){super(),this.filterText=e,this.elementType="filter expression literal"}getExpression(){return this.loggedErrorExpr("filter-expression-type","Filter expression illegal here")}apply(e,r,i,s=!1){var o;if(r==="~"||r==="!~"){const u=i.getExpression(e);if(u.type==="error")return u;let a;switch(u.type){case"string":a=Ib.StringFilterExpression.parse(this.filterText);break;case"number":a=Ib.NumberFilterExpression.parse(this.filterText);break;case"boolean":if(!((o=e.dialectObj())===null||o===void 0)&&o.booleanAsNumbers)return this.loggedErrorExpr("filter-expression-type","Boolean filters not supported on this connection type");a=Ib.BooleanFilterExpression.parse(this.filterText);break;case"date":case"timestamp":a=Ib.TemporalFilterExpression.parse(this.filterText);break;default:return i.loggedErrorExpr("filter-expression-type",`Cannot use filter expressions with type '${u.type}'`)}if(a.log.length>0)for(const c of a.log)return this.loggedErrorExpr("filter-expression-error",`Filter parse error: ${c.message}`);const l={node:"filterMatch",dataType:u.type,filter:a.parsed,e:u.value};return r==="!~"&&(l.notMatch=!0),(0,out.computedExprValue)({value:l,dataType:{type:"boolean"},from:[u]})}return this.loggedErrorExpr("filter-expression-type",`Cannot use the '${r}' operator with a filter expression`)}}Lb.ExprFilterExpression=aut;var $b={};Object.defineProperty($b,"__esModule",{value:!0}),$b.ExprRegEx=void 0;const lut=Qt,cut=xt;class fut extends cut.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return(0,lut.literalExprValue)({dataType:{type:"regular expression"},value:{node:"regexpLiteral",literal:this.regex}})}}$b.ExprRegEx=fut;var Bb={};Object.defineProperty(Bb,"__esModule",{value:!0}),Bb.ExprString=void 0;const xut=xt,dut=Qt;class hut extends xut.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return(0,dut.literalExprValue)({dataType:{type:"string"},value:{node:"stringLiteral",literal:this.value}})}}Bb.ExprString=hut;var kb={};Object.defineProperty(kb,"__esModule",{value:!0}),kb.ExprSum=void 0;const put=d2;class mut extends put.ExprAsymmetric{constructor(e,r,i){super("sum",e,r,i),this.has({source:r})}}kb.ExprSum=mut;var Mb={};Object.defineProperty(Mb,"__esModule",{value:!0}),Mb.ExprTimeExtract=void 0;const Xl=Xe,Pb=Qt,KB=xt,gut=Bc;class Ky extends KB.ExpressionDef{static extractor(e){const r=Ky.pluralMap[e];if(r)return r;if((0,Xl.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){const r=Ky.extractor(this.extractText);if(r){if(this.args.length!==1)return this.loggedErrorExpr("too-many-arguments-for-time-extraction",`Extraction function ${r} requires one argument`);const i=this.args[0];if(i instanceof gut.Range){let s=i.first.getExpression(e),o=i.last.getExpression(e);if(s.type==="error"||o.type==="error")return(0,Pb.computedErrorExprValue)({dataType:{type:"number"},error:"extract from error",from:[s,o]});if(!(0,Xl.isTemporalType)(s.type))return i.first.loggedErrorExpr("invalid-type-for-time-extraction",`Can't extract ${r} from '${s.type}'`);if(!(0,Xl.isTemporalType)(o.type))return i.last.loggedErrorExpr("invalid-type-for-time-extraction",`Cannot extract ${r} from '${o.type}'`);let u=s.type;if(!Xl.TD.eq(s,o)){let a=!0;if(u="timestamp",s.type==="date"){const l=(0,KB.getMorphicValue)(s,"timestamp");l&&(s=l,a=!1)}else{const l=(0,KB.getMorphicValue)(o,"timestamp");l&&(o=l,a=!1)}if(a)return i.first.loggedErrorExpr("invalid-types-for-time-measurement",`Cannot measure from ${s.type} to ${o.type}`)}return["week","month","quarter","year"].includes(r)?this.loggedErrorExpr("invalid-timeframe-for-time-measurement",`Cannot measure interval using '${r}'`):(0,Xl.isTimestampUnit)(r)?(0,Pb.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"timeDiff",units:r,kids:{left:(0,Xl.mkTemporal)(s.value,u),right:(0,Xl.mkTemporal)(o.value,u)}},from:[s,o]}):this.loggedErrorExpr("invalid-time-extraction-unit",`Cannot extract ${r} from a range`)}else{const s=i.getExpression(e);return(0,Xl.isTemporalType)(s.type)?(0,Pb.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"extract",e:(0,Xl.mkTemporal)(s.value,s.type),units:r},from:[s]}):(s.type!=="error"&&this.logError("unsupported-type-for-time-extraction",`${this.extractText}() requires time type, not '${s.type}'`),(0,Pb.computedErrorExprValue)({dataType:{type:"number",numberType:"integer"},error:`${this.extractText} bad type ${s.type}`,from:[s]}))}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}Mb.ExprTimeExtract=Ky,Ky.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var Ub={},mu={},jb={};Object.defineProperty(jb,"__esModule",{value:!0}),jb.QueryInputSpace=void 0;const yut=hs,Eut=Zp;class Aut extends Eut.RefinedSpace{constructor(e,r,i){super(e),this.queryOutput=r,this._isProtectedAccessSpace=i,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof yut.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}isProtectedAccessSpace(){return this._isProtectedAccessSpace}}jb.QueryInputSpace=Aut;var _ut=T&&T.__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]}),vut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Cut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&_ut(e,t,r);return vut(e,t),e};Object.defineProperty(mu,"__esModule",{value:!0}),mu.ReduceFieldSpace=mu.QuerySpace=mu.QueryOperationSpace=void 0;const qb=Cut(Xe),JB=Fc,Wle=Pc,Vle=Pr,Sut=yt,but=Zp,Tut=wy,Rut=Ur,Dut=jb,Oa=lt,Out=ed;class Yle extends but.RefinedSpace{get compositeFieldUsage(){if(this._compositeFieldUsage===void 0)throw new Error("Composite field usage accessed before computed");return this._compositeFieldUsage}constructor(e,r,i,s){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=i,this.astEl=s,this.expandedWild={},this.compositeFieldUsers=[],this._compositeFieldUsage=void 0,this.exprSpace=new Dut.QueryInputSpace(e.structDef(),this,e.isProtectedAccessSpace()),r&&this.addRefineFromFields(r)}logError(e,r,i){return this.astEl&&this.astEl.logError(e,r,i),e}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof Rut.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-defined",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries())if(!e.except.has(a)&&l.refType!=="parameter")if(this.entry(a)){const c=(r=this.expandedWild[a])===null||r===void 0?void 0:r.path.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=l.typeDesc();qb.TD.isAtomic(c)&&qb.expressionIsScalar(c.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:a,entry:l}),this.expandedWild[a]={path:s.concat(a),entry:l})}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.newEntry(a.name,e,a.entry)}addValidatedCompositeFieldUserFromEntry(e,r){r instanceof Vle.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:r,logTo:void 0})}getJoinOnCompositeFieldUsage(e){var r;const i=e.map(o=>new Wle.FieldName(o));this.astEl.has({reference:i});const s=this.exprSpace.lookup(i);if(s.found&&s.found instanceof Out.StructSpaceFieldBase)return(0,Oa.joinedCompositeFieldUsage)(e.slice(0,-1),(r=s.found.fieldDef().onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Oa.emptyCompositeFieldUsage)());throw new Error("Unexpected join lookup was not found or not a struct")}getCompositeFieldUsageIncludingJoinOns(e){let r=e;const i=(0,Oa.compositeFieldUsageJoinPaths)(e);for(const s of i)r=(0,Oa.mergeCompositeFieldUsage)(this.getJoinOnCompositeFieldUsage(s),r);return r}addCompositeFieldUserFromFilter(e,r){e.compositeFieldUsage!==void 0&&this.compositeFieldUsers.push({type:"filter",filter:e,logTo:r})}newEntry(e,r,i){i instanceof Vle.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:i,logTo:r}),super.newEntry(e,r,i)}applyNextCompositeFieldUsage(e,r,i,s,o){if(s){const u=this.getCompositeFieldUsageIncludingJoinOns((0,Oa.compositeFieldUsageDifference)(s,r));if(r=(0,Oa.mergeCompositeFieldUsage)(r,u),!(0,Oa.isEmptyCompositeFieldUsage)(u)){const a=(0,Oa.narrowCompositeFieldResolution)(e,r,i);a.error?(o??this).logError("invalid-composite-field-usage",{newUsage:u,allUsage:r}):i=a.narrowedCompositeFieldResolution}}return{compositeFieldUsage:r,narrowedCompositeFieldResolution:i}}}mu.QueryOperationSpace=Yle;class Kle extends Yle{addRefineFromFields(e){var r;if(qb.isQuerySegment(e)){if(e!=null&&e.extendSource)for(const i of e.extendSource)this.exprSpace.addFieldDef(i);for(const i of e.queryFields)if(i.type==="fieldref"){const s=this.exprSpace.lookup(i.path.map(o=>new Wle.FieldName(o)));if(s.found){const o=i.path[i.path.length-1];this.setEntry(o,s.found),this.addValidatedCompositeFieldUserFromEntry(o,s.found)}}else if(i.type!=="turtle"){const s=new Tut.ColumnSpaceField(i),o=(r=i.as)!==null&&r!==void 0?r:i.name;this.setEntry(o,s),this.addValidatedCompositeFieldUserFromEntry(o,s)}}}pushFields(...e){for(const r of e)r instanceof Sut.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){const e=[];let r=(0,Oa.emptyCompositeFieldUsage)(),i=(0,Oa.emptyNarrowedCompositeFieldResolution)();const s=this.inputSpace().structDef();for(const o of this.compositeFieldUsers){let u;if(o.type==="filter")o.filter.compositeFieldUsage&&(u=o.filter.compositeFieldUsage);else{const{name:l,field:c}=o,f=this.expandedWild[l];if(f)e.push({type:"fieldref",path:f.path}),u=f.entry.typeDesc().compositeFieldUsage;else{const x=c.getQueryFieldDef(this.exprSpace);if(x){const h=c.typeDesc();u=h.compositeFieldUsage,h&&h.type!=="error"&&this.canContain(h)&&!wut(x)&&e.push(x)}}}const a=this.applyNextCompositeFieldUsage(s,r,i,u,o.logTo);r=a.compositeFieldUsage,i=a.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,e}getQuerySegment(e){const r=this.getPipeSegment(e);if(qb.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.logError("unexpected-index-segment","internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};const r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,JB.mergeFields)(e==null?void 0:e.queryFields,r.queryFields),e!=null&&e.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const i=[],s=this.exprSpace.structDef();for(const o of this.exprSpace.extendList){const u=s.fields.find(a=>(0,JB.nameFromDef)(a)===o);u&&i.push(u)}r.extendSource=(0,JB.mergeFields)(r.extendSource,i)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),r}lookup(e){const r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}mu.QuerySpace=Kle;class Fut extends Kle{constructor(){super(...arguments),this.segmentType="reduce"}}mu.ReduceFieldSpace=Fut;function wut(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}var Nut=T&&T.__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]}),Lut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Iut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Nut(e,t,r);return Lut(e,t),e};Object.defineProperty(Ub,"__esModule",{value:!0}),Ub.ExprUngroup=void 0;const Jle=Xe,$ut=mu,Xle=Iut(Zt),But=xt;class kut extends But.ExpressionDef{constructor(e,r,i){super({expr:r,fields:i}),this.control=e,this.expr=r,this.fields=i,this.legalChildTypes=Xle.anyAtomicT,this.elementType="ungroup"}getExpression(e){const r=this.expr.getExpression(e);if(!(0,Jle.expressionIsAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,Jle.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-ungrouped-aggregate",`${this.control}() expression must not already be ungrouped`);const i={node:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const s=[],o=this.control==="exclude";for(const u of this.fields){let a=e.outputSpace(),l=!0;for(;a;){const c=a.lookup([u]);if(c.found&&c.isOutputField)s.push(u.refString),l=!1;else if(a instanceof $ut.QuerySpace){a=a.nestParent;continue}break}if(l){const c=o?"exclude()":"all()";u.logError("ungroup-field-not-in-output",`${c} '${u.refString}' is missing from query output`)}}i.fields=s}return{...Xle.atomicDef(r),expressionType:"ungrouped_aggregate",value:i,evalSpace:"output",compositeFieldUsage:r.compositeFieldUsage}}return this.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}Ub.ExprUngroup=kut;var Qb={},Mut=T&&T.__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]}),Put=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Uut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Mut(e,t,r);return Put(e,t),e};Object.defineProperty(Qb,"__esModule",{value:!0}),Qb.ForRange=void 0;const jut=ks,Zle=Uut(Zt),Hb=ps,qut=Qt,Qut=xt,zb=c2,e0e=Bc;class Hut extends Qut.ExpressionDef{constructor(e,r,i){super({from:e,duration:r,timeframe:i}),this.from=e,this.duration=r,this.timeframe=i,this.elementType="forRange",this.legalChildTypes=[Zle.timestampT,Zle.dateT]}apply(e,r,i){const s=this.from.getExpression(e),o=i.getExpression(e);if(!this.typeCheck(i,o))return(0,jut.errorFor)("no time for range");const u=this.duration.getExpression(e);if(u.type!=="number")return u.type!=="error"&&this.logError("invalid-duration-quantity",`FOR duration count must be a number, not '${u.type}'`),(0,qut.computedErrorExprValue)({dataType:{type:"boolean"},error:"for not number",from:[s,o]});const a=this.timeframe.text;let l=(0,Hb.resolution)(a);if(s.type==="timestamp"&&(l="timestamp"),o.type==="date"&&l==="date"){const m=this.from,y=(0,Hb.timeOffset)("date",s.value,"+",u.value,a),g=new zb.ExprTime("date",y);return new e0e.Range(m,g).apply(e,r,i)}const c=zb.ExprTime.fromValue("timestamp",o);let f=this.from,x=s.value;if(s.type==="date"){const m=s.morphic&&s.morphic.timestamp;m?x=m:x=(0,Hb.castTo)("timestamp",x,"date"),f=new zb.ExprTime("timestamp",x,[s])}const h=(0,Hb.timeOffset)("timestamp",x,"+",u.value,a),p=new zb.ExprTime("timestamp",h,[s,u]);return new e0e.Range(f,p).apply(e,r,c)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}Qb.ForRange=Hut;var Sr={};Object.defineProperty(Sr,"__esModule",{value:!0}),Sr.LiteralYear=Sr.LiteralQuarter=Sr.LiteralMonth=Sr.LiteralWeek=Sr.LiteralDay=Sr.LiteralHour=Sr.LiteralTimestamp=Sr.TimeFormatError=void 0;const jc=Cy,zut=Xe,Gut=Qt,Wut=Bc,t0e=c2,XB=xt;class Vut extends Error{}Sr.TimeFormatError=Vut;function id(t,e){const r=t.slice(1);if(e){const i=r.match(/\[[^\]]+]$/);if(i)return{tzSpec:i[0].slice(1,-1),text:r.slice(0,-i[0].length)}}return{text:r}}const n0e="yyyy",r0e=`${n0e}-LL`,Ao=`${r0e}-dd`,i0e=`${Ao} HH`,s0e=`${i0e}:mm`,ZB=`${s0e}:ss`;class o0e extends XB.ExpressionDef{constructor(e,r,i){super(),this.units=r,this.timeType=i,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){const i={node:"timeLiteral",literal:e,typeDef:{type:r}};return this.timeZone&&(i.timezone=this.timeZone),i}makeValue(e,r){const i=this.makeLiteral(e,r);return(0,Gut.literalTimeResult)({value:i,dataType:{type:r},timeframe:this.units})}getExpression(e){return this.makeValue(this.literalPart,this.timeType)}getNext(){if(this.nextLit)return this.makeValue(this.nextLit,this.timeType)}granular(){return this.nextLit!==void 0}}class ek extends o0e{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r;const i=id(e,!0);e=i.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),i.text=e);const s=e.match(/^([^.,]+)[,.](\d+)$/);s&&(e=s[1]);let o=jc.DateTime.fromFormat(e,ZB);if(o.isValid)return new ek(i,r);if(o=jc.DateTime.fromFormat(e,s0e),o.isValid){i.text=i.text+":00",r="minute";const u=o.plus({minute:1}).toFormat(ZB);return new tk(i,r,"timestamp",u)}}}Sr.LiteralTimestamp=ek;class tk extends o0e{constructor(e,r,i,s){super(e,r,i),this.nextLit=s,this.elementType="granularTimeLiteral"}apply(e,r,i){let s=this.getExpression(e),o=this.getNext();if(o){const u=i.getExpression(e);if(u.type==="timestamp"){const a=(0,XB.getMorphicValue)(s,"timestamp"),l=(0,XB.getMorphicValue)(o,"timestamp");if(a&&l)s=a,o=l;else return super.apply(e,r,i)}if(o&&(0,zut.isTemporalType)(u.type)){const a=u.type;return new Wut.Range(new t0e.ExprTime(a,s.value),new t0e.ExprTime(a,o.value)).apply(e,r,i)}}return super.apply(e,r,i)}}class nk extends tk{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){const r=id(e,!1);let i=r.text;const s=jc.DateTime.fromFormat(r.text,i0e);if(s.isValid)return r.text=r.text+":00:00",i=s.plus({hour:1}).toFormat(ZB),new nk(r,i)}}Sr.LiteralHour=nk;class Jy extends tk{constructor(e,r,i){super(e,r,"date",i)}getExpression(e){const r=this.makeValue(this.literalPart,"date"),i=this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp");return{...r,morphic:{timestamp:i},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),r=this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp");return{...e,morphic:{timestamp:r}}}}class rk extends Jy{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){const r=id(e,!1);let i=r.text;const s=jc.DateTime.fromFormat(r.text,Ao);if(s.isValid)return i=s.plus({day:1}).toFormat(Ao),new rk(r,i)}}Sr.LiteralDay=rk;class ik extends Jy{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){const r=id(e,!1);let i=r.text;const s=r.text.slice(0,10),o=jc.DateTime.fromFormat(s,Ao);if(o.isValid&&o.weekday===7){const a=o.plus({days:7});return r.text=o.toFormat(Ao),i=a.toFormat(Ao),new ik(r,i)}}}Sr.LiteralWeek=ik;class sk extends Jy{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){const r=id(e,!1);let i=r.text;const s=jc.DateTime.fromFormat(r.text,r0e);if(s.isValid){const o=s.plus({months:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new sk(r,i)}}}Sr.LiteralMonth=sk;class ok extends Jy{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){const r=id(e,!1);let i=r.text;const s=r.text.match(/(^\d{4})-[qQ](\d)$/);if(s){const o=Number.parseInt(s[2])-1;let u=jc.DateTime.fromFormat(s[1],"yyyy");o>0&&(u=u.plus({quarters:o}));const a=u.plus({quarter:1});return r.text=u.toFormat(Ao),i=a.toFormat(Ao),new ok(r,i)}}}Sr.LiteralQuarter=ok;class uk extends Jy{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){const r=id(e,!1);let i=r.text;const s=jc.DateTime.fromFormat(r.text,n0e);if(s.isValid){const o=s.plus({year:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new uk(r,i)}}}Sr.LiteralYear=uk;var Gb={};Object.defineProperty(Gb,"__esModule",{value:!0}),Gb.PartialCompare=void 0;const u0e=xt;class Yut extends u0e.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,i){return this.right.apply(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial comparison does not have a value")}atNodeType(){return u0e.ATNodeType.Partial}}Gb.PartialCompare=Yut;var m2={},Kut=T&&T.__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]}),Jut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Kut(e,t,r);return Jut(e,t),e};Object.defineProperty(m2,"__esModule",{value:!0}),m2.PickWhen=m2.Pick=void 0;const g2=Xut(Zt),a0e=Qt,Zut=xt,eat=Je;function Wb(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class tat extends Zut.ExpressionDef{constructor(e,r){super({choices:e}),this.choices=e,this.elsePick=r,this.elementType="pick",this.has({elsePick:r})}requestExpression(e){if(this.elsePick!==void 0){for(const r of this.choices){if(r.pick===void 0)return;const i=r.when.requestExpression(e);if(i===void 0||i.type!=="boolean")return}return this.getExpression(e)}}apply(e,r,i){var s;const o={node:"case",kids:{caseWhen:[],caseThen:[]}};let u;const a=[];for(const h of this.choices){const p=h.when.apply(e,"=",i),m=h.pick?h.pick.getExpression(e):i.getExpression(e);if(a.push(p,m),u&&!g2.typeEq(u,m,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:m.type,returnType:u.type});u=Wb(u,m),o.kids.caseWhen.push(p.value),o.kids.caseThen.push(m.value)}const l=(s=this.elsePick)===null||s===void 0?void 0:s.getExpression(e),c=i.getExpression(e);a.push(c),l&&a.push(l);const f=l??c,x=Wb(u,f);return g2.typeEq(x,f,!0)?(o.kids.caseElse=f.value,(0,a0e.computedExprValue)({dataType:x,value:o,from:a})):this.elsePick?this.loggedErrorExpr("pick-else-type-does-not-match",{elseType:f.type,returnType:x.type}):this.loggedErrorExpr("pick-default-type-does-not-match",{defaultType:f.type,returnType:x.type})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}};if(this.elsePick===void 0)return this.loggedErrorExpr("pick-missing-else","pick incomplete, missing 'else'");const i=[],s=[];for(const l of this.choices){if(l.pick===void 0)return this.loggedErrorExpr("pick-missing-value","pick with no value can only be used with apply");l.when.requestExpression(e)===void 0&&this.loggedErrorExpr("pick-illegal-partial","pick with partial when can only be used with apply");const f=l.pick.getExpression(e),x=l.when.getExpression(e);i.push({pick:f,when:x}),s.push(f,x)}let o;for(const l of i){if(!g2.typeEq(l.when,g2.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:l.when.type});if(o&&!g2.typeEq(o,l.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:l.pick.type,returnType:o.type});o=Wb(o,l.pick),r.kids.caseWhen.push(l.when.value),r.kids.caseThen.push(l.pick.value)}const u=this.elsePick.getExpression(e);s.push(u);const a=Wb(o,u);return g2.typeEq(a,u,!0)?(r.kids.caseElse=u.value,(0,a0e.computedExprValue)({dataType:a,value:r,from:s})):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.type,returnType:a.type})}}m2.Pick=tat;class nat extends eat.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="caseWhen",this.has({pick:e})}}m2.PickWhen=nat;var y2={},rat=T&&T.__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]}),iat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rat(e,t,r);return iat(e,t),e};Object.defineProperty(y2,"__esModule",{value:!0}),y2.CaseWhen=y2.Case=void 0;const oat=Qt,uat=xt,aat=Je,E2=sat(Zt);function l0e(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class lat extends uat.ExpressionDef{constructor(e,r,i){super({choices:r}),this.value=e,this.choices=r,this.elseValue=i,this.elementType="case",this.has({elseValue:i,value:e})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}},i=[];let s;if(this.value){const a=this.value.getExpression(e);i.push(a),r.kids.caseValue=a.value,s=a}const o=[];for(const a of this.choices){const l=a.when.getExpression(e),c=a.then.getExpression(e);o.push({when:l,then:c}),i.push(l,c)}let u;for(const a of o){if(s!==void 0){if(!E2.typeEq(a.when,s))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:a.when.type,valueType:s.type})}else if(!E2.typeEq(a.when,E2.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:a.when.type});if(u&&!E2.typeEq(u,a.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:a.then.type,returnType:u.type});u=l0e(u,a.then),r.kids.caseWhen.push(a.when.value),r.kids.caseThen.push(a.then.value)}if(this.elseValue){const a=this.elseValue.getExpression(e);if(u&&!E2.typeEq(u,a,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:a.type,returnType:u.type});u=l0e(u,a),i.push(a),r.kids.caseElse=a.value}return(0,oat.computedExprValue)({value:r,dataType:u?E2.atomicDef(u):{type:"null"},from:i})}}y2.Case=lat;class cat extends aat.MalloyElement{constructor(e,r){super({when:e,then:r}),this.when=e,this.then=r,this.elementType="caseWhen"}}y2.CaseWhen=cat;var Vb={},sd={},fat=T&&T.__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]}),xat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&fat(e,t,r);return xat(e,t),e};Object.defineProperty(sd,"__esModule",{value:!0}),sd.RecordLiteral=sd.RecordElement=void 0;const c0e=ji,hat=Qt,pat=xt,mat=Je,gat=dat(Zt);class yat extends mat.MalloyElement{constructor(e){if(super(),this.elementType="record element","value"in e)this.value=e.value,this.has({value:e.value}),e.key&&(this.key=e.key);else{this.has({path:e.path}),this.value=e.path;const r=e.path.fieldReference.path;this.key=r[r.length-1]}}}sd.RecordElement=yat;class Eat extends pat.ExpressionDef{constructor(e){super(),this.pairs=e,this.elementType="record literal",this.has({pairs:e})}getExpression(e){return this.getRecord(e,[])}getRecord(e,r){var i;const s={node:"recordLiteral",kids:{},typeDef:{type:"record",fields:[]}},o=[];let u=0;for(const a of this.pairs){const l=(i=a.key)!==null&&i!==void 0?i:r[u];if(u+=1,l===void 0){a.logError("record-literal-needs-keys","Anonymous record element not legal here");continue}const c=a.value.getExpression(e);c0e.TD.isAtomic(c)?(o.push(c),s.kids[l]=c.value,s.typeDef.fields.push((0,c0e.mkFieldDef)(gat.atomicDef(c),l))):a.value.logError("illegal-record-property-type",`Record property '${a.key} is type '${c.type}', which is not a legal property value type`)}return(0,hat.computedExprValue)({value:s,dataType:s.typeDef,from:o})}getNextElement(e,r){const i=r.value;return i.node==="recordLiteral"?this.getRecord(e,Object.keys(i.kids)):this.getRecord(e,[])}}sd.RecordLiteral=Eat;var Aat=T&&T.__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]}),_at=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Aat(e,t,r);return _at(e,t),e};Object.defineProperty(Vb,"__esModule",{value:!0}),Vb.ArrayLiteral=void 0;const Cat=Qt,Sat=xt,f0e=vat(Zt),bat=sd;class Tat extends Sat.ExpressionDef{constructor(e){super(),this.elements=e,this.elementType="array literal",this.has({elements:e})}getExpression(e){const r=[],i=[];let s;if(this.elements.length>0)for(const l of this.elements){const c=s&&l instanceof bat.RecordLiteral?l.getNextElement(e,s):l.getExpression(e);if(i.push(c),c.type!=="error"){if(s){if(c.type!=="null"&&!f0e.typeEq(s,c)){l.logError("array-values-incompatible","All array elements must be same type");continue}}else c.type!=="null"&&(s=c);r.push(c.value)}}const o=f0e.atomicDef(s||{type:"number"}),u=o.type==="record"?{type:"array",elementTypeDef:{type:"record_element"},fields:o.fields}:{type:"array",elementTypeDef:o},a={node:"arrayLiteral",kids:{values:r},typeDef:u};return(0,Cat.computedExprValue)({dataType:u,value:a,from:i})}}Vb.ArrayLiteral=Tat;var Yb={};Object.defineProperty(Yb,"__esModule",{value:!0}),Yb.Timeframe=void 0;const Rat=Xe,Dat=Je;class Oat extends Dat.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,Rat.isTimestampUnit)(r)?r:"second"}}Yb.Timeframe=Oat;var qc={};Object.defineProperty(qc,"__esModule",{value:!0}),qc.ImportStatement=qc.ImportSelect=qc.ImportSourceName=void 0;const ak=Je;class Fat extends ak.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}qc.ImportSourceName=Fat;class wat extends ak.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}}qc.ImportSelect=wat;class Nat extends ak.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.logError("invalid-import-url","Invalid URL in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const i=e.childRequest(this.fullURL);if(i)return i}}execute(e){const r=this.translator();if(!r)this.logError("no-translator-for-import","Cannot import without translation context");else if(this.fullURL){const i=r.root.pretranslatedModels.get(this.fullURL),s=r.root.importZone.getEntry(this.fullURL);if(i||s.status==="present"){const o=r.getChildExports(this.fullURL);if(this.notEmpty())for(const u of this.list){const a=u.from||u;if(e.getEntry(u.text))u.logError("name-conflict-on-selective-import",`Cannot redefine '${u.text}'`);else if(o[a.text]){const l={...o[a.text]};u.from&&(l.as=u.text),e.setEntry(u.text,{entry:l,exported:!1})}else a.logError("selective-import-not-found",`Cannot find '${a.text}', not imported`)}else for(const[u,a]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(u)?this.logError("name-conflict-on-indiscriminate-import",`Cannot redefine '${u}'`):e.setEntry(u,{entry:a,exported:!1})}else s.status==="error"?this.logError("failed-import",`import failed: '${s.message}'`):this.logError("failed-import",`import failed with status: '${s.status}'`)}}}qc.ImportStatement=Nat;var Xy={};Object.defineProperty(Xy,"__esModule",{value:!0}),Xy.ExtendBlock=void 0;const Lat=Je,Iat=qn;class $at extends Lat.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Iat.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)for(const i of r.list)e.inputFS.extendSource(i)}}Xy.ExtendBlock=$at;var Kb={};Object.defineProperty(Kb,"__esModule",{value:!0}),Kb.Argument=void 0;const Bat=Je;class kat extends Bat.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}Kb.Argument=kat;var Jb={};Object.defineProperty(Jb,"__esModule",{value:!0}),Jb.HasParameter=void 0;const x0e=Xe,Mat=Je;class Pat extends Mat.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,x0e.isCastType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default}))}parameter(){var e;if(this.default!==void 0){const r=this.default.constantValue();return this.type&&this.type!==r.type&&r.type!=="null"&&r.type!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),r.type==="null"?this.type?{type:this.type,value:r.value,name:this.name}:(this.default.logError("parameter-null-default-without-declared-type","Default value cannot have type `null` unless parameter type is also specified"),{value:r.value,name:this.name,type:"error"}):!(0,x0e.isCastType)(r.type)&&r.type!=="error"?(this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${r.type}\``),{value:r.value,name:this.name,type:"error"}):{value:r.value,name:this.name,type:r.type}}return this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),{value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"}}}Jb.HasParameter=Pat;var Xb={};Object.defineProperty(Xb,"__esModule",{value:!0}),Xb.AnonymousQuery=void 0;const Uat=Je,jat=Mr;class qat extends Uat.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=jat.extendNoteMethod,this.has({queryExpr:e})}execute(e){const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("non-query-used-as-query","Cannot run this object as a query");return}const i={...r.query()},s=this.note||{};i.annotation&&(s.inherits=i.annotation),(s.notes||s.blockNotes||s.inherits)&&(i.annotation=s),e.queryList.push(i)}}Xb.AnonymousQuery=qat;var Qc={};Object.defineProperty(Qc,"__esModule",{value:!0}),Qc.View=void 0;const Qat=Je;class Hat extends Qat.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}}Qc.View=Hat;var Zb={};Object.defineProperty(Zb,"__esModule",{value:!0}),Zb.ViewArrow=void 0;const zat=Ur,Gat=Qc;class Wat extends Gat.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){const r=this.base.pipelineComp(e),i=new zat.StaticSourceSpace(r.outputStruct),s=this.operation.pipelineComp(i);return{pipeline:[...r.pipeline,...s.pipeline],outputStruct:s.outputStruct}}refine(e,r,i){return this.logError("refinement-with-multistage-view","A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}Zb.ViewArrow=Wat;var eT={},Zy={};Object.defineProperty(Zy,"__esModule",{value:!0}),Zy.refine=void 0;const lk=ji,Vat=lt,ck=Fc;function Yat(t,e,r){var i,s;if(e.length!==1)return t.logError("refinement-with-multistage-view","Named refinements of multi-stage views are not supported"),e;const o={...e[0]},u=r;if((0,lk.isRawSegment)(o))t.logError("refinement-of-raw-query","Cannot refine raw query, must add an explicit query stage");else if(o.type==="partial"&&u.type!=="index"&&u.type!=="raw"?o.type=u.type:u.type!==o.type&&t.logError("mismatched-view-types-for-refinement",`cannot refine ${o.type} view with ${u.type} view`),u.type!=="index"&&o.type!=="index"&&u.type!=="raw"&&(u.orderBy!==void 0&&!u.defaultOrderBy&&(o.orderBy===void 0||o.defaultOrderBy?o.orderBy=u.orderBy:t.logError("ordering-overridden-in-refinement","refinement cannot override existing ordering")),u.limit!==void 0&&(o.limit===void 0?o.limit=u.limit:t.logError("limit-overridden-in-refinement","refinement cannot override existing limit"))),o.filterList=o.filterList!==void 0||u.filterList!==void 0?[...(i=o.filterList)!==null&&i!==void 0?i:[],...(s=u.filterList)!==null&&s!==void 0?s:[]]:void 0,(0,lk.isQuerySegment)(u)&&(0,lk.isQuerySegment)(o)){const a=[],l=[],c=new Map(o.queryFields.map(f=>[(0,ck.nameFromDef)(f),f]));for(const f of u.queryFields)c.has((0,ck.nameFromDef)(f))?a.push(f):l.push(f);o.queryFields=[...o.queryFields,...l],a.length>0&&t.logError("name-conflict-in-refinement",`overlapping fields in refinement: ${a.map(ck.nameFromDef)}`),o.compositeFieldUsage=(0,Vat.mergeCompositeFieldUsage)(o.compositeFieldUsage,u.compositeFieldUsage)}else u.type==="index"&&o.type==="index"&&(o.indexFields=[...u.indexFields,...o.indexFields]);return[o]}Zy.refine=Yat,Object.defineProperty(eT,"__esModule",{value:!0}),eT.ViewRefine=void 0;const Kat=li,Jat=Ps,Xat=Zy,Zat=Qc;class elt extends Zat.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){const i=this.base.pipelineComp(e),s=this.refinement.refine(e,i.pipeline,r);return{pipeline:s,annotation:i.annotation,outputStruct:s.length>0?(0,Jat.getFinalStruct)(this.refinement,e.structDef(),s):Kat.ErrorFactory.structDef}}refine(e,r,i){const s=this.pipeline(e,i);return s.length!==1?(this.refinement.logError("refinement-with-multistage-view","refinement must have exactly one stage"),r):(0,Xat.refine)(this,r,s[0])}getImplicitName(){return this.base.getImplicitName()}}eT.ViewRefine=elt;var tT={};Object.defineProperty(tT,"__esModule",{value:!0}),tT.ReferenceView=void 0;const fk=Xe,d0e=li,tlt=Ps,nlt=Pr,rlt=Zy,ilt=Qc;class slt extends ilt.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,r){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:r}={forRefinement:!1}){const i=this.reference.getField(e),s=function(){return{inputStruct:d0e.ErrorFactory.structDef,outputStruct:d0e.ErrorFactory.structDef,pipeline:[],error:!0}};if(!i.found)return this.reference.logError(i.error.code,i.error.message),s();if(!(i.found instanceof nlt.SpaceField))throw new Error("Expected space field");const o=i.found.fieldDef();if(o===void 0)throw new Error("Expected field to have definition");if((0,fk.isAtomic)(o)){const u={type:"reduce",queryFields:[this.reference.refToField],compositeFieldUsage:o.compositeFieldUsage},a=this.reference.nameString,l={...(0,fk.sourceBase)(e.structDef()),type:"query_result",name:a,fields:[o]};return{pipeline:[u],name:a,outputStruct:l}}else return(0,fk.isTurtle)(o)?this.reference.list.length>1?(r?this.logError("refinement-with-joined-view","Cannot use view from join as refinement"):this.logError("nest-of-joined-view","Cannot use view from join"),s()):{pipeline:[...o.pipeline],name:o.name,annotation:o.annotation,outputStruct:(0,tlt.getFinalStruct)(this.reference,e.structDef(),o.pipeline)}:(r?this.reference.logError("refinement-with-source",`named refinement \`${this.reference.refString}\` must be a view, found a ${o.type}`):this.reference.logError("nest-of-source","This operation is not supported"),s())}getRefinementSegment(e){const{pipeline:r,error:i}=this._pipelineComp(e,{forRefinement:!0});if(!i){if(r.length!==1){this.reference.logError("refinement-with-multistage-view",`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,i){const s=this.getRefinementSegment(e);return s?(0,rlt.refine)(this,r,s):r}getImplicitName(){return this.reference.nameString}}tT.ReferenceView=slt;var nT={},eE={},rT={},tE={};Object.defineProperty(tE,"__esModule",{value:!0}),tE.Index=void 0;const olt=Je,ult=qn;class alt extends olt.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=ult.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}}tE.Index=alt;var nE={};Object.defineProperty(nE,"__esModule",{value:!0}),nE.SampleProperty=void 0;const llt=Je,h0e=qn;class clt extends llt.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=h0e.LegalRefinementStage.Tail,this.forceQueryClass=h0e.QueryClass.Index}sampling(){return this.sample}}nE.SampleProperty=clt;var iT={};Object.defineProperty(iT,"__esModule",{value:!0}),iT.IndexFieldSpace=void 0;const p0e=lt,m0e=Xe,xk=yt,flt=Pr,xlt=mu,dlt=Iy,hlt=Ur;class plt extends xlt.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const r of e)r instanceof xk.FieldReference?super.pushFields(r):r instanceof xk.WildcardFieldReference?this.addWild(r):r.logError("invalid-field-in-index-query","Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.logError("refinement-of-index-segment","index query operations cannot be refined"),{type:"index",indexFields:[]};let r=(0,p0e.emptyCompositeFieldUsage)(),i=(0,p0e.emptyNarrowedCompositeFieldResolution)();const s=[],o=this.inputSpace().structDef();for(const[u,a]of this.entries())if(a instanceof flt.SpaceField){let l,c;const f=this.expandedWild[u];if(f)s.push({type:"fieldref",path:f.path}),l=f.entry.typeDesc().compositeFieldUsage;else if(a instanceof dlt.ReferenceField){const h=a.fieldRef,p=h.getField(this.exprSpace);p.error?h.logError(p.error.code,p.error.message):(s.push(h.refToField),l=p.found.typeDesc().compositeFieldUsage,c=h)}const x=this.applyNextCompositeFieldUsage(o,r,i,l,c);r=x.compositeFieldUsage,i=x.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,{type:"index",indexFields:s}}addRefineFromFields(e){}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof hlt.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-found",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries()){if(e.except.has(a)||l.refType==="parameter")continue;const c=xk.IndexFieldReference.indexOutputName([...s,a]);if(this.entry(c)){const f=(r=this.expandedWild[c].path)===null||r===void 0?void 0:r.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${f?` (conflicts with ${f})`:""}`)}else{const f=l.typeDesc();m0e.TD.isLeafAtomic(f)&&(0,m0e.expressionIsScalar)(f.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:c,entry:l}),this.expandedWild[c]={path:s.concat(a),entry:l})}}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.setEntry(a.name,a.entry)}}iT.IndexFieldSpace=plt,Object.defineProperty(rT,"__esModule",{value:!0}),rT.IndexBuilder=void 0;const dk=Xe,mlt=li,glt=Da,ylt=tE,Elt=Mc,Alt=nE,_lt=iT,hk=lt;class vlt{constructor(e,r,i,s){this.filters=[],this.alwaysJoins=[],this.type="index",this.resultFS=new _lt.IndexFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof glt.Filter?e.queryExecute(this):e instanceof Elt.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof ylt.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.logError("index-by-already-specified","Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof Alt.SampleProperty?this.sample=e.sampling():e.logError("illegal-operation-for-index","Not legal in an index query operation")}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}finalize(e){var r;if(e&&!(0,dk.isIndexSegment)(e)&&!(0,dk.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),mlt.ErrorFactory.indexSegment;const i=this.resultFS.getPipeSegment(e),s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?i.filterList=this.filters:s&&(i.filterList=[...s,...this.filters]),e!=null&&e.limit&&(i.limit=e.limit),this.limit&&(i.limit=this.limit.limit),this.indexOn&&(i.weightMeasure=this.indexOn.refString),e&&(0,dk.isIndexSegment)(e)&&(e!=null&&e.sample)&&(i.sample=e.sample),this.sample&&(i.sample=this.sample),this.alwaysJoins.length>0&&(i.alwaysJoins=[...this.alwaysJoins]);const o=e&&e.type==="index"&&(r=e.compositeFieldUsage)!==null&&r!==void 0?r:(0,hk.emptyCompositeFieldUsage)();return i.compositeFieldUsage=(0,hk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage),i}}rT.IndexBuilder=vlt;var sT={},rE={};Object.defineProperty(rE,"__esModule",{value:!0}),rE.GroupBy=void 0;const Clt=Ms,g0e=qn;class Slt extends Clt.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=g0e.LegalRefinementStage.Single,this.forceQueryClass=g0e.QueryClass.Grouping}}rE.GroupBy=Slt;var oT={};Object.defineProperty(oT,"__esModule",{value:!0}),oT.ProjectFieldSpace=void 0;const uT=Xe,blt=mu;class Tlt extends blt.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e===void 0||!uT.TD.isAtomic(e)||(0,uT.expressionIsAggregate)(e.expressionType)?!1:(0,uT.expressionInvolvesAggregate)(e.expressionType)&&(0,uT.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}oT.ProjectFieldSpace=Tlt;var Hc={},od={};Object.defineProperty(od,"__esModule",{value:!0}),od.Ordering=od.OrderBy=void 0;const Rlt=Xe,y0e=Pc,E0e=Je,Dlt=qn;class Olt extends E0e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof y0e.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var r;if(this.field instanceof y0e.FieldName&&e.isQueryFieldSpace()){const s=e.outputSpace(),o=this.field.getField(s);o.error&&this.field.logError(o.error.code,o.error.message),(!o.found||!o.isOutputField)&&this.logError("order-by-not-found-in-output",`Unknown field ${this.field.refString} in output space`),(0,Rlt.expressionIsAnalytic)((r=o.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.logError("order-by-analytic",`Illegal order by of analytic field ${this.field.refString}`)}const i={field:this.modelField};return this.dir&&(i.dir=this.dir),i}}od.OrderBy=Olt;class Flt extends E0e.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Dlt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}}od.Ordering=Flt,Object.defineProperty(Hc,"__esModule",{value:!0}),Hc.ReduceBuilder=Hc.QuerySegmentBuilder=void 0;const gu=Xe,wlt=li,Nlt=Pc,Llt=Mc,Ilt=od,$lt=mu,Blt=Ms,pk=lt;function A0e(t){return t.type==="fieldref"?t.path[t.path.length-1]:t.name}class _0e{constructor(){this.alwaysJoins=[],this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}e instanceof Blt.DefinitionList?this.resultFS.pushFields(...e.list):e instanceof Llt.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof Ilt.Ordering&&(this.order?e.logError("ordering-already-specified","Query operation already sorted"):this.order=e)}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}refineFrom(e,r){var i;e&&e.type!=="index"&&e.type!=="raw"&&(!this.limit&&e.orderBy&&!e.defaultOrderBy&&(r.orderBy=e.orderBy),!this.limit&&e.limit&&(r.limit=e.limit)),this.order&&(r.orderBy=this.order.getOrderBy(this.inputFS),delete r.defaultOrderBy),this.limit&&(r.limit=this.limit);const s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?r.filterList=this.filters:s&&(r.filterList=[...s,...this.filters]),this.alwaysJoins.length>0&&(r.alwaysJoins=[...this.alwaysJoins]);const o=e&&(0,gu.isQuerySegment)(e)&&(i=e.compositeFieldUsage)!==null&&i!==void 0?i:(0,pk.emptyCompositeFieldUsage)();r.compositeFieldUsage=(0,pk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage)}}Hc.QuerySegmentBuilder=_0e;class klt extends _0e{constructor(e,r,i,s){super(),this.type="grouping",this.resultFS=new $lt.ReduceFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,gu.isReduceSegment)(e)||(0,gu.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-reduce-refinement",`Can't refine reduce with ${e.type}`),wlt.ErrorFactory.reduceSegment;const i=this.resultFS.getQuerySegment(r);if(this.refineFrom(r,i),i.orderBy){for(const s of i.orderBy)if(typeof s.field=="number"){const o=i.queryFields[s.field-1];s.field=A0e(o)}}if(i.orderBy===void 0||i.defaultOrderBy){let s;for(const o of i.queryFields){let u=!1,a=!1,l;const c=A0e(o);if(o.type==="fieldref"){const f=o.path.map(h=>new Nlt.FieldName(h)),x=this.inputFS.lookup(f).found;if(x){const h=x.typeDesc();l=h.type,u=(0,gu.expressionIsAggregate)(h.expressionType),a=(0,gu.expressionIsAnalytic)(h.expressionType)}else continue}else l=o.type,u=(0,gu.hasExpression)(o)&&(0,gu.expressionIsAggregate)(o.expressionType),a=(0,gu.hasExpression)(o)&&(0,gu.expressionIsAnalytic)(o.expressionType);if((0,gu.isTemporalType)(l)||u){i.defaultOrderBy=!0,i.orderBy=[{field:c,dir:"desc"}],s=void 0;break}(0,gu.canOrderBy)(l)&&!a&&!s&&(s=c)}s&&(i.defaultOrderBy=!0,i.orderBy=[{field:s,dir:"asc"}])}return i}}Hc.ReduceBuilder=klt,Object.defineProperty(sT,"__esModule",{value:!0}),sT.ProjectBuilder=void 0;const v0e=Xe,Mlt=li,Plt=rE,Ult=oT,jlt=Hc;class qlt extends jlt.QuerySegmentBuilder{constructor(e,r,i,s){super(),this.type="project",this.resultFS=new Ult.ProjectFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Plt.GroupBy?e.logError("illegal-operation-in-select-segment","Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,v0e.isProjectSegment)(e)||(0,v0e.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),Mlt.ErrorFactory.projectSegment;const i=this.resultFS.getQuerySegment(r);return this.refineFrom(r,i),i}}sT.ProjectBuilder=qlt;var aT={};Object.defineProperty(aT,"__esModule",{value:!0}),aT.PartialBuilder=void 0;const Qlt=ji,Hlt=Hc;class zlt extends Hlt.ReduceBuilder{finalize(e){const r=super.finalize(e);if((0,Qlt.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}}aT.PartialBuilder=zlt,Object.defineProperty(eE,"__esModule",{value:!0}),eE.QOpDesc=void 0;const Glt=rT,Wlt=sT,Vlt=Hc,Ylt=Je,Klt=Ps,Jlt=Ur,ud=qn,Xlt=aT;class Zlt extends Ylt.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,i=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=ud.QueryClass.Grouping:this.refineThis.type==="project"?r=ud.QueryClass.Project:this.refineThis.type==="index"&&(r=ud.QueryClass.Index));for(const s of this.list)s.forceQueryClass&&(r?r!==s.forceQueryClass&&s.logError(`illegal-${r}-operation`,`Not legal in ${r} query`):r=s.forceQueryClass),i||(i=(e=s.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&i&&(this.logError("ambiguous-view-type",{}),r=ud.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,i){switch(this.computeType()){case ud.QueryClass.Grouping:return new Vlt.ReduceBuilder(e,this.refineThis,r,i);case ud.QueryClass.Project:return new Wlt.ProjectBuilder(e,this.refineThis,r,i);case ud.QueryClass.Index:return new Glt.IndexBuilder(e,this.refineThis,r,i);case void 0:return new Xlt.PartialBuilder(e,this.refineThis,r,i)}}getOp(e,r){const i=this.getBuilder(e,r,this);for(const o of this.list)i.execute(o);const s=i.finalize(this.refineThis);return{segment:s,outputSpace:()=>new Jlt.StaticSourceSpace((0,Klt.opOutputStruct)(this,e.structDef(),s))}}}eE.QOpDesc=Zlt,Object.defineProperty(nT,"__esModule",{value:!0}),nT.QOpDescView=void 0;const e0t=Xe,t0t=Ur,C0e=eE,n0t=Ps,mk=qn,r0t=Qc;class i0t extends r0t.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){const i=this.operation.getOp(e,r);return{pipeline:[i.segment],outputStruct:i.outputSpace().structDef()}}getOp(e,r,i,s){return(0,e0t.isRawSegment)(s)?(this.logError("refinement-of-raw-query","A raw query cannot be refined"),s):(i.refineFrom(s),i.getOp(e,r).segment)}refine(e,r,i){const s=[...r];if(s.length===0)return s;if(s.length===1)return this.operation.refineFrom(s[0]),[this.getOp(e,i,this.operation,s[0])];const o=new C0e.QOpDesc([]),u=new C0e.QOpDesc([]);for(const a of this.operation.list)switch(a.queryRefinementStage){case mk.LegalRefinementStage.Head:o.push(a);break;case mk.LegalRefinementStage.Single:a.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case mk.LegalRefinementStage.Tail:u.push(a);break;default:a.logError("illegal-refinement-operation","Illegal query refinement")}if(o.notEmpty()&&(this.has({headRefinements:o}),s[0]=this.getOp(e,void 0,o,s[0])),u.notEmpty()){const a=s.length-1;this.has({tailRefinements:u});const l=(0,n0t.getFinalStruct)(this,e.structDef(),s.slice(-1));s[a]=this.getOp(new t0t.StaticSourceSpace(l),void 0,u,s[a])}return s}getImplicitName(){}}nT.QOpDescView=i0t;var Dn={},s0t=T&&T.__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]}),o0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),u0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&s0t(e,t,r);return o0t(e,t),e};Object.defineProperty(Dn,"__esModule",{value:!0}),Dn.FieldDefinitionValue=Dn.DefSpace=Dn.DimensionFieldDeclaration=Dn.MeasureFieldDeclaration=Dn.DeclareFieldDeclaration=Dn.ProjectFieldDeclaration=Dn.GroupByFieldDeclaration=Dn.AggregateFieldDeclaration=Dn.CalculateFieldDeclaration=Dn.AtomicFieldDeclaration=void 0;const gk=Xe,S0e=u0t(Zt),a0t=l2,l0t=Je,ad=sr,c0t=Mr,f0t=Pr;class zc extends l0t.MalloyElement{constructor(e,r,i){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=i,this.isNoteableObj=!0,this.extendNote=c0t.extendNoteMethod}getName(){return this.defineName}fieldDef(e,r){return this.queryFieldDef(new yk(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let i;function s(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const u=this.executesInOutputSpace()?s():e;i=this.expr.getExpression(u)}catch(u){return this.logError("failed-field-definition",`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}if(i.type==="null"&&(this.expr.logWarning("null-typed-field-definition",'null value defaults to type number, use "null::TYPE" to specify correct type'),i={type:"number",value:i.value,expressionType:i.expressionType,evalSpace:i.evalSpace,compositeFieldUsage:i.compositeFieldUsage}),(0,gk.isAtomicFieldType)(i.type)&&i.type!=="error"){this.typecheckExprValue(i);const u=(0,gk.mkFieldDef)(S0e.atomicDef(i),r);return(u.type==="date"||u.type==="timestamp")&&(0,a0t.isGranularResult)(i)&&(u.timeframe=i.timeframe),u.location=this.location,u.e=i.value,u.compositeFieldUsage=i.compositeFieldUsage,i.expressionType&&(u.expressionType=i.expressionType),this.exprSrc&&(u.code=this.exprSrc),this.note&&(u.annotation=this.note),u}if(!(e instanceof yk&&e.foundCircle)&&i.type!=="error"){const u=S0e.inspect(i);this.logError("invalid-type-for-field-definition",`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new b0e(e,this))}}Dn.AtomicFieldDeclaration=zc;class x0t extends zc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}Dn.CalculateFieldDeclaration=x0t;class d0t extends zc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckAggregate)(e,this)}}Dn.AggregateFieldDeclaration=d0t;class h0t extends zc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckGroupBy)(e,this)}}Dn.GroupByFieldDeclaration=h0t;class p0t extends zc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckProject)(e,this)}}Dn.ProjectFieldDeclaration=p0t;class m0t extends zc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckDeclare)(e,this)}}Dn.DeclareFieldDeclaration=m0t;class g0t extends zc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckMeasure)(e,this)}}Dn.MeasureFieldDeclaration=g0t;class y0t extends zc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,ad.typecheckDimension)(e,this)}}Dn.DimensionFieldDeclaration=y0t;class yk{constructor(e,r){this.realFS=e,this.circular=r,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:{message:`Circular reference to '${this.circular.defineName}' in definition`,code:"circular-reference-in-field-definition"},found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectName(){return this.realFS.dialectName()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}isProtectedAccessSpace(){return!0}}Dn.DefSpace=yk;class b0e extends f0t.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){var e;const r=(e=this.defInSource)!==null&&e!==void 0?e:this.exprDef.fieldDef(this.space,this.name);return this.defInSource=r,r}getQueryFieldDef(e){if(!this.defInQuery){const r=this.exprDef.queryFieldDef(e,this.name);this.defInQuery=r}return this.defInQuery}typeDesc(){const e=this.defInQuery||this.fieldDef();if((0,gk.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}entryType(){return(this.defInQuery||this.fieldDef()).type}}Dn.FieldDefinitionValue=b0e;var lT={};Object.defineProperty(lT,"__esModule",{value:!0}),lT.Aggregate=void 0;const E0t=Ms,T0e=qn;class A0t extends E0t.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=T0e.LegalRefinementStage.Single,this.forceQueryClass=T0e.QueryClass.Grouping}}lT.Aggregate=A0t;var cT={};Object.defineProperty(cT,"__esModule",{value:!0}),cT.Calculate=void 0;const _0t=Ms,v0t=qn;class C0t extends _0t.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=v0t.LegalRefinementStage.Single}}cT.Calculate=C0t;var iE={};Object.defineProperty(iE,"__esModule",{value:!0}),iE.Dimensions=void 0;const S0t=wc;class b0t extends S0t.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}iE.Dimensions=b0t;var sE={};Object.defineProperty(sE,"__esModule",{value:!0}),sE.Measures=void 0;const T0t=wc;class R0t extends T0t.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}sE.Measures=R0t;var fT={};Object.defineProperty(fT,"__esModule",{value:!0}),fT.Nests=void 0;const D0t=Ms,R0e=qn;class O0t extends D0t.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=R0e.LegalRefinementStage.Single,this.forceQueryClass=R0e.QueryClass.Grouping}}fT.Nests=O0t;var xT={};Object.defineProperty(xT,"__esModule",{value:!0}),xT.ProjectStatement=void 0;const F0t=Ms,D0e=qn;class w0t extends F0t.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=D0e.QueryClass.Project,this.queryRefinementStage=D0e.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}xT.ProjectStatement=w0t;var Gc={},Zl={},Bn={};Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.getPlainString=Bn.unIndent=Bn.getOptionalId=Bn.idToStr=Bn.getId=Bn.getStringParts=Bn.getStringIfShort=Bn.getShortString=void 0;const O0e=Zo;function F0e(t){var e,r;const i=((e=t.DQ_STRING())===null||e===void 0?void 0:e.text)||((r=t.SQ_STRING())===null||r===void 0?void 0:r.text);return i?O0e.ParseUtil.parseString(i,i[0]):""}Bn.getShortString=F0e;function w0e(t){const e=t.string().shortString();if(e)return F0e(e)}Bn.getStringIfShort=w0e;function*N0e(t){var e;if(t){for(const i of t.sqlInterpolation()){const s=i.OPEN_CODE().text;s.length>2&&(yield s.slice(0,s.length-2)),i.sqExpr()&&(yield i.sqExpr())}const r=(e=t.SQL_END())===null||e===void 0?void 0:e.text.slice(0,-3);r&&r.length>0&&(yield r)}}Bn.getStringParts=N0e;function L0e(t){return I0e(t.id())}Bn.getId=L0e;function I0e(t){const e=t.BQ_STRING();return e?O0e.ParseUtil.parseString(e.text,"`"):t.text}Bn.idToStr=I0e;function N0t(t){function e(r){return"id"in r}if(e(t)&&t.id())return L0e(t)}Bn.getOptionalId=N0t;function*$0e(t){for(;t.length>0;){const e=t.match(/^.*?\r?\n/);let r=t;e&&(r=e[0]),yield r,t=t.slice(r.length)}}function L0t(t){let e;for(const r of $0e(t)){const i=r.match(/^( *).*[^\s]/);if(i){const s=i[1].length;(e===void 0||s<e)&&(e=s)}}return e}function B0e(t){let e;for(const r of t)if(typeof r=="string"){const i=L0t(r);i!==void 0&&(e===void 0||i<e)&&(e=i)}if(e)for(let r=0;r<=t.length;r+=1){const i=t[r];if(typeof i=="string"){let s="";for(let o of $0e(i))o[0]===" "&&(o=o.slice(e)),s+=o;t[r]=s}}}Bn.unIndent=B0e;function I0t(t,e=!1){const r=[],i=w0e(t);if(i)return[i,r];const s=[],o=t.string().sqlString();if(o){for(const u of N0e(o))if(typeof u=="string")s.push(u);else if(r.push(u),e)return[void 0,r];return B0e(s),[s.join(""),r]}return["",r]}Bn.getPlainString=I0t,Object.defineProperty(Zl,"__esModule",{value:!0}),Zl.findReferences=Zl.deprecatedParseTableURI=Zl.constructTableKey=void 0;const $0t=ac,Ek=Bn;function Ak(t){const e=(0,Ek.getStringIfShort)(t);if(e)return e;const r=[],i=t.string().sqlString();if(i){for(const s of(0,Ek.getStringParts)(i))typeof s=="string"&&r.push(s);return r.join("")}return""}class B0t{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,i){const s=k0e(e,r);this.needTables[s]||(this.needTables[s]={connectionName:e,tablePath:r,firstReference:i})}enterTableMethod(e){const r=(0,Ek.getId)(e.connectionId()),i=Ak(e.tablePath()),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterTableFunction(e){const r=Ak(e.tableURI()),{connectionName:i,tablePath:s}=M0e(r),o=this.trans.rangeFromContext(e);this.registerTableReference(i,s,o)}enterImportURL(e){const r=Ak(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}}function k0e(t,e){return t===void 0?e:`${t}:${e}`}Zl.constructTableKey=k0e;function M0e(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,r,i]=e;return{connectionName:r,tablePath:i}}else return{tablePath:t}}Zl.deprecatedParseTableURI=M0e;function k0t(t,e,r){const i=new B0t(t,e),s=i;return $0t.ParseTreeWalker.DEFAULT.walk(s,r),{tables:i.needTables,urls:i.needImports}}Zl.findReferences=k0t,Object.defineProperty(Gc,"__esModule",{value:!0}),Gc.TableFunctionSource=Gc.TableMethodSource=Gc.TableSource=void 0;const P0e=Zl,M0t=Eo,U0e=li;class _k extends M0t.Source{getSourceDef(){var e,r,i;const s=this.getTableInfo();if(s===void 0)return U0e.ErrorFactory.structDef;const{tablePath:o,connectionName:u}=s,a=(0,P0e.constructTableKey)(u,o),l=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(a);let c=`Schema read failure for table '${o}' for connection '${u}'`;if(l){if(l.status==="present"){(r=this.document())===null||r===void 0||r.checkExperimentalDialect(this,l.value.dialect),l.value.location=this.location,l.value.fields.forEach(x=>{x.location=this.location});const f={...l.value,fields:l.value.fields.map(x=>({...x,location:this.location})),location:this.location};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(f),f}l.status==="error"&&(c=l.message)}return this.logError("failed-to-fetch-table-schema",c),U0e.ErrorFactory.structDef}}Gc.TableSource=_k;class P0t extends _k{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.logError("invalid-connection-for-table-source",`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}Gc.TableMethodSource=P0t;class U0t extends _k{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,P0e.deprecatedParseTableURI)(this.tableURI)}}Gc.TableFunctionSource=U0t;var dT={};Object.defineProperty(dT,"__esModule",{value:!0}),dT.SQLString=void 0;const j0t=Je,j0e=hu;class q0t extends j0t.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(Q0t)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof j0e.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.logError("invalid-sql-source-interpolation","This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const r of this.elements)if(typeof r=="string")e.push({sql:r});else{const i=r.getQuery();i?e.push(i.query()):r.sqLog("failed-to-expand-sql-source","Cannot expand into a query")}return e}}dT.SQLString=q0t;function Q0t(t){return t instanceof j0e.SourceQueryElement}var hT={};Object.defineProperty(hT,"__esModule",{value:!0}),hT.SourceDesc=void 0;const H0t=Je;class z0t extends H0t.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}hT.SourceDesc=z0t;var pT={};Object.defineProperty(pT,"__esModule",{value:!0}),pT.isSourceProperty=void 0;const G0t=Da,W0t=wc,V0t=n2,Y0t=Lc,K0t=r2,J0t=i2,X0t=s2,Z0t=Nc,ect=hs;function tct(t){return t instanceof G0t.Filter||t instanceof ect.JoinStatement||t instanceof W0t.DeclareFields||t instanceof V0t.FieldListEdit||t instanceof Y0t.Renames||t instanceof K0t.PrimaryKey||t instanceof Z0t.ObjectAnnotation||t instanceof J0t.Views||t instanceof X0t.TimezoneStatement}pT.isSourceProperty=tct;var mT={};Object.defineProperty(mT,"__esModule",{value:!0}),mT.isFieldCollectionMember=void 0;const nct=Dn,q0e=yt;function rct(t){return t instanceof q0e.FieldReference||t instanceof q0e.WildcardFieldReference||t instanceof nct.AtomicFieldDeclaration}mT.isFieldCollectionMember=rct;var gT={};Object.defineProperty(gT,"__esModule",{value:!0}),gT.isQueryElement=void 0;const ict=o2,sct=u2,oct=jy,uct=qy;function act(t){return t instanceof ict.QueryArrow||t instanceof sct.QueryRefine||t instanceof oct.QueryReference||t instanceof uct.QueryRaw}gT.isQueryElement=act;var Q0e={};Object.defineProperty(Q0e,"__esModule",{value:!0});var yT={};Object.defineProperty(yT,"__esModule",{value:!0}),yT.isQueryProperty=void 0;function lct(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}yT.isQueryProperty=lct;var ET={};Object.defineProperty(ET,"__esModule",{value:!0}),ET.isQueryExtendProperty=void 0;const cct=iE,fct=hs,xct=sE;function dct(t){return t instanceof cct.Dimensions||t instanceof xct.Measures||t instanceof fct.JoinStatement}ET.isQueryExtendProperty=dct;var AT={};Object.defineProperty(AT,"__esModule",{value:!0}),AT.isFieldPropStatement=void 0;const hct=kc,pct=Da,mct=Mc,gct=h2;function yct(t){return t instanceof pct.Filter||t instanceof mct.Limit||t instanceof gct.PartitionBy||t instanceof hct.FunctionOrdering}AT.isFieldPropStatement=yct,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__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(Ty,t),r(Jp,t),r(Xp,t),r(Eo,t),r(Oy,t),r(hu,t),r(eb,t),r(tb,t),r(ib,t),r(By,t),r(sb,t),r(ob,t),r(du,t),r(n2,t),r(r2,t),r(Lc,t),r(i2,t),r(s2,t),r(ab,t),r(f2,t),r(cb,t),r(kc,t),r(fb,t),r(Jl,t),r(xb,t),r(d2,t),r(db,t),r(hb,t),r(pb,t),r(Kl,t),r(mb,t),r(gb,t),r(Eb,t),r(Vy,t),r(Gy,t),r(nd,t),r(_b,t),r(vb,t),r(Sb,t),r(Tb,t),r(Rb,t),r(Db,t),r(Ob,t),r(Uc,t),r(wb,t),r(Nb,t),r(Lb,t),r($b,t),r(Bb,t),r(kb,t),r(Mb,t),r(Ub,t),r(Qb,t),r(Sr,t),r(Gb,t),r(h2,t),r(m2,t),r(y2,t),r(Vb,t),r(sd,t),r(Bc,t),r(Yb,t),r(Yy,t),r(qc,t),r(Xy,t),r(Kb,t),r(Jb,t),r(Xb,t),r(u2,t),r(o2,t),r(Qc,t),r(Zb,t),r(eT,t),r(tT,t),r(nT,t),r(Dn,t),r(yt,t),r(lT,t),r(cT,t),r(wc,t),r(iE,t),r(Xy,t),r(Da,t),r(rE,t),r(tE,t),r(hs,t),r(Ry,t),r(Mc,t),r(sE,t),r(Ty,t),r(fT,t),r(od,t),r(xT,t),r(eE,t),r(nE,t),r(a2,t),r(td,t),r(Qy,t),r(Gc,t),r(dT,t),r(Nc,t),r(pu,t),r(hT,t),r(pT,t),r(xt,t),r(mT,t),r(Pc,t),r(Je,t),r(gT,t),r(Q0e,t),r(yT,t),r(ET,t),r(AT,t)}(W4);var _T={},A2={};Object.defineProperty(A2,"__esModule",{value:!0}),A2.ConstantExpression=A2.ConstantFieldSpace=void 0;const Ect=xt;class H0e{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:{message:"Only constants allowed in parameter default values",code:"illegal-reference-in-parameter-default"},found:void 0}}entries(){return[]}entry(){}dialectName(){return"~constant-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}A2.ConstantFieldSpace=H0e;class Act extends Ect.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new H0e),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}apply(e,r,i){return this.expr.apply(e,r,i)}requestExpression(e){return this.expr.requestExpression(e)}}A2.ConstantExpression=Act;var _ct=T&&T.__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]}),vct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Cct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&_ct(e,t,r);return vct(e,t),e};Object.defineProperty(_T,"__esModule",{value:!0}),_T.MalloyToAST=void 0;const z0e=hy,Sct=Jh,re=Cct(W4),vk=Vp,G0e=Er,bct=W4,Yn=Bn,Ck=Xe,Tct=Zo,Rct=A2,W0e=Vn;class V0e extends re.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class Sk extends re.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const Dct=["##! m4warnings=error"];class Oct extends Sct.AbstractParseTreeVisitor{constructor(e,r,i){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=i;for(const s of Dct){const o=Tct.Tag.fromTagLine(s,0,this.compilerFlags);this.compilerFlags=o.tag}}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}astError(e,r,i,s){this.msgLog.log((0,vk.makeLogMessage)(r,i,{at:e.location,...s}))}rangeFromContext(e){return(0,W0e.rangeFromContext)(this.parseInfo.sourceInfo,e)}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new G0e.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,r,i,s){this.msgLog.log((0,vk.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}warnWithReplacement(e,r,i,s){this.msgLog.log((0,vk.makeLogMessage)(e,r,{at:{url:this.parseInfo.sourceURL,range:i},severity:"warn",replacement:s}))}inExperiment(e,r){const i=this.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(this.contextError(r,"experiment-not-enabled",{experimentId:e}),!1)}m4Severity(){const e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,r,i){const s=this.m4Severity();s&&this.contextError(e,r,i,{severity:s})}only(e,r,i){const s=[];for(const o of e){const u=r(o);u?s.push(u):o instanceof Sk||this.astError(o,"unexpected-statement-in-translation",`Parser enountered unexpected statement type '${o.elementType}' when it needed '${i}'`)}return s}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new re.FieldName((0,Yn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new re.ModelEntryReference((0,Yn.getId)(e)),e.id())}defaultResult(){return new re.Unimplemented}astAt(e,r){return e.location={url:this.parseInfo.sourceURL,range:this.rangeFromContext(r)},e}getSourceCode(e){const r=e.start.startIndex,i=e.stop||e.start,s=new G0e.Interval(r,i.stopIndex);return this.parseInfo.sourceStream.getText(s)}getFilterElement(e){const r=this.getFieldExpr(e),i=new re.FilterElement(r,this.getSourceCode(e));return this.astAt(i,e)}getFieldDefs(e,r){return e.map(i=>this.getFieldDef(i,r))}getFieldExpr(e){const r=this.visit(e);if(r instanceof re.ExpressionDef)return this.astAt(r,e);throw this.internalError(e,`expression node unknown type '${r.elementType}'`)}getPlainStringFrom(e){const[r,i]=(0,Yn.getPlainString)(e);for(const s of i)s instanceof z0e.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return r||""}makeSqlString(e,r){for(const i of e.sqlInterpolation())i.CLOSE_CODE()&&this.m4advisory(i,"percent-terminated-query-interpolation","Use %{ ... } instead of %{ ... }%");for(const i of(0,Yn.getStringParts)(e))i instanceof z0e.ParserRuleContext?r.push(this.visit(i)):r.push(i);r.complete(),this.astAt(r,e)}parseTime(e,r){let i=r(e.text);return i||(this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),i=new re.LiteralTimestamp({text:e.text})),this.astAt(i,e)}getNotes(e){return e.ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const r=this.only(e.malloyStatement().map(i=>this.visit(i)),i=>re.isDocStatementOrDocStatementList(i)&&i,"statement");return new re.Document(r)}visitDefineSourceStatement(e){const i=e.sourcePropertyList().sourceDefinition().map(u=>this.visitSourceDefinition(u)),s=this.getNotes(e.tags()),o=new re.DefineSourceList(i);return o.extendNote({blockNotes:s}),o}getSourceParameter(e){const r=e.fieldExpr(),i=r?this.astAt(new Rct.ConstantExpression(this.getFieldExpr(r)),r):void 0,s=e.malloyType(),o=s?this.getMalloyType(s):void 0;return this.astAt(new re.HasParameter({name:(0,Yn.getId)(e.parameterNameDef()),type:o,default:i}),e)}getSourceParameters(e){return e===void 0?[]:(this.inExperiment("parameters",e),e.sourceParameter().map(r=>this.getSourceParameter(r)))}visitSourceDefinition(e){const r=this.visit(e.sqExplore()),i=this.getSourceParameters(e.sourceParameters()),s=new re.DefineSource((0,Yn.getId)(e.sourceNameDef()),r instanceof re.SourceQueryElement?r:void 0,!0,i),o=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return s.extendNote({notes:o}),this.astAt(s,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>re.isSourceProperty(s)&&s,"source property");return new re.SourceDesc(r)}visitTableFunction(e){const r=this.getPlainStringFrom(e.tableURI()),i=this.astAt(new re.TableFunctionSource(r),e);return this.m4advisory(e,"table-function","`table('connection_name:table_path')` is deprecated; use `connection_name.table('table_path')`"),i}visitTableMethod(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=this.getPlainStringFrom(e.tablePath());return this.astAt(new re.TableMethodSource(i,s),e)}visitSqlSource(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=new re.SQLString,o=e.sqlString();o&&this.makeSqlString(o,s);const u=e.shortString();u&&s.push((0,Yn.getShortString)(u));const a=new re.SQLSource(i,s);return this.astAt(a,e)}visitDefJoinMany(e){const r=this.getAccessLabel(e.accessLabel()),i=[];for(const o of e.joinList().joinDef()){const u=this.visit(o);u instanceof re.Join&&(i.push(u),u instanceof re.ExpressionJoin?(u.joinType="many",u.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):u instanceof re.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const s=new re.JoinStatement(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),s}visitDefJoinOne(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof re.Join&&(s.push(u),u instanceof re.ExpressionJoin&&(u.joinType="one"));const o=new re.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}visitDefJoinCross(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof re.Join&&(s.push(u),u instanceof re.ExpressionJoin?u.joinType="cross":u.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const o=new re.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}getJoinList(e){return this.only(e.joinDef().map(r=>this.visit(r)),r=>r instanceof re.Join&&r,"join")}getJoinFrom(e){const r=e.isExplore(),i=this.getModelEntryName(e.joinNameDef());if(r){const o=this.getSqExpr(r.sqExpr()),u=this.getNotes(r._before_is).concat(this.getNotes(r._after_is));return{joinFrom:o,notes:u,joinAs:i}}const s=e.sourceArguments();return s?{joinFrom:this.astAt(new re.SQReference(i,this.getSQArguments(s)),e),notes:[],joinAs:i}:{joinAs:i,joinFrom:new re.SQReference(i),notes:[]}}visitQueryJoinStatement(e){return this.astAt(this.visit(e.joinStatement()),e)}visitJoinOn(e){var r;const{joinAs:i,joinFrom:s,notes:o}=this.getJoinFrom(e.joinFrom()),u=new re.ExpressionJoin(i,s),a=e.joinExpression(),l=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,Ck.isMatrixOperation)(l)?u.matrixOperation=l:this.contextError(e,"unknown-matrix-operation","Internal Error: Unknown matrixOperation"),a&&(u.joinOn=this.getFieldExpr(a)),u.extendNote({notes:this.getNotes(e).concat(o)}),this.astAt(u,e)}visitJoinWith(e){const{joinAs:r,joinFrom:i,notes:s}=this.getJoinFrom(e.joinFrom()),o=this.getFieldExpr(e.fieldExpr()),u=new re.KeyJoin(r,i,o);return u.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(u,e)}getFieldDef(e,r){const i=e.fieldExpr(),s=(0,Yn.getId)(e.fieldNameDef()),o=this.getFieldExpr(i),u=new r(o,s,this.getSourceCode(i)),a=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return u.extendNote({notes:a}),this.astAt(u,e)}visitDefDimensions(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),re.DimensionFieldDeclaration),s=new re.Dimensions(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}getAccessLabel(e){if(e!==void 0){if(e.INTERNAL_KW())return"internal";if(e.PRIVATE_KW())return"private";if(e.PUBLIC_KW())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}getAccessLabelProp(e){if(e!==void 0){if(e.INTERNAL())return"internal";if(e.PRIVATE())return"private";if(e.PUBLIC())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}visitDefMeasures(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),re.MeasureFieldDeclaration),s=new re.Measures(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}visitQueryExtend(e){const r=[],i=e.queryExtendStatementList().queryExtendStatement().map(o=>this.visit(o));for(const o of i)if(re.isQueryExtendProperty(o))r.push(o);else throw this.internalError(e,`Query extend matched, but ${o.elementType} found`);const s=new re.ExtendBlock(r);return this.astAt(s,e)}visitDeclareStatement(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),re.DeclareFieldDeclaration),s=new re.DeclareFields(i,r),o=this.astAt(s,e);return this.m4advisory(e,"declare","`declare:` is deprecated; use `dimension:` or `measure:` inside a source or `extend:` block"),o}visitExploreRenameDef(e){const r=e.fieldName(0),i=e.fieldName(1),s=new re.RenameField((0,Yn.getId)(r),this.getFieldName(i));return this.astAt(s,e)}visitDefExploreRename(e){const r=this.getAccessLabel(e.accessLabel()),s=e.renameList().exploreRenameDef().map(u=>this.visitExploreRenameDef(u)),o=new re.Renames(s,r);return this.astAt(o,e)}visitFilterClauseList(e){return new re.Filter(e.fieldExpr().map(r=>this.getFilterElement(r)))}visitWhereStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!1,this.astAt(r,e)}visitHavingStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!0,this.astAt(r,e)}visitDefExploreQuery(e){const r=this.getAccessLabel(e.accessLabel()),i=e.subQueryDefList().exploreQueryDef().map(u=>this.visitExploreQueryDef(u)),s=new re.Views(i,r),o=this.getNotes(e.tags());return s.extendNote({blockNotes:o}),e.QUERY()&&this.m4advisory(e,"query-in-source","Use view: inside of a source instead of query:"),s}visitDefExplorePrimaryKey(e){const r=new re.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}getFieldNameList(e,r){const i=e.fieldName().map(s=>this.astAt(new r([this.getFieldName(s)]),s));return new re.FieldReferences(i)}visitDefExploreEditField(e){const r=e.ACCEPT()?"accept":"except";return new re.FieldListEdit(r,this.getFieldNameList(e.fieldNameList(),re.AcceptExceptFieldReference))}visitSQInclude(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new re.SQExtend(r,new re.SourceDesc([]),s);return this.astAt(o,e)}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const r=this.getPlainStringFrom(e),i=this.astAt(new re.TimezoneStatement(r),e.string());return i.isValid||this.astError(i,"invalid-timezone",{timezone:i.tz}),this.astAt(i,e)}visitQueryProperties(e){const r=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>re.isQueryProperty(i)&&i,"query statement");return new re.QOpDesc(r)}getFieldPath(e,r){const i=e.fieldName().map(s=>this.getFieldName(s));return this.astAt(new r(i),e)}getQueryFieldDef(e,r){const i=this.getFieldDef(e,r);return this.astAt(i,e)}getQueryFieldEntry(e,r,i){const s=e.taggedRef();if(s)return this.getTaggedRef(s,r,i);const o=e.fieldDef();if(o)return this.getQueryFieldDef(o,r);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,r,i){return this.only(e.queryFieldEntry().map(s=>this.getQueryFieldEntry(s,r,i)),s=>s instanceof re.FieldReference||s instanceof re.AtomicFieldDeclaration?s:!1,"view field")}visitAggregateStatement(e){const r=new re.Aggregate(this.getQueryItems(e.queryFieldList(),re.AggregateFieldDeclaration,re.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){const r=new re.GroupBy(this.getQueryItems(e.queryFieldList(),re.GroupByFieldDeclaration,re.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){const r=new re.Calculate(this.getQueryItems(e.queryFieldList(),re.CalculateFieldDeclaration,re.CalculateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}getTaggedRef(e,r,i){const s=e.refExpr();if(s){const u=this.getFieldPath(e.fieldPath(),re.ExpressionFieldReference);let a;const l=s.timeframe();l&&(a=new re.ExprGranularTime(new re.ExprIdReference(u),this.visitTimeframe(l).text,!0));const c=s.aggregate();if(c){const x=c.text.toLowerCase();if(x==="sum")a=new re.ExprSum(void 0,u);else return this.contextError(c,"invalid-reference-only-aggregation",`\`${x}\` is not legal in a reference-only aggregation`),u}const f=new r(a,u.outputName);return f.extendNote({notes:this.getNotes(e.tags())}),f}const o=this.getFieldPath(e.fieldPath(),i);return o.extendNote({notes:this.getNotes(e.tags())}),o}getFieldCollectionMember(e,r,i){const s=e.fieldDef();if(s)return this.getFieldDef(s,r);const o=e.taggedRef();if(o)return this.getTaggedRef(o,r,i);const u=e.collectionWildCard();if(u)return this.visitCollectionWildCard(u);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const r=e.collectionMember().map(i=>this.getFieldCollectionMember(i,re.ProjectFieldDeclaration,re.ProjectFieldReference));return this.astAt(new re.ProjectStatement(r),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project","project: keyword is deprecated, use select:");const r=this.visitFieldCollection(e.fieldCollection());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCollectionWildCard(e){var r;const i=e.fieldPath(),s=i?this.getFieldPath(i,re.ProjectFieldReference):void 0,o=this.astAt(new re.WildcardFieldReference(s),e),u=((r=e.starQualified())===null||r===void 0?void 0:r.fieldNameList())||[];for(const a of u)for(const l of a.fieldName())o.except.add((0,Yn.getId)(l));return o}visitIndexFields(e){const r=e.indexElement().map(i=>{const s=i.fieldPath();if(!s)return this.astAt(new re.WildcardFieldReference(void 0),e);const o=this.getFieldPath(s,re.IndexFieldReference);return i.STAR()?this.astAt(new re.WildcardFieldReference(o),e):this.astAt(o,e)});return new re.FieldReferences(r)}visitIndexStatement(e){const r=this.visitIndexFields(e.indexFields()),i=new re.Index(r),s=e.fieldName();return s&&i.useWeight(this.getFieldName(s)),this.astAt(i,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new re.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.fieldExpr(),s=i?this.getFieldExpr(i):void 0;return this.astAt(new re.FunctionOrderBy(s,r),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const r=e.aggregateOrderBySpec().map(i=>this.visitAggregateOrderBySpec(i));return this.astAt(new re.FunctionOrdering(r),e)}visitOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.INTEGER_LITERAL();if(i)return new re.OrderBy(this.getNumber(i),r);const s=e.fieldName();if(s)return new re.OrderBy(this.getFieldName(s),r);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const r=e.orderBySpec().map(i=>this.visitOrderBySpec(i));return this.astAt(new re.Ordering(r),e)}visitTopStatement(e){const r=this.getNumber(e.INTEGER_LITERAL());return this.astAt(new re.Limit(r),e)}visitTopLevelQueryDefs(e){const r=e.topLevelQueryDef().map(o=>this.visitTopLevelQueryDef(o)),i=this.getNotes(e.tags()),s=new re.DefineQueryList(r);return s.extendNote({blockNotes:i}),s}visitTopLevelQueryDef(e){const r=(0,Yn.getId)(e.queryName()),i=this.visit(e.sqExpr()),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(i instanceof re.SourceQueryElement){const o=new re.DefineQuery(r,i);return o.extendNote({notes:s}),this.astAt(o,e)}throw this.internalError(e,`Expected query definition, got a '${i.elementType}'`)}visitAnonymousQuery(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new re.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.m4advisory(r,"anonymous-query","Anonymous `query:` statements are deprecated, use `run:` instead"),this.astAt(s,e)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new re.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.astAt(s,e)}visitNestStatement(e){const r=this.visitNestedQueryList(e.nestedQueryList());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitNestedQueryList(e){return new re.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof re.NestFieldDeclaration&&r,"query"))}visitNestDef(e){const r=e.queryName();let i;const s=this.getVExpr(e.vExpr());if(r)i=(0,Yn.getId)(r);else{const a=s.getImplicitName();a===void 0&&this.contextError(e,"anonymous-nest","`nest:` view requires a name (add `nest_name is ...`)"),i=a??"__unnamed__"}const o=new re.NestFieldDeclaration(i,s),u=e.isDefine();return o.extendNote({notes:this.getNotes(e.tags()).concat(u?this.getIsNotes(u):[])}),this.astAt(o,e)}visitExploreQueryDef(e){const r=(0,Yn.getId)(e.exploreQueryNameDef()),i=new re.ViewFieldDeclaration(r,this.getVExpr(e.vExpr())),s=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,e)}visitExprNot(e){return new re.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new re.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(r=>this.getFieldExpr(r))}visitExprLogicalOr(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new re.ExprLogicalOp(r,"or",i)}visitExprLogicalAnd(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new re.ExprLogicalOp(r,"and",i)}visitExprOrTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new re.ExprAlternationTree(r,"|",i),e)}visitExprAndTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new re.ExprAlternationTree(r,"&",i),e)}visitExprCoalesce(e){const r=this.getFieldExpr(e.fieldExpr()[0]),i=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new re.ExprCoalesce(r,i),e)}visitPartialCompare(e){const r=e.compareOp().text;if(re.isComparison(r))return this.astAt(new re.PartialCompare(r,this.getFieldExpr(e.fieldExpr())),e);throw this.internalError(e,`partial comparison '${r}' not recognized`)}visitPartialTest(e){const r=e.partialCompare();return r?this.visitPartialCompare(r):this.astAt(new re.PartialIsNull(e.NOT()?"!=":"="),e)}visitPartialAllowedFieldExpr(e){const r=e.fieldExpr();if(r)return this.getFieldExpr(r);const i=e.partialTest();if(i)return this.visitPartialTest(i);throw this.internalError(e,"impossible partial")}visitExprString(e){const r=this.getPlainStringFrom(e);return new re.ExprString(r)}visitRawString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
|
|
1161
1161
|
`){const o=r[0]==="'"?'"':"'";this.contextError(e,"literal-string-newline",`Missing ${o}${r[0]}${o} before end-of-line`)}const s=new re.ExprString(r.slice(1,-1));return this.astAt(s,e)}visitExprRegex(e){const r=e.HACKY_REGEX().text;return new re.ExprRegEx(r.slice(2,-1))}visitExprNow(e){return new re.ExprNow}visitExprNumber(e){return new re.ExprNumber(e.text)}visitExprFieldPath(e){const r=new re.ExprIdReference(this.getFieldPath(e.fieldPath(),re.ExpressionFieldReference));return this.astAt(r,e)}visitExprNULL(e){return new re.ExprNULL}visitExprExpr(e){return new re.ExprParens(this.getFieldExpr(e.fieldExpr()))}visitExprMinus(e){return new re.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1)),s=e.PLUS()?"+":"-";return new re.ExprAddSub(r,s,i)}visitExprMulDiv(e){const r=e.STAR()?"*":e.SLASH()?"/":"%";return new re.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){const r=e.compareOp().text,i=this.getFieldExpr(e.fieldExpr(0)),s=this.getFieldExpr(e.fieldExpr(1));if(re.isEquality(r)){const o=this.rangeFromContext(e);return s instanceof re.ExprNULL&&(r==="="?this.warnWithReplacement("sql-is-null","Use 'is null' to check for NULL instead of '= null'",o,`${this.getSourceCode(e.fieldExpr(0))} is null`):r==="!="&&this.warnWithReplacement("sql-is-not-null","Use 'is not null' to check for NULL instead of '!= null'",o,`${this.getSourceCode(e.fieldExpr(0))} is not null`)),this.astAt(new re.ExprEquality(i,r,s),e)}else if(re.isComparison(r))return this.astAt(new re.ExprCompare(i,r,s),e);throw this.internalError(e,`untranslatable comparison operator '${r}'`)}visitExprUngroup(e){const r=e.fieldName().map(s=>this.getFieldName(s)),i=e.ungroup().text.toLowerCase();return this.astAt(new re.ExprUngroup(i==="all"?i:"exclude",this.getFieldExpr(e.fieldExpr()),r),e)}symmetricAggregateUsageError(e){return`Symmetric aggregate function \`${e}\` must be written as \`${e}(expression)\` or \`path.to.field.${e}()\``}asymmetricAggregateUsageError(e){return`Asymmetric aggregate function \`${e}\` must be written as \`path.to.field.${e}()\`, \`path.to.join.${e}(expression)\`, or \`${e}(expression)\``}visitExprAggregate(e){const r=e.fieldPath(),i=this.getFieldPath(r,re.ExpressionFieldReference),s=r&&i?this.astAt(i,r):void 0,o=e.aggregate().text.toLowerCase(),u=e.fieldExpr();if(e.aggregate().COUNT())return u&&this.contextError(u,"count-expression-with-locality","Expression illegal inside path.count()"),new re.ExprCount(s);const a=u?this.getFieldExpr(u):void 0;if(o==="min"||o==="max")if(a)this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o));else{const l=this.astAt(new re.ExprIdReference(i),r);return o==="min"?new re.ExprMin(l):new re.ExprMax(l)}else{if(o==="avg")return new re.ExprAvg(a,s);if(o==="sum")return new re.ExprSum(a,s);this.contextError(e,"aggregate-parse-error",`Cannot parse aggregate function ${o}`)}return new re.ExprNULL}visitExprPathlessAggregate(e){const r=e.fieldExpr(),i=r?this.getFieldExpr(r):void 0,s=void 0,o=e.aggregate().text.toLowerCase();if(e.STAR()&&this.m4advisory(e,"wildcard-in-aggregate",`* illegal inside ${o}()`),o==="count")return this.astAt(i?new re.ExprCountDistinct(i):new re.ExprCount,e);if(o==="min"){if(i)return new re.ExprMin(i);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o))}else if(o==="max"){if(i)return new re.ExprMax(i);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o))}else{if(i===void 0)return this.contextError(e,"invalid-asymmetric-aggregate",this.asymmetricAggregateUsageError(o)),new re.ExprNULL;const u=e.SOURCE_KW()!==void 0;if(o==="avg")return new re.ExprAvg(i,s,u);if(o==="sum")return new re.ExprSum(i,s,u)}return new re.ExprNULL}visitExprApply(e){return new re.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new re.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new re.ExprCast(this.getFieldExpr(e.fieldExpr()),r)}getMalloyType(e){const r=e.text;if((0,Ck.isCastType)(r))return r;throw this.internalError(e,`unknown type '${r}'`)}getMalloyOrSQLType(e){const r=e.malloyType();if(r)return this.getMalloyType(r);const i=e.string();if(i)return{raw:this.getPlainStringFrom({string:()=>i})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){const r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new re.ExprCast(this.getFieldExpr(e.fieldExpr()),r,!0)}visitExprTimeTrunc(e){return new re.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new re.Timeframe(e.text)}visitExprForRange(e){const r=this.getFieldExpr(e._startAt),i=this.getFieldExpr(e._duration),s=this.visitTimeframe(e.timeframe());return new re.ForRange(r,i,s)}visitExprAggFunc(e){const r=e.argumentList(),i=r?this.allFieldExpressions(r.fieldExpr()):[],s=(0,Yn.getId)(e),o=e.fieldPath(),u=o?this.getFieldPath(o,re.ExpressionFieldReference):void 0,a=o&&u?this.astAt(u,o):void 0;return re.ExprTimeExtract.extractor(s)?this.astAt(new re.ExprTimeExtract(s,i),e):this.astAt(new re.ExprFunc(s,i,!1,void 0,a),e)}visitExprFunc(e){var r,i;const s=e.argumentList(),o=s?this.allFieldExpressions(s.fieldExpr()):[],u=e.EXCLAM()!==void 0,a=(r=e.malloyType())===null||r===void 0?void 0:r.text;let l;a&&((0,Ck.isCastType)(a)?l=a:(this.contextError(e,"unexpected-malloy-type",`'#' assertion for unknown type '${a}'`),l=void 0));let c=(0,Yn.getOptionalId)(e)||((i=e.timeframe())===null||i===void 0?void 0:i.text);return c===void 0&&(this.contextError(e,"failed-to-parse-function-name","Function name error"),c="FUNCTION_NAME_ERROR"),re.ExprTimeExtract.extractor(c)?this.astAt(new re.ExprTimeExtract(c,o),e):this.astAt(new re.ExprFunc(c,o,u,l),e)}visitExprDuration(e){return new re.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitCaseStatement(e){const r=e._valueExpr,i=r?this.getFieldExpr(r):void 0,s=e.caseWhen(),o=s.map(l=>new re.CaseWhen(this.getFieldExpr(l._condition),this.getFieldExpr(l._result))),u=e._caseElse,a=u?this.getFieldExpr(u):void 0;return this.warnWithReplacement("sql-case","Use a `pick` statement instead of `case`",this.rangeFromContext(e),`${[...r?[`${this.getSourceCode(r)} ?`]:[],...s.map(l=>`pick ${this.getSourceCode(l._result)} when ${this.getSourceCode(l._condition)}`),u?`else ${u.text}`:"else null"].join(" ")}`),new re.Case(i,o,a)}visitPickStatement(e){const r=e.pick().map(i=>{let s;return i._pickValue&&(s=this.getFieldExpr(i._pickValue)),new re.PickWhen(s,this.getFieldExpr(i._pickWhen))});return e.ELSE()?new re.Pick(r,this.getFieldExpr(e._pickElse)):new re.Pick(r)}visitExprFieldProps(e){const r=this.only(e.fieldProperties().fieldPropertyStatement().map(i=>this.visit(i)),i=>re.isFieldPropStatement(i)&&i,"field property statement");return new re.ExprProps(this.getFieldExpr(e.fieldExpr()),r)}visitPartitionByStatement(e){return this.astAt(new re.PartitionBy(e.id().map(r=>this.astAt(new re.PartitionByFieldReference([this.astAt(new re.FieldName((0,Yn.idToStr)(r)),r)]),r))),e)}visitLiteralTimestamp(e){return this.parseTime(e,re.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,re.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,re.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,re.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,re.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,re.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,re.LiteralYear.parse)}visitImportStatement(e){const r=this.getPlainStringFrom(e.importURL()),i=this.astAt(new re.ImportStatement(r,this.parseInfo.importBaseURL),e),s=e.importSelect();if(s)for(const o of s.importItem()){const u=o.id(),a=u[1]?this.astAt(new re.ImportSourceName((0,Yn.idToStr)(u[1])),u[1]):void 0;i.push(this.astAt(new re.ImportSelect((0,Yn.idToStr)(u[0]),a),u[0]))}return i}visitDebugExpr(e){return this.getFieldExpr(e.fieldExpr())}visitSampleStatement(e){const r=e.sampleSpec().INTEGER_LITERAL();if(r)return new re.SampleProperty({rows:this.getNumber(r)});const i=e.sampleSpec().PERCENT_LITERAL();if(i)return new re.SampleProperty({percent:this.getNumber(i)});const s=e.sampleSpec().TRUE()!==void 0;return new re.SampleProperty({enable:s})}visitDocAnnotations(e){const r=e.DOC_ANNOTATION().map(s=>({text:s.text,at:this.getLocation(e)})),i=new re.ModelAnnotation(r);return this.compilerFlags=i.getCompilerFlags(this.compilerFlags,this.msgLog),i}visitIgnoredObjectAnnotations(e){return this.contextError(e,"orphaned-object-annotation","Object annotation not connected to any object"),new Sk(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"misplaced-model-annotation","Model annotations not allowed at this scope"),new Sk(e.text)}visitDefExploreAnnotation(e){const r=this.getNotes(e);return new re.ObjectAnnotation(r)}getSQArgument(e){const r=e.argumentId(),i=r?this.astAt(new re.PartitionByFieldReference([this.astAt(new re.FieldName((0,Yn.idToStr)(r.id())),r)]),r):void 0;return this.astAt(new re.Argument({id:i,value:this.getFieldExpr(e.fieldExpr())}),e)}getSQArguments(e){if(e!==void 0)return this.inExperiment("parameters",e),e.sourceArgument().map(r=>this.getSQArgument(r))}visitSQID(e){const r=this.getModelEntryName(e),i=this.getSQArguments(e.sourceArguments());return this.astAt(new re.SQReference(r,i),e.id())}getSqExpr(e){const r=this.visit(e);return r instanceof re.SourceQueryElement?r:(this.contextError(e,"unexpected-non-source-query-expression-node",`Expected a source/query expression, not '${r.elementType}'`),new V0e)}visitSQExtendedSource(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new re.SQExtend(r,this.getSourceExtensions(e.exploreProperties()),s);return this.astAt(o,e)}getIncludeItems(e){return this.inExperiment("access_modifiers",e),e.includeItem().map(r=>this.getIncludeItem(r)).filter(W0e.isNotUndefined)}getIncludeItem(e){var r;const i=e.tags(),s=i?this.getNotes(i):[],o=e.includeExceptList();if(o){i&&s.length>0&&this.contextError(i,"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const u=this.getExcludeList(o);return this.astAt(new re.IncludeExceptItem(u),e)}else{const u=e.includeList();if(u===void 0){this.contextError((r=e.orphanedAnnotation())!==null&&r!==void 0?r:e,"orphaned-object-annotation","This tag is not attached to anything",{severity:"warn"});return}const a=this.getAccessLabelProp(e.accessLabelProp()),l=this.getIncludeList(u),c=this.astAt(new re.IncludeAccessItem(a,l),e);return c.extendNote({blockNotes:s}),c}}getIncludeList(e){const r=e.includeField();if(r===void 0)throw this.internalError(e,"Expected a field name list");return r.map(i=>this.getIncludeListItem(i))}getExcludeList(e){return e.includeExceptListItem().map(r=>{r.tags().ANNOTATION().length>0&&this.contextError(r.tags(),"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const i=r.fieldName();if(i)return this.astAt(new re.AccessModifierFieldReference([this.astAt(this.getFieldName(i),r)]),i);const s=r.collectionWildCard();if(s)return this.astAt(this.visitCollectionWildCard(s),s);throw this.internalError(r,"Expected a field name or wildcard")})}getIncludeListItem(e){const r=e.collectionWildCard(),i=r?this.visitCollectionWildCard(r):void 0,s=e._as?e._as.text:void 0,o=e.tags(),u=o?this.getNotes(o):[],a=e.isDefine(),l=a?this.getIsNotes(a):[],c=[...u,...l],f=e._name?this.astAt(new re.AccessModifierFieldReference([this.astAt(this.getFieldName(e._name),e._name)]),e._name):void 0,x=f??i;if(x===void 0)throw this.internalError(e,"Expected a field name or wildcard");const h=this.astAt(new re.IncludeListItem(x,s),e);return h.extendNote({notes:c}),h}visitSQParens(e){const r=this.getSqExpr(e.sqExpr());return this.astAt(r,e)}visitSQCompose(e){const r=e.sqExpr().map(i=>this.getSqExpr(i));return this.inExperiment("composite_sources",e),this.astAt(new re.SQCompose(r),e)}visitSQArrow(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new re.SQArrow(r,this.getVExpr(i));return this.astAt(s,e)}getVExpr(e){const r=this.visit(e);if(r instanceof re.View)return r;throw this.internalError(e,`Expected view, got a '${r.elementType}'`)}visitSegField(e){return new re.ReferenceView(this.getFieldPath(e.fieldPath(),re.ViewOrScalarFieldReference))}visitSegOps(e){return new re.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new re.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new re.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new re.SQRefine(r,this.getVExpr(i));return this.astAt(s,e)}visitSQTable(e){const r=this.visit(e.exploreTable());if(r instanceof bct.TableSource){const i=new re.SQSource(r);return this.astAt(i,e)}return new V0e}visitSQSQL(e){const r=new re.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(r,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new re.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}visitRecordRef(e){const r=new re.ExprIdReference(this.getFieldPath(e.fieldPath(),re.ExpressionFieldReference));return this.astAt(new re.RecordElement({path:r}),e)}visitRecordExpr(e){const r=this.getFieldExpr(e.fieldExpr()),i=e.recordKey(),s=i?{key:(0,Yn.getId)(i),value:r}:{value:r};return this.astAt(new re.RecordElement(s),e)}visitExprLiteralRecord(e){const r=this.only(e.recordElement().map(i=>this.astAt(this.visit(i),i)),i=>i instanceof re.RecordElement&&i,"a legal record property description");return new re.RecordLiteral(r)}visitExprArrayLiteral(e){const r=e.fieldExpr().map(s=>this.getFieldExpr(s)),i=new re.ArrayLiteral(r);return this.astAt(i,e)}visitExprWarnLike(e){let r="~";const i=e.fieldExpr(0),s=e.fieldExpr(1),o=this.rangeFromContext(e);return e.NOT()?(r="!~",this.warnWithReplacement("sql-not-like","Use Malloy operator '!~' instead of 'NOT LIKE'",o,`${this.getSourceCode(i)} !~ ${this.getSourceCode(s)}`)):this.warnWithReplacement("sql-like","Use Malloy operator '~' instead of 'LIKE'",o,`${this.getSourceCode(i)} ~ ${this.getSourceCode(s)}`),this.astAt(new re.ExprCompare(this.getFieldExpr(i),r,this.getFieldExpr(s)),e)}visitExprNullCheck(e){const r=e.fieldExpr();return this.astAt(new re.ExprIsNull(this.getFieldExpr(r),e.NOT()?"!=":"="),e)}visitExprWarnIn(e){const r=this.getFieldExpr(e.fieldExpr()),i=!!e.NOT(),s=e.fieldExprList().fieldExpr(),o=this.astAt(new re.ExprLegacyIn(r,i,s.map(u=>this.getFieldExpr(u))),e);return this.warnWithReplacement("sql-in",`Use = (a|b|c) instead of${i?" NOT":""} IN (a,b,c)`,this.rangeFromContext(e),`${this.getSourceCode(e.fieldExpr())} ${i?"!=":"="} (${s.map(u=>this.getSourceCode(u)).join(" | ")})`),o}visitTickFilterString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
|
|
1162
1162
|
`){const u=r[0]==="'"?'"':"'";this.contextError(e,"literal-string-newline",`Missing $${u}${r[0]}${u} before end-of-line`)}const s=r.slice(1,-1),o=new re.ExprFilterExpression(s);return this.astAt(o,e)}visitTripFilterString(e){const i=e.text.slice(1).trimStart().slice(3,-3),s=new re.ExprFilterExpression(i);return this.astAt(s,e)}}_T.MalloyToAST=Oct;var vT={};Object.defineProperty(vT,"__esModule",{value:!0}),vT.Zone=void 0;class Fct{constructor(){this.location={},this.zone=new Map}get(e){const r=this.zone.get(e);if((r==null?void 0:r.status)==="present")return r.value}getEntry(e){const r=this.zone.get(e);return r?r.firstReference||!this.location[e]?r:{...r,firstReference:this.location[e]}:{status:"error",message:"import reference failure"}}define(e,r){this.zone.set(e,{status:"present",value:r})}reference(e,r){const i=this.zone.get(e);(i==null?void 0:i.status)===void 0&&(this.zone.set(e,{status:"reference",firstReference:r}),this.location[e]=r)}getUndefined(){const e=[];for(const[r,i]of this.zone)i.status==="reference"&&e.push(r);return e.length>0?e:void 0}updateFrom(e,r){if(e)for(const[i,s]of Object.entries(e))s!==void 0&&this.define(i,s);if(r)for(const[i,s]of Object.entries(r))this.zone.set(i,{status:"error",message:s})}}vT.Zone=Fct;var CT={};Object.defineProperty(CT,"__esModule",{value:!0}),CT.walkForDocumentSymbols=void 0;const wct=ac,Nct=Bn;class Lct{constructor(e,r,i,s){this.translator=e,this.tokens=r,this.scopes=i,this.symbols=s}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){const r=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=r)}enterTopLevelQueryDef(e){this.symbols.push({range:this.translator.rangeFromContext(e),name:e.queryName().text,type:"query",children:[],lensRange:this.blockRange}),this.blockRange=void 0}enterRunStatement(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterAnonymousQuery(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef().sqExpr()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterDefineSourceStatement(e){const r=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=r)}enterSourceDefinition(e){const r=this.translator.rangeFromContext(e);this.scopes.push({range:r,name:e.sourceNameDef().id().text,type:"explore",children:[],lensRange:this.blockRange}),this.blockRange=void 0}exitSourceDefinition(e){const r=this.popScope();r&&this.symbols.push(r)}enterDefExploreQuery(e){const r=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=r)}enterExploreQueryDef(e){const r={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},i=this.peekScope();i&&i.children.push(r),this.scopes.push(r),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}getNestDefName(e){const r=e.queryName();if(r)return r.id().text;let i,s=!1;const o={enterVArrow(a){a.vExpr().enterRule(o)},enterVSeg(a){a.segExpr().enterRule(u)}},u={enterSegField(a){const l=a.fieldPath().fieldName();s||(i??(i=l[l.length-1].id().text))},enterSegParen(a){a.vExpr().enterRule(o)},enterSegRefine(a){a._lhs.enterRule(u)},enterSegOps(){i=void 0,s=!0}};return e.vExpr().enterRule(o),i}handleNestEntry(e){const r=this.getNestDefName(e);if(r===void 0)return;const i={range:this.translator.rangeFromContext(e),name:r,type:"query",children:[]},s=this.peekScope();return s&&s.children.push(i),i}enterNestDef(e){const r=this.handleNestEntry(e);r&&this.scopes.push(r)}exitNestDef(e){this.popScope()}enterFieldDef(e){const r={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},i=this.peekScope();i&&i.children.push(r)}enterQueryFieldEntry(e){var r;const i=(r=e.taggedRef())===null||r===void 0?void 0:r.fieldPath();if(i===void 0)return;const s={range:this.translator.rangeFromContext(e),name:i.text,type:"field",children:[]},o=this.peekScope();o&&o.children.push(s)}enterExploreRenameDef(e){const r={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},i=this.peekScope();i&&i.children.push(r)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){const r={range:this.translator.rangeFromContext(e),name:e.joinFrom().joinNameDef().id().text,type:"join",children:[]},i=this.peekScope();i&&i.children.push(r)}enterImportStatement(e){const r=(0,Nct.getStringIfShort)(e.importURL());r&&this.scopes.push({range:this.translator.rangeFromContext(e),name:r,type:"import",children:[]})}exitImportStatement(){const e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){const r=this.peekScope();if(r)for(const i of e.importItem()){const s={range:this.translator.rangeFromContext(e),name:i.text,type:"import_item",children:[]};r.children.push(s)}}}function Ict(t,e,r){const i=new Lct(t,e,[],[]),s=i;return wct.ParseTreeWalker.DEFAULT.walk(s,r),i.symbols}CT.walkForDocumentSymbols=Ict;var ST={};Object.defineProperty(ST,"__esModule",{value:!0}),ST.walkForDocumentCompletions=void 0;const $ct=ac,Bct=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],kct=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],Mct=["source","explore","query","sql"];class Pct{constructor(e,r,i){this.tokens=e,this.completions=r,this.position=i}rangeOf(e){const r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}inRange(e){const{start:r,end:i}=e,s=this.position.line>r.line||this.position.line===r.line&&this.position.character>=r.character,o=this.position.line<i.line||this.position.line===i.line&&this.position.character<=i.character;return s&&o}enterExploreProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.exploreStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Bct)this.completions.push({type:"explore_property",text:`${i}: `})}}enterQueryProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.queryStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of kct)this.completions.push({type:"query_property",text:`${i}: `})}}enterMalloyDocument(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.malloyStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Mct)this.completions.push({type:"model_property",text:`${i}: `})}}}function Uct(t,e,r){const i=new Pct(t,[],r),s=i;return $ct.ParseTreeWalker.DEFAULT.walk(s,e),i.completions}ST.walkForDocumentCompletions=Uct;var bT={};Object.defineProperty(bT,"__esModule",{value:!0}),bT.walkForDocumentHelpContext=void 0;const jct=QL;class qct extends jct.AbstractParseTreeVisitor{constructor(e){super(),this.position=e,this.type=""}rangeOf(e){const r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}inRange(e){return e.start.line<=this.position.line&&e.end.line>=this.position.line&&(this.position.line!==e.start.line||this.position.character>=e.start.character)&&(this.position.line!==e.end.line||this.position.character<=e.end.character)}defaultResult(){}visitChildren(e){let r=this.defaultResult();if(this.inRange(this.rangeOf(e))){r={type:this.type,token:e.start.text};const i=e.childCount;for(let s=0;s<i;s++){const u=e.getChild(s).accept(this);u&&(r=this.aggregateResult(r,u))}}return r}visitMalloyDocument(e){return this.inRange(this.rangeOf(e))?(this.type="model_property",this.visitChildren(e)):this.defaultResult()}visitExploreProperties(e){return this.inRange(this.rangeOf(e))?(this.type="explore_property",this.visitChildren(e)):this.defaultResult()}visitQueryProperties(e){return this.inRange(this.rangeOf(e))?(this.type="query_property",this.visitChildren(e)):this.defaultResult()}aggregateResult(e,r){return r}}function Qct(t,e){return new qct(e).visit(t)}bT.walkForDocumentHelpContext=Qct;var TT={};Object.defineProperty(TT,"__esModule",{value:!0}),TT.ReferenceList=void 0;const Hct=Vn;class zct{constructor(e){this.sourceURL=e,this.references=[]}findIndexBefore(e){let r=0,i=this.references.length;for(;r<i;){const s=Math.floor((r+i)/2),o=this.references[s].location.range.end;o.line<e.line||o.line===e.line&&o.character<e.character?r=s+1:i=s}return r}add(e){if(e.location.url!==this.sourceURL)return;const r=this.findIndexBefore(e.location.range.end);r<this.references.length&&this.isPositionEqual(e,this.references[r])||this.references.splice(r,0,e)}isPositionEqual(e,r){const i=e.location.range,s=r.location.range;return i.start.line===s.start.line&&i.start.character===s.start.character&&i.end.line===s.end.line&&i.end.character===s.end.character}find(e){const r=this.findIndexBefore(e);if(r===this.references.length)return;const i=this.references[r];if((0,Hct.locationContainsPosition)(i.location,e))return i}}TT.ReferenceList=zct;var RT={};Object.defineProperty(RT,"__esModule",{value:!0}),RT.isNeedResponse=void 0;function Gct(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}RT.isNeedResponse=Gct;var DT={};Object.defineProperty(DT,"__esModule",{value:!0}),DT.walkForModelAnnotation=void 0;const Wct=ac;class Vct{constructor(e,r,i){this.translator=e,this.tokens=r,this.parseInfo=i,this.notes=[]}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.translator.rangeFromContext(e)}}enterDocAnnotations(e){const r=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)}));this.notes.push(...r)}get annotation(){return{notes:this.notes}}}function Yct(t,e,r){const i=new Vct(t,e,r),s=i;return Wct.ParseTreeWalker.DEFAULT.walk(s,r.root),i.annotation}DT.walkForModelAnnotation=Yct;var OT={};Object.defineProperty(OT,"__esModule",{value:!0}),OT.walkForTablePath=void 0;const Y0e=Bn,Kct=ac;class Jct{constructor(e,r){this.translator=e,this.tokens=r,this.pathInfos=[]}enterTableMethod(e){const r=(0,Y0e.getId)(e.connectionId()),[i,s]=(0,Y0e.getPlainString)(e.tablePath(),!0);i!==void 0&&this.pathInfos.push({connectionId:r,tablePath:i,range:this.translator.rangeFromContext(e)})}}function Xct(t,e,r){const i=new Jct(t,e),s=i;return Kct.ParseTreeWalker.DEFAULT.walk(s,r.root),i.pathInfos}OT.walkForTablePath=Xct;var oE={},FT={},Zct=T&&T.__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]}),eft=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tft=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zct(e,t,r);return eft(e,t),e};Object.defineProperty(FT,"__esModule",{value:!0}),FT.MalloyLexer=void 0;const nft=bp(),rft=Ml(),ift=Jg(),sft=Ns,K0e=tft(bn);class oe extends rft.Lexer{get vocabulary(){return oe.VOCABULARY}constructor(e){super(e),this._interp=new ift.LexerATNSimulator(oe._ATN,this)}get grammarFileName(){return"MalloyLexer.g4"}get ruleNames(){return oe.ruleNames}get serializedATN(){return oe._serializedATN}get channelNames(){return oe.channelNames}get modeNames(){return oe.modeNames}static get _ATN(){return oe.__ATN||(oe.__ATN=new nft.ATNDeserializer().deserialize(K0e.toCharArray(oe._serializedATN))),oe.__ATN}}FT.MalloyLexer=oe,oe.ACCEPT=1,oe.AGGREGATE=2,oe.CALCULATE=3,oe.CALCULATION=4,oe.CONNECTION=5,oe.DECLARE=6,oe.DIMENSION=7,oe.EXCEPT=8,oe.EXTENDQ=9,oe.GROUP_BY=10,oe.HAVING=11,oe.INDEX=12,oe.INTERNAL=13,oe.JOIN_CROSS=14,oe.JOIN_ONE=15,oe.JOIN_MANY=16,oe.LIMIT=17,oe.MEASURE=18,oe.NEST=19,oe.ORDER_BY=20,oe.PARTITION_BY=21,oe.PRIMARY_KEY=22,oe.PRIVATE=23,oe.PROJECT=24,oe.PUBLIC=25,oe.QUERY=26,oe.RENAME=27,oe.RUN=28,oe.SAMPLE=29,oe.SELECT=30,oe.SOURCE=31,oe.TOP=32,oe.WHERE=33,oe.VIEW=34,oe.TIMEZONE=35,oe.ALL=36,oe.AND=37,oe.AS=38,oe.ASC=39,oe.AVG=40,oe.BOOLEAN=41,oe.BY=42,oe.CASE=43,oe.CAST=44,oe.CONDITION=45,oe.COUNT=46,oe.COMPOSE=47,oe.DATE=48,oe.DAY=49,oe.DESC=50,oe.DISTINCT=51,oe.ELSE=52,oe.END=53,oe.EXCLUDE=54,oe.EXTEND=55,oe.FALSE=56,oe.FULL=57,oe.FOR=58,oe.FROM=59,oe.HAS=60,oe.HOUR=61,oe.IMPORT=62,oe.INCLUDE=63,oe.INNER=64,oe.IS=65,oe.IN=66,oe.INTERNAL_KW=67,oe.JSON=68,oe.LAST=69,oe.LEFT=70,oe.LIKE=71,oe.MAX=72,oe.MIN=73,oe.MINUTE=74,oe.MONTH=75,oe.NOT=76,oe.NOW=77,oe.NULL=78,oe.NUMBER=79,oe.ON=80,oe.OR=81,oe.PICK=82,oe.PRIVATE_KW=83,oe.PUBLIC_KW=84,oe.QUARTER=85,oe.RIGHT=86,oe.SECOND=87,oe.STRING=88,oe.SOURCE_KW=89,oe.SUM=90,oe.SQL=91,oe.TABLE=92,oe.THEN=93,oe.THIS=94,oe.TIMESTAMP=95,oe.TO=96,oe.TRUE=97,oe.TURTLE=98,oe.WEEK=99,oe.WHEN=100,oe.WITH=101,oe.YEAR=102,oe.UNGROUPED=103,oe.HACKY_REGEX=104,oe.RAW_SQ=105,oe.RAW_DQ=106,oe.SQ3_FILTER=107,oe.SQ_FILTER=108,oe.DQ3_FILTER=109,oe.DQ_FILTER=110,oe.BQ3_FILTER=111,oe.BQ_FILTER=112,oe.SQ_STRING=113,oe.DQ_STRING=114,oe.BQ_STRING=115,oe.DOC_ANNOTATION=116,oe.ANNOTATION=117,oe.AMPER=118,oe.ARROW=119,oe.FAT_ARROW=120,oe.OPAREN=121,oe.CPAREN=122,oe.OBRACK=123,oe.CBRACK=124,oe.OCURLY=125,oe.CCURLY=126,oe.DOUBLECOLON=127,oe.TRIPLECOLON=128,oe.EXCLAM=129,oe.COLON=130,oe.COMMA=131,oe.DOT=132,oe.LT=133,oe.GT=134,oe.EQ=135,oe.NE=136,oe.LTE=137,oe.GTE=138,oe.PLUS=139,oe.MINUS=140,oe.STAR=141,oe.STARSTAR=142,oe.SLASH=143,oe.BAR=144,oe.SEMI=145,oe.NOT_MATCH=146,oe.MATCH=147,oe.PERCENT=148,oe.DOUBLE_QMARK=149,oe.QMARK=150,oe.LITERAL_TIMESTAMP=151,oe.LITERAL_HOUR=152,oe.LITERAL_DAY=153,oe.LITERAL_QUARTER=154,oe.LITERAL_MONTH=155,oe.LITERAL_WEEK=156,oe.LITERAL_YEAR=157,oe.IDENTIFIER=158,oe.PERCENT_LITERAL=159,oe.NUMERIC_LITERAL=160,oe.INTEGER_LITERAL=161,oe.BLOCK_COMMENT=162,oe.COMMENT_TO_EOL=163,oe.WHITE_SPACE=164,oe.SQL_BEGIN=165,oe.CLOSE_CODE=166,oe.UNWATED_CHARS_TRAILING_NUMBERS=167,oe.UNEXPECTED_CHAR=168,oe.OPEN_CODE=169,oe.SQL_END=170,oe.SQL_MODE=1,oe.channelNames=["DEFAULT_TOKEN_CHANNEL","HIDDEN"],oe.modeNames=["DEFAULT_MODE","SQL_MODE"],oe.ruleNames=["SPACE_CHAR","ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","SQ","BQ","DQ","SQ3","DQ3","BQ3","RAW_CHAR","RAW3_CHAR","FILTER","RAWSTR","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","HEX","UNICODE","SAFE_NON_QUOTE","ESCAPED","STR_CHAR","SQ_STRING","DQ_STRING","BQ_STRING","F_TO_EOL","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","F_YEAR","F_DD","F_TZ","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","EXPONENT","NUMERIC_LITERAL","INTEGER_LITERAL","ID_CHAR","DIGIT","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","CLOSE_CODE","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","SQL_CHAR","OPEN_CODE","SQL_END"],oe._LITERAL_NAMES=[void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,"'&'","'->'","'=>'","'('","')'","'['","']'","'{'","'}'","'::'","':::'","'!'","':'","','","'.'","'<'","'>'","'='","'!='","'<='","'>='","'+'","'-'","'*'","'**'","'/'","'|'","';'","'!~'","'~'","'%'","'??'","'?'",void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,`'"""'`,"'}%'"],oe._SYMBOLIC_NAMES=[void 0,"ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","SQ_STRING","DQ_STRING","BQ_STRING","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","NUMERIC_LITERAL","INTEGER_LITERAL","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","CLOSE_CODE","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","OPEN_CODE","SQL_END"],oe.VOCABULARY=new sft.VocabularyImpl(oe._LITERAL_NAMES,oe._SYMBOLIC_NAMES,[]),oe._serializedATNSegments=4,oe._serializedATNSegment0=`줝쪺֍꾺体؇쉁¬ވ\b\b \x07 \x07\b \b
|
|
1163
1163
|
|