@malloydata/render 0.0.270-dev250426032717 → 0.0.270-dev250428164815

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.
@@ -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 ba)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=ba;class xZe extends ba{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}}Je.Unimplemented=xZe;class dB extends ba{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=dB;class dZe extends ba{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}}Je.ExperimentalExperiment=dZe;function Bae(t){return t.execute!==void 0}Je.isDocStatement=Bae;function hZe(t){return t instanceof Oy||Bae(t)}Je.isDocStatementOrDocStatementList=hZe;class kae extends ba{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=kae;class Oy extends kae{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=$ae.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,$ae.isNoteable)(r)&&r.extendNote(this.note),this.noteCursor+=1),r instanceof Oy){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=Oy;const pZe="5a79a191-06bc-43cf-9b12-58741cd82970";function Mae(t){const e=t.inherits?Mae(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 mZe(t){const e=Mae(t).join("");return(0,fZe.v5)(e,pZe)}class hB extends ba{constructor(e){super(),this.elementType="document",this.globalNameSpace=new cZe.GlobalNameSpace,this.documentModel={},this.queryList=[],this.didInitModel=!1,this.annotation={},this.experiments=new oZe.Tag({}),this.modelAnnotationTodoList=[],this.dialectNameSpaces=new Map,this.statements=new Oy(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,V4.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=mZe(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,V4.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,V4.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,Iae.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,Iae.getDialect)(e),i=new lZe.DialectNameSpace(r);return this.dialectNameSpaces.set(e,i),i}}Je.Document=hB;var Y4={},Jp={},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=Pi,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),g=h&&(f.type==="null"||x.type==="null"),y=p&&(f.type==="error"||x.type==="error");return m||g||y}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 Mr={},Rc={};Object.defineProperty(Rc,"__esModule",{value:!0}),Rc.canMakeEntry=Rc.SpaceEntry=void 0;class gZe{}Rc.SpaceEntry=gZe;function yZe(t){return"makeEntry"in t}Rc.canMakeEntry=yZe,Object.defineProperty(Mr,"__esModule",{value:!0}),Mr.SpaceField=void 0;const EZe=Rc,AZe=lt;class _Ze extends EZe.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,AZe.emptyCompositeFieldUsage)()}}getQueryFieldDef(e){}fieldDef(){}constructorFieldDef(){}}Mr.SpaceField=_Ze;var vZe=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]}),CZe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),SZe=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)&&vZe(e,t,r);return CZe(e,t),e};Object.defineProperty(Jp,"__esModule",{value:!0}),Jp.ViewField=void 0;const bZe=lt,TZe=SZe(Zt),RZe=Mr;class DZe extends RZe.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){var e;const r=this.fieldDef();return{...TZe.viewT,compositeFieldUsage:(e=r.compositeFieldUsage)!==null&&e!==void 0?e:(0,bZe.emptyCompositeFieldUsage)()}}}Jp.ViewField=DZe,Object.defineProperty(Y4,"__esModule",{value:!0}),Y4.ASTViewField=void 0;const OZe=Jp;class FZe extends OZe.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}}Y4.ASTViewField=FZe,Object.defineProperty(Dy,"__esModule",{value:!0}),Dy.ViewFieldDeclaration=void 0;const wZe=Je,NZe=kr,LZe=Vp,IZe=Y4;class $Ze extends wZe.MalloyElement{constructor(e,r){super({view:r}),this.name=e,this.view=r,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=NZe.extendNoteMethod}makeEntry(e){const r=new IZe.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,LZe.detectAndRemovePartialStages)(r,this);return{type:"turtle",name:this.name,pipeline:s,annotation:{...this.note,inherits:i},location:this.location}}}Dy.ViewFieldDeclaration=$Ze;var qn={};Object.defineProperty(qn,"__esModule",{value:!0}),qn.LegalRefinementStage=qn.QueryClass=void 0;var Pae;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(Pae||(qn.QueryClass=Pae={}));var Uae;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(Uae||(qn.LegalRefinementStage=Uae={}));var BZe=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]}),kZe=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),MZe=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)&&BZe(e,t,r);return kZe(e,t),e};Object.defineProperty(Ry,"__esModule",{value:!0}),Ry.NestFieldDeclaration=void 0;const PZe=MZe(Xe),UZe=Vp,jZe=Dy,jae=qn;class qZe extends jZe.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=jae.LegalRefinementStage.Single,this.forceQueryClass=jae.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]&&PZe.isQuerySegment(r[0])?r[0].compositeFieldUsage:void 0,o=(0,UZe.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")}}Ry.NestFieldDeclaration=qZe;var Xp={},ai={};Object.defineProperty(ai,"__esModule",{value:!0}),ai.ErrorFactory=void 0;const qae="~malformed~";class pB{static get structDef(){return{type:"table",name:qae,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],errorFactory:!0}}static get joinDef(){return{type:"table",name:qae,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:pB.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}}ai.ErrorFactory=pB,Object.defineProperty(Xp,"__esModule",{value:!0}),Xp.DefineSourceList=Xp.DefineSource=void 0;const HZe=ai,Hae=Je,QZe=kr;class zZe extends Hae.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=QZe.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),HZe.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`)}}Xp.DefineSource=zZe;class GZe extends Hae.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}}Xp.DefineSourceList=GZe;var Zp={};Object.defineProperty(Zp,"__esModule",{value:!0}),Zp.DefineQueryList=Zp.DefineQuery=void 0;const Qae=Je,WZe=kr;class VZe extends Qae.MalloyElement{constructor(e,r){super({queryExpr:r}),this.name=e,this.queryExpr=r,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=WZe.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})}}Zp.DefineQuery=VZe;class YZe extends Qae.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}}Zp.DefineQueryList=YZe;var Eo={};Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.Source=void 0;const KZe=Je;class JZe extends KZe.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=JZe;var Fy={},e2={},K4={},Dc={};Object.defineProperty(Dc,"__esModule",{value:!0}),Dc.mergeFields=Dc.nameFromDef=void 0;function mB(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}Dc.nameFromDef=mB;function XZe(t,e){if(t===void 0)return e;const r=new Set(e.map(s=>mB(s))),i=t.filter(s=>!r.has(mB(s)));return i.push(...e),i}Dc.mergeFields=XZe;var wy={},Pr={},Ta={},ZZe=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]}),eet=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tet=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)&&ZZe(e,t,r);return eet(e,t),e};Object.defineProperty(Ta,"__esModule",{value:!0}),Ta.DefinedParameter=Ta.AbstractParameter=Ta.SpaceParam=void 0;const net=Rc,zae=tet(Zt),Gae=lt;class gB extends net.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}}Ta.SpaceParam=gB;class ret extends gB{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(){const e=this.parameter(),r=e.type;return{...r==="filter expression"?{type:r}:zae.atomicDef(e),expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:(0,Gae.emptyCompositeFieldUsage)()}}}Ta.AbstractParameter=ret;class iet extends gB{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){const e=this.parameter(),r=e.type;return{...r==="filter expression"?{type:r}:zae.atomicDef(e),expressionType:"scalar",evalSpace:"input",compositeFieldUsage:(0,Gae.emptyCompositeFieldUsage)()}}}Ta.DefinedParameter=iet;var Xx={},set=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]}),oet=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uet=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)&&set(e,t,r);return oet(e,t),e};Object.defineProperty(Xx,"__esModule",{value:!0}),Xx.StructSpaceFieldBase=void 0;const Wae=lt,aet=Xe,cet=uet(Zt),fet=Mr;class xet extends fet.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,aet.isSourceDef)(this.structDef)?{type:this.structDef.type,evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(e=this.structDef.onCompositeFieldUsage)!==null&&e!==void 0?e:(0,Wae.emptyCompositeFieldUsage)()}:{...cet.atomicDef(this.structDef),evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(r=this.structDef.onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Wae.emptyCompositeFieldUsage)()}}}Xx.StructSpaceFieldBase=xet;var Ny={};Object.defineProperty(Ny,"__esModule",{value:!0}),Ny.ColumnSpaceField=void 0;const det=Mr;class het extends det.SpaceField{constructor(e){super(),this.sourceFieldDef=e}fieldDef(){return this.sourceFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.sourceFieldDef)}constructorFieldDef(){return this.sourceFieldDef}}Ny.ColumnSpaceField=het;var J4={};Object.defineProperty(J4,"__esModule",{value:!0}),J4.IRViewField=void 0;const pet=Jp;class met extends pet.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()}}J4.IRViewField=met,Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.StaticSourceSpace=Pr.StructSpaceField=Pr.StaticSpace=void 0;const get=va,t2=Xe,yet=Ta,Eet=Mr,Ly=Xx,Aet=Ny,_et=J4;class yB{constructor(e,r){this.type="fieldSpace",this.fromStruct=e,this.structDialect=r}dialectName(){return this.structDialect}dialectObj(){try{return(0,get.getDialect)(this.structDialect)}catch{return}}defToSpaceField(e){return(0,t2.isJoined)(e)?new EB(e,this.structDialect):(0,t2.isTurtle)(e)?new _et.IRViewField(this,e):new Aet.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,t2.isSourceDef)(this.fromStruct)&&this.fromStruct.parameters)for(const[e,r]of Object.entries(this.fromStruct.parameters))e in this.memoMap||(this.memoMap[e]=new yet.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,t2.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 Eet.SpaceField){const u=s.fieldDef();if(u&&(!(s instanceof Ly.StructSpaceFieldBase)&&(0,t2.isJoined)(u)&&(s=new EB(u,this.structDialect)),r.addReference({type:s instanceof Ly.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 Ly.StructSpaceFieldBase?[{...s.joinPathElement,name:r.refString}]:[];if(i.length){if(s instanceof Ly.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}}Pr.StaticSpace=yB;class EB extends Ly.StructSpaceFieldBase{constructor(e,r){super(e),this.forDialect=r}get fieldSpace(){return(0,t2.isSourceDef)(this.structDef)?new Vae(this.structDef):new yB(this.structDef,this.forDialect)}}Pr.StructSpaceField=EB;class Vae extends yB{constructor(e){super(e,e.dialect),this.source=e}structDef(){return this.source}emptyStructDef(){const e={...this.source};return e.parameters={},e.fields=[],e}}Pr.StaticSourceSpace=Vae,Object.defineProperty(wy,"__esModule",{value:!0}),wy.JoinSpaceField=void 0;const vet=Pr;class Cet extends vet.StructSpaceField{constructor(e,r,i){super(r.getStructDef(e),i),this.parameterSpace=e,this.join=r}}wy.JoinSpaceField=Cet;var n2={};Object.defineProperty(n2,"__esModule",{value:!0}),n2.ParameterSpace=void 0;const bet=Ta;class Tet{constructor(e){this.type="fieldSpace",this._map={};for(const r of e)this._map[r.name]=new bet.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}}n2.ParameterSpace=Tet;var 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]}),Det=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Oet=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 Det(e,t),e};Object.defineProperty(K4,"__esModule",{value:!0}),K4.DynamicSpace=void 0;const Fet=Oet(Xe),wet=Dc,Net=ai,Let=Mr,Iet=wy,$et=Jp,Yae=Ta,Bet=Pr,ket=Xx,Met=n2;class Pet extends Bet.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 Yae.AbstractParameter(r)));return this}parameterSpace(){return new Met.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,wet.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 Yae.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 ket.StructSpaceFieldBase?s.push([l,c]):c instanceof $et.ViewField?o.push([l,c]):c instanceof Let.SpaceField&&i.push([l,c]);const u=[...i,...s,...o],a=this.parameterSpace();for(const[l,c]of u)if(c instanceof Iet.JoinSpaceField){const f=c.join.getStructDef(a);Net.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&&Fet.isSourceDef(this.sourceDef)&&(this.sourceDef.queryTimezone=this.newTimezone),this.sourceDef}emptyStructDef(){const e={...this.fromSource};return e.fields=[],e}}K4.DynamicSpace=Pet;var Iy={};Object.defineProperty(Iy,"__esModule",{value:!0}),Iy.RenameSpaceField=void 0;const Uet=Mr;class jet extends Uet.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()}}Iy.RenameSpaceField=jet,Object.defineProperty(e2,"__esModule",{value:!0}),e2.RefinedSpace=void 0;const qet=K4,Het=Rc,Qet=Iy,zet=Mr;class AB extends qet.DynamicSpace{static filteredFrom(e,r,i,s,o){const u=new AB(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 zet.SpaceField?u.setEntry(x.as,new Qet.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,Het.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}}e2.RefinedSpace=AB;var Oc={},Bs={};Object.defineProperty(Bs,"__esModule",{value:!0}),Bs.DefinitionList=void 0;const Get=Je,Kae=kr;class Wet extends Get.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,Kae.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(const e of this.elements)(0,Kae.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}}Bs.DefinitionList=Wet,Object.defineProperty(Oc,"__esModule",{value:!0}),Oc.DeclareFields=void 0;const Vet=Bs,Yet=qn;class Ket extends Vet.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="declareFields",this.queryRefinementStage=Yet.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)}}Oc.DeclareFields=Ket;var Ra={};Object.defineProperty(Ra,"__esModule",{value:!0}),Ra.Filter=Ra.FilterElement=void 0;const Jae=Xe,Jet=jn,Xae=Je,_B=qn;class Xet extends Xae.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}}}Ra.FilterElement=Xet;class Zet extends Xae.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=_B.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?_B.LegalRefinementStage.Tail:_B.LegalRefinementStage.Head}checkedFilterCondition(e,r){const i=r.filterCondition(e);if(this.havingClause!==void 0){const s=(0,Jae.expressionIsAggregate)(i.expressionType),o=(0,Jae.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(Jet.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))}}}Ra.Filter=Zet;var r2={};Object.defineProperty(r2,"__esModule",{value:!0}),r2.FieldListEdit=void 0;const ett=Je;class ttt extends ett.MalloyElement{constructor(e,r){super({refs:r}),this.edit=e,this.refs=r,this.elementType="fieldListEdit"}}r2.FieldListEdit=ttt;var i2={};Object.defineProperty(i2,"__esModule",{value:!0}),i2.PrimaryKey=void 0;const ntt=Je;class rtt extends ntt.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}}i2.PrimaryKey=rtt;var s2={};Object.defineProperty(s2,"__esModule",{value:!0}),s2.Views=void 0;const itt=Bs;class stt extends itt.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="turtleDefList"}get delarationNames(){return this.list.map(e=>e.name)}}s2.Views=stt;var o2={};Object.defineProperty(o2,"__esModule",{value:!0}),o2.TimezoneStatement=void 0;const ott=Je,utt=by;class att extends ott.MalloyElement{constructor(e){super(),this.tz=e,this.elementType="timezone",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}get isValid(){try{return utt.DateTime.fromISO("2020-02-19T00:00:00",{zone:this.tz}),!0}catch{return!1}}queryExecute(e){e.resultFS.setTimezone(this.tz)}}o2.TimezoneStatement=att;var Fc={};Object.defineProperty(Fc,"__esModule",{value:!0}),Fc.ModelAnnotation=Fc.ObjectAnnotation=void 0;const ltt=Je,ctt=ui;class Zae extends ltt.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}}Fc.ObjectAnnotation=Zae;class ftt extends Zae{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,r){const i=(0,ctt.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)}}Fc.ModelAnnotation=ftt;var wc={};Object.defineProperty(wc,"__esModule",{value:!0}),wc.Renames=wc.RenameField=void 0;const xtt=Iy,ele=Je,dtt=Mr;class htt extends ele.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 dtt.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new xtt.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}}wc.RenameField=htt;class ptt extends ele.ListOf{constructor(e,r){super(e),this.accessModifier=r,this.elementType="renameFields"}get delarationNames(){return this.list.map(e=>e.getName())}}wc.Renames=ptt;var xs={};Object.defineProperty(xs,"__esModule",{value:!0}),xs.JoinStatement=xs.ExpressionJoin=xs.KeyJoin=xs.Join=void 0;const vB=Xe,mtt=wy,gtt=Bs,ytt=Je,Ett=kr,tle=ai,Att=qn;class CB extends ytt.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=Ett.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new mtt.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"),tle.ErrorFactory.structDef)}}xs.Join=CB;class _tt extends CB{constructor(e,r,i){super({name:e,sourceExpr:r,keyExpr:i}),this.name=e,this.sourceExpr=r,this.keyExpr=i,this.elementType="joinOnKey"}getStructDef(e){var r;const i=this.getStructDefFromExpr(e);if(!(0,vB.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,vB.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")}}xs.KeyJoin=_tt;class vtt extends CB{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}getStructDef(e){var r;const i=this.sourceExpr.getSource();if(!i)return this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),tle.ErrorFactory.joinDef;const s=i.getSourceDef(e);let o="left";if(this.inExperiment("join_types",!0)&&(o=this.matrixOperation),!(0,vB.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}}xs.ExpressionJoin=vtt;class Ctt extends gtt.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="joinStatement",this.forceQueryClass=void 0,this.queryRefinementStage=Att.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)}}xs.JoinStatement=Ctt;var du={};Object.defineProperty(du,"__esModule",{value:!0}),du.IncludeListItem=du.IncludeExceptItem=du.IncludeAccessItem=du.IncludeItem=void 0;const nle=Je,rle=kr;class SB extends nle.MalloyElement{}du.IncludeItem=SB;class Stt extends SB{constructor(e,r){super(),this.kind=e,this.fields=r,this.elementType="include-access-item",this.isNoteableObj=!0,this.extendNote=rle.extendNoteMethod,this.has({fields:r})}}du.IncludeAccessItem=Stt;class btt extends SB{constructor(e){super(),this.fields=e,this.elementType="include-except-item",this.kind="except",this.has({fields:e})}}du.IncludeExceptItem=btt;class Ttt extends nle.MalloyElement{constructor(e,r){super({name:e}),this.name=e,this.as=r,this.elementType="include-list-item",this.isNoteableObj=!0,this.extendNote=rle.extendNoteMethod}}du.IncludeListItem=Ttt;var yt={},$y={},Rtt=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]}),Dtt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ott=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)&&Rtt(e,t,r);return Dtt(e,t),e};Object.defineProperty($y,"__esModule",{value:!0}),$y.ReferenceField=void 0;const ile=Xe,sle=Ott(Zt),ole=Mr,Ftt=lt;class wtt extends ole.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(ile.TD.isAtomic(o))this.queryFieldDef={...(0,ile.mkFieldDef)(sle.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 ole.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,Ftt.joinedCompositeFieldUsage)(r,i.compositeFieldUsage)},this.memoTypeDesc}return sle.errorT}}$y.ReferenceField=wtt;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 In=Pi;function Ntt(t,e){if(t.type==="turtle"||!(0,In.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="select-of-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="select-of-analytic";else if((0,In.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=Ntt;function Ltt(t,e){if(t.type==="turtle"||!(0,In.expressionIsScalar)(t.expressionType)){let r,i;if(t.type==="turtle")r="a view",i="index-of-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="an analytic",i="index-of-analytic";else if((0,In.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=Ltt;function Itt(t,e){if(!(0,In.expressionIsScalar)(t.expressionType))if((0,In.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,In.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=Itt;function $tt(t,e){if(!(0,In.expressionIsAggregate)(t.expressionType))if((0,In.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,In.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=$tt;function Btt(t,e){t.type==="turtle"?e.logError("view-in-declare","Views cannot be used in a declare block"):(0,In.expressionIsAnalytic)(t.expressionType)&&e.logError("analytic-in-declare","Analytic expressions can not be used in a declare block")}sr.typecheckDeclare=Btt;function ktt(t,e){if(t.type==="turtle"||!(0,In.expressionIsAnalytic)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="calculate-of-view";else if((0,In.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="calculate-of-aggregate";else if((0,In.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=ktt;function Mtt(t,e){if(t.type==="turtle"||!(0,In.expressionIsAggregate)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="aggregate-of-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="aggregate-of-analytic";else if((0,In.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=Mtt;function Ptt(t,e){if(t.type==="turtle"||!(0,In.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="group-by-view";else if((0,In.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="group-by-analytic";else if((0,In.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=Ptt,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 Utt=$y,jtt=Bs,ule=Je,ale=kr,Nc=sr;class ji extends ule.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=ale.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 Utt.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=ji;class qtt extends ji{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}yt.AcceptExceptFieldReference=qtt;class Htt extends ji{constructor(){super(...arguments),this.elementType="accessModifierFieldReference"}typecheck(){}}yt.AccessModifierFieldReference=Htt;class Qtt extends ji{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}yt.ExpressionFieldReference=Qtt;class ztt extends ji{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}yt.PartitionByFieldReference=ztt;class Gtt extends ji{constructor(){super(...arguments),this.elementType="parameterFieldReference"}typecheck(){}}yt.ParameterFieldReference=Gtt;class Wtt extends ji{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,Nc.typecheckCalculate)(e,this)}}yt.CalculateFieldReference=Wtt;class bB extends ji{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,Nc.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return bB.indexOutputName(this.path)}}yt.IndexFieldReference=bB;class Vtt extends ji{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,Nc.typecheckAggregate)(e,this)}}yt.AggregateFieldReference=Vtt;class Ytt extends ji{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,Nc.typecheckGroupBy)(e,this)}}yt.GroupByFieldReference=Ytt;class Ktt extends ji{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,Nc.typecheckProject)(e,this)}}yt.ProjectFieldReference=Ktt;class Jtt extends ji{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,Nc.typecheckDeclare)(e,this)}}yt.DeclareFieldReference=Jtt;class Xtt extends ji{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,Nc.typecheckMeasure)(e,this)}}yt.MeasureFieldReference=Xtt;class Ztt extends ji{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,Nc.typecheckDimension)(e,this)}}yt.DimensionFieldReference=Ztt;class ent extends ji{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}yt.ViewOrScalarFieldReference=ent;class tnt extends ule.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=ale.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=tnt;class nnt extends jtt.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}yt.FieldReferences=nnt,Object.defineProperty(Fy,"__esModule",{value:!0}),Fy.RefinedSource=void 0;const rnt=Xe,int=e2,snt=Oc,ont=Ra,unt=r2,ant=i2,lnt=s2,cnt=Eo,fnt=o2,xnt=Fc,dnt=wc,hnt=n2,pnt=xs,lle=du,TB=yt;class mnt extends cnt.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 xnt.ObjectAnnotation)continue;const C=v;if(v instanceof ant.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 unt.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 snt.DeclareFields||v instanceof pnt.JoinStatement||v instanceof lnt.Views||v instanceof dnt.Renames?(u.push(...v.list),v.accessModifier&&c.push({fields:v.delarationNames,access:v.accessModifier})):v instanceof ont.Filter?a.push(v):v instanceof fnt.TimezoneStatement?l=v.tz:C.logError("unexpected-source-property",`Unexpected source property: '${C.elementType}'`)}const f=r?new hnt.ParameterSpace(r):void 0,x=structuredClone(this.source.getSourceDef(f)),{fieldsToInclude:h,modifiers:p,renames:m,notes:g}=gnt(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 y=int.RefinedSpace.filteredFrom(x,o,h,m,f);if(l&&y.setTimezone(l),r&&y.addParameters(r),y.pushFields(...u),s){const v=s.field.getField(y);v.error&&s.logError(v.error.code,v.error.message)}y.addAccessModifiers(p),y.addNotes(g);const E=y.structDef(),A=E.filterList||[];let _=!1;for(const v of a)for(const C of v.list){const b=C.filterCondition(y);(0,rnt.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)}}Fy.RefinedSource=mnt;function gnt(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 g,y;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 lle.IncludeAccessItem)for(const S of b.fields)if(S.name instanceof TB.WildcardFieldReference)S.name.joinPath&&S.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"),g!==void 0?b.logError("already-used-star-in-include","Wildcard already used in this include block"):(g=(r=b.kind)!==null&&r!==void 0?r:"inherit",y={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 TB.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 lle.IncludeExceptItem)for(const S of b.fields)S instanceof TB.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",g="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(g!==void 0)for(const b of v)g!=="inherit"&&E.set(b,g),y&&_.set(b,{...y});return p!=="exclude"?g!==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 ynt=Je;class RB extends ynt.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 RB&&r.errored){e=!1;break}return e}}hu.SourceQueryElement=RB;var X4={},Zx={};Object.defineProperty(Zx,"__esModule",{value:!0}),Zx.QuerySource=void 0;const Ent=Eo,Ant=Pp;class _nt extends Ent.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,Ant.v4)()}`,type:"query_source",query:s.query};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(o),{...o,parameters:this.packParameters(r)}}}Zx.QuerySource=_nt;var u2={},By={};Object.defineProperty(By,"__esModule",{value:!0}),By.QueryBase=void 0;const DB=lt,cle=Xe,vnt=Vp,Cnt=Je;class Snt extends Cnt.MalloyElement{resolveCompositeSource(e,r){var i;const s=r.pipeline[0];if(s&&((0,cle.isQuerySegment)(s)||(0,cle.isIndexSegment)(s))){const o=(i=s.compositeFieldUsage)!==null&&i!==void 0?i:(0,DB.emptyCompositeFieldUsage)();if(!(0,DB.isEmptyCompositeFieldUsage)(o)||e.type==="composite")return(0,DB.resolveCompositeSources)(e,o).sourceDef}}query(){const{query:e}=this.queryComp(!0);return{...e,pipeline:(0,vnt.detectAndRemovePartialStages)(e.pipeline,this)}}}By.QueryBase=Snt,Object.defineProperty(u2,"__esModule",{value:!0}),u2.QueryArrow=void 0;const bnt=Xe,Tnt=Eo,fle=Pr,Rnt=By;class Dnt extends Rnt.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 Tnt.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,bnt.refIsStructDef)(h.structRef)?h.structRef:this.source.getSourceDef(void 0),o=new fle.StaticSourceSpace(i)}else{const h=this.source.queryComp(e);s=h.query,i=h.outputStruct,o=new fle.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}}}u2.QueryArrow=Dnt,Object.defineProperty(X4,"__esModule",{value:!0}),X4.SQArrow=void 0;const Ont=hu,Fnt=Zx,wnt=u2;class Nnt extends Ont.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 wnt.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 Fnt.QuerySource(e);return this.has({asSource:r}),r}}X4.SQArrow=Nnt;var Z4={},a2={},ks={};Object.defineProperty(ks,"__esModule",{value:!0}),ks.getStructFieldDef=ks.getFinalStruct=ks.opOutputStruct=void 0;const xle=lc,Lnt=Ls,eb=Xe,dle=ai;function hle(t,e,r){const i=dle.ErrorFactory.didCreate(e)||(0,eb.structHasErrors)(e);(0,eb.isPartialSegment)(r)&&(r={...r,type:"reduce"});const s=(0,eb.segmentHasErrors)(r);if(!i&&!s)try{const o=Lnt.Segment.nextStructDef(e,r);if((0,eb.isSourceDef)(o))return o;t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: RETURNED A NON SOURCE
1158
1158
  STRUCTDEF: ${(0,xle.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,xle.inspect)(r,{breakLength:72,depth:1/0})}`)}return dle.ErrorFactory.structDef}ks.opOutputStruct=hle;function Int(t,e,r){for(const i of r)e=hle(t,e,i);return e}ks.getFinalStruct=Int;function $nt(t,e){return t.fields.find(r=>(r.as||r.name)===e)}ks.getStructFieldDef=$nt,Object.defineProperty(a2,"__esModule",{value:!0}),a2.QueryRefine=void 0;const Bnt=Pr,knt=ks,Mnt=By;class Pnt extends Mnt.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 Bnt.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,knt.getFinalStruct)(this.refinement,r.inputStruct,s),inputStruct:r.inputStruct}}}a2.QueryRefine=Pnt;var ky={},l2={},ds={};Object.defineProperty(ds,"__esModule",{value:!0}),ds.mkTimeResult=ds.resolution=ds.castTo=ds.timeOffset=void 0;const OB=Xe;function Unt(t,e,r,i,s){return{node:"delta",kids:{base:(0,OB.mkTemporal)(e,t),delta:i},op:r,units:s}}ds.timeOffset=Unt;function jnt(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,OB.isCastType)(r)&&(s.srcType={type:r}),s}ds.castTo=jnt;function qnt(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}ds.resolution=qnt;function Hnt(t,e){if(e){if(t.type==="timestamp")return{...t,timeframe:e};if((0,OB.isDateUnit)(e))return{...t,timeframe:e}}return t}ds.mkTimeResult=Hnt;var ed={},ct={},Gt={};Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.literalTimeResult=Gt.literalExprValue=Gt.computedErrorExprValue=Gt.computedTimeResult=Gt.computedExprValue=void 0;const ple=Pi,FB=lt;function My({value:t,dataType:e,from:r}){return{...e,value:t,expressionType:(0,ple.maxOfExpressionTypes)(r.map(i=>i.expressionType)),evalSpace:(0,ple.mergeEvalSpaces)(...r.map(i=>i.evalSpace)),compositeFieldUsage:(0,FB.mergeCompositeFieldUsage)(...r.map(i=>i.compositeFieldUsage))}}Gt.computedExprValue=My;function Qnt({value:t,dataType:e,from:r,timeframe:i}){const s=My({value:t,dataType:e,from:r}),o={...e,expressionType:s.expressionType,evalSpace:s.evalSpace,value:s.value,compositeFieldUsage:(0,FB.mergeCompositeFieldUsage)(...r.map(u=>u.compositeFieldUsage))};return i&&(o.timeframe=i),o}Gt.computedTimeResult=Qnt;function znt({dataType:t,from:e,error:r}){return My({dataType:t??{type:"error"},value:{node:"error",message:r},from:e})}Gt.computedErrorExprValue=znt;function Gnt(t){return My({...t,from:[]})}Gt.literalExprValue=Gnt;function Wnt({value:t,dataType:e,timeframe:r}){const i=My({value:t,dataType:e,from:[]}),s={...e,expressionType:i.expressionType,evalSpace:i.evalSpace,value:i.value,compositeFieldUsage:(0,FB.emptyCompositeFieldUsage)()};return r&&(s.timeframe=r),s}Gt.literalTimeResult=Wnt;var c2={};Object.defineProperty(c2,"__esModule",{value:!0}),c2.isGranularResult=void 0;function Vnt(t){return t.type==="date"||t.type==="timestamp"?t.timeframe!==void 0:!1}c2.isGranularResult=Vnt;var pu={};Object.defineProperty(pu,"__esModule",{value:!0}),pu.isComparison=pu.isEquality=pu.getExprNode=void 0;function Ynt(t){switch(t){case"~":return"like";case"!~":return"!like"}return t}pu.getExprNode=Ynt;function mle(t){return t==="="||t==="!="||t==="~"||t==="!~"}pu.isEquality=mle;function Knt(t){return mle(t)||t===">="||t==="<="||t===">"||t==="<"}pu.isComparison=Knt;var Jnt=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]}),Xnt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Znt=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)&&Jnt(e,t,r);return Xnt(e,t),e};Object.defineProperty(ct,"__esModule",{value:!0}),ct.checkFilterExpression=ct.applyBinary=ct.getMorphicValue=ct.ExprDuration=ct.ExpressionDef=ct.ATNodeType=void 0;const Lc=Xe,td=Znt(Zt),wB=$s,Vl=Gt,ert=ds,gle=c2,trt=Je,Py=pu,Uy=Cy;class nrt extends Error{}var NB;(function(t){t[t.And=0]="And",t[t.Or=1]="Or",t[t.Value=2]="Value",t[t.Partial=3]="Partial"})(NB||(ct.ATNodeType=NB={}));class yle extends trt.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=td.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.type!=="error"&&!td.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 ${td.inspect(r)}`),!1):!0}apply(e,r,i,s=!1){return vle(e,i,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,Lc.expressionIsAggregate)(e.expressionType)}atNodeType(){return NB.Value}atExpr(){return this}}ct.ExpressionDef=yle;class LB extends yle{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[td.timestampT,td.dateT]}apply(e,r,i){const s=i.getExpression(e);if(this.typeCheck(this,s),(0,Lc.isTemporalType)(s.type)&&(r==="+"||r==="-")){const o=this.n.getExpression(e);if(!td.typeEq(o,td.numberT))return this.logError("invalid-duration-quantity",`Duration quantity needs number not '${o.type}`),(0,wB.errorFor)("illegal unit expression");let u;return(0,gle.isGranularResult)(s)&&s.timeframe===this.timeframe&&(u=s.timeframe),s.type==="date"&&!(0,Lc.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,ert.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]})}}ct.ExprDuration=LB;function Ele(t,e){return t.type===e?t.value:t.morphic&&t.morphic[e]}function rrt(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]})}ct.getMorphicValue=rrt;function Ale(t,e,r,i){const s=(0,Lc.isTemporalType)(e.type),o=(0,Lc.isTemporalType)(i.type),u=(0,Py.getExprNode)(r);if(s&&o)if(e.type!==i.type){const a=Ele(e,"timestamp"),l=Ele(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 irt(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 srt(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=(0,Py.getExprNode)(r),a=jy("boolean",s,o);if(a)return a;const l=Lc.TD.isSQL(s)?s.rawType||"typeless-left":void 0,c=Lc.TD.isSQL(o)?o.rawType||"typeless-right":void 0;if((l||c)&&!(s.type==="null"||o.type==="null"||l===c)){const h=qy(e,s,i,o);if(h)return{...h,type:"boolean"}}let f;if(o.type==="filter expression"){if(r!=="~"&&r!=="!~")return i.loggedErrorExpr("filter-expression-error",`Cannot use the '${r}' operator with a filter expression`);if((0,Uy.isFilterable)(s.type)){let x=o.value;for(;x.node==="()";)x=x.e;x.node!=="parameter"&&Cle(i,s.type,x);const h={node:"filterMatch",dataType:s.type,kids:{filterExpr:o.value,expr:s.value}};r==="!~"&&(h.notMatch=!0),f=h}else return e.loggedErrorExpr("filter-expression-type",`Cannot use filter expressions with type '${s.type}'`)}else if(f=Ale(e,s,r,o)||{node:u,kids:{left:s.value,right:o.value}},s.type!=="error"&&o.type!=="error"&&(r==="~"||r==="!~")&&(s.type!=="string"||o.type!=="string")){let x=irt(s,o);if(x)r[0]==="!"&&(x={node:"not",e:{...x}});else throw new nrt("Incompatible types for match('~') operator");f=x}return(0,Vl.computedExprValue)({dataType:{type:"boolean"},value:f,from:[s,o]})}function ort(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=jy("boolean",s,o);if(u)return u;const a=qy(e,s,i,o);if(a)return{...a,type:"boolean"};const l=Ale(e,s,r,o)||{node:(0,Py.getExprNode)(r),kids:{left:s.value,right:o.value}};return(0,Vl.computedExprValue)({dataType:{type:"boolean"},value:l,from:[s,o]})}function _le(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=jy("number",s,o);if(u)return u;const a=qy(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,wB.errorFor)("numbers required")}function urt(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=qy(e,s,i,o);if(u)return u;const a=(0,Lc.isTemporalType)(s.type),l=jy(a?"error":"number",s,o);if(l)return l;if(a){let c=i;if(o.type!=="duration")if((0,gle.isGranularResult)(s))c=new LB(i,s.timeframe);else if(s.type==="date")c=new LB(i,"day");else return e.loggedErrorExpr("time-offset-type-mismatch",`Can not offset time by '${o.type}'`);return c.apply(t,r,e)}return _le(t,e,r,i)}function vle(t,e,r,i){if((0,Py.isEquality)(r))return srt(t,e,r,i);if((0,Py.isComparison)(r))return ort(t,e,r,i);if(r==="+"||r==="-")return urt(t,e,r,i);if(r==="*")return _le(t,e,r,i);if(r==="/"||r==="%"){const s=e.getExpression(t),o=i.getExpression(t),u=qy(e,s,i,o);if(u)return u;const a=jy("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,wB.errorFor)("divide type mismatch")}return e.loggedErrorExpr("unexpected-binary-operator",`Cannot use ${r} operator here`)}ct.applyBinary=vle;function jy(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 qy(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}function Cle(t,e,r){for(var i,s,o,u;r.node==="()";)r=r.e;if(r.node!=="filterLiteral"){t.logError("filter-expression-error","Expected a filter expression literal here");return}const a=r.filterSrc;let l;e==="date"||e==="timestamp"?l=(i=Uy.TemporalFilterExpression.parse(a).log[0])===null||i===void 0?void 0:i.message:e==="string"?l=(s=Uy.StringFilterExpression.parse(a).log[0])===null||s===void 0?void 0:s.message:e==="number"?l=(o=Uy.NumberFilterExpression.parse(a).log[0])===null||o===void 0?void 0:o.message:e==="boolean"?l=(u=Uy.BooleanFilterExpression.parse(a).log[0])===null||u===void 0?void 0:u.message:t.logError("filter-expression-type",`Cannot apply filter expression to type ${e}`),l!==void 0&&t.logError("filter-expression-error",`Filter syntax error: ${l}`)}ct.checkFilterExpression=Cle,Object.defineProperty(ed,"__esModule",{value:!0}),ed.ExprIdReference=void 0;const art=Xe,lrt=ct,crt=lt;class frt extends lrt.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,crt.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,art.expressionIsAggregate)(s.expressionType)?"output":s.evalSpace;return{...s,value:u,evalSpace:a,compositeFieldUsage:o}}return this.loggedErrorExpr(r.error.code,r.error.message)}}ed.ExprIdReference=frt,Object.defineProperty(l2,"__esModule",{value:!0}),l2.NamedSource=void 0;const IB=Xe,xrt=Eo,drt=ai,hrt=ds,Sle=Je,prt=ed,mrt=n2,grt=ct;class yrt extends xrt.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 Sle.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof Sle.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,IB.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 prt.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 mrt.ParameterSpace(i??[]),p=l.value.getExpression(h);let m=p.value;p.type==="filter expression"&&x.type==="filter expression"&&x.filterType&&(0,grt.checkFilterExpression)(l.value,x.filterType,m),p.type!==x.type&&(0,IB.isCastType)(x.type)&&(m=(0,hrt.castTo)(x.type,p.value,p.type,!0)),u[f]={...x,value:m}}}for(const l in r)l in u||((0,IB.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=drt.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}}l2.NamedSource=yrt;var Hy={},tb={};Object.defineProperty(tb,"__esModule",{value:!0}),tb.QueryHeadStruct=void 0;const Ert=Xe,Art=Eo,_rt=l2;class vrt extends Art.Source{constructor(e,r){super(),this.fromRef=e,this.sourceArguments=r,this.elementType="internalOnlyQueryHead"}structRef(){return{structRef:this.fromRef}}getSourceDef(e){if((0,Ert.refIsStructDef)(this.fromRef))return this.fromRef;const r=new _rt.NamedSource(this.fromRef,this.sourceArguments,void 0);return this.has({exploreReference:r}),r.getSourceDef(e)}}tb.QueryHeadStruct=vrt,Object.defineProperty(Hy,"__esModule",{value:!0}),Hy.QueryReference=void 0;const $B=ai,Crt=Je,Srt=tb,brt=Xe,Trt=ks;class Rrt extends Crt.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:$B.ErrorFactory.structDef,outputStruct:$B.ErrorFactory.structDef,query:$B.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 Srt.QueryHeadStruct(i.structRef,i.sourceArguments);this.has({queryHead:o});const u=o.getSourceDef(void 0),a=(0,Trt.getFinalStruct)(this,u,i.pipeline);return{query:e||(0,brt.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}}Hy.QueryReference=Rrt,Object.defineProperty(ky,"__esModule",{value:!0}),ky.SQReference=void 0;const Drt=hu,Ort=Zx,Frt=l2,ble=Hy,Tle=Pi;class wrt extends Drt.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 ble.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,Tle.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 ble.QueryReference(this.ref);this.asSource=new Ort.QuerySource(r)}else if((0,Tle.isSourceDef)(e))this.asSource=new Frt.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}}ky.SQReference=wrt,Object.defineProperty(Z4,"__esModule",{value:!0}),Z4.SQRefine=void 0;const Nrt=hu,Lrt=Zx,Irt=a2,$rt=ky;class Brt extends Nrt.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 $rt.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 Irt.QueryRefine(e,this.refine);return this.has({query:r}),r}}getSource(){const e=this.getQuery();if(e){const r=new Lrt.QuerySource(e);return this.has({queryAsSource:r}),r}}}Z4.SQRefine=Brt;var nb={},Qy={};Object.defineProperty(Qy,"__esModule",{value:!0}),Qy.QueryRaw=void 0;const krt=Xe,Mrt=Je;class Prt extends Mrt.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,krt.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=Prt;var zy={},Yl={};Object.defineProperty(Yl,"__esModule",{value:!0}),Yl.sqlKey=Yl.compileSQLInterpolation=void 0;const Urt=Ls,jrt=Xe,qrt=$t;function Hrt(t,e,r){let i,s="",o=!1;for(const u of t)if((0,jrt.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 Urt.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=Hrt;function Qrt(t,e){return`sql://${t}/${(0,qrt.generateHash)(e)}`}Yl.sqlKey=Qrt,Object.defineProperty(zy,"__esModule",{value:!0}),zy.SQLSource=void 0;const BB=Yl,zrt=Eo,Gy=ai;class Grt extends zrt.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,BB.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,BB.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 Gy.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"),Gy.ErrorFactory.structDef;if(this.requestBlock===void 0)return this.logError("failed-to-fetch-sql-source-schema","Expected to have already compiled the sql block"),Gy.ErrorFactory.structDef;const i=this.requestBlock,s=(0,BB.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
- `)),Gy.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"),Gy.ErrorFactory.structDef}}zy.SQLSource=Grt,Object.defineProperty(nb,"__esModule",{value:!0}),nb.SQSource=void 0;const Wrt=hu,Vrt=Qy,Yrt=zy;class Krt extends Wrt.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 Yrt.SQLSource){const e=new Vrt.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}nb.SQSource=Krt;var rb={};Object.defineProperty(rb,"__esModule",{value:!0}),rb.SQExtend=void 0;const Jrt=Fy,Xrt=hu;class Zrt extends Xrt.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 Jrt.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}}rb.SQExtend=Zrt;var ib={},sb={};Object.defineProperty(sb,"__esModule",{value:!0}),sb.CompositeSource=void 0;const eit=Xe,tit=Eo;class nit extends tit.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,eit.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,g=l.get(m);if(g===void 0){const y={...p,name:m,as:void 0,e:{node:"compositeField"},compositeFieldUsage:{fields:[m],joinedUsage:{}},code:this.code,location:this.codeLocation};l.set(m,y),a.push(y)}else p.accessModifier==="internal"&&(g.accessModifier="internal")}}),{type:"composite",sources:i,connection:s,fields:a,dialect:o,name:u,parameters:i[0].parameters}}}sb.CompositeSource=nit,Object.defineProperty(ib,"__esModule",{value:!0}),ib.SQCompose=void 0;const rit=sb,iit=hu;class sit extends iit.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(oit(e))return this.asSource=new rit.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}}ib.SQCompose=sit;function oit(t){return t.every(e=>e!==void 0)}var ob={},Kl={},Wy={},uit=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}),lit=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)&&uit(e,t,r);return ait(e,t),e};Object.defineProperty(Wy,"__esModule",{value:!0}),Wy.BinaryBoolean=void 0;const cit=$s,fit=lit(Zt),xit=pu,dit=Gt,hit=ct;class pit extends hit.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=[fit.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,dit.computedExprValue)({dataType:{type:"boolean"},value:{node:(0,xit.getExprNode)(this.op),kids:{left:r.value,right:i.value}},from:[r,i]}):(0,cit.errorFor)("logical-op expected boolean")}}Wy.BinaryBoolean=pit;var mit=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]}),git=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),yit=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)&&mit(e,t,r);return git(e,t),e};Object.defineProperty(Kl,"__esModule",{value:!0}),Kl.ExprLegacyIn=Kl.ExprEquality=Kl.ExprCompare=void 0;const fn=yit(Zt),Eit=Gt,Ait=ct,_it=Wy,vit={"~":[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 Rle extends _it.BinaryBoolean{constructor(e,r,i){super(e,r,i),this.elementType="a<=>b",this.legalChildTypes=vit[r]}getExpression(e){return this.right.apply(e,this.op,this.left)}}Kl.ExprCompare=Rle;class Cit extends Rle{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=Cit;class Sit extends Ait.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,Eit.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=Sit;var Vy={},f2={};Object.defineProperty(f2,"__esModule",{value:!0}),f2.ExprTime=void 0;const bit=Xe,Tit=Gt,Rit=ct;class kB extends Rit.ExpressionDef{constructor(e,r,i){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue=(0,Tit.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,bit.isTemporalType)(r.type)&&(s.srcType={type:r.type}),i=s}return new kB(e,i,[r])}}f2.ExprTime=kB;var Ic={};Object.defineProperty(Ic,"__esModule",{value:!0}),Ic.Range=void 0;const Dit=$s,Oit=Gt,Fit=ct;class wit extends Fit.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,Oit.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,Dit.errorFor)("a range is not a value")}}Ic.Range=wit;var Nit=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]}),Lit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Iit=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)&&Nit(e,t,r);return Lit(e,t),e};Object.defineProperty(Vy,"__esModule",{value:!0}),Vy.ExprGranularTime=void 0;const MB=Xe,$it=$s,Dle=Iit(Zt),Ole=ds,Bit=ct,ub=f2,Fle=Ic;class kit extends Bit.ExpressionDef{constructor(e,r,i){super({expr:e}),this.expr=e,this.units=r,this.truncate=i,this.elementType="granularTime",this.legalChildTypes=[Dle.timestampT,Dle.dateT]}granular(){return!0}getExpression(e){const r=this.units,i=this.expr.getExpression(e);if(MB.TD.isTemporal(i)){const o={...i,timeframe:r};return this.truncate&&(o.value={node:"trunc",e:(0,MB.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,MB.isDateUnit)(r)?"date":"timestamp"),{...s,value:(0,$it.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const r=this.getExpression(e),i={node:"numberLiteral",literal:"1"};if(r.type==="timestamp"){const a=ub.ExprTime.fromValue("timestamp",r),l=new ub.ExprTime("timestamp",(0,Ole.timeOffset)("timestamp",r.value,"+",i,this.units),[r]);return new Fle.Range(a,l)}const s=new ub.ExprTime("date",r.value,[r]),o=(0,Ole.timeOffset)("date",r.value,"+",i,this.units),u=new ub.ExprTime("date",o,[r]);return new Fle.Range(s,u)}}Vy.ExprGranularTime=kit,Object.defineProperty(ob,"__esModule",{value:!0}),ob.Apply=void 0;const Mit=Kl,Pit=c2,wle=Vy;class Uit extends Mit.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,Pit.isGranularResult)(i)&&(r=new wle.ExprGranularTime(this.right,i.timeframe,!1))}return r instanceof wle.ExprGranularTime?r.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}ob.Apply=Uit;var x2={},jit=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]}),qit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Hit=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)&&jit(e,t,r);return qit(e,t),e};Object.defineProperty(x2,"__esModule",{value:!0}),x2.BinaryNumeric=void 0;const Qit=Hit(Zt),zit=ct;class Git extends zit.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=[Qit.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}x2.BinaryNumeric=Git;var ab={},Wit=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]}),Vit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Yit=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)&&Wit(e,t,r);return Vit(e,t),e};Object.defineProperty(ab,"__esModule",{value:!0}),ab.Boolean=void 0;const Kit=ct,Jit=Yit(Zt);let Xit=class extends Kit.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...Jit.boolT,value:{node:this.value}}}};ab.Boolean=Xit;var d2={};Object.defineProperty(d2,"__esModule",{value:!0}),d2.ConstantExpression=d2.ConstantFieldSpace=void 0;const Zit=ct;class Nle{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}}d2.ConstantFieldSpace=Nle;class est extends Zit.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 Nle),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)}}d2.ConstantExpression=est;var $c={};Object.defineProperty($c,"__esModule",{value:!0}),$c.FunctionOrdering=$c.FunctionOrderBy=void 0;const PB=Xe,Lle=Je,tst=ed;class nst extends Lle.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,PB.expressionIsAggregate)(r.expressionType)||((0,PB.expressionIsScalar)(r.expressionType)?(!(this.field instanceof tst.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,PB.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}}}$c.FunctionOrderBy=nst;class rst extends Lle.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))}}$c.FunctionOrdering=rst;var lb={};Object.defineProperty(lb,"__esModule",{value:!0}),lb.ExprAddSub=void 0;const ist=x2;class sst extends ist.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}lb.ExprAddSub=sst;var Jl={},ost=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]}),ust=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ast=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)&&ost(e,t,r);return ust(e,t),e};Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.ExprAggregateFunction=void 0;const Yy=Xe,lst=$t,cst=$s,Ile=Pr,$le=ast(Zt),fst=yt,xst=ct,dst=Mr,hst=ed;class pst extends xst.ExpressionDef{constructor(e,r,i){super(),this.func=e,this.legalChildTypes=[$le.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 Ile.StructSpaceField))if((0,Yy.isAtomicFieldType)(p.type)){u=this.source,a={...$le.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(y=>mst(y,m[0])))&&(l=m[0].map(y=>y.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,Yy.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=jB(c,x),g=qB(this.elementType,m),y=h?g==null?void 0:g.message:"Join path is required for this calculation";if(y){const E=gst(y,x,u,this.elementType),A=(s=g==null?void 0:g.code)!==null&&s!==void 0?s:"bad-join-usage";g?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,cst.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(...UB(e,s))}if(this.expr){const i=this.expr.getExpression(e).value;r.push(...UB(e,i))}return r}}Jl.ExprAggregateFunction=pst;function mst(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 UB(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 Ile.StructSpaceField&&a.length>0){const c=i(l.fieldSpace,a);return{...c,joinPath:[{...l.joinPathElement,name:u},...c.joinPath]}}else if(l instanceof dst.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,lst.exprWalk)(e))if(s.node==="field"){const o=i(t,s.path),u=o.def;if((0,Yy.isAtomic)(u)&&!(0,Yy.isJoined)(u))if((0,Yy.hasExpression)(u)){const a=UB(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 jB(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 qB(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 gst(t,e,r,i){if(e.length===0)return t;let s=e[0];for(const m of e.slice(1))for(let g=0;g<s.length;g++){const y=s[g],E=m[g];if(y.name!==E.name){s=s.slice(0,g);break}}const o=jB(s,e),u=qB(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=jB(c,e),x=qB(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 fst.FieldReference?`${r.refString}.${i}()`:r instanceof hst.ExprIdReference?`${r.fieldReference.refString}.${i}()`:`${h}.${i}(${r.code})`,g=`${p}.${i}(${r.code})`;let y=`${t}; use \`${m}\``;return x===void 0&&p!==h&&(y+=` or \`${g}\` to get a result weighted with respect to \`${p}\``),y}}var cb={};Object.defineProperty(cb,"__esModule",{value:!0}),cb.ExprAlternationTree=void 0;const Ble=Gt,h2=ct,yst=pu;function HB(t){const e=t.atExpr();switch(e.atNodeType()){case h2.ATNodeType.And:case h2.ATNodeType.Partial:return;case h2.ATNodeType.Or:{if(e instanceof kle){const r=HB(e.left);if(r){const i=HB(e.right);if(i)return[...r,...i]}}return}default:return e.granular()?void 0:[e]}}class kle extends h2.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=HB(this)||[]),this.inList}apply(e,r,i,s){if((0,yst.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,Ble.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,Ble.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==="|"?h2.ATNodeType.Or:h2.ATNodeType.And}}cb.ExprAlternationTree=kle;var p2={};Object.defineProperty(p2,"__esModule",{value:!0}),p2.ExprAsymmetric=void 0;const Est=Jl;class Ast extends Est.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}`}}}}p2.ExprAsymmetric=Ast;var fb={};Object.defineProperty(fb,"__esModule",{value:!0}),fb.ExprAvg=void 0;const _st=p2;class vst extends _st.ExprAsymmetric{constructor(e,r,i){super("avg",e,r,i),this.has({source:r})}}fb.ExprAvg=vst;var xb={};Object.defineProperty(xb,"__esModule",{value:!0}),xb.ExprCast=void 0;const Cst=ds,Sst=Gt,bst=ct;class Tst extends bst.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,Sst.computedExprValue)({dataType:i,value:(0,Cst.castTo)(this.castType,r.value,r.type,this.safe),from:[r]})}}xb.ExprCast=Tst;var db={},Rst=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]}),Dst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ost=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)&&Rst(e,t,r);return Dst(e,t),e};Object.defineProperty(db,"__esModule",{value:!0}),db.ExprCoalesce=void 0;const Mle=Pi,Ple=Ost(Zt),Fst=ct;class wst extends Fst.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=Ple.anyAtomicT}getExpression(e){const r=this.expr.getExpression(e),i=this.altExpr.getExpression(e);return r.type==="null"?i:(Ple.typeEq(r,i)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${r.type}, ${i.type})`),{...r.type==="error"?i:r,expressionType:(0,Mle.maxExpressionType)(r.expressionType,i.expressionType),value:{node:"coalesce",kids:{left:r.value,right:i.value}},evalSpace:(0,Mle.mergeEvalSpaces)(r.evalSpace,i.evalSpace)})}}db.ExprCoalesce=wst;var hb={};Object.defineProperty(hb,"__esModule",{value:!0}),hb.ExprCount=void 0;const Nst=lt,Lst=Jl;class Ist extends Lst.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,Nst.emptyCompositeFieldUsage)()}}}hb.ExprCount=Ist;var pb={},$st=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]}),Bst=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)&&$st(e,t,r);return Bst(e,t),e};Object.defineProperty(pb,"__esModule",{value:!0}),pb.ExprCountDistinct=void 0;const mb=kst(Zt),Mst=Jl;class Pst extends Mst.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[mb.numberT,mb.stringT,mb.dateT,mb.timestampT]}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}}pb.ExprCountDistinct=Pst;var gb={},Bc={};Object.defineProperty(Bc,"__esModule",{value:!0}),Bc.Limit=void 0;const Ust=Je,jst=qn;class qst extends Ust.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=jst.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}Bc.Limit=qst;var m2={};Object.defineProperty(m2,"__esModule",{value:!0}),m2.PartitionBy=void 0;const Hst=Je;class Qst extends Hst.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}m2.PartitionBy=Qst;var Ky={},kc={};Object.defineProperty(kc,"__esModule",{value:!0}),kc.FieldName=void 0;const zst=Je;class Gst extends zst.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])}}kc.FieldName=Gst;var Wst=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]}),Vst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Yst=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)&&Wst(e,t,r);return Vst(e,t),e};Object.defineProperty(Ky,"__esModule",{value:!0}),Ky.ExprFunc=void 0;const Cr=Xe,Kst=$s,Jst=Xx,Xst=Gt,Zst=ct,eot=kc,Ule=$t,jle=Yst(Zt),tot=lt;class not extends Zst.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,Y)=>{Y!==0&&$.push(","),$.push(q.value)}),$.push(")");const D=(i=a[0])!==null&&i!==void 0?i:{type:"number"},k=this.rawType?{type:this.rawType}:D;return(0,Xst.computedExprValue)({dataType:k,value:(0,Ule.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,Kst.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 k=D.typeDesc();if((0,Cr.isAtomicFieldType)(k.type))x={...jle.atomicDef(k),expressionType:k.expressionType,value:{node:"field",path:this.source.path},evalSpace:k.evalSpace,compositeFieldUsage:k.compositeFieldUsage},h=this.source.path.slice(0,-1);else if(!(D instanceof Jst.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${k.type}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const p=[...x?[x]:[],...a],m=rot(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:g,expressionTypeErrors:y,evalSpaceErrors:E,nullabilityErrors:A,returnType:_}=m;for(const $ of y){const D=$.argIndex-(x?1:0),k=(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 ${k}, but received ${$.actualExpressionType}`)}for(const $ of E){const D=$.argIndex-(x?1:0),k=$.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 ${k}, 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=g.returnType,C=(0,Cr.maxOfExpressionTypes)([(u=v.expressionType)!==null&&u!==void 0?u:"scalar",...p.map($=>$.expressionType)]);if(!(0,Cr.expressionIsAggregate)(g.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:g,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)(g.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"),g.supportsOrderBy||$){const D=g.supportsOrderBy!=="only_default",k=r.orderBys.flatMap(q=>$?q.getAnalyticOrderBy(e):q.getAggregateOrderBy(e,D));b.kids.orderBy=k}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&&(g.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 k of D.partitionFields){const q=k.getField(e);q.found===void 0?k.logError("partition-by-not-found",`${k.refString} is not defined`):(0,Cr.expressionIsAnalytic)(q.found.typeDesc().expressionType)||(0,Cr.expressionIsUngroupedAggregate)(q.found.typeDesc().expressionType)?k.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):$.push(k.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,k=iot(D),q=k.filter(Q=>Q.type==="interpolation"&&Q.name.includes(".")).map(Q=>Q.type==="interpolation"?`\${${Q.name}}`:`\${${Q.value}}`);if(q.length>0){const Q=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",Q)}const Y=[];for(const Q of k)if(Q.type==="string")Y.push(Q.value);else if(Q.name==="TABLE")Y.push({node:"source-reference"});else{const X=new eot.FieldName(Q.name);this.has({name:X});const ce=e.lookup([X]);if(ce.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${ce.error.message}`);if(ce.found.typeDesc().type==="filter expression")return this.loggedErrorExpr("filter-expression-error","Filter expressions cannot be used in sql_ functions");ce.found.refType==="parameter"?Y.push({node:"parameter",path:[Q.name]}):Y.push({node:"field",path:[Q.name]})}S=(0,Ule.composeSQLExpr)(Y)}}const R=(0,Cr.mergeEvalSpaces)(...p.map($=>$.evalSpace)),O=R==="constant"?"constant":(0,Cr.expressionIsScalar)(C)?R:"output";return{...(0,Cr.isAtomic)(_)?jle.atomicDef(_):_,expressionType:C,value:S,evalSpace:O,compositeFieldUsage:(0,tot.mergeCompositeFieldUsage)(...p.map($=>$.compositeFieldUsage))}}}Ky.ExprFunc=not;function rot(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],g=i.params[o];if(g===void 0){u=!1;break}if(!g.allowedTypes.some(E=>{var A;const{dataTypeMatch:_,genericsSet:v}=g2(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:g})),(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:g,maxEvalSpace:E.evalSpace,actualEvalSpace:m.evalSpace}),E.evalSpace==="literal"&&m.type==="null"&&f.push({argIndex:p,param:g}),_})){u=!1;break}g.isVariadic?p===e.length-1&&(a=!0):o++}if(!a&&(o!==e.length||o!==i.params.length))continue;const x=yb(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 iot(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 g2(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.isBasicArray)(r))return(0,Cr.isRepeatedRecordFunctionParam)(i)?{dataTypeMatch:!1,genericsSet:[]}:g2(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 g2(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=g2(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 g2(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=g2(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 yb(t,e){switch(t.type){case"array":{if("fields"in t){const s=t.fields.map(o=>{const u=yb(o,e);return{...o,...u}});return{error:void 0,returnType:{type:"array",elementTypeDef:t.elementTypeDef,fields:s}}}const r=yb(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=yb(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 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]}),oot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uot=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 oot(e,t),e};Object.defineProperty(gb,"__esModule",{value:!0}),gb.ExprProps=void 0;const aot=Xe,lot=$s,cot=uot(Zt),fot=$c,xot=Bc,dot=m2,hot=ct,pot=Ky,mot=lt;class got extends hot.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=cot.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,aot.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,mot.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,lot.errorFor)("cannot filter type"))}return r}getExpression(e){const r=[];let i;const s=[],o=[];for(const a of this.statements)a instanceof dot.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 xot.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 fot.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 pot.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:i,orderBys:s}):this.expr.getExpression(e);return this.getFilteredExpression(e,u,o)}}gb.ExprProps=got;var Eb={},yot=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]}),Eot=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)&&yot(e,t,r);return Eot(e,t),e};Object.defineProperty(Eb,"__esModule",{value:!0}),Eb.ExprLogicalOp=void 0;const _ot=Wy,qle=Aot(Zt);class vot extends _ot.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[qle.boolT,qle.aggregateBoolT]}}Eb.ExprLogicalOp=vot;var Ab={},Cot=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]}),Sot=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)&&Cot(e,t,r);return Sot(e,t),e};Object.defineProperty(Ab,"__esModule",{value:!0}),Ab.ExprMax=void 0;const _b=bot(Zt),Tot=Jl;class Rot extends Tot.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[_b.numberT,_b.stringT,_b.dateT,_b.timestampT]}returns(e){return e}}Ab.ExprMax=Rot;var vb={},Dot=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]}),Oot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Fot=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)&&Dot(e,t,r);return Oot(e,t),e};Object.defineProperty(vb,"__esModule",{value:!0}),vb.ExprMin=void 0;const Cb=Fot(Zt),wot=Jl;class Not extends wot.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[Cb.numberT,Cb.stringT,Cb.dateT,Cb.timestampT]}returns(e){return e}}vb.ExprMin=Not;var Sb={},Lot=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]}),Iot=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)&&Lot(e,t,r);return Iot(e,t),e};Object.defineProperty(Sb,"__esModule",{value:!0}),Sb.ExprMinus=void 0;const Bot=$s,Hle=$ot(Zt),kot=ct;class Mot extends kot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[Hle.numberT]}getExpression(e){const r=this.expr.getExpression(e);return Hle.typeIn(r,this.legalChildTypes)?{...r,type:"number",value:{node:"unary-",e:r.value}}:(0,Bot.errorFor)("negate requires number")}}Sb.ExprMinus=Mot;var bb={};Object.defineProperty(bb,"__esModule",{value:!0}),bb.ExprMulDiv=void 0;const Pot=x2;class Uot extends Pot.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}bb.ExprMulDiv=Uot;var Tb={},Jy={};Object.defineProperty(Jy,"__esModule",{value:!0}),Jy.Unary=void 0;const jot=ct;class qot extends jot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}Jy.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]}),Qot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zot=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 Qot(e,t),e};Object.defineProperty(Tb,"__esModule",{value:!0}),Tb.ExprNot=void 0;const QB=zot(Zt),Got=Jy;class Wot extends Got.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[QB.boolT,QB.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(QB.numberT);const s=this.typeCheck(this.expr,i);return{...i,type:"boolean",value:{node:"not",e:s?i.value:{node:"false"}}}}}Tb.ExprNot=Wot;var Rb={};Object.defineProperty(Rb,"__esModule",{value:!0}),Rb.ExprNow=void 0;const Vot=ct,Yot=lt;class Kot extends Vot.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{type:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now",typeDef:{type:"timestamp"}},compositeFieldUsage:(0,Yot.emptyCompositeFieldUsage)()}}}Rb.ExprNow=Kot;var Mc={};Object.defineProperty(Mc,"__esModule",{value:!0}),Mc.ExprIsNull=Mc.PartialIsNull=Mc.ExprNULL=void 0;const Jot=Gt,Db=ct;function zB(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 Xot extends Db.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return(0,Jot.literalExprValue)({dataType:{type:"null"},value:{node:"null"}})}apply(e,r,i){return r==="!="||r==="="?zB(e,r,i):super.apply(e,r,i,!0)}}Mc.ExprNULL=Xot;class Zot extends Db.ExpressionDef{constructor(e){super(),this.op=e,this.elementType="<=> NULL"}apply(e,r,i){return zB(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial null check does not have a value")}atNodeType(){return Db.ATNodeType.Partial}}Mc.PartialIsNull=Zot;class eut extends Db.ExpressionDef{constructor(e,r){super(),this.expr=e,this.op=r,this.elementType="is null",this.has({expr:e})}getExpression(e){return zB(e,this.op,this.expr)}}Mc.ExprIsNull=eut;var Ob={};Object.defineProperty(Ob,"__esModule",{value:!0}),Ob.ExprNumber=void 0;const tut=Gt,nut=ct;class rut extends nut.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,tut.literalExprValue)({dataType:r,value:{node:"numberLiteral",literal:this.n}})}}Ob.ExprNumber=rut;var Fb={};Object.defineProperty(Fb,"__esModule",{value:!0}),Fb.ExprParens=void 0;const GB=ct;class iut extends GB.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()===GB.ATNodeType.Or?this.expr.apply(e,r,i,s):(0,GB.applyBinary)(e,i,r,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}Fb.ExprParens=iut;var wb={};Object.defineProperty(wb,"__esModule",{value:!0}),wb.ExprFilterExpression=void 0;const sut=ct;class out extends sut.ExpressionDef{constructor(e){super(),this.filterText=e,this.elementType="filter expression literal"}getExpression(){return{type:"filter expression",value:{node:"filterLiteral",filterSrc:this.filterText},expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:{fields:[],joinedUsage:{}}}}}wb.ExprFilterExpression=out;var Nb={};Object.defineProperty(Nb,"__esModule",{value:!0}),Nb.ExprRegEx=void 0;const uut=Gt,aut=ct;class lut extends aut.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return(0,uut.literalExprValue)({dataType:{type:"regular expression"},value:{node:"regexpLiteral",literal:this.regex}})}}Nb.ExprRegEx=lut;var Lb={};Object.defineProperty(Lb,"__esModule",{value:!0}),Lb.ExprString=void 0;const cut=ct,fut=Gt;class xut extends cut.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return(0,fut.literalExprValue)({dataType:{type:"string"},value:{node:"stringLiteral",literal:this.value}})}}Lb.ExprString=xut;var Ib={};Object.defineProperty(Ib,"__esModule",{value:!0}),Ib.ExprSum=void 0;const dut=p2;class hut extends dut.ExprAsymmetric{constructor(e,r,i){super("sum",e,r,i),this.has({source:r})}}Ib.ExprSum=hut;var $b={};Object.defineProperty($b,"__esModule",{value:!0}),$b.ExprTimeExtract=void 0;const Xl=Xe,Bb=Gt,WB=ct,put=Ic;class Xy extends WB.ExpressionDef{static extractor(e){const r=Xy.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=Xy.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 put.Range){let s=i.first.getExpression(e),o=i.last.getExpression(e);if(s.type==="error"||o.type==="error")return(0,Bb.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,WB.getMorphicValue)(s,"timestamp");l&&(s=l,a=!1)}else{const l=(0,WB.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,Bb.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,Bb.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,Bb.computedErrorExprValue)({dataType:{type:"number",numberType:"integer"},error:`${this.extractText} bad type ${s.type}`,from:[s]}))}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}$b.ExprTimeExtract=Xy,Xy.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var kb={},mu={},Mb={};Object.defineProperty(Mb,"__esModule",{value:!0}),Mb.QueryInputSpace=void 0;const mut=xs,gut=e2;class yut extends gut.RefinedSpace{constructor(e,r,i){super(e),this.queryOutput=r,this._isProtectedAccessSpace=i,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof mut.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}}Mb.QueryInputSpace=yut;var Eut=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]}),Aut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_ut=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)&&Eut(e,t,r);return Aut(e,t),e};Object.defineProperty(mu,"__esModule",{value:!0}),mu.ReduceFieldSpace=mu.QuerySpace=mu.QueryOperationSpace=void 0;const Pb=_ut(Xe),VB=Dc,Qle=kc,zle=Mr,vut=yt,Cut=e2,Sut=Ny,but=Pr,Tut=Mb,Da=lt,Rut=Xx;class Gle extends Cut.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 Tut.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 but.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();Pb.TD.isAtomic(c)&&Pb.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 zle.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:r,logTo:void 0})}getJoinOnCompositeFieldUsage(e){var r;const i=e.map(o=>new Qle.FieldName(o));this.astEl.has({reference:i});const s=this.exprSpace.lookup(i);if(s.found&&s.found instanceof Rut.StructSpaceFieldBase)return(0,Da.joinedCompositeFieldUsage)(e.slice(0,-1),(r=s.found.fieldDef().onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Da.emptyCompositeFieldUsage)());throw new Error("Unexpected join lookup was not found or not a struct")}getCompositeFieldUsageIncludingJoinOns(e){let r=e;const i=(0,Da.compositeFieldUsageJoinPaths)(e);for(const s of i)r=(0,Da.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 zle.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,Da.compositeFieldUsageDifference)(s,r));if(r=(0,Da.mergeCompositeFieldUsage)(r,u),!(0,Da.isEmptyCompositeFieldUsage)(u)){const a=(0,Da.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=Gle;class Wle extends Gle{addRefineFromFields(e){var r;if(Pb.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 Qle.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 Sut.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 vut.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){const e=[];let r=(0,Da.emptyCompositeFieldUsage)(),i=(0,Da.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)&&!Out(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(Pb.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,VB.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,VB.nameFromDef)(a)===o);u&&i.push(u)}r.extendSource=(0,VB.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=Wle;class Dut extends Wle{constructor(){super(...arguments),this.segmentType="reduce"}}mu.ReduceFieldSpace=Dut;function Out(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}var Fut=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]}),wut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Nut=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)&&Fut(e,t,r);return wut(e,t),e};Object.defineProperty(kb,"__esModule",{value:!0}),kb.ExprUngroup=void 0;const Vle=Xe,Lut=mu,Yle=Nut(Zt),Iut=ct;class $ut extends Iut.ExpressionDef{constructor(e,r,i){super({expr:r,fields:i}),this.control=e,this.expr=r,this.fields=i,this.legalChildTypes=Yle.anyAtomicT,this.elementType="ungroup"}getExpression(e){const r=this.expr.getExpression(e);if(!(0,Vle.expressionIsAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,Vle.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 Lut.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{...Yle.atomicDef(r),expressionType:"ungrouped_aggregate",value:i,evalSpace:"output",compositeFieldUsage:r.compositeFieldUsage}}return this.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}kb.ExprUngroup=$ut;var Ub={},But=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]}),kut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mut=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)&&But(e,t,r);return kut(e,t),e};Object.defineProperty(Ub,"__esModule",{value:!0}),Ub.ForRange=void 0;const Put=$s,Kle=Mut(Zt),jb=ds,Uut=Gt,jut=ct,qb=f2,Jle=Ic;class qut extends jut.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=[Kle.timestampT,Kle.dateT]}apply(e,r,i){const s=this.from.getExpression(e),o=i.getExpression(e);if(!this.typeCheck(i,o))return(0,Put.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,Uut.computedErrorExprValue)({dataType:{type:"boolean"},error:"for not number",from:[s,o]});const a=this.timeframe.text;let l=(0,jb.resolution)(a);if(s.type==="timestamp"&&(l="timestamp"),o.type==="date"&&l==="date"){const m=this.from,g=(0,jb.timeOffset)("date",s.value,"+",u.value,a),y=new qb.ExprTime("date",g);return new Jle.Range(m,y).apply(e,r,i)}const c=qb.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,jb.castTo)("timestamp",x,"date"),f=new qb.ExprTime("timestamp",x,[s])}const h=(0,jb.timeOffset)("timestamp",x,"+",u.value,a),p=new qb.ExprTime("timestamp",h,[s,u]);return new Jle.Range(f,p).apply(e,r,c)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}Ub.ForRange=qut;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 Pc=by,Hut=Xe,Qut=Gt,zut=Ic,Xle=f2,YB=ct;class Gut extends Error{}Sr.TimeFormatError=Gut;function nd(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 Zle="yyyy",e0e=`${Zle}-LL`,Ao=`${e0e}-dd`,t0e=`${Ao} HH`,n0e=`${t0e}:mm`,KB=`${n0e}:ss`;class r0e extends YB.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,Qut.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 JB extends r0e{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r;const i=nd(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=Pc.DateTime.fromFormat(e,KB);if(o.isValid)return new JB(i,r);if(o=Pc.DateTime.fromFormat(e,n0e),o.isValid){i.text=i.text+":00",r="minute";const u=o.plus({minute:1}).toFormat(KB);return new XB(i,r,"timestamp",u)}}}Sr.LiteralTimestamp=JB;class XB extends r0e{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,YB.getMorphicValue)(s,"timestamp"),l=(0,YB.getMorphicValue)(o,"timestamp");if(a&&l)s=a,o=l;else return super.apply(e,r,i)}if(o&&(0,Hut.isTemporalType)(u.type)){const a=u.type;return new zut.Range(new Xle.ExprTime(a,s.value),new Xle.ExprTime(a,o.value)).apply(e,r,i)}}return super.apply(e,r,i)}}class ZB extends XB{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,t0e);if(s.isValid)return r.text=r.text+":00:00",i=s.plus({hour:1}).toFormat(KB),new ZB(r,i)}}Sr.LiteralHour=ZB;class Zy extends XB{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 ek extends Zy{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,Ao);if(s.isValid)return i=s.plus({day:1}).toFormat(Ao),new ek(r,i)}}Sr.LiteralDay=ek;class tk extends Zy{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){const r=nd(e,!1);let i=r.text;const s=r.text.slice(0,10),o=Pc.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 tk(r,i)}}}Sr.LiteralWeek=tk;class nk extends Zy{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,e0e);if(s.isValid){const o=s.plus({months:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new nk(r,i)}}}Sr.LiteralMonth=nk;class rk extends Zy{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){const r=nd(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=Pc.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 rk(r,i)}}}Sr.LiteralQuarter=rk;class ik extends Zy{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,Zle);if(s.isValid){const o=s.plus({year:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new ik(r,i)}}}Sr.LiteralYear=ik;var Hb={};Object.defineProperty(Hb,"__esModule",{value:!0}),Hb.PartialCompare=void 0;const i0e=ct;class Wut extends i0e.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 i0e.ATNodeType.Partial}}Hb.PartialCompare=Wut;var y2={},Vut=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]}),Yut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Kut=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)&&Vut(e,t,r);return Yut(e,t),e};Object.defineProperty(y2,"__esModule",{value:!0}),y2.PickWhen=y2.Pick=void 0;const E2=Kut(Zt),s0e=Gt,Jut=ct,Xut=Je;function Qb(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class Zut extends Jut.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&&!E2.typeEq(u,m,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:m.type,returnType:u.type});u=Qb(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=Qb(u,f);return E2.typeEq(x,f,!0)?x.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(o.kids.caseElse=f.value,(0,s0e.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(!E2.typeEq(l.when,E2.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:l.when.type});if(o&&!E2.typeEq(o,l.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:l.pick.type,returnType:o.type});o=Qb(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=Qb(o,u);return E2.typeEq(a,u,!0)?a.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(r.kids.caseElse=u.value,(0,s0e.computedExprValue)({dataType:a,value:r,from:s})):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.type,returnType:a.type})}}y2.Pick=Zut;class eat extends Xut.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="caseWhen",this.has({pick:e})}}y2.PickWhen=eat;var A2={},tat=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]}),nat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),rat=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)&&tat(e,t,r);return nat(e,t),e};Object.defineProperty(A2,"__esModule",{value:!0}),A2.CaseWhen=A2.Case=void 0;const iat=Gt,sat=ct,oat=Je,_2=rat(Zt);function o0e(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class uat extends sat.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(!_2.typeEq(a.when,s))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:a.when.type,valueType:s.type})}else if(!_2.typeEq(a.when,_2.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:a.when.type});if(u&&!_2.typeEq(u,a.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:a.then.type,returnType:u.type});u=o0e(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&&!_2.typeEq(u,a,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:a.type,returnType:u.type});u=o0e(u,a),i.push(a),r.kids.caseElse=a.value}return(0,iat.computedExprValue)({value:r,dataType:u?_2.atomicDef(u):{type:"null"},from:i})}}A2.Case=uat;class aat extends oat.MalloyElement{constructor(e,r){super({when:e,then:r}),this.when=e,this.then=r,this.elementType="caseWhen"}}A2.CaseWhen=aat;var zb={},rd={},lat=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]}),cat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),fat=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)&&lat(e,t,r);return cat(e,t),e};Object.defineProperty(rd,"__esModule",{value:!0}),rd.RecordLiteral=rd.RecordElement=void 0;const u0e=Pi,xat=Gt,dat=ct,hat=Je,pat=fat(Zt);class mat extends hat.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]}}}rd.RecordElement=mat;class gat extends dat.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);u0e.TD.isAtomic(c)?(o.push(c),s.kids[l]=c.value,s.typeDef.fields.push((0,u0e.mkFieldDef)(pat.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,xat.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,[])}}rd.RecordLiteral=gat;var yat=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]}),Eat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Aat=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)&&yat(e,t,r);return Eat(e,t),e};Object.defineProperty(zb,"__esModule",{value:!0}),zb.ArrayLiteral=void 0;const _at=Gt,vat=ct,a0e=Aat(Zt),Cat=rd;class Sat extends vat.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 Cat.RecordLiteral?l.getNextElement(e,s):l.getExpression(e);if(i.push(c),c.type!=="error"){if(s){if(c.type!=="null"&&!a0e.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=a0e.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,_at.computedExprValue)({dataType:u,value:a,from:i})}}zb.ArrayLiteral=Sat;var Gb={};Object.defineProperty(Gb,"__esModule",{value:!0}),Gb.Timeframe=void 0;const bat=Xe,Tat=Je;class Rat extends Tat.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,bat.isTimestampUnit)(r)?r:"second"}}Gb.Timeframe=Rat;var Uc={};Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.ImportStatement=Uc.ImportSelect=Uc.ImportSourceName=void 0;const sk=Je;class Dat extends sk.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}Uc.ImportSourceName=Dat;class Oat extends sk.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}}Uc.ImportSelect=Oat;class Fat extends sk.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}'`)}}}Uc.ImportStatement=Fat;var eE={};Object.defineProperty(eE,"__esModule",{value:!0}),eE.ExtendBlock=void 0;const wat=Je,Nat=qn;class Lat extends wat.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Nat.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)for(const i of r.list)e.inputFS.extendSource(i)}}eE.ExtendBlock=Lat;var Wb={};Object.defineProperty(Wb,"__esModule",{value:!0}),Wb.Argument=void 0;const Iat=Je;class $at extends Iat.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}Wb.Argument=$at;var Vb={};Object.defineProperty(Vb,"__esModule",{value:!0}),Vb.HasParameter=void 0;const l0e=Xe,Bat=Je,kat=ct;class Mat extends Bat.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,l0e.isParameterType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default})),e.filterType&&(this.filterType=e.filterType)}parameter(){var e;let r;if(this.default!==void 0){const i=this.default.constantValue();if(this.type&&this.type!==i.type&&i.type!=="null"&&i.type!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),i.type==="null")return this.type?{type:this.type,value:i.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:i.value,name:this.name,type:"error"});if(i.type==="filter expression")return this.type!=="filter expression"&&this.logError("parameter-missing-default-or-type",`Filter expression parameters must have expicit filter type, for example '${this.name}::filter<string>'`),this.filterType&&(0,kat.checkFilterExpression)(this,this.filterType,i.value),{value:i.value,name:this.name,type:i.type};if(!(0,l0e.isCastType)(i.type)&&i.type!=="error")return this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${i.type}\``),{value:i.value,name:this.name,type:"error"};r={value:i.value,name:this.name,type:i.type}}else this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),r={value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"};return r.type==="filter expression"&&this.filterType&&(r.filterType=this.filterType),r}}Vb.HasParameter=Mat;var Yb={};Object.defineProperty(Yb,"__esModule",{value:!0}),Yb.AnonymousQuery=void 0;const Pat=Je,Uat=kr;class jat extends Pat.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Uat.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)}}Yb.AnonymousQuery=jat;var jc={};Object.defineProperty(jc,"__esModule",{value:!0}),jc.View=void 0;const qat=Je;class Hat extends qat.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}}jc.View=Hat;var Kb={};Object.defineProperty(Kb,"__esModule",{value:!0}),Kb.ViewArrow=void 0;const Qat=Pr,zat=jc;class Gat extends zat.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 Qat.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()}}Kb.ViewArrow=Gat;var Jb={},tE={};Object.defineProperty(tE,"__esModule",{value:!0}),tE.refine=void 0;const ok=Pi,Wat=lt,uk=Dc;function Vat(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,ok.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,ok.isQuerySegment)(u)&&(0,ok.isQuerySegment)(o)){const a=[],l=[],c=new Map(o.queryFields.map(f=>[(0,uk.nameFromDef)(f),f]));for(const f of u.queryFields)c.has((0,uk.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(uk.nameFromDef)}`),o.compositeFieldUsage=(0,Wat.mergeCompositeFieldUsage)(o.compositeFieldUsage,u.compositeFieldUsage)}else u.type==="index"&&o.type==="index"&&(o.indexFields=[...u.indexFields,...o.indexFields]);return[o]}tE.refine=Vat,Object.defineProperty(Jb,"__esModule",{value:!0}),Jb.ViewRefine=void 0;const Yat=ai,Kat=ks,Jat=tE,Xat=jc;class Zat extends Xat.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,Kat.getFinalStruct)(this.refinement,e.structDef(),s):Yat.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,Jat.refine)(this,r,s[0])}getImplicitName(){return this.base.getImplicitName()}}Jb.ViewRefine=Zat;var Xb={};Object.defineProperty(Xb,"__esModule",{value:!0}),Xb.ReferenceView=void 0;const ak=Xe,c0e=ai,elt=ks,tlt=Mr,nlt=tE,rlt=jc;class ilt extends rlt.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:c0e.ErrorFactory.structDef,outputStruct:c0e.ErrorFactory.structDef,pipeline:[],error:!0}};if(!i.found)return this.reference.logError(i.error.code,i.error.message),s();if(!(i.found instanceof tlt.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,ak.isAtomic)(o)){const u={type:"reduce",queryFields:[this.reference.refToField],compositeFieldUsage:o.compositeFieldUsage},a=this.reference.nameString,l={...(0,ak.sourceBase)(e.structDef()),type:"query_result",name:a,fields:[o]};return{pipeline:[u],name:a,outputStruct:l}}else return(0,ak.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,elt.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,nlt.refine)(this,r,s):r}getImplicitName(){return this.reference.nameString}}Xb.ReferenceView=ilt;var Zb={},nE={},eT={},rE={};Object.defineProperty(rE,"__esModule",{value:!0}),rE.Index=void 0;const slt=Je,olt=qn;class ult extends slt.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=olt.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}}rE.Index=ult;var iE={};Object.defineProperty(iE,"__esModule",{value:!0}),iE.SampleProperty=void 0;const alt=Je,f0e=qn;class llt extends alt.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=f0e.LegalRefinementStage.Tail,this.forceQueryClass=f0e.QueryClass.Index}sampling(){return this.sample}}iE.SampleProperty=llt;var tT={};Object.defineProperty(tT,"__esModule",{value:!0}),tT.IndexFieldSpace=void 0;const x0e=lt,d0e=Xe,lk=yt,clt=Mr,flt=mu,xlt=$y,dlt=Pr;class hlt extends flt.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const r of e)r instanceof lk.FieldReference?super.pushFields(r):r instanceof lk.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,x0e.emptyCompositeFieldUsage)(),i=(0,x0e.emptyNarrowedCompositeFieldResolution)();const s=[],o=this.inputSpace().structDef();for(const[u,a]of this.entries())if(a instanceof clt.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 xlt.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 dlt.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=lk.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();d0e.TD.isBasicAtomic(f)&&(0,d0e.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)}}tT.IndexFieldSpace=hlt,Object.defineProperty(eT,"__esModule",{value:!0}),eT.IndexBuilder=void 0;const ck=Xe,plt=ai,mlt=Ra,glt=rE,ylt=Bc,Elt=iE,Alt=tT,fk=lt;class _lt{constructor(e,r,i,s){this.filters=[],this.alwaysJoins=[],this.type="index",this.resultFS=new Alt.IndexFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof mlt.Filter?e.queryExecute(this):e instanceof ylt.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof glt.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 Elt.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,ck.isIndexSegment)(e)&&!(0,ck.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),plt.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,ck.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,fk.emptyCompositeFieldUsage)();return i.compositeFieldUsage=(0,fk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage),i}}eT.IndexBuilder=_lt;var nT={},sE={};Object.defineProperty(sE,"__esModule",{value:!0}),sE.GroupBy=void 0;const vlt=Bs,h0e=qn;class Clt extends vlt.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=h0e.LegalRefinementStage.Single,this.forceQueryClass=h0e.QueryClass.Grouping}}sE.GroupBy=Clt;var rT={};Object.defineProperty(rT,"__esModule",{value:!0}),rT.ProjectFieldSpace=void 0;const iT=Xe,Slt=mu;class blt extends Slt.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e===void 0||!iT.TD.isAtomic(e)||(0,iT.expressionIsAggregate)(e.expressionType)?!1:(0,iT.expressionInvolvesAggregate)(e.expressionType)&&(0,iT.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}rT.ProjectFieldSpace=blt;var qc={},id={};Object.defineProperty(id,"__esModule",{value:!0}),id.Ordering=id.OrderBy=void 0;const Tlt=Xe,p0e=kc,m0e=Je,Rlt=qn;class Dlt extends m0e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof p0e.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 p0e.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,Tlt.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}}id.OrderBy=Dlt;class Olt extends m0e.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Rlt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}}id.Ordering=Olt,Object.defineProperty(qc,"__esModule",{value:!0}),qc.ReduceBuilder=qc.QuerySegmentBuilder=void 0;const gu=Xe,Flt=ai,wlt=kc,Nlt=Bc,Llt=id,Ilt=mu,$lt=Bs,xk=lt;function g0e(t){return t.type==="fieldref"?t.path[t.path.length-1]:t.name}class y0e{constructor(){this.alwaysJoins=[],this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}e instanceof $lt.DefinitionList?this.resultFS.pushFields(...e.list):e instanceof Nlt.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof Llt.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,xk.emptyCompositeFieldUsage)();r.compositeFieldUsage=(0,xk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage)}}qc.QuerySegmentBuilder=y0e;class Blt extends y0e{constructor(e,r,i,s){super(),this.type="grouping",this.resultFS=new Ilt.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}`),Flt.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=g0e(o)}}if(i.orderBy===void 0||i.defaultOrderBy){let s;for(const o of i.queryFields){let u=!1,a=!1,l;const c=g0e(o);if(o.type==="fieldref"){const f=o.path.map(h=>new wlt.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}}qc.ReduceBuilder=Blt,Object.defineProperty(nT,"__esModule",{value:!0}),nT.ProjectBuilder=void 0;const E0e=Xe,klt=ai,Mlt=sE,Plt=rT,Ult=qc;class jlt extends Ult.QuerySegmentBuilder{constructor(e,r,i,s){super(),this.type="project",this.resultFS=new Plt.ProjectFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Mlt.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,E0e.isProjectSegment)(e)||(0,E0e.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),klt.ErrorFactory.projectSegment;const i=this.resultFS.getQuerySegment(r);return this.refineFrom(r,i),i}}nT.ProjectBuilder=jlt;var sT={};Object.defineProperty(sT,"__esModule",{value:!0}),sT.PartialBuilder=void 0;const qlt=Pi,Hlt=qc;class Qlt 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}`)}}sT.PartialBuilder=Qlt,Object.defineProperty(nE,"__esModule",{value:!0}),nE.QOpDesc=void 0;const zlt=eT,Glt=nT,Wlt=qc,Vlt=Je,Ylt=ks,Klt=Pr,sd=qn,Jlt=sT;class Xlt extends Vlt.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,i=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=sd.QueryClass.Grouping:this.refineThis.type==="project"?r=sd.QueryClass.Project:this.refineThis.type==="index"&&(r=sd.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=sd.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,i){switch(this.computeType()){case sd.QueryClass.Grouping:return new Wlt.ReduceBuilder(e,this.refineThis,r,i);case sd.QueryClass.Project:return new Glt.ProjectBuilder(e,this.refineThis,r,i);case sd.QueryClass.Index:return new zlt.IndexBuilder(e,this.refineThis,r,i);case void 0:return new Jlt.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 Klt.StaticSourceSpace((0,Ylt.opOutputStruct)(this,e.structDef(),s))}}}nE.QOpDesc=Xlt,Object.defineProperty(Zb,"__esModule",{value:!0}),Zb.QOpDescView=void 0;const Zlt=Xe,e0t=Pr,A0e=nE,t0t=ks,dk=qn,n0t=jc;class r0t extends n0t.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,Zlt.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 A0e.QOpDesc([]),u=new A0e.QOpDesc([]);for(const a of this.operation.list)switch(a.queryRefinementStage){case dk.LegalRefinementStage.Head:o.push(a);break;case dk.LegalRefinementStage.Single:a.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case dk.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,t0t.getFinalStruct)(this,e.structDef(),s.slice(-1));s[a]=this.getOp(new e0t.StaticSourceSpace(l),void 0,u,s[a])}return s}getImplicitName(){}}Zb.QOpDescView=r0t;var Rn={},i0t=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]}),s0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o0t=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)&&i0t(e,t,r);return s0t(e,t),e};Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.FieldDefinitionValue=Rn.DefSpace=Rn.DimensionFieldDeclaration=Rn.MeasureFieldDeclaration=Rn.DeclareFieldDeclaration=Rn.ProjectFieldDeclaration=Rn.GroupByFieldDeclaration=Rn.AggregateFieldDeclaration=Rn.CalculateFieldDeclaration=Rn.AtomicFieldDeclaration=void 0;const hk=Xe,_0e=o0t(Zt),u0t=c2,a0t=Je,od=sr,l0t=kr,c0t=Mr;class Hc extends a0t.MalloyElement{constructor(e,r,i){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=i,this.isNoteableObj=!0,this.extendNote=l0t.extendNoteMethod}getName(){return this.defineName}fieldDef(e,r){return this.queryFieldDef(new pk(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,hk.isAtomicFieldType)(i.type)&&i.type!=="error"){this.typecheckExprValue(i);const u=(0,hk.mkFieldDef)(_0e.atomicDef(i),r);return(u.type==="date"||u.type==="timestamp")&&(0,u0t.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 pk&&e.foundCircle)&&i.type!=="error"){const u=_0e.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 v0e(e,this))}}Rn.AtomicFieldDeclaration=Hc;class f0t extends Hc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}Rn.CalculateFieldDeclaration=f0t;class x0t extends Hc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckAggregate)(e,this)}}Rn.AggregateFieldDeclaration=x0t;class d0t extends Hc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckGroupBy)(e,this)}}Rn.GroupByFieldDeclaration=d0t;class h0t extends Hc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckProject)(e,this)}}Rn.ProjectFieldDeclaration=h0t;class p0t extends Hc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckDeclare)(e,this)}}Rn.DeclareFieldDeclaration=p0t;class m0t extends Hc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckMeasure)(e,this)}}Rn.MeasureFieldDeclaration=m0t;class g0t extends Hc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckDimension)(e,this)}}Rn.DimensionFieldDeclaration=g0t;class pk{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}}Rn.DefSpace=pk;class v0e extends c0t.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,hk.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}}Rn.FieldDefinitionValue=v0e;var oT={};Object.defineProperty(oT,"__esModule",{value:!0}),oT.Aggregate=void 0;const y0t=Bs,C0e=qn;class E0t extends y0t.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=C0e.LegalRefinementStage.Single,this.forceQueryClass=C0e.QueryClass.Grouping}}oT.Aggregate=E0t;var uT={};Object.defineProperty(uT,"__esModule",{value:!0}),uT.Calculate=void 0;const A0t=Bs,_0t=qn;class v0t extends A0t.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=_0t.LegalRefinementStage.Single}}uT.Calculate=v0t;var oE={};Object.defineProperty(oE,"__esModule",{value:!0}),oE.Dimensions=void 0;const C0t=Oc;class S0t extends C0t.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}oE.Dimensions=S0t;var uE={};Object.defineProperty(uE,"__esModule",{value:!0}),uE.Measures=void 0;const b0t=Oc;class T0t extends b0t.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}uE.Measures=T0t;var aT={};Object.defineProperty(aT,"__esModule",{value:!0}),aT.Nests=void 0;const R0t=Bs,S0e=qn;class D0t extends R0t.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=S0e.LegalRefinementStage.Single,this.forceQueryClass=S0e.QueryClass.Grouping}}aT.Nests=D0t;var lT={};Object.defineProperty(lT,"__esModule",{value:!0}),lT.ProjectStatement=void 0;const O0t=Bs,b0e=qn;class F0t extends O0t.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=b0e.QueryClass.Project,this.queryRefinementStage=b0e.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}lT.ProjectStatement=F0t;var Qc={},Zl={},$n={};Object.defineProperty($n,"__esModule",{value:!0}),$n.getPlainString=$n.unIndent=$n.getOptionalId=$n.idToStr=$n.getId=$n.getStringParts=$n.getStringIfShort=$n.getShortString=void 0;const T0e=Zo;function R0e(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?T0e.ParseUtil.parseString(i,i[0]):""}$n.getShortString=R0e;function D0e(t){const e=t.string().shortString();if(e)return R0e(e)}$n.getStringIfShort=D0e;function*O0e(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)}}$n.getStringParts=O0e;function F0e(t){return w0e(t.id())}$n.getId=F0e;function w0e(t){const e=t.BQ_STRING();return e?T0e.ParseUtil.parseString(e.text,"`"):t.text}$n.idToStr=w0e;function w0t(t){function e(r){return"id"in r}if(e(t)&&t.id())return F0e(t)}$n.getOptionalId=w0t;function*N0e(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 N0t(t){let e;for(const r of N0e(t)){const i=r.match(/^( *).*[^\s]/);if(i){const s=i[1].length;(e===void 0||s<e)&&(e=s)}}return e}function L0e(t){let e;for(const r of t)if(typeof r=="string"){const i=N0t(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 N0e(i))o[0]===" "&&(o=o.slice(e)),s+=o;t[r]=s}}}$n.unIndent=L0e;function L0t(t,e=!1){const r=[],i=D0e(t);if(i)return[i,r];const s=[],o=t.string().sqlString();if(o){for(const u of O0e(o))if(typeof u=="string")s.push(u);else if(r.push(u),e)return[void 0,r];return L0e(s),[s.join(""),r]}return["",r]}$n.getPlainString=L0t,Object.defineProperty(Zl,"__esModule",{value:!0}),Zl.findReferences=Zl.deprecatedParseTableURI=Zl.constructTableKey=void 0;const I0t=uc,mk=$n;function I0e(t){const e=(0,mk.getStringIfShort)(t);if(e)return e;const r=[],i=t.string().sqlString();if(i){for(const s of(0,mk.getStringParts)(i))typeof s=="string"&&r.push(s);return r.join("")}return""}class $0t{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,i){const s=$0e(e,r);this.needTables[s]||(this.needTables[s]={connectionName:e,tablePath:r,firstReference:i})}enterExploreTable(e){const r=(0,mk.getId)(e.connectionId()),i=I0e(e.tablePath()),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const r=I0e(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}}function $0e(t,e){return t===void 0?e:`${t}:${e}`}Zl.constructTableKey=$0e;function B0t(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,r,i]=e;return{connectionName:r,tablePath:i}}else return{tablePath:t}}Zl.deprecatedParseTableURI=B0t;function k0t(t,e,r){const i=new $0t(t,e),s=i;return I0t.ParseTreeWalker.DEFAULT.walk(s,r),{tables:i.needTables,urls:i.needImports}}Zl.findReferences=k0t,Object.defineProperty(Qc,"__esModule",{value:!0}),Qc.TableFunctionSource=Qc.TableMethodSource=Qc.TableSource=void 0;const B0e=Zl,M0t=Eo,k0e=ai;class gk extends M0t.Source{getSourceDef(){var e,r,i;const s=this.getTableInfo();if(s===void 0)return k0e.ErrorFactory.structDef;const{tablePath:o,connectionName:u}=s,a=(0,B0e.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),k0e.ErrorFactory.structDef}}Qc.TableSource=gk;class P0t extends gk{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}}}Qc.TableMethodSource=P0t;class U0t extends gk{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,B0e.deprecatedParseTableURI)(this.tableURI)}}Qc.TableFunctionSource=U0t;var cT={};Object.defineProperty(cT,"__esModule",{value:!0}),cT.SQLString=void 0;const j0t=Je,M0e=hu;class q0t extends j0t.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(H0t)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof M0e.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}}cT.SQLString=q0t;function H0t(t){return t instanceof M0e.SourceQueryElement}var fT={};Object.defineProperty(fT,"__esModule",{value:!0}),fT.SourceDesc=void 0;const Q0t=Je;class z0t extends Q0t.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}fT.SourceDesc=z0t;var xT={};Object.defineProperty(xT,"__esModule",{value:!0}),xT.isSourceProperty=void 0;const G0t=Ra,W0t=Oc,V0t=r2,Y0t=wc,K0t=i2,J0t=s2,X0t=o2,Z0t=Fc,ect=xs;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}xT.isSourceProperty=tct;var dT={};Object.defineProperty(dT,"__esModule",{value:!0}),dT.isFieldCollectionMember=void 0;const nct=Rn,P0e=yt;function rct(t){return t instanceof P0e.FieldReference||t instanceof P0e.WildcardFieldReference||t instanceof nct.AtomicFieldDeclaration}dT.isFieldCollectionMember=rct;var hT={};Object.defineProperty(hT,"__esModule",{value:!0}),hT.isQueryElement=void 0;const ict=u2,sct=a2,oct=Hy,uct=Qy;function act(t){return t instanceof ict.QueryArrow||t instanceof sct.QueryRefine||t instanceof oct.QueryReference||t instanceof uct.QueryRaw}hT.isQueryElement=act;var U0e={};Object.defineProperty(U0e,"__esModule",{value:!0});var pT={};Object.defineProperty(pT,"__esModule",{value:!0}),pT.isQueryProperty=void 0;function lct(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}pT.isQueryProperty=lct;var mT={};Object.defineProperty(mT,"__esModule",{value:!0}),mT.isQueryExtendProperty=void 0;const cct=oE,fct=xs,xct=uE;function dct(t){return t instanceof cct.Dimensions||t instanceof xct.Measures||t instanceof fct.JoinStatement}mT.isQueryExtendProperty=dct;var gT={};Object.defineProperty(gT,"__esModule",{value:!0}),gT.isFieldPropStatement=void 0;const hct=$c,pct=Ra,mct=Bc,gct=m2;function yct(t){return t instanceof pct.Filter||t instanceof mct.Limit||t instanceof gct.PartitionBy||t instanceof hct.FunctionOrdering}gT.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(Ry,t),r(Xp,t),r(Zp,t),r(Eo,t),r(Fy,t),r(hu,t),r(X4,t),r(Z4,t),r(nb,t),r(ky,t),r(rb,t),r(ib,t),r(du,t),r(r2,t),r(i2,t),r(wc,t),r(s2,t),r(o2,t),r(ob,t),r(x2,t),r(ab,t),r(d2,t),r($c,t),r(lb,t),r(Jl,t),r(cb,t),r(p2,t),r(fb,t),r(xb,t),r(db,t),r(Kl,t),r(hb,t),r(pb,t),r(gb,t),r(Ky,t),r(Vy,t),r(ed,t),r(Eb,t),r(Ab,t),r(vb,t),r(Sb,t),r(bb,t),r(Tb,t),r(Rb,t),r(Mc,t),r(Ob,t),r(Fb,t),r(wb,t),r(Nb,t),r(Lb,t),r(Ib,t),r($b,t),r(kb,t),r(Ub,t),r(Sr,t),r(Hb,t),r(m2,t),r(y2,t),r(A2,t),r(zb,t),r(rd,t),r(Ic,t),r(Gb,t),r(Jy,t),r(Uc,t),r(eE,t),r(Wb,t),r(Vb,t),r(Yb,t),r(a2,t),r(u2,t),r(jc,t),r(Kb,t),r(Jb,t),r(Xb,t),r(Zb,t),r(Rn,t),r(yt,t),r(oT,t),r(uT,t),r(Oc,t),r(oE,t),r(eE,t),r(Ra,t),r(sE,t),r(rE,t),r(xs,t),r(Dy,t),r(Bc,t),r(uE,t),r(Ry,t),r(aT,t),r(id,t),r(lT,t),r(nE,t),r(iE,t),r(l2,t),r(Zx,t),r(zy,t),r(Qc,t),r(cT,t),r(Fc,t),r(pu,t),r(fT,t),r(xT,t),r(ct,t),r(dT,t),r(kc,t),r(Je,t),r(hT,t),r(U0e,t),r(pT,t),r(mT,t),r(gT,t)}(z4);var yT={},Ect=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]}),Act=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_ct=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)&&Ect(e,t,r);return Act(e,t),e};Object.defineProperty(yT,"__esModule",{value:!0}),yT.MalloyToAST=void 0;const j0e=py,vct=Kh,ie=_ct(z4),yk=Yp,q0e=Er,Cct=z4,Yn=$n,ET=Xe,Sct=Zo,H0e=jn,bct=Cy;class Q0e extends ie.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class Ek extends ie.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const Tct=[];class Rct extends vct.AbstractParseTreeVisitor{constructor(e,r,i){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=i;for(const s of Tct){const o=Sct.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,yk.makeLogMessage)(r,i,{at:e.location,...s}))}rangeFromContext(e){return(0,H0e.rangeFromContext)(this.parseInfo.sourceInfo,e)}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new q0e.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,r,i,s){this.msgLog.log((0,yk.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}warnWithReplacement(e,r,i,s){this.msgLog.log((0,yk.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)}only(e,r,i){const s=[];for(const o of e){const u=r(o);u?s.push(u):o instanceof Ek||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 ie.FieldName((0,Yn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new ie.ModelEntryReference((0,Yn.getId)(e)),e.id())}defaultResult(){return new ie.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 q0e.Interval(r,i.stopIndex);return this.parseInfo.sourceStream.getText(s)}getFilterElement(e){const r=this.getFieldExpr(e),i=new ie.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 ie.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 j0e.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return r||""}makeSqlString(e,r){for(const i of(0,Yn.getStringParts)(e))i instanceof j0e.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 ie.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=>ie.isDocStatementOrDocStatementList(i)&&i,"statement");return new ie.Document(r)}visitDefineSourceStatement(e){const i=e.sourcePropertyList().sourceDefinition().map(u=>this.visitSourceDefinition(u)),s=this.getNotes(e.tags()),o=new ie.DefineSourceList(i);return o.extendNote({blockNotes:s}),o}getSourceParameter(e){const r=(0,Yn.getId)(e.parameterNameDef());let i,s;const o=e.legalParamType();if(o){const l=o.malloyType();if(l){const f=this.getMalloyType(l);(0,bct.isFilterable)(f)?s=f:this.contextError(o,"parameter-illegal-default-type",`Unknown filter type ${f}`)}const c=o.FILTER()?"filter expression":o.text.toLowerCase();if(!(0,ET.isParameterType)(c))return this.contextError(o,"parameter-illegal-default-type",`Unknown parameter type ${c}`),null;i=c}const u=e.fieldExpr();let a;if(u){const l=new ie.ConstantExpression(this.getFieldExpr(u));a=this.astAt(l,u)}return this.astAt(new ie.HasParameter({name:r,type:i,default:a,filterType:s}),e)}getSourceParameters(e){if(e===void 0)return[];this.inExperiment("parameters",e);function r(i){return i!==null}return e.sourceParameter().map(i=>this.getSourceParameter(i)).filter(r)}visitSourceDefinition(e){const r=this.visit(e.sqExplore()),i=this.getSourceParameters(e.sourceParameters()),s=new ie.DefineSource((0,Yn.getId)(e.sourceNameDef()),r instanceof ie.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=>ie.isSourceProperty(s)&&s,"source property");return new ie.SourceDesc(r)}visitExploreTable(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=this.getPlainStringFrom(e.tablePath());return this.astAt(new ie.TableMethodSource(i,s),e)}visitSqlSource(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=new ie.SQLString,o=e.sqlString();o&&this.makeSqlString(o,s);const u=e.shortString();u&&s.push((0,Yn.getShortString)(u));const a=new ie.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 ie.Join&&(i.push(u),u instanceof ie.ExpressionJoin?(u.joinType="many",u.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):u instanceof ie.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const s=new ie.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 ie.Join&&(s.push(u),u instanceof ie.ExpressionJoin&&(u.joinType="one"));const o=new ie.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 ie.Join&&(s.push(u),u instanceof ie.ExpressionJoin?u.joinType="cross":u.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const o=new ie.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 ie.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 ie.SQReference(i,this.getSQArguments(s)),e),notes:[],joinAs:i}:{joinAs:i,joinFrom:new ie.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 ie.ExpressionJoin(i,s),a=e.joinExpression(),l=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,ET.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 ie.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(),ie.DimensionFieldDeclaration),s=new ie.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(),ie.MeasureFieldDeclaration),s=new ie.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(ie.isQueryExtendProperty(o))r.push(o);else throw this.internalError(e,`Query extend matched, but ${o.elementType} found`);const s=new ie.ExtendBlock(r);return this.astAt(s,e)}visitExploreRenameDef(e){const r=e.fieldName(0),i=e.fieldName(1),s=new ie.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 ie.Renames(s,r);return this.astAt(o,e)}visitFilterClauseList(e){return new ie.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 ie.Views(i,r),o=this.getNotes(e.tags());return s.extendNote({blockNotes:o}),s}visitDefExplorePrimaryKey(e){const r=new ie.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 ie.FieldReferences(i)}visitDefExploreEditField(e){const r=e.ACCEPT()?"accept":"except";return new ie.FieldListEdit(r,this.getFieldNameList(e.fieldNameList(),ie.AcceptExceptFieldReference))}visitSQInclude(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new ie.SQExtend(r,new ie.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 ie.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=>ie.isQueryProperty(i)&&i,"query statement");return new ie.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 ie.FieldReference||s instanceof ie.AtomicFieldDeclaration?s:!1,"view field")}visitAggregateStatement(e){const r=new ie.Aggregate(this.getQueryItems(e.queryFieldList(),ie.AggregateFieldDeclaration,ie.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){const r=new ie.GroupBy(this.getQueryItems(e.queryFieldList(),ie.GroupByFieldDeclaration,ie.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){const r=new ie.Calculate(this.getQueryItems(e.queryFieldList(),ie.CalculateFieldDeclaration,ie.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(),ie.ExpressionFieldReference);let a;const l=s.timeframe();l&&(a=new ie.ExprGranularTime(new ie.ExprIdReference(u),this.visitTimeframe(l).text,!0));const c=s.aggregate();if(c){const x=c.text.toLowerCase();if(x==="sum")a=new ie.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,ie.ProjectFieldDeclaration,ie.ProjectFieldReference));return this.astAt(new ie.ProjectStatement(r),e)}visitProjectStatement(e){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,ie.ProjectFieldReference):void 0,o=this.astAt(new ie.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 ie.WildcardFieldReference(void 0),e);const o=this.getFieldPath(s,ie.IndexFieldReference);return i.STAR()?this.astAt(new ie.WildcardFieldReference(o),e):this.astAt(o,e)});return new ie.FieldReferences(r)}visitIndexStatement(e){const r=this.visitIndexFields(e.indexFields()),i=new ie.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 ie.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 ie.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 ie.FunctionOrdering(r),e)}visitOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.INTEGER_LITERAL();if(i)return new ie.OrderBy(this.getNumber(i),r);const s=e.fieldName();if(s)return new ie.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 ie.Ordering(r),e)}visitTopStatement(e){const r=this.getNumber(e.INTEGER_LITERAL());return this.astAt(new ie.Limit(r),e)}visitTopLevelQueryDefs(e){const r=e.topLevelQueryDef().map(o=>this.visitTopLevelQueryDef(o)),i=this.getNotes(e.tags()),s=new ie.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 ie.SourceQueryElement){const o=new ie.DefineQuery(r,i);return o.extendNote({notes:s}),this.astAt(o,e)}throw this.internalError(e,`Expected query definition, got a '${i.elementType}'`)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new ie.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 ie.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof ie.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 ie.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 ie.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 ie.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new ie.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 ie.ExprLogicalOp(r,"or",i)}visitExprLogicalAnd(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new ie.ExprLogicalOp(r,"and",i)}visitExprOrTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ie.ExprAlternationTree(r,"|",i),e)}visitExprAndTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ie.ExprAlternationTree(r,"&",i),e)}visitExprCoalesce(e){const r=this.getFieldExpr(e.fieldExpr()[0]),i=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new ie.ExprCoalesce(r,i),e)}visitPartialCompare(e){const r=e.compareOp().text;if(ie.isComparison(r))return this.astAt(new ie.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 ie.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 ie.ExprString(r)}visitRawString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
1160
+ `)),Gy.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"),Gy.ErrorFactory.structDef}}zy.SQLSource=Grt,Object.defineProperty(nb,"__esModule",{value:!0}),nb.SQSource=void 0;const Wrt=hu,Vrt=Qy,Yrt=zy;class Krt extends Wrt.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 Yrt.SQLSource){const e=new Vrt.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}nb.SQSource=Krt;var rb={};Object.defineProperty(rb,"__esModule",{value:!0}),rb.SQExtend=void 0;const Jrt=Fy,Xrt=hu;class Zrt extends Xrt.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 Jrt.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}}rb.SQExtend=Zrt;var ib={},sb={};Object.defineProperty(sb,"__esModule",{value:!0}),sb.CompositeSource=void 0;const eit=Xe,tit=Eo;class nit extends tit.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,eit.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,g=l.get(m);if(g===void 0){const y={...p,name:m,as:void 0,e:{node:"compositeField"},compositeFieldUsage:{fields:[m],joinedUsage:{}},code:this.code,location:this.codeLocation};l.set(m,y),a.push(y)}else p.accessModifier==="internal"&&(g.accessModifier="internal")}}),{type:"composite",sources:i,connection:s,fields:a,dialect:o,name:u,parameters:i[0].parameters}}}sb.CompositeSource=nit,Object.defineProperty(ib,"__esModule",{value:!0}),ib.SQCompose=void 0;const rit=sb,iit=hu;class sit extends iit.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(oit(e))return this.asSource=new rit.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}}ib.SQCompose=sit;function oit(t){return t.every(e=>e!==void 0)}var ob={},Kl={},Wy={},uit=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}),lit=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)&&uit(e,t,r);return ait(e,t),e};Object.defineProperty(Wy,"__esModule",{value:!0}),Wy.BinaryBoolean=void 0;const cit=$s,fit=lit(Zt),xit=pu,dit=Gt,hit=ct;class pit extends hit.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=[fit.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,dit.computedExprValue)({dataType:{type:"boolean"},value:{node:(0,xit.getExprNode)(this.op),kids:{left:r.value,right:i.value}},from:[r,i]}):(0,cit.errorFor)("logical-op expected boolean")}}Wy.BinaryBoolean=pit;var mit=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]}),git=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),yit=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)&&mit(e,t,r);return git(e,t),e};Object.defineProperty(Kl,"__esModule",{value:!0}),Kl.ExprLegacyIn=Kl.ExprEquality=Kl.ExprCompare=void 0;const fn=yit(Zt),Eit=Gt,Ait=ct,_it=Wy,vit={"~":[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 Rle extends _it.BinaryBoolean{constructor(e,r,i){super(e,r,i),this.elementType="a<=>b",this.legalChildTypes=vit[r]}getExpression(e){return this.right.apply(e,this.op,this.left)}}Kl.ExprCompare=Rle;class Cit extends Rle{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=Cit;class Sit extends Ait.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,Eit.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=Sit;var Vy={},f2={};Object.defineProperty(f2,"__esModule",{value:!0}),f2.ExprTime=void 0;const bit=Xe,Tit=Gt,Rit=ct;class kB extends Rit.ExpressionDef{constructor(e,r,i){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue=(0,Tit.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,bit.isTemporalType)(r.type)&&(s.srcType={type:r.type}),i=s}return new kB(e,i,[r])}}f2.ExprTime=kB;var Ic={};Object.defineProperty(Ic,"__esModule",{value:!0}),Ic.Range=void 0;const Dit=$s,Oit=Gt,Fit=ct;class wit extends Fit.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,Oit.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,Dit.errorFor)("a range is not a value")}}Ic.Range=wit;var Nit=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]}),Lit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Iit=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)&&Nit(e,t,r);return Lit(e,t),e};Object.defineProperty(Vy,"__esModule",{value:!0}),Vy.ExprGranularTime=void 0;const MB=Xe,$it=$s,Dle=Iit(Zt),Ole=ds,Bit=ct,ub=f2,Fle=Ic;class kit extends Bit.ExpressionDef{constructor(e,r,i){super({expr:e}),this.expr=e,this.units=r,this.truncate=i,this.elementType="granularTime",this.legalChildTypes=[Dle.timestampT,Dle.dateT]}granular(){return!0}getExpression(e){const r=this.units,i=this.expr.getExpression(e);if(MB.TD.isTemporal(i)){const o={...i,timeframe:r};return this.truncate&&(o.value={node:"trunc",e:(0,MB.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,MB.isDateUnit)(r)?"date":"timestamp"),{...s,value:(0,$it.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const r=this.getExpression(e),i={node:"numberLiteral",literal:"1"};if(r.type==="timestamp"){const a=ub.ExprTime.fromValue("timestamp",r),l=new ub.ExprTime("timestamp",(0,Ole.timeOffset)("timestamp",r.value,"+",i,this.units),[r]);return new Fle.Range(a,l)}const s=new ub.ExprTime("date",r.value,[r]),o=(0,Ole.timeOffset)("date",r.value,"+",i,this.units),u=new ub.ExprTime("date",o,[r]);return new Fle.Range(s,u)}}Vy.ExprGranularTime=kit,Object.defineProperty(ob,"__esModule",{value:!0}),ob.Apply=void 0;const Mit=Kl,Pit=c2,wle=Vy;class Uit extends Mit.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,Pit.isGranularResult)(i)&&(r=new wle.ExprGranularTime(this.right,i.timeframe,!1))}return r instanceof wle.ExprGranularTime?r.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}ob.Apply=Uit;var x2={},jit=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]}),qit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Hit=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)&&jit(e,t,r);return qit(e,t),e};Object.defineProperty(x2,"__esModule",{value:!0}),x2.BinaryNumeric=void 0;const Qit=Hit(Zt),zit=ct;class Git extends zit.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=[Qit.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}x2.BinaryNumeric=Git;var ab={},Wit=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]}),Vit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Yit=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)&&Wit(e,t,r);return Vit(e,t),e};Object.defineProperty(ab,"__esModule",{value:!0}),ab.Boolean=void 0;const Kit=ct,Jit=Yit(Zt);let Xit=class extends Kit.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...Jit.boolT,value:{node:this.value}}}};ab.Boolean=Xit;var d2={};Object.defineProperty(d2,"__esModule",{value:!0}),d2.ConstantExpression=d2.ConstantFieldSpace=void 0;const Zit=ct;class Nle{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}}d2.ConstantFieldSpace=Nle;class est extends Zit.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 Nle),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)}}d2.ConstantExpression=est;var $c={};Object.defineProperty($c,"__esModule",{value:!0}),$c.FunctionOrdering=$c.FunctionOrderBy=void 0;const PB=Xe,Lle=Je,tst=ed;class nst extends Lle.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,PB.expressionIsAggregate)(r.expressionType)||((0,PB.expressionIsScalar)(r.expressionType)?(!(this.field instanceof tst.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,PB.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}}}$c.FunctionOrderBy=nst;class rst extends Lle.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))}}$c.FunctionOrdering=rst;var lb={};Object.defineProperty(lb,"__esModule",{value:!0}),lb.ExprAddSub=void 0;const ist=x2;class sst extends ist.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}lb.ExprAddSub=sst;var Jl={},ost=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]}),ust=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ast=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)&&ost(e,t,r);return ust(e,t),e};Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.ExprAggregateFunction=void 0;const Yy=Xe,lst=$t,cst=$s,Ile=Pr,$le=ast(Zt),fst=yt,xst=ct,dst=Mr,hst=ed;class pst extends xst.ExpressionDef{constructor(e,r,i){super(),this.func=e,this.legalChildTypes=[$le.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 Ile.StructSpaceField))if((0,Yy.isAtomicFieldType)(p.type)){u=this.source,a={...$le.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(y=>mst(y,m[0])))&&(l=m[0].map(y=>y.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,Yy.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=jB(c,x),g=qB(this.elementType,m),y=h?g==null?void 0:g.message:"Join path is required for this calculation";if(y){const E=gst(y,x,u,this.elementType),A=(s=g==null?void 0:g.code)!==null&&s!==void 0?s:"bad-join-usage";g?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,cst.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(...UB(e,s))}if(this.expr){const i=this.expr.getExpression(e).value;r.push(...UB(e,i))}return r}}Jl.ExprAggregateFunction=pst;function mst(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 UB(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 Ile.StructSpaceField&&a.length>0){const c=i(l.fieldSpace,a);return{...c,joinPath:[{...l.joinPathElement,name:u},...c.joinPath]}}else if(l instanceof dst.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,lst.exprWalk)(e))if(s.node==="field"){const o=i(t,s.path),u=o.def;if((0,Yy.isAtomic)(u)&&!(0,Yy.isJoined)(u))if((0,Yy.hasExpression)(u)){const a=UB(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 jB(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 qB(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 gst(t,e,r,i){if(e.length===0)return t;let s=e[0];for(const m of e.slice(1))for(let g=0;g<s.length&&g<m.length;g++){const y=s[g],E=m[g];if(y.name!==E.name){s=s.slice(0,g);break}}const o=jB(s,e),u=qB(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=jB(c,e),x=qB(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 fst.FieldReference?`${r.refString}.${i}()`:r instanceof hst.ExprIdReference?`${r.fieldReference.refString}.${i}()`:`${h}.${i}(${r.code})`,g=`${p}.${i}(${r.code})`;let y=`${t}; use \`${m}\``;return x===void 0&&p!==h&&(y+=` or \`${g}\` to get a result weighted with respect to \`${p}\``),y}}var cb={};Object.defineProperty(cb,"__esModule",{value:!0}),cb.ExprAlternationTree=void 0;const Ble=Gt,h2=ct,yst=pu;function HB(t){const e=t.atExpr();switch(e.atNodeType()){case h2.ATNodeType.And:case h2.ATNodeType.Partial:return;case h2.ATNodeType.Or:{if(e instanceof kle){const r=HB(e.left);if(r){const i=HB(e.right);if(i)return[...r,...i]}}return}default:return e.granular()?void 0:[e]}}class kle extends h2.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=HB(this)||[]),this.inList}apply(e,r,i,s){if((0,yst.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,Ble.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,Ble.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==="|"?h2.ATNodeType.Or:h2.ATNodeType.And}}cb.ExprAlternationTree=kle;var p2={};Object.defineProperty(p2,"__esModule",{value:!0}),p2.ExprAsymmetric=void 0;const Est=Jl;class Ast extends Est.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}`}}}}p2.ExprAsymmetric=Ast;var fb={};Object.defineProperty(fb,"__esModule",{value:!0}),fb.ExprAvg=void 0;const _st=p2;class vst extends _st.ExprAsymmetric{constructor(e,r,i){super("avg",e,r,i),this.has({source:r})}}fb.ExprAvg=vst;var xb={};Object.defineProperty(xb,"__esModule",{value:!0}),xb.ExprCast=void 0;const Cst=ds,Sst=Gt,bst=ct;class Tst extends bst.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,Sst.computedExprValue)({dataType:i,value:(0,Cst.castTo)(this.castType,r.value,r.type,this.safe),from:[r]})}}xb.ExprCast=Tst;var db={},Rst=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]}),Dst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ost=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)&&Rst(e,t,r);return Dst(e,t),e};Object.defineProperty(db,"__esModule",{value:!0}),db.ExprCoalesce=void 0;const Mle=Pi,Ple=Ost(Zt),Fst=ct;class wst extends Fst.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=Ple.anyAtomicT}getExpression(e){const r=this.expr.getExpression(e),i=this.altExpr.getExpression(e);return r.type==="null"?i:(Ple.typeEq(r,i)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${r.type}, ${i.type})`),{...r.type==="error"?i:r,expressionType:(0,Mle.maxExpressionType)(r.expressionType,i.expressionType),value:{node:"coalesce",kids:{left:r.value,right:i.value}},evalSpace:(0,Mle.mergeEvalSpaces)(r.evalSpace,i.evalSpace)})}}db.ExprCoalesce=wst;var hb={};Object.defineProperty(hb,"__esModule",{value:!0}),hb.ExprCount=void 0;const Nst=lt,Lst=Jl;class Ist extends Lst.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,Nst.emptyCompositeFieldUsage)()}}}hb.ExprCount=Ist;var pb={},$st=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]}),Bst=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)&&$st(e,t,r);return Bst(e,t),e};Object.defineProperty(pb,"__esModule",{value:!0}),pb.ExprCountDistinct=void 0;const mb=kst(Zt),Mst=Jl;class Pst extends Mst.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[mb.numberT,mb.stringT,mb.dateT,mb.timestampT]}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}}pb.ExprCountDistinct=Pst;var gb={},Bc={};Object.defineProperty(Bc,"__esModule",{value:!0}),Bc.Limit=void 0;const Ust=Je,jst=qn;class qst extends Ust.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=jst.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}Bc.Limit=qst;var m2={};Object.defineProperty(m2,"__esModule",{value:!0}),m2.PartitionBy=void 0;const Hst=Je;class Qst extends Hst.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}m2.PartitionBy=Qst;var Ky={},kc={};Object.defineProperty(kc,"__esModule",{value:!0}),kc.FieldName=void 0;const zst=Je;class Gst extends zst.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])}}kc.FieldName=Gst;var Wst=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]}),Vst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Yst=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)&&Wst(e,t,r);return Vst(e,t),e};Object.defineProperty(Ky,"__esModule",{value:!0}),Ky.ExprFunc=void 0;const Cr=Xe,Kst=$s,Jst=Xx,Xst=Gt,Zst=ct,eot=kc,Ule=$t,jle=Yst(Zt),tot=lt;class not extends Zst.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,Y)=>{Y!==0&&$.push(","),$.push(q.value)}),$.push(")");const D=(i=a[0])!==null&&i!==void 0?i:{type:"number"},k=this.rawType?{type:this.rawType}:D;return(0,Xst.computedExprValue)({dataType:k,value:(0,Ule.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,Kst.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 k=D.typeDesc();if((0,Cr.isAtomicFieldType)(k.type))x={...jle.atomicDef(k),expressionType:k.expressionType,value:{node:"field",path:this.source.path},evalSpace:k.evalSpace,compositeFieldUsage:k.compositeFieldUsage},h=this.source.path.slice(0,-1);else if(!(D instanceof Jst.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${k.type}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const p=[...x?[x]:[],...a],m=rot(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:g,expressionTypeErrors:y,evalSpaceErrors:E,nullabilityErrors:A,returnType:_}=m;for(const $ of y){const D=$.argIndex-(x?1:0),k=(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 ${k}, but received ${$.actualExpressionType}`)}for(const $ of E){const D=$.argIndex-(x?1:0),k=$.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 ${k}, 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=g.returnType,C=(0,Cr.maxOfExpressionTypes)([(u=v.expressionType)!==null&&u!==void 0?u:"scalar",...p.map($=>$.expressionType)]);if(!(0,Cr.expressionIsAggregate)(g.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:g,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)(g.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"),g.supportsOrderBy||$){const D=g.supportsOrderBy!=="only_default",k=r.orderBys.flatMap(q=>$?q.getAnalyticOrderBy(e):q.getAggregateOrderBy(e,D));b.kids.orderBy=k}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&&(g.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 k of D.partitionFields){const q=k.getField(e);q.found===void 0?k.logError("partition-by-not-found",`${k.refString} is not defined`):(0,Cr.expressionIsAnalytic)(q.found.typeDesc().expressionType)||(0,Cr.expressionIsUngroupedAggregate)(q.found.typeDesc().expressionType)?k.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):$.push(k.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,k=iot(D),q=k.filter(Q=>Q.type==="interpolation"&&Q.name.includes(".")).map(Q=>Q.type==="interpolation"?`\${${Q.name}}`:`\${${Q.value}}`);if(q.length>0){const Q=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",Q)}const Y=[];for(const Q of k)if(Q.type==="string")Y.push(Q.value);else if(Q.name==="TABLE")Y.push({node:"source-reference"});else{const X=new eot.FieldName(Q.name);this.has({name:X});const ce=e.lookup([X]);if(ce.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${ce.error.message}`);if(ce.found.typeDesc().type==="filter expression")return this.loggedErrorExpr("filter-expression-error","Filter expressions cannot be used in sql_ functions");ce.found.refType==="parameter"?Y.push({node:"parameter",path:[Q.name]}):Y.push({node:"field",path:[Q.name]})}S=(0,Ule.composeSQLExpr)(Y)}}const R=(0,Cr.mergeEvalSpaces)(...p.map($=>$.evalSpace)),O=R==="constant"?"constant":(0,Cr.expressionIsScalar)(C)?R:"output";return{...(0,Cr.isAtomic)(_)?jle.atomicDef(_):_,expressionType:C,value:S,evalSpace:O,compositeFieldUsage:(0,tot.mergeCompositeFieldUsage)(...p.map($=>$.compositeFieldUsage))}}}Ky.ExprFunc=not;function rot(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],g=i.params[o];if(g===void 0){u=!1;break}if(!g.allowedTypes.some(E=>{var A;const{dataTypeMatch:_,genericsSet:v}=g2(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:g})),(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:g,maxEvalSpace:E.evalSpace,actualEvalSpace:m.evalSpace}),E.evalSpace==="literal"&&m.type==="null"&&f.push({argIndex:p,param:g}),_})){u=!1;break}g.isVariadic?p===e.length-1&&(a=!0):o++}if(!a&&(o!==e.length||o!==i.params.length))continue;const x=yb(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 iot(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 g2(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.isBasicArray)(r))return(0,Cr.isRepeatedRecordFunctionParam)(i)?{dataTypeMatch:!1,genericsSet:[]}:g2(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 g2(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=g2(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 g2(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=g2(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 yb(t,e){switch(t.type){case"array":{if("fields"in t){const s=t.fields.map(o=>{const u=yb(o,e);return{...o,...u}});return{error:void 0,returnType:{type:"array",elementTypeDef:t.elementTypeDef,fields:s}}}const r=yb(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=yb(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 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]}),oot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uot=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 oot(e,t),e};Object.defineProperty(gb,"__esModule",{value:!0}),gb.ExprProps=void 0;const aot=Xe,lot=$s,cot=uot(Zt),fot=$c,xot=Bc,dot=m2,hot=ct,pot=Ky,mot=lt;class got extends hot.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=cot.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,aot.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,mot.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,lot.errorFor)("cannot filter type"))}return r}getExpression(e){const r=[];let i;const s=[],o=[];for(const a of this.statements)a instanceof dot.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 xot.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 fot.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 pot.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:i,orderBys:s}):this.expr.getExpression(e);return this.getFilteredExpression(e,u,o)}}gb.ExprProps=got;var Eb={},yot=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]}),Eot=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)&&yot(e,t,r);return Eot(e,t),e};Object.defineProperty(Eb,"__esModule",{value:!0}),Eb.ExprLogicalOp=void 0;const _ot=Wy,qle=Aot(Zt);class vot extends _ot.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[qle.boolT,qle.aggregateBoolT]}}Eb.ExprLogicalOp=vot;var Ab={},Cot=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]}),Sot=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)&&Cot(e,t,r);return Sot(e,t),e};Object.defineProperty(Ab,"__esModule",{value:!0}),Ab.ExprMax=void 0;const _b=bot(Zt),Tot=Jl;class Rot extends Tot.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[_b.numberT,_b.stringT,_b.dateT,_b.timestampT]}returns(e){return e}}Ab.ExprMax=Rot;var vb={},Dot=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]}),Oot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Fot=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)&&Dot(e,t,r);return Oot(e,t),e};Object.defineProperty(vb,"__esModule",{value:!0}),vb.ExprMin=void 0;const Cb=Fot(Zt),wot=Jl;class Not extends wot.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[Cb.numberT,Cb.stringT,Cb.dateT,Cb.timestampT]}returns(e){return e}}vb.ExprMin=Not;var Sb={},Lot=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]}),Iot=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)&&Lot(e,t,r);return Iot(e,t),e};Object.defineProperty(Sb,"__esModule",{value:!0}),Sb.ExprMinus=void 0;const Bot=$s,Hle=$ot(Zt),kot=ct;class Mot extends kot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[Hle.numberT]}getExpression(e){const r=this.expr.getExpression(e);return Hle.typeIn(r,this.legalChildTypes)?{...r,type:"number",value:{node:"unary-",e:r.value}}:(0,Bot.errorFor)("negate requires number")}}Sb.ExprMinus=Mot;var bb={};Object.defineProperty(bb,"__esModule",{value:!0}),bb.ExprMulDiv=void 0;const Pot=x2;class Uot extends Pot.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}bb.ExprMulDiv=Uot;var Tb={},Jy={};Object.defineProperty(Jy,"__esModule",{value:!0}),Jy.Unary=void 0;const jot=ct;class qot extends jot.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}Jy.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]}),Qot=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zot=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 Qot(e,t),e};Object.defineProperty(Tb,"__esModule",{value:!0}),Tb.ExprNot=void 0;const QB=zot(Zt),Got=Jy;class Wot extends Got.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[QB.boolT,QB.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(QB.numberT);const s=this.typeCheck(this.expr,i);return{...i,type:"boolean",value:{node:"not",e:s?i.value:{node:"false"}}}}}Tb.ExprNot=Wot;var Rb={};Object.defineProperty(Rb,"__esModule",{value:!0}),Rb.ExprNow=void 0;const Vot=ct,Yot=lt;class Kot extends Vot.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{type:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now",typeDef:{type:"timestamp"}},compositeFieldUsage:(0,Yot.emptyCompositeFieldUsage)()}}}Rb.ExprNow=Kot;var Mc={};Object.defineProperty(Mc,"__esModule",{value:!0}),Mc.ExprIsNull=Mc.PartialIsNull=Mc.ExprNULL=void 0;const Jot=Gt,Db=ct;function zB(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 Xot extends Db.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return(0,Jot.literalExprValue)({dataType:{type:"null"},value:{node:"null"}})}apply(e,r,i){return r==="!="||r==="="?zB(e,r,i):super.apply(e,r,i,!0)}}Mc.ExprNULL=Xot;class Zot extends Db.ExpressionDef{constructor(e){super(),this.op=e,this.elementType="<=> NULL"}apply(e,r,i){return zB(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial null check does not have a value")}atNodeType(){return Db.ATNodeType.Partial}}Mc.PartialIsNull=Zot;class eut extends Db.ExpressionDef{constructor(e,r){super(),this.expr=e,this.op=r,this.elementType="is null",this.has({expr:e})}getExpression(e){return zB(e,this.op,this.expr)}}Mc.ExprIsNull=eut;var Ob={};Object.defineProperty(Ob,"__esModule",{value:!0}),Ob.ExprNumber=void 0;const tut=Gt,nut=ct;class rut extends nut.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,tut.literalExprValue)({dataType:r,value:{node:"numberLiteral",literal:this.n}})}}Ob.ExprNumber=rut;var Fb={};Object.defineProperty(Fb,"__esModule",{value:!0}),Fb.ExprParens=void 0;const GB=ct;class iut extends GB.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()===GB.ATNodeType.Or?this.expr.apply(e,r,i,s):(0,GB.applyBinary)(e,i,r,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}Fb.ExprParens=iut;var wb={};Object.defineProperty(wb,"__esModule",{value:!0}),wb.ExprFilterExpression=void 0;const sut=ct;class out extends sut.ExpressionDef{constructor(e){super(),this.filterText=e,this.elementType="filter expression literal"}getExpression(){return{type:"filter expression",value:{node:"filterLiteral",filterSrc:this.filterText},expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:{fields:[],joinedUsage:{}}}}}wb.ExprFilterExpression=out;var Nb={};Object.defineProperty(Nb,"__esModule",{value:!0}),Nb.ExprRegEx=void 0;const uut=Gt,aut=ct;class lut extends aut.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return(0,uut.literalExprValue)({dataType:{type:"regular expression"},value:{node:"regexpLiteral",literal:this.regex}})}}Nb.ExprRegEx=lut;var Lb={};Object.defineProperty(Lb,"__esModule",{value:!0}),Lb.ExprString=void 0;const cut=ct,fut=Gt;class xut extends cut.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return(0,fut.literalExprValue)({dataType:{type:"string"},value:{node:"stringLiteral",literal:this.value}})}}Lb.ExprString=xut;var Ib={};Object.defineProperty(Ib,"__esModule",{value:!0}),Ib.ExprSum=void 0;const dut=p2;class hut extends dut.ExprAsymmetric{constructor(e,r,i){super("sum",e,r,i),this.has({source:r})}}Ib.ExprSum=hut;var $b={};Object.defineProperty($b,"__esModule",{value:!0}),$b.ExprTimeExtract=void 0;const Xl=Xe,Bb=Gt,WB=ct,put=Ic;class Xy extends WB.ExpressionDef{static extractor(e){const r=Xy.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=Xy.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 put.Range){let s=i.first.getExpression(e),o=i.last.getExpression(e);if(s.type==="error"||o.type==="error")return(0,Bb.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,WB.getMorphicValue)(s,"timestamp");l&&(s=l,a=!1)}else{const l=(0,WB.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,Bb.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,Bb.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,Bb.computedErrorExprValue)({dataType:{type:"number",numberType:"integer"},error:`${this.extractText} bad type ${s.type}`,from:[s]}))}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}$b.ExprTimeExtract=Xy,Xy.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var kb={},mu={},Mb={};Object.defineProperty(Mb,"__esModule",{value:!0}),Mb.QueryInputSpace=void 0;const mut=xs,gut=e2;class yut extends gut.RefinedSpace{constructor(e,r,i){super(e),this.queryOutput=r,this._isProtectedAccessSpace=i,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof mut.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}}Mb.QueryInputSpace=yut;var Eut=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]}),Aut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_ut=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)&&Eut(e,t,r);return Aut(e,t),e};Object.defineProperty(mu,"__esModule",{value:!0}),mu.ReduceFieldSpace=mu.QuerySpace=mu.QueryOperationSpace=void 0;const Pb=_ut(Xe),VB=Dc,Qle=kc,zle=Mr,vut=yt,Cut=e2,Sut=Ny,but=Pr,Tut=Mb,Da=lt,Rut=Xx;class Gle extends Cut.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 Tut.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 but.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();Pb.TD.isAtomic(c)&&Pb.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 zle.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:r,logTo:void 0})}getJoinOnCompositeFieldUsage(e){var r;const i=e.map(o=>new Qle.FieldName(o));this.astEl.has({reference:i});const s=this.exprSpace.lookup(i);if(s.found&&s.found instanceof Rut.StructSpaceFieldBase)return(0,Da.joinedCompositeFieldUsage)(e.slice(0,-1),(r=s.found.fieldDef().onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Da.emptyCompositeFieldUsage)());throw new Error("Unexpected join lookup was not found or not a struct")}getCompositeFieldUsageIncludingJoinOns(e){let r=e;const i=(0,Da.compositeFieldUsageJoinPaths)(e);for(const s of i)r=(0,Da.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 zle.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,Da.compositeFieldUsageDifference)(s,r));if(r=(0,Da.mergeCompositeFieldUsage)(r,u),!(0,Da.isEmptyCompositeFieldUsage)(u)){const a=(0,Da.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=Gle;class Wle extends Gle{addRefineFromFields(e){var r;if(Pb.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 Qle.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 Sut.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 vut.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){const e=[];let r=(0,Da.emptyCompositeFieldUsage)(),i=(0,Da.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)&&!Out(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(Pb.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,VB.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,VB.nameFromDef)(a)===o);u&&i.push(u)}r.extendSource=(0,VB.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=Wle;class Dut extends Wle{constructor(){super(...arguments),this.segmentType="reduce"}}mu.ReduceFieldSpace=Dut;function Out(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}var Fut=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]}),wut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Nut=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)&&Fut(e,t,r);return wut(e,t),e};Object.defineProperty(kb,"__esModule",{value:!0}),kb.ExprUngroup=void 0;const Vle=Xe,Lut=mu,Yle=Nut(Zt),Iut=ct;class $ut extends Iut.ExpressionDef{constructor(e,r,i){super({expr:r,fields:i}),this.control=e,this.expr=r,this.fields=i,this.legalChildTypes=Yle.anyAtomicT,this.elementType="ungroup"}getExpression(e){const r=this.expr.getExpression(e);if(!(0,Vle.expressionIsAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,Vle.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 Lut.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{...Yle.atomicDef(r),expressionType:"ungrouped_aggregate",value:i,evalSpace:"output",compositeFieldUsage:r.compositeFieldUsage}}return this.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}kb.ExprUngroup=$ut;var Ub={},But=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]}),kut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mut=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)&&But(e,t,r);return kut(e,t),e};Object.defineProperty(Ub,"__esModule",{value:!0}),Ub.ForRange=void 0;const Put=$s,Kle=Mut(Zt),jb=ds,Uut=Gt,jut=ct,qb=f2,Jle=Ic;class qut extends jut.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=[Kle.timestampT,Kle.dateT]}apply(e,r,i){const s=this.from.getExpression(e),o=i.getExpression(e);if(!this.typeCheck(i,o))return(0,Put.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,Uut.computedErrorExprValue)({dataType:{type:"boolean"},error:"for not number",from:[s,o]});const a=this.timeframe.text;let l=(0,jb.resolution)(a);if(s.type==="timestamp"&&(l="timestamp"),o.type==="date"&&l==="date"){const m=this.from,g=(0,jb.timeOffset)("date",s.value,"+",u.value,a),y=new qb.ExprTime("date",g);return new Jle.Range(m,y).apply(e,r,i)}const c=qb.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,jb.castTo)("timestamp",x,"date"),f=new qb.ExprTime("timestamp",x,[s])}const h=(0,jb.timeOffset)("timestamp",x,"+",u.value,a),p=new qb.ExprTime("timestamp",h,[s,u]);return new Jle.Range(f,p).apply(e,r,c)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}Ub.ForRange=qut;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 Pc=by,Hut=Xe,Qut=Gt,zut=Ic,Xle=f2,YB=ct;class Gut extends Error{}Sr.TimeFormatError=Gut;function nd(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 Zle="yyyy",e0e=`${Zle}-LL`,Ao=`${e0e}-dd`,t0e=`${Ao} HH`,n0e=`${t0e}:mm`,KB=`${n0e}:ss`;class r0e extends YB.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,Qut.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 JB extends r0e{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r;const i=nd(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=Pc.DateTime.fromFormat(e,KB);if(o.isValid)return new JB(i,r);if(o=Pc.DateTime.fromFormat(e,n0e),o.isValid){i.text=i.text+":00",r="minute";const u=o.plus({minute:1}).toFormat(KB);return new XB(i,r,"timestamp",u)}}}Sr.LiteralTimestamp=JB;class XB extends r0e{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,YB.getMorphicValue)(s,"timestamp"),l=(0,YB.getMorphicValue)(o,"timestamp");if(a&&l)s=a,o=l;else return super.apply(e,r,i)}if(o&&(0,Hut.isTemporalType)(u.type)){const a=u.type;return new zut.Range(new Xle.ExprTime(a,s.value),new Xle.ExprTime(a,o.value)).apply(e,r,i)}}return super.apply(e,r,i)}}class ZB extends XB{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,t0e);if(s.isValid)return r.text=r.text+":00:00",i=s.plus({hour:1}).toFormat(KB),new ZB(r,i)}}Sr.LiteralHour=ZB;class Zy extends XB{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 ek extends Zy{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,Ao);if(s.isValid)return i=s.plus({day:1}).toFormat(Ao),new ek(r,i)}}Sr.LiteralDay=ek;class tk extends Zy{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){const r=nd(e,!1);let i=r.text;const s=r.text.slice(0,10),o=Pc.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 tk(r,i)}}}Sr.LiteralWeek=tk;class nk extends Zy{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,e0e);if(s.isValid){const o=s.plus({months:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new nk(r,i)}}}Sr.LiteralMonth=nk;class rk extends Zy{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){const r=nd(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=Pc.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 rk(r,i)}}}Sr.LiteralQuarter=rk;class ik extends Zy{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){const r=nd(e,!1);let i=r.text;const s=Pc.DateTime.fromFormat(r.text,Zle);if(s.isValid){const o=s.plus({year:1});return r.text=s.toFormat(Ao),i=o.toFormat(Ao),new ik(r,i)}}}Sr.LiteralYear=ik;var Hb={};Object.defineProperty(Hb,"__esModule",{value:!0}),Hb.PartialCompare=void 0;const i0e=ct;class Wut extends i0e.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 i0e.ATNodeType.Partial}}Hb.PartialCompare=Wut;var y2={},Vut=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]}),Yut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Kut=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)&&Vut(e,t,r);return Yut(e,t),e};Object.defineProperty(y2,"__esModule",{value:!0}),y2.PickWhen=y2.Pick=void 0;const E2=Kut(Zt),s0e=Gt,Jut=ct,Xut=Je;function Qb(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class Zut extends Jut.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&&!E2.typeEq(u,m,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:m.type,returnType:u.type});u=Qb(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=Qb(u,f);return E2.typeEq(x,f,!0)?x.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(o.kids.caseElse=f.value,(0,s0e.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(!E2.typeEq(l.when,E2.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:l.when.type});if(o&&!E2.typeEq(o,l.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:l.pick.type,returnType:o.type});o=Qb(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=Qb(o,u);return E2.typeEq(a,u,!0)?a.type==="filter expression"?this.loggedErrorExpr("filter-expression-error","Pick statments cannot have filter expression values"):(r.kids.caseElse=u.value,(0,s0e.computedExprValue)({dataType:a,value:r,from:s})):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.type,returnType:a.type})}}y2.Pick=Zut;class eat extends Xut.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="caseWhen",this.has({pick:e})}}y2.PickWhen=eat;var A2={},tat=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]}),nat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),rat=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)&&tat(e,t,r);return nat(e,t),e};Object.defineProperty(A2,"__esModule",{value:!0}),A2.CaseWhen=A2.Case=void 0;const iat=Gt,sat=ct,oat=Je,_2=rat(Zt);function o0e(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class uat extends sat.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(!_2.typeEq(a.when,s))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:a.when.type,valueType:s.type})}else if(!_2.typeEq(a.when,_2.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:a.when.type});if(u&&!_2.typeEq(u,a.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:a.then.type,returnType:u.type});u=o0e(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&&!_2.typeEq(u,a,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:a.type,returnType:u.type});u=o0e(u,a),i.push(a),r.kids.caseElse=a.value}return(0,iat.computedExprValue)({value:r,dataType:u?_2.atomicDef(u):{type:"null"},from:i})}}A2.Case=uat;class aat extends oat.MalloyElement{constructor(e,r){super({when:e,then:r}),this.when=e,this.then=r,this.elementType="caseWhen"}}A2.CaseWhen=aat;var zb={},rd={},lat=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]}),cat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),fat=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)&&lat(e,t,r);return cat(e,t),e};Object.defineProperty(rd,"__esModule",{value:!0}),rd.RecordLiteral=rd.RecordElement=void 0;const u0e=Pi,xat=Gt,dat=ct,hat=Je,pat=fat(Zt);class mat extends hat.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]}}}rd.RecordElement=mat;class gat extends dat.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);u0e.TD.isAtomic(c)?(o.push(c),s.kids[l]=c.value,s.typeDef.fields.push((0,u0e.mkFieldDef)(pat.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,xat.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,[])}}rd.RecordLiteral=gat;var yat=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]}),Eat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Aat=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)&&yat(e,t,r);return Eat(e,t),e};Object.defineProperty(zb,"__esModule",{value:!0}),zb.ArrayLiteral=void 0;const _at=Gt,vat=ct,a0e=Aat(Zt),Cat=rd;class Sat extends vat.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 Cat.RecordLiteral?l.getNextElement(e,s):l.getExpression(e);if(i.push(c),c.type!=="error"){if(s){if(c.type!=="null"&&!a0e.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=a0e.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,_at.computedExprValue)({dataType:u,value:a,from:i})}}zb.ArrayLiteral=Sat;var Gb={};Object.defineProperty(Gb,"__esModule",{value:!0}),Gb.Timeframe=void 0;const bat=Xe,Tat=Je;class Rat extends Tat.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,bat.isTimestampUnit)(r)?r:"second"}}Gb.Timeframe=Rat;var Uc={};Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.ImportStatement=Uc.ImportSelect=Uc.ImportSourceName=void 0;const sk=Je;class Dat extends sk.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}Uc.ImportSourceName=Dat;class Oat extends sk.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}}Uc.ImportSelect=Oat;class Fat extends sk.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}'`)}}}Uc.ImportStatement=Fat;var eE={};Object.defineProperty(eE,"__esModule",{value:!0}),eE.ExtendBlock=void 0;const wat=Je,Nat=qn;class Lat extends wat.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Nat.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)for(const i of r.list)e.inputFS.extendSource(i)}}eE.ExtendBlock=Lat;var Wb={};Object.defineProperty(Wb,"__esModule",{value:!0}),Wb.Argument=void 0;const Iat=Je;class $at extends Iat.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}Wb.Argument=$at;var Vb={};Object.defineProperty(Vb,"__esModule",{value:!0}),Vb.HasParameter=void 0;const l0e=Xe,Bat=Je,kat=ct;class Mat extends Bat.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,l0e.isParameterType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default})),e.filterType&&(this.filterType=e.filterType)}parameter(){var e;let r;if(this.default!==void 0){const i=this.default.constantValue();if(this.type&&this.type!==i.type&&i.type!=="null"&&i.type!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),i.type==="null")return this.type?{type:this.type,value:i.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:i.value,name:this.name,type:"error"});if(i.type==="filter expression")return this.type!=="filter expression"&&this.logError("parameter-missing-default-or-type",`Filter expression parameters must have expicit filter type, for example '${this.name}::filter<string>'`),this.filterType&&(0,kat.checkFilterExpression)(this,this.filterType,i.value),{value:i.value,name:this.name,type:i.type};if(!(0,l0e.isCastType)(i.type)&&i.type!=="error")return this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${i.type}\``),{value:i.value,name:this.name,type:"error"};r={value:i.value,name:this.name,type:i.type}}else this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),r={value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"};return r.type==="filter expression"&&this.filterType&&(r.filterType=this.filterType),r}}Vb.HasParameter=Mat;var Yb={};Object.defineProperty(Yb,"__esModule",{value:!0}),Yb.AnonymousQuery=void 0;const Pat=Je,Uat=kr;class jat extends Pat.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Uat.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)}}Yb.AnonymousQuery=jat;var jc={};Object.defineProperty(jc,"__esModule",{value:!0}),jc.View=void 0;const qat=Je;class Hat extends qat.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}}jc.View=Hat;var Kb={};Object.defineProperty(Kb,"__esModule",{value:!0}),Kb.ViewArrow=void 0;const Qat=Pr,zat=jc;class Gat extends zat.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 Qat.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()}}Kb.ViewArrow=Gat;var Jb={},tE={};Object.defineProperty(tE,"__esModule",{value:!0}),tE.refine=void 0;const ok=Pi,Wat=lt,uk=Dc;function Vat(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,ok.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,ok.isQuerySegment)(u)&&(0,ok.isQuerySegment)(o)){const a=[],l=[],c=new Map(o.queryFields.map(f=>[(0,uk.nameFromDef)(f),f]));for(const f of u.queryFields)c.has((0,uk.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(uk.nameFromDef)}`),o.compositeFieldUsage=(0,Wat.mergeCompositeFieldUsage)(o.compositeFieldUsage,u.compositeFieldUsage)}else u.type==="index"&&o.type==="index"&&(o.indexFields=[...u.indexFields,...o.indexFields]);return[o]}tE.refine=Vat,Object.defineProperty(Jb,"__esModule",{value:!0}),Jb.ViewRefine=void 0;const Yat=ai,Kat=ks,Jat=tE,Xat=jc;class Zat extends Xat.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,Kat.getFinalStruct)(this.refinement,e.structDef(),s):Yat.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,Jat.refine)(this,r,s[0])}getImplicitName(){return this.base.getImplicitName()}}Jb.ViewRefine=Zat;var Xb={};Object.defineProperty(Xb,"__esModule",{value:!0}),Xb.ReferenceView=void 0;const ak=Xe,c0e=ai,elt=ks,tlt=Mr,nlt=tE,rlt=jc;class ilt extends rlt.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:c0e.ErrorFactory.structDef,outputStruct:c0e.ErrorFactory.structDef,pipeline:[],error:!0}};if(!i.found)return this.reference.logError(i.error.code,i.error.message),s();if(!(i.found instanceof tlt.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,ak.isAtomic)(o)){const u={type:"reduce",queryFields:[this.reference.refToField],compositeFieldUsage:o.compositeFieldUsage},a=this.reference.nameString,l={...(0,ak.sourceBase)(e.structDef()),type:"query_result",name:a,fields:[o]};return{pipeline:[u],name:a,outputStruct:l}}else return(0,ak.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,elt.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,nlt.refine)(this,r,s):r}getImplicitName(){return this.reference.nameString}}Xb.ReferenceView=ilt;var Zb={},nE={},eT={},rE={};Object.defineProperty(rE,"__esModule",{value:!0}),rE.Index=void 0;const slt=Je,olt=qn;class ult extends slt.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=olt.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}}rE.Index=ult;var iE={};Object.defineProperty(iE,"__esModule",{value:!0}),iE.SampleProperty=void 0;const alt=Je,f0e=qn;class llt extends alt.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=f0e.LegalRefinementStage.Tail,this.forceQueryClass=f0e.QueryClass.Index}sampling(){return this.sample}}iE.SampleProperty=llt;var tT={};Object.defineProperty(tT,"__esModule",{value:!0}),tT.IndexFieldSpace=void 0;const x0e=lt,d0e=Xe,lk=yt,clt=Mr,flt=mu,xlt=$y,dlt=Pr;class hlt extends flt.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const r of e)r instanceof lk.FieldReference?super.pushFields(r):r instanceof lk.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,x0e.emptyCompositeFieldUsage)(),i=(0,x0e.emptyNarrowedCompositeFieldResolution)();const s=[],o=this.inputSpace().structDef();for(const[u,a]of this.entries())if(a instanceof clt.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 xlt.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 dlt.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=lk.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();d0e.TD.isBasicAtomic(f)&&(0,d0e.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)}}tT.IndexFieldSpace=hlt,Object.defineProperty(eT,"__esModule",{value:!0}),eT.IndexBuilder=void 0;const ck=Xe,plt=ai,mlt=Ra,glt=rE,ylt=Bc,Elt=iE,Alt=tT,fk=lt;class _lt{constructor(e,r,i,s){this.filters=[],this.alwaysJoins=[],this.type="index",this.resultFS=new Alt.IndexFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof mlt.Filter?e.queryExecute(this):e instanceof ylt.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof glt.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 Elt.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,ck.isIndexSegment)(e)&&!(0,ck.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),plt.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,ck.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,fk.emptyCompositeFieldUsage)();return i.compositeFieldUsage=(0,fk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage),i}}eT.IndexBuilder=_lt;var nT={},sE={};Object.defineProperty(sE,"__esModule",{value:!0}),sE.GroupBy=void 0;const vlt=Bs,h0e=qn;class Clt extends vlt.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=h0e.LegalRefinementStage.Single,this.forceQueryClass=h0e.QueryClass.Grouping}}sE.GroupBy=Clt;var rT={};Object.defineProperty(rT,"__esModule",{value:!0}),rT.ProjectFieldSpace=void 0;const iT=Xe,Slt=mu;class blt extends Slt.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e===void 0||!iT.TD.isAtomic(e)||(0,iT.expressionIsAggregate)(e.expressionType)?!1:(0,iT.expressionInvolvesAggregate)(e.expressionType)&&(0,iT.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}rT.ProjectFieldSpace=blt;var qc={},id={};Object.defineProperty(id,"__esModule",{value:!0}),id.Ordering=id.OrderBy=void 0;const Tlt=Xe,p0e=kc,m0e=Je,Rlt=qn;class Dlt extends m0e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof p0e.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 p0e.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,Tlt.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}}id.OrderBy=Dlt;class Olt extends m0e.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Rlt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}}id.Ordering=Olt,Object.defineProperty(qc,"__esModule",{value:!0}),qc.ReduceBuilder=qc.QuerySegmentBuilder=void 0;const gu=Xe,Flt=ai,wlt=kc,Nlt=Bc,Llt=id,Ilt=mu,$lt=Bs,xk=lt;function g0e(t){return t.type==="fieldref"?t.path[t.path.length-1]:t.name}class y0e{constructor(){this.alwaysJoins=[],this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}e instanceof $lt.DefinitionList?this.resultFS.pushFields(...e.list):e instanceof Nlt.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof Llt.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,xk.emptyCompositeFieldUsage)();r.compositeFieldUsage=(0,xk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage)}}qc.QuerySegmentBuilder=y0e;class Blt extends y0e{constructor(e,r,i,s){super(),this.type="grouping",this.resultFS=new Ilt.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}`),Flt.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=g0e(o)}}if(i.orderBy===void 0||i.defaultOrderBy){let s;for(const o of i.queryFields){let u=!1,a=!1,l;const c=g0e(o);if(o.type==="fieldref"){const f=o.path.map(h=>new wlt.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}}qc.ReduceBuilder=Blt,Object.defineProperty(nT,"__esModule",{value:!0}),nT.ProjectBuilder=void 0;const E0e=Xe,klt=ai,Mlt=sE,Plt=rT,Ult=qc;class jlt extends Ult.QuerySegmentBuilder{constructor(e,r,i,s){super(),this.type="project",this.resultFS=new Plt.ProjectFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Mlt.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,E0e.isProjectSegment)(e)||(0,E0e.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),klt.ErrorFactory.projectSegment;const i=this.resultFS.getQuerySegment(r);return this.refineFrom(r,i),i}}nT.ProjectBuilder=jlt;var sT={};Object.defineProperty(sT,"__esModule",{value:!0}),sT.PartialBuilder=void 0;const qlt=Pi,Hlt=qc;class Qlt 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}`)}}sT.PartialBuilder=Qlt,Object.defineProperty(nE,"__esModule",{value:!0}),nE.QOpDesc=void 0;const zlt=eT,Glt=nT,Wlt=qc,Vlt=Je,Ylt=ks,Klt=Pr,sd=qn,Jlt=sT;class Xlt extends Vlt.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,i=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=sd.QueryClass.Grouping:this.refineThis.type==="project"?r=sd.QueryClass.Project:this.refineThis.type==="index"&&(r=sd.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=sd.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,i){switch(this.computeType()){case sd.QueryClass.Grouping:return new Wlt.ReduceBuilder(e,this.refineThis,r,i);case sd.QueryClass.Project:return new Glt.ProjectBuilder(e,this.refineThis,r,i);case sd.QueryClass.Index:return new zlt.IndexBuilder(e,this.refineThis,r,i);case void 0:return new Jlt.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 Klt.StaticSourceSpace((0,Ylt.opOutputStruct)(this,e.structDef(),s))}}}nE.QOpDesc=Xlt,Object.defineProperty(Zb,"__esModule",{value:!0}),Zb.QOpDescView=void 0;const Zlt=Xe,e0t=Pr,A0e=nE,t0t=ks,dk=qn,n0t=jc;class r0t extends n0t.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,Zlt.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 A0e.QOpDesc([]),u=new A0e.QOpDesc([]);for(const a of this.operation.list)switch(a.queryRefinementStage){case dk.LegalRefinementStage.Head:o.push(a);break;case dk.LegalRefinementStage.Single:a.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case dk.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,t0t.getFinalStruct)(this,e.structDef(),s.slice(-1));s[a]=this.getOp(new e0t.StaticSourceSpace(l),void 0,u,s[a])}return s}getImplicitName(){}}Zb.QOpDescView=r0t;var Rn={},i0t=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]}),s0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o0t=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)&&i0t(e,t,r);return s0t(e,t),e};Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.FieldDefinitionValue=Rn.DefSpace=Rn.DimensionFieldDeclaration=Rn.MeasureFieldDeclaration=Rn.DeclareFieldDeclaration=Rn.ProjectFieldDeclaration=Rn.GroupByFieldDeclaration=Rn.AggregateFieldDeclaration=Rn.CalculateFieldDeclaration=Rn.AtomicFieldDeclaration=void 0;const hk=Xe,_0e=o0t(Zt),u0t=c2,a0t=Je,od=sr,l0t=kr,c0t=Mr;class Hc extends a0t.MalloyElement{constructor(e,r,i){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=i,this.isNoteableObj=!0,this.extendNote=l0t.extendNoteMethod}getName(){return this.defineName}fieldDef(e,r){return this.queryFieldDef(new pk(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,hk.isAtomicFieldType)(i.type)&&i.type!=="error"){this.typecheckExprValue(i);const u=(0,hk.mkFieldDef)(_0e.atomicDef(i),r);return(u.type==="date"||u.type==="timestamp")&&(0,u0t.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 pk&&e.foundCircle)&&i.type!=="error"){const u=_0e.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 v0e(e,this))}}Rn.AtomicFieldDeclaration=Hc;class f0t extends Hc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}Rn.CalculateFieldDeclaration=f0t;class x0t extends Hc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckAggregate)(e,this)}}Rn.AggregateFieldDeclaration=x0t;class d0t extends Hc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckGroupBy)(e,this)}}Rn.GroupByFieldDeclaration=d0t;class h0t extends Hc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckProject)(e,this)}}Rn.ProjectFieldDeclaration=h0t;class p0t extends Hc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckDeclare)(e,this)}}Rn.DeclareFieldDeclaration=p0t;class m0t extends Hc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckMeasure)(e,this)}}Rn.MeasureFieldDeclaration=m0t;class g0t extends Hc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,od.typecheckDimension)(e,this)}}Rn.DimensionFieldDeclaration=g0t;class pk{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}}Rn.DefSpace=pk;class v0e extends c0t.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,hk.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}}Rn.FieldDefinitionValue=v0e;var oT={};Object.defineProperty(oT,"__esModule",{value:!0}),oT.Aggregate=void 0;const y0t=Bs,C0e=qn;class E0t extends y0t.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=C0e.LegalRefinementStage.Single,this.forceQueryClass=C0e.QueryClass.Grouping}}oT.Aggregate=E0t;var uT={};Object.defineProperty(uT,"__esModule",{value:!0}),uT.Calculate=void 0;const A0t=Bs,_0t=qn;class v0t extends A0t.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=_0t.LegalRefinementStage.Single}}uT.Calculate=v0t;var oE={};Object.defineProperty(oE,"__esModule",{value:!0}),oE.Dimensions=void 0;const C0t=Oc;class S0t extends C0t.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}oE.Dimensions=S0t;var uE={};Object.defineProperty(uE,"__esModule",{value:!0}),uE.Measures=void 0;const b0t=Oc;class T0t extends b0t.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}uE.Measures=T0t;var aT={};Object.defineProperty(aT,"__esModule",{value:!0}),aT.Nests=void 0;const R0t=Bs,S0e=qn;class D0t extends R0t.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=S0e.LegalRefinementStage.Single,this.forceQueryClass=S0e.QueryClass.Grouping}}aT.Nests=D0t;var lT={};Object.defineProperty(lT,"__esModule",{value:!0}),lT.ProjectStatement=void 0;const O0t=Bs,b0e=qn;class F0t extends O0t.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=b0e.QueryClass.Project,this.queryRefinementStage=b0e.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}lT.ProjectStatement=F0t;var Qc={},Zl={},$n={};Object.defineProperty($n,"__esModule",{value:!0}),$n.getPlainString=$n.unIndent=$n.getOptionalId=$n.idToStr=$n.getId=$n.getStringParts=$n.getStringIfShort=$n.getShortString=void 0;const T0e=Zo;function R0e(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?T0e.ParseUtil.parseString(i,i[0]):""}$n.getShortString=R0e;function D0e(t){const e=t.string().shortString();if(e)return R0e(e)}$n.getStringIfShort=D0e;function*O0e(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)}}$n.getStringParts=O0e;function F0e(t){return w0e(t.id())}$n.getId=F0e;function w0e(t){const e=t.BQ_STRING();return e?T0e.ParseUtil.parseString(e.text,"`"):t.text}$n.idToStr=w0e;function w0t(t){function e(r){return"id"in r}if(e(t)&&t.id())return F0e(t)}$n.getOptionalId=w0t;function*N0e(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 N0t(t){let e;for(const r of N0e(t)){const i=r.match(/^( *).*[^\s]/);if(i){const s=i[1].length;(e===void 0||s<e)&&(e=s)}}return e}function L0e(t){let e;for(const r of t)if(typeof r=="string"){const i=N0t(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 N0e(i))o[0]===" "&&(o=o.slice(e)),s+=o;t[r]=s}}}$n.unIndent=L0e;function L0t(t,e=!1){const r=[],i=D0e(t);if(i)return[i,r];const s=[],o=t.string().sqlString();if(o){for(const u of O0e(o))if(typeof u=="string")s.push(u);else if(r.push(u),e)return[void 0,r];return L0e(s),[s.join(""),r]}return["",r]}$n.getPlainString=L0t,Object.defineProperty(Zl,"__esModule",{value:!0}),Zl.findReferences=Zl.deprecatedParseTableURI=Zl.constructTableKey=void 0;const I0t=uc,mk=$n;function I0e(t){const e=(0,mk.getStringIfShort)(t);if(e)return e;const r=[],i=t.string().sqlString();if(i){for(const s of(0,mk.getStringParts)(i))typeof s=="string"&&r.push(s);return r.join("")}return""}class $0t{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,i){const s=$0e(e,r);this.needTables[s]||(this.needTables[s]={connectionName:e,tablePath:r,firstReference:i})}enterExploreTable(e){const r=(0,mk.getId)(e.connectionId()),i=I0e(e.tablePath()),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const r=I0e(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}}function $0e(t,e){return t===void 0?e:`${t}:${e}`}Zl.constructTableKey=$0e;function B0t(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,r,i]=e;return{connectionName:r,tablePath:i}}else return{tablePath:t}}Zl.deprecatedParseTableURI=B0t;function k0t(t,e,r){const i=new $0t(t,e),s=i;return I0t.ParseTreeWalker.DEFAULT.walk(s,r),{tables:i.needTables,urls:i.needImports}}Zl.findReferences=k0t,Object.defineProperty(Qc,"__esModule",{value:!0}),Qc.TableFunctionSource=Qc.TableMethodSource=Qc.TableSource=void 0;const B0e=Zl,M0t=Eo,k0e=ai;class gk extends M0t.Source{getSourceDef(){var e,r,i;const s=this.getTableInfo();if(s===void 0)return k0e.ErrorFactory.structDef;const{tablePath:o,connectionName:u}=s,a=(0,B0e.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),k0e.ErrorFactory.structDef}}Qc.TableSource=gk;class P0t extends gk{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}}}Qc.TableMethodSource=P0t;class U0t extends gk{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,B0e.deprecatedParseTableURI)(this.tableURI)}}Qc.TableFunctionSource=U0t;var cT={};Object.defineProperty(cT,"__esModule",{value:!0}),cT.SQLString=void 0;const j0t=Je,M0e=hu;class q0t extends j0t.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(H0t)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof M0e.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}}cT.SQLString=q0t;function H0t(t){return t instanceof M0e.SourceQueryElement}var fT={};Object.defineProperty(fT,"__esModule",{value:!0}),fT.SourceDesc=void 0;const Q0t=Je;class z0t extends Q0t.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}fT.SourceDesc=z0t;var xT={};Object.defineProperty(xT,"__esModule",{value:!0}),xT.isSourceProperty=void 0;const G0t=Ra,W0t=Oc,V0t=r2,Y0t=wc,K0t=i2,J0t=s2,X0t=o2,Z0t=Fc,ect=xs;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}xT.isSourceProperty=tct;var dT={};Object.defineProperty(dT,"__esModule",{value:!0}),dT.isFieldCollectionMember=void 0;const nct=Rn,P0e=yt;function rct(t){return t instanceof P0e.FieldReference||t instanceof P0e.WildcardFieldReference||t instanceof nct.AtomicFieldDeclaration}dT.isFieldCollectionMember=rct;var hT={};Object.defineProperty(hT,"__esModule",{value:!0}),hT.isQueryElement=void 0;const ict=u2,sct=a2,oct=Hy,uct=Qy;function act(t){return t instanceof ict.QueryArrow||t instanceof sct.QueryRefine||t instanceof oct.QueryReference||t instanceof uct.QueryRaw}hT.isQueryElement=act;var U0e={};Object.defineProperty(U0e,"__esModule",{value:!0});var pT={};Object.defineProperty(pT,"__esModule",{value:!0}),pT.isQueryProperty=void 0;function lct(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}pT.isQueryProperty=lct;var mT={};Object.defineProperty(mT,"__esModule",{value:!0}),mT.isQueryExtendProperty=void 0;const cct=oE,fct=xs,xct=uE;function dct(t){return t instanceof cct.Dimensions||t instanceof xct.Measures||t instanceof fct.JoinStatement}mT.isQueryExtendProperty=dct;var gT={};Object.defineProperty(gT,"__esModule",{value:!0}),gT.isFieldPropStatement=void 0;const hct=$c,pct=Ra,mct=Bc,gct=m2;function yct(t){return t instanceof pct.Filter||t instanceof mct.Limit||t instanceof gct.PartitionBy||t instanceof hct.FunctionOrdering}gT.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(Ry,t),r(Xp,t),r(Zp,t),r(Eo,t),r(Fy,t),r(hu,t),r(X4,t),r(Z4,t),r(nb,t),r(ky,t),r(rb,t),r(ib,t),r(du,t),r(r2,t),r(i2,t),r(wc,t),r(s2,t),r(o2,t),r(ob,t),r(x2,t),r(ab,t),r(d2,t),r($c,t),r(lb,t),r(Jl,t),r(cb,t),r(p2,t),r(fb,t),r(xb,t),r(db,t),r(Kl,t),r(hb,t),r(pb,t),r(gb,t),r(Ky,t),r(Vy,t),r(ed,t),r(Eb,t),r(Ab,t),r(vb,t),r(Sb,t),r(bb,t),r(Tb,t),r(Rb,t),r(Mc,t),r(Ob,t),r(Fb,t),r(wb,t),r(Nb,t),r(Lb,t),r(Ib,t),r($b,t),r(kb,t),r(Ub,t),r(Sr,t),r(Hb,t),r(m2,t),r(y2,t),r(A2,t),r(zb,t),r(rd,t),r(Ic,t),r(Gb,t),r(Jy,t),r(Uc,t),r(eE,t),r(Wb,t),r(Vb,t),r(Yb,t),r(a2,t),r(u2,t),r(jc,t),r(Kb,t),r(Jb,t),r(Xb,t),r(Zb,t),r(Rn,t),r(yt,t),r(oT,t),r(uT,t),r(Oc,t),r(oE,t),r(eE,t),r(Ra,t),r(sE,t),r(rE,t),r(xs,t),r(Dy,t),r(Bc,t),r(uE,t),r(Ry,t),r(aT,t),r(id,t),r(lT,t),r(nE,t),r(iE,t),r(l2,t),r(Zx,t),r(zy,t),r(Qc,t),r(cT,t),r(Fc,t),r(pu,t),r(fT,t),r(xT,t),r(ct,t),r(dT,t),r(kc,t),r(Je,t),r(hT,t),r(U0e,t),r(pT,t),r(mT,t),r(gT,t)}(z4);var yT={},Ect=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]}),Act=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_ct=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)&&Ect(e,t,r);return Act(e,t),e};Object.defineProperty(yT,"__esModule",{value:!0}),yT.MalloyToAST=void 0;const j0e=py,vct=Kh,ie=_ct(z4),yk=Yp,q0e=Er,Cct=z4,Yn=$n,ET=Xe,Sct=Zo,H0e=jn,bct=Cy;class Q0e extends ie.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class Ek extends ie.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const Tct=[];class Rct extends vct.AbstractParseTreeVisitor{constructor(e,r,i){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=i;for(const s of Tct){const o=Sct.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,yk.makeLogMessage)(r,i,{at:e.location,...s}))}rangeFromContext(e){return(0,H0e.rangeFromContext)(this.parseInfo.sourceInfo,e)}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new q0e.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,r,i,s){this.msgLog.log((0,yk.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}warnWithReplacement(e,r,i,s){this.msgLog.log((0,yk.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)}only(e,r,i){const s=[];for(const o of e){const u=r(o);u?s.push(u):o instanceof Ek||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 ie.FieldName((0,Yn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new ie.ModelEntryReference((0,Yn.getId)(e)),e.id())}defaultResult(){return new ie.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 q0e.Interval(r,i.stopIndex);return this.parseInfo.sourceStream.getText(s)}getFilterElement(e){const r=this.getFieldExpr(e),i=new ie.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 ie.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 j0e.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return r||""}makeSqlString(e,r){for(const i of(0,Yn.getStringParts)(e))i instanceof j0e.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 ie.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=>ie.isDocStatementOrDocStatementList(i)&&i,"statement");return new ie.Document(r)}visitDefineSourceStatement(e){const i=e.sourcePropertyList().sourceDefinition().map(u=>this.visitSourceDefinition(u)),s=this.getNotes(e.tags()),o=new ie.DefineSourceList(i);return o.extendNote({blockNotes:s}),o}getSourceParameter(e){const r=(0,Yn.getId)(e.parameterNameDef());let i,s;const o=e.legalParamType();if(o){const l=o.malloyType();if(l){const f=this.getMalloyType(l);(0,bct.isFilterable)(f)?s=f:this.contextError(o,"parameter-illegal-default-type",`Unknown filter type ${f}`)}const c=o.FILTER()?"filter expression":o.text.toLowerCase();if(!(0,ET.isParameterType)(c))return this.contextError(o,"parameter-illegal-default-type",`Unknown parameter type ${c}`),null;i=c}const u=e.fieldExpr();let a;if(u){const l=new ie.ConstantExpression(this.getFieldExpr(u));a=this.astAt(l,u)}return this.astAt(new ie.HasParameter({name:r,type:i,default:a,filterType:s}),e)}getSourceParameters(e){if(e===void 0)return[];this.inExperiment("parameters",e);function r(i){return i!==null}return e.sourceParameter().map(i=>this.getSourceParameter(i)).filter(r)}visitSourceDefinition(e){const r=this.visit(e.sqExplore()),i=this.getSourceParameters(e.sourceParameters()),s=new ie.DefineSource((0,Yn.getId)(e.sourceNameDef()),r instanceof ie.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=>ie.isSourceProperty(s)&&s,"source property");return new ie.SourceDesc(r)}visitExploreTable(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=this.getPlainStringFrom(e.tablePath());return this.astAt(new ie.TableMethodSource(i,s),e)}visitSqlSource(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=new ie.SQLString,o=e.sqlString();o&&this.makeSqlString(o,s);const u=e.shortString();u&&s.push((0,Yn.getShortString)(u));const a=new ie.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 ie.Join&&(i.push(u),u instanceof ie.ExpressionJoin?(u.joinType="many",u.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):u instanceof ie.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const s=new ie.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 ie.Join&&(s.push(u),u instanceof ie.ExpressionJoin&&(u.joinType="one"));const o=new ie.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 ie.Join&&(s.push(u),u instanceof ie.ExpressionJoin?u.joinType="cross":u.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const o=new ie.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 ie.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 ie.SQReference(i,this.getSQArguments(s)),e),notes:[],joinAs:i}:{joinAs:i,joinFrom:new ie.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 ie.ExpressionJoin(i,s),a=e.joinExpression(),l=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,ET.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 ie.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(),ie.DimensionFieldDeclaration),s=new ie.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(),ie.MeasureFieldDeclaration),s=new ie.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(ie.isQueryExtendProperty(o))r.push(o);else throw this.internalError(e,`Query extend matched, but ${o.elementType} found`);const s=new ie.ExtendBlock(r);return this.astAt(s,e)}visitExploreRenameDef(e){const r=e.fieldName(0),i=e.fieldName(1),s=new ie.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 ie.Renames(s,r);return this.astAt(o,e)}visitFilterClauseList(e){return new ie.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 ie.Views(i,r),o=this.getNotes(e.tags());return s.extendNote({blockNotes:o}),s}visitDefExplorePrimaryKey(e){const r=new ie.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 ie.FieldReferences(i)}visitDefExploreEditField(e){const r=e.ACCEPT()?"accept":"except";return new ie.FieldListEdit(r,this.getFieldNameList(e.fieldNameList(),ie.AcceptExceptFieldReference))}visitSQInclude(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new ie.SQExtend(r,new ie.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 ie.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=>ie.isQueryProperty(i)&&i,"query statement");return new ie.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 ie.FieldReference||s instanceof ie.AtomicFieldDeclaration?s:!1,"view field")}visitAggregateStatement(e){const r=new ie.Aggregate(this.getQueryItems(e.queryFieldList(),ie.AggregateFieldDeclaration,ie.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){const r=new ie.GroupBy(this.getQueryItems(e.queryFieldList(),ie.GroupByFieldDeclaration,ie.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){const r=new ie.Calculate(this.getQueryItems(e.queryFieldList(),ie.CalculateFieldDeclaration,ie.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(),ie.ExpressionFieldReference);let a;const l=s.timeframe();l&&(a=new ie.ExprGranularTime(new ie.ExprIdReference(u),this.visitTimeframe(l).text,!0));const c=s.aggregate();if(c){const x=c.text.toLowerCase();if(x==="sum")a=new ie.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,ie.ProjectFieldDeclaration,ie.ProjectFieldReference));return this.astAt(new ie.ProjectStatement(r),e)}visitProjectStatement(e){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,ie.ProjectFieldReference):void 0,o=this.astAt(new ie.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 ie.WildcardFieldReference(void 0),e);const o=this.getFieldPath(s,ie.IndexFieldReference);return i.STAR()?this.astAt(new ie.WildcardFieldReference(o),e):this.astAt(o,e)});return new ie.FieldReferences(r)}visitIndexStatement(e){const r=this.visitIndexFields(e.indexFields()),i=new ie.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 ie.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 ie.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 ie.FunctionOrdering(r),e)}visitOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.INTEGER_LITERAL();if(i)return new ie.OrderBy(this.getNumber(i),r);const s=e.fieldName();if(s)return new ie.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 ie.Ordering(r),e)}visitTopStatement(e){const r=this.getNumber(e.INTEGER_LITERAL());return this.astAt(new ie.Limit(r),e)}visitTopLevelQueryDefs(e){const r=e.topLevelQueryDef().map(o=>this.visitTopLevelQueryDef(o)),i=this.getNotes(e.tags()),s=new ie.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 ie.SourceQueryElement){const o=new ie.DefineQuery(r,i);return o.extendNote({notes:s}),this.astAt(o,e)}throw this.internalError(e,`Expected query definition, got a '${i.elementType}'`)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new ie.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 ie.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof ie.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 ie.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 ie.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 ie.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new ie.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 ie.ExprLogicalOp(r,"or",i)}visitExprLogicalAnd(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new ie.ExprLogicalOp(r,"and",i)}visitExprOrTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ie.ExprAlternationTree(r,"|",i),e)}visitExprAndTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ie.ExprAlternationTree(r,"&",i),e)}visitExprCoalesce(e){const r=this.getFieldExpr(e.fieldExpr()[0]),i=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new ie.ExprCoalesce(r,i),e)}visitPartialCompare(e){const r=e.compareOp().text;if(ie.isComparison(r))return this.astAt(new ie.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 ie.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 ie.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 ie.ExprString(r.slice(1,-1));return this.astAt(s,e)}visitExprRegex(e){const r=e.HACKY_REGEX().text;return new ie.ExprRegEx(r.slice(2,-1))}visitExprNow(e){return new ie.ExprNow}visitExprNumber(e){return new ie.ExprNumber(e.text)}visitExprFieldPath(e){const r=new ie.ExprIdReference(this.getFieldPath(e.fieldPath(),ie.ExpressionFieldReference));return this.astAt(r,e)}visitExprNULL(e){return new ie.ExprNULL}visitExprExpr(e){return new ie.ExprParens(this.getFieldExpr(e.fieldExpr()))}visitExprMinus(e){return new ie.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 ie.ExprAddSub(r,s,i)}visitExprMulDiv(e){const r=e.STAR()?"*":e.SLASH()?"/":"%";return new ie.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(ie.isEquality(r)){const o=this.rangeFromContext(e);return s instanceof ie.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 ie.ExprEquality(i,r,s),e)}else if(ie.isComparison(r))return this.astAt(new ie.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 ie.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,ie.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 ie.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 ie.ExprIdReference(i),r);return o==="min"?new ie.ExprMin(l):new ie.ExprMax(l)}else{if(o==="avg")return new ie.ExprAvg(a,s);if(o==="sum")return new ie.ExprSum(a,s);this.contextError(e,"aggregate-parse-error",`Cannot parse aggregate function ${o}`)}return new ie.ExprNULL}visitExprPathlessAggregate(e){const r=e.fieldExpr(),i=r?this.getFieldExpr(r):void 0,s=void 0,o=e.aggregate().text.toLowerCase();if(o==="count")return this.astAt(i?new ie.ExprCountDistinct(i):new ie.ExprCount,e);if(o==="min"){if(i)return new ie.ExprMin(i);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o))}else if(o==="max"){if(i)return new ie.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 ie.ExprNULL;const u=e.SOURCE_KW()!==void 0;if(o==="avg")return new ie.ExprAvg(i,s,u);if(o==="sum")return new ie.ExprSum(i,s,u)}return new ie.ExprNULL}visitExprApply(e){return new ie.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new ie.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new ie.ExprCast(this.getFieldExpr(e.fieldExpr()),r)}getMalloyType(e){const r=e.text;if((0,ET.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 ie.ExprCast(this.getFieldExpr(e.fieldExpr()),r,!0)}visitExprTimeTrunc(e){return new ie.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new ie.Timeframe(e.text)}visitExprForRange(e){const r=this.getFieldExpr(e._startAt),i=this.getFieldExpr(e._duration),s=this.visitTimeframe(e.timeframe());return new ie.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,ie.ExpressionFieldReference):void 0,a=o&&u?this.astAt(u,o):void 0;return ie.ExprTimeExtract.extractor(s)?this.astAt(new ie.ExprTimeExtract(s,i),e):this.astAt(new ie.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,ET.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"),ie.ExprTimeExtract.extractor(c)?this.astAt(new ie.ExprTimeExtract(c,o),e):this.astAt(new ie.ExprFunc(c,o,u,l),e)}visitExprDuration(e){return new ie.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 ie.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 ie.Case(i,o,a)}visitPickStatement(e){const r=e.pick().map(i=>{let s;return i._pickValue&&(s=this.getFieldExpr(i._pickValue)),new ie.PickWhen(s,this.getFieldExpr(i._pickWhen))});return e.ELSE()?new ie.Pick(r,this.getFieldExpr(e._pickElse)):new ie.Pick(r)}visitExprFieldProps(e){const r=this.only(e.fieldProperties().fieldPropertyStatement().map(i=>this.visit(i)),i=>ie.isFieldPropStatement(i)&&i,"field property statement");return new ie.ExprProps(this.getFieldExpr(e.fieldExpr()),r)}visitPartitionByStatement(e){return this.astAt(new ie.PartitionBy(e.id().map(r=>this.astAt(new ie.PartitionByFieldReference([this.astAt(new ie.FieldName((0,Yn.idToStr)(r)),r)]),r))),e)}visitLiteralTimestamp(e){return this.parseTime(e,ie.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,ie.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,ie.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,ie.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,ie.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,ie.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,ie.LiteralYear.parse)}visitImportStatement(e){const r=this.getPlainStringFrom(e.importURL()),i=this.astAt(new ie.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 ie.ImportSourceName((0,Yn.idToStr)(u[1])),u[1]):void 0;i.push(this.astAt(new ie.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 ie.SampleProperty({rows:this.getNumber(r)});const i=e.sampleSpec().PERCENT_LITERAL();if(i)return new ie.SampleProperty({percent:this.getNumber(i)});const s=e.sampleSpec().TRUE()!==void 0;return new ie.SampleProperty({enable:s})}visitDocAnnotations(e){const r=e.DOC_ANNOTATION().map(s=>({text:s.text,at:this.getLocation(e)})),i=new ie.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 Ek(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"misplaced-model-annotation","Model annotations not allowed at this scope"),new Ek(e.text)}visitDefExploreAnnotation(e){const r=this.getNotes(e);return new ie.ObjectAnnotation(r)}getSQArgument(e){const r=e.argumentId(),i=r?this.astAt(new ie.PartitionByFieldReference([this.astAt(new ie.FieldName((0,Yn.idToStr)(r.id())),r)]),r):void 0;return this.astAt(new ie.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 ie.SQReference(r,i),e.id())}getSqExpr(e){const r=this.visit(e);return r instanceof ie.SourceQueryElement?r:(this.contextError(e,"unexpected-non-source-query-expression-node",`Expected a source/query expression, not '${r.elementType}'`),new Q0e)}visitSQExtendedSource(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new ie.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(H0e.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 ie.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 ie.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 ie.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 ie.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 ie.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 ie.SQCompose(r),e)}visitSQArrow(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new ie.SQArrow(r,this.getVExpr(i));return this.astAt(s,e)}getVExpr(e){const r=this.visit(e);if(r instanceof ie.View)return r;throw this.internalError(e,`Expected view, got a '${r.elementType}'`)}visitSegField(e){return new ie.ReferenceView(this.getFieldPath(e.fieldPath(),ie.ViewOrScalarFieldReference))}visitSegOps(e){return new ie.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new ie.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new ie.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new ie.SQRefine(r,this.getVExpr(i));return this.astAt(s,e)}visitSQTable(e){const r=this.visit(e.exploreTable());if(r instanceof Cct.TableSource){const i=new ie.SQSource(r);return this.astAt(i,e)}return new Q0e}visitSQSQL(e){const r=new ie.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(r,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new ie.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}visitRecordRef(e){const r=new ie.ExprIdReference(this.getFieldPath(e.fieldPath(),ie.ExpressionFieldReference));return this.astAt(new ie.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 ie.RecordElement(s),e)}visitExprLiteralRecord(e){const r=this.only(e.recordElement().map(i=>this.astAt(this.visit(i),i)),i=>i instanceof ie.RecordElement&&i,"a legal record property description");return new ie.RecordLiteral(r)}visitExprArrayLiteral(e){const r=e.fieldExpr().map(s=>this.getFieldExpr(s)),i=new ie.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 ie.ExprCompare(this.getFieldExpr(i),r,this.getFieldExpr(s)),e)}visitExprNullCheck(e){const r=e.fieldExpr();return this.astAt(new ie.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 ie.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 ie.ExprFilterExpression(s);return this.astAt(o,e)}visitTripFilterString(e){const i=e.text.slice(1).trimStart().slice(3,-3),s=new ie.ExprFilterExpression(i);return this.astAt(s,e)}}yT.MalloyToAST=Rct;var AT={};Object.defineProperty(AT,"__esModule",{value:!0}),AT.Zone=void 0;class Dct{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})}}AT.Zone=Dct;var _T={};Object.defineProperty(_T,"__esModule",{value:!0}),_T.walkForDocumentSymbols=void 0;const Oct=uc,Fct=$n;class wct{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)})}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,Fct.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 Nct(t,e,r){const i=new wct(t,e,[],[]),s=i;return Oct.ParseTreeWalker.DEFAULT.walk(s,r),i.symbols}_T.walkForDocumentSymbols=Nct;var vT={};Object.defineProperty(vT,"__esModule",{value:!0}),vT.walkForDocumentCompletions=void 0;const Lct=uc,Ict=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],$ct=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],Bct=["source","explore","query","sql"];class kct{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 Ict)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 $ct)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 Bct)this.completions.push({type:"model_property",text:`${i}: `})}}}function Mct(t,e,r){const i=new kct(t,[],r),s=i;return Lct.ParseTreeWalker.DEFAULT.walk(s,e),i.completions}vT.walkForDocumentCompletions=Mct;var CT={};Object.defineProperty(CT,"__esModule",{value:!0}),CT.walkForDocumentHelpContext=void 0;const Pct=qL;class Uct extends Pct.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 jct(t,e){return new Uct(e).visit(t)}CT.walkForDocumentHelpContext=jct;var aE={};Object.defineProperty(aE,"__esModule",{value:!0}),aE.ReferenceList=void 0;const qct=jn;class Hct{constructor(e,r=[]){this.sourceURL=e,this.references=r}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,qct.locationContainsPosition)(i.location,e))return i}toArray(){return[...this.references]}}aE.ReferenceList=Hct;var ST={};Object.defineProperty(ST,"__esModule",{value:!0}),ST.isNeedResponse=void 0;function Qct(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}ST.isNeedResponse=Qct;var bT={};Object.defineProperty(bT,"__esModule",{value:!0}),bT.walkForModelAnnotation=void 0;const zct=uc;class Gct{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 Wct(t,e,r){const i=new Gct(t,e,r),s=i;return zct.ParseTreeWalker.DEFAULT.walk(s,r.root),i.annotation}bT.walkForModelAnnotation=Wct;var TT={};Object.defineProperty(TT,"__esModule",{value:!0}),TT.walkForTablePath=void 0;const z0e=$n,Vct=uc;class Yct{constructor(e,r){this.translator=e,this.tokens=r,this.pathInfos=[]}enterExploreTable(e){const r=(0,z0e.getId)(e.connectionId()),[i,s]=(0,z0e.getPlainString)(e.tablePath(),!0);i!==void 0&&this.pathInfos.push({connectionId:r,tablePath:i,range:this.translator.rangeFromContext(e)})}}function Kct(t,e,r){const i=new Yct(t,e),s=i;return Vct.ParseTreeWalker.DEFAULT.walk(s,r.root),i.pathInfos}TT.walkForTablePath=Kct;var lE={},RT={},Jct=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]}),Xct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Zct=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)&&Jct(e,t,r);return Xct(e,t),e};Object.defineProperty(RT,"__esModule",{value:!0}),RT.MalloyLexer=void 0;const eft=Sp(),tft=Ml(),nft=Xg(),rft=Fs,G0e=Zct(Sn);class se extends tft.Lexer{get vocabulary(){return se.VOCABULARY}constructor(e){super(e),this._interp=new nft.LexerATNSimulator(se._ATN,this)}get grammarFileName(){return"MalloyLexer.g4"}get ruleNames(){return se.ruleNames}get serializedATN(){return se._serializedATN}get channelNames(){return se.channelNames}get modeNames(){return se.modeNames}static get _ATN(){return se.__ATN||(se.__ATN=new eft.ATNDeserializer().deserialize(G0e.toCharArray(se._serializedATN))),se.__ATN}}RT.MalloyLexer=se,se.ACCEPT=1,se.AGGREGATE=2,se.CALCULATE=3,se.CALCULATION=4,se.CONNECTION=5,se.DECLARE=6,se.DIMENSION=7,se.EXCEPT=8,se.EXTENDQ=9,se.GROUP_BY=10,se.HAVING=11,se.INDEX=12,se.INTERNAL=13,se.JOIN_CROSS=14,se.JOIN_ONE=15,se.JOIN_MANY=16,se.LIMIT=17,se.MEASURE=18,se.NEST=19,se.ORDER_BY=20,se.PARTITION_BY=21,se.PRIMARY_KEY=22,se.PRIVATE=23,se.PROJECT=24,se.PUBLIC=25,se.QUERY=26,se.RENAME=27,se.RUN=28,se.SAMPLE=29,se.SELECT=30,se.SOURCE=31,se.TOP=32,se.WHERE=33,se.VIEW=34,se.TIMEZONE=35,se.ALL=36,se.AND=37,se.AS=38,se.ASC=39,se.AVG=40,se.BOOLEAN=41,se.BY=42,se.CASE=43,se.CAST=44,se.CONDITION=45,se.COUNT=46,se.COMPOSE=47,se.DATE=48,se.DAY=49,se.DESC=50,se.DISTINCT=51,se.ELSE=52,se.END=53,se.EXCLUDE=54,se.EXTEND=55,se.FALSE=56,se.FILTER=57,se.FULL=58,se.FOR=59,se.FROM=60,se.HAS=61,se.HOUR=62,se.IMPORT=63,se.INCLUDE=64,se.INNER=65,se.IS=66,se.IN=67,se.INTERNAL_KW=68,se.JSON=69,se.LAST=70,se.LEFT=71,se.LIKE=72,se.MAX=73,se.MIN=74,se.MINUTE=75,se.MONTH=76,se.NOT=77,se.NOW=78,se.NULL=79,se.NUMBER=80,se.ON=81,se.OR=82,se.PICK=83,se.PRIVATE_KW=84,se.PUBLIC_KW=85,se.QUARTER=86,se.RIGHT=87,se.SECOND=88,se.STRING=89,se.SOURCE_KW=90,se.SUM=91,se.SQL=92,se.TABLE=93,se.THEN=94,se.THIS=95,se.TIMESTAMP=96,se.TO=97,se.TRUE=98,se.TURTLE=99,se.WEEK=100,se.WHEN=101,se.WITH=102,se.YEAR=103,se.UNGROUPED=104,se.HACKY_REGEX=105,se.RAW_SQ=106,se.RAW_DQ=107,se.SQ3_FILTER=108,se.SQ_FILTER=109,se.DQ3_FILTER=110,se.DQ_FILTER=111,se.BQ3_FILTER=112,se.BQ_FILTER=113,se.SQ_STRING=114,se.DQ_STRING=115,se.BQ_STRING=116,se.DOC_ANNOTATION=117,se.ANNOTATION=118,se.AMPER=119,se.ARROW=120,se.FAT_ARROW=121,se.OPAREN=122,se.CPAREN=123,se.OBRACK=124,se.CBRACK=125,se.OCURLY=126,se.CCURLY=127,se.DOUBLECOLON=128,se.TRIPLECOLON=129,se.EXCLAM=130,se.COLON=131,se.COMMA=132,se.DOT=133,se.LT=134,se.GT=135,se.EQ=136,se.NE=137,se.LTE=138,se.GTE=139,se.PLUS=140,se.MINUS=141,se.STAR=142,se.STARSTAR=143,se.SLASH=144,se.BAR=145,se.SEMI=146,se.NOT_MATCH=147,se.MATCH=148,se.PERCENT=149,se.DOUBLE_QMARK=150,se.QMARK=151,se.LITERAL_TIMESTAMP=152,se.LITERAL_HOUR=153,se.LITERAL_DAY=154,se.LITERAL_QUARTER=155,se.LITERAL_MONTH=156,se.LITERAL_WEEK=157,se.LITERAL_YEAR=158,se.IDENTIFIER=159,se.PERCENT_LITERAL=160,se.NUMERIC_LITERAL=161,se.INTEGER_LITERAL=162,se.BLOCK_COMMENT=163,se.COMMENT_TO_EOL=164,se.WHITE_SPACE=165,se.SQL_BEGIN=166,se.UNWATED_CHARS_TRAILING_NUMBERS=167,se.UNEXPECTED_CHAR=168,se.OPEN_CODE=169,se.SQL_END=170,se.SQL_MODE=1,se.channelNames=["DEFAULT_TOKEN_CHANNEL","HIDDEN"],se.modeNames=["DEFAULT_MODE","SQL_MODE"],se.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","FILTER","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","F_PREFIX","S_PREFIX","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","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","SQL_CHAR","OPEN_CODE","SQL_END"],se._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,void 0,`'"""'`],se._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","FILTER","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","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","OPEN_CODE","SQL_END"],se.VOCABULARY=new rft.VocabularyImpl(se._LITERAL_NAMES,se._SYMBOLIC_NAMES,[]),se._serializedATNSegments=4,se._serializedATNSegment0=`줝쪺֍꾺体؇쉁¬ފ\b\b     \x07 \x07\b \b 
1163
1163