@malloydata/render 0.0.123-dev240208001444 → 0.0.123-dev240209030627
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.
|
@@ -678,8 +678,8 @@ ${n} ${s}: [`,o.length>0&&(i+=`
|
|
|
678
678
|
`)+`
|
|
679
679
|
${n} `),i+="]")}return i}*walk(){for(let e of Object.keys(this.children)){let r=this.children[e];if(r instanceof t)yield r;else for(let n of r)yield n}}varInfo(){let e="";for(let[r,n]of Object.entries(this))r!=="elementType"&&(typeof n=="boolean"?e+=n?` ${r}`:` !${r}`:(typeof n=="string"||typeof n=="number")&&(e+=` ${r}=${n}`));return e}internalError(e){return this.log(`INTERNAL ERROR IN TRANSLATION: ${e}`),new Error(e)}needs(e){for(let r of this.walk()){let n=r.needs(e);if(n)return n}}inExperiment(e,r=!1){var n;let i=(n=this.translator())===null||n===void 0?void 0:n.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(r||this.log(`Experimental flag '${e}' is not set, feature not available`),!1)}};$n.MalloyElement=Cp;var uY=class extends Cp{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}};$n.Unimplemented=uY;var KC=class extends Cp{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}};$n.ModelEntryReference=KC;var lY=class extends Cp{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}};$n.ExperimentalExperiment=lY;function e3e(t){return t.execute!==void 0}$n.isDocStatement=e3e;function ZJe(t){return t instanceof XC||e3e(t)}$n.isDocStatementOrDocStatementList=ZJe;var lL=class extends Cp{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(let r of this.elements){let n=r.needs(e);if(n)return n}}};$n.ListOf=lL;var XC=class t extends lL{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=Zge.extendNoteMethod,this.noteCursor=0}executeList(e){for(;this.execCursor<this.elements.length;){let r=this.elements[this.execCursor];if(this.noteCursor===this.execCursor&&(this.note&&(0,Zge.isNoteable)(r)&&r.extendNote(this.note),this.noteCursor+=1),r instanceof t){let n=r.executeList(e);if(n)return n}else{let n=r.needs(e);if(n)return n;r.execute(e)}this.execCursor+=1}}};$n.DocStatementList=XC;var eZe="5a79a191-06bc-43cf-9b12-58741cd82970";function t3e(t){let e=t.inherits?t3e(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 tZe(t){let e=t3e(t).join("");return(0,JJe.v5)(e,eZe)}var JC=class extends Cp{constructor(e){super(),this.elementType="document",this.globalNameSpace=new XJe.GlobalNameSpace,this.documentModel={},this.queryList=[],this.sqlBlocks=[],this.didInitModel=!1,this.annotation={},this.experiments=new KJe.Tag({}),this.modelAnnotationTodoList=[],this.statements=new XC(e),this.has({statements:e})}initModelDef(e){if(!this.didInitModel){if(this.documentModel={},this.queryList=[],this.sqlBlocks=[],e){e.annotation&&(this.annotation.inherits=e.annotation);for(let[r,n]of Object.entries(e.contents)){let i=structuredClone(n);if(i.type==="struct"||i.type==="query"||i.type==="function"){let s=e.exports.includes(r);this.setEntry(r,{entry:i,exported:s})}}}this.didInitModel=!0}}compile(){let e=this.statements.executeList(this),r=this.modelDef();if(e===void 0){for(let i of this.queryList)i.modelAnnotation===void 0&&r.annotation&&(i.modelAnnotation=r.annotation);for(let i of this.sqlBlocks)i.modelAnnotation===void 0&&r.annotation&&(i.modelAnnotation=r.annotation)}if(r.annotation)for(let i of this.modelAnnotationTodoList)i.modelAnnotation||(i.modelAnnotation=r.annotation);return{modelDef:r,queryList:this.queryList,sqlBlocks:this.sqlBlocks,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()){let e={...this.annotation,id:""};return e.id=tZe(e),e}}modelDef(){let e={name:"",exports:[],contents:{}};this.hasAnnotation()&&(e.annotation=this.currentModelAnnotation());for(let r in this.documentModel){let n=this.documentModel[r].entry;if(n.type==="struct"||n.type==="query"){this.documentModel[r].exported&&e.exports.push(r);let i=structuredClone(n);i.modelAnnotation===void 0&&e.annotation&&(i.modelAnnotation=e.annotation),e.contents[r]=i}}return e}defineSQL(e,r){let n={...e,as:`$${this.sqlBlocks.length}`,declaredSQLBlock:!0};if(r){if(this.getEntry(r))return!1;n.as=r,this.setEntry(r,{entry:n})}return this.sqlBlocks.push(n),!0}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.log(`Cannot redefine '${e}', which is in global namespace`),this.documentModel[e]=r}};$n.Document=JC});var cL=v(yS=>{"use strict";Object.defineProperty(yS,"__esModule",{value:!0});yS.canMakeEntry=yS.SpaceEntry=void 0;var cY=class{};yS.SpaceEntry=cY;function rZe(t){return"makeEntry"in t}yS.canMakeEntry=rZe});var la=v(fL=>{"use strict";Object.defineProperty(fL,"__esModule",{value:!0});fL.SpaceField=void 0;var nZe=Ke(),iZe=cL(),fY=class extends iZe.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){let r={dataType:e.type,expressionType:"scalar",evalSpace:"input"};return(0,nZe.isFieldTypeDef)(e)&&e.expressionType&&(r.expressionType=e.expressionType),r.dataType==="unsupported"&&e.type==="unsupported"&&e.rawType&&(r.rawType=e.rawType),r}getQueryFieldDef(e){}fieldDef(){}};fL.SpaceField=fY});var dL=v(xL=>{"use strict";Object.defineProperty(xL,"__esModule",{value:!0});xL.ViewField=void 0;var sZe=la(),xY=class extends sZe.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){return{dataType:"turtle",expressionType:"scalar",evalSpace:"input"}}};xL.ViewField=xY});var r3e=v(hL=>{"use strict";Object.defineProperty(hL,"__esModule",{value:!0});hL.ASTViewField=void 0;var oZe=dL(),dY=class extends oZe.ViewField{constructor(e,r,n){super(e),this.view=r,this.name=n}getQueryFieldDef(e){return this.view.getFieldDef(e)}fieldDef(){return this.view.getFieldDef(this.inSpace)}};hL.ASTViewField=dY});var pY=v(pL=>{"use strict";Object.defineProperty(pL,"__esModule",{value:!0});pL.ViewFieldDeclaration=void 0;var aZe=mt(),uZe=Wc(),lZe=J9(),cZe=r3e(),hY=class extends aZe.MalloyElement{constructor(e,r){super({view:r}),this.name=e,this.view=r,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=uZe.extendNoteMethod}makeEntry(e){let r=new cZe.ASTViewField(e,this,this.name);e.newEntry(this.name,this,r)}getFieldDef(e){let{pipeline:r,annotation:n}=this.view.pipelineComp(e),i=(0,lZe.detectAndRemovePartialStages)(r,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:n},location:this.location}}};pL.ViewFieldDeclaration=hY});var Ii=v(ES=>{"use strict";Object.defineProperty(ES,"__esModule",{value:!0});ES.LegalRefinementStage=ES.QueryClass=void 0;var n3e;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(n3e||(ES.QueryClass=n3e={}));var i3e;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(i3e||(ES.LegalRefinementStage=i3e={}))});var gY=v(mL=>{"use strict";Object.defineProperty(mL,"__esModule",{value:!0});mL.NestFieldDeclaration=void 0;var fZe=J9(),xZe=pY(),s3e=Ii(),mY=class extends xZe.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=s3e.LegalRefinementStage.Single,this.forceQueryClass=s3e.QueryClass.Grouping}queryExecute(e){e.resultFS.pushFields(this)}getFieldDef(e){if(e.isQueryFieldSpace()){let{pipeline:r,annotation:n}=this.view.pipelineComp(e,e.outputSpace()),i=(0,fZe.detectAndRemovePartialStages)(r,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:n},location:this.location}}throw this.internalError("Unexpected namespace for nest")}};mL.NestFieldDeclaration=mY});var ca=v(gL=>{"use strict";Object.defineProperty(gL,"__esModule",{value:!0});gL.ErrorFactory=void 0;var o3e={type:"struct",name:"~malformed~",dialect:"~malformed~",structSource:{type:"table",tablePath:"//undefined_error_table_path"},structRelationship:{type:"basetable",connectionName:"//undefined_error_connection"},fields:[]},yY=class t{static get structDef(){return{...o3e}}static isErrorStructDef(e){return e.name.includes(o3e.name)}static get query(){return{structRef:t.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}};gL.ErrorFactory=yY});var AY=v(yL=>{"use strict";Object.defineProperty(yL,"__esModule",{value:!0});yL.HasParameter=void 0;var dZe=Ke(),hZe=mt(),EY=class extends hZe.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,this.isCondition=e.isCondition,e.type&&(0,dZe.isCastType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default}))}parameter(){var e,r;let n=this.name,i=this.type||"string";if(this.isCondition){let o=((e=this.default)===null||e===void 0?void 0:e.constantCondition(i).value)||null;return{type:i,name:n,condition:o}}return{value:((r=this.default)===null||r===void 0?void 0:r.constantValue().value)||null,type:i,name:this.name,constant:!1}}};yL.HasParameter=EY});var u3e=v(AS=>{"use strict";Object.defineProperty(AS,"__esModule",{value:!0});AS.DefineSourceList=AS.DefineSource=void 0;var pZe=ca(),mZe=AY(),a3e=mt(),gZe=Wc(),SY=class extends a3e.MalloyElement{constructor(e,r,n,i){if(super(),this.name=e,this.sourceExpr=r,this.exported=n,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=gZe.extendNoteMethod,r&&this.has({sourceExpr:r}),i){this.parameters=[];for(let s of i)s instanceof mZe.HasParameter?this.parameters.push(s):this.log(`Unexpected element type in define statement: ${s.elementType}`);this.has({parameters:this.parameters})}}execute(e){var r;if(e.modelEntry(this.name))this.log(`Cannot redefine '${this.name}'`);else{let n=(r=this.sourceExpr)===null||r===void 0?void 0:r.getSource();if(n===void 0)return;let i=n.withParameters(this.parameters);if(pZe.ErrorFactory.isErrorStructDef(i))return;let s={...i,as:this.name,location:this.location};this.note&&(s.annotation=i.annotation?{...this.note,inherits:i.annotation}:this.note),e.setEntry(this.name,{entry:s,exported:this.exported})}}};AS.DefineSource=SY;var vY=class extends a3e.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}};AS.DefineSourceList=vY});var c3e=v(SS=>{"use strict";Object.defineProperty(SS,"__esModule",{value:!0});SS.DefineQueryList=SS.DefineQuery=void 0;var l3e=mt(),yZe=Wc(),_Y=class extends l3e.MalloyElement{constructor(e,r){super({queryExpr:r}),this.name=e,this.queryExpr=r,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=yZe.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.log(`'${this.name}' is already defined, cannot redefine`);return}let n=this.queryExpr.getQuery();if(!n){this.queryExpr.sqLog("Cannot define a query from this expression");return}let i={...n.query(),type:"query",name:this.name,location:this.location};this.note&&(i.annotation=i.annotation?{...this.note,inherits:i.annotation}:this.note),e.setEntry(this.name,{entry:i,exported:!0})}};SS.DefineQuery=_Y;var bY=class extends l3e.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}};SS.DefineQueryList=bY});var Px=v(EL=>{"use strict";Object.defineProperty(EL,"__esModule",{value:!0});EL.Source=void 0;var EZe=mt(),TY=class extends EZe.MalloyElement{structRef(){return this.structDef()}withParameters(e){let r=this.structDef();if(e){let n={...r.parameters||{}};for(let i of e){let s=i.parameter();n[s.name]=s}return{...r,parameters:n}}return r}};EL.Source=TY});var AL=v(vS=>{"use strict";Object.defineProperty(vS,"__esModule",{value:!0});vS.mergeFields=vS.nameFromDef=void 0;function CY(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}vS.nameFromDef=CY;function AZe(t,e){if(t===void 0)return e;let r=new Set(e.map(i=>CY(i))),n=t.filter(i=>!r.has(CY(i)));return n.push(...e),n}vS.mergeFields=AZe});var SL=v(Rp=>{"use strict";Object.defineProperty(Rp,"__esModule",{value:!0});Rp.DefinedParameter=Rp.AbstractParameter=Rp.SpaceParam=void 0;var SZe=cL(),ZC=class extends SZe.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}};Rp.SpaceParam=ZC;var RY=class extends ZC{constructor(e){super(),this.astParam=e}parameter(){return this.astParam.parameter()}typeDesc(){return{dataType:this.astParam.type||"error",expressionType:"scalar",evalSpace:"input"}}};Rp.AbstractParameter=RY;var OY=class extends ZC{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){return{dataType:this.paramDef.type,expressionType:"scalar",evalSpace:"input"}}};Rp.DefinedParameter=OY});var e5=v(vL=>{"use strict";Object.defineProperty(vL,"__esModule",{value:!0});vL.StructSpaceFieldBase=void 0;var vZe=la(),DY=class extends vZe.SpaceField{constructor(e){super(),this.sourceDef=e}get structRelationship(){return this.sourceDef.structRelationship}fieldDef(){return this.sourceDef}typeDesc(){return{dataType:"struct",expressionType:"scalar",evalSpace:"input"}}};vL.StructSpaceFieldBase=DY});var FY=v(_L=>{"use strict";Object.defineProperty(_L,"__esModule",{value:!0});_L.ColumnSpaceField=void 0;var _Ze=la(),NY=class extends _Ze.SpaceField{constructor(e){super(),this.haveFieldDef=e}fieldDef(){return this.haveFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.haveFieldDef)}};_L.ColumnSpaceField=NY});var f3e=v(bL=>{"use strict";Object.defineProperty(bL,"__esModule",{value:!0});bL.IRViewField=void 0;var bZe=dL(),wY=class extends bZe.ViewField{constructor(e,r){super(e),this.turtleDef=r,this.haveFieldDef=r}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}};bL.IRViewField=wY});var tl=v(_S=>{"use strict";Object.defineProperty(_S,"__esModule",{value:!0});_S.StructSpaceField=_S.StaticSpace=void 0;var TZe=vF(),CZe=Ke(),RZe=SL(),OZe=la(),TL=e5(),DZe=FY(),NZe=f3e(),CL=class{constructor(e){this.type="fieldSpace",this.fromStruct=e}dialectObj(){try{return(0,TZe.getDialect)(this.fromStruct.dialect)}catch{return}}defToSpaceField(e){return e.type==="struct"?new RL(e):(0,CZe.isTurtleDef)(e)?new NZe.IRViewField(this,e):new DZe.ColumnSpaceField(e)}get map(){if(this.memoMap===void 0){this.memoMap={};for(let e of this.fromStruct.fields){let r=e.as||e.name;this.memoMap[r]=this.defToSpaceField(e)}if(this.fromStruct.parameters)for(let[e,r]of Object.entries(this.fromStruct.parameters)){if(this.memoMap[e])throw new Error(`In struct '${this.fromStruct.as||this.fromStruct.name}': : Field and parameter name conflict '${e}`);this.memoMap[e]=new RZe.DefinedParameter(r)}}return this.memoMap}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(){return{...this.fromStruct,fields:[]}}lookup(e){let r=e[0],n=e.slice(1),i=this.entry(r.refString);if(!i)return{error:`'${r}' is not defined`,found:i};if(i instanceof OZe.SpaceField){let o=i.fieldDef();o&&r.addReference({type:i instanceof TL.StructSpaceFieldBase?"joinReference":"fieldReference",definition:o,location:r.location,text:r.refString})}let s=i instanceof TL.StructSpaceFieldBase?[{name:r.refString,structRelationship:i.structRelationship}]:[];if(n.length){if(i instanceof TL.StructSpaceFieldBase){let o=i.fieldSpace.lookup(n);return o.found?{...o,relationship:[...s,...o.relationship]}:o}return{error:`'${r}' cannot contain a '${n[0]}'`,found:void 0}}return{found:i,error:void 0,relationship:s,isOutputField:!1}}isQueryFieldSpace(){return!1}};_S.StaticSpace=CL;var RL=class extends TL.StructSpaceFieldBase{constructor(e){super(e)}get fieldSpace(){return new CL(this.sourceDef)}};_S.StructSpaceField=RL});var IY=v(OL=>{"use strict";Object.defineProperty(OL,"__esModule",{value:!0});OL.JoinSpaceField=void 0;var FZe=tl(),LY=class extends FZe.StructSpaceField{constructor(e){super(e.structDef()),this.join=e}};OL.JoinSpaceField=LY});var PY=v(DL=>{"use strict";Object.defineProperty(DL,"__esModule",{value:!0});DL.SpaceSeed=void 0;var wZe=tl();function x3e(t){return t.type==="fieldSpace"}var MY=class{constructor(e){this.sourceSpec=e,this.spaceSpec=e}get structDef(){return x3e(this.spaceSpec)?(this.asStruct||(this.asStruct=this.spaceSpec.structDef()),this.asStruct):this.spaceSpec}get fieldSpace(){return x3e(this.spaceSpec)?this.spaceSpec:(this.asFS||(this.asFS=new wZe.StaticSpace(this.spaceSpec)),this.asFS)}};DL.SpaceSeed=MY});var h3e=v(NL=>{"use strict";Object.defineProperty(NL,"__esModule",{value:!0});NL.DynamicSpace=void 0;var LZe=AL(),IZe=ca(),MZe=la(),PZe=IY(),kZe=dL(),d3e=SL(),BZe=PY(),qZe=tl(),UZe=e5(),kY=class extends qZe.StaticSpace{constructor(e){let r=new BZe.SpaceSeed(e);super(structuredClone(r.structDef)),this.completions=[],this.complete=!1,this.final=void 0,this.source=r}isComplete(){this.complete=!0}setEntry(e,r){if(this.final)throw new Error("Space already final");super.setEntry(e,r)}addParameters(e){for(let r of e)this.setEntry(r.name,new d3e.AbstractParameter(r));return this}newEntry(e,r,n){if(this.entry(e)){r.log(`Cannot redefine '${e}'`);return}this.setEntry(e,n)}renameEntry(e,r,n){this.dropEntry(e),this.setEntry(r,n)}addFieldDef(e){this.setEntry((0,LZe.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){let e=this.fromStruct.parameters||{};if(this.final===void 0){this.final={...this.fromStruct,fields:[]};let r=[],n=[],i=[],s=[];for(let[a,u]of this.entries())u instanceof UZe.StructSpaceFieldBase?n.push([a,u]):u instanceof kZe.ViewField?i.push([a,u]):u instanceof MZe.SpaceField?r.push([a,u]):u instanceof d3e.SpaceParam&&(e[a]=u.parameter());let o=[...r,...n,...i];for(let[,a]of o)if(a instanceof PZe.JoinSpaceField){let u=a.join.structDef();IZe.ErrorFactory.isErrorStructDef(u)||(this.final.fields.push(u),s.push([a.join,u]))}else{let u=a.fieldDef();u&&this.final.fields.push(u)}Object.entries(e).length>0&&(this.final.parameters=e);for(let[a,u]of s)a.fixupJoinOn(this,u)}return this.newTimezone&&(this.final.queryTimezone=this.newTimezone),this.isComplete(),this.final}};NL.DynamicSpace=kY});var wL=v(FL=>{"use strict";Object.defineProperty(FL,"__esModule",{value:!0});FL.RefinedSpace=void 0;var $Ze=h3e(),jZe=cL(),BY=class t extends $Ze.DynamicSpace{static filteredFrom(e,r){let n=new t(e);if(r){let i=r.refs.list,s=n.entries();n.dropEntries();for(let[o,a]of s){let u=!!i.find(c=>c.refString===o),l=r.edit==="accept";u===l&&n.setEntry(o,a)}}return n}pushFields(...e){for(let r of e)(0,jZe.canMakeEntry)(r)?r.makeEntry(this):r.log(`Internal error, ${r.elementType} not expected in this context`)}};FL.RefinedSpace=BY});var n0=v(LL=>{"use strict";Object.defineProperty(LL,"__esModule",{value:!0});LL.DefinitionList=void 0;var HZe=mt(),p3e=Wc(),qY=class extends HZe.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,p3e.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(let e of this.elements)(0,p3e.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}};LL.DefinitionList=qY});var bS=v(IL=>{"use strict";Object.defineProperty(IL,"__esModule",{value:!0});IL.DeclareFields=void 0;var zZe=n0(),GZe=Ii(),UY=class extends zZe.DefinitionList{constructor(e){super(e),this.elementType="declareFields",this.queryRefinementStage=GZe.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(let r of this.list)e.inputFS.extendSource(r)}};IL.DeclareFields=UY});var hs=v(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});Op.nullsafeNot=Op.compressExpr=Op.compose=void 0;var QZe=Ke();function m3e(t){return t.length>1?["(",...t,")"]:t.length===0?["__MISSING_VALUE__"]:t}function VZe(t,e,r){let n=e.match(/^[A-Za-z]/),i=t.length===1&&n?" ":"",s=r.length===1&&n?" ":"",o=i+e+s;return[...m3e(t),o,...m3e(r)]}Op.compose=VZe;function WZe(t){let e=[],r;for(let n of t.flat())typeof n=="string"?r=r?r+n:n:(r&&(e.push(r),r=void 0),e.push(n));return r&&e.push(r),e}Op.compressExpr=WZe;function YZe(t,e){return e===void 0||e==="!="||e==="!~"?(0,QZe.mkExpr)`COALESCE(NOT(${t}),FALSE)`:t}Op.nullsafeNot=YZe});var Ym=v(TS=>{"use strict";Object.defineProperty(TS,"__esModule",{value:!0});TS.Filter=TS.FilterElement=void 0;var g3e=Ke(),KZe=hs(),y3e=mt(),$Y=Ii(),jY=class extends y3e.MalloyElement{constructor(e,r){super({expr:e}),this.expr=e,this.exprSrc=r,this.elementType="filterElement"}filterExpression(e){let r=this.expr.getExpression(e);return r.dataType!=="boolean"?(this.expr.log("Filter expression must have boolean value"),{code:this.exprSrc,expression:["_FILTER_MUST_RETURN_BOOLEAN_"],expressionType:"scalar"}):{code:this.exprSrc,expression:(0,KZe.compressExpr)(r.value),expressionType:r.expressionType}}};TS.FilterElement=jY;var HY=class extends y3e.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=$Y.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?$Y.LegalRefinementStage.Tail:$Y.LegalRefinementStage.Head}getFilterList(e){let r=[];for(let n of this.list){let i=n.filterExpression(e);if(this.havingClause!==void 0){let s=(0,g3e.expressionIsAggregate)(i.expressionType),o=(0,g3e.expressionIsAnalytic)(i.expressionType);if(this.havingClause){if(o){n.log("Analytic expressions are not allowed in `having:`");continue}}else if(o){n.log("Analytic expressions are not allowed in `where:`");continue}else s&&n.log("Aggregate expressions are not allowed in `where:`; use `having:`")}r.push(i)}return r}};TS.Filter=HY});var CS=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.Joins=Yc.ExpressionJoin=Yc.KeyJoin=Yc.Join=void 0;var XZe=Ke(),JZe=hs(),ZZe=IY(),eet=n0(),tet=mt(),ret=Wc(),net=Ii(),E3e=ca(),t5=class extends tet.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=ret.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new ZZe.JoinSpaceField(this))}getStructDefFromExpr(){let e=this.sourceExpr.getSource();return e?e.structDef():(this.sourceExpr.sqLog("Cannot great a source to join from"),E3e.ErrorFactory.structDef)}};Yc.Join=t5;var zY=class extends t5{constructor(e,r,n){super({name:e,sourceExpr:r,keyExpr:n}),this.name=e,this.sourceExpr=r,this.keyExpr=n,this.elementType="joinOnKey"}structDef(){var e;let r=this.getStructDefFromExpr(),n={...r,structRelationship:{type:"one",matrixOperation:"left",onExpression:["('join fixup'='not done yet')"]},location:this.location};return r.structSource.type==="query"?n.name=this.name.refString:n.as=this.name.refString,this.note&&(n.annotation=this.note),(e=this.document())===null||e===void 0||e.rememberToAddModelAnnotations(n),n}fixupJoinOn(e,r){let n=this.keyExpr.getExpression(e);if(r.primaryKey){let i=r.fields.find(s=>(s.as||s.name)===r.primaryKey);if(i)if(i.type===n.dataType){r.structRelationship={type:"one",matrixOperation:"left",onExpression:[{type:"field",path:[this.name.refString,r.primaryKey]},"=",...n.value]};return}else this.log(`join_one: with type mismatch with primary key: ${n.dataType}/${i.type}`);else this.log(`join_one: Primary key '${i}' not found in source`)}else this.log("join_one: Cannot use with unless source has a primary key")}};Yc.KeyJoin=zY;var GY=class extends t5{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;let n=this.expr.getExpression(e);if(n.dataType!=="boolean"){this.log("join conditions must be boolean expressions");return}let i=r.structRelationship;(0,XZe.isJoinOn)(i)&&(i.onExpression=(0,JZe.compressExpr)(n.value))}structDef(){var e;let r=this.sourceExpr.getSource();if(!r)return this.sourceExpr.sqLog("Cannot create a source to join from"),E3e.ErrorFactory.structDef;let n=r.structDef(),i="left";this.inExperiment("join_types",!0)&&(i=this.matrixOperation);let s={...n,structRelationship:{type:this.joinType,matrixOperation:i},location:this.location};return n.structSource.type==="query"?(s.name=this.name.refString,delete s.as):s.as=this.name.refString,this.note&&(s.annotation=this.note),(e=this.document())===null||e===void 0||e.rememberToAddModelAnnotations(s),s}};Yc.ExpressionJoin=GY;var QY=class extends eet.DefinitionList{constructor(e){super(e),this.elementType="joinList",this.forceQueryClass=void 0,this.queryRefinementStage=net.LegalRefinementStage.Single}queryExecute(e){for(let r of this.list)e.inputFS.extendSource(r)}};Yc.Joins=QY});var PL=v(ML=>{"use strict";Object.defineProperty(ML,"__esModule",{value:!0});ML.FieldListEdit=void 0;var iet=mt(),VY=class extends iet.MalloyElement{constructor(e,r){super({refs:r}),this.edit=e,this.refs=r,this.elementType="fieldListEdit"}};ML.FieldListEdit=VY});var BL=v(kL=>{"use strict";Object.defineProperty(kL,"__esModule",{value:!0});kL.PrimaryKey=void 0;var set=mt(),WY=class extends set.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}};kL.PrimaryKey=WY});var UL=v(qL=>{"use strict";Object.defineProperty(qL,"__esModule",{value:!0});qL.Views=void 0;var oet=n0(),YY=class extends oet.DefinitionList{constructor(){super(...arguments),this.elementType="turtleDefList"}};qL.Views=YY});var jL=v($L=>{"use strict";Object.defineProperty($L,"__esModule",{value:!0});$L.TimezoneStatement=void 0;var aet=mt(),KY=class extends aet.MalloyElement{constructor(e){super(),this.tz=e,this.elementType="timezone",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}get isValid(){try{return Intl.DateTimeFormat(void 0,{timeZone:this.tz}),!0}catch{return!1}}queryExecute(e){e.resultFS.setTimezone(this.tz)}};$L.TimezoneStatement=KY});var zL=v(RS=>{"use strict";Object.defineProperty(RS,"__esModule",{value:!0});RS.ModelAnnotation=RS.ObjectAnnotation=void 0;var uet=Wm(),cet=mt(),HL=class extends cet.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}};RS.ObjectAnnotation=HL;var XY=class extends HL{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,r){let n=uet.Tag.annotationToTag({notes:this.notes},{prefix:/^##! /,extending:e});return n.log.forEach(i=>r.log(i)),n.tag}execute(e){e.annotation.notes===void 0&&(e.annotation.notes=[]),e.annotation.notes.push(...this.notes)}};RS.ModelAnnotation=XY});var A3e=v(GL=>{"use strict";Object.defineProperty(GL,"__esModule",{value:!0});GL.RenameSpaceField=void 0;var fet=la(),JY=class extends fet.SpaceField{constructor(e,r,n){super(),this.otherField=e,this.newName=r,this.location=n}fieldDef(){let e=this.otherField.fieldDef();if(e!==void 0)return{...e,as:this.newName,location:this.location}}typeDesc(){return this.otherField.typeDesc()}};GL.RenameSpaceField=JY});var QL=v(OS=>{"use strict";Object.defineProperty(OS,"__esModule",{value:!0});OS.Renames=OS.RenameField=void 0;var xet=A3e(),S3e=mt(),det=la(),ZY=class extends S3e.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.log("Can't rename field to itself");return}let r=this.oldName.getField(e);r.found?r.found instanceof det.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new xet.RenameSpaceField(r.found,this.newName,this.location)):this.log(`'${this.oldName}' cannot be renamed`):this.log(`Can't rename '${this.oldName}', no such field`)}};OS.RenameField=ZY;var eK=class extends S3e.ListOf{constructor(){super(...arguments),this.elementType="renameFields"}};OS.Renames=eK});var rK=v(VL=>{"use strict";Object.defineProperty(VL,"__esModule",{value:!0});VL.RefinedSource=void 0;var het=Ke(),pet=wL(),met=bS(),get=Ym(),yet=CS(),Eet=PL(),Aet=BL(),vet=UL(),_et=Px(),bet=jL(),Tet=zL(),Cet=QL(),tK=class extends _et.Source{constructor(e,r){super({source:e,refinement:r}),this.source=e,this.refinement=r,this.elementType="refinedSource"}structDef(){return this.withParameters([])}withParameters(e){var r;let n,i,s=[],o=[],a;for(let d of this.refinement.list){if(d instanceof Tet.ObjectAnnotation)continue;let h=d;d instanceof Aet.PrimaryKey?(n&&(n.log("Primary key already defined"),d.log("Primary key redefined")),n=d):d instanceof Eet.FieldListEdit?(i&&(i.log("Too many accept/except statements"),d.log("Too many accept/except statements")),i=d):d instanceof met.DeclareFields||d instanceof yet.Joins||d instanceof vet.Views||d instanceof Cet.Renames?s.push(...d.list):d instanceof get.Filter?o.push(d):d instanceof bet.TimezoneStatement?a=d.tz:h.log(`Unexpected source property: '${h.elementType}'`)}let u=structuredClone(this.source.structDef());n&&(u.primaryKey=n.field.name);let l=pet.RefinedSpace.filteredFrom(u,i);if(a&&l.setTimezone(a),l.pushFields(...s),e&&l.addParameters(e),n){let d=n.field.getField(l);d.error&&n.log(d.error)}let c=l.structDef(),f=c.filterList||[],x=!1;for(let d of o)for(let h of d.list){let p=h.filterExpression(l);(0,het.expressionIsCalculation)(p.expressionType)?h.log("Can't use aggregate computations in top level filters"):(f.push(p),x=!0)}return x?{...c,filterList:f}:((r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(c),c)}};VL.RefinedSource=tK});var Dp=v(WL=>{"use strict";Object.defineProperty(WL,"__esModule",{value:!0});WL.SourceQueryElement=void 0;var Ret=mt(),nK=class t extends Ret.MalloyElement{constructor(){super(...arguments),this.errored=!1}getSource(){}getQuery(){}isSource(){return!1}sqLog(e){this.isErrorFree()&&this.log(e),this.errored=!0}isErrorFree(){if(this.errored)return!1;let e=!0;for(let r of this.walk())if(r instanceof t&&r.errored){e=!1;break}return e}};WL.SourceQueryElement=nK});var r5=v(YL=>{"use strict";Object.defineProperty(YL,"__esModule",{value:!0});YL.QuerySource=void 0;var Oet=Px(),iK=class extends Oet.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}structDef(){var e;let r=this.query.queryComp(!1),n={...r.outputStruct,structSource:{type:"query",query:r.query}};return(e=this.document())===null||e===void 0||e.rememberToAddModelAnnotations(n),n}};YL.QuerySource=iK});var oK=v(KL=>{"use strict";Object.defineProperty(KL,"__esModule",{value:!0});KL.QueryBase=void 0;var Det=J9(),Net=mt(),sK=class extends Net.MalloyElement{query(){let e=this.queryComp(!0).query;return{...e,pipeline:(0,Det.detectAndRemovePartialStages)(e.pipeline,this)}}};KL.QueryBase=sK});var JL=v(XL=>{"use strict";Object.defineProperty(XL,"__esModule",{value:!0});XL.QueryArrow=void 0;var Fet=Ke(),wet=Px(),v3e=tl(),Let=oK(),aK=class extends Let.QueryBase{constructor(e,r){super({source:e,view:r}),this.source=e,this.view=r,this.elementType="arrow"}queryComp(e){let r,n,i;if(this.source instanceof wet.Source){let l=e?this.source.structRef():this.source.structDef();n={type:"query",structRef:l,pipeline:[],location:this.location},r=(0,Fet.refIsStructDef)(l)?l:this.source.structDef(),i=new v3e.StaticSpace(r)}else{let l=this.source.queryComp(e);n=l.query,r=l.outputStruct,i=new v3e.StaticSpace(l.outputStruct)}let{pipeline:s,annotation:o,outputStruct:a,name:u}=this.view.pipelineComp(i);return{query:{...n,name:u,annotation:o,pipeline:[...n.pipeline,...s]},outputStruct:a,inputStruct:r}}};XL.QueryArrow=aK});var _3e=v(ZL=>{"use strict";Object.defineProperty(ZL,"__esModule",{value:!0});ZL.SQArrow=void 0;var Iet=Dp(),Met=r5(),Pet=JL(),uK=class extends Iet.SourceQueryElement{constructor(e,r){super({applyTo:e,operation:r}),this.applyTo=e,this.operation=r,this.elementType="sq-arrow"}getQuery(){let e=this.applyTo.isSource()?this.applyTo.getSource():this.applyTo.getQuery();if(e===void 0){this.sqLog("Could not get LHS of arrow operation");return}let r=new Pet.QueryArrow(e,this.operation);return this.has({query:r}),r}getSource(){let e=this.getQuery();if(!e){this.sqLog("Couldn't comprehend query well enough to make a source");return}let r=new Met.QuerySource(e);return this.has({asSource:r}),r}};ZL.SQArrow=uK});var Km=v(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});Np.getStructFieldDef=Np.getFinalStruct=Np.opOutputStruct=void 0;var ket=Vd(),Bet=$G(),qet=Ke(),b3e=ca();function T3e(t,e,r){let n=b3e.ErrorFactory.isErrorStructDef(e);if((0,qet.isPartialSegment)(r)&&(r={...r,type:"reduce"}),!n)try{return Bet.Segment.nextStructDef(e,r)}catch(i){t.log(`INTERNAL ERROR model/Segment.nextStructDef: ${i.message}
|
|
680
680
|
QUERY: ${(0,ket.inspect)(r,{breakLength:72,depth:1/0})}`)}return{...b3e.ErrorFactory.structDef,dialect:e.dialect}}Np.opOutputStruct=T3e;function Uet(t,e,r){for(let n of r)e=T3e(t,e,n);return e}Np.getFinalStruct=Uet;function $et(t,e){return t.fields.find(r=>(r.as||r.name)===e)}Np.getStructFieldDef=$et});var tI=v(eI=>{"use strict";Object.defineProperty(eI,"__esModule",{value:!0});eI.QueryRefine=void 0;var jet=tl(),Het=Km(),zet=oK(),lK=class extends zet.QueryBase{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="query-refine"}queryComp(e){let r=this.base.queryComp(e),n=new jet.StaticSpace(r.inputStruct),i=this.refinement.refine(n,r.query.pipeline,void 0);return{query:{...r.query,pipeline:i},outputStruct:(0,Het.getFinalStruct)(this.refinement,r.inputStruct,i),inputStruct:r.inputStruct}}};eI.QueryRefine=lK});var DS=v(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.dateOffset=Mi.timestampOffset=Mi.timeResult=Mi.resolution=Mi.castDateToTimestamp=Mi.castTimestampToDate=Mi.castTo=Mi.timeOffset=void 0;var Get=Ke(),C3e=hs();function Qet(t,e,r,n,i){return[{type:"dialect",function:"delta",base:{valueType:t,value:e},op:r,delta:n,units:i}]}Mi.timeOffset=Qet;function Vet(t,e,r,n=!1){let i={type:"dialect",function:"cast",dstType:t,expr:e,safe:n};return(0,Get.isAtomicFieldType)(r)&&(i.srcType=r),[i]}Mi.castTo=Vet;function Wet(t,e=!1){return[{type:"dialect",function:"cast",dstType:"date",srcType:"timestamp",expr:t,safe:e}]}Mi.castTimestampToDate=Wet;function Yet(t,e=!1){return[{type:"dialect",function:"cast",dstType:"timestamp",srcType:"date",expr:t,safe:e}]}Mi.castDateToTimestamp=Yet;function Ket(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}Mi.resolution=Ket;function Xet(t,e){return e?{...t,timeframe:e}:t}Mi.timeResult=Xet;function Jet(t,e,r,n,i=!1){let s=["week","month","quarter","year"].includes(n),o=e==="+"?"_ADD":"_SUB",a=n.toUpperCase();if(s)return[`TIMESTAMP(DATETIME${o}(DATETIME(`,...t,"),INTERVAL ",...r,` ${a}))`];let u=i?["TIMESTAMP(",...t,")"]:t;return(0,C3e.compressExpr)([`TIMESTAMP${o}(`,...u,",INTERVAL ",...r,` ${a})`])}Mi.timestampOffset=Jet;function Zet(t,e,r,n){let i=e==="+"?"_ADD":"_SUB",s=n.toUpperCase();return(0,C3e.compressExpr)([`DATE${i}(`,...t,",INTERVAL ",...r,` ${s})`])}Mi.dateOffset=Zet});var n5=v(NS=>{"use strict";Object.defineProperty(NS,"__esModule",{value:!0});NS.NamedSource=NS.IsValueBlock=void 0;var rI=Ke(),ett=Px(),ttt=ca(),rtt=DS(),nI=mt(),iI=class extends nI.MalloyElement{constructor(e){super(),this.isMap=e,this.elementType="isValueBlock",this.has(e)}};NS.IsValueBlock=iI;var cK=class extends ett.Source{constructor(e,r={}){super(),this.ref=e,this.elementType="namedSource",r&&Object.keys(r).length>0&&(this.isBlock=new iI(r),this.has({parameterValues:this.isBlock})),e instanceof nI.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof nI.ModelEntryReference?this.ref.name:this.ref}structRef(){if(this.isBlock)return this.structDef();let e=this.modelEntry(this.ref);return e&&!e.exported?this.structDef():this.refName}modelStruct(){let e=this.modelEntry(this.ref),r=e?.entry;if(!r){let n=`Undefined source '${this.refName}'`;(this.ref instanceof nI.ModelEntryReference?this.ref:this).log(n);return}if(r.type==="query"){this.log(`Cannot construct a source from a query '${this.refName}'`);return}else if(r.type==="function"){this.log(`Cannot construct a source from a function '${this.refName}'`);return}else if(r.type==="connection"){this.log(`Cannot construct a source from a connection '${this.refName}'`);return}else if((0,rI.isSQLBlockStruct)(r)&&r.declaredSQLBlock){this.log(`Must use 'from_sql()' for sql source '${this.refName}'`);return}return{...r}}structDef(){var e,r;let n=this.modelStruct();if(!n){let o=ttt.ErrorFactory.structDef,a=`${this.refName}-undefined`;return o.name=o.name+a,o.dialect=o.dialect+a,o}let i={...n.parameters},s=((e=this.isBlock)===null||e===void 0?void 0:e.isMap)||{};for(let[o,a]of Object.entries(s)){let u=i[o];if(!u)this.log(`Value given for undeclared parameter '${o}`);else if((0,rI.isValueParameter)(u))if(u.constant)a.log(`Cannot override constant parameter ${o}`);else{let l=a.constantValue(),c=l.value;l.dataType!==u.type&&(0,rI.isCastType)(u.type)&&(c=(0,rtt.castTo)(u.type,l.value,l.dataType,!0)),u.value=c}else u.condition=a.constantCondition(u.type).value}for(let o in n.parameters)(0,rI.paramHasValue)(i[o])||this.log(`Value not provided for required parameter ${o}`);return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(n),n}};NS.NamedSource=cK});var R3e=v(sI=>{"use strict";Object.defineProperty(sI,"__esModule",{value:!0});sI.QueryHeadStruct=void 0;var ntt=Ke(),itt=Px(),stt=n5(),fK=class extends itt.Source{constructor(e){super(),this.fromRef=e,this.elementType="internalOnlyQueryHead"}structRef(){return this.fromRef}structDef(){if((0,ntt.refIsStructDef)(this.fromRef))return this.fromRef;let e=new stt.NamedSource(this.fromRef);return this.has({exploreReference:e}),e.structDef()}};sI.QueryHeadStruct=fK});var hK=v(oI=>{"use strict";Object.defineProperty(oI,"__esModule",{value:!0});oI.QueryReference=void 0;var xK=ca(),ott=mt(),att=R3e(),utt=Ke(),ltt=Km(),dK=class extends ott.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){let r=this.modelEntry(this.name),n=r?.entry,i=function(){return{inputStruct:xK.ErrorFactory.structDef,outputStruct:xK.ErrorFactory.structDef,query:xK.ErrorFactory.query}};if(!n)return this.log(`Reference to undefined query '${this.name.refString}'`),i();if(n.type==="query"){let s=new att.QueryHeadStruct(n.structRef);this.has({queryHead:s});let o=s.structDef(),a=(0,ltt.getFinalStruct)(this,o,n.pipeline);return{query:e||(0,utt.refIsStructDef)(n.structRef)?n:{...n,structRef:o},outputStruct:a,inputStruct:o}}return this.log(`Illegal reference to '${this.name}', query expected`),i()}query(){return this.queryComp(!0).query}};oI.QueryReference=dK});var mK=v(aI=>{"use strict";Object.defineProperty(aI,"__esModule",{value:!0});aI.SQReference=void 0;var ctt=Dp(),ftt=r5(),xtt=n5(),O3e=hK(),pK=class extends ctt.SourceQueryElement{constructor(e){super({ref:e}),this.ref=e,this.elementType="sq-reference"}getQuery(){let e=this.ref.getNamed();if(e)if(e.type==="query"){let r=new O3e.QueryReference(this.ref);return this.has({query:r}),r}else this.sqLog(`Illegal reference to '${e.as||e.name}', query expected`);else this.ref.log(`Reference to undefined object '${this.ref.refString}'`),this.errored=!0}isSource(){var e;return((e=this.ref.getNamed())===null||e===void 0?void 0:e.type)==="struct"}getSource(){if(this.asSource)return this.asSource;let e=this.ref.getNamed();if(!e){this.ref.log(`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){let r=new O3e.QueryReference(this.ref);this.asSource=new ftt.QuerySource(r)}else if(e.type==="struct")this.asSource=new xtt.NamedSource(this.ref);else{this.sqLog(`Expected '${this.ref.refString}' to be of type query or source, not '${e.type}'`);return}return this.has({asSource:this.asSource}),this.asSource}};aI.SQReference=pK});var D3e=v(uI=>{"use strict";Object.defineProperty(uI,"__esModule",{value:!0});uI.SQRefine=void 0;var dtt=Dp(),htt=r5(),ptt=tI(),mtt=mK(),gK=class extends dtt.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 mtt.SQReference?this.sqLog(`Cannot add view refinements to '${this.toRefine.ref.refString}' because it is a source`):this.sqLog("Cannot add view refinements to a source");return}let e=this.toRefine.getQuery();if(e){let r=new ptt.QueryRefine(e,this.refine);return this.has({query:r}),r}}getSource(){let e=this.getQuery();if(e){let r=new htt.QuerySource(e);return this.has({queryAsSource:r}),r}}};uI.SQRefine=gK});var EK=v(lI=>{"use strict";Object.defineProperty(lI,"__esModule",{value:!0});lI.QueryRaw=void 0;var gtt=Ke(),ytt=mt(),yK=class extends ytt.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){let r=e?this.source.structRef():this.source.structDef(),n=(0,gtt.refIsStructDef)(r)?r:this.source.structDef();return{query:{type:"query",structRef:r,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:n,inputStruct:n}}query(){return this.queryComp(!0).query}};lI.QueryRaw=yK});var AK=v(cI=>{"use strict";Object.defineProperty(cI,"__esModule",{value:!0});cI.makeSQLBlock=void 0;var Ett=Ke(),Att=jd();function Stt(t,e){let r={name:`md5:/${e||"$default"}//${vtt(t)}`,select:t};return e&&(r.connection=e),r}cI.makeSQLBlock=Stt;function vtt(t){let e=t.map(r=>(0,Ett.isSQLFragment)(r)?r.sql:JSON.stringify(r));return(0,Att.generateHash)(e.join(";"))}});var vK=v(xI=>{"use strict";Object.defineProperty(xI,"__esModule",{value:!0});xI.SQLSource=void 0;var _tt=AK(),btt=Px(),fI=ca(),SK=class extends btt.Source{constructor(e,r){super(),this.connectionName=e,this.select=r,this.elementType="sqlSource",this.connectionNameInvalid=!1,this.has({connectionName:e,select:r})}sqlBlock(){return this.requestBlock||(this.requestBlock=(0,_tt.makeSQLBlock)(this.select.sqlPhrases(),this.connectionName.refString)),this.requestBlock}structRef(){return this.structDef()}validateConnectionName(){var e;let r=this.modelEntry(this.connectionName),n=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(n,{entry:{type:"connection",name:n},exported:!0},!0);else if(r.entry.type!=="connection")return this.connectionName.log(`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var r;if(!this.validateConnectionName())return;let n=super.needs(e);if(n)return n;let i=this.sqlBlock(),s=(r=this.translator())===null||r===void 0?void 0:r.root.sqlQueryZone;if(!s){this.log("Cant't look up schema for sql block");return}if(s.reference(i.name,this.location),s.getEntry(i.name).status==="reference")return{compileSQL:i,partialModel:this.select.containsQueries?e.modelDef():void 0}}structDef(){var e;if(!this.validateConnectionName())return fI.ErrorFactory.structDef;let r=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!r)return this.log("Cant't look up schema for sql block"),fI.ErrorFactory.structDef;let n=this.sqlBlock();r.reference(n.name,this.location);let i=r.getEntry(n.name);if(i.status==="error"){let s=i.message.split(/\r?\n/);return this.select.log("Invalid SQL, "+s.join(`
|
|
681
|
-
`)),fI.ErrorFactory.structDef}else if(i.status==="present"){let s=this.select.location,o={...i.value,fields:i.value.fields.map(l=>({...l,location:s})),location:this.location},a=this.document(),u=a?.currentModelAnnotation();return u&&(o.modelAnnotation=u),o}else return this.log("`connection_name.sql(...)` can currently only be used in top level source/query definitions"),fI.ErrorFactory.structDef}};xI.SQLSource=SK});var N3e=v(dI=>{"use strict";Object.defineProperty(dI,"__esModule",{value:!0});dI.SQSource=void 0;var Ttt=Dp(),Ctt=EK(),Rtt=vK(),_K=class extends Ttt.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 Rtt.SQLSource){let e=new Ctt.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("This source cannot be used as a query")}};dI.SQSource=_K});var F3e=v(hI=>{"use strict";Object.defineProperty(hI,"__esModule",{value:!0});hI.SQExtend=void 0;var Ott=rK(),Dtt=Dp(),bK=class extends Dtt.SourceQueryElement{constructor(e,r){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;let e=this.sqSrc.getSource();if(e)return this.asSource=new Ott.RefinedSource(e,this.extend),this.has({asSource:this.asSource}),this.asSource;this.sqLog("Could not compute source to extend")}isSource(){return!0}};hI.SQExtend=bK});var pI=v(FS=>{"use strict";Object.defineProperty(FS,"__esModule",{value:!0});FS.isComparison=FS.Comparison=void 0;var TK;(function(t){t.Like="~",t.NotLike="!~",t.LessThan="<",t.LessThanOrEqualTo="<=",t.EqualTo="=",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.NotEqualTo="!="})(TK||(FS.Comparison=TK={}));function Ntt(t){return Object.values(TK).includes(t)}FS.isComparison=Ntt});var pn=v(mI=>{"use strict";Object.defineProperty(mI,"__esModule",{value:!0});mI.FT=void 0;var Ftt=lc();function Xm(t,e="scalar",r="constant"){return{dataType:t,expressionType:e,evalSpace:r}}var $s=class t{static in(e,r){return e?r.find(i=>t.eq(i,e))!==void 0:!1}static eq(e,r){return r!==void 0&&e.dataType===r.dataType&&e.expressionType===r.expressionType}static typeIn(e,r){return e?r.find(i=>t.typeEq(i,e))!==void 0:!1}static typeEq(e,r,n=!1,i=!0){let s=e.dataType===r.dataType,o=n&&(e.dataType==="null"||r.dataType==="null"),a=i&&(e.dataType==="error"||r.dataType==="error");return s||o||a}static inspect(...e){return e.map(n=>{if(n){let i=n.dataType;return(0,Ftt.expressionIsScalar)(n.expressionType)||(i=`${n.expressionType} ${i}`),i}return"undefined"}).join(",")}};mI.FT=$s;$s.nullT=Xm("null");$s.numberT=Xm("number");$s.stringT=Xm("string");$s.dateT=Xm("date");$s.timestampT=Xm("timestamp");$s.boolT=Xm("boolean");$s.anyAtomicT=[$s.numberT,$s.stringT,$s.dateT,$s.timestampT,$s.boolT];$s.aggregateBoolT=Xm("boolean","aggregate")});var yI=v(gI=>{"use strict";Object.defineProperty(gI,"__esModule",{value:!0});gI.isGranularResult=void 0;function wtt(t){return t.dataType==="date"||t.dataType==="timestamp"?t.timeframe!==void 0:!1}gI.isGranularResult=wtt});var js=v(EI=>{"use strict";Object.defineProperty(EI,"__esModule",{value:!0});EI.errorFor=void 0;function Ltt(t){return{dataType:"error",expressionType:"scalar",value:[`_ERROR_${t.replace(/ /g,"_")}`],evalSpace:"constant"}}EI.errorFor=Ltt});var w3e=v(wS=>{"use strict";Object.defineProperty(wS,"__esModule",{value:!0});wS.isEquality=wS.Equality=void 0;var CK;(function(t){t.Like="~",t.NotLike="!~",t.Equals="=",t.NotEquals="!="})(CK||(wS.Equality=CK={}));function Itt(t){return Object.values(CK).includes(t)}wS.isEquality=Itt});var ir=v(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.applyBinary=Kc.getMorphicValue=Kc.ExprDuration=Kc.ExpressionDef=void 0;var mn=Ke(),LS=js(),kx=hs(),Jm=pn(),AI=DS(),Mtt=pI(),Ptt=w3e(),M3e=yI(),ktt=mt(),OK=class extends Error{},SI=class extends ktt.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=Jm.FT.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.dataType!=="error"&&!Jm.FT.in(r,this.legalChildTypes)?(e.log(`'${this.elementType}' Can't use type ${Jm.FT.inspect(r)}`),!1):!0}apply(e,r,n){return B3e(e,n,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,mn.expressionIsAggregate)(e.expressionType)}};Kc.ExpressionDef=SI;var i5=class extends SI{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[Jm.FT.timestampT,Jm.FT.dateT]}apply(e,r,n){let i=n.getExpression(e);if(this.typeCheck(this,i),(0,mn.isTimeFieldType)(i.dataType)&&(r==="+"||r==="-")){let s=this.n.getExpression(e);if(!Jm.FT.typeEq(s,Jm.FT.numberT))return this.log(`Duration units needs number not '${s.dataType}`),(0,LS.errorFor)("illegal unit expression");let o;if((0,M3e.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.dataType==="timestamp"){let a=(0,AI.timeOffset)("timestamp",i.value,r,s.value,this.timeframe);return(0,AI.timeResult)({dataType:"timestamp",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:a},o)}return(0,mn.isDateUnit)(this.timeframe)?(0,AI.timeResult)({dataType:"date",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,AI.timeOffset)("date",i.value,r,s.value,this.timeframe)},o):(this.log(`Cannot offset date by ${this.timeframe}`),(0,LS.errorFor)("ofsset date error"))}return super.apply(e,r,n)}getExpression(e){return{dataType:"duration",expressionType:"scalar",value:["__ERROR_DURATION_IS_NOT_A_VALUE__"],evalSpace:"constant"}}};Kc.ExprDuration=i5;function L3e(t,e){return t.dataType===e?t.value:t.morphic&&t.morphic[e]}function Btt(t,e){if(t.dataType===e)return t;if(t.morphic&&t.morphic[e])return{...t,dataType:e,value:t.morphic[e]}}Kc.getMorphicValue=Btt;function P3e(t,e,r,n){let i=(0,mn.isTimeFieldType)(e.dataType),s=(0,mn.isTimeFieldType)(n.dataType);if(i&&s)if(e.dataType!==n.dataType){let o=L3e(e,"timestamp"),a=L3e(n,"timestamp");if(o&&a)return(0,kx.compose)(o,r,a)}else return(0,kx.compose)(e.value,r,n.value);if((i||s)&&e.dataType!=="null"&&n.dataType!=="null")return t.log(`Cannot compare a ${e.dataType} to a ${n.dataType}`),["false"]}function I3e(t,e){if(t.dataType==="string"){if(e.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:t.value,regexp:e.value}]}else if(e.dataType==="string"&&t.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:e.value,regexp:t.value}]}function qtt(t,e,r){let n=e==="!="||e==="!~";if(t.dataType==="null"||r.dataType==="null"){let i=n?" NOT":"";return t.dataType!=="null"?[...t.value,` IS${i} NULL`]:r.dataType!=="null"?[...r.value,`IS${i} NULL`]:[n?"false":"true"]}}function Utt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("boolean",i,s);if(o)return o;if(i.dataType==="unsupported"||s.dataType==="unsupported"){let l=i.dataType==="null"||s.dataType==="null",c=i.rawType&&i.rawType===s.rawType;if(!(l||c)){let f=o5(e,i,n,s);if(f)return{...f,dataType:"boolean"}}}let u=P3e(e,i,r,s)||(0,kx.compose)(i.value,r,s.value);if(i.dataType!=="error"&&s.dataType!=="error")switch(r){case"~":case"!~":{if(i.dataType==="string"&&s.dataType==="string")u=(0,kx.compose)(i.value,"LIKE",s.value);else{let l=I3e(i,s);if(l===void 0)throw new OK("Incompatible types for match('~') operator");u=l}u=(0,kx.nullsafeNot)(u,r);break}case"=":case"!=":{let l=qtt(i,r,s);l?u=l:u=(0,kx.nullsafeNot)(I3e(i,s)||(0,kx.compose)(i.value,"=",s.value),r);break}}return{dataType:"boolean",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:u}}function $tt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("boolean",i,s);if(o)return o;let a=(0,mn.maxExpressionType)(i.expressionType,s.expressionType),u=o5(e,i,n,s);if(u)return{...u,dataType:"boolean"};let l=P3e(e,i,r,s)||(0,kx.compose)(i.value,r,s.value);return{dataType:"boolean",expressionType:a,evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:l}}function RK(t,...e){return e.includes(t)}function jtt(t,...e){for(let r of e)if(r.dataType!==t)return!1;return!0}function k3e(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("number",i,s);if(o)return o;let a=o5(e,i,n,s);if(a)return a;let u=(0,mn.maxExpressionType)(i.expressionType,s.expressionType);return jtt("number",i,s)?{dataType:"number",expressionType:u,value:(0,kx.compose)(i.value,r,s.value),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace)}:(e.log(`Non numeric('${i.dataType},${s.dataType}') value with '${r}'`),(0,LS.errorFor)("numbers required"))}function Htt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=o5(e,i,n,s);if(o)return o;let a=(0,mn.isTimeFieldType)(i.dataType),u=s5(a?"error":"number",i,s);if(u)return u;if(a){let l=n;if(s.dataType!=="duration")if((0,M3e.isGranularResult)(i))l=new i5(n,i.timeframe);else if(i.dataType==="date")l=new i5(n,"day");else return e.log(`Can not offset time by '${s.dataType}'`),(0,LS.errorFor)(`time plus ${s.dataType}`);return l.apply(t,r,e)}return k3e(t,e,r,n)}function B3e(t,e,r,n){if((0,Ptt.isEquality)(r))return Utt(t,e,r,n);if((0,Mtt.isComparison)(r))return $tt(t,e,r,n);if(RK(r,"+","-"))return Htt(t,e,r,n);if(RK(r,"*","%"))return k3e(t,e,r,n);if(RK(r,"/")){let i=e.getExpression(t),s=n.getExpression(t),o=o5(e,i,n,s);if(o)return e.log("Cannot operate with unsupported type"),o;let a=s5("number",i,s);if(a)return a;if(i.dataType!=="number")e.log("Numerator for division must be a number");else if(s.dataType!=="number")n.log("Denominator for division must be a number");else{let u={type:"dialect",function:"div",numerator:i.value,denominator:s.value};return{dataType:"number",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:[u]}}return(0,LS.errorFor)("divide type mismatch")}return e.log(`Cannot use ${r} operator here`),(0,LS.errorFor)("applybinary bad operator")}Kc.applyBinary=B3e;function s5(t,...e){if(e.some(r=>r.dataType==="error"))return{dataType:t,expressionType:(0,mn.maxOfExpressionTypes)(e.map(r=>r.expressionType)),value:["'cascading error'"],evalSpace:(0,mn.mergeEvalSpaces)(...e.map(r=>r.evalSpace))}}function o5(t,e,r,n){let i={dataType:e.dataType,expressionType:(0,mn.maxExpressionType)(e.expressionType,n.expressionType),value:["'unsupported operation'"],evalSpace:(0,mn.mergeEvalSpaces)(e.evalSpace,n.evalSpace)};if(e.dataType==="unsupported")return t.log("Unsupported type not allowed in expression"),{...i,dataType:n.dataType};if(n.dataType==="unsupported")return r.log("Unsupported type not allowed in expression"),i}});var _I=v(vI=>{"use strict";Object.defineProperty(vI,"__esModule",{value:!0});vI.BinaryBoolean=void 0;var q3e=Ke(),ztt=js(),Gtt=pn(),Qtt=ir(),Vtt=hs(),DK=class extends Qtt.ExpressionDef{constructor(e,r,n){super({left:e,right:n}),this.left=e,this.op=r,this.right=n,this.elementType="abstract boolean binary",this.legalChildTypes=[Gtt.FT.boolT]}getExpression(e){let r=this.left.getExpression(e),n=this.right.getExpression(e);if(this.typeCheck(this.left,r)&&this.typeCheck(this.right,n)){let i=(0,q3e.mergeEvalSpaces)(r.evalSpace,n.evalSpace);return{dataType:"boolean",expressionType:(0,q3e.maxExpressionType)(r.expressionType,n.expressionType),evalSpace:i,value:(0,Vtt.compose)(r.value,this.op,n.value)}}return(0,ztt.errorFor)("logial required boolean")}};vI.BinaryBoolean=DK});var TI=v(bI=>{"use strict";Object.defineProperty(bI,"__esModule",{value:!0});bI.ExprTime=void 0;var Wtt=Ke(),Ytt=hs(),Ktt=ir(),NK=class t extends Ktt.ExpressionDef{constructor(e,r,n="scalar"){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue={dataType:e,expressionType:n,value:typeof r=="string"?[r]:r,evalSpace:"constant"}}getExpression(e){return this.translationValue}static fromValue(e,r){let n=r.value;if(e!==r.dataType){let i={type:"dialect",function:"cast",safe:!1,dstType:e,expr:r.value};(0,Wtt.isTimeFieldType)(r.dataType)&&(i.srcType=r.dataType),n=(0,Ytt.compressExpr)([i])}return new t(e,n,r.expressionType)}};bI.ExprTime=NK});var IS=v(CI=>{"use strict";Object.defineProperty(CI,"__esModule",{value:!0});CI.Range=void 0;var U3e=Ke(),Xtt=js(),Jtt=ir(),Ztt=hs(),FK=class extends Jtt.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,n){switch(r){case"=":case"!=":{let i=r==="="?">=":"<",s=r==="="?"and":"or",o=r==="="?"<":">=",a=this.first.apply(e,i,n),u=this.last.apply(e,o,n);return{dataType:"boolean",expressionType:(0,U3e.maxExpressionType)(a.expressionType,u.expressionType),evalSpace:(0,U3e.mergeEvalSpaces)(a.evalSpace,u.evalSpace),value:(0,Ztt.compose)(a.value,s,u.value)}}case">":return this.last.apply(e,">=",n);case">=":return this.first.apply(e,">=",n);case"<":return this.first.apply(e,"<",n);case"<=":return this.last.apply(e,"<",n)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,Xtt.errorFor)("a range is not a value")}};CI.Range=FK});var IK=v(OI=>{"use strict";Object.defineProperty(OI,"__esModule",{value:!0});OI.ExprGranularTime=void 0;var wK=Ke(),ert=js(),$3e=pn(),j3e=DS(),trt=ir(),RI=TI(),H3e=IS(),LK=class extends trt.ExpressionDef{constructor(e,r,n){super({expr:e}),this.expr=e,this.units=r,this.truncate=n,this.elementType="granularTime",this.legalChildTypes=[$3e.FT.timestampT,$3e.FT.dateT]}granular(){return!0}getExpression(e){let r=this.units,n=this.expr.getExpression(e);if((0,wK.isTimeFieldType)(n.dataType)){let s={...n,dataType:n.dataType,timeframe:r};return this.truncate&&(s.value=[{type:"dialect",function:"trunc",expr:{value:n.value,valueType:n.dataType},units:r}]),s}n.dataType!=="error"&&this.log(`Cannot do time truncation on type '${n.dataType}'`);let i=n.dataType==="error"?(0,wK.isDateUnit)(r)?"date":"timestamp":n.dataType;return{...n,dataType:i,value:(0,ert.errorFor)("granularity typecheck").value,evalSpace:"constant"}}apply(e,r,n){return this.getRange(e).apply(e,r,n)}getRange(e){let r=this.getExpression(e);if(r.dataType==="timestamp"){let o=RI.ExprTime.fromValue("timestamp",r),a=new RI.ExprTime("timestamp",(0,j3e.timeOffset)("timestamp",r.value,"+",(0,wK.mkExpr)`1`,this.units),r.expressionType);return new H3e.Range(o,a)}let n=new RI.ExprTime("date",r.value,r.expressionType),i=(0,j3e.timeOffset)("date",r.value,"+",["1"],this.units),s=new RI.ExprTime("date",i,r.expressionType);return new H3e.Range(n,s)}};OI.ExprGranularTime=LK});var PK=v(DI=>{"use strict";Object.defineProperty(DI,"__esModule",{value:!0});DI.ExprCompare=void 0;var Cr=pn(),rrt=yI(),nrt=_I(),irt=IK(),srt={"~":[Cr.FT.stringT],"!~":[Cr.FT.stringT],"<":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"<=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"!=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],">=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],">":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT]},MK=class extends nrt.BinaryBoolean{constructor(e,r,n){super(e,r,n),this.elementType="a<=>b",this.legalChildTypes=srt[r]}getExpression(e){if(!this.right.granular()){let r=this.right.requestExpression(e);if(r&&(0,rrt.isGranularResult)(r))return new irt.ExprGranularTime(this.right,r.timeframe,!1).apply(e,this.op,this.left)}return this.right.apply(e,this.op,this.left)}};DI.ExprCompare=MK});var z3e=v(NI=>{"use strict";Object.defineProperty(NI,"__esModule",{value:!0});NI.Apply=void 0;var ort=pI(),art=PK(),kK=class extends art.ExprCompare{constructor(e,r){super(e,ort.Comparison.EqualTo,r),this.left=e,this.right=r,this.elementType="apply"}};NI.Apply=kK});var wI=v(FI=>{"use strict";Object.defineProperty(FI,"__esModule",{value:!0});FI.BinaryNumeric=void 0;var urt=pn(),lrt=ir(),BK=class extends lrt.ExpressionDef{constructor(e,r,n){super({left:e,right:n}),this.left=e,this.op=r,this.right=n,this.elementType="numeric binary abstract",this.legalChildTypes=[urt.FT.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}};FI.BinaryNumeric=BK});var G3e=v(LI=>{"use strict";Object.defineProperty(LI,"__esModule",{value:!0});LI.Boolean=void 0;var crt=ir(),frt=pn(),qK=class extends crt.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...frt.FT.boolT,value:[this.value]}}};LI.Boolean=qK});var MI=v(II=>{"use strict";Object.defineProperty(II,"__esModule",{value:!0});II.ExprIdReference=void 0;var UK=Ke(),xrt=js(),drt=SL(),hrt=ir(),$K=class extends hrt.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){let r=this.fieldReference.getField(e);if(r.found){let n=r.found.typeDesc();if(r.isOutputField)return{...n,evalSpace:n.evalSpace==="constant"?"constant":"output",value:[{type:"outputField",name:this.refString}]};let i=[{type:r.found.refType,path:this.fieldReference.path}],s=(0,UK.expressionIsAggregate)(n.expressionType)?"output":n.evalSpace;return{...n,value:i,evalSpace:s}}return this.log(r.error),(0,xrt.errorFor)(r.error)}apply(e,r,n){let i=this.fieldReference.getField(e).found;if(i instanceof drt.SpaceParam){let s=i.parameter();if((0,UK.isConditionParameter)(s)){let o=n.getExpression(e);return{dataType:"boolean",expressionType:o.expressionType,evalSpace:(0,UK.mergeEvalSpaces)(o.evalSpace,"input"),value:[{type:"apply",value:o.value,to:[{type:"parameter",path:this.fieldReference.path}]}]}}}return super.apply(e,r,n)}};II.ExprIdReference=$K});var PI=v(MS=>{"use strict";Object.defineProperty(MS,"__esModule",{value:!0});MS.FunctionOrdering=MS.FunctionOrderBy=void 0;var jK=Ke(),Q3e=mt(),prt=MI(),HK=class extends Q3e.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.log("analytic `order_by` must specify an aggregate expression or output field reference"),{e:["error"],dir:this.dir};let r=this.field.getExpression(e);return(0,jK.expressionIsAggregate)(r.expressionType)||((0,jK.expressionIsScalar)(r.expressionType)?(!(this.field instanceof prt.ExprIdReference)||r.evalSpace==="input")&&this.field.log("analytic `order_by` must be an aggregate or an output field reference"):this.field.log("analytic `order_by` must be scalar or aggregate")),{e:r.value,dir:this.dir}}getAggregateOrderBy(e,r){if(this.field){let n=this.field.getExpression(e);return(0,jK.expressionIsScalar)(n.expressionType)||this.field.log("aggregate `order_by` must be scalar"),r||this.field.log("`order_by` must be only `asc` or `desc` with no expression"),{e:n.value,dir:this.dir}}else return this.dir===void 0?(this.log("field or order direction must be specified"),{e:void 0,dir:"asc"}):{e:void 0,dir:this.dir}}};MS.FunctionOrderBy=HK;var zK=class extends Q3e.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(n=>n.getAggregateOrderBy(e,r))}};MS.FunctionOrdering=zK});var V3e=v(kI=>{"use strict";Object.defineProperty(kI,"__esModule",{value:!0});kI.ExprAddSub=void 0;var mrt=wI(),GK=class extends mrt.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}};kI.ExprAddSub=GK});var VK=v(BI=>{"use strict";Object.defineProperty(BI,"__esModule",{value:!0});BI.ReferenceField=void 0;var W3e=la(),QK=class extends W3e.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){let r=this.fieldRef.getField(e);r.error&&this.fieldRef.log(r.error),this.queryFieldDef={type:"fieldref",path:this.fieldRef.list.map(i=>i.name)};let n=this.referenceTo;if(n instanceof W3e.SpaceField&&n.haveFieldDef){let i=n.haveFieldDef,s=this.fieldRef.note;if(i.annotation||s){let o=s||{};i.annotation&&(o.inherits=i.annotation),this.queryFieldDef.annotation=o}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;let e=this.referenceTo;return e?(this.memoTypeDesc=e.typeDesc(),this.memoTypeDesc):{dataType:"error",expressionType:"scalar",evalSpace:"input"}}};BI.ReferenceField=QK});var WK=v(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.typecheckGroupBy=Pi.typecheckAggregate=Pi.typecheckCalculate=Pi.typecheckDeclare=Pi.typecheckMeasure=Pi.typecheckDimension=Pi.typecheckIndex=Pi.typecheckProject=void 0;var gn=lc();function grt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a select operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckProject=grt;function yrt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r;if(t.dataType==="turtle")r="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in an index operation`)}}Pi.typecheckIndex=yrt;function Ert(t,e){if(!(0,gn.expressionIsScalar)(t.expressionType))if((0,gn.expressionIsAggregate)(t.expressionType))e.log("Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,gn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Pi.typecheckDimension=Ert;function Art(t,e){if(!(0,gn.expressionIsAggregate)(t.expressionType))if((0,gn.expressionIsScalar)(t.expressionType))e.log("Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,gn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Pi.typecheckMeasure=Art;function Srt(t,e){t.dataType==="turtle"?e.log("Query fields cannot be used in a declare block"):(0,gn.expressionIsAnalytic)(t.expressionType)&&e.log("Analytic expressions can not be used in a declare block")}Pi.typecheckDeclare=Srt;function vrt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsAnalytic)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else if((0,gn.expressionIsScalar)(t.expressionType))r="a group_by or select",n="a scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a calculate operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckCalculate=vrt;function _rt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsAggregate)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsScalar)(t.expressionType))r="a group_by or select",n="a scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.log(`Cannot use ${n} field in an aggregate operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckAggregate=_rt;function brt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a group_by operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckGroupBy=brt});var PS=v(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.FieldReferences=Gt.WildcardFieldReference=Gt.ViewOrScalarFieldReference=Gt.DimensionFieldReference=Gt.MeasureFieldReference=Gt.DeclareFieldReference=Gt.ProjectFieldReference=Gt.GroupByFieldReference=Gt.AggregateFieldReference=Gt.IndexFieldReference=Gt.CalculateFieldReference=Gt.PartitionByFieldReference=Gt.ExpressionFieldReference=Gt.AcceptExceptFieldReference=Gt.FieldReference=void 0;var Trt=VK(),Crt=n0(),Y3e=mt(),K3e=Wc(),Fp=WK(),Ro=class extends Y3e.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=K3e.extendNoteMethod}makeEntry(e){let r=this.outputName;if(e.entry(r))this.log(`Output already has a field named '${r}'`);else{let n=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(r,this,new Trt.ReferenceField(this,n))}}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){let r=e.lookup(this.list);if(r.found){let n=r.found.typeDesc();this.typecheck(n)}return r}};Gt.FieldReference=Ro;var YK=class extends Ro{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}};Gt.AcceptExceptFieldReference=YK;var KK=class extends Ro{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}};Gt.ExpressionFieldReference=KK;var XK=class extends Ro{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}};Gt.PartitionByFieldReference=XK;var JK=class extends Ro{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,Fp.typecheckCalculate)(e,this)}};Gt.CalculateFieldReference=JK;var ZK=class t extends Ro{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,Fp.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return t.indexOutputName(this.path)}};Gt.IndexFieldReference=ZK;var eX=class extends Ro{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,Fp.typecheckAggregate)(e,this)}};Gt.AggregateFieldReference=eX;var tX=class extends Ro{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,Fp.typecheckGroupBy)(e,this)}};Gt.GroupByFieldReference=tX;var rX=class extends Ro{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,Fp.typecheckProject)(e,this)}};Gt.ProjectFieldReference=rX;var nX=class extends Ro{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,Fp.typecheckDeclare)(e,this)}};Gt.DeclareFieldReference=nX;var iX=class extends Ro{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,Fp.typecheckMeasure)(e,this)}};Gt.MeasureFieldReference=iX;var sX=class extends Ro{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,Fp.typecheckDimension)(e,this)}};Gt.DimensionFieldReference=sX;var oX=class extends Ro{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}};Gt.ViewOrScalarFieldReference=oX;var aX=class extends Y3e.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=K3e.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}.*`:"*"}};Gt.WildcardFieldReference=aX;var uX=class extends Crt.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}};Gt.FieldReferences=uX});var Zm=v(qI=>{"use strict";Object.defineProperty(qI,"__esModule",{value:!0});qI.ExprAggregateFunction=void 0;var X3e=Ke(),Rrt=jd(),a5=js(),Ort=tl(),Drt=e5(),Nrt=pn(),Frt=PS(),wrt=ir(),Lrt=la(),Irt=MI(),lX=class extends wrt.ExpressionDef{constructor(e,r,n){super(),this.func=e,this.legalChildTypes=[Nrt.FT.numberT],this.elementType=e,this.explicitSource=n,r&&(this.expr=r,this.has({expr:r}))}returns(e){return"number"}getExpression(e){var r,n;let i=e.isQueryFieldSpace()?e.inputSpace():e,s=this.expr,o=(r=this.expr)===null||r===void 0?void 0:r.getExpression(i),a=(n=this.source)===null||n===void 0?void 0:n.path,u=[];if(this.source){let c=this.source.getField(i);if(c.found){u=c.relationship;let f=c.found,x=f.typeDesc();if((0,X3e.isAtomicFieldType)(x.dataType)){s=this.source,o={dataType:x.dataType,expressionType:x.expressionType,value:[x.evalSpace==="output"?{type:"outputField",name:this.source.refString}:{type:"field",path:this.source.path}],evalSpace:x.evalSpace},a=this.source.path;let d=this.getJoinUsage(i);(d.length===1||d.length>1&&d.slice(1).every(p=>Mrt(p,d[0])))&&(a=d[0].map(p=>p.name),u=d[0])}else if(!(f instanceof Drt.StructSpaceFieldBase))return this.log(`Aggregate source cannot be a ${x.dataType}`),(0,a5.errorFor)(`Aggregate source cannot be a ${x.dataType}`)}else return this.log(`Reference to undefined value ${this.source.refString}`),(0,a5.errorFor)(`Reference to undefined value ${this.source.refString}`)}if(o===void 0)return this.log("Missing expression for aggregate function"),(0,a5.errorFor)("agggregate without expression");if((0,X3e.expressionIsAggregate)(o.expressionType))return this.log("Aggregate expression cannot be aggregate"),(0,a5.errorFor)("reagggregate");if(!(o.dataType==="error")){let c=this.getJoinUsage(i),f=this.source!==void 0||this.explicitSource;if(s&&!(!this.source&&c.every(d=>d.length===0))&&!this.isSymmetricFunction()){let d=fX(u,c),h=xX(this.elementType,d),p=f?h:"Join path is required for this calculation";if(p){let m=Prt(p,c,s,this.elementType);this.log(m,h?"error":"warn")}}}if(this.typeCheck(this.expr||this,{...o,expressionType:"scalar"})){let c={type:"aggregate",function:this.func,e:o.value};return a&&a.length>0&&(c.structPath=a),{dataType:this.returns(o),expressionType:"aggregate",value:[c],evalSpace:"output"}}return(0,a5.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){let r=[];if(this.source&&this.source.getField(e).found){let i=[{type:"field",path:this.source.path}];r.push(...cX(e,i))}if(this.expr){let n=this.expr.getExpression(e).value;r.push(...cX(e,n))}return r}};qI.ExprAggregateFunction=lX;function Mrt(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 cX(t,e){let r=[],n=(i,s)=>{let o=s[0],a=s.slice(1),u=i.entry(o);if(u===void 0)throw new Error(`Invalid field lookup ${o}`);if(u instanceof Ort.StructSpaceField&&a.length>0){let l=n(u.fieldSpace,a);return{...l,relationship:[{name:o,structRelationship:u.structRelationship},...l.relationship]}}else if(u instanceof Lrt.SpaceField){if(a.length!==0)throw new Error(`${o} cannot contain a ${a.join(".")}`);let l=u.fieldDef();if(l)return{fs:i,def:l,relationship:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};return(0,Rrt.exprWalk)(e,i=>{if(typeof i!="string"){if(i.type==="field"){let s=n(t,i.path);if(s.def.type!=="struct"&&s.def.type!=="turtle")if(s.def.e){let o=cX(s.fs,s.def.e);r.push(...o.map(a=>[...s.relationship,...a]))}else r.push(s.relationship)}else if(i.type==="source-reference")if(i.path){let s=n(t,i.path);r.push(s.relationship)}else r.push([])}}),r}function fX(t,e){let r=[];for(let n of e){let i=0;for(let u=0;u<t.length&&u<n.length&&t[u].name===n[u].name;u++)i=u+1;let s=t.slice(i),o=n.slice(i),a=[...s.map(u=>({...u,reverse:!0})),...o.map(u=>({...u,reverse:!1}))];r.push(a)}return r}function xX(t,e){for(let r of e)for(let n of r){if(n.structRelationship.type==="cross")return`Cannot compute \`${t}\` across \`join_cross\` relationship \`${n.name}\``;if(n.structRelationship.type==="many"&&!n.reverse)return`Cannot compute \`${t}\` across \`join_many\` relationship \`${n.name}\``;if(n.structRelationship.type==="nested"&&!n.reverse)return`Cannot compute \`${t}\` across repeated relationship \`${n.name}\``}}function Prt(t,e,r,n){if(e.length===0)return t;let i=e[0];for(let h of e.slice(1))for(let p=0;p<i.length;p++){let m=i[p],g=h[p];if(m.name!==g.name){i=i.slice(0,p);break}}let s=fX(i,e),o=xX(n,s),a=i.slice().reverse().findIndex(h=>h.structRelationship.type==="many"||h.structRelationship.type==="cross"),u=a===-1?0:i.length-a,l=i.slice(0,u),c=fX(l,e),f=xX(n,c),x=i.length>0?i.map(h=>h.name).join("."):"source",d=l.length>0?l.map(h=>h.name).join("."):"source";if(o)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()`";{let h=r instanceof Frt.FieldReference?`${r.refString}.${n}()`:r instanceof Irt.ExprIdReference?`${r.fieldReference.refString}.${n}()`:`${x}.${n}(${r.code})`,p=`${d}.${n}(${r.code})`,m=`${t}; use \`${h}\``;return f===void 0&&d!==x&&(m+=` or \`${p}\` to get a result weighted with respect to \`${d}\``),m}}});var Z3e=v(UI=>{"use strict";Object.defineProperty(UI,"__esModule",{value:!0});UI.ExprAlternationTree=void 0;var J3e=Ke(),krt=js(),Brt=_I(),qrt=hs(),dX=class extends Brt.BinaryBoolean{constructor(e,r,n){super(e,r,n),this.elementType="alternation",this.elementType=`${r}alternation${r}`}apply(e,r,n){let i=this.left.apply(e,r,n),s=this.right.apply(e,r,n);return{dataType:"boolean",expressionType:(0,J3e.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,J3e.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,qrt.compose)(i.value,this.op==="&"?"and":"or",s.value)}}requestExpression(e){}getExpression(e){return this.log("Alternation tree has no value"),(0,krt.errorFor)("no value from alternation tree")}};UI.ExprAlternationTree=dX});var jI=v($I=>{"use strict";Object.defineProperty($I,"__esModule",{value:!0});$I.ExprAsymmetric=void 0;var Urt=Zm(),hX=class extends Urt.ExprAggregateFunction{constructor(e,r,n,i){super(e,r,i),this.func=e,this.expr=r,this.source=n,this.has({source:n})}isSymmetricFunction(){return!1}defaultFieldName(){if(this.source&&this.expr===void 0){let e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}};$I.ExprAsymmetric=hX});var eye=v(HI=>{"use strict";Object.defineProperty(HI,"__esModule",{value:!0});HI.ExprAvg=void 0;var $rt=jI(),pX=class extends $rt.ExprAsymmetric{constructor(e,r,n){super("avg",e,r,n),this.has({source:r})}};HI.ExprAvg=pX});var tye=v(zI=>{"use strict";Object.defineProperty(zI,"__esModule",{value:!0});zI.ExprCast=void 0;var jrt=DS(),Hrt=ir(),zrt=hs(),mX=class extends Hrt.ExpressionDef{constructor(e,r,n=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=n,this.elementType="cast"}getExpression(e){var r,n,i;let s=this.expr.getExpression(e),o="unsupported";if(typeof this.castType=="string")o=this.castType;else{let a=e.dialectObj();a&&(a.validateTypeName(this.castType.raw)?o=(i=(n=(r=e.dialectObj())===null||r===void 0?void 0:r.sqlTypeToMalloyType(this.castType.raw))===null||n===void 0?void 0:n.type)!==null&&i!==void 0?i:"unsupported":this.log(`Cast type \`${this.castType.raw}\` is invalid for ${a.name} dialect`))}return{dataType:o,expressionType:s.expressionType,value:(0,zrt.compressExpr)((0,jrt.castTo)(this.castType,s.value,s.dataType,this.safe)),evalSpace:s.evalSpace}}};zI.ExprCast=mX});var nye=v(GI=>{"use strict";Object.defineProperty(GI,"__esModule",{value:!0});GI.ExprCoalesce=void 0;var gX=lc(),rye=pn(),Grt=ir(),yX=class extends Grt.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=rye.FT.anyAtomicT}getExpression(e){let r=this.expr.getExpression(e),n=this.altExpr.getExpression(e);return r.dataType==="null"?n:(rye.FT.typeEq(r,n)||this.log(`Mismatched types for coalesce (${r.dataType}, ${n.dataType})`),{...n,dataType:r.dataType==="error"?n.dataType:r.dataType,expressionType:(0,gX.maxExpressionType)(r.expressionType,n.expressionType),value:(0,gX.mkExpr)`COALESCE(${r.value},${n.value})`,evalSpace:(0,gX.mergeEvalSpaces)(r.evalSpace,n.evalSpace)})}};GI.ExprCoalesce=yX});var iye=v(QI=>{"use strict";Object.defineProperty(QI,"__esModule",{value:!0});QI.ExprCount=void 0;var Qrt=Zm(),EX=class extends Qrt.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}getExpression(e){let r={type:"aggregate",function:"count",e:[]};return this.source&&(r.structPath=this.source.path),{dataType:"number",expressionType:"aggregate",value:[r],evalSpace:"output"}}};QI.ExprCount=EX});var sye=v(WI=>{"use strict";Object.defineProperty(WI,"__esModule",{value:!0});WI.ExprCountDistinct=void 0;var VI=pn(),Vrt=Zm(),AX=class extends Vrt.ExprAggregateFunction{constructor(e){super("count_distinct",e),this.legalChildTypes=[VI.FT.numberT,VI.FT.stringT,VI.FT.dateT,VI.FT.timestampT]}};WI.ExprCountDistinct=AX});var kS=v(YI=>{"use strict";Object.defineProperty(YI,"__esModule",{value:!0});YI.Limit=void 0;var Wrt=mt(),Yrt=Ii(),SX=class extends Wrt.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=Yrt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}};YI.Limit=SX});var XI=v(KI=>{"use strict";Object.defineProperty(KI,"__esModule",{value:!0});KI.PartitionBy=void 0;var Krt=mt(),vX=class extends Krt.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}};KI.PartitionBy=vX});var bX=v(JI=>{"use strict";Object.defineProperty(JI,"__esModule",{value:!0});JI.ExprFunc=void 0;var i0=Ke(),Bx=js(),Xrt=e5(),Jrt=ir(),oye=hs(),_X=class extends Jrt.ExpressionDef{constructor(e,r,n,i,s){super({args:r}),this.name=e,this.args=r,this.isRaw=n,this.rawType=i,this.source=s,this.elementType="function call()",this.has({source:s})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}getPropsExpression(e,r){var n,i,s,o,a;let u=this.args.map(O=>O.getExpression(e));if(this.isRaw){let O="scalar",N,k=[`${this.name}(`];for(let H of u)O=(0,i0.maxExpressionType)(O,H.expressionType),N?k.push(","):N=H.dataType,k.push(...H.value);return k.push(")"),{dataType:(i=(n=this.rawType)!==null&&n!==void 0?n:N)!==null&&i!==void 0?i:"number",expressionType:O,value:(0,oye.compressExpr)(k),evalSpace:(0,i0.mergeEvalSpaces)(...u.map(H=>H.evalSpace))}}let l=(s=this.modelEntry(this.name.toLowerCase()))===null||s===void 0?void 0:s.entry;if(l===void 0)return this.log(`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),(0,Bx.errorFor)("unknown function");if(l.type!=="function")return this.log(`Cannot call '${this.name}', which is of type ${l.type}`),(0,Bx.errorFor)("called non function");l.name!==this.name&&this.log(`Case insensitivity for function names is deprecated, use '${l.name}' instead`,"warn");let c,f=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){let O=this.source.getField(e).found;if(O){let N=O.typeDesc();if((0,i0.isAtomicFieldType)(N.dataType))c={dataType:N.dataType,expressionType:N.expressionType,value:[{type:"field",path:this.source.path}],evalSpace:N.evalSpace},f=this.source.path.slice(0,-1);else if(!(O instanceof Xrt.StructSpaceFieldBase)){let k=`Aggregate source cannot be a ${N.dataType}`;return this.log(k),(0,Bx.errorFor)(k)}}else{let N=`Reference to undefined value ${this.source.refString}`;return this.log(N),(0,Bx.errorFor)(N)}}let x=[...c?[c]:[],...u],d=Zrt(l,x);if(d===void 0)return this.log(`No matching overload for function ${this.name}(${x.map(O=>O.dataType).join(", ")})`),(0,Bx.errorFor)("no matching overload");let{overload:h,expressionTypeErrors:p,evalSpaceErrors:m,nullabilityErrors:g}=d;for(let O of p){let N=O.argIndex-(c?1:0),k=(0,i0.expressionIsScalar)(O.maxExpressionType)?"scalar":"scalar or aggregate";this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${k}, but received ${O.actualExpressionType}`)}for(let O of m){let N=O.argIndex-(c?1:0),k=O.maxEvalSpace==="literal"?"literal":O.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${k}, but received ${O.actualEvalSpace}`)}for(let O of g){let N=O.argIndex-(c?1:0);this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must not be a literal null`)}let y=h.returnType,A=(0,i0.maxOfExpressionTypes)([y.expressionType,...x.map(O=>O.expressionType)]);if(!(0,i0.expressionIsAggregate)(h.returnType.expressionType)&&this.source!==void 0)return this.log(`Cannot call function ${this.name}(${x.map(O=>O.dataType).join(", ")}) with source`),(0,Bx.errorFor)("cannot call with source");let S={type:"function_call",overload:h,name:this.name,args:x.map(O=>O.value),expressionType:A,structPath:f},T=[S],b=(a=e.dialectObj())===null||a===void 0?void 0:a.name,_=b?h.dialect[b]:void 0;if(_===void 0)this.log(`Function ${this.name} is not defined in dialect ${b}`);else{if(r?.orderBys&&r.orderBys.length>0){let O=(0,i0.expressionIsAnalytic)(h.returnType.expressionType);if(_.supportsOrderBy||O){let N=_.supportsOrderBy!=="only_default",k=r.orderBys.flatMap(P=>O?P.getAnalyticOrderBy(e):P.getAggregateOrderBy(e,N));S.orderBy=k}else r.orderBys[0].log(`Function ${this.name} does not support order_by`)}r?.limit!==void 0&&(_.supportsLimit?S.limit=r.limit.limit:this.log(`Function ${this.name} does not support limit`))}if(r?.partitionBys&&r.partitionBys.length>0){let O=[];for(let N of r.partitionBys)for(let k of N.partitionFields){let P=k.getField(e);P.found===void 0?k.log(`${k.refString} is not defined`):(0,i0.expressionIsScalar)(P.found.typeDesc().expressionType)?O.push(k.nameString):k.log("Partition expression must be scalar")}S.partitionBy=O}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0))return(0,Bx.errorFor)(`Cannot use sql_function \`${l.name}\`; use \`sql_functions\` experiment to enable this behavior`);let O=x[0].value;if(O.length!==1||typeof O[0]=="string"||O[0].type!=="dialect"||O[0].function!=="stringLiteral")this.log(`Invalid string literal for \`${l.name}\``);else{let N=O[0].literal,k=ent(N),P=k.filter(H=>H.type==="interpolation"&&H.name.includes(".")).map(H=>H.type==="interpolation"?`\${${H.name}}`:`\${${H.value}}`);if(P.length>0){let H=P.length===1?`'.' paths are not yet supported in sql interpolations, found ${P.at(0)}`:`'.' paths are not yet supported in sql interpolations, found [${P.join(", ")}]`;return this.log(H),(0,Bx.errorFor)(`${H}. See LookML \${...} documentation at https://cloud.google.com/looker/docs/reference/param-field-sql#sql_for_dimensions`)}T=[{type:"sql-string",e:k.map(H=>H.type==="string"?H.value:H.name==="TABLE"?{type:"source-reference"}:{type:"field",path:[H.name]})}]}}if(y.dataType==="any")return this.log(`Invalid return type ${y.dataType} for function '${this.name}'`),(0,Bx.errorFor)("invalid return type");let R=(0,i0.mergeEvalSpaces)(...x.map(O=>O.evalSpace)),D=R==="constant"?"constant":(0,i0.expressionIsScalar)(A)?R:"output";return{dataType:y.dataType,expressionType:A,value:(0,oye.compressExpr)(T),evalSpace:D}}};JI.ExprFunc=_X;function Zrt(t,e){for(let r of t.overloads){let n=0,i=!0,s=!1,o=[],a=[],u=[];for(let l=0;l<e.length;l++){let c=e[l],f=r.params[n];if(f===void 0){i=!1;break}if(!f.allowedTypes.some(d=>{let h=d.dataType===c.dataType||d.dataType==="any"||c.dataType==="null"||c.dataType==="error";return d.expressionType&&((0,i0.isExpressionTypeLEQ)(c.expressionType,d.expressionType)||o.push({argIndex:l,maxExpressionType:d.expressionType,actualExpressionType:c.expressionType,param:f})),(d.evalSpace==="literal"&&c.evalSpace!=="literal"||d.evalSpace==="constant"&&(c.evalSpace==="input"||c.evalSpace==="output")||d.evalSpace==="output"&&c.evalSpace==="input")&&a.push({argIndex:l,param:f,maxEvalSpace:d.evalSpace,actualEvalSpace:c.evalSpace}),d.evalSpace==="literal"&&c.dataType==="null"&&u.push({argIndex:l,param:f}),h})){i=!1;break}f.isVariadic?l===e.length-1&&(s=!0):n++}if(!(!s&&(n!==e.length||n!==r.params.length))&&i)return{overload:r,expressionTypeErrors:o,evalSpaceErrors:a,nullabilityErrors:u}}}function ent(t){let e=[],r=t;for(;r.length;){let n=r.indexOf("${");if(n===-1){e.push({type:"string",value:r});break}else{let i=r.slice(n).indexOf("}");if(i===-1){e.push({type:"string",value:r});break}n>0&&e.push({type:"string",value:r.slice(0,n)}),e.push({type:"interpolation",name:r.slice(n+2,i+n)}),r=r.slice(i+n+1)}}return e}});var aye=v(ZI=>{"use strict";Object.defineProperty(ZI,"__esModule",{value:!0});ZI.ExprProps=void 0;var tnt=Ke(),rnt=js(),nnt=pn(),int=PI(),snt=kS(),ont=XI(),ant=ir(),unt=bX(),TX=class extends ant.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=nnt.FT.anyAtomicT}getFilteredExpression(e,r,n){if(n.length>0){if(!this.expr.supportsWhere(r))return this.expr.log("Filtered expression requires an aggregate computation"),r;let i=[];for(let s of n){let o=s.getFilterList(e);if(o.find(a=>(0,tnt.expressionIsCalculation)(a.expressionType)))return s.log("Cannot filter an expresion with an aggregate or analytical computation"),r;i.push(...o)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,value:[{type:"filterExpression",e:r.value,filterList:i}]}:(this.expr.log(`Cannot filter '${r.dataType}' data`),(0,rnt.errorFor)("cannot filter type"))}return r}getExpression(e){let r=[],n,i=[],s=[];for(let a of this.statements)a instanceof ont.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.log("`partition_by` is not supported for this kind of expression"):a instanceof snt.Limit?n?a.log("limit already specified"):this.expr.canSupportLimit()?n=a:a.log("`limit` is not supported for this kind of expression"):a instanceof int.FunctionOrdering?this.expr.canSupportPartitionBy()?i.push(a):a.log("`order_by` is not supported for this kind of expression"):s.push(a);let o=this.expr instanceof unt.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:n,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}};ZI.ExprProps=TX});var lye=v(eM=>{"use strict";Object.defineProperty(eM,"__esModule",{value:!0});eM.ExprLogicalOp=void 0;var lnt=_I(),uye=pn(),CX=class extends lnt.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[uye.FT.boolT,uye.FT.aggregateBoolT]}};eM.ExprLogicalOp=CX});var cye=v(rM=>{"use strict";Object.defineProperty(rM,"__esModule",{value:!0});rM.ExprMax=void 0;var tM=pn(),cnt=Zm(),RX=class extends cnt.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[tM.FT.numberT,tM.FT.stringT,tM.FT.dateT,tM.FT.timestampT]}returns(e){return e.dataType}};rM.ExprMax=RX});var fye=v(iM=>{"use strict";Object.defineProperty(iM,"__esModule",{value:!0});iM.ExprMin=void 0;var nM=pn(),fnt=Zm(),OX=class extends fnt.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[nM.FT.numberT,nM.FT.stringT,nM.FT.dateT,nM.FT.timestampT]}returns(e){return e.dataType}};iM.ExprMin=OX});var dye=v(sM=>{"use strict";Object.defineProperty(sM,"__esModule",{value:!0});sM.ExprMinus=void 0;var xnt=js(),xye=pn(),dnt=ir(),DX=class extends dnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[xye.FT.numberT]}getExpression(e){let r=this.expr.getExpression(e);return xye.FT.typeIn(r,this.legalChildTypes)?r.value.length>1?{...r,dataType:"number",value:["-(",...r.value,")"]}:{...r,dataType:"number",value:["-",...r.value]}:(0,xnt.errorFor)("negate requires number")}};sM.ExprMinus=DX});var hye=v(oM=>{"use strict";Object.defineProperty(oM,"__esModule",{value:!0});oM.ExprMulDiv=void 0;var hnt=wI(),NX=class extends hnt.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}};oM.ExprMulDiv=NX});var wX=v(aM=>{"use strict";Object.defineProperty(aM,"__esModule",{value:!0});aM.Unary=void 0;var pnt=ir(),FX=class extends pnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}};aM.Unary=FX});var mye=v(uM=>{"use strict";Object.defineProperty(uM,"__esModule",{value:!0});uM.ExprNot=void 0;var pye=pn(),mnt=wX(),gnt=hs(),LX=class extends mnt.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[pye.FT.boolT,pye.FT.nullT]}getExpression(e){let r=this.expr.getExpression(e),n=this.typeCheck(this.expr,r);return{...r,dataType:"boolean",value:n?(0,gnt.nullsafeNot)(r.value):["false"]}}};uM.ExprNot=LX});var gye=v(lM=>{"use strict";Object.defineProperty(lM,"__esModule",{value:!0});lM.ExprNow=void 0;var ynt=ir(),IX=class extends ynt.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{dataType:"timestamp",expressionType:"scalar",evalSpace:"constant",value:[{type:"dialect",function:"now"}]}}};lM.ExprNow=IX});var yye=v(cM=>{"use strict";Object.defineProperty(cM,"__esModule",{value:!0});cM.ExprNULL=void 0;var Ent=ir(),MX=class extends Ent.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return{dataType:"null",value:["NULL"],expressionType:"scalar",evalSpace:"literal"}}};cM.ExprNULL=MX});var Eye=v(fM=>{"use strict";Object.defineProperty(fM,"__esModule",{value:!0});fM.ExprNumber=void 0;var Ant=pn(),Snt=ir(),PX=class extends Snt.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){return{...Ant.FT.numberT,evalSpace:"literal",value:[{type:"dialect",function:"numberLiteral",literal:this.n}]}}};fM.ExprNumber=PX});var Aye=v(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0});xM.ExprParens=void 0;var vnt=ir(),kX=class extends vnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){let r=this.expr.getExpression(e);return{...r,value:["(",...r.value,")"]}}};xM.ExprParens=kX});var Sye=v(dM=>{"use strict";Object.defineProperty(dM,"__esModule",{value:!0});dM.ExprRegEx=void 0;var _nt=ir(),BX=class extends _nt.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return{dataType:"regular expression",expressionType:"scalar",value:[{type:"dialect",function:"regexpLiteral",literal:this.regex}],evalSpace:"literal"}}};dM.ExprRegEx=BX});var vye=v(hM=>{"use strict";Object.defineProperty(hM,"__esModule",{value:!0});hM.ExprString=void 0;var bnt=ir(),Tnt=pn(),qX=class extends bnt.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return{...Tnt.FT.stringT,value:[{type:"dialect",function:"stringLiteral",literal:this.value}],evalSpace:"literal"}}};hM.ExprString=qX});var _ye=v(pM=>{"use strict";Object.defineProperty(pM,"__esModule",{value:!0});pM.ExprSum=void 0;var Cnt=jI(),UX=class extends Cnt.ExprAsymmetric{constructor(e,r,n){super("sum",e,r,n),this.has({source:r})}};pM.ExprSum=UX});var bye=v(gM=>{"use strict";Object.defineProperty(gM,"__esModule",{value:!0});gM.ExprTimeExtract=void 0;var eg=Ke(),wp=js(),$X=ir(),Rnt=IS(),mM=class t extends $X.ExpressionDef{static extractor(e){let r=t.pluralMap[e];if(r)return r;if((0,eg.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){let r=t.extractor(this.extractText);if(r){if(this.args.length!==1)return this.log(`Extraction function ${r} requires one argument`),(0,wp.errorFor)("{this.name} arg count");let n=this.args[0];if(n instanceof Rnt.Range){let i=n.first.getExpression(e),s=n.last.getExpression(e),o=(0,eg.maxExpressionType)(i.expressionType,s.expressionType),a=(0,eg.mergeEvalSpaces)(i.evalSpace,s.evalSpace);if(i.dataType==="error"||s.dataType==="error")return{dataType:"number",expressionType:o,evalSpace:a,value:(0,wp.errorFor)("extract from error").value};if(!(0,eg.isTimeFieldType)(i.dataType))return n.first.log(`Can't extract ${r} from '${i.dataType}'`),(0,wp.errorFor)(`${r} bad type ${i.dataType}`);if(!(0,eg.isTimeFieldType)(s.dataType))return n.last.log(`Cannot extract ${r} from '${s.dataType}'`),(0,wp.errorFor)(`${r} bad type ${s.dataType}`);let u=i.dataType;if(i.dataType!==s.dataType){let l=!0;if(u="timestamp",i.dataType==="date"){let c=(0,$X.getMorphicValue)(i,"timestamp");c&&(i=c,l=!1)}else{let c=(0,$X.getMorphicValue)(s,"timestamp");c&&(s=c,l=!1)}if(l)return n.first.log(`Cannot measure from ${i.dataType} to ${s.dataType}`),(0,wp.errorFor)(`${r} range mismatch`)}return["week","month","quarter","year"].includes(r)?(this.log(`Cannot measure interval using '${r}'`),(0,wp.errorFor)(`${r} civil extraction`)):(0,eg.isTimestampUnit)(r)?{dataType:"number",expressionType:o,evalSpace:a,value:[{type:"dialect",function:"timeDiff",units:r,left:{valueType:u,value:i.value},right:{valueType:u,value:s.value}}]}:(this.log(`Cannot extract ${r} from a range`),(0,wp.errorFor)(`${r} bad extraction`))}else{let i=n.getExpression(e);return(0,eg.isTimeFieldType)(i.dataType)?{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:[{type:"dialect",function:"extract",expr:{value:i.value,valueType:i.dataType},units:r}]}:(i.dataType!=="error"&&this.log(`${this.extractText}() requires time type, not '${i.dataType}'`),{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:(0,wp.errorFor)(`${this.extractText} bad type ${i.dataType}`).value})}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}};gM.ExprTimeExtract=mM;mM.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"}});var u5=v(yM=>{"use strict";Object.defineProperty(yM,"__esModule",{value:!0});yM.FieldName=void 0;var Ont=mt(),jX=class extends Ont.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])}};yM.FieldName=jX});var Tye=v(EM=>{"use strict";Object.defineProperty(EM,"__esModule",{value:!0});EM.QueryInputSpace=void 0;var Dnt=CS(),Nnt=PY(),Fnt=wL(),HX=class extends Fnt.RefinedSpace{constructor(e,r){let n=new Nnt.SpaceSeed(e);super(n.structDef),this.queryOutput=r,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof Dnt.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}};EM.QueryInputSpace=HX});var l5=v(fa=>{"use strict";var wnt=fa&&fa.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Lnt=fa&&fa.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Int=fa&&fa.__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)&&wnt(e,t,r);return Lnt(e,t),e};Object.defineProperty(fa,"__esModule",{value:!0});fa.ReduceFieldSpace=fa.QuerySpace=fa.QueryOperationSpace=void 0;var AM=Int(Ke()),zX=AL(),Mnt=u5(),Pnt=la(),knt=PS(),Bnt=wL(),qnt=FY(),Unt=tl(),$nt=Tye(),SM=class extends Bnt.RefinedSpace{constructor(e,r,n,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=n,this.astEl=i,this.expandedWild={},this.exprSpace=new $nt.QueryInputSpace(e,this),r&&this.addRefineFromFields(r)}log(e){this.astEl&&this.astEl.log(e)}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let n=this.exprSpace,i=[];if(e.joinPath)for(let a of e.joinPath.list){let u=a.refString;i.push(u);let l=n.entry(u);if(l)if(l instanceof Unt.StructSpaceField)n=l.fieldSpace;else{a.log(`Field '${u}' does not contain rows and cannot be expanded with '*'`);return}else{a.log(`No such field as '${u}'`);return}}let s=this.dialectObj(),o=[];for(let[a,u]of n.entries())if(!e.except.has(a))if(this.entry(a)){let l=(r=this.expandedWild[a])===null||r===void 0?void 0:r.join(".");e.log(`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${l?` (conflicts with ${l})`:""}`)}else{let l=u.typeDesc();AM.isAtomicFieldType(l.dataType)&&AM.expressionIsScalar(l.expressionType)&&(s===void 0||!s.ignoreInProject(a))&&(o.push({name:a,entry:u}),this.expandedWild[a]=i.concat(a))}for(let a of o.sort((u,l)=>u.name.localeCompare(l.name)))this.setEntry(a.name,a.entry)}};fa.QueryOperationSpace=SM;var vM=class extends SM{addRefineFromFields(e){var r;if(AM.isQuerySegment(e))for(let n of e.queryFields)if(n.type==="fieldref"){let i=this.exprSpace.lookup(n.path.map(s=>new Mnt.FieldName(s)));i.found&&this.setEntry(n.path[n.path.length-1],i.found)}else n.type!=="turtle"&&this.setEntry((r=n.as)!==null&&r!==void 0?r:n.name,new qnt.ColumnSpaceField(n))}pushFields(...e){for(let r of e)r instanceof knt.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){let e=[];for(let[r,n]of this.entries())if(n instanceof Pnt.SpaceField){let i=this.expandedWild[r];if(i){e.push({type:"fieldref",path:i});continue}let s=n.getQueryFieldDef(this.exprSpace);if(s){let o=n.typeDesc();o.dataType!=="error"&&this.canContain(o)&&!jnt(s)&&e.push(s)}}return this.isComplete(),e}getQuerySegment(e){let r=this.getPipeSegment(e);if(AM.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.log("internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};if(e?.extendSource)for(let n of e.extendSource)this.exprSpace.addFieldDef(n);let r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,zX.mergeFields)(e?.queryFields,r.queryFields),e?.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){let n=[],i=this.exprSpace.structDef();for(let s of this.exprSpace.extendList){let o=i.fields.find(a=>(0,zX.nameFromDef)(a)===s);o&&n.push(o)}r.extendSource=(0,zX.mergeFields)(r.extendSource,n)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),this.isComplete(),r}lookup(e){let r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}};fa.QuerySpace=vM;var GX=class extends vM{constructor(){super(...arguments),this.segmentType="reduce"}};fa.ReduceFieldSpace=GX;function jnt(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}});var Rye=v(_M=>{"use strict";Object.defineProperty(_M,"__esModule",{value:!0});_M.ExprUngroup=void 0;var Cye=Ke(),QX=js(),Hnt=l5(),znt=pn(),Gnt=ir(),VX=class extends Gnt.ExpressionDef{constructor(e,r,n){super({expr:r,fields:n}),this.control=e,this.expr=r,this.fields=n,this.legalChildTypes=znt.FT.anyAtomicT,this.elementType="ungroup"}returns(e){return"number"}getExpression(e){let r=this.expr.getExpression(e);if(!(0,Cye.expressionIsAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must be an aggregate`),(0,QX.errorFor)("ungrouped scalar");if((0,Cye.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must not already be ungrouped`),(0,QX.errorFor)("doubly-ungrouped aggregate");let n={type:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){let i=[],s=this.control==="exclude";for(let o of this.fields){let a=e.outputSpace(),u=!0;for(;a;){let l=a.lookup([o]);if(l.found&&l.isOutputField)i.push(o.refString),u=!1;else if(a instanceof Hnt.QuerySpace){a=a.nestParent;continue}break}if(u){let l=s?"exclude()":"all()";o.log(`${l} '${o.refString}' is missing from query output`)}}n.fields=i}return{dataType:this.returns(r),expressionType:"ungrouped_aggregate",value:[n],evalSpace:"output"}}return this.log(`${this.control}() incompatible type`),(0,QX.errorFor)("ungrouped type check")}};_M.ExprUngroup=VX});var Fye=v(CM=>{"use strict";Object.defineProperty(CM,"__esModule",{value:!0});CM.ForRange=void 0;var Oye=lc(),WX=js(),Dye=pn(),bM=DS(),Qnt=ir(),TM=TI(),Nye=IS(),YX=class extends Qnt.ExpressionDef{constructor(e,r,n){super({from:e,duration:r,timeframe:n}),this.from=e,this.duration=r,this.timeframe=n,this.elementType="forRange",this.legalChildTypes=[Dye.FT.timestampT,Dye.FT.dateT]}apply(e,r,n){let i=this.from.getExpression(e),s=n.getExpression(e);if(!this.typeCheck(n,s))return(0,WX.errorFor)("no time for range");let o=this.duration.getExpression(e);if(o.dataType!=="number")return o.dataType!=="error"&&this.log(`FOR duration count must be a number, not '${o.dataType}'`),{dataType:"boolean",evalSpace:(0,Oye.mergeEvalSpaces)(i.evalSpace,s.evalSpace),expressionType:(0,Oye.maxExpressionType)(i.expressionType,s.expressionType),value:(0,WX.errorFor)("for not number").value};let a=this.timeframe.text,u=(0,bM.resolution)(a);if(i.dataType==="timestamp"&&(u="timestamp"),s.dataType==="date"&&u==="date"){let h=this.from,p=(0,bM.timeOffset)("date",i.value,"+",o.value,a),m=new TM.ExprTime("date",p);return new Nye.Range(h,m).apply(e,r,n)}let l=TM.ExprTime.fromValue("timestamp",s),c=this.from,f=i.value;if(i.dataType==="date"){let h=i.morphic&&i.morphic.timestamp;h?f=h:f=(0,bM.castDateToTimestamp)(f),c=new TM.ExprTime("timestamp",f,i.expressionType)}let x=(0,bM.timeOffset)("timestamp",f,"+",o.value,a),d=new TM.ExprTime("timestamp",x,i.expressionType);return new Nye.Range(c,d).apply(e,r,l)}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,WX.errorFor)("range has no value")}};CM.ForRange=YX});var bJ=v(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});var Ux=class extends Error{},iJ=class extends Ux{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},sJ=class extends Ux{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},oJ=class extends Ux{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},ig=class extends Ux{},LM=class extends Ux{constructor(e){super(`Invalid unit ${e}`)}},xa=class extends Ux{},Xc=class extends Ux{constructor(){super("Zone is an abstract class")}},Re="numeric",u0="short",lu="long",aJ={year:Re,month:Re,day:Re},rEe={year:Re,month:u0,day:Re},Vnt={year:Re,month:u0,day:Re,weekday:u0},nEe={year:Re,month:lu,day:Re},iEe={year:Re,month:lu,day:Re,weekday:lu},sEe={hour:Re,minute:Re},oEe={hour:Re,minute:Re,second:Re},aEe={hour:Re,minute:Re,second:Re,timeZoneName:u0},uEe={hour:Re,minute:Re,second:Re,timeZoneName:lu},lEe={hour:Re,minute:Re,hourCycle:"h23"},cEe={hour:Re,minute:Re,second:Re,hourCycle:"h23"},fEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:u0},xEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:lu},dEe={year:Re,month:Re,day:Re,hour:Re,minute:Re},hEe={year:Re,month:Re,day:Re,hour:Re,minute:Re,second:Re},pEe={year:Re,month:u0,day:Re,hour:Re,minute:Re},mEe={year:Re,month:u0,day:Re,hour:Re,minute:Re,second:Re},Wnt={year:Re,month:u0,day:Re,weekday:u0,hour:Re,minute:Re},gEe={year:Re,month:lu,day:Re,hour:Re,minute:Re,timeZoneName:u0},yEe={year:Re,month:lu,day:Re,hour:Re,minute:Re,second:Re,timeZoneName:u0},EEe={year:Re,month:lu,day:Re,weekday:lu,hour:Re,minute:Re,timeZoneName:lu},AEe={year:Re,month:lu,day:Re,weekday:lu,hour:Re,minute:Re,second:Re,timeZoneName:lu};function kt(t){return typeof t>"u"}function og(t){return typeof t=="number"}function qM(t){return typeof t=="number"&&t%1===0}function Ynt(t){return typeof t=="string"}function Knt(t){return Object.prototype.toString.call(t)==="[object Date]"}function SEe(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Xnt(t){return Array.isArray(t)?t:[t]}function wye(t,e,r){if(t.length!==0)return t.reduce((n,i)=>{let s=[e(i),i];return n&&r(n[0],s[0])===n[0]?n:s},null)[1]}function Jnt(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function US(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function qx(t,e,r){return qM(t)&&t>=e&&t<=r}function Znt(t,e){return t-e*Math.floor(t/e)}function jn(t,e=2){let r=t<0,n;return r?n="-"+(""+-t).padStart(e,"0"):n=(""+t).padStart(e,"0"),n}function Lp(t){if(!(kt(t)||t===null||t===""))return parseInt(t,10)}function tg(t){if(!(kt(t)||t===null||t===""))return parseFloat(t)}function gJ(t){if(!(kt(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function yJ(t,e,r=!1){let n=10**e;return(r?Math.trunc:Math.round)(t*n)/n}function g5(t){return t%4===0&&(t%100!==0||t%400===0)}function p5(t){return g5(t)?366:365}function IM(t,e){let r=Znt(e-1,12)+1,n=t+(e-r)/12;return r===2?g5(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function EJ(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(e.getUTCFullYear()-1900)),+e}function MM(t){let e=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7,r=t-1,n=(r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400))%7;return e===4||n===3?53:52}function uJ(t){return t>99?t:t>60?1900+t:2e3+t}function vEe(t,e,r,n=null){let i=new Date(t),s={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(s.timeZone=n);let o={timeZoneName:e,...s},a=new Intl.DateTimeFormat(r,o).formatToParts(i).find(u=>u.type.toLowerCase()==="timezonename");return a?a.value:null}function UM(t,e){let r=parseInt(t,10);Number.isNaN(r)&&(r=0);let n=parseInt(e,10)||0,i=r<0||Object.is(r,-0)?-n:n;return r*60+i}function _Ee(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new xa(`Invalid unit value ${t}`);return e}function PM(t,e){let r={};for(let n in t)if(US(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=_Ee(i)}return r}function m5(t,e){let r=Math.trunc(Math.abs(t/60)),n=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${jn(r,2)}:${jn(n,2)}`;case"narrow":return`${i}${r}${n>0?`:${n}`:""}`;case"techie":return`${i}${jn(r,2)}${jn(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function $M(t){return Jnt(t,["hour","minute","second","millisecond"])}var bEe=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,eit=["January","February","March","April","May","June","July","August","September","October","November","December"],TEe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],tit=["J","F","M","A","M","J","J","A","S","O","N","D"];function CEe(t){switch(t){case"narrow":return[...tit];case"short":return[...TEe];case"long":return[...eit];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var REe=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],OEe=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],rit=["M","T","W","T","F","S","S"];function DEe(t){switch(t){case"narrow":return[...rit];case"short":return[...OEe];case"long":return[...REe];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var NEe=["AM","PM"],nit=["Before Christ","Anno Domini"],iit=["BC","AD"],sit=["B","A"];function FEe(t){switch(t){case"narrow":return[...sit];case"short":return[...iit];case"long":return[...nit];default:return null}}function oit(t){return NEe[t.hour<12?0:1]}function ait(t,e){return DEe(e)[t.weekday-1]}function uit(t,e){return CEe(e)[t.month-1]}function lit(t,e){return FEe(e)[t.year<0?0:1]}function cit(t,e,r="always",n=!1){let i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},s=["hours","minutes","seconds"].indexOf(t)===-1;if(r==="auto"&&s){let f=t==="days";switch(e){case 1:return f?"tomorrow":`next ${i[t][0]}`;case-1:return f?"yesterday":`last ${i[t][0]}`;case 0:return f?"today":`this ${i[t][0]}`}}let o=Object.is(e,-0)||e<0,a=Math.abs(e),u=a===1,l=i[t],c=n?u?l[1]:l[2]||l[1]:u?i[t][0]:t;return o?`${a} ${c} ago`:`in ${a} ${c}`}function Lye(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var fit={D:aJ,DD:rEe,DDD:nEe,DDDD:iEe,t:sEe,tt:oEe,ttt:aEe,tttt:uEe,T:lEe,TT:cEe,TTT:fEe,TTTT:xEe,f:dEe,ff:pEe,fff:gEe,ffff:EEe,F:hEe,FF:mEe,FFF:yEe,FFFF:AEe},a0=class t{static create(e,r={}){return new t(e,r)}static parseFormat(e){let r=null,n="",i=!1,s=[];for(let o=0;o<e.length;o++){let a=e.charAt(o);a==="'"?(n.length>0&&s.push({literal:i,val:n}),r=null,n="",i=!i):i||a===r?n+=a:(n.length>0&&s.push({literal:!1,val:n}),n=a,r=a)}return n.length>0&&s.push({literal:i,val:n}),s}static macroTokenToFormatOpts(e){return fit[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}formatDateTime(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).format()}formatDateTimeParts(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).formatToParts()}resolvedOptions(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).resolvedOptions()}num(e,r=0){if(this.opts.forceSimple)return jn(e,r);let n={...this.opts};return r>0&&(n.padTo=r),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,r){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",s=(d,h)=>this.loc.extract(e,d,h),o=d=>e.isOffsetFixed&&e.offset===0&&d.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,d.format):"",a=()=>n?oit(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),u=(d,h)=>n?uit(e,d):s(h?{month:d}:{month:d,day:"numeric"},"month"),l=(d,h)=>n?ait(e,d):s(h?{weekday:d}:{weekday:d,month:"long",day:"numeric"},"weekday"),c=d=>{let h=t.macroTokenToFormatOpts(d);return h?this.formatWithSystemDefault(e,h):d},f=d=>n?lit(e,d):s({era:d},"era"),x=d=>{switch(d){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return i?s({day:"numeric"},"day"):this.num(e.day);case"dd":return i?s({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return l("short",!0);case"cccc":return l("long",!0);case"ccccc":return l("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return l("short",!1);case"EEEE":return l("long",!1);case"EEEEE":return l("narrow",!1);case"L":return i?s({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?s({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return u("short",!0);case"LLLL":return u("long",!0);case"LLLLL":return u("narrow",!0);case"M":return i?s({month:"numeric"},"month"):this.num(e.month);case"MM":return i?s({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return u("short",!1);case"MMMM":return u("long",!1);case"MMMMM":return u("narrow",!1);case"y":return i?s({year:"numeric"},"year"):this.num(e.year);case"yy":return i?s({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?s({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?s({year:"numeric"},"year"):this.num(e.year,6);case"G":return f("short");case"GG":return f("long");case"GGGGG":return f("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return c(d)}};return Lye(t.parseFormat(r),x)}formatDurationFromString(e,r){let n=u=>{switch(u[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},i=u=>l=>{let c=n(l);return c?this.num(u.get(c),l.length):l},s=t.parseFormat(r),o=s.reduce((u,{literal:l,val:c})=>l?u:u.concat(c),[]),a=e.shiftTo(...o.map(n).filter(u=>u));return Lye(s,i(a))}},uu=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},Mp=class{get type(){throw new Xc}get name(){throw new Xc}get ianaName(){return this.name}get isUniversal(){throw new Xc}offsetName(e,r){throw new Xc}formatOffset(e,r){throw new Xc}offset(e){throw new Xc}equals(e){throw new Xc}get isValid(){throw new Xc}},KX=null,kM=class t extends Mp{static get instance(){return KX===null&&(KX=new t),KX}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return vEe(e,r,n)}formatOffset(e,r){return m5(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}},FM={};function xit(t){return FM[t]||(FM[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),FM[t]}var dit={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function hit(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,i,s,o,a,u,l,c]=n;return[o,i,s,a,u,l,c]}function pit(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:s,value:o}=r[i],a=dit[s];s==="era"?n[a]=o:kt(a)||(n[a]=parseInt(o,10))}return n}var RM={},$x=class t extends Mp{static create(e){return RM[e]||(RM[e]=new t(e)),RM[e]}static resetCache(){RM={},FM={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return vEe(e,r,n,this.name)}formatOffset(e,r){return m5(this.offset(e),r)}offset(e){let r=new Date(e);if(isNaN(r))return NaN;let n=xit(this.name),[i,s,o,a,u,l,c]=n.formatToParts?pit(n,r):hit(n,r);a==="BC"&&(i=-Math.abs(i)+1);let x=EJ({year:i,month:s,day:o,hour:u===24?0:u,minute:l,second:c,millisecond:0}),d=+r,h=d%1e3;return d-=h>=0?h:1e3+h,(x-d)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}},XX=null,cu=class t extends Mp{static get utcInstance(){return XX===null&&(XX=new t(0)),XX}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new t(UM(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${m5(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${m5(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return m5(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}},BM=class extends Mp{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function Ip(t,e){if(kt(t)||t===null)return e;if(t instanceof Mp)return t;if(Ynt(t)){let r=t.toLowerCase();return r==="local"||r==="system"?e:r==="utc"||r==="gmt"?cu.utcInstance:cu.parseSpecifier(r)||$x.create(t)}else return og(t)?cu.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new BM(t)}var Iye=()=>Date.now(),Mye="system",Pye=null,kye=null,Bye=null,qye,yn=class{static get now(){return Iye}static set now(e){Iye=e}static set defaultZone(e){Mye=e}static get defaultZone(){return Ip(Mye,kM.instance)}static get defaultLocale(){return Pye}static set defaultLocale(e){Pye=e}static get defaultNumberingSystem(){return kye}static set defaultNumberingSystem(e){kye=e}static get defaultOutputCalendar(){return Bye}static set defaultOutputCalendar(e){Bye=e}static get throwOnInvalid(){return qye}static set throwOnInvalid(e){qye=e}static resetCaches(){Hn.resetCache(),$x.resetCache()}},Uye={};function mit(t,e={}){let r=JSON.stringify([t,e]),n=Uye[r];return n||(n=new Intl.ListFormat(t,e),Uye[r]=n),n}var lJ={};function cJ(t,e={}){let r=JSON.stringify([t,e]),n=lJ[r];return n||(n=new Intl.DateTimeFormat(t,e),lJ[r]=n),n}var fJ={};function git(t,e={}){let r=JSON.stringify([t,e]),n=fJ[r];return n||(n=new Intl.NumberFormat(t,e),fJ[r]=n),n}var xJ={};function yit(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),s=xJ[i];return s||(s=new Intl.RelativeTimeFormat(t,e),xJ[i]=s),s}var h5=null;function Eit(){return h5||(h5=new Intl.DateTimeFormat().resolvedOptions().locale,h5)}function Ait(t){let e=t.indexOf("-u-");if(e===-1)return[t];{let r,n=t.substring(0,e);try{r=cJ(t).resolvedOptions()}catch{r=cJ(n).resolvedOptions()}let{numberingSystem:i,calendar:s}=r;return[n,i,s]}}function Sit(t,e,r){return(r||e)&&(t+="-u",r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function vit(t){let e=[];for(let r=1;r<=12;r++){let n=En.utc(2016,r,1);e.push(t(n))}return e}function _it(t){let e=[];for(let r=1;r<=7;r++){let n=En.utc(2016,11,13+r);e.push(t(n))}return e}function OM(t,e,r,n,i){let s=t.listingMode(r);return s==="error"?null:s==="en"?n(e):i(e)}function bit(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}var dJ=class{constructor(e,r,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:s,...o}=n;if(!r||Object.keys(o).length>0){let a={useGrouping:!1,...n};n.padTo>0&&(a.minimumIntegerDigits=n.padTo),this.inf=git(e,a)}}format(e){if(this.inf){let r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{let r=this.floor?Math.floor(e):yJ(e,3);return jn(r,this.padTo)}}},hJ=class{constructor(e,r,n){this.opts=n;let i;if(e.zone.isUniversal){let o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&$x.create(a).valid?(i=a,this.dt=e):(i="UTC",n.timeZoneName?this.dt=e:this.dt=e.offset===0?e:En.fromMillis(e.ts+e.offset*60*1e3))}else e.zone.type==="system"?this.dt=e:(this.dt=e,i=e.zone.name);let s={...this.opts};i&&(s.timeZone=i),this.dtf=cJ(r,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}},pJ=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&SEe()&&(this.rtf=yit(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):cit(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}},Hn=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,r,n,i=!1){let s=e||yn.defaultLocale,o=s||(i?"en-US":Eit()),a=r||yn.defaultNumberingSystem,u=n||yn.defaultOutputCalendar;return new t(o,a,u,s)}static resetCache(){h5=null,lJ={},fJ={},xJ={}}static fromObject({locale:e,numberingSystem:r,outputCalendar:n}={}){return t.create(e,r,n)}constructor(e,r,n,i){let[s,o,a]=Ait(e);this.locale=s,this.numberingSystem=r||o||null,this.outputCalendar=n||a||null,this.intl=Sit(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=bit(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,r=!1,n=!0){return OM(this,e,n,CEe,()=>{let i=r?{month:e,day:"numeric"}:{month:e},s=r?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=vit(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,r=!1,n=!0){return OM(this,e,n,DEe,()=>{let i=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=r?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=_it(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return OM(this,void 0,e,()=>NEe,()=>{if(!this.meridiemCache){let r={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[En.utc(2016,11,13,9),En.utc(2016,11,13,19)].map(n=>this.extract(n,r,"dayperiod"))}return this.meridiemCache})}eras(e,r=!0){return OM(this,e,r,FEe,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[En.utc(-40,1,1),En.utc(2017,1,1)].map(i=>this.extract(i,n,"era"))),this.eraCache[e]})}extract(e,r,n){let i=this.dtFormatter(e,r),s=i.formatToParts(),o=s.find(a=>a.type.toLowerCase()===n);return o?o.value:null}numberFormatter(e={}){return new dJ(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new hJ(e,this.intl,r)}relFormatter(e={}){return new pJ(this.intl,this.isEnglish(),e)}listFormatter(e={}){return mit(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}};function $S(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function jS(...t){return e=>t.reduce(([r,n,i],s)=>{let[o,a,u]=s(e,i);return[{...r,...o},a||n,u]},[{},null,1]).slice(0,2)}function HS(t,...e){if(t==null)return[null,null];for(let[r,n]of e){let i=r.exec(t);if(i)return n(i)}return[null,null]}function wEe(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=Lp(e[r+i]);return[n,null,r+i]}}var LEe=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Tit=`(?:${LEe.source}?(?:\\[(${bEe.source})\\])?)?`,AJ=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,IEe=RegExp(`${AJ.source}${Tit}`),SJ=RegExp(`(?:T${IEe.source})?`),Cit=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Rit=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Oit=/(\d{4})-?(\d{3})/,Dit=wEe("weekYear","weekNumber","weekDay"),Nit=wEe("year","ordinal"),Fit=/(\d{4})-(\d\d)-(\d\d)/,MEe=RegExp(`${AJ.source} ?(?:${LEe.source}|(${bEe.source}))?`),wit=RegExp(`(?: ${MEe.source})?`);function qS(t,e,r){let n=t[e];return kt(n)?r:Lp(n)}function Lit(t,e){return[{year:qS(t,e),month:qS(t,e+1,1),day:qS(t,e+2,1)},null,e+3]}function zS(t,e){return[{hours:qS(t,e,0),minutes:qS(t,e+1,0),seconds:qS(t,e+2,0),milliseconds:gJ(t[e+3])},null,e+4]}function y5(t,e){let r=!t[e]&&!t[e+1],n=UM(t[e+1],t[e+2]),i=r?null:cu.instance(n);return[{},i,e+3]}function E5(t,e){let r=t[e]?$x.create(t[e]):null;return[{},r,e+1]}var Iit=RegExp(`^T?${AJ.source}$`),Mit=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function Pit(t){let[e,r,n,i,s,o,a,u,l]=t,c=e[0]==="-",f=u&&u[0]==="-",x=(d,h=!1)=>d!==void 0&&(h||d&&c)?-d:d;return[{years:x(tg(r)),months:x(tg(n)),weeks:x(tg(i)),days:x(tg(s)),hours:x(tg(o)),minutes:x(tg(a)),seconds:x(tg(u),u==="-0"),milliseconds:x(gJ(l),f)}]}var kit={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function vJ(t,e,r,n,i,s,o){let a={year:e.length===2?uJ(Lp(e)):Lp(e),month:TEe.indexOf(r)+1,day:Lp(n),hour:Lp(i),minute:Lp(s)};return o&&(a.second=Lp(o)),t&&(a.weekday=t.length>3?REe.indexOf(t)+1:OEe.indexOf(t)+1),a}var Bit=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function qit(t){let[,e,r,n,i,s,o,a,u,l,c,f]=t,x=vJ(e,i,n,r,s,o,a),d;return u?d=kit[u]:l?d=0:d=UM(c,f),[x,new cu(d)]}function Uit(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var $it=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,jit=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Hit=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function $ye(t){let[,e,r,n,i,s,o,a]=t;return[vJ(e,i,n,r,s,o,a),cu.utcInstance]}function zit(t){let[,e,r,n,i,s,o,a]=t;return[vJ(e,a,r,n,i,s,o),cu.utcInstance]}var Git=$S(Cit,SJ),Qit=$S(Rit,SJ),Vit=$S(Oit,SJ),Wit=$S(IEe),PEe=jS(Lit,zS,y5,E5),Yit=jS(Dit,zS,y5,E5),Kit=jS(Nit,zS,y5,E5),Xit=jS(zS,y5,E5);function Jit(t){return HS(t,[Git,PEe],[Qit,Yit],[Vit,Kit],[Wit,Xit])}function Zit(t){return HS(Uit(t),[Bit,qit])}function est(t){return HS(t,[$it,$ye],[jit,$ye],[Hit,zit])}function tst(t){return HS(t,[Mit,Pit])}var rst=jS(zS);function nst(t){return HS(t,[Iit,rst])}var ist=$S(Fit,wit),sst=$S(MEe),ost=jS(zS,y5,E5);function ast(t){return HS(t,[ist,PEe],[sst,ost])}var ust="Invalid Duration",kEe={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},lst={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...kEe},rl=146097/400,BS=146097/4800,cst={years:{quarters:4,months:12,weeks:rl/7,days:rl,hours:rl*24,minutes:rl*24*60,seconds:rl*24*60*60,milliseconds:rl*24*60*60*1e3},quarters:{months:3,weeks:rl/28,days:rl/4,hours:rl*24/4,minutes:rl*24*60/4,seconds:rl*24*60*60/4,milliseconds:rl*24*60*60*1e3/4},months:{weeks:BS/7,days:BS,hours:BS*24,minutes:BS*24*60,seconds:BS*24*60*60,milliseconds:BS*24*60*60*1e3},...kEe},ng=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],fst=ng.slice(0).reverse();function rg(t,e,r=!1){let n={values:r?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy};return new ci(n)}function xst(t){return t<0?Math.floor(t):Math.ceil(t)}function BEe(t,e,r,n,i){let s=t[i][r],o=e[r]/s,a=Math.sign(o)===Math.sign(n[i]),u=!a&&n[i]!==0&&Math.abs(o)<=1?xst(o):Math.trunc(o);n[i]+=u,e[r]-=u*s}function dst(t,e){fst.reduce((r,n)=>kt(e[n])?r:(r&&BEe(t,e,r,e,n),n),null)}var ci=class t{constructor(e){let r=e.conversionAccuracy==="longterm"||!1;this.values=e.values,this.loc=e.loc||Hn.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=r?cst:lst,this.isLuxonDuration=!0}static fromMillis(e,r){return t.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new xa(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:PM(e,t.normalizeUnit),loc:Hn.fromObject(r),conversionAccuracy:r.conversionAccuracy})}static fromDurationLike(e){if(og(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new xa(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){let[n]=tst(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){let[n]=nst(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new xa("need to specify a reason the Duration is invalid");let n=e instanceof uu?e:new uu(e,r);if(yn.throwOnInvalid)throw new oJ(n);return new t({invalid:n})}static normalizeUnit(e){let r={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!r)throw new LM(e);return r}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,r={}){let n={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?a0.create(this.loc,n).formatDurationFromString(this,e):ust}toHuman(e={}){let r=ng.map(n=>{let i=this.values[n];return kt(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(r)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=yJ(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let r=this.toMillis();if(r<0||r>=864e5)return null;e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e};let n=this.shiftTo("hours","minutes","seconds","milliseconds"),i=e.format==="basic"?"hhmm":"hh:mm";(!e.suppressSeconds||n.seconds!==0||n.milliseconds!==0)&&(i+=e.format==="basic"?"ss":":ss",(!e.suppressMilliseconds||n.milliseconds!==0)&&(i+=".SSS"));let s=n.toFormat(i);return e.includePrefix&&(s="T"+s),s}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.as("milliseconds")}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e),n={};for(let i of ng)(US(r.values,i)||US(this.values,i))&&(n[i]=r.get(i)+this.get(i));return rg(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;let r={};for(let n of Object.keys(this.values))r[n]=_Ee(e(this.values[n],n));return rg(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...PM(e,t.normalizeUnit)};return rg(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r}),s={loc:i};return n&&(s.conversionAccuracy=n),rg(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return dst(this.matrix,e),rg(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>t.normalizeUnit(o));let r={},n={},i=this.toObject(),s;for(let o of ng)if(e.indexOf(o)>=0){s=o;let a=0;for(let l in n)a+=this.matrix[l][o]*n[l],n[l]=0;og(i[o])&&(a+=i[o]);let u=Math.trunc(a);r[o]=u,n[o]=(a*1e3-u*1e3)/1e3;for(let l in i)ng.indexOf(l)>ng.indexOf(o)&&BEe(this.matrix,i,l,r,o)}else og(i[o])&&(n[o]=i[o]);for(let o in n)n[o]!==0&&(r[s]+=o===s?n[o]:n[o]/this.matrix[s][o]);return rg(this,{values:r},!0).normalize()}negate(){if(!this.isValid)return this;let e={};for(let r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return rg(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function r(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of ng)if(!r(this.values[n],e.values[n]))return!1;return!0}},c5="Invalid Interval";function hst(t,e){return!t||!t.isValid?ag.invalid("missing or invalid start"):!e||!e.isValid?ag.invalid("missing or invalid end"):e<t?ag.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var ag=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new xa("need to specify a reason the Interval is invalid");let n=e instanceof uu?e:new uu(e,r);if(yn.throwOnInvalid)throw new sJ(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=d5(e),i=d5(r),s=hst(n,i);return s??new t({start:n,end:i})}static after(e,r){let n=ci.fromDurationLike(r),i=d5(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=ci.fromDurationLike(r),i=d5(e);return t.fromDateTimes(i.minus(n),i)}static fromISO(e,r){let[n,i]=(e||"").split("/",2);if(n&&i){let s,o;try{s=En.fromISO(n,r),o=s.isValid}catch{o=!1}let a,u;try{a=En.fromISO(i,r),u=a.isValid}catch{u=!1}if(o&&u)return t.fromDateTimes(s,a);if(o){let l=ci.fromISO(i,r);if(l.isValid)return t.after(s,l)}else if(u){let l=ci.fromISO(n,r);if(l.isValid)return t.before(a,l)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds"){if(!this.isValid)return NaN;let r=this.start.startOf(e),n=this.end.startOf(e);return Math.floor(n.diff(r,e).get(e))+1}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:r}={}){return this.isValid?t.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];let r=e.map(d5).filter(o=>this.contains(o)).sort(),n=[],{s:i}=this,s=0;for(;i<this.e;){let o=r[s]||this.e,a=+o>+this.e?this.e:o;n.push(t.fromDateTimes(i,a)),i=a,s+=1}return n}splitBy(e){let r=ci.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:n}=this,i=1,s,o=[];for(;n<this.e;){let a=this.start.plus(r.mapUnits(u=>u*i));s=+a>+this.e?this.e:a,o.push(t.fromDateTimes(n,s)),n=s,i+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let r=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return r>=n?null:t.fromDateTimes(r,n)}union(e){if(!this.isValid)return this;let r=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return t.fromDateTimes(r,n)}static merge(e){let[r,n]=e.sort((i,s)=>i.s-s.s).reduce(([i,s],o)=>s?s.overlaps(o)||s.abutsStart(o)?[i,s.union(o)]:[i.concat([s]),o]:[i,o],[[],null]);return n&&r.push(n),r}static xor(e){let r=null,n=0,i=[],s=e.map(u=>[{time:u.s,type:"s"},{time:u.e,type:"e"}]),o=Array.prototype.concat(...s),a=o.sort((u,l)=>u.time-l.time);for(let u of a)n+=u.type==="s"?1:-1,n===1?r=u.time:(r&&+r!=+u.time&&i.push(t.fromDateTimes(r,u.time)),r=null);return t.merge(i)}difference(...e){return t.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:c5}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:c5}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:c5}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:c5}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:c5}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):ci.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}},sg=class{static hasDST(e=yn.defaultZone){let r=En.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return $x.isValidZone(e)}static normalizeZone(e){return Ip(e,yn.defaultZone)}static months(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||Hn.create(r,n,s)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||Hn.create(r,n,s)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||Hn.create(r,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||Hn.create(r,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return Hn.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return Hn.create(r,null,"gregory").eras(e)}static features(){return{relative:SEe()}}};function jye(t,e){let r=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=r(e)-r(t);return Math.floor(ci.fromMillis(n).as("days"))}function pst(t,e,r){let n=[["years",(a,u)=>u.year-a.year],["quarters",(a,u)=>u.quarter-a.quarter],["months",(a,u)=>u.month-a.month+(u.year-a.year)*12],["weeks",(a,u)=>{let l=jye(a,u);return(l-l%7)/7}],["days",jye]],i={},s,o;for(let[a,u]of n)if(r.indexOf(a)>=0){s=a;let l=u(t,e);o=t.plus({[a]:l}),o>e?(t=t.plus({[a]:l-1}),l-=1):t=o,i[a]=l}return[t,i,o,s]}function mst(t,e,r,n){let[i,s,o,a]=pst(t,e,r),u=e-i,l=r.filter(f=>["hours","minutes","seconds","milliseconds"].indexOf(f)>=0);l.length===0&&(o<e&&(o=i.plus({[a]:1})),o!==i&&(s[a]=(s[a]||0)+u/(o-i)));let c=ci.fromObject(s,n);return l.length>0?ci.fromMillis(u,n).shiftTo(...l).plus(c):c}var _J={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Hye={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},gst=_J.hanidec.replace(/[\[|\]]/g,"").split("");function yst(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(t[r].search(_J.hanidec)!==-1)e+=gst.indexOf(t[r]);else for(let i in Hye){let[s,o]=Hye[i];n>=s&&n<=o&&(e+=n-s)}}return parseInt(e,10)}else return e}function s0({numberingSystem:t},e=""){return new RegExp(`${_J[t||"latn"]}${e}`)}var Est="missing Intl.DateTimeFormat.formatToParts support";function Yt(t,e=r=>r){return{regex:t,deser:([r])=>e(yst(r))}}var Ast="\xA0",qEe=`[ ${Ast}]`,UEe=new RegExp(qEe,"g");function Sst(t){return t.replace(/\./g,"\\.?").replace(UEe,qEe)}function zye(t){return t.replace(/\./g,"").replace(UEe," ").toLowerCase()}function o0(t,e){return t===null?null:{regex:RegExp(t.map(Sst).join("|")),deser:([r])=>t.findIndex(n=>zye(r)===zye(n))+e}}function Gye(t,e){return{regex:t,deser:([,r,n])=>UM(r,n),groups:e}}function JX(t){return{regex:t,deser:([e])=>e}}function vst(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function _st(t,e){let r=s0(e),n=s0(e,"{2}"),i=s0(e,"{3}"),s=s0(e,"{4}"),o=s0(e,"{6}"),a=s0(e,"{1,2}"),u=s0(e,"{1,3}"),l=s0(e,"{1,6}"),c=s0(e,"{1,9}"),f=s0(e,"{2,4}"),x=s0(e,"{4,6}"),d=m=>({regex:RegExp(vst(m.val)),deser:([g])=>g,literal:!0}),p=(m=>{if(t.literal)return d(m);switch(m.val){case"G":return o0(e.eras("short",!1),0);case"GG":return o0(e.eras("long",!1),0);case"y":return Yt(l);case"yy":return Yt(f,uJ);case"yyyy":return Yt(s);case"yyyyy":return Yt(x);case"yyyyyy":return Yt(o);case"M":return Yt(a);case"MM":return Yt(n);case"MMM":return o0(e.months("short",!0,!1),1);case"MMMM":return o0(e.months("long",!0,!1),1);case"L":return Yt(a);case"LL":return Yt(n);case"LLL":return o0(e.months("short",!1,!1),1);case"LLLL":return o0(e.months("long",!1,!1),1);case"d":return Yt(a);case"dd":return Yt(n);case"o":return Yt(u);case"ooo":return Yt(i);case"HH":return Yt(n);case"H":return Yt(a);case"hh":return Yt(n);case"h":return Yt(a);case"mm":return Yt(n);case"m":return Yt(a);case"q":return Yt(a);case"qq":return Yt(n);case"s":return Yt(a);case"ss":return Yt(n);case"S":return Yt(u);case"SSS":return Yt(i);case"u":return JX(c);case"uu":return JX(a);case"uuu":return Yt(r);case"a":return o0(e.meridiems(),0);case"kkkk":return Yt(s);case"kk":return Yt(f,uJ);case"W":return Yt(a);case"WW":return Yt(n);case"E":case"c":return Yt(r);case"EEE":return o0(e.weekdays("short",!1,!1),1);case"EEEE":return o0(e.weekdays("long",!1,!1),1);case"ccc":return o0(e.weekdays("short",!0,!1),1);case"cccc":return o0(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return Gye(new RegExp(`([+-]${a.source})(?::(${n.source}))?`),2);case"ZZZ":return Gye(new RegExp(`([+-]${a.source})(${n.source})?`),2);case"z":return JX(/[a-z_+-/]{1,256}?/i);default:return d(m)}})(t)||{invalidReason:Est};return p.token=t,p}var bst={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour:{numeric:"h","2-digit":"hh"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"}};function Tst(t,e,r){let{type:n,value:i}=t;if(n==="literal")return{literal:!0,val:i};let s=r[n],o=bst[n];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function Cst(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function Rst(t,e,r){let n=t.match(e);if(n){let i={},s=1;for(let o in r)if(US(r,o)){let a=r[o],u=a.groups?a.groups+1:1;!a.literal&&a.token&&(i[a.token.val[0]]=a.deser(n.slice(s,s+u))),s+=u}return[n,i]}else return[n,{}]}function Ost(t){let e=s=>{switch(s){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},r=null,n;return kt(t.z)||(r=$x.create(t.z)),kt(t.Z)||(r||(r=new cu(t.Z)),n=t.Z),kt(t.q)||(t.M=(t.q-1)*3+1),kt(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),kt(t.u)||(t.S=gJ(t.u)),[Object.keys(t).reduce((s,o)=>{let a=e(o);return a&&(s[a]=t[o]),s},{}),r,n]}var ZX=null;function Dst(){return ZX||(ZX=En.fromMillis(1555555555555)),ZX}function Nst(t,e){if(t.literal)return t;let r=a0.macroTokenToFormatOpts(t.val);if(!r)return t;let s=a0.create(e,r).formatDateTimeParts(Dst()).map(o=>Tst(o,e,r));return s.includes(void 0)?t:s}function Fst(t,e){return Array.prototype.concat(...t.map(r=>Nst(r,e)))}function $Ee(t,e,r){let n=Fst(a0.parseFormat(r),t),i=n.map(o=>_st(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:n,invalidReason:s.invalidReason};{let[o,a]=Cst(i),u=RegExp(o,"i"),[l,c]=Rst(e,u,a),[f,x,d]=c?Ost(c):[null,null,void 0];if(US(c,"a")&&US(c,"H"))throw new ig("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:u,rawMatches:l,matches:c,result:f,zone:x,specificOffset:d}}}function wst(t,e,r){let{result:n,zone:i,specificOffset:s,invalidReason:o}=$Ee(t,e,r);return[n,i,s,o]}var jEe=[0,31,59,90,120,151,181,212,243,273,304,334],HEe=[0,31,60,91,121,152,182,213,244,274,305,335];function nl(t,e){return new uu("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function zEe(t,e,r){let n=new Date(Date.UTC(t,e-1,r));t<100&&t>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function GEe(t,e,r){return r+(g5(t)?HEe:jEe)[e-1]}function QEe(t,e){let r=g5(t)?HEe:jEe,n=r.findIndex(s=>s<e),i=e-r[n];return{month:n+1,day:i}}function mJ(t){let{year:e,month:r,day:n}=t,i=GEe(e,r,n),s=zEe(e,r,n),o=Math.floor((i-s+10)/7),a;return o<1?(a=e-1,o=MM(a)):o>MM(e)?(a=e+1,o=1):a=e,{weekYear:a,weekNumber:o,weekday:s,...$M(t)}}function Qye(t){let{weekYear:e,weekNumber:r,weekday:n}=t,i=zEe(e,1,4),s=p5(e),o=r*7+n-i-3,a;o<1?(a=e-1,o+=p5(a)):o>s?(a=e+1,o-=p5(e)):a=e;let{month:u,day:l}=QEe(a,o);return{year:a,month:u,day:l,...$M(t)}}function eJ(t){let{year:e,month:r,day:n}=t,i=GEe(e,r,n);return{year:e,ordinal:i,...$M(t)}}function Vye(t){let{year:e,ordinal:r}=t,{month:n,day:i}=QEe(e,r);return{year:e,month:n,day:i,...$M(t)}}function Lst(t){let e=qM(t.weekYear),r=qx(t.weekNumber,1,MM(t.weekYear)),n=qx(t.weekday,1,7);return e?r?n?!1:nl("weekday",t.weekday):nl("week",t.week):nl("weekYear",t.weekYear)}function Ist(t){let e=qM(t.year),r=qx(t.ordinal,1,p5(t.year));return e?r?!1:nl("ordinal",t.ordinal):nl("year",t.year)}function VEe(t){let e=qM(t.year),r=qx(t.month,1,12),n=qx(t.day,1,IM(t.year,t.month));return e?r?n?!1:nl("day",t.day):nl("month",t.month):nl("year",t.year)}function WEe(t){let{hour:e,minute:r,second:n,millisecond:i}=t,s=qx(e,0,23)||e===24&&r===0&&n===0&&i===0,o=qx(r,0,59),a=qx(n,0,59),u=qx(i,0,999);return s?o?a?u?!1:nl("millisecond",i):nl("second",n):nl("minute",r):nl("hour",e)}var tJ="Invalid DateTime",Wye=864e13;function DM(t){return new uu("unsupported zone",`the zone "${t.name}" is not supported`)}function rJ(t){return t.weekData===null&&(t.weekData=mJ(t.c)),t.weekData}function f5(t,e){let r={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new En({...r,...e,old:r})}function YEe(t,e,r){let n=t-e*60*1e3,i=r.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let s=r.offset(n);return i===s?[n,i]:[t-Math.min(i,s)*60*1e3,Math.max(i,s)]}function Yye(t,e){t+=e*60*1e3;let r=new Date(t);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function wM(t,e,r){return YEe(EJ(t),e,r)}function Kye(t,e){let r=t.o,n=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,s={...t.c,year:n,month:i,day:Math.min(t.c.day,IM(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=ci.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=EJ(s),[u,l]=YEe(a,r,t.zone);return o!==0&&(u+=o,l=t.zone.offset(u)),{ts:u,o:l}}function x5(t,e,r,n,i,s){let{setZone:o,zone:a}=r;if(t&&Object.keys(t).length!==0){let u=e||a,l=En.fromObject(t,{...r,zone:u,specificOffset:s});return o?l:l.setZone(a)}else return En.invalid(new uu("unparsable",`the input "${i}" can't be parsed as ${n}`))}function NM(t,e,r=!0){return t.isValid?a0.create(Hn.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function nJ(t,e){let r=t.c.year>9999||t.c.year<0,n="";return r&&t.c.year>=0&&(n+="+"),n+=jn(t.c.year,r?6:4),e?(n+="-",n+=jn(t.c.month),n+="-",n+=jn(t.c.day)):(n+=jn(t.c.month),n+=jn(t.c.day)),n}function Xye(t,e,r,n,i,s){let o=jn(t.c.hour);return e?(o+=":",o+=jn(t.c.minute),(t.c.second!==0||!r)&&(o+=":")):o+=jn(t.c.minute),(t.c.second!==0||!r)&&(o+=jn(t.c.second),(t.c.millisecond!==0||!n)&&(o+=".",o+=jn(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!s?o+="Z":t.o<0?(o+="-",o+=jn(Math.trunc(-t.o/60)),o+=":",o+=jn(Math.trunc(-t.o%60))):(o+="+",o+=jn(Math.trunc(t.o/60)),o+=":",o+=jn(Math.trunc(t.o%60)))),s&&(o+="["+t.zone.ianaName+"]"),o}var KEe={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Mst={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Pst={ordinal:1,hour:0,minute:0,second:0,millisecond:0},XEe=["year","month","day","hour","minute","second","millisecond"],kst=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Bst=["year","ordinal","hour","minute","second","millisecond"];function Jye(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new LM(t);return e}function Zye(t,e){let r=Ip(e.zone,yn.defaultZone),n=Hn.fromObject(e),i=yn.now(),s,o;if(kt(t.year))s=i;else{for(let l of XEe)kt(t[l])&&(t[l]=KEe[l]);let a=VEe(t)||WEe(t);if(a)return En.invalid(a);let u=r.offset(i);[s,o]=wM(t,u,r)}return new En({ts:s,zone:r,loc:n,o})}function eEe(t,e,r){let n=kt(r.round)?!0:r.round,i=(o,a)=>(o=yJ(o,n||r.calendary?0:2,!0),e.loc.clone(r).relFormatter(r).format(o,a)),s=o=>r.calendary?e.hasSame(t,o)?0:e.startOf(o).diff(t.startOf(o),o).get(o):e.diff(t,o).get(o);if(r.unit)return i(s(r.unit),r.unit);for(let o of r.units){let a=s(o);if(Math.abs(a)>=1)return i(a,o)}return i(t>e?-0:0,r.units[r.units.length-1])}function tEe(t){let e={},r;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],r=Array.from(t).slice(0,t.length-1)):r=Array.from(t),[e,r]}var En=class t{constructor(e){let r=e.zone||yn.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new uu("invalid input"):null)||(r.isValid?null:DM(r));this.ts=kt(e.ts)?yn.now():e.ts;let i=null,s=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[i,s]=[e.old.c,e.old.o];else{let a=r.offset(this.ts);i=Yye(this.ts,a),n=Number.isNaN(i.year)?new uu("invalid input"):null,i=n?null:i,s=n?null:a}this._zone=r,this.loc=e.loc||Hn.create(),this.invalid=n,this.weekData=null,this.c=i,this.o=s,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,r]=tEe(arguments),[n,i,s,o,a,u,l]=r;return Zye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static utc(){let[e,r]=tEe(arguments),[n,i,s,o,a,u,l]=r;return e.zone=cu.utcInstance,Zye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static fromJSDate(e,r={}){let n=Knt(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=Ip(r.zone,yn.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:Hn.fromObject(r)}):t.invalid(DM(i))}static fromMillis(e,r={}){if(og(e))return e<-Wye||e>Wye?t.invalid("Timestamp out of range"):new t({ts:e,zone:Ip(r.zone,yn.defaultZone),loc:Hn.fromObject(r)});throw new xa(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(og(e))return new t({ts:e*1e3,zone:Ip(r.zone,yn.defaultZone),loc:Hn.fromObject(r)});throw new xa("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=Ip(r.zone,yn.defaultZone);if(!n.isValid)return t.invalid(DM(n));let i=yn.now(),s=kt(r.specificOffset)?n.offset(i):r.specificOffset,o=PM(e,Jye),a=!kt(o.ordinal),u=!kt(o.year),l=!kt(o.month)||!kt(o.day),c=u||l,f=o.weekYear||o.weekNumber,x=Hn.fromObject(r);if((c||a)&&f)throw new ig("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&a)throw new ig("Can't mix ordinal dates with month/day");let d=f||o.weekday&&!c,h,p,m=Yye(i,s);d?(h=kst,p=Mst,m=mJ(m)):a?(h=Bst,p=Pst,m=eJ(m)):(h=XEe,p=KEe);let g=!1;for(let R of h){let D=o[R];kt(D)?g?o[R]=p[R]:o[R]=m[R]:g=!0}let y=d?Lst(o):a?Ist(o):VEe(o),A=y||WEe(o);if(A)return t.invalid(A);let S=d?Qye(o):a?Vye(o):o,[T,b]=wM(S,s,n),_=new t({ts:T,zone:n,o:b,loc:x});return o.weekday&&c&&e.weekday!==_.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${_.toISO()}`):_}static fromISO(e,r={}){let[n,i]=Jit(e);return x5(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=Zit(e);return x5(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=est(e);return x5(n,i,r,"HTTP",r)}static fromFormat(e,r,n={}){if(kt(e)||kt(r))throw new xa("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:s=null}=n,o=Hn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0}),[a,u,l,c]=wst(o,e,r);return c?t.invalid(c):x5(a,u,n,`format ${r}`,e,l)}static fromString(e,r,n={}){return t.fromFormat(e,r,n)}static fromSQL(e,r={}){let[n,i]=ast(e);return x5(n,i,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new xa("need to specify a reason the DateTime is invalid");let n=e instanceof uu?e:new uu(e,r);if(yn.throwOnInvalid)throw new iJ(n);return new t({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?rJ(this).weekYear:NaN}get weekNumber(){return this.isValid?rJ(this).weekNumber:NaN}get weekday(){return this.isValid?rJ(this).weekday:NaN}get ordinal(){return this.isValid?eJ(this.c).ordinal:NaN}get monthShort(){return this.isValid?sg.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?sg.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?sg.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?sg.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}get isInLeapYear(){return g5(this.year)}get daysInMonth(){return IM(this.year,this.month)}get daysInYear(){return this.isValid?p5(this.year):NaN}get weeksInWeekYear(){return this.isValid?MM(this.weekYear):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=a0.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:n,outputCalendar:i}}toUTC(e=0,r={}){return this.setZone(cu.instance(e),r)}toLocal(){return this.setZone(yn.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:n=!1}={}){if(e=Ip(e,yn.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(r||n){let s=e.offset(this.ts),o=this.toObject();[i]=wM(o,s,e)}return f5(this,{ts:i,zone:e})}else return t.invalid(DM(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return f5(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=PM(e,Jye),n=!kt(r.weekYear)||!kt(r.weekNumber)||!kt(r.weekday),i=!kt(r.ordinal),s=!kt(r.year),o=!kt(r.month)||!kt(r.day),a=s||o,u=r.weekYear||r.weekNumber;if((a||i)&&u)throw new ig("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new ig("Can't mix ordinal dates with month/day");let l;n?l=Qye({...mJ(this.c),...r}):kt(r.ordinal)?(l={...this.toObject(),...r},kt(r.day)&&(l.day=Math.min(IM(l.year,l.month),l.day))):l=Vye({...eJ(this.c),...r});let[c,f]=wM(l,this.o,this.zone);return f5(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e);return f5(this,Kye(this,r))}minus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e).negate();return f5(this,Kye(this,r))}startOf(e){if(!this.isValid)return this;let r={},n=ci.normalizeUnit(e);switch(n){case"years":r.month=1;case"quarters":case"months":r.day=1;case"weeks":case"days":r.hour=0;case"hours":r.minute=0;case"minutes":r.second=0;case"seconds":r.millisecond=0;break}if(n==="weeks"&&(r.weekday=1),n==="quarters"){let i=Math.ceil(this.month/3);r.month=(i-1)*3+1}return this.set(r)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,r={}){return this.isValid?a0.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):tJ}toLocaleString(e=aJ,r={}){return this.isValid?a0.create(this.loc.clone(r),e).formatDateTime(this):tJ}toLocaleParts(e={}){return this.isValid?a0.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:s=!1}={}){if(!this.isValid)return null;let o=e==="extended",a=nJ(this,o);return a+="T",a+=Xye(this,o,r,n,i,s),a}toISODate({format:e="extended"}={}){return this.isValid?nJ(this,e==="extended"):null}toISOWeekDate(){return NM(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:s=!1,format:o="extended"}={}){return this.isValid?(i?"T":"")+Xye(this,o==="extended",r,e,n,s):null}toRFC2822(){return NM(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return NM(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?nJ(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(r||e)&&(n&&(i+=" "),r?i+="z":e&&(i+="ZZ")),NM(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():tJ}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",n={}){if(!this.isValid||!e.isValid)return ci.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},s=Xnt(r).map(ci.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,u=o?e:this,l=mst(a,u,s,i);return o?l.negate():l}diffNow(e="milliseconds",r={}){return this.diff(t.now(),e,r)}until(e){return this.isValid?ag.fromDateTimes(this,e):this}hasSame(e,r){if(!this.isValid)return!1;let n=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(r)<=n&&n<=i.endOf(r)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let r=e.base||t.fromObject({},{zone:this.zone}),n=e.padding?this<r?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],s=e.unit;return Array.isArray(e.unit)&&(i=e.unit,s=void 0),eEe(r,this.plus(n),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?eEe(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new xa("min requires all arguments be DateTimes");return wye(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new xa("max requires all arguments be DateTimes");return wye(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,n={}){let{locale:i=null,numberingSystem:s=null}=n,o=Hn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0});return $Ee(o,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static get DATE_SHORT(){return aJ}static get DATE_MED(){return rEe}static get DATE_MED_WITH_WEEKDAY(){return Vnt}static get DATE_FULL(){return nEe}static get DATE_HUGE(){return iEe}static get TIME_SIMPLE(){return sEe}static get TIME_WITH_SECONDS(){return oEe}static get TIME_WITH_SHORT_OFFSET(){return aEe}static get TIME_WITH_LONG_OFFSET(){return uEe}static get TIME_24_SIMPLE(){return lEe}static get TIME_24_WITH_SECONDS(){return cEe}static get TIME_24_WITH_SHORT_OFFSET(){return fEe}static get TIME_24_WITH_LONG_OFFSET(){return xEe}static get DATETIME_SHORT(){return dEe}static get DATETIME_SHORT_WITH_SECONDS(){return hEe}static get DATETIME_MED(){return pEe}static get DATETIME_MED_WITH_SECONDS(){return mEe}static get DATETIME_MED_WITH_WEEKDAY(){return Wnt}static get DATETIME_FULL(){return gEe}static get DATETIME_FULL_WITH_SECONDS(){return yEe}static get DATETIME_HUGE(){return EEe}static get DATETIME_HUGE_WITH_SECONDS(){return AEe}};function d5(t){if(En.isDateTime(t))return t;if(t&&t.valueOf&&og(t.valueOf()))return En.fromJSDate(t);if(t&&typeof t=="object")return En.fromObject(t);throw new xa(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var qst="2.5.2";fu.DateTime=En;fu.Duration=ci;fu.FixedOffsetZone=cu;fu.IANAZone=$x;fu.Info=sg;fu.Interval=ag;fu.InvalidZone=BM;fu.Settings=yn;fu.SystemZone=kM;fu.VERSION=qst;fu.Zone=Mp});var nAe=v(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.LiteralYear=ki.LiteralQuarter=ki.LiteralMonth=ki.LiteralWeek=ki.LiteralDay=ki.LiteralHour=ki.LiteralTimestamp=ki.TimeFormatError=void 0;var Pp=bJ(),Ust=Ke(),$st=IS(),JEe=TI(),TJ=ir(),CJ=class extends Error{};ki.TimeFormatError=CJ;function lg(t,e){let r=t.slice(1);if(e){let n=r.match(/\[[^\]]+]$/);if(n)return{tzSpec:n[0].slice(1,-1),text:r.slice(0,-n[0].length)}}return{text:r}}var ZEe="yyyy",eAe=`${ZEe}-LL`,il=`${eAe}-dd`,tAe=`${il} HH`,rAe=`${tAe}:mm`,RJ=`${rAe}:ss`,jM=class extends TJ.ExpressionDef{constructor(e,r,n){super(),this.units=r,this.timeType=n,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){let n={type:"dialect",function:"timeLiteral",literal:e,literalType:r};return this.timeZone&&(n.timezone=this.timeZone),n}makeValue(e,r){let n=this.makeLiteral(e,r),i="scalar",s=[n];return this.units?{dataType:r,expressionType:i,value:s,timeframe:this.units,evalSpace:"literal"}:{dataType:r,expressionType:i,value:s,evalSpace:"literal"}}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}},OJ=class t extends jM{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r,n=lg(e,!0);e=n.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),n.text=e);let i=e.match(/^([^.,]+)[,.](\d+)$/);i&&(e=i[1]);let s=Pp.DateTime.fromFormat(e,RJ);if(s.isValid)return new t(n,r);if(s=Pp.DateTime.fromFormat(e,rAe),s.isValid){n.text=n.text+":00",r="minute";let o=s.plus({minute:1}).toFormat(RJ);return new A5(n,r,"timestamp",o)}}};ki.LiteralTimestamp=OJ;var A5=class extends jM{constructor(e,r,n,i){super(e,r,n),this.nextLit=i,this.elementType="granularTimeLiteral"}apply(e,r,n){let i=this.getExpression(e),s=this.getNext();if(s){let o=n.getExpression(e);if(o.dataType==="timestamp"){let a=(0,TJ.getMorphicValue)(i,"timestamp"),u=(0,TJ.getMorphicValue)(s,"timestamp");if(a&&u)i=a,s=u;else return super.apply(e,r,n)}if((0,Ust.isTimeFieldType)(o.dataType)){let a=o.dataType;return new $st.Range(new JEe.ExprTime(a,i.value),new JEe.ExprTime(a,s.value)).apply(e,r,n)}}return super.apply(e,r,n)}},DJ=class t extends A5{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){let r=lg(e,!1),n=r.text,i=Pp.DateTime.fromFormat(r.text,tAe);if(i.isValid)return r.text=r.text+":00:00",n=i.plus({hour:1}).toFormat(RJ),new t(r,n)}};ki.LiteralHour=DJ;var ug=class extends A5{constructor(e,r,n){super(e,r,"date",n)}getExpression(e){let r=this.makeValue(this.literalPart,"date"),n=[this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp")];return{...r,morphic:{timestamp:n},evalSpace:"literal"}}getNext(){let e=this.makeValue(this.nextLit,"date"),r=[this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp")];return{...e,morphic:{timestamp:r}}}},NJ=class t extends ug{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){let r=lg(e,!1),n=r.text,i=Pp.DateTime.fromFormat(r.text,il);if(i.isValid)return n=i.plus({day:1}).toFormat(il),new t(r,n)}};ki.LiteralDay=NJ;var FJ=class t extends ug{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){let r=lg(e,!1),n=r.text,i=r.text.slice(0,10),s=Pp.DateTime.fromFormat(i,il);if(s.isValid&&s.weekday===7){let a=s.plus({days:7});return r.text=s.toFormat(il),n=a.toFormat(il),new t(r,n)}}};ki.LiteralWeek=FJ;var wJ=class t extends ug{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){let r=lg(e,!1),n=r.text,i=Pp.DateTime.fromFormat(r.text,eAe);if(i.isValid){let s=i.plus({months:1});return r.text=i.toFormat(il),n=s.toFormat(il),new t(r,n)}}};ki.LiteralMonth=wJ;var LJ=class t extends ug{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){let r=lg(e,!1),n=r.text,i=r.text.match(/(^\d{4})-[qQ](\d)$/);if(i){let s=Number.parseInt(i[2])-1,o=Pp.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));let a=o.plus({quarter:1});return r.text=o.toFormat(il),n=a.toFormat(il),new t(r,n)}}};ki.LiteralQuarter=LJ;var IJ=class t extends ug{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){let r=lg(e,!1),n=r.text,i=Pp.DateTime.fromFormat(r.text,ZEe);if(i.isValid){let s=i.plus({year:1});return r.text=i.toFormat(il),n=s.toFormat(il),new t(r,n)}}};ki.LiteralYear=IJ});var iAe=v(HM=>{"use strict";Object.defineProperty(HM,"__esModule",{value:!0});HM.PartialCompare=void 0;var jst=js(),Hst=ir(),MJ=class extends Hst.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,n){return this.right.apply(e,this.op,n)}requestExpression(e){}getExpression(e){return this.log("Partial comparison does not have a value"),(0,jst.errorFor)("no value for partial compare")}};HM.PartialCompare=MJ});var oAe=v(GS=>{"use strict";Object.defineProperty(GS,"__esModule",{value:!0});GS.PickWhen=GS.Pick=void 0;var Jc=Ke(),kp=js(),l0=pn(),zst=ir(),Gst=mt(),sAe=hs();function zM(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}var PJ=class extends zst.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(let r of this.choices){if(r.pick===void 0)return;let n=r.when.requestExpression(e);if(n===void 0||n.dataType!=="boolean")return}return this.getExpression(e)}}apply(e,r,n){let i=["CASE"],s,o="scalar",a="constant";for(let c of this.choices){let f=c.when.apply(e,"=",n),x=c.pick?c.pick.getExpression(e):n.getExpression(e);if(o=(0,Jc.maxExpressionType)(o,(0,Jc.maxExpressionType)(f.expressionType,x.expressionType)),a=(0,Jc.mergeEvalSpaces)(a,f.evalSpace,x.evalSpace),s&&!l0.FT.typeEq(s,x,!0)){let d=l0.FT.inspect(x);return this.log(`pick type '${d}', expected '${s.dataType}'`),(0,kp.errorFor)("pick when type")}s=zM(s,x),i.push(" WHEN ",...f.value," THEN ",...x.value)}let l=(this.elsePick||n).getExpression(e);if(s=zM(s,l),!l0.FT.typeEq(s,l,!0)){let c=this.elsePick?"else":"pick default";return this.log(`${c} type '${l0.FT.inspect(l)}', expected '${s.dataType}'`),(0,kp.errorFor)("pick else type")}return{dataType:s.dataType,expressionType:(0,Jc.maxExpressionType)(o,l.expressionType),evalSpace:(0,Jc.mergeEvalSpaces)(a,l.evalSpace),value:(0,sAe.compressExpr)([...i," ELSE ",...l.value," END"])}}getExpression(e){if(this.elsePick===void 0)return this.log("pick incomplete, missing 'else'"),(0,kp.errorFor)("no value for partial pick");let r=[];for(let u of this.choices){if(u.pick===void 0)return this.log("pick with no value can only be used with apply"),(0,kp.errorFor)("no value for partial pick");if(u.when.requestExpression(e)===void 0)return this.log("pick with partial when can only be used with apply"),(0,kp.errorFor)("partial when");r.push({pick:u.pick.getExpression(e),when:u.when.getExpression(e)})}let n,i=["CASE"],s="scalar",o="constant";for(let u of r){if(!l0.FT.typeEq(u.when,l0.FT.boolT))return this.log(`when expression must be boolean, not '${l0.FT.inspect(u.when)}`),(0,kp.errorFor)("pick when type");if(n&&!l0.FT.typeEq(n,u.pick,!0)){let l=l0.FT.inspect(u.pick);return this.log(`pick type '${l}', expected '${n.dataType}'`),(0,kp.errorFor)("pick value type")}n=zM(n,u.pick),s=(0,Jc.maxExpressionType)(s,(0,Jc.maxExpressionType)(u.pick.expressionType,u.when.expressionType)),o=(0,Jc.mergeEvalSpaces)(o,u.pick.evalSpace,u.when.evalSpace),i.push(" WHEN ",...u.when.value," THEN ",...u.pick.value)}let a=this.elsePick.getExpression(e);return s=(0,Jc.maxExpressionType)(s,a.expressionType),o=(0,Jc.mergeEvalSpaces)(o,a.evalSpace),n=zM(n,a),l0.FT.typeEq(n,a,!0)?(i.push(" ELSE ",...a.value," END"),{dataType:n.dataType,expressionType:s,value:(0,sAe.compressExpr)(i),evalSpace:o}):(this.elsePick.log(`else type '${l0.FT.inspect(a)}', expected '${n.dataType}'`),(0,kp.errorFor)("pick value type mismatch"))}};GS.Pick=PJ;var kJ=class extends Gst.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="pickWhen",this.has({pick:e})}};GS.PickWhen=kJ});var aAe=v(GM=>{"use strict";Object.defineProperty(GM,"__esModule",{value:!0});GM.Timeframe=void 0;var Qst=Ke(),Vst=mt(),BJ=class extends Vst.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,Qst.isTimestampUnit)(r)?r:"second"}};GM.Timeframe=BJ});var lAe=v(QM=>{"use strict";Object.defineProperty(QM,"__esModule",{value:!0});QM.TopBy=void 0;var Wst=Ke(),uAe=ir(),Yst=mt(),Kst=hs(),qJ=class extends Yst.MalloyElement{constructor(e){super(),this.by=e,this.elementType="topBy",e instanceof uAe.ExpressionDef&&this.has({by:e})}getBy(e){if(this.by instanceof uAe.ExpressionDef){let r=this.by.getExpression(e);return(0,Wst.expressionIsAggregate)(r.expressionType)||this.log("top by expression must be an aggregate"),{by:"expression",e:(0,Kst.compressExpr)(r.value)}}return{by:"name",name:this.by}}};QM.TopBy=qJ});var cAe=v(Bp=>{"use strict";Object.defineProperty(Bp,"__esModule",{value:!0});Bp.ImportStatement=Bp.ImportSelect=Bp.ImportSourceName=void 0;var HJ=mt(),UJ=class extends HJ.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}};Bp.ImportSourceName=UJ;var $J=class extends HJ.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}};Bp.ImportSelect=$J;var jJ=class extends HJ.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.log("Invalid URI in import statement")}}needs(){let e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){let n=e.childRequest(this.fullURL);if(n)return n}}execute(e){let r=this.translator();if(!r)this.log("Cannot import without translation context");else if(this.fullURL){let n=r.root.importZone.getEntry(this.fullURL);if(n.status==="present"){let i=r.getChildExports(this.fullURL);if(this.notEmpty())for(let s of this.list){let o=s.from||s;if(e.getEntry(s.text))s.log(`Cannot redefine '${s.text}'`);else if(i[o.text]){let a={...i[o.text]};s.from&&(a.as=s.text),e.setEntry(s.text,{entry:a,exported:!1})}else o.log(`Cannot find '${o.text}', not imported`)}else for(let[s,o]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(s)?this.log(`Cannot redefine '${s}'`):e.setEntry(s,{entry:o,exported:!1})}else n.status==="error"?this.log(`import failed: '${n.message}'`):this.log(`import failed with status: '${n.status}'`)}}};Bp.ImportStatement=jJ});var GJ=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.ExtendBlock=void 0;var Xst=mt(),Jst=Ii(),zJ=class extends Xst.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Jst.LegalRefinementStage.Single}queryExecute(e){for(let r of this.list)for(let n of r.list)e.inputFS.extendSource(n)}};VM.ExtendBlock=zJ});var fAe=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0});WM.AnonymousQuery=void 0;var Zst=mt(),eot=Wc(),QJ=class extends Zst.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=eot.extendNoteMethod,this.has({queryExpr:e})}execute(e){let r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("Cannot run this object as a query");return}let n={...r.query()},i=this.note||{};n.annotation&&(i.inherits=n.annotation),(i.notes||i.blockNotes||i.inherits)&&(n.annotation=i),e.queryList.push(n)}};WM.AnonymousQuery=QJ});var QS=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0});YM.View=void 0;var tot=mt(),VJ=class extends tot.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}};YM.View=VJ});var xAe=v(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.ViewArrow=void 0;var rot=tl(),not=QS(),WJ=class extends not.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){let r=this.base.pipelineComp(e),n=new rot.StaticSpace(r.outputStruct),i=this.operation.pipelineComp(n);return{pipeline:[...r.pipeline,...i.pipeline],outputStruct:i.outputStruct}}refine(e,r,n){return this.log("A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}};KM.ViewArrow=WJ});var XJ=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0});XM.refine=void 0;var YJ=lc(),KJ=AL();function iot(t,e,r){var n,i;if(e.length!==1)return t.log("Named refinements of multi-stage views are not supported"),e;let s={...e[0]},o=r;if((0,YJ.isRawSegment)(s))t.log("Cannot refine raw query, must add an explicit query stage");else if(s.type==="partial"&&o.type!=="index"&&o.type!=="raw"?s.type=o.type:o.type!==s.type&&t.log(`cannot refine ${s.type} view with ${o.type} view`),o.type!=="index"&&s.type!=="index"&&o.type!=="raw"&&((o.orderBy!==void 0||o.by!==void 0)&&(s.orderBy===void 0&&s.by===void 0?o.orderBy?s.orderBy=o.orderBy:o.by&&(s.by=o.by):t.log("refinement cannot override existing ordering")),o.limit!==void 0&&(s.limit===void 0?s.limit=o.limit:t.log("refinement cannot override existing limit"))),s.filterList=s.filterList!==void 0||o.filterList!==void 0?[...(n=s.filterList)!==null&&n!==void 0?n:[],...(i=o.filterList)!==null&&i!==void 0?i:[]]:void 0,(0,YJ.isQuerySegment)(o)&&(0,YJ.isQuerySegment)(s)){let a=[],u=[],l=new Map(s.queryFields.map(c=>[(0,KJ.nameFromDef)(c),c]));for(let c of o.queryFields)l.has((0,KJ.nameFromDef)(c))?a.push(c):u.push(c);s.queryFields=[...s.queryFields,...u],a.length>0&&t.log(`overlapping fields in refinement: ${a.map(KJ.nameFromDef)}`)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}XM.refine=iot});var dAe=v(JM=>{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});JM.ViewRefine=void 0;var sot=ca(),oot=Km(),aot=XJ(),uot=QS(),JJ=class extends uot.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){let n=this.base.pipelineComp(e),i=this.refinement.refine(e,n.pipeline,r);return{pipeline:i,annotation:n.annotation,outputStruct:i.length>0?(0,oot.getFinalStruct)(this.refinement,e.structDef(),i):sot.ErrorFactory.structDef}}refine(e,r,n){let i=this.pipeline(e,n);return i.length!==1?(this.refinement.log("refinement must have exactly one stage"),r):(0,aot.refine)(this,r,i[0])}getImplicitName(){return this.base.getImplicitName()}};JM.ViewRefine=JJ});var mAe=v(ZM=>{"use strict";Object.defineProperty(ZM,"__esModule",{value:!0});ZM.ReferenceView=void 0;var hAe=Ke(),pAe=ca(),lot=Km(),cot=la(),fot=XJ(),xot=QS(),ZJ=class extends xot.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}){let n=this.reference.getField(e),i=function(){return{inputStruct:pAe.ErrorFactory.structDef,outputStruct:pAe.ErrorFactory.structDef,pipeline:[],error:!0}};if(!n.found)return this.log(`\`${this.reference.refString}\` is not defined`),i();if(!(n.found instanceof cot.SpaceField))throw new Error("Expected space field");let s=n.found.fieldDef();if(s===void 0)throw new Error("Expected field to have definition");if((0,hAe.isAtomicFieldType)(s.type)){let o={type:"reduce",queryFields:[this.reference.refToField]},{dialect:a,queryTimezone:u,structRelationship:l}=e.structDef(),c=this.reference.nameString;return{pipeline:[o],name:c,outputStruct:{type:"struct",dialect:a,queryTimezone:u,name:c,fields:[s],structRelationship:l,structSource:{type:"query_result"}}}}else return(0,hAe.isTurtleDef)(s)?this.reference.list.length>1?(r?this.log("Cannot use view from join as refinement"):this.log("Cannot use view from join"),i()):{pipeline:[...s.pipeline],name:s.name,annotation:s.annotation,outputStruct:(0,lot.getFinalStruct)(this.reference,e.structDef(),s.pipeline)}:(r?this.reference.log(`named refinement \`${this.reference.refString}\` must be a view, found a ${s.type}`):this.reference.log("This operation is not supported"),i())}getRefinementSegment(e){let{pipeline:r,error:n}=this._pipelineComp(e,{forRefinement:!0});if(!n){if(r.length!==1){this.reference.log(`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,n){let i=this.getRefinementSegment(e);return i?(0,fot.refine)(this,r,i):r}getImplicitName(){return this.reference.nameString}};ZM.ReferenceView=ZJ});var tZ=v(eP=>{"use strict";Object.defineProperty(eP,"__esModule",{value:!0});eP.Index=void 0;var dot=mt(),hot=Ii(),eZ=class extends dot.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=hot.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};eP.Index=eZ});var nZ=v(tP=>{"use strict";Object.defineProperty(tP,"__esModule",{value:!0});tP.SampleProperty=void 0;var pot=mt(),gAe=Ii(),rZ=class extends pot.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=gAe.LegalRefinementStage.Tail,this.forceQueryClass=gAe.QueryClass.Index}sampling(){return this.sample}};tP.SampleProperty=rZ});var EAe=v(rP=>{"use strict";Object.defineProperty(rP,"__esModule",{value:!0});rP.IndexFieldSpace=void 0;var yAe=Ke(),iZ=PS(),mot=la(),got=l5(),yot=VK(),Eot=tl(),sZ=class extends got.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(let r of e)r instanceof iZ.FieldReference?super.pushFields(r):r instanceof iZ.WildcardFieldReference?this.addWild(r):r.log("Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.log("index query operations cannot be refined"),{type:"index",indexFields:[]};let r=[];for(let[n,i]of this.entries())if(i instanceof mot.SpaceField){let s=this.expandedWild[n];if(s){r.push({type:"fieldref",path:s});continue}if(i instanceof yot.ReferenceField){let o=i.fieldRef,a=o.getField(this.exprSpace);a.error?o.log(a.error):r.push(o.refToField)}}return{type:"index",indexFields:r}}addRefineFromFields(e){}addWild(e){var r;let n=this.exprSpace,i=[];if(e.joinPath)for(let a of e.joinPath.list){let u=a.refString;i.push(u);let l=n.entry(u);if(l)if(l instanceof Eot.StructSpaceField)n=l.fieldSpace;else{a.log(`Field '${u}' does not contain rows and cannot be expanded with '*'`);return}else{a.log(`No such field as '${u}'`);return}}let s=this.dialectObj(),o=[];for(let[a,u]of n.entries()){if(e.except.has(a))continue;let l=iZ.IndexFieldReference.indexOutputName([...i,a]);if(this.entry(l)){let c=(r=this.expandedWild[l])===null||r===void 0?void 0:r.join(".");e.log(`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{let c=u.typeDesc();(0,yAe.isAtomicFieldType)(c.dataType)&&(0,yAe.expressionIsScalar)(c.expressionType)&&(s===void 0||!s.ignoreInProject(a))&&(o.push({name:l,entry:u}),this.expandedWild[l]=i.concat(a))}}for(let a of o.sort((u,l)=>u.name.localeCompare(l.name)))this.setEntry(a.name,a.entry)}};rP.IndexFieldSpace=sZ});var AAe=v(nP=>{"use strict";Object.defineProperty(nP,"__esModule",{value:!0});nP.IndexBuilder=void 0;var oZ=Ke(),Aot=ca(),Sot=Ym(),vot=tZ(),_ot=kS(),bot=nZ(),Tot=EAe(),aZ=class{constructor(e,r,n,i){this.filters=[],this.type="index",this.resultFS=new Tot.IndexFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof Sot.Filter?this.filters.push(...e.getFilterList(this.inputFS)):e instanceof _ot.Limit?(this.limit&&this.limit.log("Ignored, too many limit: statements"),this.limit=e):e instanceof vot.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.log("Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof bot.SampleProperty?this.sample=e.sampling():e.log("Not legal in an index query operation")}finalize(e){if(e&&!(0,oZ.isIndexSegment)(e)&&!(0,oZ.isPartialSegment)(e))return this.resultFS.log(`Can't refine index with ${e.type}`),Aot.ErrorFactory.indexSegment;let r=this.resultFS.getPipeSegment(e),n=e?.filterList||[];return this.filters.length>0&&!n?r.filterList=this.filters:n&&(r.filterList=[...n,...this.filters]),e?.limit&&(r.limit=e.limit),this.limit&&(r.limit=this.limit.limit),this.indexOn&&(r.weightMeasure=this.indexOn.refString),e&&(0,oZ.isIndexSegment)(e)&&e?.sample&&(r.sample=e.sample),this.sample&&(r.sample=this.sample),r}};nP.IndexBuilder=aZ});var lZ=v(iP=>{"use strict";Object.defineProperty(iP,"__esModule",{value:!0});iP.GroupBy=void 0;var Cot=n0(),SAe=Ii(),uZ=class extends Cot.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=SAe.LegalRefinementStage.Single,this.forceQueryClass=SAe.QueryClass.Grouping}};iP.GroupBy=uZ});var vAe=v(sP=>{"use strict";Object.defineProperty(sP,"__esModule",{value:!0});sP.ProjectFieldSpace=void 0;var cZ=Ke(),Rot=l5(),fZ=class extends Rot.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e.dataType==="turtle"||(0,cZ.expressionIsAggregate)(e.expressionType)?!1:(0,cZ.expressionInvolvesAggregate)(e.expressionType)&&(0,cZ.expressionIsAnalytic)(e.expressionType)?(this.log("Cannot add aggregate analyics to project"),!1):!0}};sP.ProjectFieldSpace=fZ});var hZ=v(VS=>{"use strict";Object.defineProperty(VS,"__esModule",{value:!0});VS.Ordering=VS.OrderBy=void 0;var Oot=Ke(),_Ae=u5(),bAe=mt(),Dot=Ii(),xZ=class extends bAe.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof _Ae.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 _Ae.FieldName&&e.isQueryFieldSpace()){let i=e.outputSpace(),s=this.field.getField(i);s.error&&this.field.log(s.error),(!s.found||!s.isOutputField)&&this.log(`Unknown field ${this.field.refString} in output space`),(0,Oot.expressionIsAnalytic)((r=s.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.log(`Illegal order by of analytic field ${this.field.refString}`)}let n={field:this.modelField};return this.dir&&(n.dir=this.dir),n}};VS.OrderBy=xZ;var dZ=class extends bAe.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Dot.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}};VS.Ordering=dZ});var mZ=v(oP=>{"use strict";Object.defineProperty(oP,"__esModule",{value:!0});oP.Top=void 0;var TAe=Ke(),Not=hs(),Fot=u5(),wot=mt(),Lot=Ii(),pZ=class extends wot.MalloyElement{constructor(e,r){super(),this.limit=e,this.by=r,this.elementType="top",this.queryRefinementStage=Lot.LegalRefinementStage.Tail,this.forceQueryClass=void 0,this.has({by:r})}getBy(e){var r;if(this.by)if(this.by instanceof Fot.FieldName){if(e.isQueryFieldSpace()){let n=e.outputSpace(),i=this.by.getField(n);i.error&&this.by.log(i.error),(!i.found||!i.isOutputField)&&this.by.log(`Unknown field ${this.by.refString} in output space`),(0,TAe.expressionIsAnalytic)((r=i.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.by.log(`Illegal order by of analytic field ${this.by.refString}`)}return{by:"name",name:this.by.refString}}else{let n=this.by.getExpression(e);return(0,TAe.expressionIsAggregate)(n.expressionType)&&this.by.log("top by expression must be an aggregate"),n.evalSpace==="output"&&this.by.log("top by expression must be an output expression"),{by:"expression",e:(0,Not.compressExpr)(n.value)}}}};oP.Top=pZ});var uP=v(WS=>{"use strict";Object.defineProperty(WS,"__esModule",{value:!0});WS.ReduceBuilder=WS.QuerySegmentBuilder=void 0;var CAe=Ke(),Iot=ca(),Mot=Ym(),Pot=kS(),RAe=hZ(),OAe=mZ(),kot=l5(),Bot=n0(),aP=class{constructor(){this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}if(e instanceof Bot.DefinitionList)this.resultFS.pushFields(...e.list);else if(e instanceof Mot.Filter){let r=e.havingClause?this.resultFS:this.inputFS;this.filters.push(...e.getFilterList(r))}else e instanceof OAe.Top?(this.limit?e.log("Query operation already limited"):this.limit=e.limit,e.by&&(this.order?e.log("Query operation is already sorted"):this.order=e)):e instanceof Pot.Limit?this.limit?e.log("Query operation already limited"):this.limit=e.limit:e instanceof RAe.Ordering&&(this.order?e.log("Query operation already sorted"):this.order=e)}refineFrom(e,r){if(e&&e.type!=="index"&&e.type!=="raw"&&(this.order||(e.orderBy?r.orderBy=e.orderBy:e.by&&(r.by=e.by)),!this.limit&&e.limit&&(r.limit=e.limit)),this.limit&&(r.limit=this.limit),this.order instanceof OAe.Top){let i=this.order.getBy(this.inputFS);i&&(r.by=i)}this.order instanceof RAe.Ordering&&(r.orderBy=this.order.getOrderBy(this.inputFS));let n=e?.filterList||[];this.filters.length>0&&!n?r.filterList=this.filters:n&&(r.filterList=[...n,...this.filters])}};WS.QuerySegmentBuilder=aP;var gZ=class extends aP{constructor(e,r,n,i){super(),this.type="grouping",this.resultFS=new kot.ReduceFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,CAe.isReduceSegment)(e)||(0,CAe.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine reduce with ${e.type}`),Iot.ErrorFactory.reduceSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};WS.ReduceBuilder=gZ});var NAe=v(lP=>{"use strict";Object.defineProperty(lP,"__esModule",{value:!0});lP.ProjectBuilder=void 0;var DAe=Ke(),qot=ca(),Uot=lZ(),$ot=vAe(),jot=uP(),yZ=class extends jot.QuerySegmentBuilder{constructor(e,r,n,i){super(),this.type="project",this.resultFS=new $ot.ProjectFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Uot.GroupBy?e.log("Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,DAe.isProjectSegment)(e)||(0,DAe.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine select with ${e.type}`),qot.ErrorFactory.projectSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};lP.ProjectBuilder=yZ});var FAe=v(cP=>{"use strict";Object.defineProperty(cP,"__esModule",{value:!0});cP.PartialBuilder=void 0;var Hot=lc(),zot=uP(),EZ=class extends zot.ReduceBuilder{finalize(e){let r=super.finalize(e);if((0,Hot.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}};cP.PartialBuilder=EZ});var SZ=v(fP=>{"use strict";Object.defineProperty(fP,"__esModule",{value:!0});fP.QOpDesc=void 0;var Got=AAe(),Qot=NAe(),Vot=uP(),Wot=mt(),Yot=Km(),Kot=tl(),cg=Ii(),Xot=FAe(),AZ=class extends Wot.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,n=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=cg.QueryClass.Grouping:this.refineThis.type==="project"?r=cg.QueryClass.Project:this.refineThis.type==="index"&&(r=cg.QueryClass.Index));for(let i of this.list)i.forceQueryClass&&(r?r!==i.forceQueryClass&&i.log(`Not legal in ${r} query`):r=i.forceQueryClass),n||(n=(e=i.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&n&&(this.log("Can't determine view type (`group_by` / `aggregate` / `nest`, `project`, `index`)"),r=cg.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,n){switch(this.computeType()){case cg.QueryClass.Grouping:return new Vot.ReduceBuilder(e,this.refineThis,r,n);case cg.QueryClass.Project:return new Qot.ProjectBuilder(e,this.refineThis,r,n);case cg.QueryClass.Index:return new Got.IndexBuilder(e,this.refineThis,r,n);case void 0:return new Xot.PartialBuilder(e,this.refineThis,r,n)}}getOp(e,r){let n=this.getBuilder(e,r,this);for(let s of this.list)n.execute(s);let i=n.finalize(this.refineThis);return{segment:i,outputSpace:()=>new Kot.StaticSpace((0,Yot.opOutputStruct)(this,e.structDef(),i))}}};fP.QOpDesc=AZ});var LAe=v(xP=>{"use strict";Object.defineProperty(xP,"__esModule",{value:!0});xP.QOpDescView=void 0;var Jot=Ke(),Zot=tl(),wAe=SZ(),eat=Km(),vZ=Ii(),tat=QS(),_Z=class extends tat.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){let n=this.operation.getOp(e,r);return{pipeline:[n.segment],outputStruct:n.outputSpace().structDef()}}getOp(e,r,n,i){return(0,Jot.isRawSegment)(i)?(this.log("A raw query cannot be refined"),i):(n.refineFrom(i),n.getOp(e,r).segment)}refine(e,r,n){let i=[...r];if(i.length===0)return i;if(i.length===1)return this.operation.refineFrom(i[0]),[this.getOp(e,n,this.operation,i[0])];let s=new wAe.QOpDesc([]),o=new wAe.QOpDesc([]);for(let a of this.operation.list)switch(a.queryRefinementStage){case vZ.LegalRefinementStage.Head:s.push(a);break;case vZ.LegalRefinementStage.Single:a.log("Illegal in refinement of a query with more than one stage");break;case vZ.LegalRefinementStage.Tail:o.push(a);break;default:a.log("Illegal query refinement")}if(s.notEmpty()&&(this.has({headRefinements:s}),i[0]=this.getOp(e,void 0,s,i[0])),o.notEmpty()){let a=i.length-1;this.has({tailRefinements:o});let u=(0,eat.getFinalStruct)(this,e.structDef(),i.slice(-1));i[a]=this.getOp(new Zot.StaticSpace(u),void 0,o,i[a])}return i}getImplicitName(){}};xP.QOpDescView=_Z});var FZ=v(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.FieldDefinitionValue=An.DefSpace=An.DimensionFieldDeclaration=An.MeasureFieldDeclaration=An.DeclareFieldDeclaration=An.ProjectFieldDeclaration=An.GroupByFieldDeclaration=An.AggregateFieldDeclaration=An.CalculateFieldDeclaration=An.AtomicFieldDeclaration=void 0;var rat=Ke(),nat=hs(),iat=pn(),sat=yI(),oat=mt(),fg=WK(),aat=Wc(),uat=la(),Zc=class extends oat.MalloyElement{constructor(e,r,n){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=n,this.isNoteableObj=!0,this.extendNote=aat.extendNoteMethod}fieldDef(e,r){return this.queryFieldDef(new S5(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let n;function i(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{let u=this.executesInOutputSpace()?i():e;n=this.expr.getExpression(u)}catch(u){return this.log(`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}let s=(0,nat.compressExpr)(n.value),o=n.dataType;if(o==="null"&&(this.expr.log('null value defaults to type number, use "null::TYPE" to specify correct type',"warn"),o="number"),(0,rat.isAtomicFieldType)(o)&&o!=="error"){let u={name:r,type:o,location:this.location};return s.length>0&&(u.e=s),n.expressionType&&(u.expressionType=n.expressionType),this.typecheckExprValue(n),this.exprSrc&&(u.code=this.exprSrc),(0,sat.isGranularResult)(n)&&u.type==="timestamp"&&(u.timeframe=n.timeframe),this.note&&(u.annotation=this.note),u}if(!(e instanceof S5&&e.foundCircle)&&n.dataType!=="error"){let u=iat.FT.inspect(n);this.log(`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new dP(e,this))}};An.AtomicFieldDeclaration=Zc;var bZ=class extends Zc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}};An.CalculateFieldDeclaration=bZ;var TZ=class extends Zc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckAggregate)(e,this)}};An.AggregateFieldDeclaration=TZ;var CZ=class extends Zc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckGroupBy)(e,this)}};An.GroupByFieldDeclaration=CZ;var RZ=class extends Zc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckProject)(e,this)}};An.ProjectFieldDeclaration=RZ;var OZ=class extends Zc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckDeclare)(e,this)}};An.DeclareFieldDeclaration=OZ;var DZ=class extends Zc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckMeasure)(e,this)}};An.MeasureFieldDeclaration=DZ;var NZ=class extends Zc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckDimension)(e,this)}};An.DimensionFieldDeclaration=NZ;var S5=class{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:`Circular reference to '${this.circular.defineName}' in definition`,found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}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")}};An.DefSpace=S5;var dP=class extends uat.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){return this.haveFieldDef||(this.haveFieldDef=this.exprDef.fieldDef(this.space,this.name)),this.haveFieldDef}getQueryFieldDef(e){if(!this.qfd){let r=this.exprDef.queryFieldDef(e,this.name);this.qfd=r}return this.qfd}typeDesc(){let e=this.qfd||this.fieldDef();return this.fieldTypeFromFieldDef(e)}};An.FieldDefinitionValue=dP});var MAe=v(hP=>{"use strict";Object.defineProperty(hP,"__esModule",{value:!0});hP.Aggregate=void 0;var lat=n0(),IAe=Ii(),wZ=class extends lat.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=IAe.LegalRefinementStage.Single,this.forceQueryClass=IAe.QueryClass.Grouping}};hP.Aggregate=wZ});var PAe=v(pP=>{"use strict";Object.defineProperty(pP,"__esModule",{value:!0});pP.Calculate=void 0;var cat=n0(),fat=Ii(),LZ=class extends cat.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=fat.LegalRefinementStage.Single}};pP.Calculate=LZ});var MZ=v(mP=>{"use strict";Object.defineProperty(mP,"__esModule",{value:!0});mP.Dimensions=void 0;var xat=bS(),IZ=class extends xat.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}};mP.Dimensions=IZ});var kZ=v(gP=>{"use strict";Object.defineProperty(gP,"__esModule",{value:!0});gP.Measures=void 0;var dat=bS(),PZ=class extends dat.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}};gP.Measures=PZ});var BAe=v(yP=>{"use strict";Object.defineProperty(yP,"__esModule",{value:!0});yP.Nests=void 0;var hat=n0(),kAe=Ii(),BZ=class extends hat.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=kAe.LegalRefinementStage.Single,this.forceQueryClass=kAe.QueryClass.Grouping}};yP.Nests=BZ});var UAe=v(EP=>{"use strict";Object.defineProperty(EP,"__esModule",{value:!0});EP.ProjectStatement=void 0;var pat=n0(),qAe=Ii(),qZ=class extends pat.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=qAe.QueryClass.Project,this.queryRefinementStage=qAe.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}};EP.ProjectStatement=qZ});var jAe=v(AP=>{"use strict";Object.defineProperty(AP,"__esModule",{value:!0});AP.FromSQLSource=void 0;var $Ae=Ke(),mat=n5(),UZ=class extends mat.NamedSource{constructor(){super(...arguments),this.elementType="fromSQLSource"}structRef(){return this.structDef()}modelStruct(){let e=this.modelEntry(this.ref),r=e?.entry;if(!r){this.log(`Undefined from_sql source '${this.refName}'`);return}if(r.type==="function"){this.log(`Cannot construct a source from a function '${this.refName}'`);return}else if(r.type==="query"){this.log(`Cannot use 'from_sql()' with a query '${this.refName}'`);return}else if(r.type==="connection"){this.log(`Cannot use 'from_sql()' with a connection '${this.refName}'`);return}else if((0,$Ae.isSQLBlockStruct)(r)&&r.declaredSQLBlock){let{declaredSQLBlock:n,...i}=r;return i}else if(!(0,$Ae.isSQLBlockStruct)(r)){this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`);return}this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`)}};AP.FromSQLSource=UZ});var zZ=v(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});qp.findReferences=qp.deprecatedParseTableURI=qp.constructTableKey=void 0;var gat=_p(),jZ=WC();function $Z(t){let e=(0,jZ.getStringIfShort)(t);if(e)return e;let r=[],n=t.string().sqlString();if(n){for(let i of(0,jZ.getStringParts)(n))typeof i=="string"&&r.push(i);return r.join("")}return""}var HZ=class{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,n){let i=HAe(e,r);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:r,firstReference:n})}enterTableMethod(e){let r=(0,jZ.getId)(e.connectionId()),n=$Z(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(r,n,i)}enterTableFunction(e){let r=$Z(e.tableURI()),{connectionName:n,tablePath:i}=zAe(r),s=this.trans.rangeFromContext(e);this.registerTableReference(n,i,s)}enterImportURL(e){let r=$Z(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}};function HAe(t,e){return t===void 0?e:`${t}:${e}`}qp.constructTableKey=HAe;function zAe(t){let e=t.match(/^([^:]*):(.*)$/);if(e){let[,r,n]=e;return{connectionName:r,tablePath:n}}else return{tablePath:t}}qp.deprecatedParseTableURI=zAe;function yat(t,e,r){let n=new HZ(t,e),i=n;return gat.ParseTreeWalker.DEFAULT.walk(i,r),{tables:n.needTables,urls:n.needImports}}qp.findReferences=yat});var VAe=v(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});Up.TableFunctionSource=Up.TableMethodSource=Up.TableSource=void 0;var QAe=zZ(),Eat=Px(),GAe=ca(),v5=class extends Eat.Source{structDef(){var e,r;let n=this.getTableInfo();if(n===void 0)return GAe.ErrorFactory.structDef;let{tablePath:i,connectionName:s}=n,o=(0,QAe.constructTableKey)(s,i),a=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(o),u=`Schema read failure for table '${i}' for connection '${s}'`;if(a){if(a.status==="present"){a.value.location=this.location,a.value.fields.forEach(c=>{c.location=this.location});let l={...a.value,fields:a.value.fields.map(c=>({...c,location:this.location})),location:this.location};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(l),l}a.status==="error"&&(u=a.message)}return this.log(u),GAe.ErrorFactory.structDef}};Up.TableSource=v5;var GZ=class extends v5{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;let r=this.modelEntry(this.connectionName),n=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(n,{entry:{type:"connection",name:n},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.log(`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}};Up.TableMethodSource=GZ;var QZ=class extends v5{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,QAe.deprecatedParseTableURI)(this.tableURI)}};Up.TableFunctionSource=QZ});var WAe=v(SP=>{"use strict";Object.defineProperty(SP,"__esModule",{value:!0});SP.SQLStatement=void 0;var Aat=AK(),Sat=mt(),VZ=class extends Sat.MalloyElement{constructor(e){super(),this.select=e,this.elementType="sqlStatement",this.has({select:e})}sqlBlock(){return this.requestBlock||(this.requestBlock=(0,Aat.makeSQLBlock)(this.select.sqlPhrases(),this.connection)),this.requestBlock}lookupCompiledSQL(e){var r;let n=(r=this.translator())===null||r===void 0?void 0:r.root.sqlQueryZone;if(n)return n.reference(e.name,this.location),n.getEntry(e.name)}needs(e){let r=this.sqlBlock(),n=this.lookupCompiledSQL(r);if(n?.status==="reference")return{compileSQL:r,partialModel:this.select.containsQueries?e.modelDef():void 0}}execute(e){let r=this.sqlBlock(),n=this.lookupCompiledSQL(r);if(!n){this.log("Cant't look up schema for sql block");return}if(n.status==="error"){let i=n.message.split(/\r?\n/);this.select.log("Invalid SQL, "+i.join(`
|
|
682
|
-
`));return}if(n.status==="present"){let i=this.select.location,s={...n.value,fields:n.value.fields.map(o=>({...o,location:i})),location:this.location};this.is&&!e.defineSQL(s,this.is)&&this.log(`'${this.is}' already defined`);return}}};SP.SQLStatement=VZ});var KAe=v(vP=>{"use strict";Object.defineProperty(vP,"__esModule",{value:!0});vP.SQLString=void 0;var vat=mt(),YAe=Dp(),WZ=class extends vat.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(_at)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof YAe.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.log("This element is not legal inside an SQL string")}sqlPhrases(){let e=[];for(let r of this.elements)if(typeof r=="string")e.push({sql:r});else{let n=r.getQuery();n?e.push(n.query()):r.sqLog("Cannot expand into a query")}return e}};vP.SQLString=WZ;function _at(t){return t instanceof YAe.SourceQueryElement}});var XAe=v(_P=>{"use strict";Object.defineProperty(_P,"__esModule",{value:!0});_P.SourceDesc=void 0;var bat=mt(),YZ=class extends bat.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}};_P.SourceDesc=YZ});var JAe=v(bP=>{"use strict";Object.defineProperty(bP,"__esModule",{value:!0});bP.isSourceProperty=void 0;var Tat=Ym(),Cat=CS(),Rat=bS(),Oat=PL(),Dat=QL(),Nat=BL(),Fat=UL(),wat=jL(),Lat=zL();function Iat(t){return t instanceof Tat.Filter||t instanceof Cat.Joins||t instanceof Rat.DeclareFields||t instanceof Oat.FieldListEdit||t instanceof Dat.Renames||t instanceof Nat.PrimaryKey||t instanceof Lat.ObjectAnnotation||t instanceof Fat.Views||t instanceof wat.TimezoneStatement}bP.isSourceProperty=Iat});var eSe=v(TP=>{"use strict";Object.defineProperty(TP,"__esModule",{value:!0});TP.isFieldCollectionMember=void 0;var Mat=FZ(),ZAe=PS();function Pat(t){return t instanceof ZAe.FieldReference||t instanceof ZAe.WildcardFieldReference||t instanceof Mat.AtomicFieldDeclaration}TP.isFieldCollectionMember=Pat});var tSe=v(CP=>{"use strict";Object.defineProperty(CP,"__esModule",{value:!0});CP.isQueryElement=void 0;var kat=JL(),Bat=tI(),qat=hK(),Uat=EK();function $at(t){return t instanceof kat.QueryArrow||t instanceof Bat.QueryRefine||t instanceof qat.QueryReference||t instanceof Uat.QueryRaw}CP.isQueryElement=$at});var nSe=v(rSe=>{"use strict";Object.defineProperty(rSe,"__esModule",{value:!0})});var iSe=v(RP=>{"use strict";Object.defineProperty(RP,"__esModule",{value:!0});RP.isQueryProperty=void 0;function jat(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}RP.isQueryProperty=jat});var sSe=v(OP=>{"use strict";Object.defineProperty(OP,"__esModule",{value:!0});OP.isQueryExtendProperty=void 0;var Hat=MZ(),zat=CS(),Gat=kZ();function Qat(t){return t instanceof Hat.Dimensions||t instanceof Gat.Measures||t instanceof zat.Joins}OP.isQueryExtendProperty=Qat});var oSe=v(DP=>{"use strict";Object.defineProperty(DP,"__esModule",{value:!0});DP.isFieldPropStatement=void 0;var Vat=PI(),Wat=Ym(),Yat=kS(),Kat=XI();function Xat(t){return t instanceof Wat.Filter||t instanceof Yat.Limit||t instanceof Kat.PartitionBy||t instanceof Vat.FunctionOrdering}DP.isFieldPropStatement=Xat});var NP=v(ne=>{"use strict";var Jat=ne&&ne.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),ie=ne&&ne.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Jat(e,t,r)};Object.defineProperty(ne,"__esModule",{value:!0});ie(gY(),ne);ie(u3e(),ne);ie(c3e(),ne);ie(Px(),ne);ie(rK(),ne);ie(Dp(),ne);ie(_3e(),ne);ie(D3e(),ne);ie(N3e(),ne);ie(mK(),ne);ie(F3e(),ne);ie(PL(),ne);ie(BL(),ne);ie(QL(),ne);ie(UL(),ne);ie(jL(),ne);ie(z3e(),ne);ie(wI(),ne);ie(G3e(),ne);ie(PI(),ne);ie(V3e(),ne);ie(Zm(),ne);ie(Z3e(),ne);ie(jI(),ne);ie(eye(),ne);ie(tye(),ne);ie(nye(),ne);ie(PK(),ne);ie(iye(),ne);ie(sye(),ne);ie(aye(),ne);ie(bX(),ne);ie(IK(),ne);ie(MI(),ne);ie(lye(),ne);ie(cye(),ne);ie(fye(),ne);ie(dye(),ne);ie(hye(),ne);ie(mye(),ne);ie(gye(),ne);ie(yye(),ne);ie(Eye(),ne);ie(Aye(),ne);ie(Sye(),ne);ie(vye(),ne);ie(_ye(),ne);ie(bye(),ne);ie(Rye(),ne);ie(Fye(),ne);ie(nAe(),ne);ie(iAe(),ne);ie(XI(),ne);ie(oAe(),ne);ie(IS(),ne);ie(aAe(),ne);ie(lAe(),ne);ie(wX(),ne);ie(hs(),ne);ie(cAe(),ne);ie(GJ(),ne);ie(AY(),ne);ie(fAe(),ne);ie(tI(),ne);ie(JL(),ne);ie(QS(),ne);ie(xAe(),ne);ie(dAe(),ne);ie(mAe(),ne);ie(LAe(),ne);ie(FZ(),ne);ie(PS(),ne);ie(MAe(),ne);ie(PAe(),ne);ie(bS(),ne);ie(MZ(),ne);ie(GJ(),ne);ie(Ym(),ne);ie(lZ(),ne);ie(tZ(),ne);ie(CS(),ne);ie(pY(),ne);ie(kS(),ne);ie(kZ(),ne);ie(gY(),ne);ie(BAe(),ne);ie(hZ(),ne);ie(UAe(),ne);ie(SZ(),ne);ie(nZ(),ne);ie(mZ(),ne);ie(n5(),ne);ie(r5(),ne);ie(jAe(),ne);ie(vK(),ne);ie(VAe(),ne);ie(WAe(),ne);ie(KAe(),ne);ie(zL(),ne);ie(pI(),ne);ie(XAe(),ne);ie(JAe(),ne);ie(ir(),ne);ie(eSe(),ne);ie(u5(),ne);ie(mt(),ne);ie(tSe(),ne);ie(nSe(),ne);ie(iSe(),ne);ie(sSe(),ne);ie(oSe(),ne)});var uSe=v(ef=>{"use strict";var Zat=ef&&ef.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),eut=ef&&ef.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tut=ef&&ef.__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)&&Zat(e,t,r);return eut(e,t),e};Object.defineProperty(ef,"__esModule",{value:!0});ef.MalloyToAST=void 0;var aSe=E8(),rut=eY(),M=tut(NP()),nut=Is(),iut=NP(),zn=WC(),KZ=Ke(),sut=Wm(),FP=class extends M.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}},_5=class extends M.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}},out=["##! m4warnings=error"],XZ=class extends rut.AbstractParseTreeVisitor{constructor(e,r,n){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=n;for(let i of out){let s=sut.Tag.fromTagline(i,this.compilerFlags);this.compilerFlags=s.tag}}internalError(e,r){let n=`Internal Translator Error: ${r}`;return this.contextError(e,n),new Error(n)}astError(e,r,n="error"){this.msgLog.log({message:r,at:e.location,severity:n})}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}contextError(e,r,n="error"){this.msgLog.log({message:r,at:this.getLocation(e),severity:n})}inExperiment(e,r){let n=this.compilerFlags.tag("experimental");return n&&(n.bare()||n.has(e))?!0:(this.contextError(r,`Experimental flag '${e}' required to enable this feature`),!1)}m4Severity(){let e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,r){let n=this.m4Severity();n&&this.contextError(e,r,n)}only(e,r,n){let i=[];for(let s of e){let o=r(s);o?i.push(o):s instanceof _5||this.astError(s,`Parser enountered unexpected statement type '${s.elementType}' when it needed '${n}'`)}return i}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new M.FieldName((0,zn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new M.ModelEntryReference((0,zn.getId)(e)),e.id())}defaultResult(){return new M.Unimplemented}astAt(e,r){return e.location={url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(r)},e}getSourceCode(e){let r=e.start.startIndex,n=e.stop||e.start,i=new nut.Interval(r,n.stopIndex);return this.parseInfo.sourceStream.getText(i)}getFilterElement(e){let r=this.getFieldExpr(e),n=new M.FilterElement(r,this.getSourceCode(e));return this.astAt(n,e)}getFieldDefs(e,r){return e.map(n=>this.getFieldDef(n,r))}getFieldExpr(e){let r=this.visit(e);if(r instanceof M.ExpressionDef)return this.astAt(r,e);throw this.internalError(e,`expression node unknown type '${r.elementType}'`)}getFilterShortcut(e){let r=this.getFilterElement(e.fieldExpr());return this.m4advisory(e,"Filter shortcut `{? condition }` is deprecated; use `{ where: condition } instead"),new M.Filter([r])}getPlainString(e){let r=(0,zn.getStringIfShort)(e);if(r)return r;let n=[],i=e.string().sqlString();if(i){for(let s of(0,zn.getStringParts)(i))s instanceof aSe.ParserRuleContext?this.contextError(s,"%{ query } illegal in this string"):n.push(s);return(0,zn.unIndent)(n),n.join("")}return""}makeSqlString(e,r){for(let n of e.sqlInterpolation())n.CLOSE_CODE()&&this.m4advisory(n,"Use %{ ... } instead of %{ ... }%");for(let n of(0,zn.getStringParts)(e))n instanceof aSe.ParserRuleContext?r.push(this.visit(n)):r.push(n);r.complete(),this.astAt(r,e)}parseTime(e,r){let n=r(e.text);return n||(this.contextError(e,"Time data parse error"),n=new M.LiteralTimestamp({text:e.text})),this.astAt(n,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){let r=this.only(e.malloyStatement().map(n=>this.visit(n)),n=>M.isDocStatementOrDocStatementList(n)&&n,"statement");return new M.Document(r)}visitDefineSourceStatement(e){let n=e.sourcePropertyList().sourceDefinition().map(o=>this.visitSourceDefinition(o)),i=this.getNotes(e.tags()),s=new M.DefineSourceList(n);return s.extendNote({blockNotes:i}),s}visitSourceDefinition(e){let r=this.visit(e.sqExplore()),n=new M.DefineSource((0,zn.getId)(e.sourceNameDef()),r instanceof M.SourceQueryElement?r:void 0,!0,[]),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return n.extendNote({notes:i}),this.astAt(n,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){let r=e.filterShortcut(),n=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>M.isSourceProperty(s)&&s,"source property"),i=new M.SourceDesc(n);return r&&i.push(this.getFilterShortcut(r)),i}visitTableFunction(e){let r=this.getPlainString(e.tableURI()),n=this.astAt(new M.TableFunctionSource(r),e);return this.m4advisory(e,"`table('connection_name:table_path')` is deprecated; use `connection_name.table('table_path')`"),n}visitTableMethod(e){let r=e.connectionId(),n=this.astAt(this.getModelEntryName(r),r),i=this.getPlainString(e.tablePath());return this.astAt(new M.TableMethodSource(n,i),e)}getLegacySQLSouce(e){let r=this.getModelEntryName(e);return this.astAt(new M.FromSQLSource(r),e)}visitSqlSource(e){let r=e.connectionId(),n=this.astAt(this.getModelEntryName(r),r),i=new M.SQLString,s=e.sqlString();s&&this.makeSqlString(s,i);let o=e.shortString();o&&i.push((0,zn.getShortString)(o));let a=new M.SQLSource(n,i);return this.astAt(a,e)}visitDefJoinMany(e){let r=[];for(let i of e.joinList().joinDef()){let s=this.visit(i);s instanceof M.Join&&(r.push(s),s instanceof M.ExpressionJoin?(s.joinType="many",s.joinOn===void 0&&this.contextError(e,"join_many: requires ON expression")):s instanceof M.KeyJoin&&this.contextError(e,"Foreign key join not legal in join_many:"))}let n=new M.Joins(r);return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitDefJoinOne(e){let r=this.getJoinList(e.joinList()),n=[];for(let s of r)s instanceof M.Join&&(n.push(s),s instanceof M.ExpressionJoin&&(s.joinType="one"));let i=new M.Joins(n);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}visitDefJoinCross(e){let r=this.getJoinList(e.joinList()),n=[];for(let s of r)s instanceof M.Join&&(n.push(s),s instanceof M.ExpressionJoin?s.joinType="cross":s.log("Foreign key join not legal in join_cross:"));let i=new M.Joins(n);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}getJoinList(e){return e.joinDef().map(r=>this.visit(r))}getJoinSource(e,r){if(r){let n=this.getSqExpr(r.sqExpr()),i=this.getNotes(r._before_is).concat(this.getNotes(r._after_is));return{joinFrom:n,notes:i}}return{joinFrom:new M.SQReference(e),notes:[]}}visitQueryJoinStatement(e){let r=this.astAt(this.visit(e.joinStatement()),e);return this.m4advisory(e,"Joins in queries are deprecated, move into an `extend:` block."),r}visitJoinOn(e){var r;let n=this.getModelEntryName(e.joinNameDef()),{joinFrom:i,notes:s}=this.getJoinSource(n,e.isExplore()),o=new M.ExpressionJoin(n,i),a=e.joinExpression(),u=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,KZ.isMatrixOperation)(u)?o.matrixOperation=u:this.contextError(e,"Internal Error: Unknown matrixOperation"),a&&(o.joinOn=this.getFieldExpr(a)),o.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(o,e)}visitJoinWith(e){let r=this.getModelEntryName(e.joinNameDef()),{joinFrom:n,notes:i}=this.getJoinSource(r,e.isExplore()),s=this.getFieldExpr(e.fieldExpr()),o=new M.KeyJoin(r,n,s);return o.extendNote({notes:this.getNotes(e).concat(i)}),this.astAt(o,e)}getFieldDef(e,r){let n=e.fieldExpr(),i=(0,zn.getId)(e.fieldNameDef()),s=this.getFieldExpr(n),o=new r(s,i,this.getSourceCode(n)),a=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return o.extendNote({notes:a}),this.astAt(o,e)}visitDefDimensions(e){let r=this.getFieldDefs(e.defList().fieldDef(),M.DimensionFieldDeclaration),n=new M.Dimensions(r);return n.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(n,e)}visitDefMeasures(e){let r=this.getFieldDefs(e.defList().fieldDef(),M.MeasureFieldDeclaration),n=new M.Measures(r);return n.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(n,e)}visitQueryExtend(e){let r=[],n=e.queryExtendStatementList().queryExtendStatement().map(s=>this.visit(s));for(let s of n)if(M.isQueryExtendProperty(s))r.push(s);else throw this.internalError(e,`Query extend matched, but ${s.elementType} found`);let i=new M.ExtendBlock(r);return this.astAt(i,e)}visitDeclareStatement(e){let r=this.getFieldDefs(e.defList().fieldDef(),M.DeclareFieldDeclaration),n=new M.DeclareFields(r),i=this.astAt(n,e);return this.m4advisory(e,"`declare:` is deprecated; use `dimension:` or `measure:` inside a source or `extend:` block"),i}visitExploreRenameDef(e){let r=e.fieldName(0),n=e.fieldName(1),i=new M.RenameField((0,zn.getId)(r),this.getFieldName(n));return this.astAt(i,e)}visitDefExploreRename(e){let n=e.renameList().exploreRenameDef().map(s=>this.visitExploreRenameDef(s)),i=new M.Renames(n);return this.astAt(i,e)}visitFilterClauseList(e){return new M.Filter(e.fieldExpr().map(r=>this.getFilterElement(r)))}visitWhereStatement(e){let r=this.visitFilterClauseList(e.filterClauseList());return r.having=!1,this.astAt(r,e)}visitHavingStatement(e){let r=this.visitFilterClauseList(e.filterClauseList());return r.having=!0,this.astAt(r,e)}visitSubQueryDefList(e){let r=e.exploreQueryDef().map(n=>this.visitExploreQueryDef(n));return new M.Views(r)}visitDefExploreQuery(e){let r=this.visitSubQueryDefList(e.subQueryDefList()),n=this.getNotes(e.tags());return r.extendNote({blockNotes:n}),e.QUERY()&&this.m4advisory(e,"Use view: inside of a source instead of query:"),r}visitDefExplorePrimaryKey(e){let r=new M.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}visitFieldNameList(e){let r=e.fieldName().map(n=>new M.AcceptExceptFieldReference([this.getFieldName(n)]));return new M.FieldReferences(r)}visitDefExploreEditField(e){let r=e.ACCEPT()?"accept":"except";return new M.FieldListEdit(r,this.visitFieldNameList(e.fieldNameList()))}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){let r=this.getPlainString(e),n=this.astAt(new M.TimezoneStatement(r),e.string());return n.isValid||this.astError(n,`Invalid timezone: ${n.tz}`),this.astAt(n,e)}visitQueryProperties(e){let r=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>M.isQueryProperty(i)&&i,"query statement"),n=e.filterShortcut();return n&&r.push(this.getFilterShortcut(n)),new M.QOpDesc(r)}getFieldPath(e,r){let n=e.fieldName().map(i=>this.getFieldName(i));return this.astAt(new r(n),e)}getQueryFieldDef(e,r){let n=this.getFieldDef(e,r);return this.astAt(n,e)}getQueryFieldEntry(e,r,n){let i=e.taggedRef();if(i)return this.getTaggedRef(i,r,n);let s=e.fieldDef();if(s)return this.getQueryFieldDef(s,r);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,r,n){return this.only(e.queryFieldEntry().map(i=>this.getQueryFieldEntry(i,r,n)),i=>i instanceof M.FieldReference||i instanceof M.AtomicFieldDeclaration?i:!1,"view field")}visitAggregateStatement(e){let r=new M.Aggregate(this.getQueryItems(e.queryFieldList(),M.AggregateFieldDeclaration,M.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){let r=new M.GroupBy(this.getQueryItems(e.queryFieldList(),M.GroupByFieldDeclaration,M.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){let r=new M.Calculate(this.getQueryItems(e.queryFieldList(),M.CalculateFieldDeclaration,M.CalculateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}getTaggedRef(e,r,n){let i=e.refExpr();if(i){let o=this.getFieldPath(e.fieldPath(),M.ExpressionFieldReference),a,u=i.timeframe();u&&(a=new M.ExprGranularTime(new M.ExprIdReference(o),this.visitTimeframe(u).text,!0));let l=i.aggregate();if(l){let f=l.text.toLowerCase();if(f==="sum")a=new M.ExprSum(void 0,o);else return this.contextError(l,`\`${f}\` is not legal in a reference-only aggregation`),o}let c=new r(a,o.outputName);return c.extendNote({notes:this.getNotes(e.tags())}),c}let s=this.getFieldPath(e.fieldPath(),n);return s.extendNote({notes:this.getNotes(e.tags())}),s}getFieldCollectionMember(e,r,n){let i=e.fieldDef();if(i)return this.getFieldDef(i,r);let s=e.taggedRef();if(s)return this.getTaggedRef(s,r,n);let o=e.collectionWildCard();if(o)return this.visitCollectionWildCard(o);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){let r=e.collectionMember().map(n=>this.getFieldCollectionMember(n,M.ProjectFieldDeclaration,M.ProjectFieldReference));return this.astAt(new M.ProjectStatement(r),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project: keyword is deprecated, use select:");let r=this.visitFieldCollection(e.fieldCollection());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCollectionWildCard(e){var r;let n=e.fieldPath(),i=n?this.getFieldPath(n,M.ProjectFieldReference):void 0,s=this.astAt(new M.WildcardFieldReference(i),e),o=((r=e.starQualified())===null||r===void 0?void 0:r.fieldNameList())||[];for(let a of o)for(let u of a.fieldName())s.except.add((0,zn.getId)(u));return s}visitIndexFields(e){let r=e.indexElement().map(n=>{let i=n.fieldPath();if(!i)return this.astAt(new M.WildcardFieldReference(void 0),e);let s=this.getFieldPath(i,M.IndexFieldReference);return n.STAR()?this.astAt(new M.WildcardFieldReference(s),e):this.astAt(s,e)});return new M.FieldReferences(r)}visitIndexStatement(e){let r=this.visitIndexFields(e.indexFields()),n=new M.Index(r),i=e.fieldName();return i&&n.useWeight(this.getFieldName(i)),this.astAt(n,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new M.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){let r=e.ASC()?"asc":e.DESC()?"desc":void 0,n=e.fieldExpr(),i=n?this.getFieldExpr(n):void 0;return this.astAt(new M.FunctionOrderBy(i,r),e)}visitAggregateOrderByStatement(e){return this.inExperiment("function_order_by",e),this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){let r=e.aggregateOrderBySpec().map(n=>this.visitAggregateOrderBySpec(n));return this.astAt(new M.FunctionOrdering(r),e)}visitOrderBySpec(e){let r=e.ASC()?"asc":e.DESC()?"desc":void 0,n=e.INTEGER_LITERAL();if(n)return new M.OrderBy(this.getNumber(n),r);let i=e.fieldName();if(i)return new M.OrderBy(this.getFieldName(i),r);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){let r=e.orderBySpec().map(n=>this.visitOrderBySpec(n));return this.astAt(new M.Ordering(r),e)}visitTopStatement(e){let r=e.bySpec(),n=this.getNumber(e.INTEGER_LITERAL()),i;if(r){this.m4advisory(r,"by clause of top statement unupported. Use order_by instead");let s=r.fieldName();if(s){let a=this.getFieldName(s);i=new M.Top(n,a)}let o=r.fieldExpr();o&&(i=new M.Top(n,this.getFieldExpr(o)))}return i||(i=new M.Top(n,void 0)),this.astAt(i,e)}visitSourceID(e){return this.astAt(new M.NamedSource((0,zn.getId)(e)),e)}visitTopLevelQueryDefs(e){let r=e.topLevelQueryDef().map(s=>this.visitTopLevelQueryDef(s)),n=this.getNotes(e.tags()),i=new M.DefineQueryList(r);return i.extendNote({blockNotes:n}),i}visitTopLevelQueryDef(e){let r=(0,zn.getId)(e.queryName()),n=this.visit(e.sqExpr()),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(n instanceof M.SourceQueryElement){let s=new M.DefineQuery(r,n);return s.extendNote({notes:i}),this.astAt(s,e)}throw this.internalError(e,`Expected query definition, got a '${n.elementType}'`)}visitAnonymousQuery(e){let r=e.topLevelAnonQueryDef(),n=this.getSqExpr(r.sqExpr()),i=this.astAt(new M.AnonymousQuery(n),r),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.m4advisory(r,"Anonymous `query:` statements are deprecated, use `run:` instead"),this.astAt(i,e)}visitRunStatement(e){let r=e.topLevelAnonQueryDef(),n=this.getSqExpr(r.sqExpr()),i=this.astAt(new M.AnonymousQuery(n),r),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.astAt(i,e)}visitNestStatement(e){let r=this.visitNestedQueryList(e.nestedQueryList());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitNestedQueryList(e){return new M.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof M.NestFieldDeclaration&&r,"query"))}visitNestDef(e){let r=e.queryName(),n,i=this.getVExpr(e.vExpr());if(r)n=(0,zn.getId)(r);else{let a=i.getImplicitName();a===void 0&&this.contextError(e,"`nest:` view requires a name (add `nest_name is ...`)"),n=a??"__unnamed__"}let s=new M.NestFieldDeclaration(n,i),o=e.isDefine();return s.extendNote({notes:this.getNotes(e.tags()).concat(o?this.getIsNotes(o):[])}),this.astAt(s,e)}visitExploreQueryDef(e){let r=(0,zn.getId)(e.exploreQueryNameDef()),n=new M.ViewFieldDeclaration(r,this.getVExpr(e.vExpr())),i=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return n.extendNote({notes:i}),this.astAt(n,e)}visitExprNot(e){return new M.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new M.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(r=>this.getFieldExpr(r))}visitExprLogicalOr(e){let r=this.getFieldExpr(e.fieldExpr(0)),n=this.getFieldExpr(e.fieldExpr(1));return new M.ExprLogicalOp(r,"or",n)}visitExprLogicalAnd(e){let r=this.getFieldExpr(e.fieldExpr(0)),n=this.getFieldExpr(e.fieldExpr(1));return new M.ExprLogicalOp(r,"and",n)}visitExprOrTree(e){let r=this.getFieldExpr(e.fieldExpr()),n=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new M.ExprAlternationTree(r,"|",n),e)}visitExprAndTree(e){let r=this.getFieldExpr(e.fieldExpr()),n=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new M.ExprAlternationTree(r,"&",n),e)}visitExprCoalesce(e){let r=this.getFieldExpr(e.fieldExpr()[0]),n=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new M.ExprCoalesce(r,n),e)}visitPartialAllowedFieldExpr(e){var r;let n=this.getFieldExpr(e.fieldExpr()),i=(r=e.compareOp())===null||r===void 0?void 0:r.text;if(i){if(M.isComparison(i))return this.astAt(new M.PartialCompare(i,n),e);throw this.internalError(e,`partial comparison '${i}' not recognized`)}return n}visitExprString(e){let r=this.getPlainString(e);return new M.ExprString(r)}visitExprRegex(e){let r=e.HACKY_REGEX().text;return new M.ExprRegEx(r.slice(2,-1))}visitExprNow(e){return new M.ExprNow}visitExprNumber(e){return new M.ExprNumber(e.text)}visitExprFieldPath(e){let r=new M.ExprIdReference(this.getFieldPath(e.fieldPath(),M.ExpressionFieldReference));return this.astAt(r,e)}visitExprNULL(e){return new M.ExprNULL}visitExprExpr(e){return new M.ExprParens(this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprMinus(e){return new M.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){let r=this.getFieldExpr(e.fieldExpr(0)),n=this.getFieldExpr(e.fieldExpr(1)),i=e.PLUS()?"+":"-";return new M.ExprAddSub(r,i,n)}visitExprMulDiv(e){let r=e.STAR()?"*":e.SLASH()?"/":"%";return new M.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){let r=e.compareOp().text;if(M.isComparison(r))return new M.ExprCompare(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)));throw this.internalError(e,`untranslatable comparison operator '${r}'`)}visitExprCountDisinct(e){return this.m4advisory(e,"`count(distinct expression)` deprecated, use `count(expression)` instead"),this.astAt(new M.ExprCountDistinct(this.getFieldExpr(e.fieldExpr())),e)}visitExprUngroup(e){let r=e.fieldName().map(i=>this.getFieldName(i)),n=e.ungroup().text.toLowerCase();return this.astAt(new M.ExprUngroup(n==="all"?n:"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){let r=e.fieldPath(),n=this.getFieldPath(r,M.ExpressionFieldReference),i=r&&n?this.astAt(n,r):void 0,s=e.aggregate().text.toLowerCase(),o=e.fieldExpr();if(e.aggregate().COUNT())return o&&this.contextError(o,"Expression illegal inside path.count()"),new M.ExprCount(i);let a=o?this.getFieldExpr(o):void 0;if(s==="min"||s==="max")if(a)this.contextError(e,this.symmetricAggregateUsageError(s));else{let u=this.astAt(new M.ExprIdReference(n),r);return s==="min"?new M.ExprMin(u):new M.ExprMax(u)}else{if(s==="avg")return new M.ExprAvg(a,i);if(s==="sum")return new M.ExprSum(a,i);this.contextError(e,`Cannot parse aggregate function ${s}`)}return new M.ExprNULL}visitExprPathlessAggregate(e){let r=e.fieldExpr(),n=r?this.getFieldExpr(r):void 0,i=void 0,s=e.aggregate().text.toLowerCase();if(e.STAR()&&this.m4advisory(e,`* illegal inside ${s}()`),s==="count")return this.astAt(n?new M.ExprCountDistinct(n):new M.ExprCount,e);if(s==="min"){if(n)return new M.ExprMin(n);this.contextError(e,this.symmetricAggregateUsageError(s))}else if(s==="max"){if(n)return new M.ExprMax(n);this.contextError(e,this.symmetricAggregateUsageError(s))}else{if(n===void 0)return this.contextError(e,this.asymmetricAggregateUsageError(s)),new M.ExprNULL;let o=e.SOURCE_KW()!==void 0;if(s==="avg")return new M.ExprAvg(n,i,o);if(s==="sum")return new M.ExprSum(n,i,o)}return new M.ExprNULL}visitExprApply(e){return new M.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new M.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){let r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new M.ExprCast(this.getFieldExpr(e.fieldExpr()),r)}getMalloyOrSQLType(e){let r=e.malloyType();if(r){let i=r.text;if((0,KZ.isCastType)(i))return i;throw this.internalError(e,`unknown type '${i}'`)}let n=e.string();if(n)return{raw:this.getPlainString({string:()=>n})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){let r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new M.ExprCast(this.getFieldExpr(e.fieldExpr()),r,!0)}visitExprTimeTrunc(e){return new M.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new M.Timeframe(e.text)}visitExprForRange(e){let r=this.getFieldExpr(e._startAt),n=this.getFieldExpr(e._duration),i=this.visitTimeframe(e.timeframe());return new M.ForRange(r,n,i)}visitExprAggFunc(e){let r=e.argumentList(),n=r?this.allFieldExpressions(r.fieldExpr()):[],i=(0,zn.getId)(e),s=e.fieldPath(),o=s?this.getFieldPath(s,M.ExpressionFieldReference):void 0,a=s&&o?this.astAt(o,s):void 0;return M.ExprTimeExtract.extractor(i)?this.astAt(new M.ExprTimeExtract(i,n),e):this.astAt(new M.ExprFunc(i,n,!1,void 0,a),e)}visitExprFunc(e){var r,n;let i=e.argumentList(),s=i?this.allFieldExpressions(i.fieldExpr()):[],o=e.EXCLAM()!==void 0,a=(r=e.malloyType())===null||r===void 0?void 0:r.text,u;a&&((0,KZ.isCastType)(a)?u=a:(this.contextError(e,`'#' assertion for unknown type '${a}'`),u=void 0));let l=(0,zn.getOptionalId)(e)||((n=e.timeframe())===null||n===void 0?void 0:n.text);return l===void 0&&(this.contextError(e,"Function name error"),l="FUNCTION_NAME_ERROR"),M.ExprTimeExtract.extractor(l)?this.astAt(new M.ExprTimeExtract(l,s),e):this.astAt(new M.ExprFunc(l,s,o,u),e)}visitExprDuration(e){return new M.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitPickStatement(e){let r=e.pick().map(n=>{let i;return n._pickValue&&(i=this.getFieldExpr(n._pickValue)),new M.PickWhen(i,this.getFieldExpr(n._pickWhen))});return e.ELSE()?new M.Pick(r,this.getFieldExpr(e._pickElse)):new M.Pick(r)}visitExprFieldProps(e){let r=this.only(e.fieldProperties().fieldPropertyStatement().map(n=>this.visit(n)),n=>M.isFieldPropStatement(n)&&n,"field property statement");return new M.ExprProps(this.getFieldExpr(e.fieldExpr()),r)}visitPartitionByStatement(e){return this.inExperiment("partition_by",e),this.astAt(new M.PartitionBy(e.id().map(r=>this.astAt(new M.PartitionByFieldReference([this.astAt(new M.FieldName((0,zn.idToStr)(r)),r)]),r))),e)}visitLiteralTimestamp(e){return this.parseTime(e,M.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,M.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,M.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,M.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,M.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,M.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,M.LiteralYear.parse)}visitImportStatement(e){let r=this.getPlainString(e.importURL()),n=this.astAt(new M.ImportStatement(r,this.parseInfo.importBaseURL),e),i=e.importSelect();if(i)for(let s of i.importItem()){let o=s.id(),a=o[1]?this.astAt(new M.ImportSourceName((0,zn.idToStr)(o[1])),o[1]):void 0;n.push(this.astAt(new M.ImportSelect((0,zn.idToStr)(o[0]),a),o[0]))}return n}visitJustExpr(e){return this.getFieldExpr(e.fieldExpr())}visitDefineSQLStatement(e){var r;let n=(r=e.nameSQLBlock())===null||r===void 0?void 0:r.text,i=e.sqlBlock().blockSQLDef(),s=new M.SQLString,o;for(let l of i){let c=l.connectionName();c&&(o?this.contextError(c,"Cannot redefine connection"):o=this.getPlainString(c));let f=l.sqlString();f&&this.makeSqlString(f,s)}let a=new M.SQLStatement(s);o!==void 0&&(a.connection=o),a.is=n;let u=this.astAt(a,e);return this.m4advisory(e,"`sql:` statement is deprecated, use `connection_name.sql(...)` instead"),u}visitSampleStatement(e){let r=e.sampleSpec().INTEGER_LITERAL();if(r)return new M.SampleProperty({rows:this.getNumber(r)});let n=e.sampleSpec().PERCENT_LITERAL();if(n)return new M.SampleProperty({percent:this.getNumber(n)});let i=e.sampleSpec().TRUE()!==void 0;return new M.SampleProperty({enable:i})}visitDocAnnotations(e){let r=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)})),n=new M.ModelAnnotation(r);return this.compilerFlags=n.getCompilerFlags(this.compilerFlags,this.msgLog),n}visitIgnoredObjectAnnotations(e){return this.contextError(e,"Object annotation not connected to any object"),new _5(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"Model annotations not allowed at this scope"),new _5(e.text)}visitDefExploreAnnotation(e){let r=this.getNotes(e);return new M.ObjectAnnotation(r)}visitSQID(e){let r=this.getModelEntryName(e);return this.astAt(new M.SQReference(r),e.id())}getSqExpr(e){let r=this.visit(e);return r instanceof M.SourceQueryElement?r:(this.contextError(e,`Expected a source/query expression, not '${r.elementType}'`),new FP)}visitSQExtendedSource(e){let r=this.getSqExpr(e.sqExpr()),n=new M.SQExtend(r,this.getSourceExtensions(e.exploreProperties()));return this.astAt(n,e)}visitSQParens(e){let r=this.getSqExpr(e.sqExpr());return this.astAt(r,e)}visitSQArrow(e){let r=this.getSqExpr(e.sqExpr()),n=e.segExpr(),i=new M.SQArrow(r,this.getVExpr(n));return this.astAt(i,e)}getVExpr(e){let r=this.visit(e);if(r instanceof M.View)return r;throw this.internalError(e,`Expected view, got a '${r.elementType}'`)}visitSegField(e){return new M.ReferenceView(this.getFieldPath(e.fieldPath(),M.ViewOrScalarFieldReference))}visitSegOps(e){return new M.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new M.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new M.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){let r=this.getSqExpr(e.sqExpr()),n=e.segExpr(),i=new M.SQRefine(r,this.getVExpr(n));return this.astAt(i,e)}visitSQTable(e){let r=this.visit(e.exploreTable());if(r instanceof iut.TableSource){let n=new M.SQSource(r);return this.astAt(n,e)}return new FP}visitSQSQL(e){let r=new M.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(r,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new M.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}};ef.MalloyToAST=XZ});var lSe=v(wP=>{"use strict";Object.defineProperty(wP,"__esModule",{value:!0});wP.MessageLog=void 0;var JZ=class{constructor(){this.rawLog=[]}getLog(){return this.rawLog}log(e){this.rawLog.push(e)}reset(){this.rawLog.length=0}noErrors(){return!this.hasErrors()}hasErrors(){return this.rawLog.find(r=>r.severity!=="warn")!==void 0}empty(){return this.rawLog.length===0}};wP.MessageLog=JZ});var cSe=v(LP=>{"use strict";Object.defineProperty(LP,"__esModule",{value:!0});LP.Zone=void 0;var ZZ=class{constructor(){this.location={},this.zone=new Map}get(e){let r=this.zone.get(e);if(r?.status==="present")return r.value}getEntry(e){let 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){let n=this.zone.get(e);n?.status===void 0&&(this.zone.set(e,{status:"reference",firstReference:r}),this.location[e]=r)}getUndefined(){let e=[];for(let[r,n]of this.zone)n.status==="reference"&&e.push(r);return e.length>0?e:void 0}updateFrom(e,r){if(e)for(let[n,i]of Object.entries(e))i!==void 0&&this.define(n,i);if(r)for(let[n,i]of Object.entries(r))this.zone.set(n,{status:"error",message:i})}};LP.Zone=ZZ});var fSe=v(IP=>{"use strict";Object.defineProperty(IP,"__esModule",{value:!0});IP.walkForDocumentSymbols=void 0;var aut=_p(),uut=WC(),eee=class{constructor(e,r,n,i){this.translator=e,this.tokens=r,this.scopes=n,this.symbols=i}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){let r=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=r)}enterTopLevelQueryDef(e){this.symbols.push({range:this.translator.rangeFromContext(e),name:e.queryName().text,type:"query",children:[],lensRange:this.blockRange}),this.blockRange=void 0}enterRunStatement(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterAnonymousQuery(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef().sqExpr()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterDefineSourceStatement(e){let r=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=r)}enterSourceDefinition(e){let 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){let r=this.popScope();r&&this.symbols.push(r)}enterDefExploreQuery(e){let r=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=r)}enterExploreQueryDef(e){let r={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},n=this.peekScope();n&&n.children.push(r),this.scopes.push(r),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}getNestDefName(e){let r=e.queryName();if(r)return r.id().text;let n,i=!1,s={enterVArrow(a){a.vExpr().enterRule(s)},enterVSeg(a){a.segExpr().enterRule(o)}},o={enterSegField(a){let u=a.fieldPath().fieldName();i||(n??(n=u[u.length-1].id().text))},enterSegParen(a){a.vExpr().enterRule(s)},enterSegRefine(a){a._lhs.enterRule(o)},enterSegOps(){n=void 0,i=!0}};return e.vExpr().enterRule(s),n}handleNestEntry(e){let r=this.getNestDefName(e);if(r===void 0)return;let n={range:this.translator.rangeFromContext(e),name:r,type:"query",children:[]},i=this.peekScope();return i&&i.children.push(n),n}enterNestDef(e){let r=this.handleNestEntry(e);r&&this.scopes.push(r)}exitNestDef(e){this.popScope()}enterFieldDef(e){let r={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},n=this.peekScope();n&&n.children.push(r)}enterQueryFieldEntry(e){var r;let n=(r=e.taggedRef())===null||r===void 0?void 0:r.fieldPath();if(n===void 0)return;let i={range:this.translator.rangeFromContext(e),name:n.text,type:"field",children:[]},s=this.peekScope();s&&s.children.push(i)}enterExploreRenameDef(e){let r={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},n=this.peekScope();n&&n.children.push(r)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){let r={range:this.translator.rangeFromContext(e),name:e.joinNameDef().id().text,type:"join",children:[]},n=this.peekScope();n&&n.children.push(r)}enterDefineSQLStatement(e){let r=e.nameSQLBlock().text,n={range:this.translator.rangeFromContext(e),name:r,type:"sql",children:[]};this.symbols.push(n)}enterImportStatement(e){let r=(0,uut.getStringIfShort)(e.importURL());r&&this.scopes.push({range:this.translator.rangeFromContext(e),name:r,type:"import",children:[]})}exitImportStatement(){let e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){let r=this.peekScope();if(r)for(let n of e.importItem()){let i={range:this.translator.rangeFromContext(e),name:n.text,type:"import_item",children:[]};r.children.push(i)}}};function lut(t,e,r){let n=new eee(t,e,[],[]),i=n;return aut.ParseTreeWalker.DEFAULT.walk(i,r),n.symbols}IP.walkForDocumentSymbols=lut});var ree=v(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.sortHighlights=Ue.walkForDocumentHighlights=Ue.passForHighlights=Ue.HighlightType=void 0;var cut=_p(),Te=ZW();Ue.HighlightType={Identifier:"identifier",Type:"type",Literal:{Date:"literal.date",Number:"literal.number",String:"literal.string",RegularExpression:"literal.regular_expression",Boolean:"literal.boolean",Null:"literal.null"},Call:{Aggregate:"call.aggregate",TimeFrame:"call.time_frame",Cast:"call.cast",Table:"call.table",From:"call.from",Function:"call.function",FromSQL:"call.from_sql"},Keyword:{AggregateModifier:{Distinct:"keyword.aggregate_modifier.distinct"},CastModifier:{As:"keyword.cast_modifier.as"},Is:"keyword.is",On:"keyword.on",Desc:"keyword.desc",Asc:"keyword.asc",Pick:"keyword.pick",When:"keyword.when",Else:"keyword.else",With:"keyword.with",JSON:"keyword.json",Turtle:"keyword.turtle",Import:"keyword.import"},Operator:{Comparison:"operator.comparison",Boolean:"operator.boolean",Date:"operator.date"},Comment:{Line:"comment.line",Block:"comment.block"},Property:{Accept:"property.accept",Aggregate:"property.aggregate",Dimension:"property.dimension",Except:"property.except",Source:"property.source",GroupBy:"property.group_by",Having:"property.having",Index:"property.index",JoinOne:"keyword.join_one",JoinMany:"keyword.join_many",JoinCross:"keyword.join_cross",Limit:"property.limit",Measure:"property.measure",Nest:"property.nest",OrderBy:"property.order_by",PrimaryKey:"property.primary_key",Project:"property.project",Query:"property.query",Rename:"property.rename",Top:"property.top",Where:"property.where",SQL:"property.sql"}};function fut(t){let e=[],r=(n,i,s=!1)=>{var o;let a=n.startIndex-n.charPositionInLine,u=((o=n.text)===null||o===void 0?void 0:o.split(`
|
|
681
|
+
`)),fI.ErrorFactory.structDef}else if(i.status==="present"){let s=this.select.location,o={...i.value,fields:i.value.fields.map(l=>({...l,location:s})),location:this.location},a=this.document(),u=a?.currentModelAnnotation();return u&&(o.modelAnnotation=u),o}else return this.log("`connection_name.sql(...)` can currently only be used in top level source/query definitions"),fI.ErrorFactory.structDef}};xI.SQLSource=SK});var N3e=v(dI=>{"use strict";Object.defineProperty(dI,"__esModule",{value:!0});dI.SQSource=void 0;var Ttt=Dp(),Ctt=EK(),Rtt=vK(),_K=class extends Ttt.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 Rtt.SQLSource){let e=new Ctt.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("This source cannot be used as a query")}};dI.SQSource=_K});var F3e=v(hI=>{"use strict";Object.defineProperty(hI,"__esModule",{value:!0});hI.SQExtend=void 0;var Ott=rK(),Dtt=Dp(),bK=class extends Dtt.SourceQueryElement{constructor(e,r){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;let e=this.sqSrc.getSource();if(e)return this.asSource=new Ott.RefinedSource(e,this.extend),this.has({asSource:this.asSource}),this.asSource;this.sqLog("Could not compute source to extend")}isSource(){return!0}};hI.SQExtend=bK});var pI=v(FS=>{"use strict";Object.defineProperty(FS,"__esModule",{value:!0});FS.isComparison=FS.Comparison=void 0;var TK;(function(t){t.Like="~",t.NotLike="!~",t.LessThan="<",t.LessThanOrEqualTo="<=",t.EqualTo="=",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.NotEqualTo="!="})(TK||(FS.Comparison=TK={}));function Ntt(t){return Object.values(TK).includes(t)}FS.isComparison=Ntt});var pn=v(mI=>{"use strict";Object.defineProperty(mI,"__esModule",{value:!0});mI.FT=void 0;var Ftt=lc();function Xm(t,e="scalar",r="constant"){return{dataType:t,expressionType:e,evalSpace:r}}var $s=class t{static in(e,r){return e?r.find(i=>t.eq(i,e))!==void 0:!1}static eq(e,r){return r!==void 0&&e.dataType===r.dataType&&e.expressionType===r.expressionType}static typeIn(e,r){return e?r.find(i=>t.typeEq(i,e))!==void 0:!1}static typeEq(e,r,n=!1,i=!0){let s=e.dataType===r.dataType,o=n&&(e.dataType==="null"||r.dataType==="null"),a=i&&(e.dataType==="error"||r.dataType==="error");return s||o||a}static inspect(...e){return e.map(n=>{if(n){let i=n.dataType;return(0,Ftt.expressionIsScalar)(n.expressionType)||(i=`${n.expressionType} ${i}`),i}return"undefined"}).join(",")}};mI.FT=$s;$s.nullT=Xm("null");$s.numberT=Xm("number");$s.stringT=Xm("string");$s.dateT=Xm("date");$s.timestampT=Xm("timestamp");$s.boolT=Xm("boolean");$s.anyAtomicT=[$s.numberT,$s.stringT,$s.dateT,$s.timestampT,$s.boolT];$s.aggregateBoolT=Xm("boolean","aggregate")});var yI=v(gI=>{"use strict";Object.defineProperty(gI,"__esModule",{value:!0});gI.isGranularResult=void 0;function wtt(t){return t.dataType==="date"||t.dataType==="timestamp"?t.timeframe!==void 0:!1}gI.isGranularResult=wtt});var js=v(EI=>{"use strict";Object.defineProperty(EI,"__esModule",{value:!0});EI.errorFor=void 0;function Ltt(t){return{dataType:"error",expressionType:"scalar",value:[`_ERROR_${t.replace(/ /g,"_")}`],evalSpace:"constant"}}EI.errorFor=Ltt});var w3e=v(wS=>{"use strict";Object.defineProperty(wS,"__esModule",{value:!0});wS.isEquality=wS.Equality=void 0;var CK;(function(t){t.Like="~",t.NotLike="!~",t.Equals="=",t.NotEquals="!="})(CK||(wS.Equality=CK={}));function Itt(t){return Object.values(CK).includes(t)}wS.isEquality=Itt});var ir=v(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.applyBinary=Kc.getMorphicValue=Kc.ExprDuration=Kc.ExpressionDef=void 0;var mn=Ke(),LS=js(),kx=hs(),Jm=pn(),AI=DS(),Mtt=pI(),Ptt=w3e(),M3e=yI(),ktt=mt(),OK=class extends Error{},SI=class extends ktt.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=Jm.FT.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.dataType!=="error"&&!Jm.FT.in(r,this.legalChildTypes)?(e.log(`'${this.elementType}' Can't use type ${Jm.FT.inspect(r)}`),!1):!0}apply(e,r,n){return B3e(e,n,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,mn.expressionIsAggregate)(e.expressionType)}};Kc.ExpressionDef=SI;var i5=class extends SI{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[Jm.FT.timestampT,Jm.FT.dateT]}apply(e,r,n){let i=n.getExpression(e);if(this.typeCheck(this,i),(0,mn.isTimeFieldType)(i.dataType)&&(r==="+"||r==="-")){let s=this.n.getExpression(e);if(!Jm.FT.typeEq(s,Jm.FT.numberT))return this.log(`Duration units needs number not '${s.dataType}`),(0,LS.errorFor)("illegal unit expression");let o;if((0,M3e.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.dataType==="timestamp"){let a=(0,AI.timeOffset)("timestamp",i.value,r,s.value,this.timeframe);return(0,AI.timeResult)({dataType:"timestamp",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:a},o)}return(0,mn.isDateUnit)(this.timeframe)?(0,AI.timeResult)({dataType:"date",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,AI.timeOffset)("date",i.value,r,s.value,this.timeframe)},o):(this.log(`Cannot offset date by ${this.timeframe}`),(0,LS.errorFor)("ofsset date error"))}return super.apply(e,r,n)}getExpression(e){return{dataType:"duration",expressionType:"scalar",value:["__ERROR_DURATION_IS_NOT_A_VALUE__"],evalSpace:"constant"}}};Kc.ExprDuration=i5;function L3e(t,e){return t.dataType===e?t.value:t.morphic&&t.morphic[e]}function Btt(t,e){if(t.dataType===e)return t;if(t.morphic&&t.morphic[e])return{...t,dataType:e,value:t.morphic[e]}}Kc.getMorphicValue=Btt;function P3e(t,e,r,n){let i=(0,mn.isTimeFieldType)(e.dataType),s=(0,mn.isTimeFieldType)(n.dataType);if(i&&s)if(e.dataType!==n.dataType){let o=L3e(e,"timestamp"),a=L3e(n,"timestamp");if(o&&a)return(0,kx.compose)(o,r,a)}else return(0,kx.compose)(e.value,r,n.value);if((i||s)&&e.dataType!=="null"&&n.dataType!=="null")return t.log(`Cannot compare a ${e.dataType} to a ${n.dataType}`),["false"]}function I3e(t,e){if(t.dataType==="string"){if(e.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:t.value,regexp:e.value}]}else if(e.dataType==="string"&&t.dataType==="regular expression")return[{type:"dialect",function:"regexpMatch",expr:e.value,regexp:t.value}]}function qtt(t,e,r){let n=e==="!="||e==="!~";if(t.dataType==="null"||r.dataType==="null"){let i=n?" NOT":"";return t.dataType!=="null"?[...t.value,` IS${i} NULL`]:r.dataType!=="null"?[...r.value,`IS${i} NULL`]:[n?"false":"true"]}}function Utt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("boolean",i,s);if(o)return o;if(i.dataType==="unsupported"||s.dataType==="unsupported"){let l=i.dataType==="null"||s.dataType==="null",c=i.rawType&&i.rawType===s.rawType;if(!(l||c)){let f=o5(e,i,n,s);if(f)return{...f,dataType:"boolean"}}}let u=P3e(e,i,r,s)||(0,kx.compose)(i.value,r,s.value);if(i.dataType!=="error"&&s.dataType!=="error")switch(r){case"~":case"!~":{if(i.dataType==="string"&&s.dataType==="string")u=(0,kx.compose)(i.value,"LIKE",s.value);else{let l=I3e(i,s);if(l===void 0)throw new OK("Incompatible types for match('~') operator");u=l}u=(0,kx.nullsafeNot)(u,r);break}case"=":case"!=":{let l=qtt(i,r,s);l?u=l:u=(0,kx.nullsafeNot)(I3e(i,s)||(0,kx.compose)(i.value,"=",s.value),r);break}}return{dataType:"boolean",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:u}}function $tt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("boolean",i,s);if(o)return o;let a=(0,mn.maxExpressionType)(i.expressionType,s.expressionType),u=o5(e,i,n,s);if(u)return{...u,dataType:"boolean"};let l=P3e(e,i,r,s)||(0,kx.compose)(i.value,r,s.value);return{dataType:"boolean",expressionType:a,evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:l}}function RK(t,...e){return e.includes(t)}function jtt(t,...e){for(let r of e)if(r.dataType!==t)return!1;return!0}function k3e(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=s5("number",i,s);if(o)return o;let a=o5(e,i,n,s);if(a)return a;let u=(0,mn.maxExpressionType)(i.expressionType,s.expressionType);return jtt("number",i,s)?{dataType:"number",expressionType:u,value:(0,kx.compose)(i.value,r,s.value),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace)}:(e.log(`Non numeric('${i.dataType},${s.dataType}') value with '${r}'`),(0,LS.errorFor)("numbers required"))}function Htt(t,e,r,n){let i=e.getExpression(t),s=n.getExpression(t),o=o5(e,i,n,s);if(o)return o;let a=(0,mn.isTimeFieldType)(i.dataType),u=s5(a?"error":"number",i,s);if(u)return u;if(a){let l=n;if(s.dataType!=="duration")if((0,M3e.isGranularResult)(i))l=new i5(n,i.timeframe);else if(i.dataType==="date")l=new i5(n,"day");else return e.log(`Can not offset time by '${s.dataType}'`),(0,LS.errorFor)(`time plus ${s.dataType}`);return l.apply(t,r,e)}return k3e(t,e,r,n)}function B3e(t,e,r,n){if((0,Ptt.isEquality)(r))return Utt(t,e,r,n);if((0,Mtt.isComparison)(r))return $tt(t,e,r,n);if(RK(r,"+","-"))return Htt(t,e,r,n);if(RK(r,"*","%"))return k3e(t,e,r,n);if(RK(r,"/")){let i=e.getExpression(t),s=n.getExpression(t),o=o5(e,i,n,s);if(o)return e.log("Cannot operate with unsupported type"),o;let a=s5("number",i,s);if(a)return a;if(i.dataType!=="number")e.log("Numerator for division must be a number");else if(s.dataType!=="number")n.log("Denominator for division must be a number");else{let u={type:"dialect",function:"div",numerator:i.value,denominator:s.value};return{dataType:"number",expressionType:(0,mn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,mn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:[u]}}return(0,LS.errorFor)("divide type mismatch")}return e.log(`Cannot use ${r} operator here`),(0,LS.errorFor)("applybinary bad operator")}Kc.applyBinary=B3e;function s5(t,...e){if(e.some(r=>r.dataType==="error"))return{dataType:t,expressionType:(0,mn.maxOfExpressionTypes)(e.map(r=>r.expressionType)),value:["'cascading error'"],evalSpace:(0,mn.mergeEvalSpaces)(...e.map(r=>r.evalSpace))}}function o5(t,e,r,n){let i={dataType:e.dataType,expressionType:(0,mn.maxExpressionType)(e.expressionType,n.expressionType),value:["'unsupported operation'"],evalSpace:(0,mn.mergeEvalSpaces)(e.evalSpace,n.evalSpace)};if(e.dataType==="unsupported")return t.log("Unsupported type not allowed in expression"),{...i,dataType:n.dataType};if(n.dataType==="unsupported")return r.log("Unsupported type not allowed in expression"),i}});var _I=v(vI=>{"use strict";Object.defineProperty(vI,"__esModule",{value:!0});vI.BinaryBoolean=void 0;var q3e=Ke(),ztt=js(),Gtt=pn(),Qtt=ir(),Vtt=hs(),DK=class extends Qtt.ExpressionDef{constructor(e,r,n){super({left:e,right:n}),this.left=e,this.op=r,this.right=n,this.elementType="abstract boolean binary",this.legalChildTypes=[Gtt.FT.boolT]}getExpression(e){let r=this.left.getExpression(e),n=this.right.getExpression(e);if(this.typeCheck(this.left,r)&&this.typeCheck(this.right,n)){let i=(0,q3e.mergeEvalSpaces)(r.evalSpace,n.evalSpace);return{dataType:"boolean",expressionType:(0,q3e.maxExpressionType)(r.expressionType,n.expressionType),evalSpace:i,value:(0,Vtt.compose)(r.value,this.op,n.value)}}return(0,ztt.errorFor)("logial required boolean")}};vI.BinaryBoolean=DK});var TI=v(bI=>{"use strict";Object.defineProperty(bI,"__esModule",{value:!0});bI.ExprTime=void 0;var Wtt=Ke(),Ytt=hs(),Ktt=ir(),NK=class t extends Ktt.ExpressionDef{constructor(e,r,n="scalar"){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue={dataType:e,expressionType:n,value:typeof r=="string"?[r]:r,evalSpace:"constant"}}getExpression(e){return this.translationValue}static fromValue(e,r){let n=r.value;if(e!==r.dataType){let i={type:"dialect",function:"cast",safe:!1,dstType:e,expr:r.value};(0,Wtt.isTimeFieldType)(r.dataType)&&(i.srcType=r.dataType),n=(0,Ytt.compressExpr)([i])}return new t(e,n,r.expressionType)}};bI.ExprTime=NK});var IS=v(CI=>{"use strict";Object.defineProperty(CI,"__esModule",{value:!0});CI.Range=void 0;var U3e=Ke(),Xtt=js(),Jtt=ir(),Ztt=hs(),FK=class extends Jtt.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,n){switch(r){case"=":case"!=":{let i=r==="="?">=":"<",s=r==="="?"and":"or",o=r==="="?"<":">=",a=this.first.apply(e,i,n),u=this.last.apply(e,o,n);return{dataType:"boolean",expressionType:(0,U3e.maxExpressionType)(a.expressionType,u.expressionType),evalSpace:(0,U3e.mergeEvalSpaces)(a.evalSpace,u.evalSpace),value:(0,Ztt.compose)(a.value,s,u.value)}}case">":return this.last.apply(e,">=",n);case">=":return this.first.apply(e,">=",n);case"<":return this.first.apply(e,"<",n);case"<=":return this.last.apply(e,"<",n)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,Xtt.errorFor)("a range is not a value")}};CI.Range=FK});var IK=v(OI=>{"use strict";Object.defineProperty(OI,"__esModule",{value:!0});OI.ExprGranularTime=void 0;var wK=Ke(),ert=js(),$3e=pn(),j3e=DS(),trt=ir(),RI=TI(),H3e=IS(),LK=class extends trt.ExpressionDef{constructor(e,r,n){super({expr:e}),this.expr=e,this.units=r,this.truncate=n,this.elementType="granularTime",this.legalChildTypes=[$3e.FT.timestampT,$3e.FT.dateT]}granular(){return!0}getExpression(e){let r=this.units,n=this.expr.getExpression(e);if((0,wK.isTimeFieldType)(n.dataType)){let s={...n,dataType:n.dataType,timeframe:r};return this.truncate&&(s.value=[{type:"dialect",function:"trunc",expr:{value:n.value,valueType:n.dataType},units:r}]),s}n.dataType!=="error"&&this.log(`Cannot do time truncation on type '${n.dataType}'`);let i=n.dataType==="error"?(0,wK.isDateUnit)(r)?"date":"timestamp":n.dataType;return{...n,dataType:i,value:(0,ert.errorFor)("granularity typecheck").value,evalSpace:"constant"}}apply(e,r,n){return this.getRange(e).apply(e,r,n)}getRange(e){let r=this.getExpression(e);if(r.dataType==="timestamp"){let o=RI.ExprTime.fromValue("timestamp",r),a=new RI.ExprTime("timestamp",(0,j3e.timeOffset)("timestamp",r.value,"+",(0,wK.mkExpr)`1`,this.units),r.expressionType);return new H3e.Range(o,a)}let n=new RI.ExprTime("date",r.value,r.expressionType),i=(0,j3e.timeOffset)("date",r.value,"+",["1"],this.units),s=new RI.ExprTime("date",i,r.expressionType);return new H3e.Range(n,s)}};OI.ExprGranularTime=LK});var PK=v(DI=>{"use strict";Object.defineProperty(DI,"__esModule",{value:!0});DI.ExprCompare=void 0;var Cr=pn(),rrt=yI(),nrt=_I(),irt=IK(),srt={"~":[Cr.FT.stringT],"!~":[Cr.FT.stringT],"<":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"<=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],"!=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],">=":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT],">":[Cr.FT.numberT,Cr.FT.stringT,Cr.FT.dateT,Cr.FT.timestampT]},MK=class extends nrt.BinaryBoolean{constructor(e,r,n){super(e,r,n),this.elementType="a<=>b",this.legalChildTypes=srt[r]}getExpression(e){if(!this.right.granular()){let r=this.right.requestExpression(e);if(r&&(0,rrt.isGranularResult)(r))return new irt.ExprGranularTime(this.right,r.timeframe,!1).apply(e,this.op,this.left)}return this.right.apply(e,this.op,this.left)}};DI.ExprCompare=MK});var z3e=v(NI=>{"use strict";Object.defineProperty(NI,"__esModule",{value:!0});NI.Apply=void 0;var ort=pI(),art=PK(),kK=class extends art.ExprCompare{constructor(e,r){super(e,ort.Comparison.EqualTo,r),this.left=e,this.right=r,this.elementType="apply"}};NI.Apply=kK});var wI=v(FI=>{"use strict";Object.defineProperty(FI,"__esModule",{value:!0});FI.BinaryNumeric=void 0;var urt=pn(),lrt=ir(),BK=class extends lrt.ExpressionDef{constructor(e,r,n){super({left:e,right:n}),this.left=e,this.op=r,this.right=n,this.elementType="numeric binary abstract",this.legalChildTypes=[urt.FT.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}};FI.BinaryNumeric=BK});var G3e=v(LI=>{"use strict";Object.defineProperty(LI,"__esModule",{value:!0});LI.Boolean=void 0;var crt=ir(),frt=pn(),qK=class extends crt.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...frt.FT.boolT,value:[this.value]}}};LI.Boolean=qK});var MI=v(II=>{"use strict";Object.defineProperty(II,"__esModule",{value:!0});II.ExprIdReference=void 0;var UK=Ke(),xrt=js(),drt=SL(),hrt=ir(),$K=class extends hrt.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){let r=this.fieldReference.getField(e);if(r.found){let n=r.found.typeDesc();if(r.isOutputField)return{...n,evalSpace:n.evalSpace==="constant"?"constant":"output",value:[{type:"outputField",name:this.refString}]};let i=[{type:r.found.refType,path:this.fieldReference.path}],s=(0,UK.expressionIsAggregate)(n.expressionType)?"output":n.evalSpace;return{...n,value:i,evalSpace:s}}return this.log(r.error),(0,xrt.errorFor)(r.error)}apply(e,r,n){let i=this.fieldReference.getField(e).found;if(i instanceof drt.SpaceParam){let s=i.parameter();if((0,UK.isConditionParameter)(s)){let o=n.getExpression(e);return{dataType:"boolean",expressionType:o.expressionType,evalSpace:(0,UK.mergeEvalSpaces)(o.evalSpace,"input"),value:[{type:"apply",value:o.value,to:[{type:"parameter",path:this.fieldReference.path}]}]}}}return super.apply(e,r,n)}};II.ExprIdReference=$K});var PI=v(MS=>{"use strict";Object.defineProperty(MS,"__esModule",{value:!0});MS.FunctionOrdering=MS.FunctionOrderBy=void 0;var jK=Ke(),Q3e=mt(),prt=MI(),HK=class extends Q3e.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.log("analytic `order_by` must specify an aggregate expression or output field reference"),{e:["error"],dir:this.dir};let r=this.field.getExpression(e);return(0,jK.expressionIsAggregate)(r.expressionType)||((0,jK.expressionIsScalar)(r.expressionType)?(!(this.field instanceof prt.ExprIdReference)||r.evalSpace==="input")&&this.field.log("analytic `order_by` must be an aggregate or an output field reference"):this.field.log("analytic `order_by` must be scalar or aggregate")),{e:r.value,dir:this.dir}}getAggregateOrderBy(e,r){if(this.field){let n=this.field.getExpression(e);return(0,jK.expressionIsScalar)(n.expressionType)||this.field.log("aggregate `order_by` must be scalar"),r||this.field.log("`order_by` must be only `asc` or `desc` with no expression"),{e:n.value,dir:this.dir}}else return this.dir===void 0?(this.log("field or order direction must be specified"),{e:void 0,dir:"asc"}):{e:void 0,dir:this.dir}}};MS.FunctionOrderBy=HK;var zK=class extends Q3e.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(n=>n.getAggregateOrderBy(e,r))}};MS.FunctionOrdering=zK});var V3e=v(kI=>{"use strict";Object.defineProperty(kI,"__esModule",{value:!0});kI.ExprAddSub=void 0;var mrt=wI(),GK=class extends mrt.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}};kI.ExprAddSub=GK});var VK=v(BI=>{"use strict";Object.defineProperty(BI,"__esModule",{value:!0});BI.ReferenceField=void 0;var W3e=la(),QK=class extends W3e.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){let r=this.fieldRef.getField(e);r.error&&this.fieldRef.log(r.error),this.queryFieldDef={type:"fieldref",path:this.fieldRef.list.map(i=>i.name)};let n=this.referenceTo;if(n instanceof W3e.SpaceField&&n.haveFieldDef){let i=n.haveFieldDef,s=this.fieldRef.note;if(i.annotation||s){let o=s||{};i.annotation&&(o.inherits=i.annotation),this.queryFieldDef.annotation=o}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;let e=this.referenceTo;return e?(this.memoTypeDesc=e.typeDesc(),this.memoTypeDesc):{dataType:"error",expressionType:"scalar",evalSpace:"input"}}};BI.ReferenceField=QK});var WK=v(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.typecheckGroupBy=Pi.typecheckAggregate=Pi.typecheckCalculate=Pi.typecheckDeclare=Pi.typecheckMeasure=Pi.typecheckDimension=Pi.typecheckIndex=Pi.typecheckProject=void 0;var gn=lc();function grt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a select operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckProject=grt;function yrt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r;if(t.dataType==="turtle")r="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in an index operation`)}}Pi.typecheckIndex=yrt;function Ert(t,e){if(!(0,gn.expressionIsScalar)(t.expressionType))if((0,gn.expressionIsAggregate)(t.expressionType))e.log("Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,gn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Pi.typecheckDimension=Ert;function Art(t,e){if(!(0,gn.expressionIsAggregate)(t.expressionType))if((0,gn.expressionIsScalar)(t.expressionType))e.log("Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,gn.expressionIsAnalytic)(t.expressionType))e.log("Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}Pi.typecheckMeasure=Art;function Srt(t,e){t.dataType==="turtle"?e.log("Query fields cannot be used in a declare block"):(0,gn.expressionIsAnalytic)(t.expressionType)&&e.log("Analytic expressions can not be used in a declare block")}Pi.typecheckDeclare=Srt;function vrt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsAnalytic)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else if((0,gn.expressionIsScalar)(t.expressionType))r="a group_by or select",n="a scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a calculate operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckCalculate=vrt;function _rt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsAggregate)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsScalar)(t.expressionType))r="a group_by or select",n="a scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.log(`Cannot use ${n} field in an aggregate operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckAggregate=_rt;function brt(t,e){if(t.dataType==="turtle"||!(0,gn.expressionIsScalar)(t.expressionType)){let r,n;if(t.dataType==="turtle")r="a nest",n="a view";else if((0,gn.expressionIsAnalytic)(t.expressionType))r="a calculate",n="an analytic";else if((0,gn.expressionIsAggregate)(t.expressionType))r="an aggregate",n="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in a group_by operation, did you mean to use ${r} operation instead?`)}}Pi.typecheckGroupBy=brt});var PS=v(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.FieldReferences=Gt.WildcardFieldReference=Gt.ViewOrScalarFieldReference=Gt.DimensionFieldReference=Gt.MeasureFieldReference=Gt.DeclareFieldReference=Gt.ProjectFieldReference=Gt.GroupByFieldReference=Gt.AggregateFieldReference=Gt.IndexFieldReference=Gt.CalculateFieldReference=Gt.PartitionByFieldReference=Gt.ExpressionFieldReference=Gt.AcceptExceptFieldReference=Gt.FieldReference=void 0;var Trt=VK(),Crt=n0(),Y3e=mt(),K3e=Wc(),Fp=WK(),Ro=class extends Y3e.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=K3e.extendNoteMethod}makeEntry(e){let r=this.outputName;if(e.entry(r))this.log(`Output already has a field named '${r}'`);else{let n=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(r,this,new Trt.ReferenceField(this,n))}}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){let r=e.lookup(this.list);if(r.found){let n=r.found.typeDesc();this.typecheck(n)}return r}};Gt.FieldReference=Ro;var YK=class extends Ro{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}};Gt.AcceptExceptFieldReference=YK;var KK=class extends Ro{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}};Gt.ExpressionFieldReference=KK;var XK=class extends Ro{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}};Gt.PartitionByFieldReference=XK;var JK=class extends Ro{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,Fp.typecheckCalculate)(e,this)}};Gt.CalculateFieldReference=JK;var ZK=class t extends Ro{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,Fp.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return t.indexOutputName(this.path)}};Gt.IndexFieldReference=ZK;var eX=class extends Ro{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,Fp.typecheckAggregate)(e,this)}};Gt.AggregateFieldReference=eX;var tX=class extends Ro{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,Fp.typecheckGroupBy)(e,this)}};Gt.GroupByFieldReference=tX;var rX=class extends Ro{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,Fp.typecheckProject)(e,this)}};Gt.ProjectFieldReference=rX;var nX=class extends Ro{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,Fp.typecheckDeclare)(e,this)}};Gt.DeclareFieldReference=nX;var iX=class extends Ro{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,Fp.typecheckMeasure)(e,this)}};Gt.MeasureFieldReference=iX;var sX=class extends Ro{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,Fp.typecheckDimension)(e,this)}};Gt.DimensionFieldReference=sX;var oX=class extends Ro{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}};Gt.ViewOrScalarFieldReference=oX;var aX=class extends Y3e.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=K3e.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}.*`:"*"}};Gt.WildcardFieldReference=aX;var uX=class extends Crt.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}};Gt.FieldReferences=uX});var Zm=v(qI=>{"use strict";Object.defineProperty(qI,"__esModule",{value:!0});qI.ExprAggregateFunction=void 0;var X3e=Ke(),Rrt=jd(),a5=js(),Ort=tl(),Drt=e5(),Nrt=pn(),Frt=PS(),wrt=ir(),Lrt=la(),Irt=MI(),lX=class extends wrt.ExpressionDef{constructor(e,r,n){super(),this.func=e,this.legalChildTypes=[Nrt.FT.numberT],this.elementType=e,this.explicitSource=n,r&&(this.expr=r,this.has({expr:r}))}returns(e){return"number"}getExpression(e){var r,n;let i=e.isQueryFieldSpace()?e.inputSpace():e,s=this.expr,o=(r=this.expr)===null||r===void 0?void 0:r.getExpression(i),a=(n=this.source)===null||n===void 0?void 0:n.path,u=[];if(this.source){let c=this.source.getField(i);if(c.found){u=c.relationship;let f=c.found,x=f.typeDesc();if((0,X3e.isAtomicFieldType)(x.dataType)){s=this.source,o={dataType:x.dataType,expressionType:x.expressionType,value:[x.evalSpace==="output"?{type:"outputField",name:this.source.refString}:{type:"field",path:this.source.path}],evalSpace:x.evalSpace},a=this.source.path;let d=this.getJoinUsage(i);(d.length===1||d.length>1&&d.slice(1).every(p=>Mrt(p,d[0])))&&(a=d[0].map(p=>p.name),u=d[0])}else if(!(f instanceof Drt.StructSpaceFieldBase))return this.log(`Aggregate source cannot be a ${x.dataType}`),(0,a5.errorFor)(`Aggregate source cannot be a ${x.dataType}`)}else return this.log(`Reference to undefined value ${this.source.refString}`),(0,a5.errorFor)(`Reference to undefined value ${this.source.refString}`)}if(o===void 0)return this.log("Missing expression for aggregate function"),(0,a5.errorFor)("agggregate without expression");if((0,X3e.expressionIsAggregate)(o.expressionType))return this.log("Aggregate expression cannot be aggregate"),(0,a5.errorFor)("reagggregate");if(!(o.dataType==="error")){let c=this.getJoinUsage(i),f=this.source!==void 0||this.explicitSource;if(s&&!(!this.source&&c.every(d=>d.length===0))&&!this.isSymmetricFunction()){let d=fX(u,c),h=xX(this.elementType,d),p=f?h:"Join path is required for this calculation";if(p){let m=Prt(p,c,s,this.elementType);this.log(m,h?"error":"warn")}}}if(this.typeCheck(this.expr||this,{...o,expressionType:"scalar"})){let c={type:"aggregate",function:this.func,e:o.value};return a&&a.length>0&&(c.structPath=a),{dataType:this.returns(o),expressionType:"aggregate",value:[c],evalSpace:"output"}}return(0,a5.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){let r=[];if(this.source&&this.source.getField(e).found){let i=[{type:"field",path:this.source.path}];r.push(...cX(e,i))}if(this.expr){let n=this.expr.getExpression(e).value;r.push(...cX(e,n))}return r}};qI.ExprAggregateFunction=lX;function Mrt(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 cX(t,e){let r=[],n=(i,s)=>{let o=s[0],a=s.slice(1),u=i.entry(o);if(u===void 0)throw new Error(`Invalid field lookup ${o}`);if(u instanceof Ort.StructSpaceField&&a.length>0){let l=n(u.fieldSpace,a);return{...l,relationship:[{name:o,structRelationship:u.structRelationship},...l.relationship]}}else if(u instanceof Lrt.SpaceField){if(a.length!==0)throw new Error(`${o} cannot contain a ${a.join(".")}`);let l=u.fieldDef();if(l)return{fs:i,def:l,relationship:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};return(0,Rrt.exprWalk)(e,i=>{if(typeof i!="string"){if(i.type==="field"){let s=n(t,i.path);if(s.def.type!=="struct"&&s.def.type!=="turtle")if(s.def.e){let o=cX(s.fs,s.def.e);r.push(...o.map(a=>[...s.relationship,...a]))}else r.push(s.relationship)}else if(i.type==="source-reference")if(i.path){let s=n(t,i.path);r.push(s.relationship)}else r.push([])}}),r}function fX(t,e){let r=[];for(let n of e){let i=0;for(let u=0;u<t.length&&u<n.length&&t[u].name===n[u].name;u++)i=u+1;let s=t.slice(i),o=n.slice(i),a=[...s.map(u=>({...u,reverse:!0})),...o.map(u=>({...u,reverse:!1}))];r.push(a)}return r}function xX(t,e){for(let r of e)for(let n of r){if(n.structRelationship.type==="cross")return`Cannot compute \`${t}\` across \`join_cross\` relationship \`${n.name}\``;if(n.structRelationship.type==="many"&&!n.reverse)return`Cannot compute \`${t}\` across \`join_many\` relationship \`${n.name}\``;if(n.structRelationship.type==="nested"&&!n.reverse)return`Cannot compute \`${t}\` across repeated relationship \`${n.name}\``}}function Prt(t,e,r,n){if(e.length===0)return t;let i=e[0];for(let h of e.slice(1))for(let p=0;p<i.length;p++){let m=i[p],g=h[p];if(m.name!==g.name){i=i.slice(0,p);break}}let s=fX(i,e),o=xX(n,s),a=i.slice().reverse().findIndex(h=>h.structRelationship.type==="many"||h.structRelationship.type==="cross"),u=a===-1?0:i.length-a,l=i.slice(0,u),c=fX(l,e),f=xX(n,c),x=i.length>0?i.map(h=>h.name).join("."):"source",d=l.length>0?l.map(h=>h.name).join("."):"source";if(o)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()`";{let h=r instanceof Frt.FieldReference?`${r.refString}.${n}()`:r instanceof Irt.ExprIdReference?`${r.fieldReference.refString}.${n}()`:`${x}.${n}(${r.code})`,p=`${d}.${n}(${r.code})`,m=`${t}; use \`${h}\``;return f===void 0&&d!==x&&(m+=` or \`${p}\` to get a result weighted with respect to \`${d}\``),m}}});var Z3e=v(UI=>{"use strict";Object.defineProperty(UI,"__esModule",{value:!0});UI.ExprAlternationTree=void 0;var J3e=Ke(),krt=js(),Brt=_I(),qrt=hs(),dX=class extends Brt.BinaryBoolean{constructor(e,r,n){super(e,r,n),this.elementType="alternation",this.elementType=`${r}alternation${r}`}apply(e,r,n){let i=this.left.apply(e,r,n),s=this.right.apply(e,r,n);return{dataType:"boolean",expressionType:(0,J3e.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,J3e.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,qrt.compose)(i.value,this.op==="&"?"and":"or",s.value)}}requestExpression(e){}getExpression(e){return this.log("Alternation tree has no value"),(0,krt.errorFor)("no value from alternation tree")}};UI.ExprAlternationTree=dX});var jI=v($I=>{"use strict";Object.defineProperty($I,"__esModule",{value:!0});$I.ExprAsymmetric=void 0;var Urt=Zm(),hX=class extends Urt.ExprAggregateFunction{constructor(e,r,n,i){super(e,r,i),this.func=e,this.expr=r,this.source=n,this.has({source:n})}isSymmetricFunction(){return!1}defaultFieldName(){if(this.source&&this.expr===void 0){let e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}};$I.ExprAsymmetric=hX});var eye=v(HI=>{"use strict";Object.defineProperty(HI,"__esModule",{value:!0});HI.ExprAvg=void 0;var $rt=jI(),pX=class extends $rt.ExprAsymmetric{constructor(e,r,n){super("avg",e,r,n),this.has({source:r})}};HI.ExprAvg=pX});var tye=v(zI=>{"use strict";Object.defineProperty(zI,"__esModule",{value:!0});zI.ExprCast=void 0;var jrt=DS(),Hrt=ir(),zrt=hs(),mX=class extends Hrt.ExpressionDef{constructor(e,r,n=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=n,this.elementType="cast"}getExpression(e){var r,n,i;let s=this.expr.getExpression(e),o="unsupported";if(typeof this.castType=="string")o=this.castType;else{let a=e.dialectObj();a&&(a.validateTypeName(this.castType.raw)?o=(i=(n=(r=e.dialectObj())===null||r===void 0?void 0:r.sqlTypeToMalloyType(this.castType.raw))===null||n===void 0?void 0:n.type)!==null&&i!==void 0?i:"unsupported":this.log(`Cast type \`${this.castType.raw}\` is invalid for ${a.name} dialect`))}return{dataType:o,expressionType:s.expressionType,value:(0,zrt.compressExpr)((0,jrt.castTo)(this.castType,s.value,s.dataType,this.safe)),evalSpace:s.evalSpace}}};zI.ExprCast=mX});var nye=v(GI=>{"use strict";Object.defineProperty(GI,"__esModule",{value:!0});GI.ExprCoalesce=void 0;var gX=lc(),rye=pn(),Grt=ir(),yX=class extends Grt.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=rye.FT.anyAtomicT}getExpression(e){let r=this.expr.getExpression(e),n=this.altExpr.getExpression(e);return r.dataType==="null"?n:(rye.FT.typeEq(r,n)||this.log(`Mismatched types for coalesce (${r.dataType}, ${n.dataType})`),{...n,dataType:r.dataType==="error"?n.dataType:r.dataType,expressionType:(0,gX.maxExpressionType)(r.expressionType,n.expressionType),value:(0,gX.mkExpr)`COALESCE(${r.value},${n.value})`,evalSpace:(0,gX.mergeEvalSpaces)(r.evalSpace,n.evalSpace)})}};GI.ExprCoalesce=yX});var iye=v(QI=>{"use strict";Object.defineProperty(QI,"__esModule",{value:!0});QI.ExprCount=void 0;var Qrt=Zm(),EX=class extends Qrt.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}getExpression(e){let r={type:"aggregate",function:"count",e:[]};return this.source&&(r.structPath=this.source.path),{dataType:"number",expressionType:"aggregate",value:[r],evalSpace:"output"}}};QI.ExprCount=EX});var sye=v(WI=>{"use strict";Object.defineProperty(WI,"__esModule",{value:!0});WI.ExprCountDistinct=void 0;var VI=pn(),Vrt=Zm(),AX=class extends Vrt.ExprAggregateFunction{constructor(e){super("count_distinct",e),this.legalChildTypes=[VI.FT.numberT,VI.FT.stringT,VI.FT.dateT,VI.FT.timestampT]}};WI.ExprCountDistinct=AX});var kS=v(YI=>{"use strict";Object.defineProperty(YI,"__esModule",{value:!0});YI.Limit=void 0;var Wrt=mt(),Yrt=Ii(),SX=class extends Wrt.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=Yrt.LegalRefinementStage.Tail,this.forceQueryClass=void 0}};YI.Limit=SX});var XI=v(KI=>{"use strict";Object.defineProperty(KI,"__esModule",{value:!0});KI.PartitionBy=void 0;var Krt=mt(),vX=class extends Krt.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}};KI.PartitionBy=vX});var bX=v(JI=>{"use strict";Object.defineProperty(JI,"__esModule",{value:!0});JI.ExprFunc=void 0;var i0=Ke(),Bx=js(),Xrt=e5(),Jrt=ir(),oye=hs(),_X=class extends Jrt.ExpressionDef{constructor(e,r,n,i,s){super({args:r}),this.name=e,this.args=r,this.isRaw=n,this.rawType=i,this.source=s,this.elementType="function call()",this.has({source:s})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}getPropsExpression(e,r){var n,i,s,o,a;let u=this.args.map(O=>O.getExpression(e));if(this.isRaw){let O="scalar",N,k=[`${this.name}(`];for(let H of u)O=(0,i0.maxExpressionType)(O,H.expressionType),N?k.push(","):N=H.dataType,k.push(...H.value);return k.push(")"),{dataType:(i=(n=this.rawType)!==null&&n!==void 0?n:N)!==null&&i!==void 0?i:"number",expressionType:O,value:(0,oye.compressExpr)(k),evalSpace:(0,i0.mergeEvalSpaces)(...u.map(H=>H.evalSpace))}}let l=(s=this.modelEntry(this.name.toLowerCase()))===null||s===void 0?void 0:s.entry;if(l===void 0)return this.log(`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),(0,Bx.errorFor)("unknown function");if(l.type!=="function")return this.log(`Cannot call '${this.name}', which is of type ${l.type}`),(0,Bx.errorFor)("called non function");l.name!==this.name&&this.log(`Case insensitivity for function names is deprecated, use '${l.name}' instead`,"warn");let c,f=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){let O=this.source.getField(e).found;if(O){let N=O.typeDesc();if((0,i0.isAtomicFieldType)(N.dataType))c={dataType:N.dataType,expressionType:N.expressionType,value:[{type:"field",path:this.source.path}],evalSpace:N.evalSpace},f=this.source.path.slice(0,-1);else if(!(O instanceof Xrt.StructSpaceFieldBase)){let k=`Aggregate source cannot be a ${N.dataType}`;return this.log(k),(0,Bx.errorFor)(k)}}else{let N=`Reference to undefined value ${this.source.refString}`;return this.log(N),(0,Bx.errorFor)(N)}}let x=[...c?[c]:[],...u],d=Zrt(l,x);if(d===void 0)return this.log(`No matching overload for function ${this.name}(${x.map(O=>O.dataType).join(", ")})`),(0,Bx.errorFor)("no matching overload");let{overload:h,expressionTypeErrors:p,evalSpaceErrors:m,nullabilityErrors:g}=d;for(let O of p){let N=O.argIndex-(c?1:0),k=(0,i0.expressionIsScalar)(O.maxExpressionType)?"scalar":"scalar or aggregate";this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${k}, but received ${O.actualExpressionType}`)}for(let O of m){let N=O.argIndex-(c?1:0),k=O.maxEvalSpace==="literal"?"literal":O.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must be ${k}, but received ${O.actualEvalSpace}`)}for(let O of g){let N=O.argIndex-(c?1:0);this.args[N].log(`Parameter ${O.argIndex+1} ('${O.param.name}') of ${this.name} must not be a literal null`)}let y=h.returnType,A=(0,i0.maxOfExpressionTypes)([y.expressionType,...x.map(O=>O.expressionType)]);if(!(0,i0.expressionIsAggregate)(h.returnType.expressionType)&&this.source!==void 0)return this.log(`Cannot call function ${this.name}(${x.map(O=>O.dataType).join(", ")}) with source`),(0,Bx.errorFor)("cannot call with source");let S={type:"function_call",overload:h,name:this.name,args:x.map(O=>O.value),expressionType:A,structPath:f},T=[S],b=(a=e.dialectObj())===null||a===void 0?void 0:a.name,_=b?h.dialect[b]:void 0;if(_===void 0)this.log(`Function ${this.name} is not defined in dialect ${b}`);else{if(r?.orderBys&&r.orderBys.length>0){let O=(0,i0.expressionIsAnalytic)(h.returnType.expressionType);if(O||this.inExperiment("aggregate_order_by",!0)||r.orderBys[0].log("Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),_.supportsOrderBy||O){let N=_.supportsOrderBy!=="only_default",k=r.orderBys.flatMap(P=>O?P.getAnalyticOrderBy(e):P.getAggregateOrderBy(e,N));S.orderBy=k}else r.orderBys[0].log(`Function \`${this.name}\` does not support \`order_by\``)}r?.limit!==void 0&&(_.supportsLimit?S.limit=r.limit.limit:this.log(`Function ${this.name} does not support limit`))}if(r?.partitionBys&&r.partitionBys.length>0){let O=[];for(let N of r.partitionBys)for(let k of N.partitionFields){let P=k.getField(e);P.found===void 0?k.log(`${k.refString} is not defined`):(0,i0.expressionIsScalar)(P.found.typeDesc().expressionType)?O.push(k.nameString):k.log("Partition expression must be scalar")}S.partitionBy=O}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0))return(0,Bx.errorFor)(`Cannot use sql_function \`${l.name}\`; use \`sql_functions\` experiment to enable this behavior`);let O=x[0].value;if(O.length!==1||typeof O[0]=="string"||O[0].type!=="dialect"||O[0].function!=="stringLiteral")this.log(`Invalid string literal for \`${l.name}\``);else{let N=O[0].literal,k=ent(N),P=k.filter(H=>H.type==="interpolation"&&H.name.includes(".")).map(H=>H.type==="interpolation"?`\${${H.name}}`:`\${${H.value}}`);if(P.length>0){let H=P.length===1?`'.' paths are not yet supported in sql interpolations, found ${P.at(0)}`:`'.' paths are not yet supported in sql interpolations, found [${P.join(", ")}]`;return this.log(H),(0,Bx.errorFor)(`${H}. See LookML \${...} documentation at https://cloud.google.com/looker/docs/reference/param-field-sql#sql_for_dimensions`)}T=[{type:"sql-string",e:k.map(H=>H.type==="string"?H.value:H.name==="TABLE"?{type:"source-reference"}:{type:"field",path:[H.name]})}]}}if(y.dataType==="any")return this.log(`Invalid return type ${y.dataType} for function '${this.name}'`),(0,Bx.errorFor)("invalid return type");let R=(0,i0.mergeEvalSpaces)(...x.map(O=>O.evalSpace)),D=R==="constant"?"constant":(0,i0.expressionIsScalar)(A)?R:"output";return{dataType:y.dataType,expressionType:A,value:(0,oye.compressExpr)(T),evalSpace:D}}};JI.ExprFunc=_X;function Zrt(t,e){for(let r of t.overloads){let n=0,i=!0,s=!1,o=[],a=[],u=[];for(let l=0;l<e.length;l++){let c=e[l],f=r.params[n];if(f===void 0){i=!1;break}if(!f.allowedTypes.some(d=>{let h=d.dataType===c.dataType||d.dataType==="any"||c.dataType==="null"||c.dataType==="error";return d.expressionType&&((0,i0.isExpressionTypeLEQ)(c.expressionType,d.expressionType)||o.push({argIndex:l,maxExpressionType:d.expressionType,actualExpressionType:c.expressionType,param:f})),(d.evalSpace==="literal"&&c.evalSpace!=="literal"||d.evalSpace==="constant"&&(c.evalSpace==="input"||c.evalSpace==="output")||d.evalSpace==="output"&&c.evalSpace==="input")&&a.push({argIndex:l,param:f,maxEvalSpace:d.evalSpace,actualEvalSpace:c.evalSpace}),d.evalSpace==="literal"&&c.dataType==="null"&&u.push({argIndex:l,param:f}),h})){i=!1;break}f.isVariadic?l===e.length-1&&(s=!0):n++}if(!(!s&&(n!==e.length||n!==r.params.length))&&i)return{overload:r,expressionTypeErrors:o,evalSpaceErrors:a,nullabilityErrors:u}}}function ent(t){let e=[],r=t;for(;r.length;){let n=r.indexOf("${");if(n===-1){e.push({type:"string",value:r});break}else{let i=r.slice(n).indexOf("}");if(i===-1){e.push({type:"string",value:r});break}n>0&&e.push({type:"string",value:r.slice(0,n)}),e.push({type:"interpolation",name:r.slice(n+2,i+n)}),r=r.slice(i+n+1)}}return e}});var aye=v(ZI=>{"use strict";Object.defineProperty(ZI,"__esModule",{value:!0});ZI.ExprProps=void 0;var tnt=Ke(),rnt=js(),nnt=pn(),int=PI(),snt=kS(),ont=XI(),ant=ir(),unt=bX(),TX=class extends ant.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=nnt.FT.anyAtomicT}getFilteredExpression(e,r,n){if(n.length>0){if(!this.expr.supportsWhere(r))return this.expr.log("Filtered expression requires an aggregate computation"),r;let i=[];for(let s of n){let o=s.getFilterList(e);if(o.find(a=>(0,tnt.expressionIsCalculation)(a.expressionType)))return s.log("Cannot filter an expresion with an aggregate or analytical computation"),r;i.push(...o)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,value:[{type:"filterExpression",e:r.value,filterList:i}]}:(this.expr.log(`Cannot filter '${r.dataType}' data`),(0,rnt.errorFor)("cannot filter type"))}return r}getExpression(e){let r=[],n,i=[],s=[];for(let a of this.statements)a instanceof ont.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.log("`partition_by` is not supported for this kind of expression"):a instanceof snt.Limit?n?a.log("limit already specified"):this.expr.canSupportLimit()?n=a:a.log("`limit` is not supported for this kind of expression"):a instanceof int.FunctionOrdering?this.expr.canSupportPartitionBy()?i.push(a):a.log("`order_by` is not supported for this kind of expression"):s.push(a);let o=this.expr instanceof unt.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:n,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}};ZI.ExprProps=TX});var lye=v(eM=>{"use strict";Object.defineProperty(eM,"__esModule",{value:!0});eM.ExprLogicalOp=void 0;var lnt=_I(),uye=pn(),CX=class extends lnt.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[uye.FT.boolT,uye.FT.aggregateBoolT]}};eM.ExprLogicalOp=CX});var cye=v(rM=>{"use strict";Object.defineProperty(rM,"__esModule",{value:!0});rM.ExprMax=void 0;var tM=pn(),cnt=Zm(),RX=class extends cnt.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[tM.FT.numberT,tM.FT.stringT,tM.FT.dateT,tM.FT.timestampT]}returns(e){return e.dataType}};rM.ExprMax=RX});var fye=v(iM=>{"use strict";Object.defineProperty(iM,"__esModule",{value:!0});iM.ExprMin=void 0;var nM=pn(),fnt=Zm(),OX=class extends fnt.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[nM.FT.numberT,nM.FT.stringT,nM.FT.dateT,nM.FT.timestampT]}returns(e){return e.dataType}};iM.ExprMin=OX});var dye=v(sM=>{"use strict";Object.defineProperty(sM,"__esModule",{value:!0});sM.ExprMinus=void 0;var xnt=js(),xye=pn(),dnt=ir(),DX=class extends dnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[xye.FT.numberT]}getExpression(e){let r=this.expr.getExpression(e);return xye.FT.typeIn(r,this.legalChildTypes)?r.value.length>1?{...r,dataType:"number",value:["-(",...r.value,")"]}:{...r,dataType:"number",value:["-",...r.value]}:(0,xnt.errorFor)("negate requires number")}};sM.ExprMinus=DX});var hye=v(oM=>{"use strict";Object.defineProperty(oM,"__esModule",{value:!0});oM.ExprMulDiv=void 0;var hnt=wI(),NX=class extends hnt.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}};oM.ExprMulDiv=NX});var wX=v(aM=>{"use strict";Object.defineProperty(aM,"__esModule",{value:!0});aM.Unary=void 0;var pnt=ir(),FX=class extends pnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}};aM.Unary=FX});var mye=v(uM=>{"use strict";Object.defineProperty(uM,"__esModule",{value:!0});uM.ExprNot=void 0;var pye=pn(),mnt=wX(),gnt=hs(),LX=class extends mnt.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[pye.FT.boolT,pye.FT.nullT]}getExpression(e){let r=this.expr.getExpression(e),n=this.typeCheck(this.expr,r);return{...r,dataType:"boolean",value:n?(0,gnt.nullsafeNot)(r.value):["false"]}}};uM.ExprNot=LX});var gye=v(lM=>{"use strict";Object.defineProperty(lM,"__esModule",{value:!0});lM.ExprNow=void 0;var ynt=ir(),IX=class extends ynt.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{dataType:"timestamp",expressionType:"scalar",evalSpace:"constant",value:[{type:"dialect",function:"now"}]}}};lM.ExprNow=IX});var yye=v(cM=>{"use strict";Object.defineProperty(cM,"__esModule",{value:!0});cM.ExprNULL=void 0;var Ent=ir(),MX=class extends Ent.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return{dataType:"null",value:["NULL"],expressionType:"scalar",evalSpace:"literal"}}};cM.ExprNULL=MX});var Eye=v(fM=>{"use strict";Object.defineProperty(fM,"__esModule",{value:!0});fM.ExprNumber=void 0;var Ant=pn(),Snt=ir(),PX=class extends Snt.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){return{...Ant.FT.numberT,evalSpace:"literal",value:[{type:"dialect",function:"numberLiteral",literal:this.n}]}}};fM.ExprNumber=PX});var Aye=v(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0});xM.ExprParens=void 0;var vnt=ir(),kX=class extends vnt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){let r=this.expr.getExpression(e);return{...r,value:["(",...r.value,")"]}}};xM.ExprParens=kX});var Sye=v(dM=>{"use strict";Object.defineProperty(dM,"__esModule",{value:!0});dM.ExprRegEx=void 0;var _nt=ir(),BX=class extends _nt.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return{dataType:"regular expression",expressionType:"scalar",value:[{type:"dialect",function:"regexpLiteral",literal:this.regex}],evalSpace:"literal"}}};dM.ExprRegEx=BX});var vye=v(hM=>{"use strict";Object.defineProperty(hM,"__esModule",{value:!0});hM.ExprString=void 0;var bnt=ir(),Tnt=pn(),qX=class extends bnt.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return{...Tnt.FT.stringT,value:[{type:"dialect",function:"stringLiteral",literal:this.value}],evalSpace:"literal"}}};hM.ExprString=qX});var _ye=v(pM=>{"use strict";Object.defineProperty(pM,"__esModule",{value:!0});pM.ExprSum=void 0;var Cnt=jI(),UX=class extends Cnt.ExprAsymmetric{constructor(e,r,n){super("sum",e,r,n),this.has({source:r})}};pM.ExprSum=UX});var bye=v(gM=>{"use strict";Object.defineProperty(gM,"__esModule",{value:!0});gM.ExprTimeExtract=void 0;var eg=Ke(),wp=js(),$X=ir(),Rnt=IS(),mM=class t extends $X.ExpressionDef{static extractor(e){let r=t.pluralMap[e];if(r)return r;if((0,eg.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){let r=t.extractor(this.extractText);if(r){if(this.args.length!==1)return this.log(`Extraction function ${r} requires one argument`),(0,wp.errorFor)("{this.name} arg count");let n=this.args[0];if(n instanceof Rnt.Range){let i=n.first.getExpression(e),s=n.last.getExpression(e),o=(0,eg.maxExpressionType)(i.expressionType,s.expressionType),a=(0,eg.mergeEvalSpaces)(i.evalSpace,s.evalSpace);if(i.dataType==="error"||s.dataType==="error")return{dataType:"number",expressionType:o,evalSpace:a,value:(0,wp.errorFor)("extract from error").value};if(!(0,eg.isTimeFieldType)(i.dataType))return n.first.log(`Can't extract ${r} from '${i.dataType}'`),(0,wp.errorFor)(`${r} bad type ${i.dataType}`);if(!(0,eg.isTimeFieldType)(s.dataType))return n.last.log(`Cannot extract ${r} from '${s.dataType}'`),(0,wp.errorFor)(`${r} bad type ${s.dataType}`);let u=i.dataType;if(i.dataType!==s.dataType){let l=!0;if(u="timestamp",i.dataType==="date"){let c=(0,$X.getMorphicValue)(i,"timestamp");c&&(i=c,l=!1)}else{let c=(0,$X.getMorphicValue)(s,"timestamp");c&&(s=c,l=!1)}if(l)return n.first.log(`Cannot measure from ${i.dataType} to ${s.dataType}`),(0,wp.errorFor)(`${r} range mismatch`)}return["week","month","quarter","year"].includes(r)?(this.log(`Cannot measure interval using '${r}'`),(0,wp.errorFor)(`${r} civil extraction`)):(0,eg.isTimestampUnit)(r)?{dataType:"number",expressionType:o,evalSpace:a,value:[{type:"dialect",function:"timeDiff",units:r,left:{valueType:u,value:i.value},right:{valueType:u,value:s.value}}]}:(this.log(`Cannot extract ${r} from a range`),(0,wp.errorFor)(`${r} bad extraction`))}else{let i=n.getExpression(e);return(0,eg.isTimeFieldType)(i.dataType)?{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:[{type:"dialect",function:"extract",expr:{value:i.value,valueType:i.dataType},units:r}]}:(i.dataType!=="error"&&this.log(`${this.extractText}() requires time type, not '${i.dataType}'`),{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:(0,wp.errorFor)(`${this.extractText} bad type ${i.dataType}`).value})}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}};gM.ExprTimeExtract=mM;mM.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"}});var u5=v(yM=>{"use strict";Object.defineProperty(yM,"__esModule",{value:!0});yM.FieldName=void 0;var Ont=mt(),jX=class extends Ont.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])}};yM.FieldName=jX});var Tye=v(EM=>{"use strict";Object.defineProperty(EM,"__esModule",{value:!0});EM.QueryInputSpace=void 0;var Dnt=CS(),Nnt=PY(),Fnt=wL(),HX=class extends Fnt.RefinedSpace{constructor(e,r){let n=new Nnt.SpaceSeed(e);super(n.structDef),this.queryOutput=r,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof Dnt.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}};EM.QueryInputSpace=HX});var l5=v(fa=>{"use strict";var wnt=fa&&fa.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Lnt=fa&&fa.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Int=fa&&fa.__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)&&wnt(e,t,r);return Lnt(e,t),e};Object.defineProperty(fa,"__esModule",{value:!0});fa.ReduceFieldSpace=fa.QuerySpace=fa.QueryOperationSpace=void 0;var AM=Int(Ke()),zX=AL(),Mnt=u5(),Pnt=la(),knt=PS(),Bnt=wL(),qnt=FY(),Unt=tl(),$nt=Tye(),SM=class extends Bnt.RefinedSpace{constructor(e,r,n,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=n,this.astEl=i,this.expandedWild={},this.exprSpace=new $nt.QueryInputSpace(e,this),r&&this.addRefineFromFields(r)}log(e){this.astEl&&this.astEl.log(e)}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let n=this.exprSpace,i=[];if(e.joinPath)for(let a of e.joinPath.list){let u=a.refString;i.push(u);let l=n.entry(u);if(l)if(l instanceof Unt.StructSpaceField)n=l.fieldSpace;else{a.log(`Field '${u}' does not contain rows and cannot be expanded with '*'`);return}else{a.log(`No such field as '${u}'`);return}}let s=this.dialectObj(),o=[];for(let[a,u]of n.entries())if(!e.except.has(a))if(this.entry(a)){let l=(r=this.expandedWild[a])===null||r===void 0?void 0:r.join(".");e.log(`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${l?` (conflicts with ${l})`:""}`)}else{let l=u.typeDesc();AM.isAtomicFieldType(l.dataType)&&AM.expressionIsScalar(l.expressionType)&&(s===void 0||!s.ignoreInProject(a))&&(o.push({name:a,entry:u}),this.expandedWild[a]=i.concat(a))}for(let a of o.sort((u,l)=>u.name.localeCompare(l.name)))this.setEntry(a.name,a.entry)}};fa.QueryOperationSpace=SM;var vM=class extends SM{addRefineFromFields(e){var r;if(AM.isQuerySegment(e))for(let n of e.queryFields)if(n.type==="fieldref"){let i=this.exprSpace.lookup(n.path.map(s=>new Mnt.FieldName(s)));i.found&&this.setEntry(n.path[n.path.length-1],i.found)}else n.type!=="turtle"&&this.setEntry((r=n.as)!==null&&r!==void 0?r:n.name,new qnt.ColumnSpaceField(n))}pushFields(...e){for(let r of e)r instanceof knt.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){let e=[];for(let[r,n]of this.entries())if(n instanceof Pnt.SpaceField){let i=this.expandedWild[r];if(i){e.push({type:"fieldref",path:i});continue}let s=n.getQueryFieldDef(this.exprSpace);if(s){let o=n.typeDesc();o.dataType!=="error"&&this.canContain(o)&&!jnt(s)&&e.push(s)}}return this.isComplete(),e}getQuerySegment(e){let r=this.getPipeSegment(e);if(AM.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.log("internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};if(e?.extendSource)for(let n of e.extendSource)this.exprSpace.addFieldDef(n);let r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,zX.mergeFields)(e?.queryFields,r.queryFields),e?.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){let n=[],i=this.exprSpace.structDef();for(let s of this.exprSpace.extendList){let o=i.fields.find(a=>(0,zX.nameFromDef)(a)===s);o&&n.push(o)}r.extendSource=(0,zX.mergeFields)(r.extendSource,n)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),this.isComplete(),r}lookup(e){let r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}};fa.QuerySpace=vM;var GX=class extends vM{constructor(){super(...arguments),this.segmentType="reduce"}};fa.ReduceFieldSpace=GX;function jnt(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}});var Rye=v(_M=>{"use strict";Object.defineProperty(_M,"__esModule",{value:!0});_M.ExprUngroup=void 0;var Cye=Ke(),QX=js(),Hnt=l5(),znt=pn(),Gnt=ir(),VX=class extends Gnt.ExpressionDef{constructor(e,r,n){super({expr:r,fields:n}),this.control=e,this.expr=r,this.fields=n,this.legalChildTypes=znt.FT.anyAtomicT,this.elementType="ungroup"}returns(e){return"number"}getExpression(e){let r=this.expr.getExpression(e);if(!(0,Cye.expressionIsAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must be an aggregate`),(0,QX.errorFor)("ungrouped scalar");if((0,Cye.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.log(`${this.control}() expression must not already be ungrouped`),(0,QX.errorFor)("doubly-ungrouped aggregate");let n={type:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){let i=[],s=this.control==="exclude";for(let o of this.fields){let a=e.outputSpace(),u=!0;for(;a;){let l=a.lookup([o]);if(l.found&&l.isOutputField)i.push(o.refString),u=!1;else if(a instanceof Hnt.QuerySpace){a=a.nestParent;continue}break}if(u){let l=s?"exclude()":"all()";o.log(`${l} '${o.refString}' is missing from query output`)}}n.fields=i}return{dataType:this.returns(r),expressionType:"ungrouped_aggregate",value:[n],evalSpace:"output"}}return this.log(`${this.control}() incompatible type`),(0,QX.errorFor)("ungrouped type check")}};_M.ExprUngroup=VX});var Fye=v(CM=>{"use strict";Object.defineProperty(CM,"__esModule",{value:!0});CM.ForRange=void 0;var Oye=lc(),WX=js(),Dye=pn(),bM=DS(),Qnt=ir(),TM=TI(),Nye=IS(),YX=class extends Qnt.ExpressionDef{constructor(e,r,n){super({from:e,duration:r,timeframe:n}),this.from=e,this.duration=r,this.timeframe=n,this.elementType="forRange",this.legalChildTypes=[Dye.FT.timestampT,Dye.FT.dateT]}apply(e,r,n){let i=this.from.getExpression(e),s=n.getExpression(e);if(!this.typeCheck(n,s))return(0,WX.errorFor)("no time for range");let o=this.duration.getExpression(e);if(o.dataType!=="number")return o.dataType!=="error"&&this.log(`FOR duration count must be a number, not '${o.dataType}'`),{dataType:"boolean",evalSpace:(0,Oye.mergeEvalSpaces)(i.evalSpace,s.evalSpace),expressionType:(0,Oye.maxExpressionType)(i.expressionType,s.expressionType),value:(0,WX.errorFor)("for not number").value};let a=this.timeframe.text,u=(0,bM.resolution)(a);if(i.dataType==="timestamp"&&(u="timestamp"),s.dataType==="date"&&u==="date"){let h=this.from,p=(0,bM.timeOffset)("date",i.value,"+",o.value,a),m=new TM.ExprTime("date",p);return new Nye.Range(h,m).apply(e,r,n)}let l=TM.ExprTime.fromValue("timestamp",s),c=this.from,f=i.value;if(i.dataType==="date"){let h=i.morphic&&i.morphic.timestamp;h?f=h:f=(0,bM.castDateToTimestamp)(f),c=new TM.ExprTime("timestamp",f,i.expressionType)}let x=(0,bM.timeOffset)("timestamp",f,"+",o.value,a),d=new TM.ExprTime("timestamp",x,i.expressionType);return new Nye.Range(c,d).apply(e,r,l)}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,WX.errorFor)("range has no value")}};CM.ForRange=YX});var bJ=v(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});var Ux=class extends Error{},iJ=class extends Ux{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},sJ=class extends Ux{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},oJ=class extends Ux{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},ig=class extends Ux{},LM=class extends Ux{constructor(e){super(`Invalid unit ${e}`)}},xa=class extends Ux{},Xc=class extends Ux{constructor(){super("Zone is an abstract class")}},Re="numeric",u0="short",lu="long",aJ={year:Re,month:Re,day:Re},rEe={year:Re,month:u0,day:Re},Vnt={year:Re,month:u0,day:Re,weekday:u0},nEe={year:Re,month:lu,day:Re},iEe={year:Re,month:lu,day:Re,weekday:lu},sEe={hour:Re,minute:Re},oEe={hour:Re,minute:Re,second:Re},aEe={hour:Re,minute:Re,second:Re,timeZoneName:u0},uEe={hour:Re,minute:Re,second:Re,timeZoneName:lu},lEe={hour:Re,minute:Re,hourCycle:"h23"},cEe={hour:Re,minute:Re,second:Re,hourCycle:"h23"},fEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:u0},xEe={hour:Re,minute:Re,second:Re,hourCycle:"h23",timeZoneName:lu},dEe={year:Re,month:Re,day:Re,hour:Re,minute:Re},hEe={year:Re,month:Re,day:Re,hour:Re,minute:Re,second:Re},pEe={year:Re,month:u0,day:Re,hour:Re,minute:Re},mEe={year:Re,month:u0,day:Re,hour:Re,minute:Re,second:Re},Wnt={year:Re,month:u0,day:Re,weekday:u0,hour:Re,minute:Re},gEe={year:Re,month:lu,day:Re,hour:Re,minute:Re,timeZoneName:u0},yEe={year:Re,month:lu,day:Re,hour:Re,minute:Re,second:Re,timeZoneName:u0},EEe={year:Re,month:lu,day:Re,weekday:lu,hour:Re,minute:Re,timeZoneName:lu},AEe={year:Re,month:lu,day:Re,weekday:lu,hour:Re,minute:Re,second:Re,timeZoneName:lu};function kt(t){return typeof t>"u"}function og(t){return typeof t=="number"}function qM(t){return typeof t=="number"&&t%1===0}function Ynt(t){return typeof t=="string"}function Knt(t){return Object.prototype.toString.call(t)==="[object Date]"}function SEe(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Xnt(t){return Array.isArray(t)?t:[t]}function wye(t,e,r){if(t.length!==0)return t.reduce((n,i)=>{let s=[e(i),i];return n&&r(n[0],s[0])===n[0]?n:s},null)[1]}function Jnt(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function US(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function qx(t,e,r){return qM(t)&&t>=e&&t<=r}function Znt(t,e){return t-e*Math.floor(t/e)}function jn(t,e=2){let r=t<0,n;return r?n="-"+(""+-t).padStart(e,"0"):n=(""+t).padStart(e,"0"),n}function Lp(t){if(!(kt(t)||t===null||t===""))return parseInt(t,10)}function tg(t){if(!(kt(t)||t===null||t===""))return parseFloat(t)}function gJ(t){if(!(kt(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function yJ(t,e,r=!1){let n=10**e;return(r?Math.trunc:Math.round)(t*n)/n}function g5(t){return t%4===0&&(t%100!==0||t%400===0)}function p5(t){return g5(t)?366:365}function IM(t,e){let r=Znt(e-1,12)+1,n=t+(e-r)/12;return r===2?g5(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function EJ(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(e.getUTCFullYear()-1900)),+e}function MM(t){let e=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7,r=t-1,n=(r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400))%7;return e===4||n===3?53:52}function uJ(t){return t>99?t:t>60?1900+t:2e3+t}function vEe(t,e,r,n=null){let i=new Date(t),s={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(s.timeZone=n);let o={timeZoneName:e,...s},a=new Intl.DateTimeFormat(r,o).formatToParts(i).find(u=>u.type.toLowerCase()==="timezonename");return a?a.value:null}function UM(t,e){let r=parseInt(t,10);Number.isNaN(r)&&(r=0);let n=parseInt(e,10)||0,i=r<0||Object.is(r,-0)?-n:n;return r*60+i}function _Ee(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new xa(`Invalid unit value ${t}`);return e}function PM(t,e){let r={};for(let n in t)if(US(t,n)){let i=t[n];if(i==null)continue;r[e(n)]=_Ee(i)}return r}function m5(t,e){let r=Math.trunc(Math.abs(t/60)),n=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${jn(r,2)}:${jn(n,2)}`;case"narrow":return`${i}${r}${n>0?`:${n}`:""}`;case"techie":return`${i}${jn(r,2)}${jn(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function $M(t){return Jnt(t,["hour","minute","second","millisecond"])}var bEe=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,eit=["January","February","March","April","May","June","July","August","September","October","November","December"],TEe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],tit=["J","F","M","A","M","J","J","A","S","O","N","D"];function CEe(t){switch(t){case"narrow":return[...tit];case"short":return[...TEe];case"long":return[...eit];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var REe=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],OEe=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],rit=["M","T","W","T","F","S","S"];function DEe(t){switch(t){case"narrow":return[...rit];case"short":return[...OEe];case"long":return[...REe];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var NEe=["AM","PM"],nit=["Before Christ","Anno Domini"],iit=["BC","AD"],sit=["B","A"];function FEe(t){switch(t){case"narrow":return[...sit];case"short":return[...iit];case"long":return[...nit];default:return null}}function oit(t){return NEe[t.hour<12?0:1]}function ait(t,e){return DEe(e)[t.weekday-1]}function uit(t,e){return CEe(e)[t.month-1]}function lit(t,e){return FEe(e)[t.year<0?0:1]}function cit(t,e,r="always",n=!1){let i={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},s=["hours","minutes","seconds"].indexOf(t)===-1;if(r==="auto"&&s){let f=t==="days";switch(e){case 1:return f?"tomorrow":`next ${i[t][0]}`;case-1:return f?"yesterday":`last ${i[t][0]}`;case 0:return f?"today":`this ${i[t][0]}`}}let o=Object.is(e,-0)||e<0,a=Math.abs(e),u=a===1,l=i[t],c=n?u?l[1]:l[2]||l[1]:u?i[t][0]:t;return o?`${a} ${c} ago`:`in ${a} ${c}`}function Lye(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var fit={D:aJ,DD:rEe,DDD:nEe,DDDD:iEe,t:sEe,tt:oEe,ttt:aEe,tttt:uEe,T:lEe,TT:cEe,TTT:fEe,TTTT:xEe,f:dEe,ff:pEe,fff:gEe,ffff:EEe,F:hEe,FF:mEe,FFF:yEe,FFFF:AEe},a0=class t{static create(e,r={}){return new t(e,r)}static parseFormat(e){let r=null,n="",i=!1,s=[];for(let o=0;o<e.length;o++){let a=e.charAt(o);a==="'"?(n.length>0&&s.push({literal:i,val:n}),r=null,n="",i=!i):i||a===r?n+=a:(n.length>0&&s.push({literal:!1,val:n}),n=a,r=a)}return n.length>0&&s.push({literal:i,val:n}),s}static macroTokenToFormatOpts(e){return fit[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}formatDateTime(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).format()}formatDateTimeParts(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).formatToParts()}resolvedOptions(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r}).resolvedOptions()}num(e,r=0){if(this.opts.forceSimple)return jn(e,r);let n={...this.opts};return r>0&&(n.padTo=r),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,r){let n=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",s=(d,h)=>this.loc.extract(e,d,h),o=d=>e.isOffsetFixed&&e.offset===0&&d.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,d.format):"",a=()=>n?oit(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),u=(d,h)=>n?uit(e,d):s(h?{month:d}:{month:d,day:"numeric"},"month"),l=(d,h)=>n?ait(e,d):s(h?{weekday:d}:{weekday:d,month:"long",day:"numeric"},"weekday"),c=d=>{let h=t.macroTokenToFormatOpts(d);return h?this.formatWithSystemDefault(e,h):d},f=d=>n?lit(e,d):s({era:d},"era"),x=d=>{switch(d){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return i?s({day:"numeric"},"day"):this.num(e.day);case"dd":return i?s({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return l("short",!0);case"cccc":return l("long",!0);case"ccccc":return l("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return l("short",!1);case"EEEE":return l("long",!1);case"EEEEE":return l("narrow",!1);case"L":return i?s({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return i?s({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return u("short",!0);case"LLLL":return u("long",!0);case"LLLLL":return u("narrow",!0);case"M":return i?s({month:"numeric"},"month"):this.num(e.month);case"MM":return i?s({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return u("short",!1);case"MMMM":return u("long",!1);case"MMMMM":return u("narrow",!1);case"y":return i?s({year:"numeric"},"year"):this.num(e.year);case"yy":return i?s({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return i?s({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return i?s({year:"numeric"},"year"):this.num(e.year,6);case"G":return f("short");case"GG":return f("long");case"GGGGG":return f("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return c(d)}};return Lye(t.parseFormat(r),x)}formatDurationFromString(e,r){let n=u=>{switch(u[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},i=u=>l=>{let c=n(l);return c?this.num(u.get(c),l.length):l},s=t.parseFormat(r),o=s.reduce((u,{literal:l,val:c})=>l?u:u.concat(c),[]),a=e.shiftTo(...o.map(n).filter(u=>u));return Lye(s,i(a))}},uu=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}},Mp=class{get type(){throw new Xc}get name(){throw new Xc}get ianaName(){return this.name}get isUniversal(){throw new Xc}offsetName(e,r){throw new Xc}formatOffset(e,r){throw new Xc}offset(e){throw new Xc}equals(e){throw new Xc}get isValid(){throw new Xc}},KX=null,kM=class t extends Mp{static get instance(){return KX===null&&(KX=new t),KX}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return vEe(e,r,n)}formatOffset(e,r){return m5(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}},FM={};function xit(t){return FM[t]||(FM[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),FM[t]}var dit={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function hit(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,i,s,o,a,u,l,c]=n;return[o,i,s,a,u,l,c]}function pit(t,e){let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let{type:s,value:o}=r[i],a=dit[s];s==="era"?n[a]=o:kt(a)||(n[a]=parseInt(o,10))}return n}var RM={},$x=class t extends Mp{static create(e){return RM[e]||(RM[e]=new t(e)),RM[e]}static resetCache(){RM={},FM={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return vEe(e,r,n,this.name)}formatOffset(e,r){return m5(this.offset(e),r)}offset(e){let r=new Date(e);if(isNaN(r))return NaN;let n=xit(this.name),[i,s,o,a,u,l,c]=n.formatToParts?pit(n,r):hit(n,r);a==="BC"&&(i=-Math.abs(i)+1);let x=EJ({year:i,month:s,day:o,hour:u===24?0:u,minute:l,second:c,millisecond:0}),d=+r,h=d%1e3;return d-=h>=0?h:1e3+h,(x-d)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}},XX=null,cu=class t extends Mp{static get utcInstance(){return XX===null&&(XX=new t(0)),XX}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new t(UM(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${m5(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${m5(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return m5(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}},BM=class extends Mp{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function Ip(t,e){if(kt(t)||t===null)return e;if(t instanceof Mp)return t;if(Ynt(t)){let r=t.toLowerCase();return r==="local"||r==="system"?e:r==="utc"||r==="gmt"?cu.utcInstance:cu.parseSpecifier(r)||$x.create(t)}else return og(t)?cu.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new BM(t)}var Iye=()=>Date.now(),Mye="system",Pye=null,kye=null,Bye=null,qye,yn=class{static get now(){return Iye}static set now(e){Iye=e}static set defaultZone(e){Mye=e}static get defaultZone(){return Ip(Mye,kM.instance)}static get defaultLocale(){return Pye}static set defaultLocale(e){Pye=e}static get defaultNumberingSystem(){return kye}static set defaultNumberingSystem(e){kye=e}static get defaultOutputCalendar(){return Bye}static set defaultOutputCalendar(e){Bye=e}static get throwOnInvalid(){return qye}static set throwOnInvalid(e){qye=e}static resetCaches(){Hn.resetCache(),$x.resetCache()}},Uye={};function mit(t,e={}){let r=JSON.stringify([t,e]),n=Uye[r];return n||(n=new Intl.ListFormat(t,e),Uye[r]=n),n}var lJ={};function cJ(t,e={}){let r=JSON.stringify([t,e]),n=lJ[r];return n||(n=new Intl.DateTimeFormat(t,e),lJ[r]=n),n}var fJ={};function git(t,e={}){let r=JSON.stringify([t,e]),n=fJ[r];return n||(n=new Intl.NumberFormat(t,e),fJ[r]=n),n}var xJ={};function yit(t,e={}){let{base:r,...n}=e,i=JSON.stringify([t,n]),s=xJ[i];return s||(s=new Intl.RelativeTimeFormat(t,e),xJ[i]=s),s}var h5=null;function Eit(){return h5||(h5=new Intl.DateTimeFormat().resolvedOptions().locale,h5)}function Ait(t){let e=t.indexOf("-u-");if(e===-1)return[t];{let r,n=t.substring(0,e);try{r=cJ(t).resolvedOptions()}catch{r=cJ(n).resolvedOptions()}let{numberingSystem:i,calendar:s}=r;return[n,i,s]}}function Sit(t,e,r){return(r||e)&&(t+="-u",r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function vit(t){let e=[];for(let r=1;r<=12;r++){let n=En.utc(2016,r,1);e.push(t(n))}return e}function _it(t){let e=[];for(let r=1;r<=7;r++){let n=En.utc(2016,11,13+r);e.push(t(n))}return e}function OM(t,e,r,n,i){let s=t.listingMode(r);return s==="error"?null:s==="en"?n(e):i(e)}function bit(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}var dJ=class{constructor(e,r,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:i,floor:s,...o}=n;if(!r||Object.keys(o).length>0){let a={useGrouping:!1,...n};n.padTo>0&&(a.minimumIntegerDigits=n.padTo),this.inf=git(e,a)}}format(e){if(this.inf){let r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{let r=this.floor?Math.floor(e):yJ(e,3);return jn(r,this.padTo)}}},hJ=class{constructor(e,r,n){this.opts=n;let i;if(e.zone.isUniversal){let o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&$x.create(a).valid?(i=a,this.dt=e):(i="UTC",n.timeZoneName?this.dt=e:this.dt=e.offset===0?e:En.fromMillis(e.ts+e.offset*60*1e3))}else e.zone.type==="system"?this.dt=e:(this.dt=e,i=e.zone.name);let s={...this.opts};i&&(s.timeZone=i),this.dtf=cJ(r,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}},pJ=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&SEe()&&(this.rtf=yit(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):cit(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}},Hn=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,r,n,i=!1){let s=e||yn.defaultLocale,o=s||(i?"en-US":Eit()),a=r||yn.defaultNumberingSystem,u=n||yn.defaultOutputCalendar;return new t(o,a,u,s)}static resetCache(){h5=null,lJ={},fJ={},xJ={}}static fromObject({locale:e,numberingSystem:r,outputCalendar:n}={}){return t.create(e,r,n)}constructor(e,r,n,i){let[s,o,a]=Ait(e);this.locale=s,this.numberingSystem=r||o||null,this.outputCalendar=n||a||null,this.intl=Sit(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=bit(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,r=!1,n=!0){return OM(this,e,n,CEe,()=>{let i=r?{month:e,day:"numeric"}:{month:e},s=r?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=vit(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,r=!1,n=!0){return OM(this,e,n,DEe,()=>{let i=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=r?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=_it(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return OM(this,void 0,e,()=>NEe,()=>{if(!this.meridiemCache){let r={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[En.utc(2016,11,13,9),En.utc(2016,11,13,19)].map(n=>this.extract(n,r,"dayperiod"))}return this.meridiemCache})}eras(e,r=!0){return OM(this,e,r,FEe,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[En.utc(-40,1,1),En.utc(2017,1,1)].map(i=>this.extract(i,n,"era"))),this.eraCache[e]})}extract(e,r,n){let i=this.dtFormatter(e,r),s=i.formatToParts(),o=s.find(a=>a.type.toLowerCase()===n);return o?o.value:null}numberFormatter(e={}){return new dJ(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new hJ(e,this.intl,r)}relFormatter(e={}){return new pJ(this.intl,this.isEnglish(),e)}listFormatter(e={}){return mit(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}};function $S(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function jS(...t){return e=>t.reduce(([r,n,i],s)=>{let[o,a,u]=s(e,i);return[{...r,...o},a||n,u]},[{},null,1]).slice(0,2)}function HS(t,...e){if(t==null)return[null,null];for(let[r,n]of e){let i=r.exec(t);if(i)return n(i)}return[null,null]}function wEe(...t){return(e,r)=>{let n={},i;for(i=0;i<t.length;i++)n[t[i]]=Lp(e[r+i]);return[n,null,r+i]}}var LEe=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,Tit=`(?:${LEe.source}?(?:\\[(${bEe.source})\\])?)?`,AJ=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,IEe=RegExp(`${AJ.source}${Tit}`),SJ=RegExp(`(?:T${IEe.source})?`),Cit=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Rit=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Oit=/(\d{4})-?(\d{3})/,Dit=wEe("weekYear","weekNumber","weekDay"),Nit=wEe("year","ordinal"),Fit=/(\d{4})-(\d\d)-(\d\d)/,MEe=RegExp(`${AJ.source} ?(?:${LEe.source}|(${bEe.source}))?`),wit=RegExp(`(?: ${MEe.source})?`);function qS(t,e,r){let n=t[e];return kt(n)?r:Lp(n)}function Lit(t,e){return[{year:qS(t,e),month:qS(t,e+1,1),day:qS(t,e+2,1)},null,e+3]}function zS(t,e){return[{hours:qS(t,e,0),minutes:qS(t,e+1,0),seconds:qS(t,e+2,0),milliseconds:gJ(t[e+3])},null,e+4]}function y5(t,e){let r=!t[e]&&!t[e+1],n=UM(t[e+1],t[e+2]),i=r?null:cu.instance(n);return[{},i,e+3]}function E5(t,e){let r=t[e]?$x.create(t[e]):null;return[{},r,e+1]}var Iit=RegExp(`^T?${AJ.source}$`),Mit=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function Pit(t){let[e,r,n,i,s,o,a,u,l]=t,c=e[0]==="-",f=u&&u[0]==="-",x=(d,h=!1)=>d!==void 0&&(h||d&&c)?-d:d;return[{years:x(tg(r)),months:x(tg(n)),weeks:x(tg(i)),days:x(tg(s)),hours:x(tg(o)),minutes:x(tg(a)),seconds:x(tg(u),u==="-0"),milliseconds:x(gJ(l),f)}]}var kit={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function vJ(t,e,r,n,i,s,o){let a={year:e.length===2?uJ(Lp(e)):Lp(e),month:TEe.indexOf(r)+1,day:Lp(n),hour:Lp(i),minute:Lp(s)};return o&&(a.second=Lp(o)),t&&(a.weekday=t.length>3?REe.indexOf(t)+1:OEe.indexOf(t)+1),a}var Bit=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function qit(t){let[,e,r,n,i,s,o,a,u,l,c,f]=t,x=vJ(e,i,n,r,s,o,a),d;return u?d=kit[u]:l?d=0:d=UM(c,f),[x,new cu(d)]}function Uit(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var $it=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,jit=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Hit=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function $ye(t){let[,e,r,n,i,s,o,a]=t;return[vJ(e,i,n,r,s,o,a),cu.utcInstance]}function zit(t){let[,e,r,n,i,s,o,a]=t;return[vJ(e,a,r,n,i,s,o),cu.utcInstance]}var Git=$S(Cit,SJ),Qit=$S(Rit,SJ),Vit=$S(Oit,SJ),Wit=$S(IEe),PEe=jS(Lit,zS,y5,E5),Yit=jS(Dit,zS,y5,E5),Kit=jS(Nit,zS,y5,E5),Xit=jS(zS,y5,E5);function Jit(t){return HS(t,[Git,PEe],[Qit,Yit],[Vit,Kit],[Wit,Xit])}function Zit(t){return HS(Uit(t),[Bit,qit])}function est(t){return HS(t,[$it,$ye],[jit,$ye],[Hit,zit])}function tst(t){return HS(t,[Mit,Pit])}var rst=jS(zS);function nst(t){return HS(t,[Iit,rst])}var ist=$S(Fit,wit),sst=$S(MEe),ost=jS(zS,y5,E5);function ast(t){return HS(t,[ist,PEe],[sst,ost])}var ust="Invalid Duration",kEe={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},lst={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...kEe},rl=146097/400,BS=146097/4800,cst={years:{quarters:4,months:12,weeks:rl/7,days:rl,hours:rl*24,minutes:rl*24*60,seconds:rl*24*60*60,milliseconds:rl*24*60*60*1e3},quarters:{months:3,weeks:rl/28,days:rl/4,hours:rl*24/4,minutes:rl*24*60/4,seconds:rl*24*60*60/4,milliseconds:rl*24*60*60*1e3/4},months:{weeks:BS/7,days:BS,hours:BS*24,minutes:BS*24*60,seconds:BS*24*60*60,milliseconds:BS*24*60*60*1e3},...kEe},ng=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],fst=ng.slice(0).reverse();function rg(t,e,r=!1){let n={values:r?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy};return new ci(n)}function xst(t){return t<0?Math.floor(t):Math.ceil(t)}function BEe(t,e,r,n,i){let s=t[i][r],o=e[r]/s,a=Math.sign(o)===Math.sign(n[i]),u=!a&&n[i]!==0&&Math.abs(o)<=1?xst(o):Math.trunc(o);n[i]+=u,e[r]-=u*s}function dst(t,e){fst.reduce((r,n)=>kt(e[n])?r:(r&&BEe(t,e,r,e,n),n),null)}var ci=class t{constructor(e){let r=e.conversionAccuracy==="longterm"||!1;this.values=e.values,this.loc=e.loc||Hn.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=r?cst:lst,this.isLuxonDuration=!0}static fromMillis(e,r){return t.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new xa(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:PM(e,t.normalizeUnit),loc:Hn.fromObject(r),conversionAccuracy:r.conversionAccuracy})}static fromDurationLike(e){if(og(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new xa(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){let[n]=tst(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){let[n]=nst(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new xa("need to specify a reason the Duration is invalid");let n=e instanceof uu?e:new uu(e,r);if(yn.throwOnInvalid)throw new oJ(n);return new t({invalid:n})}static normalizeUnit(e){let r={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!r)throw new LM(e);return r}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,r={}){let n={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?a0.create(this.loc,n).formatDurationFromString(this,e):ust}toHuman(e={}){let r=ng.map(n=>{let i=this.values[n];return kt(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(r)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=yJ(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let r=this.toMillis();if(r<0||r>=864e5)return null;e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e};let n=this.shiftTo("hours","minutes","seconds","milliseconds"),i=e.format==="basic"?"hhmm":"hh:mm";(!e.suppressSeconds||n.seconds!==0||n.milliseconds!==0)&&(i+=e.format==="basic"?"ss":":ss",(!e.suppressMilliseconds||n.milliseconds!==0)&&(i+=".SSS"));let s=n.toFormat(i);return e.includePrefix&&(s="T"+s),s}toJSON(){return this.toISO()}toString(){return this.toISO()}toMillis(){return this.as("milliseconds")}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e),n={};for(let i of ng)(US(r.values,i)||US(this.values,i))&&(n[i]=r.get(i)+this.get(i));return rg(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;let r={};for(let n of Object.keys(this.values))r[n]=_Ee(e(this.values[n],n));return rg(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...PM(e,t.normalizeUnit)};return rg(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r}),s={loc:i};return n&&(s.conversionAccuracy=n),rg(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return dst(this.matrix,e),rg(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>t.normalizeUnit(o));let r={},n={},i=this.toObject(),s;for(let o of ng)if(e.indexOf(o)>=0){s=o;let a=0;for(let l in n)a+=this.matrix[l][o]*n[l],n[l]=0;og(i[o])&&(a+=i[o]);let u=Math.trunc(a);r[o]=u,n[o]=(a*1e3-u*1e3)/1e3;for(let l in i)ng.indexOf(l)>ng.indexOf(o)&&BEe(this.matrix,i,l,r,o)}else og(i[o])&&(n[o]=i[o]);for(let o in n)n[o]!==0&&(r[s]+=o===s?n[o]:n[o]/this.matrix[s][o]);return rg(this,{values:r},!0).normalize()}negate(){if(!this.isValid)return this;let e={};for(let r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return rg(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function r(n,i){return n===void 0||n===0?i===void 0||i===0:n===i}for(let n of ng)if(!r(this.values[n],e.values[n]))return!1;return!0}},c5="Invalid Interval";function hst(t,e){return!t||!t.isValid?ag.invalid("missing or invalid start"):!e||!e.isValid?ag.invalid("missing or invalid end"):e<t?ag.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var ag=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new xa("need to specify a reason the Interval is invalid");let n=e instanceof uu?e:new uu(e,r);if(yn.throwOnInvalid)throw new sJ(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=d5(e),i=d5(r),s=hst(n,i);return s??new t({start:n,end:i})}static after(e,r){let n=ci.fromDurationLike(r),i=d5(e);return t.fromDateTimes(i,i.plus(n))}static before(e,r){let n=ci.fromDurationLike(r),i=d5(e);return t.fromDateTimes(i.minus(n),i)}static fromISO(e,r){let[n,i]=(e||"").split("/",2);if(n&&i){let s,o;try{s=En.fromISO(n,r),o=s.isValid}catch{o=!1}let a,u;try{a=En.fromISO(i,r),u=a.isValid}catch{u=!1}if(o&&u)return t.fromDateTimes(s,a);if(o){let l=ci.fromISO(i,r);if(l.isValid)return t.after(s,l)}else if(u){let l=ci.fromISO(n,r);if(l.isValid)return t.before(a,l)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds"){if(!this.isValid)return NaN;let r=this.start.startOf(e),n=this.end.startOf(e);return Math.floor(n.diff(r,e).get(e))+1}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:r}={}){return this.isValid?t.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];let r=e.map(d5).filter(o=>this.contains(o)).sort(),n=[],{s:i}=this,s=0;for(;i<this.e;){let o=r[s]||this.e,a=+o>+this.e?this.e:o;n.push(t.fromDateTimes(i,a)),i=a,s+=1}return n}splitBy(e){let r=ci.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:n}=this,i=1,s,o=[];for(;n<this.e;){let a=this.start.plus(r.mapUnits(u=>u*i));s=+a>+this.e?this.e:a,o.push(t.fromDateTimes(n,s)),n=s,i+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let r=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return r>=n?null:t.fromDateTimes(r,n)}union(e){if(!this.isValid)return this;let r=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return t.fromDateTimes(r,n)}static merge(e){let[r,n]=e.sort((i,s)=>i.s-s.s).reduce(([i,s],o)=>s?s.overlaps(o)||s.abutsStart(o)?[i,s.union(o)]:[i.concat([s]),o]:[i,o],[[],null]);return n&&r.push(n),r}static xor(e){let r=null,n=0,i=[],s=e.map(u=>[{time:u.s,type:"s"},{time:u.e,type:"e"}]),o=Array.prototype.concat(...s),a=o.sort((u,l)=>u.time-l.time);for(let u of a)n+=u.type==="s"?1:-1,n===1?r=u.time:(r&&+r!=+u.time&&i.push(t.fromDateTimes(r,u.time)),r=null);return t.merge(i)}difference(...e){return t.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:c5}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:c5}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:c5}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:c5}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:c5}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):ci.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}},sg=class{static hasDST(e=yn.defaultZone){let r=En.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return $x.isValidZone(e)}static normalizeZone(e){return Ip(e,yn.defaultZone)}static months(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||Hn.create(r,n,s)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||Hn.create(r,n,s)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||Hn.create(r,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:i=null}={}){return(i||Hn.create(r,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return Hn.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return Hn.create(r,null,"gregory").eras(e)}static features(){return{relative:SEe()}}};function jye(t,e){let r=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=r(e)-r(t);return Math.floor(ci.fromMillis(n).as("days"))}function pst(t,e,r){let n=[["years",(a,u)=>u.year-a.year],["quarters",(a,u)=>u.quarter-a.quarter],["months",(a,u)=>u.month-a.month+(u.year-a.year)*12],["weeks",(a,u)=>{let l=jye(a,u);return(l-l%7)/7}],["days",jye]],i={},s,o;for(let[a,u]of n)if(r.indexOf(a)>=0){s=a;let l=u(t,e);o=t.plus({[a]:l}),o>e?(t=t.plus({[a]:l-1}),l-=1):t=o,i[a]=l}return[t,i,o,s]}function mst(t,e,r,n){let[i,s,o,a]=pst(t,e,r),u=e-i,l=r.filter(f=>["hours","minutes","seconds","milliseconds"].indexOf(f)>=0);l.length===0&&(o<e&&(o=i.plus({[a]:1})),o!==i&&(s[a]=(s[a]||0)+u/(o-i)));let c=ci.fromObject(s,n);return l.length>0?ci.fromMillis(u,n).shiftTo(...l).plus(c):c}var _J={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Hye={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},gst=_J.hanidec.replace(/[\[|\]]/g,"").split("");function yst(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(t[r].search(_J.hanidec)!==-1)e+=gst.indexOf(t[r]);else for(let i in Hye){let[s,o]=Hye[i];n>=s&&n<=o&&(e+=n-s)}}return parseInt(e,10)}else return e}function s0({numberingSystem:t},e=""){return new RegExp(`${_J[t||"latn"]}${e}`)}var Est="missing Intl.DateTimeFormat.formatToParts support";function Yt(t,e=r=>r){return{regex:t,deser:([r])=>e(yst(r))}}var Ast="\xA0",qEe=`[ ${Ast}]`,UEe=new RegExp(qEe,"g");function Sst(t){return t.replace(/\./g,"\\.?").replace(UEe,qEe)}function zye(t){return t.replace(/\./g,"").replace(UEe," ").toLowerCase()}function o0(t,e){return t===null?null:{regex:RegExp(t.map(Sst).join("|")),deser:([r])=>t.findIndex(n=>zye(r)===zye(n))+e}}function Gye(t,e){return{regex:t,deser:([,r,n])=>UM(r,n),groups:e}}function JX(t){return{regex:t,deser:([e])=>e}}function vst(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function _st(t,e){let r=s0(e),n=s0(e,"{2}"),i=s0(e,"{3}"),s=s0(e,"{4}"),o=s0(e,"{6}"),a=s0(e,"{1,2}"),u=s0(e,"{1,3}"),l=s0(e,"{1,6}"),c=s0(e,"{1,9}"),f=s0(e,"{2,4}"),x=s0(e,"{4,6}"),d=m=>({regex:RegExp(vst(m.val)),deser:([g])=>g,literal:!0}),p=(m=>{if(t.literal)return d(m);switch(m.val){case"G":return o0(e.eras("short",!1),0);case"GG":return o0(e.eras("long",!1),0);case"y":return Yt(l);case"yy":return Yt(f,uJ);case"yyyy":return Yt(s);case"yyyyy":return Yt(x);case"yyyyyy":return Yt(o);case"M":return Yt(a);case"MM":return Yt(n);case"MMM":return o0(e.months("short",!0,!1),1);case"MMMM":return o0(e.months("long",!0,!1),1);case"L":return Yt(a);case"LL":return Yt(n);case"LLL":return o0(e.months("short",!1,!1),1);case"LLLL":return o0(e.months("long",!1,!1),1);case"d":return Yt(a);case"dd":return Yt(n);case"o":return Yt(u);case"ooo":return Yt(i);case"HH":return Yt(n);case"H":return Yt(a);case"hh":return Yt(n);case"h":return Yt(a);case"mm":return Yt(n);case"m":return Yt(a);case"q":return Yt(a);case"qq":return Yt(n);case"s":return Yt(a);case"ss":return Yt(n);case"S":return Yt(u);case"SSS":return Yt(i);case"u":return JX(c);case"uu":return JX(a);case"uuu":return Yt(r);case"a":return o0(e.meridiems(),0);case"kkkk":return Yt(s);case"kk":return Yt(f,uJ);case"W":return Yt(a);case"WW":return Yt(n);case"E":case"c":return Yt(r);case"EEE":return o0(e.weekdays("short",!1,!1),1);case"EEEE":return o0(e.weekdays("long",!1,!1),1);case"ccc":return o0(e.weekdays("short",!0,!1),1);case"cccc":return o0(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return Gye(new RegExp(`([+-]${a.source})(?::(${n.source}))?`),2);case"ZZZ":return Gye(new RegExp(`([+-]${a.source})(${n.source})?`),2);case"z":return JX(/[a-z_+-/]{1,256}?/i);default:return d(m)}})(t)||{invalidReason:Est};return p.token=t,p}var bst={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour:{numeric:"h","2-digit":"hh"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"}};function Tst(t,e,r){let{type:n,value:i}=t;if(n==="literal")return{literal:!0,val:i};let s=r[n],o=bst[n];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function Cst(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function Rst(t,e,r){let n=t.match(e);if(n){let i={},s=1;for(let o in r)if(US(r,o)){let a=r[o],u=a.groups?a.groups+1:1;!a.literal&&a.token&&(i[a.token.val[0]]=a.deser(n.slice(s,s+u))),s+=u}return[n,i]}else return[n,{}]}function Ost(t){let e=s=>{switch(s){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},r=null,n;return kt(t.z)||(r=$x.create(t.z)),kt(t.Z)||(r||(r=new cu(t.Z)),n=t.Z),kt(t.q)||(t.M=(t.q-1)*3+1),kt(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),kt(t.u)||(t.S=gJ(t.u)),[Object.keys(t).reduce((s,o)=>{let a=e(o);return a&&(s[a]=t[o]),s},{}),r,n]}var ZX=null;function Dst(){return ZX||(ZX=En.fromMillis(1555555555555)),ZX}function Nst(t,e){if(t.literal)return t;let r=a0.macroTokenToFormatOpts(t.val);if(!r)return t;let s=a0.create(e,r).formatDateTimeParts(Dst()).map(o=>Tst(o,e,r));return s.includes(void 0)?t:s}function Fst(t,e){return Array.prototype.concat(...t.map(r=>Nst(r,e)))}function $Ee(t,e,r){let n=Fst(a0.parseFormat(r),t),i=n.map(o=>_st(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:n,invalidReason:s.invalidReason};{let[o,a]=Cst(i),u=RegExp(o,"i"),[l,c]=Rst(e,u,a),[f,x,d]=c?Ost(c):[null,null,void 0];if(US(c,"a")&&US(c,"H"))throw new ig("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:u,rawMatches:l,matches:c,result:f,zone:x,specificOffset:d}}}function wst(t,e,r){let{result:n,zone:i,specificOffset:s,invalidReason:o}=$Ee(t,e,r);return[n,i,s,o]}var jEe=[0,31,59,90,120,151,181,212,243,273,304,334],HEe=[0,31,60,91,121,152,182,213,244,274,305,335];function nl(t,e){return new uu("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function zEe(t,e,r){let n=new Date(Date.UTC(t,e-1,r));t<100&&t>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let i=n.getUTCDay();return i===0?7:i}function GEe(t,e,r){return r+(g5(t)?HEe:jEe)[e-1]}function QEe(t,e){let r=g5(t)?HEe:jEe,n=r.findIndex(s=>s<e),i=e-r[n];return{month:n+1,day:i}}function mJ(t){let{year:e,month:r,day:n}=t,i=GEe(e,r,n),s=zEe(e,r,n),o=Math.floor((i-s+10)/7),a;return o<1?(a=e-1,o=MM(a)):o>MM(e)?(a=e+1,o=1):a=e,{weekYear:a,weekNumber:o,weekday:s,...$M(t)}}function Qye(t){let{weekYear:e,weekNumber:r,weekday:n}=t,i=zEe(e,1,4),s=p5(e),o=r*7+n-i-3,a;o<1?(a=e-1,o+=p5(a)):o>s?(a=e+1,o-=p5(e)):a=e;let{month:u,day:l}=QEe(a,o);return{year:a,month:u,day:l,...$M(t)}}function eJ(t){let{year:e,month:r,day:n}=t,i=GEe(e,r,n);return{year:e,ordinal:i,...$M(t)}}function Vye(t){let{year:e,ordinal:r}=t,{month:n,day:i}=QEe(e,r);return{year:e,month:n,day:i,...$M(t)}}function Lst(t){let e=qM(t.weekYear),r=qx(t.weekNumber,1,MM(t.weekYear)),n=qx(t.weekday,1,7);return e?r?n?!1:nl("weekday",t.weekday):nl("week",t.week):nl("weekYear",t.weekYear)}function Ist(t){let e=qM(t.year),r=qx(t.ordinal,1,p5(t.year));return e?r?!1:nl("ordinal",t.ordinal):nl("year",t.year)}function VEe(t){let e=qM(t.year),r=qx(t.month,1,12),n=qx(t.day,1,IM(t.year,t.month));return e?r?n?!1:nl("day",t.day):nl("month",t.month):nl("year",t.year)}function WEe(t){let{hour:e,minute:r,second:n,millisecond:i}=t,s=qx(e,0,23)||e===24&&r===0&&n===0&&i===0,o=qx(r,0,59),a=qx(n,0,59),u=qx(i,0,999);return s?o?a?u?!1:nl("millisecond",i):nl("second",n):nl("minute",r):nl("hour",e)}var tJ="Invalid DateTime",Wye=864e13;function DM(t){return new uu("unsupported zone",`the zone "${t.name}" is not supported`)}function rJ(t){return t.weekData===null&&(t.weekData=mJ(t.c)),t.weekData}function f5(t,e){let r={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new En({...r,...e,old:r})}function YEe(t,e,r){let n=t-e*60*1e3,i=r.offset(n);if(e===i)return[n,e];n-=(i-e)*60*1e3;let s=r.offset(n);return i===s?[n,i]:[t-Math.min(i,s)*60*1e3,Math.max(i,s)]}function Yye(t,e){t+=e*60*1e3;let r=new Date(t);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function wM(t,e,r){return YEe(EJ(t),e,r)}function Kye(t,e){let r=t.o,n=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,s={...t.c,year:n,month:i,day:Math.min(t.c.day,IM(n,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=ci.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=EJ(s),[u,l]=YEe(a,r,t.zone);return o!==0&&(u+=o,l=t.zone.offset(u)),{ts:u,o:l}}function x5(t,e,r,n,i,s){let{setZone:o,zone:a}=r;if(t&&Object.keys(t).length!==0){let u=e||a,l=En.fromObject(t,{...r,zone:u,specificOffset:s});return o?l:l.setZone(a)}else return En.invalid(new uu("unparsable",`the input "${i}" can't be parsed as ${n}`))}function NM(t,e,r=!0){return t.isValid?a0.create(Hn.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function nJ(t,e){let r=t.c.year>9999||t.c.year<0,n="";return r&&t.c.year>=0&&(n+="+"),n+=jn(t.c.year,r?6:4),e?(n+="-",n+=jn(t.c.month),n+="-",n+=jn(t.c.day)):(n+=jn(t.c.month),n+=jn(t.c.day)),n}function Xye(t,e,r,n,i,s){let o=jn(t.c.hour);return e?(o+=":",o+=jn(t.c.minute),(t.c.second!==0||!r)&&(o+=":")):o+=jn(t.c.minute),(t.c.second!==0||!r)&&(o+=jn(t.c.second),(t.c.millisecond!==0||!n)&&(o+=".",o+=jn(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!s?o+="Z":t.o<0?(o+="-",o+=jn(Math.trunc(-t.o/60)),o+=":",o+=jn(Math.trunc(-t.o%60))):(o+="+",o+=jn(Math.trunc(t.o/60)),o+=":",o+=jn(Math.trunc(t.o%60)))),s&&(o+="["+t.zone.ianaName+"]"),o}var KEe={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Mst={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Pst={ordinal:1,hour:0,minute:0,second:0,millisecond:0},XEe=["year","month","day","hour","minute","second","millisecond"],kst=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Bst=["year","ordinal","hour","minute","second","millisecond"];function Jye(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new LM(t);return e}function Zye(t,e){let r=Ip(e.zone,yn.defaultZone),n=Hn.fromObject(e),i=yn.now(),s,o;if(kt(t.year))s=i;else{for(let l of XEe)kt(t[l])&&(t[l]=KEe[l]);let a=VEe(t)||WEe(t);if(a)return En.invalid(a);let u=r.offset(i);[s,o]=wM(t,u,r)}return new En({ts:s,zone:r,loc:n,o})}function eEe(t,e,r){let n=kt(r.round)?!0:r.round,i=(o,a)=>(o=yJ(o,n||r.calendary?0:2,!0),e.loc.clone(r).relFormatter(r).format(o,a)),s=o=>r.calendary?e.hasSame(t,o)?0:e.startOf(o).diff(t.startOf(o),o).get(o):e.diff(t,o).get(o);if(r.unit)return i(s(r.unit),r.unit);for(let o of r.units){let a=s(o);if(Math.abs(a)>=1)return i(a,o)}return i(t>e?-0:0,r.units[r.units.length-1])}function tEe(t){let e={},r;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],r=Array.from(t).slice(0,t.length-1)):r=Array.from(t),[e,r]}var En=class t{constructor(e){let r=e.zone||yn.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new uu("invalid input"):null)||(r.isValid?null:DM(r));this.ts=kt(e.ts)?yn.now():e.ts;let i=null,s=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[i,s]=[e.old.c,e.old.o];else{let a=r.offset(this.ts);i=Yye(this.ts,a),n=Number.isNaN(i.year)?new uu("invalid input"):null,i=n?null:i,s=n?null:a}this._zone=r,this.loc=e.loc||Hn.create(),this.invalid=n,this.weekData=null,this.c=i,this.o=s,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,r]=tEe(arguments),[n,i,s,o,a,u,l]=r;return Zye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static utc(){let[e,r]=tEe(arguments),[n,i,s,o,a,u,l]=r;return e.zone=cu.utcInstance,Zye({year:n,month:i,day:s,hour:o,minute:a,second:u,millisecond:l},e)}static fromJSDate(e,r={}){let n=Knt(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let i=Ip(r.zone,yn.defaultZone);return i.isValid?new t({ts:n,zone:i,loc:Hn.fromObject(r)}):t.invalid(DM(i))}static fromMillis(e,r={}){if(og(e))return e<-Wye||e>Wye?t.invalid("Timestamp out of range"):new t({ts:e,zone:Ip(r.zone,yn.defaultZone),loc:Hn.fromObject(r)});throw new xa(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(og(e))return new t({ts:e*1e3,zone:Ip(r.zone,yn.defaultZone),loc:Hn.fromObject(r)});throw new xa("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=Ip(r.zone,yn.defaultZone);if(!n.isValid)return t.invalid(DM(n));let i=yn.now(),s=kt(r.specificOffset)?n.offset(i):r.specificOffset,o=PM(e,Jye),a=!kt(o.ordinal),u=!kt(o.year),l=!kt(o.month)||!kt(o.day),c=u||l,f=o.weekYear||o.weekNumber,x=Hn.fromObject(r);if((c||a)&&f)throw new ig("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&a)throw new ig("Can't mix ordinal dates with month/day");let d=f||o.weekday&&!c,h,p,m=Yye(i,s);d?(h=kst,p=Mst,m=mJ(m)):a?(h=Bst,p=Pst,m=eJ(m)):(h=XEe,p=KEe);let g=!1;for(let R of h){let D=o[R];kt(D)?g?o[R]=p[R]:o[R]=m[R]:g=!0}let y=d?Lst(o):a?Ist(o):VEe(o),A=y||WEe(o);if(A)return t.invalid(A);let S=d?Qye(o):a?Vye(o):o,[T,b]=wM(S,s,n),_=new t({ts:T,zone:n,o:b,loc:x});return o.weekday&&c&&e.weekday!==_.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${_.toISO()}`):_}static fromISO(e,r={}){let[n,i]=Jit(e);return x5(n,i,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,i]=Zit(e);return x5(n,i,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,i]=est(e);return x5(n,i,r,"HTTP",r)}static fromFormat(e,r,n={}){if(kt(e)||kt(r))throw new xa("fromFormat requires an input string and a format");let{locale:i=null,numberingSystem:s=null}=n,o=Hn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0}),[a,u,l,c]=wst(o,e,r);return c?t.invalid(c):x5(a,u,n,`format ${r}`,e,l)}static fromString(e,r,n={}){return t.fromFormat(e,r,n)}static fromSQL(e,r={}){let[n,i]=ast(e);return x5(n,i,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new xa("need to specify a reason the DateTime is invalid");let n=e instanceof uu?e:new uu(e,r);if(yn.throwOnInvalid)throw new iJ(n);return new t({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?rJ(this).weekYear:NaN}get weekNumber(){return this.isValid?rJ(this).weekNumber:NaN}get weekday(){return this.isValid?rJ(this).weekday:NaN}get ordinal(){return this.isValid?eJ(this.c).ordinal:NaN}get monthShort(){return this.isValid?sg.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?sg.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?sg.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?sg.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}get isInLeapYear(){return g5(this.year)}get daysInMonth(){return IM(this.year,this.month)}get daysInYear(){return this.isValid?p5(this.year):NaN}get weeksInWeekYear(){return this.isValid?MM(this.weekYear):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:i}=a0.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:n,outputCalendar:i}}toUTC(e=0,r={}){return this.setZone(cu.instance(e),r)}toLocal(){return this.setZone(yn.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:n=!1}={}){if(e=Ip(e,yn.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(r||n){let s=e.offset(this.ts),o=this.toObject();[i]=wM(o,s,e)}return f5(this,{ts:i,zone:e})}else return t.invalid(DM(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let i=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return f5(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=PM(e,Jye),n=!kt(r.weekYear)||!kt(r.weekNumber)||!kt(r.weekday),i=!kt(r.ordinal),s=!kt(r.year),o=!kt(r.month)||!kt(r.day),a=s||o,u=r.weekYear||r.weekNumber;if((a||i)&&u)throw new ig("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new ig("Can't mix ordinal dates with month/day");let l;n?l=Qye({...mJ(this.c),...r}):kt(r.ordinal)?(l={...this.toObject(),...r},kt(r.day)&&(l.day=Math.min(IM(l.year,l.month),l.day))):l=Vye({...eJ(this.c),...r});let[c,f]=wM(l,this.o,this.zone);return f5(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e);return f5(this,Kye(this,r))}minus(e){if(!this.isValid)return this;let r=ci.fromDurationLike(e).negate();return f5(this,Kye(this,r))}startOf(e){if(!this.isValid)return this;let r={},n=ci.normalizeUnit(e);switch(n){case"years":r.month=1;case"quarters":case"months":r.day=1;case"weeks":case"days":r.hour=0;case"hours":r.minute=0;case"minutes":r.second=0;case"seconds":r.millisecond=0;break}if(n==="weeks"&&(r.weekday=1),n==="quarters"){let i=Math.ceil(this.month/3);r.month=(i-1)*3+1}return this.set(r)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,r={}){return this.isValid?a0.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):tJ}toLocaleString(e=aJ,r={}){return this.isValid?a0.create(this.loc.clone(r),e).formatDateTime(this):tJ}toLocaleParts(e={}){return this.isValid?a0.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:n=!1,includeOffset:i=!0,extendedZone:s=!1}={}){if(!this.isValid)return null;let o=e==="extended",a=nJ(this,o);return a+="T",a+=Xye(this,o,r,n,i,s),a}toISODate({format:e="extended"}={}){return this.isValid?nJ(this,e==="extended"):null}toISOWeekDate(){return NM(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:n=!0,includePrefix:i=!1,extendedZone:s=!1,format:o="extended"}={}){return this.isValid?(i?"T":"")+Xye(this,o==="extended",r,e,n,s):null}toRFC2822(){return NM(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return NM(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?nJ(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:n=!0}={}){let i="HH:mm:ss.SSS";return(r||e)&&(n&&(i+=" "),r?i+="z":e&&(i+="ZZ")),NM(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():tJ}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",n={}){if(!this.isValid||!e.isValid)return ci.invalid("created by diffing an invalid DateTime");let i={locale:this.locale,numberingSystem:this.numberingSystem,...n},s=Xnt(r).map(ci.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,u=o?e:this,l=mst(a,u,s,i);return o?l.negate():l}diffNow(e="milliseconds",r={}){return this.diff(t.now(),e,r)}until(e){return this.isValid?ag.fromDateTimes(this,e):this}hasSame(e,r){if(!this.isValid)return!1;let n=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(r)<=n&&n<=i.endOf(r)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let r=e.base||t.fromObject({},{zone:this.zone}),n=e.padding?this<r?-e.padding:e.padding:0,i=["years","months","days","hours","minutes","seconds"],s=e.unit;return Array.isArray(e.unit)&&(i=e.unit,s=void 0),eEe(r,this.plus(n),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?eEe(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new xa("min requires all arguments be DateTimes");return wye(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new xa("max requires all arguments be DateTimes");return wye(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,n={}){let{locale:i=null,numberingSystem:s=null}=n,o=Hn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0});return $Ee(o,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static get DATE_SHORT(){return aJ}static get DATE_MED(){return rEe}static get DATE_MED_WITH_WEEKDAY(){return Vnt}static get DATE_FULL(){return nEe}static get DATE_HUGE(){return iEe}static get TIME_SIMPLE(){return sEe}static get TIME_WITH_SECONDS(){return oEe}static get TIME_WITH_SHORT_OFFSET(){return aEe}static get TIME_WITH_LONG_OFFSET(){return uEe}static get TIME_24_SIMPLE(){return lEe}static get TIME_24_WITH_SECONDS(){return cEe}static get TIME_24_WITH_SHORT_OFFSET(){return fEe}static get TIME_24_WITH_LONG_OFFSET(){return xEe}static get DATETIME_SHORT(){return dEe}static get DATETIME_SHORT_WITH_SECONDS(){return hEe}static get DATETIME_MED(){return pEe}static get DATETIME_MED_WITH_SECONDS(){return mEe}static get DATETIME_MED_WITH_WEEKDAY(){return Wnt}static get DATETIME_FULL(){return gEe}static get DATETIME_FULL_WITH_SECONDS(){return yEe}static get DATETIME_HUGE(){return EEe}static get DATETIME_HUGE_WITH_SECONDS(){return AEe}};function d5(t){if(En.isDateTime(t))return t;if(t&&t.valueOf&&og(t.valueOf()))return En.fromJSDate(t);if(t&&typeof t=="object")return En.fromObject(t);throw new xa(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var qst="2.5.2";fu.DateTime=En;fu.Duration=ci;fu.FixedOffsetZone=cu;fu.IANAZone=$x;fu.Info=sg;fu.Interval=ag;fu.InvalidZone=BM;fu.Settings=yn;fu.SystemZone=kM;fu.VERSION=qst;fu.Zone=Mp});var nAe=v(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.LiteralYear=ki.LiteralQuarter=ki.LiteralMonth=ki.LiteralWeek=ki.LiteralDay=ki.LiteralHour=ki.LiteralTimestamp=ki.TimeFormatError=void 0;var Pp=bJ(),Ust=Ke(),$st=IS(),JEe=TI(),TJ=ir(),CJ=class extends Error{};ki.TimeFormatError=CJ;function lg(t,e){let r=t.slice(1);if(e){let n=r.match(/\[[^\]]+]$/);if(n)return{tzSpec:n[0].slice(1,-1),text:r.slice(0,-n[0].length)}}return{text:r}}var ZEe="yyyy",eAe=`${ZEe}-LL`,il=`${eAe}-dd`,tAe=`${il} HH`,rAe=`${tAe}:mm`,RJ=`${rAe}:ss`,jM=class extends TJ.ExpressionDef{constructor(e,r,n){super(),this.units=r,this.timeType=n,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){let n={type:"dialect",function:"timeLiteral",literal:e,literalType:r};return this.timeZone&&(n.timezone=this.timeZone),n}makeValue(e,r){let n=this.makeLiteral(e,r),i="scalar",s=[n];return this.units?{dataType:r,expressionType:i,value:s,timeframe:this.units,evalSpace:"literal"}:{dataType:r,expressionType:i,value:s,evalSpace:"literal"}}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}},OJ=class t extends jM{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r,n=lg(e,!0);e=n.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),n.text=e);let i=e.match(/^([^.,]+)[,.](\d+)$/);i&&(e=i[1]);let s=Pp.DateTime.fromFormat(e,RJ);if(s.isValid)return new t(n,r);if(s=Pp.DateTime.fromFormat(e,rAe),s.isValid){n.text=n.text+":00",r="minute";let o=s.plus({minute:1}).toFormat(RJ);return new A5(n,r,"timestamp",o)}}};ki.LiteralTimestamp=OJ;var A5=class extends jM{constructor(e,r,n,i){super(e,r,n),this.nextLit=i,this.elementType="granularTimeLiteral"}apply(e,r,n){let i=this.getExpression(e),s=this.getNext();if(s){let o=n.getExpression(e);if(o.dataType==="timestamp"){let a=(0,TJ.getMorphicValue)(i,"timestamp"),u=(0,TJ.getMorphicValue)(s,"timestamp");if(a&&u)i=a,s=u;else return super.apply(e,r,n)}if((0,Ust.isTimeFieldType)(o.dataType)){let a=o.dataType;return new $st.Range(new JEe.ExprTime(a,i.value),new JEe.ExprTime(a,s.value)).apply(e,r,n)}}return super.apply(e,r,n)}},DJ=class t extends A5{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){let r=lg(e,!1),n=r.text,i=Pp.DateTime.fromFormat(r.text,tAe);if(i.isValid)return r.text=r.text+":00:00",n=i.plus({hour:1}).toFormat(RJ),new t(r,n)}};ki.LiteralHour=DJ;var ug=class extends A5{constructor(e,r,n){super(e,r,"date",n)}getExpression(e){let r=this.makeValue(this.literalPart,"date"),n=[this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp")];return{...r,morphic:{timestamp:n},evalSpace:"literal"}}getNext(){let e=this.makeValue(this.nextLit,"date"),r=[this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp")];return{...e,morphic:{timestamp:r}}}},NJ=class t extends ug{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){let r=lg(e,!1),n=r.text,i=Pp.DateTime.fromFormat(r.text,il);if(i.isValid)return n=i.plus({day:1}).toFormat(il),new t(r,n)}};ki.LiteralDay=NJ;var FJ=class t extends ug{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){let r=lg(e,!1),n=r.text,i=r.text.slice(0,10),s=Pp.DateTime.fromFormat(i,il);if(s.isValid&&s.weekday===7){let a=s.plus({days:7});return r.text=s.toFormat(il),n=a.toFormat(il),new t(r,n)}}};ki.LiteralWeek=FJ;var wJ=class t extends ug{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){let r=lg(e,!1),n=r.text,i=Pp.DateTime.fromFormat(r.text,eAe);if(i.isValid){let s=i.plus({months:1});return r.text=i.toFormat(il),n=s.toFormat(il),new t(r,n)}}};ki.LiteralMonth=wJ;var LJ=class t extends ug{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){let r=lg(e,!1),n=r.text,i=r.text.match(/(^\d{4})-[qQ](\d)$/);if(i){let s=Number.parseInt(i[2])-1,o=Pp.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));let a=o.plus({quarter:1});return r.text=o.toFormat(il),n=a.toFormat(il),new t(r,n)}}};ki.LiteralQuarter=LJ;var IJ=class t extends ug{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){let r=lg(e,!1),n=r.text,i=Pp.DateTime.fromFormat(r.text,ZEe);if(i.isValid){let s=i.plus({year:1});return r.text=i.toFormat(il),n=s.toFormat(il),new t(r,n)}}};ki.LiteralYear=IJ});var iAe=v(HM=>{"use strict";Object.defineProperty(HM,"__esModule",{value:!0});HM.PartialCompare=void 0;var jst=js(),Hst=ir(),MJ=class extends Hst.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,n){return this.right.apply(e,this.op,n)}requestExpression(e){}getExpression(e){return this.log("Partial comparison does not have a value"),(0,jst.errorFor)("no value for partial compare")}};HM.PartialCompare=MJ});var oAe=v(GS=>{"use strict";Object.defineProperty(GS,"__esModule",{value:!0});GS.PickWhen=GS.Pick=void 0;var Jc=Ke(),kp=js(),l0=pn(),zst=ir(),Gst=mt(),sAe=hs();function zM(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}var PJ=class extends zst.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(let r of this.choices){if(r.pick===void 0)return;let n=r.when.requestExpression(e);if(n===void 0||n.dataType!=="boolean")return}return this.getExpression(e)}}apply(e,r,n){let i=["CASE"],s,o="scalar",a="constant";for(let c of this.choices){let f=c.when.apply(e,"=",n),x=c.pick?c.pick.getExpression(e):n.getExpression(e);if(o=(0,Jc.maxExpressionType)(o,(0,Jc.maxExpressionType)(f.expressionType,x.expressionType)),a=(0,Jc.mergeEvalSpaces)(a,f.evalSpace,x.evalSpace),s&&!l0.FT.typeEq(s,x,!0)){let d=l0.FT.inspect(x);return this.log(`pick type '${d}', expected '${s.dataType}'`),(0,kp.errorFor)("pick when type")}s=zM(s,x),i.push(" WHEN ",...f.value," THEN ",...x.value)}let l=(this.elsePick||n).getExpression(e);if(s=zM(s,l),!l0.FT.typeEq(s,l,!0)){let c=this.elsePick?"else":"pick default";return this.log(`${c} type '${l0.FT.inspect(l)}', expected '${s.dataType}'`),(0,kp.errorFor)("pick else type")}return{dataType:s.dataType,expressionType:(0,Jc.maxExpressionType)(o,l.expressionType),evalSpace:(0,Jc.mergeEvalSpaces)(a,l.evalSpace),value:(0,sAe.compressExpr)([...i," ELSE ",...l.value," END"])}}getExpression(e){if(this.elsePick===void 0)return this.log("pick incomplete, missing 'else'"),(0,kp.errorFor)("no value for partial pick");let r=[];for(let u of this.choices){if(u.pick===void 0)return this.log("pick with no value can only be used with apply"),(0,kp.errorFor)("no value for partial pick");if(u.when.requestExpression(e)===void 0)return this.log("pick with partial when can only be used with apply"),(0,kp.errorFor)("partial when");r.push({pick:u.pick.getExpression(e),when:u.when.getExpression(e)})}let n,i=["CASE"],s="scalar",o="constant";for(let u of r){if(!l0.FT.typeEq(u.when,l0.FT.boolT))return this.log(`when expression must be boolean, not '${l0.FT.inspect(u.when)}`),(0,kp.errorFor)("pick when type");if(n&&!l0.FT.typeEq(n,u.pick,!0)){let l=l0.FT.inspect(u.pick);return this.log(`pick type '${l}', expected '${n.dataType}'`),(0,kp.errorFor)("pick value type")}n=zM(n,u.pick),s=(0,Jc.maxExpressionType)(s,(0,Jc.maxExpressionType)(u.pick.expressionType,u.when.expressionType)),o=(0,Jc.mergeEvalSpaces)(o,u.pick.evalSpace,u.when.evalSpace),i.push(" WHEN ",...u.when.value," THEN ",...u.pick.value)}let a=this.elsePick.getExpression(e);return s=(0,Jc.maxExpressionType)(s,a.expressionType),o=(0,Jc.mergeEvalSpaces)(o,a.evalSpace),n=zM(n,a),l0.FT.typeEq(n,a,!0)?(i.push(" ELSE ",...a.value," END"),{dataType:n.dataType,expressionType:s,value:(0,sAe.compressExpr)(i),evalSpace:o}):(this.elsePick.log(`else type '${l0.FT.inspect(a)}', expected '${n.dataType}'`),(0,kp.errorFor)("pick value type mismatch"))}};GS.Pick=PJ;var kJ=class extends Gst.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="pickWhen",this.has({pick:e})}};GS.PickWhen=kJ});var aAe=v(GM=>{"use strict";Object.defineProperty(GM,"__esModule",{value:!0});GM.Timeframe=void 0;var Qst=Ke(),Vst=mt(),BJ=class extends Vst.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,Qst.isTimestampUnit)(r)?r:"second"}};GM.Timeframe=BJ});var lAe=v(QM=>{"use strict";Object.defineProperty(QM,"__esModule",{value:!0});QM.TopBy=void 0;var Wst=Ke(),uAe=ir(),Yst=mt(),Kst=hs(),qJ=class extends Yst.MalloyElement{constructor(e){super(),this.by=e,this.elementType="topBy",e instanceof uAe.ExpressionDef&&this.has({by:e})}getBy(e){if(this.by instanceof uAe.ExpressionDef){let r=this.by.getExpression(e);return(0,Wst.expressionIsAggregate)(r.expressionType)||this.log("top by expression must be an aggregate"),{by:"expression",e:(0,Kst.compressExpr)(r.value)}}return{by:"name",name:this.by}}};QM.TopBy=qJ});var cAe=v(Bp=>{"use strict";Object.defineProperty(Bp,"__esModule",{value:!0});Bp.ImportStatement=Bp.ImportSelect=Bp.ImportSourceName=void 0;var HJ=mt(),UJ=class extends HJ.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}};Bp.ImportSourceName=UJ;var $J=class extends HJ.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}};Bp.ImportSelect=$J;var jJ=class extends HJ.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.log("Invalid URI in import statement")}}needs(){let e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){let n=e.childRequest(this.fullURL);if(n)return n}}execute(e){let r=this.translator();if(!r)this.log("Cannot import without translation context");else if(this.fullURL){let n=r.root.importZone.getEntry(this.fullURL);if(n.status==="present"){let i=r.getChildExports(this.fullURL);if(this.notEmpty())for(let s of this.list){let o=s.from||s;if(e.getEntry(s.text))s.log(`Cannot redefine '${s.text}'`);else if(i[o.text]){let a={...i[o.text]};s.from&&(a.as=s.text),e.setEntry(s.text,{entry:a,exported:!1})}else o.log(`Cannot find '${o.text}', not imported`)}else for(let[s,o]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(s)?this.log(`Cannot redefine '${s}'`):e.setEntry(s,{entry:o,exported:!1})}else n.status==="error"?this.log(`import failed: '${n.message}'`):this.log(`import failed with status: '${n.status}'`)}}};Bp.ImportStatement=jJ});var GJ=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.ExtendBlock=void 0;var Xst=mt(),Jst=Ii(),zJ=class extends Xst.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Jst.LegalRefinementStage.Single}queryExecute(e){for(let r of this.list)for(let n of r.list)e.inputFS.extendSource(n)}};VM.ExtendBlock=zJ});var fAe=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0});WM.AnonymousQuery=void 0;var Zst=mt(),eot=Wc(),QJ=class extends Zst.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=eot.extendNoteMethod,this.has({queryExpr:e})}execute(e){let r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("Cannot run this object as a query");return}let n={...r.query()},i=this.note||{};n.annotation&&(i.inherits=n.annotation),(i.notes||i.blockNotes||i.inherits)&&(n.annotation=i),e.queryList.push(n)}};WM.AnonymousQuery=QJ});var QS=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0});YM.View=void 0;var tot=mt(),VJ=class extends tot.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}};YM.View=VJ});var xAe=v(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.ViewArrow=void 0;var rot=tl(),not=QS(),WJ=class extends not.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){let r=this.base.pipelineComp(e),n=new rot.StaticSpace(r.outputStruct),i=this.operation.pipelineComp(n);return{pipeline:[...r.pipeline,...i.pipeline],outputStruct:i.outputStruct}}refine(e,r,n){return this.log("A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}};KM.ViewArrow=WJ});var XJ=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0});XM.refine=void 0;var YJ=lc(),KJ=AL();function iot(t,e,r){var n,i;if(e.length!==1)return t.log("Named refinements of multi-stage views are not supported"),e;let s={...e[0]},o=r;if((0,YJ.isRawSegment)(s))t.log("Cannot refine raw query, must add an explicit query stage");else if(s.type==="partial"&&o.type!=="index"&&o.type!=="raw"?s.type=o.type:o.type!==s.type&&t.log(`cannot refine ${s.type} view with ${o.type} view`),o.type!=="index"&&s.type!=="index"&&o.type!=="raw"&&((o.orderBy!==void 0||o.by!==void 0)&&(s.orderBy===void 0&&s.by===void 0?o.orderBy?s.orderBy=o.orderBy:o.by&&(s.by=o.by):t.log("refinement cannot override existing ordering")),o.limit!==void 0&&(s.limit===void 0?s.limit=o.limit:t.log("refinement cannot override existing limit"))),s.filterList=s.filterList!==void 0||o.filterList!==void 0?[...(n=s.filterList)!==null&&n!==void 0?n:[],...(i=o.filterList)!==null&&i!==void 0?i:[]]:void 0,(0,YJ.isQuerySegment)(o)&&(0,YJ.isQuerySegment)(s)){let a=[],u=[],l=new Map(s.queryFields.map(c=>[(0,KJ.nameFromDef)(c),c]));for(let c of o.queryFields)l.has((0,KJ.nameFromDef)(c))?a.push(c):u.push(c);s.queryFields=[...s.queryFields,...u],a.length>0&&t.log(`overlapping fields in refinement: ${a.map(KJ.nameFromDef)}`)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}XM.refine=iot});var dAe=v(JM=>{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});JM.ViewRefine=void 0;var sot=ca(),oot=Km(),aot=XJ(),uot=QS(),JJ=class extends uot.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){let n=this.base.pipelineComp(e),i=this.refinement.refine(e,n.pipeline,r);return{pipeline:i,annotation:n.annotation,outputStruct:i.length>0?(0,oot.getFinalStruct)(this.refinement,e.structDef(),i):sot.ErrorFactory.structDef}}refine(e,r,n){let i=this.pipeline(e,n);return i.length!==1?(this.refinement.log("refinement must have exactly one stage"),r):(0,aot.refine)(this,r,i[0])}getImplicitName(){return this.base.getImplicitName()}};JM.ViewRefine=JJ});var mAe=v(ZM=>{"use strict";Object.defineProperty(ZM,"__esModule",{value:!0});ZM.ReferenceView=void 0;var hAe=Ke(),pAe=ca(),lot=Km(),cot=la(),fot=XJ(),xot=QS(),ZJ=class extends xot.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}){let n=this.reference.getField(e),i=function(){return{inputStruct:pAe.ErrorFactory.structDef,outputStruct:pAe.ErrorFactory.structDef,pipeline:[],error:!0}};if(!n.found)return this.log(`\`${this.reference.refString}\` is not defined`),i();if(!(n.found instanceof cot.SpaceField))throw new Error("Expected space field");let s=n.found.fieldDef();if(s===void 0)throw new Error("Expected field to have definition");if((0,hAe.isAtomicFieldType)(s.type)){let o={type:"reduce",queryFields:[this.reference.refToField]},{dialect:a,queryTimezone:u,structRelationship:l}=e.structDef(),c=this.reference.nameString;return{pipeline:[o],name:c,outputStruct:{type:"struct",dialect:a,queryTimezone:u,name:c,fields:[s],structRelationship:l,structSource:{type:"query_result"}}}}else return(0,hAe.isTurtleDef)(s)?this.reference.list.length>1?(r?this.log("Cannot use view from join as refinement"):this.log("Cannot use view from join"),i()):{pipeline:[...s.pipeline],name:s.name,annotation:s.annotation,outputStruct:(0,lot.getFinalStruct)(this.reference,e.structDef(),s.pipeline)}:(r?this.reference.log(`named refinement \`${this.reference.refString}\` must be a view, found a ${s.type}`):this.reference.log("This operation is not supported"),i())}getRefinementSegment(e){let{pipeline:r,error:n}=this._pipelineComp(e,{forRefinement:!0});if(!n){if(r.length!==1){this.reference.log(`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,n){let i=this.getRefinementSegment(e);return i?(0,fot.refine)(this,r,i):r}getImplicitName(){return this.reference.nameString}};ZM.ReferenceView=ZJ});var tZ=v(eP=>{"use strict";Object.defineProperty(eP,"__esModule",{value:!0});eP.Index=void 0;var dot=mt(),hot=Ii(),eZ=class extends dot.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=hot.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};eP.Index=eZ});var nZ=v(tP=>{"use strict";Object.defineProperty(tP,"__esModule",{value:!0});tP.SampleProperty=void 0;var pot=mt(),gAe=Ii(),rZ=class extends pot.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=gAe.LegalRefinementStage.Tail,this.forceQueryClass=gAe.QueryClass.Index}sampling(){return this.sample}};tP.SampleProperty=rZ});var EAe=v(rP=>{"use strict";Object.defineProperty(rP,"__esModule",{value:!0});rP.IndexFieldSpace=void 0;var yAe=Ke(),iZ=PS(),mot=la(),got=l5(),yot=VK(),Eot=tl(),sZ=class extends got.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(let r of e)r instanceof iZ.FieldReference?super.pushFields(r):r instanceof iZ.WildcardFieldReference?this.addWild(r):r.log("Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.log("index query operations cannot be refined"),{type:"index",indexFields:[]};let r=[];for(let[n,i]of this.entries())if(i instanceof mot.SpaceField){let s=this.expandedWild[n];if(s){r.push({type:"fieldref",path:s});continue}if(i instanceof yot.ReferenceField){let o=i.fieldRef,a=o.getField(this.exprSpace);a.error?o.log(a.error):r.push(o.refToField)}}return{type:"index",indexFields:r}}addRefineFromFields(e){}addWild(e){var r;let n=this.exprSpace,i=[];if(e.joinPath)for(let a of e.joinPath.list){let u=a.refString;i.push(u);let l=n.entry(u);if(l)if(l instanceof Eot.StructSpaceField)n=l.fieldSpace;else{a.log(`Field '${u}' does not contain rows and cannot be expanded with '*'`);return}else{a.log(`No such field as '${u}'`);return}}let s=this.dialectObj(),o=[];for(let[a,u]of n.entries()){if(e.except.has(a))continue;let l=iZ.IndexFieldReference.indexOutputName([...i,a]);if(this.entry(l)){let c=(r=this.expandedWild[l])===null||r===void 0?void 0:r.join(".");e.log(`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{let c=u.typeDesc();(0,yAe.isAtomicFieldType)(c.dataType)&&(0,yAe.expressionIsScalar)(c.expressionType)&&(s===void 0||!s.ignoreInProject(a))&&(o.push({name:l,entry:u}),this.expandedWild[l]=i.concat(a))}}for(let a of o.sort((u,l)=>u.name.localeCompare(l.name)))this.setEntry(a.name,a.entry)}};rP.IndexFieldSpace=sZ});var AAe=v(nP=>{"use strict";Object.defineProperty(nP,"__esModule",{value:!0});nP.IndexBuilder=void 0;var oZ=Ke(),Aot=ca(),Sot=Ym(),vot=tZ(),_ot=kS(),bot=nZ(),Tot=EAe(),aZ=class{constructor(e,r,n,i){this.filters=[],this.type="index",this.resultFS=new Tot.IndexFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof Sot.Filter?this.filters.push(...e.getFilterList(this.inputFS)):e instanceof _ot.Limit?(this.limit&&this.limit.log("Ignored, too many limit: statements"),this.limit=e):e instanceof vot.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.log("Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof bot.SampleProperty?this.sample=e.sampling():e.log("Not legal in an index query operation")}finalize(e){if(e&&!(0,oZ.isIndexSegment)(e)&&!(0,oZ.isPartialSegment)(e))return this.resultFS.log(`Can't refine index with ${e.type}`),Aot.ErrorFactory.indexSegment;let r=this.resultFS.getPipeSegment(e),n=e?.filterList||[];return this.filters.length>0&&!n?r.filterList=this.filters:n&&(r.filterList=[...n,...this.filters]),e?.limit&&(r.limit=e.limit),this.limit&&(r.limit=this.limit.limit),this.indexOn&&(r.weightMeasure=this.indexOn.refString),e&&(0,oZ.isIndexSegment)(e)&&e?.sample&&(r.sample=e.sample),this.sample&&(r.sample=this.sample),r}};nP.IndexBuilder=aZ});var lZ=v(iP=>{"use strict";Object.defineProperty(iP,"__esModule",{value:!0});iP.GroupBy=void 0;var Cot=n0(),SAe=Ii(),uZ=class extends Cot.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=SAe.LegalRefinementStage.Single,this.forceQueryClass=SAe.QueryClass.Grouping}};iP.GroupBy=uZ});var vAe=v(sP=>{"use strict";Object.defineProperty(sP,"__esModule",{value:!0});sP.ProjectFieldSpace=void 0;var cZ=Ke(),Rot=l5(),fZ=class extends Rot.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e.dataType==="turtle"||(0,cZ.expressionIsAggregate)(e.expressionType)?!1:(0,cZ.expressionInvolvesAggregate)(e.expressionType)&&(0,cZ.expressionIsAnalytic)(e.expressionType)?(this.log("Cannot add aggregate analyics to project"),!1):!0}};sP.ProjectFieldSpace=fZ});var hZ=v(VS=>{"use strict";Object.defineProperty(VS,"__esModule",{value:!0});VS.Ordering=VS.OrderBy=void 0;var Oot=Ke(),_Ae=u5(),bAe=mt(),Dot=Ii(),xZ=class extends bAe.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof _Ae.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 _Ae.FieldName&&e.isQueryFieldSpace()){let i=e.outputSpace(),s=this.field.getField(i);s.error&&this.field.log(s.error),(!s.found||!s.isOutputField)&&this.log(`Unknown field ${this.field.refString} in output space`),(0,Oot.expressionIsAnalytic)((r=s.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.log(`Illegal order by of analytic field ${this.field.refString}`)}let n={field:this.modelField};return this.dir&&(n.dir=this.dir),n}};VS.OrderBy=xZ;var dZ=class extends bAe.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Dot.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}};VS.Ordering=dZ});var mZ=v(oP=>{"use strict";Object.defineProperty(oP,"__esModule",{value:!0});oP.Top=void 0;var TAe=Ke(),Not=hs(),Fot=u5(),wot=mt(),Lot=Ii(),pZ=class extends wot.MalloyElement{constructor(e,r){super(),this.limit=e,this.by=r,this.elementType="top",this.queryRefinementStage=Lot.LegalRefinementStage.Tail,this.forceQueryClass=void 0,this.has({by:r})}getBy(e){var r;if(this.by)if(this.by instanceof Fot.FieldName){if(e.isQueryFieldSpace()){let n=e.outputSpace(),i=this.by.getField(n);i.error&&this.by.log(i.error),(!i.found||!i.isOutputField)&&this.by.log(`Unknown field ${this.by.refString} in output space`),(0,TAe.expressionIsAnalytic)((r=i.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.by.log(`Illegal order by of analytic field ${this.by.refString}`)}return{by:"name",name:this.by.refString}}else{let n=this.by.getExpression(e);return(0,TAe.expressionIsAggregate)(n.expressionType)&&this.by.log("top by expression must be an aggregate"),n.evalSpace==="output"&&this.by.log("top by expression must be an output expression"),{by:"expression",e:(0,Not.compressExpr)(n.value)}}}};oP.Top=pZ});var uP=v(WS=>{"use strict";Object.defineProperty(WS,"__esModule",{value:!0});WS.ReduceBuilder=WS.QuerySegmentBuilder=void 0;var CAe=Ke(),Iot=ca(),Mot=Ym(),Pot=kS(),RAe=hZ(),OAe=mZ(),kot=l5(),Bot=n0(),aP=class{constructor(){this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}if(e instanceof Bot.DefinitionList)this.resultFS.pushFields(...e.list);else if(e instanceof Mot.Filter){let r=e.havingClause?this.resultFS:this.inputFS;this.filters.push(...e.getFilterList(r))}else e instanceof OAe.Top?(this.limit?e.log("Query operation already limited"):this.limit=e.limit,e.by&&(this.order?e.log("Query operation is already sorted"):this.order=e)):e instanceof Pot.Limit?this.limit?e.log("Query operation already limited"):this.limit=e.limit:e instanceof RAe.Ordering&&(this.order?e.log("Query operation already sorted"):this.order=e)}refineFrom(e,r){if(e&&e.type!=="index"&&e.type!=="raw"&&(this.order||(e.orderBy?r.orderBy=e.orderBy:e.by&&(r.by=e.by)),!this.limit&&e.limit&&(r.limit=e.limit)),this.limit&&(r.limit=this.limit),this.order instanceof OAe.Top){let i=this.order.getBy(this.inputFS);i&&(r.by=i)}this.order instanceof RAe.Ordering&&(r.orderBy=this.order.getOrderBy(this.inputFS));let n=e?.filterList||[];this.filters.length>0&&!n?r.filterList=this.filters:n&&(r.filterList=[...n,...this.filters])}};WS.QuerySegmentBuilder=aP;var gZ=class extends aP{constructor(e,r,n,i){super(),this.type="grouping",this.resultFS=new kot.ReduceFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,CAe.isReduceSegment)(e)||(0,CAe.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine reduce with ${e.type}`),Iot.ErrorFactory.reduceSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};WS.ReduceBuilder=gZ});var NAe=v(lP=>{"use strict";Object.defineProperty(lP,"__esModule",{value:!0});lP.ProjectBuilder=void 0;var DAe=Ke(),qot=ca(),Uot=lZ(),$ot=vAe(),jot=uP(),yZ=class extends jot.QuerySegmentBuilder{constructor(e,r,n,i){super(),this.type="project",this.resultFS=new $ot.ProjectFieldSpace(e,r,n,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Uot.GroupBy?e.log("Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,DAe.isProjectSegment)(e)||(0,DAe.isPartialSegment)(e))r=e;else return this.resultFS.log(`Can't refine select with ${e.type}`),qot.ErrorFactory.projectSegment;let n=this.resultFS.getQuerySegment(r);return this.refineFrom(r,n),n}};lP.ProjectBuilder=yZ});var FAe=v(cP=>{"use strict";Object.defineProperty(cP,"__esModule",{value:!0});cP.PartialBuilder=void 0;var Hot=lc(),zot=uP(),EZ=class extends zot.ReduceBuilder{finalize(e){let r=super.finalize(e);if((0,Hot.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}};cP.PartialBuilder=EZ});var SZ=v(fP=>{"use strict";Object.defineProperty(fP,"__esModule",{value:!0});fP.QOpDesc=void 0;var Got=AAe(),Qot=NAe(),Vot=uP(),Wot=mt(),Yot=Km(),Kot=tl(),cg=Ii(),Xot=FAe(),AZ=class extends Wot.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,n=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=cg.QueryClass.Grouping:this.refineThis.type==="project"?r=cg.QueryClass.Project:this.refineThis.type==="index"&&(r=cg.QueryClass.Index));for(let i of this.list)i.forceQueryClass&&(r?r!==i.forceQueryClass&&i.log(`Not legal in ${r} query`):r=i.forceQueryClass),n||(n=(e=i.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&n&&(this.log("Can't determine view type (`group_by` / `aggregate` / `nest`, `project`, `index`)"),r=cg.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,n){switch(this.computeType()){case cg.QueryClass.Grouping:return new Vot.ReduceBuilder(e,this.refineThis,r,n);case cg.QueryClass.Project:return new Qot.ProjectBuilder(e,this.refineThis,r,n);case cg.QueryClass.Index:return new Got.IndexBuilder(e,this.refineThis,r,n);case void 0:return new Xot.PartialBuilder(e,this.refineThis,r,n)}}getOp(e,r){let n=this.getBuilder(e,r,this);for(let s of this.list)n.execute(s);let i=n.finalize(this.refineThis);return{segment:i,outputSpace:()=>new Kot.StaticSpace((0,Yot.opOutputStruct)(this,e.structDef(),i))}}};fP.QOpDesc=AZ});var LAe=v(xP=>{"use strict";Object.defineProperty(xP,"__esModule",{value:!0});xP.QOpDescView=void 0;var Jot=Ke(),Zot=tl(),wAe=SZ(),eat=Km(),vZ=Ii(),tat=QS(),_Z=class extends tat.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){let n=this.operation.getOp(e,r);return{pipeline:[n.segment],outputStruct:n.outputSpace().structDef()}}getOp(e,r,n,i){return(0,Jot.isRawSegment)(i)?(this.log("A raw query cannot be refined"),i):(n.refineFrom(i),n.getOp(e,r).segment)}refine(e,r,n){let i=[...r];if(i.length===0)return i;if(i.length===1)return this.operation.refineFrom(i[0]),[this.getOp(e,n,this.operation,i[0])];let s=new wAe.QOpDesc([]),o=new wAe.QOpDesc([]);for(let a of this.operation.list)switch(a.queryRefinementStage){case vZ.LegalRefinementStage.Head:s.push(a);break;case vZ.LegalRefinementStage.Single:a.log("Illegal in refinement of a query with more than one stage");break;case vZ.LegalRefinementStage.Tail:o.push(a);break;default:a.log("Illegal query refinement")}if(s.notEmpty()&&(this.has({headRefinements:s}),i[0]=this.getOp(e,void 0,s,i[0])),o.notEmpty()){let a=i.length-1;this.has({tailRefinements:o});let u=(0,eat.getFinalStruct)(this,e.structDef(),i.slice(-1));i[a]=this.getOp(new Zot.StaticSpace(u),void 0,o,i[a])}return i}getImplicitName(){}};xP.QOpDescView=_Z});var FZ=v(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.FieldDefinitionValue=An.DefSpace=An.DimensionFieldDeclaration=An.MeasureFieldDeclaration=An.DeclareFieldDeclaration=An.ProjectFieldDeclaration=An.GroupByFieldDeclaration=An.AggregateFieldDeclaration=An.CalculateFieldDeclaration=An.AtomicFieldDeclaration=void 0;var rat=Ke(),nat=hs(),iat=pn(),sat=yI(),oat=mt(),fg=WK(),aat=Wc(),uat=la(),Zc=class extends oat.MalloyElement{constructor(e,r,n){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=n,this.isNoteableObj=!0,this.extendNote=aat.extendNoteMethod}fieldDef(e,r){return this.queryFieldDef(new S5(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let n;function i(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{let u=this.executesInOutputSpace()?i():e;n=this.expr.getExpression(u)}catch(u){return this.log(`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}let s=(0,nat.compressExpr)(n.value),o=n.dataType;if(o==="null"&&(this.expr.log('null value defaults to type number, use "null::TYPE" to specify correct type',"warn"),o="number"),(0,rat.isAtomicFieldType)(o)&&o!=="error"){let u={name:r,type:o,location:this.location};return s.length>0&&(u.e=s),n.expressionType&&(u.expressionType=n.expressionType),this.typecheckExprValue(n),this.exprSrc&&(u.code=this.exprSrc),(0,sat.isGranularResult)(n)&&u.type==="timestamp"&&(u.timeframe=n.timeframe),this.note&&(u.annotation=this.note),u}if(!(e instanceof S5&&e.foundCircle)&&n.dataType!=="error"){let u=iat.FT.inspect(n);this.log(`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new dP(e,this))}};An.AtomicFieldDeclaration=Zc;var bZ=class extends Zc{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}};An.CalculateFieldDeclaration=bZ;var TZ=class extends Zc{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckAggregate)(e,this)}};An.AggregateFieldDeclaration=TZ;var CZ=class extends Zc{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckGroupBy)(e,this)}};An.GroupByFieldDeclaration=CZ;var RZ=class extends Zc{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckProject)(e,this)}};An.ProjectFieldDeclaration=RZ;var OZ=class extends Zc{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckDeclare)(e,this)}};An.DeclareFieldDeclaration=OZ;var DZ=class extends Zc{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckMeasure)(e,this)}};An.MeasureFieldDeclaration=DZ;var NZ=class extends Zc{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,fg.typecheckDimension)(e,this)}};An.DimensionFieldDeclaration=NZ;var S5=class{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:`Circular reference to '${this.circular.defineName}' in definition`,found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}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")}};An.DefSpace=S5;var dP=class extends uat.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){return this.haveFieldDef||(this.haveFieldDef=this.exprDef.fieldDef(this.space,this.name)),this.haveFieldDef}getQueryFieldDef(e){if(!this.qfd){let r=this.exprDef.queryFieldDef(e,this.name);this.qfd=r}return this.qfd}typeDesc(){let e=this.qfd||this.fieldDef();return this.fieldTypeFromFieldDef(e)}};An.FieldDefinitionValue=dP});var MAe=v(hP=>{"use strict";Object.defineProperty(hP,"__esModule",{value:!0});hP.Aggregate=void 0;var lat=n0(),IAe=Ii(),wZ=class extends lat.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=IAe.LegalRefinementStage.Single,this.forceQueryClass=IAe.QueryClass.Grouping}};hP.Aggregate=wZ});var PAe=v(pP=>{"use strict";Object.defineProperty(pP,"__esModule",{value:!0});pP.Calculate=void 0;var cat=n0(),fat=Ii(),LZ=class extends cat.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=fat.LegalRefinementStage.Single}};pP.Calculate=LZ});var MZ=v(mP=>{"use strict";Object.defineProperty(mP,"__esModule",{value:!0});mP.Dimensions=void 0;var xat=bS(),IZ=class extends xat.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}};mP.Dimensions=IZ});var kZ=v(gP=>{"use strict";Object.defineProperty(gP,"__esModule",{value:!0});gP.Measures=void 0;var dat=bS(),PZ=class extends dat.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}};gP.Measures=PZ});var BAe=v(yP=>{"use strict";Object.defineProperty(yP,"__esModule",{value:!0});yP.Nests=void 0;var hat=n0(),kAe=Ii(),BZ=class extends hat.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=kAe.LegalRefinementStage.Single,this.forceQueryClass=kAe.QueryClass.Grouping}};yP.Nests=BZ});var UAe=v(EP=>{"use strict";Object.defineProperty(EP,"__esModule",{value:!0});EP.ProjectStatement=void 0;var pat=n0(),qAe=Ii(),qZ=class extends pat.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=qAe.QueryClass.Project,this.queryRefinementStage=qAe.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}};EP.ProjectStatement=qZ});var jAe=v(AP=>{"use strict";Object.defineProperty(AP,"__esModule",{value:!0});AP.FromSQLSource=void 0;var $Ae=Ke(),mat=n5(),UZ=class extends mat.NamedSource{constructor(){super(...arguments),this.elementType="fromSQLSource"}structRef(){return this.structDef()}modelStruct(){let e=this.modelEntry(this.ref),r=e?.entry;if(!r){this.log(`Undefined from_sql source '${this.refName}'`);return}if(r.type==="function"){this.log(`Cannot construct a source from a function '${this.refName}'`);return}else if(r.type==="query"){this.log(`Cannot use 'from_sql()' with a query '${this.refName}'`);return}else if(r.type==="connection"){this.log(`Cannot use 'from_sql()' with a connection '${this.refName}'`);return}else if((0,$Ae.isSQLBlockStruct)(r)&&r.declaredSQLBlock){let{declaredSQLBlock:n,...i}=r;return i}else if(!(0,$Ae.isSQLBlockStruct)(r)){this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`);return}this.log(`Cannot use 'from_sql()' to reference '${this.refName}'`)}};AP.FromSQLSource=UZ});var zZ=v(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});qp.findReferences=qp.deprecatedParseTableURI=qp.constructTableKey=void 0;var gat=_p(),jZ=WC();function $Z(t){let e=(0,jZ.getStringIfShort)(t);if(e)return e;let r=[],n=t.string().sqlString();if(n){for(let i of(0,jZ.getStringParts)(n))typeof i=="string"&&r.push(i);return r.join("")}return""}var HZ=class{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,n){let i=HAe(e,r);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:r,firstReference:n})}enterTableMethod(e){let r=(0,jZ.getId)(e.connectionId()),n=$Z(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(r,n,i)}enterTableFunction(e){let r=$Z(e.tableURI()),{connectionName:n,tablePath:i}=zAe(r),s=this.trans.rangeFromContext(e);this.registerTableReference(n,i,s)}enterImportURL(e){let r=$Z(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}};function HAe(t,e){return t===void 0?e:`${t}:${e}`}qp.constructTableKey=HAe;function zAe(t){let e=t.match(/^([^:]*):(.*)$/);if(e){let[,r,n]=e;return{connectionName:r,tablePath:n}}else return{tablePath:t}}qp.deprecatedParseTableURI=zAe;function yat(t,e,r){let n=new HZ(t,e),i=n;return gat.ParseTreeWalker.DEFAULT.walk(i,r),{tables:n.needTables,urls:n.needImports}}qp.findReferences=yat});var VAe=v(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});Up.TableFunctionSource=Up.TableMethodSource=Up.TableSource=void 0;var QAe=zZ(),Eat=Px(),GAe=ca(),v5=class extends Eat.Source{structDef(){var e,r;let n=this.getTableInfo();if(n===void 0)return GAe.ErrorFactory.structDef;let{tablePath:i,connectionName:s}=n,o=(0,QAe.constructTableKey)(s,i),a=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(o),u=`Schema read failure for table '${i}' for connection '${s}'`;if(a){if(a.status==="present"){a.value.location=this.location,a.value.fields.forEach(c=>{c.location=this.location});let l={...a.value,fields:a.value.fields.map(c=>({...c,location:this.location})),location:this.location};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(l),l}a.status==="error"&&(u=a.message)}return this.log(u),GAe.ErrorFactory.structDef}};Up.TableSource=v5;var GZ=class extends v5{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;let r=this.modelEntry(this.connectionName),n=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(n,{entry:{type:"connection",name:n},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.log(`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}};Up.TableMethodSource=GZ;var QZ=class extends v5{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,QAe.deprecatedParseTableURI)(this.tableURI)}};Up.TableFunctionSource=QZ});var WAe=v(SP=>{"use strict";Object.defineProperty(SP,"__esModule",{value:!0});SP.SQLStatement=void 0;var Aat=AK(),Sat=mt(),VZ=class extends Sat.MalloyElement{constructor(e){super(),this.select=e,this.elementType="sqlStatement",this.has({select:e})}sqlBlock(){return this.requestBlock||(this.requestBlock=(0,Aat.makeSQLBlock)(this.select.sqlPhrases(),this.connection)),this.requestBlock}lookupCompiledSQL(e){var r;let n=(r=this.translator())===null||r===void 0?void 0:r.root.sqlQueryZone;if(n)return n.reference(e.name,this.location),n.getEntry(e.name)}needs(e){let r=this.sqlBlock(),n=this.lookupCompiledSQL(r);if(n?.status==="reference")return{compileSQL:r,partialModel:this.select.containsQueries?e.modelDef():void 0}}execute(e){let r=this.sqlBlock(),n=this.lookupCompiledSQL(r);if(!n){this.log("Cant't look up schema for sql block");return}if(n.status==="error"){let i=n.message.split(/\r?\n/);this.select.log("Invalid SQL, "+i.join(`
|
|
682
|
+
`));return}if(n.status==="present"){let i=this.select.location,s={...n.value,fields:n.value.fields.map(o=>({...o,location:i})),location:this.location};this.is&&!e.defineSQL(s,this.is)&&this.log(`'${this.is}' already defined`);return}}};SP.SQLStatement=VZ});var KAe=v(vP=>{"use strict";Object.defineProperty(vP,"__esModule",{value:!0});vP.SQLString=void 0;var vat=mt(),YAe=Dp(),WZ=class extends vat.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(_at)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof YAe.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.log("This element is not legal inside an SQL string")}sqlPhrases(){let e=[];for(let r of this.elements)if(typeof r=="string")e.push({sql:r});else{let n=r.getQuery();n?e.push(n.query()):r.sqLog("Cannot expand into a query")}return e}};vP.SQLString=WZ;function _at(t){return t instanceof YAe.SourceQueryElement}});var XAe=v(_P=>{"use strict";Object.defineProperty(_P,"__esModule",{value:!0});_P.SourceDesc=void 0;var bat=mt(),YZ=class extends bat.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}};_P.SourceDesc=YZ});var JAe=v(bP=>{"use strict";Object.defineProperty(bP,"__esModule",{value:!0});bP.isSourceProperty=void 0;var Tat=Ym(),Cat=CS(),Rat=bS(),Oat=PL(),Dat=QL(),Nat=BL(),Fat=UL(),wat=jL(),Lat=zL();function Iat(t){return t instanceof Tat.Filter||t instanceof Cat.Joins||t instanceof Rat.DeclareFields||t instanceof Oat.FieldListEdit||t instanceof Dat.Renames||t instanceof Nat.PrimaryKey||t instanceof Lat.ObjectAnnotation||t instanceof Fat.Views||t instanceof wat.TimezoneStatement}bP.isSourceProperty=Iat});var eSe=v(TP=>{"use strict";Object.defineProperty(TP,"__esModule",{value:!0});TP.isFieldCollectionMember=void 0;var Mat=FZ(),ZAe=PS();function Pat(t){return t instanceof ZAe.FieldReference||t instanceof ZAe.WildcardFieldReference||t instanceof Mat.AtomicFieldDeclaration}TP.isFieldCollectionMember=Pat});var tSe=v(CP=>{"use strict";Object.defineProperty(CP,"__esModule",{value:!0});CP.isQueryElement=void 0;var kat=JL(),Bat=tI(),qat=hK(),Uat=EK();function $at(t){return t instanceof kat.QueryArrow||t instanceof Bat.QueryRefine||t instanceof qat.QueryReference||t instanceof Uat.QueryRaw}CP.isQueryElement=$at});var nSe=v(rSe=>{"use strict";Object.defineProperty(rSe,"__esModule",{value:!0})});var iSe=v(RP=>{"use strict";Object.defineProperty(RP,"__esModule",{value:!0});RP.isQueryProperty=void 0;function jat(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}RP.isQueryProperty=jat});var sSe=v(OP=>{"use strict";Object.defineProperty(OP,"__esModule",{value:!0});OP.isQueryExtendProperty=void 0;var Hat=MZ(),zat=CS(),Gat=kZ();function Qat(t){return t instanceof Hat.Dimensions||t instanceof Gat.Measures||t instanceof zat.Joins}OP.isQueryExtendProperty=Qat});var oSe=v(DP=>{"use strict";Object.defineProperty(DP,"__esModule",{value:!0});DP.isFieldPropStatement=void 0;var Vat=PI(),Wat=Ym(),Yat=kS(),Kat=XI();function Xat(t){return t instanceof Wat.Filter||t instanceof Yat.Limit||t instanceof Kat.PartitionBy||t instanceof Vat.FunctionOrdering}DP.isFieldPropStatement=Xat});var NP=v(ne=>{"use strict";var Jat=ne&&ne.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),ie=ne&&ne.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Jat(e,t,r)};Object.defineProperty(ne,"__esModule",{value:!0});ie(gY(),ne);ie(u3e(),ne);ie(c3e(),ne);ie(Px(),ne);ie(rK(),ne);ie(Dp(),ne);ie(_3e(),ne);ie(D3e(),ne);ie(N3e(),ne);ie(mK(),ne);ie(F3e(),ne);ie(PL(),ne);ie(BL(),ne);ie(QL(),ne);ie(UL(),ne);ie(jL(),ne);ie(z3e(),ne);ie(wI(),ne);ie(G3e(),ne);ie(PI(),ne);ie(V3e(),ne);ie(Zm(),ne);ie(Z3e(),ne);ie(jI(),ne);ie(eye(),ne);ie(tye(),ne);ie(nye(),ne);ie(PK(),ne);ie(iye(),ne);ie(sye(),ne);ie(aye(),ne);ie(bX(),ne);ie(IK(),ne);ie(MI(),ne);ie(lye(),ne);ie(cye(),ne);ie(fye(),ne);ie(dye(),ne);ie(hye(),ne);ie(mye(),ne);ie(gye(),ne);ie(yye(),ne);ie(Eye(),ne);ie(Aye(),ne);ie(Sye(),ne);ie(vye(),ne);ie(_ye(),ne);ie(bye(),ne);ie(Rye(),ne);ie(Fye(),ne);ie(nAe(),ne);ie(iAe(),ne);ie(XI(),ne);ie(oAe(),ne);ie(IS(),ne);ie(aAe(),ne);ie(lAe(),ne);ie(wX(),ne);ie(hs(),ne);ie(cAe(),ne);ie(GJ(),ne);ie(AY(),ne);ie(fAe(),ne);ie(tI(),ne);ie(JL(),ne);ie(QS(),ne);ie(xAe(),ne);ie(dAe(),ne);ie(mAe(),ne);ie(LAe(),ne);ie(FZ(),ne);ie(PS(),ne);ie(MAe(),ne);ie(PAe(),ne);ie(bS(),ne);ie(MZ(),ne);ie(GJ(),ne);ie(Ym(),ne);ie(lZ(),ne);ie(tZ(),ne);ie(CS(),ne);ie(pY(),ne);ie(kS(),ne);ie(kZ(),ne);ie(gY(),ne);ie(BAe(),ne);ie(hZ(),ne);ie(UAe(),ne);ie(SZ(),ne);ie(nZ(),ne);ie(mZ(),ne);ie(n5(),ne);ie(r5(),ne);ie(jAe(),ne);ie(vK(),ne);ie(VAe(),ne);ie(WAe(),ne);ie(KAe(),ne);ie(zL(),ne);ie(pI(),ne);ie(XAe(),ne);ie(JAe(),ne);ie(ir(),ne);ie(eSe(),ne);ie(u5(),ne);ie(mt(),ne);ie(tSe(),ne);ie(nSe(),ne);ie(iSe(),ne);ie(sSe(),ne);ie(oSe(),ne)});var uSe=v(ef=>{"use strict";var Zat=ef&&ef.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),eut=ef&&ef.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tut=ef&&ef.__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)&&Zat(e,t,r);return eut(e,t),e};Object.defineProperty(ef,"__esModule",{value:!0});ef.MalloyToAST=void 0;var aSe=E8(),rut=eY(),M=tut(NP()),nut=Is(),iut=NP(),zn=WC(),KZ=Ke(),sut=Wm(),FP=class extends M.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}},_5=class extends M.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}},out=["##! m4warnings=error"],XZ=class extends rut.AbstractParseTreeVisitor{constructor(e,r,n){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=n;for(let i of out){let s=sut.Tag.fromTagline(i,this.compilerFlags);this.compilerFlags=s.tag}}internalError(e,r){let n=`Internal Translator Error: ${r}`;return this.contextError(e,n),new Error(n)}astError(e,r,n="error"){this.msgLog.log({message:r,at:e.location,severity:n})}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}contextError(e,r,n="error"){this.msgLog.log({message:r,at:this.getLocation(e),severity:n})}inExperiment(e,r){let n=this.compilerFlags.tag("experimental");return n&&(n.bare()||n.has(e))?!0:(this.contextError(r,`Experimental flag '${e}' required to enable this feature`),!1)}m4Severity(){let e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,r){let n=this.m4Severity();n&&this.contextError(e,r,n)}only(e,r,n){let i=[];for(let s of e){let o=r(s);o?i.push(o):s instanceof _5||this.astError(s,`Parser enountered unexpected statement type '${s.elementType}' when it needed '${n}'`)}return i}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new M.FieldName((0,zn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new M.ModelEntryReference((0,zn.getId)(e)),e.id())}defaultResult(){return new M.Unimplemented}astAt(e,r){return e.location={url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(r)},e}getSourceCode(e){let r=e.start.startIndex,n=e.stop||e.start,i=new nut.Interval(r,n.stopIndex);return this.parseInfo.sourceStream.getText(i)}getFilterElement(e){let r=this.getFieldExpr(e),n=new M.FilterElement(r,this.getSourceCode(e));return this.astAt(n,e)}getFieldDefs(e,r){return e.map(n=>this.getFieldDef(n,r))}getFieldExpr(e){let r=this.visit(e);if(r instanceof M.ExpressionDef)return this.astAt(r,e);throw this.internalError(e,`expression node unknown type '${r.elementType}'`)}getFilterShortcut(e){let r=this.getFilterElement(e.fieldExpr());return this.m4advisory(e,"Filter shortcut `{? condition }` is deprecated; use `{ where: condition } instead"),new M.Filter([r])}getPlainString(e){let r=(0,zn.getStringIfShort)(e);if(r)return r;let n=[],i=e.string().sqlString();if(i){for(let s of(0,zn.getStringParts)(i))s instanceof aSe.ParserRuleContext?this.contextError(s,"%{ query } illegal in this string"):n.push(s);return(0,zn.unIndent)(n),n.join("")}return""}makeSqlString(e,r){for(let n of e.sqlInterpolation())n.CLOSE_CODE()&&this.m4advisory(n,"Use %{ ... } instead of %{ ... }%");for(let n of(0,zn.getStringParts)(e))n instanceof aSe.ParserRuleContext?r.push(this.visit(n)):r.push(n);r.complete(),this.astAt(r,e)}parseTime(e,r){let n=r(e.text);return n||(this.contextError(e,"Time data parse error"),n=new M.LiteralTimestamp({text:e.text})),this.astAt(n,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){let r=this.only(e.malloyStatement().map(n=>this.visit(n)),n=>M.isDocStatementOrDocStatementList(n)&&n,"statement");return new M.Document(r)}visitDefineSourceStatement(e){let n=e.sourcePropertyList().sourceDefinition().map(o=>this.visitSourceDefinition(o)),i=this.getNotes(e.tags()),s=new M.DefineSourceList(n);return s.extendNote({blockNotes:i}),s}visitSourceDefinition(e){let r=this.visit(e.sqExplore()),n=new M.DefineSource((0,zn.getId)(e.sourceNameDef()),r instanceof M.SourceQueryElement?r:void 0,!0,[]),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return n.extendNote({notes:i}),this.astAt(n,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){let r=e.filterShortcut(),n=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>M.isSourceProperty(s)&&s,"source property"),i=new M.SourceDesc(n);return r&&i.push(this.getFilterShortcut(r)),i}visitTableFunction(e){let r=this.getPlainString(e.tableURI()),n=this.astAt(new M.TableFunctionSource(r),e);return this.m4advisory(e,"`table('connection_name:table_path')` is deprecated; use `connection_name.table('table_path')`"),n}visitTableMethod(e){let r=e.connectionId(),n=this.astAt(this.getModelEntryName(r),r),i=this.getPlainString(e.tablePath());return this.astAt(new M.TableMethodSource(n,i),e)}getLegacySQLSouce(e){let r=this.getModelEntryName(e);return this.astAt(new M.FromSQLSource(r),e)}visitSqlSource(e){let r=e.connectionId(),n=this.astAt(this.getModelEntryName(r),r),i=new M.SQLString,s=e.sqlString();s&&this.makeSqlString(s,i);let o=e.shortString();o&&i.push((0,zn.getShortString)(o));let a=new M.SQLSource(n,i);return this.astAt(a,e)}visitDefJoinMany(e){let r=[];for(let i of e.joinList().joinDef()){let s=this.visit(i);s instanceof M.Join&&(r.push(s),s instanceof M.ExpressionJoin?(s.joinType="many",s.joinOn===void 0&&this.contextError(e,"join_many: requires ON expression")):s instanceof M.KeyJoin&&this.contextError(e,"Foreign key join not legal in join_many:"))}let n=new M.Joins(r);return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitDefJoinOne(e){let r=this.getJoinList(e.joinList()),n=[];for(let s of r)s instanceof M.Join&&(n.push(s),s instanceof M.ExpressionJoin&&(s.joinType="one"));let i=new M.Joins(n);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}visitDefJoinCross(e){let r=this.getJoinList(e.joinList()),n=[];for(let s of r)s instanceof M.Join&&(n.push(s),s instanceof M.ExpressionJoin?s.joinType="cross":s.log("Foreign key join not legal in join_cross:"));let i=new M.Joins(n);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}getJoinList(e){return e.joinDef().map(r=>this.visit(r))}getJoinSource(e,r){if(r){let n=this.getSqExpr(r.sqExpr()),i=this.getNotes(r._before_is).concat(this.getNotes(r._after_is));return{joinFrom:n,notes:i}}return{joinFrom:new M.SQReference(e),notes:[]}}visitQueryJoinStatement(e){let r=this.astAt(this.visit(e.joinStatement()),e);return this.m4advisory(e,"Joins in queries are deprecated, move into an `extend:` block."),r}visitJoinOn(e){var r;let n=this.getModelEntryName(e.joinNameDef()),{joinFrom:i,notes:s}=this.getJoinSource(n,e.isExplore()),o=new M.ExpressionJoin(n,i),a=e.joinExpression(),u=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,KZ.isMatrixOperation)(u)?o.matrixOperation=u:this.contextError(e,"Internal Error: Unknown matrixOperation"),a&&(o.joinOn=this.getFieldExpr(a)),o.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(o,e)}visitJoinWith(e){let r=this.getModelEntryName(e.joinNameDef()),{joinFrom:n,notes:i}=this.getJoinSource(r,e.isExplore()),s=this.getFieldExpr(e.fieldExpr()),o=new M.KeyJoin(r,n,s);return o.extendNote({notes:this.getNotes(e).concat(i)}),this.astAt(o,e)}getFieldDef(e,r){let n=e.fieldExpr(),i=(0,zn.getId)(e.fieldNameDef()),s=this.getFieldExpr(n),o=new r(s,i,this.getSourceCode(n)),a=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return o.extendNote({notes:a}),this.astAt(o,e)}visitDefDimensions(e){let r=this.getFieldDefs(e.defList().fieldDef(),M.DimensionFieldDeclaration),n=new M.Dimensions(r);return n.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(n,e)}visitDefMeasures(e){let r=this.getFieldDefs(e.defList().fieldDef(),M.MeasureFieldDeclaration),n=new M.Measures(r);return n.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(n,e)}visitQueryExtend(e){let r=[],n=e.queryExtendStatementList().queryExtendStatement().map(s=>this.visit(s));for(let s of n)if(M.isQueryExtendProperty(s))r.push(s);else throw this.internalError(e,`Query extend matched, but ${s.elementType} found`);let i=new M.ExtendBlock(r);return this.astAt(i,e)}visitDeclareStatement(e){let r=this.getFieldDefs(e.defList().fieldDef(),M.DeclareFieldDeclaration),n=new M.DeclareFields(r),i=this.astAt(n,e);return this.m4advisory(e,"`declare:` is deprecated; use `dimension:` or `measure:` inside a source or `extend:` block"),i}visitExploreRenameDef(e){let r=e.fieldName(0),n=e.fieldName(1),i=new M.RenameField((0,zn.getId)(r),this.getFieldName(n));return this.astAt(i,e)}visitDefExploreRename(e){let n=e.renameList().exploreRenameDef().map(s=>this.visitExploreRenameDef(s)),i=new M.Renames(n);return this.astAt(i,e)}visitFilterClauseList(e){return new M.Filter(e.fieldExpr().map(r=>this.getFilterElement(r)))}visitWhereStatement(e){let r=this.visitFilterClauseList(e.filterClauseList());return r.having=!1,this.astAt(r,e)}visitHavingStatement(e){let r=this.visitFilterClauseList(e.filterClauseList());return r.having=!0,this.astAt(r,e)}visitSubQueryDefList(e){let r=e.exploreQueryDef().map(n=>this.visitExploreQueryDef(n));return new M.Views(r)}visitDefExploreQuery(e){let r=this.visitSubQueryDefList(e.subQueryDefList()),n=this.getNotes(e.tags());return r.extendNote({blockNotes:n}),e.QUERY()&&this.m4advisory(e,"Use view: inside of a source instead of query:"),r}visitDefExplorePrimaryKey(e){let r=new M.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}visitFieldNameList(e){let r=e.fieldName().map(n=>new M.AcceptExceptFieldReference([this.getFieldName(n)]));return new M.FieldReferences(r)}visitDefExploreEditField(e){let r=e.ACCEPT()?"accept":"except";return new M.FieldListEdit(r,this.visitFieldNameList(e.fieldNameList()))}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){let r=this.getPlainString(e),n=this.astAt(new M.TimezoneStatement(r),e.string());return n.isValid||this.astError(n,`Invalid timezone: ${n.tz}`),this.astAt(n,e)}visitQueryProperties(e){let r=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>M.isQueryProperty(i)&&i,"query statement"),n=e.filterShortcut();return n&&r.push(this.getFilterShortcut(n)),new M.QOpDesc(r)}getFieldPath(e,r){let n=e.fieldName().map(i=>this.getFieldName(i));return this.astAt(new r(n),e)}getQueryFieldDef(e,r){let n=this.getFieldDef(e,r);return this.astAt(n,e)}getQueryFieldEntry(e,r,n){let i=e.taggedRef();if(i)return this.getTaggedRef(i,r,n);let s=e.fieldDef();if(s)return this.getQueryFieldDef(s,r);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,r,n){return this.only(e.queryFieldEntry().map(i=>this.getQueryFieldEntry(i,r,n)),i=>i instanceof M.FieldReference||i instanceof M.AtomicFieldDeclaration?i:!1,"view field")}visitAggregateStatement(e){let r=new M.Aggregate(this.getQueryItems(e.queryFieldList(),M.AggregateFieldDeclaration,M.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){let r=new M.GroupBy(this.getQueryItems(e.queryFieldList(),M.GroupByFieldDeclaration,M.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){let r=new M.Calculate(this.getQueryItems(e.queryFieldList(),M.CalculateFieldDeclaration,M.CalculateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}getTaggedRef(e,r,n){let i=e.refExpr();if(i){let o=this.getFieldPath(e.fieldPath(),M.ExpressionFieldReference),a,u=i.timeframe();u&&(a=new M.ExprGranularTime(new M.ExprIdReference(o),this.visitTimeframe(u).text,!0));let l=i.aggregate();if(l){let f=l.text.toLowerCase();if(f==="sum")a=new M.ExprSum(void 0,o);else return this.contextError(l,`\`${f}\` is not legal in a reference-only aggregation`),o}let c=new r(a,o.outputName);return c.extendNote({notes:this.getNotes(e.tags())}),c}let s=this.getFieldPath(e.fieldPath(),n);return s.extendNote({notes:this.getNotes(e.tags())}),s}getFieldCollectionMember(e,r,n){let i=e.fieldDef();if(i)return this.getFieldDef(i,r);let s=e.taggedRef();if(s)return this.getTaggedRef(s,r,n);let o=e.collectionWildCard();if(o)return this.visitCollectionWildCard(o);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){let r=e.collectionMember().map(n=>this.getFieldCollectionMember(n,M.ProjectFieldDeclaration,M.ProjectFieldReference));return this.astAt(new M.ProjectStatement(r),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project: keyword is deprecated, use select:");let r=this.visitFieldCollection(e.fieldCollection());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCollectionWildCard(e){var r;let n=e.fieldPath(),i=n?this.getFieldPath(n,M.ProjectFieldReference):void 0,s=this.astAt(new M.WildcardFieldReference(i),e),o=((r=e.starQualified())===null||r===void 0?void 0:r.fieldNameList())||[];for(let a of o)for(let u of a.fieldName())s.except.add((0,zn.getId)(u));return s}visitIndexFields(e){let r=e.indexElement().map(n=>{let i=n.fieldPath();if(!i)return this.astAt(new M.WildcardFieldReference(void 0),e);let s=this.getFieldPath(i,M.IndexFieldReference);return n.STAR()?this.astAt(new M.WildcardFieldReference(s),e):this.astAt(s,e)});return new M.FieldReferences(r)}visitIndexStatement(e){let r=this.visitIndexFields(e.indexFields()),n=new M.Index(r),i=e.fieldName();return i&&n.useWeight(this.getFieldName(i)),this.astAt(n,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new M.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){let r=e.ASC()?"asc":e.DESC()?"desc":void 0,n=e.fieldExpr(),i=n?this.getFieldExpr(n):void 0;return this.astAt(new M.FunctionOrderBy(i,r),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){let r=e.aggregateOrderBySpec().map(n=>this.visitAggregateOrderBySpec(n));return this.astAt(new M.FunctionOrdering(r),e)}visitOrderBySpec(e){let r=e.ASC()?"asc":e.DESC()?"desc":void 0,n=e.INTEGER_LITERAL();if(n)return new M.OrderBy(this.getNumber(n),r);let i=e.fieldName();if(i)return new M.OrderBy(this.getFieldName(i),r);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){let r=e.orderBySpec().map(n=>this.visitOrderBySpec(n));return this.astAt(new M.Ordering(r),e)}visitTopStatement(e){let r=e.bySpec(),n=this.getNumber(e.INTEGER_LITERAL()),i;if(r){this.m4advisory(r,"by clause of top statement unupported. Use order_by instead");let s=r.fieldName();if(s){let a=this.getFieldName(s);i=new M.Top(n,a)}let o=r.fieldExpr();o&&(i=new M.Top(n,this.getFieldExpr(o)))}return i||(i=new M.Top(n,void 0)),this.astAt(i,e)}visitSourceID(e){return this.astAt(new M.NamedSource((0,zn.getId)(e)),e)}visitTopLevelQueryDefs(e){let r=e.topLevelQueryDef().map(s=>this.visitTopLevelQueryDef(s)),n=this.getNotes(e.tags()),i=new M.DefineQueryList(r);return i.extendNote({blockNotes:n}),i}visitTopLevelQueryDef(e){let r=(0,zn.getId)(e.queryName()),n=this.visit(e.sqExpr()),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(n instanceof M.SourceQueryElement){let s=new M.DefineQuery(r,n);return s.extendNote({notes:i}),this.astAt(s,e)}throw this.internalError(e,`Expected query definition, got a '${n.elementType}'`)}visitAnonymousQuery(e){let r=e.topLevelAnonQueryDef(),n=this.getSqExpr(r.sqExpr()),i=this.astAt(new M.AnonymousQuery(n),r),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.m4advisory(r,"Anonymous `query:` statements are deprecated, use `run:` instead"),this.astAt(i,e)}visitRunStatement(e){let r=e.topLevelAnonQueryDef(),n=this.getSqExpr(r.sqExpr()),i=this.astAt(new M.AnonymousQuery(n),r),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.astAt(i,e)}visitNestStatement(e){let r=this.visitNestedQueryList(e.nestedQueryList());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitNestedQueryList(e){return new M.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof M.NestFieldDeclaration&&r,"query"))}visitNestDef(e){let r=e.queryName(),n,i=this.getVExpr(e.vExpr());if(r)n=(0,zn.getId)(r);else{let a=i.getImplicitName();a===void 0&&this.contextError(e,"`nest:` view requires a name (add `nest_name is ...`)"),n=a??"__unnamed__"}let s=new M.NestFieldDeclaration(n,i),o=e.isDefine();return s.extendNote({notes:this.getNotes(e.tags()).concat(o?this.getIsNotes(o):[])}),this.astAt(s,e)}visitExploreQueryDef(e){let r=(0,zn.getId)(e.exploreQueryNameDef()),n=new M.ViewFieldDeclaration(r,this.getVExpr(e.vExpr())),i=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return n.extendNote({notes:i}),this.astAt(n,e)}visitExprNot(e){return new M.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new M.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(r=>this.getFieldExpr(r))}visitExprLogicalOr(e){let r=this.getFieldExpr(e.fieldExpr(0)),n=this.getFieldExpr(e.fieldExpr(1));return new M.ExprLogicalOp(r,"or",n)}visitExprLogicalAnd(e){let r=this.getFieldExpr(e.fieldExpr(0)),n=this.getFieldExpr(e.fieldExpr(1));return new M.ExprLogicalOp(r,"and",n)}visitExprOrTree(e){let r=this.getFieldExpr(e.fieldExpr()),n=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new M.ExprAlternationTree(r,"|",n),e)}visitExprAndTree(e){let r=this.getFieldExpr(e.fieldExpr()),n=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new M.ExprAlternationTree(r,"&",n),e)}visitExprCoalesce(e){let r=this.getFieldExpr(e.fieldExpr()[0]),n=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new M.ExprCoalesce(r,n),e)}visitPartialAllowedFieldExpr(e){var r;let n=this.getFieldExpr(e.fieldExpr()),i=(r=e.compareOp())===null||r===void 0?void 0:r.text;if(i){if(M.isComparison(i))return this.astAt(new M.PartialCompare(i,n),e);throw this.internalError(e,`partial comparison '${i}' not recognized`)}return n}visitExprString(e){let r=this.getPlainString(e);return new M.ExprString(r)}visitExprRegex(e){let r=e.HACKY_REGEX().text;return new M.ExprRegEx(r.slice(2,-1))}visitExprNow(e){return new M.ExprNow}visitExprNumber(e){return new M.ExprNumber(e.text)}visitExprFieldPath(e){let r=new M.ExprIdReference(this.getFieldPath(e.fieldPath(),M.ExpressionFieldReference));return this.astAt(r,e)}visitExprNULL(e){return new M.ExprNULL}visitExprExpr(e){return new M.ExprParens(this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprMinus(e){return new M.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){let r=this.getFieldExpr(e.fieldExpr(0)),n=this.getFieldExpr(e.fieldExpr(1)),i=e.PLUS()?"+":"-";return new M.ExprAddSub(r,i,n)}visitExprMulDiv(e){let r=e.STAR()?"*":e.SLASH()?"/":"%";return new M.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){let r=e.compareOp().text;if(M.isComparison(r))return new M.ExprCompare(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)));throw this.internalError(e,`untranslatable comparison operator '${r}'`)}visitExprCountDisinct(e){return this.m4advisory(e,"`count(distinct expression)` deprecated, use `count(expression)` instead"),this.astAt(new M.ExprCountDistinct(this.getFieldExpr(e.fieldExpr())),e)}visitExprUngroup(e){let r=e.fieldName().map(i=>this.getFieldName(i)),n=e.ungroup().text.toLowerCase();return this.astAt(new M.ExprUngroup(n==="all"?n:"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){let r=e.fieldPath(),n=this.getFieldPath(r,M.ExpressionFieldReference),i=r&&n?this.astAt(n,r):void 0,s=e.aggregate().text.toLowerCase(),o=e.fieldExpr();if(e.aggregate().COUNT())return o&&this.contextError(o,"Expression illegal inside path.count()"),new M.ExprCount(i);let a=o?this.getFieldExpr(o):void 0;if(s==="min"||s==="max")if(a)this.contextError(e,this.symmetricAggregateUsageError(s));else{let u=this.astAt(new M.ExprIdReference(n),r);return s==="min"?new M.ExprMin(u):new M.ExprMax(u)}else{if(s==="avg")return new M.ExprAvg(a,i);if(s==="sum")return new M.ExprSum(a,i);this.contextError(e,`Cannot parse aggregate function ${s}`)}return new M.ExprNULL}visitExprPathlessAggregate(e){let r=e.fieldExpr(),n=r?this.getFieldExpr(r):void 0,i=void 0,s=e.aggregate().text.toLowerCase();if(e.STAR()&&this.m4advisory(e,`* illegal inside ${s}()`),s==="count")return this.astAt(n?new M.ExprCountDistinct(n):new M.ExprCount,e);if(s==="min"){if(n)return new M.ExprMin(n);this.contextError(e,this.symmetricAggregateUsageError(s))}else if(s==="max"){if(n)return new M.ExprMax(n);this.contextError(e,this.symmetricAggregateUsageError(s))}else{if(n===void 0)return this.contextError(e,this.asymmetricAggregateUsageError(s)),new M.ExprNULL;let o=e.SOURCE_KW()!==void 0;if(s==="avg")return new M.ExprAvg(n,i,o);if(s==="sum")return new M.ExprSum(n,i,o)}return new M.ExprNULL}visitExprApply(e){return new M.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new M.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){let r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new M.ExprCast(this.getFieldExpr(e.fieldExpr()),r)}getMalloyOrSQLType(e){let r=e.malloyType();if(r){let i=r.text;if((0,KZ.isCastType)(i))return i;throw this.internalError(e,`unknown type '${i}'`)}let n=e.string();if(n)return{raw:this.getPlainString({string:()=>n})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){let r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new M.ExprCast(this.getFieldExpr(e.fieldExpr()),r,!0)}visitExprTimeTrunc(e){return new M.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new M.Timeframe(e.text)}visitExprForRange(e){let r=this.getFieldExpr(e._startAt),n=this.getFieldExpr(e._duration),i=this.visitTimeframe(e.timeframe());return new M.ForRange(r,n,i)}visitExprAggFunc(e){let r=e.argumentList(),n=r?this.allFieldExpressions(r.fieldExpr()):[],i=(0,zn.getId)(e),s=e.fieldPath(),o=s?this.getFieldPath(s,M.ExpressionFieldReference):void 0,a=s&&o?this.astAt(o,s):void 0;return M.ExprTimeExtract.extractor(i)?this.astAt(new M.ExprTimeExtract(i,n),e):this.astAt(new M.ExprFunc(i,n,!1,void 0,a),e)}visitExprFunc(e){var r,n;let i=e.argumentList(),s=i?this.allFieldExpressions(i.fieldExpr()):[],o=e.EXCLAM()!==void 0,a=(r=e.malloyType())===null||r===void 0?void 0:r.text,u;a&&((0,KZ.isCastType)(a)?u=a:(this.contextError(e,`'#' assertion for unknown type '${a}'`),u=void 0));let l=(0,zn.getOptionalId)(e)||((n=e.timeframe())===null||n===void 0?void 0:n.text);return l===void 0&&(this.contextError(e,"Function name error"),l="FUNCTION_NAME_ERROR"),M.ExprTimeExtract.extractor(l)?this.astAt(new M.ExprTimeExtract(l,s),e):this.astAt(new M.ExprFunc(l,s,o,u),e)}visitExprDuration(e){return new M.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitPickStatement(e){let r=e.pick().map(n=>{let i;return n._pickValue&&(i=this.getFieldExpr(n._pickValue)),new M.PickWhen(i,this.getFieldExpr(n._pickWhen))});return e.ELSE()?new M.Pick(r,this.getFieldExpr(e._pickElse)):new M.Pick(r)}visitExprFieldProps(e){let r=this.only(e.fieldProperties().fieldPropertyStatement().map(n=>this.visit(n)),n=>M.isFieldPropStatement(n)&&n,"field property statement");return new M.ExprProps(this.getFieldExpr(e.fieldExpr()),r)}visitPartitionByStatement(e){return this.astAt(new M.PartitionBy(e.id().map(r=>this.astAt(new M.PartitionByFieldReference([this.astAt(new M.FieldName((0,zn.idToStr)(r)),r)]),r))),e)}visitLiteralTimestamp(e){return this.parseTime(e,M.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,M.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,M.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,M.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,M.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,M.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,M.LiteralYear.parse)}visitImportStatement(e){let r=this.getPlainString(e.importURL()),n=this.astAt(new M.ImportStatement(r,this.parseInfo.importBaseURL),e),i=e.importSelect();if(i)for(let s of i.importItem()){let o=s.id(),a=o[1]?this.astAt(new M.ImportSourceName((0,zn.idToStr)(o[1])),o[1]):void 0;n.push(this.astAt(new M.ImportSelect((0,zn.idToStr)(o[0]),a),o[0]))}return n}visitJustExpr(e){return this.getFieldExpr(e.fieldExpr())}visitDefineSQLStatement(e){var r;let n=(r=e.nameSQLBlock())===null||r===void 0?void 0:r.text,i=e.sqlBlock().blockSQLDef(),s=new M.SQLString,o;for(let l of i){let c=l.connectionName();c&&(o?this.contextError(c,"Cannot redefine connection"):o=this.getPlainString(c));let f=l.sqlString();f&&this.makeSqlString(f,s)}let a=new M.SQLStatement(s);o!==void 0&&(a.connection=o),a.is=n;let u=this.astAt(a,e);return this.m4advisory(e,"`sql:` statement is deprecated, use `connection_name.sql(...)` instead"),u}visitSampleStatement(e){let r=e.sampleSpec().INTEGER_LITERAL();if(r)return new M.SampleProperty({rows:this.getNumber(r)});let n=e.sampleSpec().PERCENT_LITERAL();if(n)return new M.SampleProperty({percent:this.getNumber(n)});let i=e.sampleSpec().TRUE()!==void 0;return new M.SampleProperty({enable:i})}visitDocAnnotations(e){let r=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)})),n=new M.ModelAnnotation(r);return this.compilerFlags=n.getCompilerFlags(this.compilerFlags,this.msgLog),n}visitIgnoredObjectAnnotations(e){return this.contextError(e,"Object annotation not connected to any object"),new _5(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"Model annotations not allowed at this scope"),new _5(e.text)}visitDefExploreAnnotation(e){let r=this.getNotes(e);return new M.ObjectAnnotation(r)}visitSQID(e){let r=this.getModelEntryName(e);return this.astAt(new M.SQReference(r),e.id())}getSqExpr(e){let r=this.visit(e);return r instanceof M.SourceQueryElement?r:(this.contextError(e,`Expected a source/query expression, not '${r.elementType}'`),new FP)}visitSQExtendedSource(e){let r=this.getSqExpr(e.sqExpr()),n=new M.SQExtend(r,this.getSourceExtensions(e.exploreProperties()));return this.astAt(n,e)}visitSQParens(e){let r=this.getSqExpr(e.sqExpr());return this.astAt(r,e)}visitSQArrow(e){let r=this.getSqExpr(e.sqExpr()),n=e.segExpr(),i=new M.SQArrow(r,this.getVExpr(n));return this.astAt(i,e)}getVExpr(e){let r=this.visit(e);if(r instanceof M.View)return r;throw this.internalError(e,`Expected view, got a '${r.elementType}'`)}visitSegField(e){return new M.ReferenceView(this.getFieldPath(e.fieldPath(),M.ViewOrScalarFieldReference))}visitSegOps(e){return new M.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new M.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new M.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){let r=this.getSqExpr(e.sqExpr()),n=e.segExpr(),i=new M.SQRefine(r,this.getVExpr(n));return this.astAt(i,e)}visitSQTable(e){let r=this.visit(e.exploreTable());if(r instanceof iut.TableSource){let n=new M.SQSource(r);return this.astAt(n,e)}return new FP}visitSQSQL(e){let r=new M.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(r,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new M.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}};ef.MalloyToAST=XZ});var lSe=v(wP=>{"use strict";Object.defineProperty(wP,"__esModule",{value:!0});wP.MessageLog=void 0;var JZ=class{constructor(){this.rawLog=[]}getLog(){return this.rawLog}log(e){this.rawLog.push(e)}reset(){this.rawLog.length=0}noErrors(){return!this.hasErrors()}hasErrors(){return this.rawLog.find(r=>r.severity!=="warn")!==void 0}empty(){return this.rawLog.length===0}};wP.MessageLog=JZ});var cSe=v(LP=>{"use strict";Object.defineProperty(LP,"__esModule",{value:!0});LP.Zone=void 0;var ZZ=class{constructor(){this.location={},this.zone=new Map}get(e){let r=this.zone.get(e);if(r?.status==="present")return r.value}getEntry(e){let 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){let n=this.zone.get(e);n?.status===void 0&&(this.zone.set(e,{status:"reference",firstReference:r}),this.location[e]=r)}getUndefined(){let e=[];for(let[r,n]of this.zone)n.status==="reference"&&e.push(r);return e.length>0?e:void 0}updateFrom(e,r){if(e)for(let[n,i]of Object.entries(e))i!==void 0&&this.define(n,i);if(r)for(let[n,i]of Object.entries(r))this.zone.set(n,{status:"error",message:i})}};LP.Zone=ZZ});var fSe=v(IP=>{"use strict";Object.defineProperty(IP,"__esModule",{value:!0});IP.walkForDocumentSymbols=void 0;var aut=_p(),uut=WC(),eee=class{constructor(e,r,n,i){this.translator=e,this.tokens=r,this.scopes=n,this.symbols=i}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){let r=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=r)}enterTopLevelQueryDef(e){this.symbols.push({range:this.translator.rangeFromContext(e),name:e.queryName().text,type:"query",children:[],lensRange:this.blockRange}),this.blockRange=void 0}enterRunStatement(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterAnonymousQuery(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef().sqExpr()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterDefineSourceStatement(e){let r=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=r)}enterSourceDefinition(e){let 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){let r=this.popScope();r&&this.symbols.push(r)}enterDefExploreQuery(e){let r=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=r)}enterExploreQueryDef(e){let r={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},n=this.peekScope();n&&n.children.push(r),this.scopes.push(r),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}getNestDefName(e){let r=e.queryName();if(r)return r.id().text;let n,i=!1,s={enterVArrow(a){a.vExpr().enterRule(s)},enterVSeg(a){a.segExpr().enterRule(o)}},o={enterSegField(a){let u=a.fieldPath().fieldName();i||(n??(n=u[u.length-1].id().text))},enterSegParen(a){a.vExpr().enterRule(s)},enterSegRefine(a){a._lhs.enterRule(o)},enterSegOps(){n=void 0,i=!0}};return e.vExpr().enterRule(s),n}handleNestEntry(e){let r=this.getNestDefName(e);if(r===void 0)return;let n={range:this.translator.rangeFromContext(e),name:r,type:"query",children:[]},i=this.peekScope();return i&&i.children.push(n),n}enterNestDef(e){let r=this.handleNestEntry(e);r&&this.scopes.push(r)}exitNestDef(e){this.popScope()}enterFieldDef(e){let r={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},n=this.peekScope();n&&n.children.push(r)}enterQueryFieldEntry(e){var r;let n=(r=e.taggedRef())===null||r===void 0?void 0:r.fieldPath();if(n===void 0)return;let i={range:this.translator.rangeFromContext(e),name:n.text,type:"field",children:[]},s=this.peekScope();s&&s.children.push(i)}enterExploreRenameDef(e){let r={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},n=this.peekScope();n&&n.children.push(r)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){let r={range:this.translator.rangeFromContext(e),name:e.joinNameDef().id().text,type:"join",children:[]},n=this.peekScope();n&&n.children.push(r)}enterDefineSQLStatement(e){let r=e.nameSQLBlock().text,n={range:this.translator.rangeFromContext(e),name:r,type:"sql",children:[]};this.symbols.push(n)}enterImportStatement(e){let r=(0,uut.getStringIfShort)(e.importURL());r&&this.scopes.push({range:this.translator.rangeFromContext(e),name:r,type:"import",children:[]})}exitImportStatement(){let e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){let r=this.peekScope();if(r)for(let n of e.importItem()){let i={range:this.translator.rangeFromContext(e),name:n.text,type:"import_item",children:[]};r.children.push(i)}}};function lut(t,e,r){let n=new eee(t,e,[],[]),i=n;return aut.ParseTreeWalker.DEFAULT.walk(i,r),n.symbols}IP.walkForDocumentSymbols=lut});var ree=v(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.sortHighlights=Ue.walkForDocumentHighlights=Ue.passForHighlights=Ue.HighlightType=void 0;var cut=_p(),Te=ZW();Ue.HighlightType={Identifier:"identifier",Type:"type",Literal:{Date:"literal.date",Number:"literal.number",String:"literal.string",RegularExpression:"literal.regular_expression",Boolean:"literal.boolean",Null:"literal.null"},Call:{Aggregate:"call.aggregate",TimeFrame:"call.time_frame",Cast:"call.cast",Table:"call.table",From:"call.from",Function:"call.function",FromSQL:"call.from_sql"},Keyword:{AggregateModifier:{Distinct:"keyword.aggregate_modifier.distinct"},CastModifier:{As:"keyword.cast_modifier.as"},Is:"keyword.is",On:"keyword.on",Desc:"keyword.desc",Asc:"keyword.asc",Pick:"keyword.pick",When:"keyword.when",Else:"keyword.else",With:"keyword.with",JSON:"keyword.json",Turtle:"keyword.turtle",Import:"keyword.import"},Operator:{Comparison:"operator.comparison",Boolean:"operator.boolean",Date:"operator.date"},Comment:{Line:"comment.line",Block:"comment.block"},Property:{Accept:"property.accept",Aggregate:"property.aggregate",Dimension:"property.dimension",Except:"property.except",Source:"property.source",GroupBy:"property.group_by",Having:"property.having",Index:"property.index",JoinOne:"keyword.join_one",JoinMany:"keyword.join_many",JoinCross:"keyword.join_cross",Limit:"property.limit",Measure:"property.measure",Nest:"property.nest",OrderBy:"property.order_by",PrimaryKey:"property.primary_key",Project:"property.project",Query:"property.query",Rename:"property.rename",Top:"property.top",Where:"property.where",SQL:"property.sql"}};function fut(t){let e=[],r=(n,i,s=!1)=>{var o;let a=n.startIndex-n.charPositionInLine,u=((o=n.text)===null||o===void 0?void 0:o.split(`
|
|
683
683
|
`))||[],l=u.length,c=u.slice(0,-1).reduce((x,d)=>x+d.length,0),f=s?1:0;e.push({type:i,range:{start:{line:n.line-1,character:n.startIndex-a},end:{line:n.line-1+l-1,character:n.stopIndex+2-(l>1?n.startIndex:a)-c-l-f}}})};for(let n=0;n<t.size;n++){let i=t.get(n);switch(i.type){case Te.MalloyParser.ACCEPT:r(i,Ue.HighlightType.Property.Accept,!0);break;case Te.MalloyParser.AGGREGATE:r(i,Ue.HighlightType.Property.Aggregate,!0);break;case Te.MalloyParser.DIMENSION:r(i,Ue.HighlightType.Property.Dimension,!0);break;case Te.MalloyParser.EXCEPT:r(i,Ue.HighlightType.Property.Except,!0);break;case Te.MalloyParser.GROUP_BY:r(i,Ue.HighlightType.Property.GroupBy,!0);break;case Te.MalloyParser.HAVING:r(i,Ue.HighlightType.Property.Having,!0);break;case Te.MalloyParser.INDEX:r(i,Ue.HighlightType.Property.Index,!0);break;case Te.MalloyParser.JOIN_CROSS:r(i,Ue.HighlightType.Property.JoinOne,!0);break;case Te.MalloyParser.JOIN_ONE:r(i,Ue.HighlightType.Property.JoinMany,!0);break;case Te.MalloyParser.JOIN_MANY:r(i,Ue.HighlightType.Property.JoinCross,!0);break;case Te.MalloyParser.LIMIT:r(i,Ue.HighlightType.Property.Limit,!0);break;case Te.MalloyParser.MEASURE:r(i,Ue.HighlightType.Property.Measure,!0);break;case Te.MalloyParser.NEST:r(i,Ue.HighlightType.Property.Nest,!0);break;case Te.MalloyParser.ORDER_BY:r(i,Ue.HighlightType.Property.OrderBy,!0);break;case Te.MalloyParser.PRIMARY_KEY:r(i,Ue.HighlightType.Property.PrimaryKey,!0);break;case Te.MalloyParser.PROJECT:r(i,Ue.HighlightType.Property.Project,!0);break;case Te.MalloyParser.QUERY:r(i,Ue.HighlightType.Property.Query,!0);break;case Te.MalloyParser.RENAME:r(i,Ue.HighlightType.Property.Rename,!0);break;case Te.MalloyParser.SOURCE:r(i,Ue.HighlightType.Property.Source,!0);break;case Te.MalloyParser.TOP:r(i,Ue.HighlightType.Property.Top,!0);break;case Te.MalloyParser.WHERE:r(i,Ue.HighlightType.Property.Where,!0);break;case Te.MalloyParser.SQL:r(i,Ue.HighlightType.Property.SQL,!0);break;case Te.MalloyParser.TABLE:r(i,Ue.HighlightType.Call.Table);break;case Te.MalloyParser.FROM:r(i,Ue.HighlightType.Call.From);break;case Te.MalloyParser.FROM_SQL:r(i,Ue.HighlightType.Call.FromSQL);break;case Te.MalloyParser.SQ_STRING:case Te.MalloyParser.DQ_STRING:r(i,Ue.HighlightType.Literal.String);break;case Te.MalloyParser.NUMERIC_LITERAL:case Te.MalloyParser.INTEGER_LITERAL:r(i,Ue.HighlightType.Literal.Number);break;case Te.MalloyParser.HACKY_REGEX:r(i,Ue.HighlightType.Literal.RegularExpression);break;case Te.MalloyParser.IS:r(i,Ue.HighlightType.Keyword.Is);break;case Te.MalloyParser.DISTINCT:r(i,Ue.HighlightType.Keyword.AggregateModifier.Distinct);break;case Te.MalloyParser.ON:r(i,Ue.HighlightType.Keyword.On);break;case Te.MalloyParser.DESC:r(i,Ue.HighlightType.Keyword.Desc);break;case Te.MalloyParser.ASC:r(i,Ue.HighlightType.Keyword.Asc);break;case Te.MalloyParser.CAST:r(i,Ue.HighlightType.Call.Cast);break;case Te.MalloyParser.AS:r(i,Ue.HighlightType.Keyword.CastModifier.As);break;case Te.MalloyParser.PICK:r(i,Ue.HighlightType.Keyword.Pick);break;case Te.MalloyParser.WHEN:r(i,Ue.HighlightType.Keyword.When);break;case Te.MalloyParser.WITH:r(i,Ue.HighlightType.Keyword.With);break;case Te.MalloyParser.ELSE:r(i,Ue.HighlightType.Keyword.Else);break;case Te.MalloyParser.JSON:r(i,Ue.HighlightType.Keyword.JSON);break;case Te.MalloyParser.TURTLE:r(i,Ue.HighlightType.Keyword.Turtle);break;case Te.MalloyParser.TRUE:case Te.MalloyParser.FALSE:r(i,Ue.HighlightType.Literal.Boolean);break;case Te.MalloyParser.NOW:case Te.MalloyParser.LITERAL_TIMESTAMP:case Te.MalloyParser.LITERAL_QUARTER:case Te.MalloyParser.LITERAL_MONTH:case Te.MalloyParser.LITERAL_DAY:case Te.MalloyParser.LITERAL_WEEK:case Te.MalloyParser.LITERAL_YEAR:r(i,Ue.HighlightType.Literal.Date);break;case Te.MalloyParser.NULL:r(i,Ue.HighlightType.Literal.Null);break;case Te.MalloyParser.AND:case Te.MalloyParser.OR:case Te.MalloyParser.NOT:r(i,Ue.HighlightType.Operator.Boolean);break;case Te.MalloyParser.FOR:r(i,Ue.HighlightType.Operator.Date);break;case Te.MalloyParser.COMMENT_TO_EOL:r(i,Ue.HighlightType.Comment.Line);break;case Te.MalloyParser.BLOCK_COMMENT:r(i,Ue.HighlightType.Comment.Block);break;case Te.MalloyParser.SUM:case Te.MalloyParser.COUNT:case Te.MalloyParser.AVG:case Te.MalloyParser.MIN:case Te.MalloyParser.MAX:r(i,Ue.HighlightType.Call.Aggregate);break;case Te.MalloyParser.IDENTIFIER:case Te.MalloyParser.BQ_STRING:r(i,Ue.HighlightType.Identifier);break;case Te.MalloyParser.STRING:case Te.MalloyParser.NUMBER:case Te.MalloyParser.BOOLEAN:case Te.MalloyParser.DATE:case Te.MalloyParser.TIMESTAMP:r(i,Ue.HighlightType.Type);break;case Te.MalloyParser.SECOND:case Te.MalloyParser.MINUTE:case Te.MalloyParser.HOUR:case Te.MalloyParser.DAY:case Te.MalloyParser.WEEK:case Te.MalloyParser.MONTH:case Te.MalloyParser.QUARTER:case Te.MalloyParser.YEAR:r(i,Ue.HighlightType.Call.TimeFrame);break;case Te.MalloyParser.IMPORT:r(i,Ue.HighlightType.Keyword.Import);break}}return e}Ue.passForHighlights=fut;var tee=class{constructor(e,r){this.tokens=e,this.highlights=r}rangeOf(e){let 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}}}enterExprFunc(e){let r=e.id()||e.timeframe();r&&this.highlights.push({range:this.rangeOf(r),type:Ue.HighlightType.Call.Function})}};function xut(t,e){let r=new tee(t,[]),n=r;return cut.ParseTreeWalker.DEFAULT.walk(n,e),r.highlights}Ue.walkForDocumentHighlights=xut;function dut(t){return t.sort((e,r)=>e.range.start.line<r.range.start.line?-1:e.range.start.line>r.range.start.line?1:e.range.start.character<r.range.start.character?-1:e.range.start.character>r.range.start.character?1:0)}Ue.sortHighlights=dut});var xSe=v(MP=>{"use strict";Object.defineProperty(MP,"__esModule",{value:!0});MP.walkForDocumentCompletions=void 0;var hut=_p(),put=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],mut=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],gut=["source","explore","query","sql"],nee=class{constructor(e,r,n){this.tokens=e,this.completions=r,this.position=n}rangeOf(e){let 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){let{start:r,end:n}=e,i=this.position.line>r.line||this.position.line===r.line&&this.position.character>=r.character,s=this.position.line<n.line||this.position.line===n.line&&this.position.character<=n.character;return i&&s}enterExploreProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(let n of e.exploreStatement())this.inRange(this.rangeOf(n))&&(r=!0);if(!r)for(let n of put)this.completions.push({type:"explore_property",text:`${n}: `})}}enterQueryProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(let n of e.queryStatement())this.inRange(this.rangeOf(n))&&(r=!0);if(!r)for(let n of mut)this.completions.push({type:"query_property",text:`${n}: `})}}enterMalloyDocument(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(let n of e.malloyStatement())this.inRange(this.rangeOf(n))&&(r=!0);if(!r)for(let n of gut)this.completions.push({type:"model_property",text:`${n}: `})}}};function yut(t,e,r){let n=new nee(t,[],r),i=n;return hut.ParseTreeWalker.DEFAULT.walk(i,e),n.completions}MP.walkForDocumentCompletions=yut});var dSe=v(PP=>{"use strict";Object.defineProperty(PP,"__esModule",{value:!0});PP.walkForDocumentHelpContext=void 0;var Eut=rY(),iee=class extends Eut.AbstractParseTreeVisitor{constructor(e){super(),this.position=e,this.type=""}rangeOf(e){let 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};let n=e.childCount;for(let i=0;i<n;i++){let o=e.getChild(i).accept(this);o&&(r=this.aggregateResult(r,o))}}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 Aut(t,e){return new iee(e).visit(t)}PP.walkForDocumentHelpContext=Aut});var see=v(kP=>{"use strict";Object.defineProperty(kP,"__esModule",{value:!0});kP.locationContainsPosition=void 0;function Sut(t,e){return t.range.start.line<=e.line&&t.range.end.line>=e.line&&(e.line!==t.range.start.line||e.character>=t.range.start.character)&&(e.line!==t.range.end.line||e.character<=t.range.end.character)}kP.locationContainsPosition=Sut});var hSe=v(BP=>{"use strict";Object.defineProperty(BP,"__esModule",{value:!0});BP.ReferenceList=void 0;var vut=see(),oee=class{constructor(e){this.sourceURL=e,this.references=[]}findIndexBefore(e){let r=0,n=this.references.length;for(;r<n;){let i=Math.floor((r+n)/2),s=this.references[i].location.range.end;s.line<e.line||s.line===e.line&&s.character<e.character?r=i+1:n=i}return r}add(e){if(e.location.url!==this.sourceURL)return;let 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){let n=e.location.range,i=r.location.range;return n.start.line===i.start.line&&n.start.character===i.start.character&&n.end.line===i.end.line&&n.end.character===i.end.character}find(e){let r=this.findIndexBefore(e);if(r===this.references.length)return;let n=this.references[r];if((0,vut.locationContainsPosition)(n.location,e))return n}};BP.ReferenceList=oee});var pSe=v(qP=>{"use strict";Object.defineProperty(qP,"__esModule",{value:!0});qP.isNeedResponse=void 0;function _ut(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}qP.isNeedResponse=_ut});var mSe=v(UP=>{"use strict";Object.defineProperty(UP,"__esModule",{value:!0});UP.walkForModelAnnotation=void 0;var but=_p(),aee=class{constructor(e,r,n){this.translator=e,this.tokens=r,this.parseInfo=n,this.notes=[]}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}enterDocAnnotations(e){let r=e.DOC_ANNOTATION().map(n=>({text:n.text,at:this.getLocation(e)}));this.notes.push(...r)}get annotation(){return{notes:this.notes}}};function Tut(t,e,r){let n=new aee(t,e,r),i=n;return but.ParseTreeWalker.DEFAULT.walk(i,r.root),n.annotation}UP.walkForModelAnnotation=Tut});var ESe=v(Hs=>{"use strict";var Cut=Hs&&Hs.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Rut=Hs&&Hs.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Out=Hs&&Hs.__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)&&Cut(e,t,r);return Rut(e,t),e};Object.defineProperty(Hs,"__esModule",{value:!0});Hs.MalloyParserErrorHandler=Hs.MalloyTranslator=Hs.MalloyChildTranslator=Hs.MalloyTranslation=void 0;var gSe=E8(),Dut=Rge(),Nut=ZW(),$P=Out(NP()),Fut=uSe(),wut=lSe(),Lut=zZ(),uee=cSe(),Iut=fSe(),lee=ree(),Mut=xSe(),Put=dSe(),kut=hSe(),jP=pSe(),But=see(),ySe=Wm(),qut=mSe(),cee=class extends Dut.MalloyLexer{popMode(){return this._modeStack.isEmpty?this._mode:super.popMode()}},fee=class{step(e){if(this.response)return this.response;if(e.urlIsFullPath===void 0)try{let s=new URL(e.sourceURL);e.urlIsFullPath=!0}catch(s){let o=s instanceof Error?s.message:"";e.urlIsFullPath=!1,e.root.logger.log({message:`Could not compute full path URL: ${o}`,severity:"error"})}if(!e.urlIsFullPath)return e.fatalResponse();let r=e.root.importZone.getEntry(e.sourceURL);if(r.status!=="present"){if(r.status==="error"){let s=r.message.includes(e.sourceURL)?`import error: ${r.message}`:`import '${e.sourceURL}' error: ${r.message}`,o=r.firstReference||e.defaultLocation();return e.root.logger.log({message:s,at:o,severity:"error"}),this.response=e.fatalResponse(),this.response}return{urls:[e.sourceURL]}}let n=r.value===""?`
|
|
684
684
|
`:r.value;this.sourceInfo=this.getSourceInfo(n);let i;try{i=this.runParser(n,e)}catch(s){e.root.logger.log({message:`Malloy internal parser exception [${s.message}]`,severity:"error"}),i=void 0}return e.root.logger.hasErrors()?this.response={parse:i,...e.fatalResponse()}:this.response={parse:i},this.response}getSourceInfo(e){let r=/\r?\n/,n={at:[],lines:[],length:e.length},i=e,s=0;for(;i!=="";){let o=i.match(r);if(o&&o.index!==void 0){n.lines.push(i.slice(0,o.index));let a=o.index+o[0].length;n.at.push({begin:s,end:s+a}),s+=a,i=i.slice(a)}else{n.lines.push(i),n.at.push({begin:s,end:s+i.length});break}}return n}runParser(e,r){let n=gSe.CharStreams.fromString(e),i=new cee(n),s=new gSe.CommonTokenStream(i),o=new Nut.MalloyParser(s);o.removeErrorListeners(),o.addErrorListener(new zP(r,r.root.logger));let a=o[r.grammarRule];if(!a)throw new Error(`No such parse rule as ${r.grammarRule}`);return{root:a.call(o),tokenStream:s,sourceStream:n,sourceURL:r.sourceURL,importBaseURL:r.importBaseURL||r.sourceURL,rangeFromContext:u=>r.rangeFromContext(u),malloyVersion:"4.0.0"}}},xee=class{constructor(e){this.parseStep=e,this.parseReferences=void 0}step(e){let r=this.parseStep.step(e);if(r.parse===void 0)return r;if(!this.parseReferences){this.parseReferences=(0,Lut.findReferences)(e,r.parse.tokenStream,r.parse.root);for(let o in this.parseReferences.tables)e.root.schemaZone.reference(o,{url:e.sourceURL,range:this.parseReferences.tables[o].firstReference});for(let o in this.parseReferences.urls){let a=this.parseReferences.urls[o];try{let u=decodeURI(new URL(o,e.importBaseURL||e.sourceURL).toString());e.addChild(u),e.imports.push({importURL:u,location:{url:e.sourceURL,range:a}}),e.root.importZone.reference(u,{url:e.sourceURL,range:a})}catch{e.root.logger.log({message:`Malformed URL '${o}'"`,at:{url:e.sourceURL,range:a},severity:"error"})}}}if(e.root.logger.hasErrors())return null;let n={},i=e.root.schemaZone.getUndefined();if(i){let o={};for(let a of i){let u=this.parseReferences.tables[a];o[a]={connectionName:u.connectionName,tablePath:u.tablePath}}n={tables:o}}let s=e.root.importZone.getUndefined();if(s&&(n={...n,urls:s}),(0,jP.isNeedResponse)(n))return n;for(let o of e.childTranslators.values()){let a=o.importsAndTablesStep.step(o);if((0,jP.isNeedResponse)(a))return a}return null}},dee=class{constructor(e){this.importStep=e,this.walked=!1}step(e){if(this.response)return this.response;let r=this.importStep.step(e);if(r)return r;let n=e.parseStep.response;if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;let i=n?.parse;if(!i)throw new Error("TRANSLATOR INTERNAL ERROR: Translator parse response had no errors, but also no parser");let s=new Fut.MalloyToAST(i,e.root.logger,e.compilerFlags),o=s.visit(i.root);if(e.compilerFlags=s.compilerFlags,e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;if(o.elementType==="unimplemented")throw new Error("TRANSLATOR INTERNAL ERROR: Unimplemented AST node");let a={};if(!this.walked){for(let u of o.walk())u instanceof $P.FromSQLSource?(a[u.refName]||(a[u.refName]={}),a[u.refName].ref=u):u instanceof $P.SQLStatement&&u.is?(a[u.is]||(a[u.is]={}),a[u.is].def=u):u instanceof $P.Unimplemented&&u.log("INTERNAL COMPILER ERROR: Untranslated parse node");this.walked=!0}if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;for(let u of e.childTranslators.values()){let l=u.astStep.step(u);if((0,jP.isNeedResponse)(l))return l}return o.setTranslator(e),this.response={...e.problemResponse(),ast:o,final:!0},this.response}},hee=class{constructor(e){this.parseStep=e}step(e){if(!this.response){let r=this.parseStep.step(e);if(r.parse){let n;try{n=(0,Iut.walkForDocumentSymbols)(e,r.parse.tokenStream,r.parse.root)}catch{}let i;try{i=(0,lee.walkForDocumentHighlights)(r.parse.tokenStream,r.parse.root)}catch{i=[]}this.response={symbols:n,highlights:(0,lee.sortHighlights)([...(0,lee.passForHighlights)(r.parse.tokenStream),...i]),final:!0}}else return r}return this.response}},pee=class{constructor(e){this.parseStep=e}step(e,r){let n=this.parseStep.step(e);if(n.parse){let i=[];if(r!==void 0)try{i=(0,Mut.walkForDocumentCompletions)(n.parse.tokenStream,n.parse.root,r)}catch{}return{...n,completions:i}}else return n}},mee=class{constructor(e){this.parseStep=e}step(e,r){let n=this.parseStep.step(e);if(n.parse){let i;if(r!==void 0)try{i=(0,Put.walkForDocumentHelpContext)(n.parse.root,r)}catch{}return{...n,helpContext:i}}else return n}},gee=class{constructor(e){this.parseStep=e}step(e,r){if(!this.response){let n=this.parseStep.step(e);if(!n.parse||n.final)return n;{let i=(0,qut.walkForModelAnnotation)(e,n.parse.tokenStream,n.parse);this.response={modelAnnotation:{...i,inherits:r?.annotation}}}}return this.response}},yee=class{constructor(e){this.astStep=e,this.importedAnnotations=!1}step(e,r){if(this.response)return this.response;if(r&&!this.importedAnnotations){let i=ySe.Tag.annotationToTag(r.annotation,{prefix:/^##! /});e.compilerFlags=i.tag,this.importedAnnotations=!0}let n=this.astStep.step(e);if((0,jP.isNeedResponse)(n))return n;if(!n.ast)return this.response=n,this.response;if(e.grammarRule==="malloyDocument")if(n.ast instanceof $P.Document){let i=n.ast;for(i.initModelDef(r);;){let s=i.compile();if(s.needs)return s.needs;e.modelDef=s.modelDef,e.queryList=s.queryList,e.sqlBlocks=s.sqlBlocks;break}}else e.root.logger.log({message:`'${e.sourceURL}' did not parse to malloy document`,at:e.defaultLocation(),severity:"error"});return e.root.logger.hasErrors()?this.response={fromSources:e.getDependencies(),...e.fatalResponse()}:this.response={translated:{modelDef:e.modelDef,queryList:e.queryList,sqlBlocks:e.sqlBlocks},fromSources:e.getDependencies(),...e.problemResponse(),final:!0},this.response}},b5=class{constructor(e,r=null,n="malloyDocument"){this.sourceURL=e,this.importBaseURL=r,this.grammarRule=n,this.queryList=[],this.sqlBlocks=[],this.imports=[],this.compilerFlags=new ySe.Tag,this.childTranslators=new Map,this.modelDef={name:e,exports:[],contents:{}},this.parseStep=new fee,this.modelAnnotationStep=new gee(this.parseStep),this.metadataStep=new hee(this.parseStep),this.completionsStep=new pee(this.parseStep),this.helpContextStep=new mee(this.parseStep),this.importsAndTablesStep=new xee(this.parseStep),this.astStep=new dee(this.importsAndTablesStep),this.translateStep=new yee(this.astStep),this.references=new kut.ReferenceList(e)}addChild(e){this.childTranslators.get(e)||this.childTranslators.set(e,new HP(e,this.root))}getDependencies(){let e=[this.sourceURL];for(let[r,n]of this.childTranslators)e.push(...n.getDependencies());return e}addReference(e){this.references.add(e)}referenceAt(e){return this.references.find(e)}fatalResponse(){return{final:!0,...this.problemResponse()}}problemResponse(){return{problems:this.problems()}}problems(){return[...this.root.logger.getLog()]}getLineMap(e){var r,n;if(e===this.sourceURL)return(r=this.parseStep.sourceInfo)===null||r===void 0?void 0:r.lines;let i=this.childTranslators.get(e);if(i)return(n=i.parseStep.sourceInfo)===null||n===void 0?void 0:n.lines}codeAtLocation(e){let r=this.getLineMap(e.url)||[];if(e.range.start.line===e.range.end.line)return r[e.range.start.line].slice(e.range.start.character,e.range.end.character);let n="";n+=r[e.range.start.line].slice(e.range.start.character);for(let i=e.range.start.line+1;i<e.range.end.line;i++)n+=r[i];return n+=r[e.range.end.line].slice(0,e.range.end.character),n}prettyErrors(){let e="",r="";for(let n of this.root.logger.getLog()){let i=n.message,s=this.sourceURL;if(n.at){s=n.at.url;let o=n.at.range.start.line,a=n.at.range.start.character,u=this.getLineMap(n.at.url);if(u){let l=u[o];i=`line ${o+1}: ${n.message}
|
|
685
685
|
| ${l}`,a>0&&(i=i+`
|