@malloydata/render 0.0.163-dev240808155642 → 0.0.163-dev240808193357
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/module/index.mjs +12016 -12258
- package/dist/module/index.umd.js +246 -246
- package/dist/register/register.mjs +9 -9
- package/dist/register/register.umd.js +2 -2
- package/dist/webcomponent/malloy-render.mjs +9 -9
- package/dist/webcomponent/malloy-render.umd.js +2 -2
- package/package.json +2 -2
|
@@ -374,7 +374,7 @@ FROM ${n}
|
|
|
374
374
|
FROM ${h}
|
|
375
375
|
`),this.resultStage}}class ape extends eo{generateSQL(e){const n=this.parent.fieldDef.structSource;if(n.type!=="sql"||n.method!=="subquery")throw new Error("Invalid struct for QueryQueryRaw, currently only supports SQL");const r=n.sqlBlock.selectStr;return e.addStage(r)}prepare(){}getResultStructDef(){return this.parent.fieldDef}getResultMetadata(e){}}class lpe extends eo{constructor(e,n,r,i){super(e,n,r,i),this.stages=[],this.fieldDef=e,this.fieldsToStages()}fieldsToStages(){const e=this.firstSegment;if(this.parent.dialect.dontUnionIndex){this.stages=[e.indexFields];return}const n={};for(const r of e.indexFields){if(r.path.length>1){const i=HM(r.path.slice(0,r.path.length-1)),s=n[i];if(s===void 0){const o=this.parent.nameMap.get(r.path[0]);if(o instanceof zr&&(o.fieldDef.structRelationship.type==="many"||o.fieldDef.structRelationship.type==="nested")&&o.fieldDef.fields.length>1){const u=[r];n[i]=u,this.stages.push(u);continue}}else{s.push(r);continue}}this.stages[0]===void 0&&(this.stages[0]=[]),this.stages[0].push(r)}}expandFields(e){}generateSQL(e){const n=this.firstSegment,r=[];for(const i of this.stages){const s=new upe({...this.fieldDef,pipeline:[{...n,indexFields:i}]},this.parent,e,this.isJoinedSubquery);s.prepare(e);const o=s.generateSQL(e);r.push(o)}return r.length===1?this.resultStage=r[0]:this.resultStage=e.addStage(r.map(i=>`SELECT * FROM ${i}
|
|
376
376
|
`).join(` UNION ALL
|
|
377
|
-
`)),this.resultStage}getResultStructDef(){const e={type:"struct",name:this.resultStage||"result",dialect:this.parent.fieldDef.dialect,fields:[{type:"string",name:"fieldName"},{type:"string",name:"fieldPath"},{type:"string",name:"fieldValue"},{type:"string",name:"fieldType"},{type:"number",name:"weight",numberType:"integer"}],structRelationship:{type:"basetable",connectionName:this.parent.connectionName},structSource:{type:"query_result"}};return this.parent.fieldDef.modelAnnotation&&(e.modelAnnotation=this.parent.fieldDef.modelAnnotation),e}}class zr extends zM{constructor(e,n,r){if(super(e),this.sourceArguments=n,this.nameMap=new Map,this._arguments=void 0,this.setParent(r),"model"in r)if(this.model=r.model,this.pathAliasMap=new Map,e.structRelationship.type==="basetable")this.connectionName=e.structRelationship.connectionName;else throw new Error("All root StructDefs should be a baseTable");else this.model=this.getModel(),this.pathAliasMap=this.root().pathAliasMap,this.connectionName=this.root().connectionName;this.fieldDef=e,this.dialect=(0,Ghe.getDialect)(this.fieldDef.dialect),this.addFieldsFromFieldList(this.fieldDef.fields)}resolveParentParameterReferences(e){return{...e,value:e.value===null?null:(0,lr.exprMap)(e.value,n=>{if(typeof n=="string")return[n];if(n.type==="parameter"){if(this.parent===void 0)throw new Error("No parent from which to retrieve parameter value");const r=this.parent.arguments()[n.path[0]],i=this.parent.resolveParentParameterReferences(r);if(i.value===null)throw new Error("Invalid parameter value");return i.value}return[n]})}}arguments(){var e,n,r;if(this._arguments!==void 0)return this._arguments;this._arguments={};const i=(e=this.fieldDef.parameters)!==null&&e!==void 0?e:{};for(const o in i)this._arguments[o]=i[o];const s=(r=(n=this.sourceArguments)!==null&&n!==void 0?n:this.fieldDef.arguments)!==null&&r!==void 0?r:{};for(const o in s){const u=s[o];this._arguments[o]=this.resolveParentParameterReferences(u)}return this._arguments}addFieldsFromFieldList(e){for(const n of e){const r=(0,Ue.getIdentifier)(n);switch(n.type){case"struct":{this.addFieldToNameMap(r,new zr(n,void 0,{struct:this}));break}case"turtle":{this.addFieldToNameMap(r,eo.makeQuery(n,this,void 0,!1));break}default:this.addFieldToNameMap(r,this.makeQueryField(n))}}this.nameMap.has("__distinct_key")||this.addFieldToNameMap("__distinct_key",new tpe({type:"string",name:"__distinct_key"},this))}getAliasIdentifier(){const e=this.getFullOutputName(),n=this.pathAliasMap.get(e);if(n===void 0){const r=Array.from(this.pathAliasMap.values()),i=Vhe((0,Ue.getIdentifier)(this.fieldDef));let s=`${i}_0`,o=1;for(;r.includes(s)&&o<1e3;)o++,s=`${i}_${o}`;if(o<1e3)return this.pathAliasMap.set(e,s),s;throw new Error("Internal Error: cannot create unique alias name")}else return n}getSQLIdentifier(){return this.unnestWithNumbers()&&this.parent!==void 0?this.parent.getSQLIdentifier()+"."+(0,Ue.getIdentifier)(this.fieldDef)+`[${this.getIdentifier()}.__row_id]`:this.getIdentifier()}getIdentifier(){return this.fieldDef.structRelationship.type==="basetable"?"base":this.fieldDef.structRelationship.type==="inline"&&this.parent?this.parent.getSQLIdentifier()+"."+super.getIdentifier():this.getAliasIdentifier()}getFullOutputName(){return this.parent?this.parent.getFullOutputName()+(0,Ue.getIdentifier)(this.fieldDef)+".":""}needsSymetricCalculation(e){const n=this.getJoinableParent().getIdentifier(),r=e.root().joins.get(n);if(r)return!r.leafiest;throw new Error(`Join ${n} not found in result set`)}unnestWithNumbers(){return this.dialect.unnestWithNumbers&&this.fieldDef.structRelationship.type==="nested"}getJoinableParent(){if(this.fieldDef.structRelationship.type==="inline"){if(this.parent)return this.parent.getJoinableParent();throw new Error("Internal Error: inline struct cannot be root")}return this}addFieldToNameMap(e,n){if(this.nameMap.has(e))throw new Error(`Redefinition of ${e}`);this.nameMap.set(e,n)}getPrimaryKeyField(e){let n;if(n=this.primaryKey())return n;throw new Error(`Missing primary key for ${e}`)}resolveQueryFields(){if(this.fieldDef.structSource.type==="query"){const e=this.model.loadQuery(this.fieldDef.structSource.query,void 0).structs.pop();if(!e)throw new Error("Internal Error, query didn't produce a struct");const n={...this.fieldDef};for(const r of e.fields){let i;this.nameMap.has(i=(0,Ue.getIdentifier)(r))||(n.fields.push(r),this.nameMap.set(i,this.makeQueryField(r)))}this.fieldDef=n,!this.fieldDef.primaryKey&&e.primaryKey&&(this.fieldDef.primaryKey=e.primaryKey)}for(const[,e]of this.nameMap)e instanceof zr&&e.resolveQueryFields()}getModel(){if(this.model)return this.model;if(this.parent===void 0)throw new Error("Expected this query struct to have a parent, as no model was present.");return this.parent.getModel()}setParent(e){"struct"in e&&(this.parent=e.struct),"model"in e?this.model=e.model:this.model=this.getModel()}makeQueryField(e){switch(e.type){case"string":return new Khe(e,this);case"date":return new tF(e,this);case"timestamp":return new nF(e,this);case"number":return new Xhe(e,this);case"boolean":return new eF(e,this);case"json":return new Jhe(e,this);case"sql native":return new Zhe(e,this);case"turtle":return new VM(e,this);default:throw new Error(`unknown field definition ${JSON.stringify(e)}`)}}structSourceSQL(e){switch(this.fieldDef.structSource.type){case"table":{const n=this.fieldDef.structSource.tablePath;return this.dialect.quoteTablePath(n)}case"sql":if(this.fieldDef.structSource.method==="nested"||this.fieldDef.structSource.method==="lastStage")return this.fieldDef.name;if(this.fieldDef.structSource.method==="subquery")return`(${this.fieldDef.structSource.sqlBlock.selectStr})`;throw new Error("Internal Error: Unknown structSource type 'sql' method");case"nested":return"UNNEST(this.fieldDef.name)";case"inline":return"";case"query":{const n=(0,Ue.getIdentifier)(this.fieldDef);if(n.includes("cache")){const r=new Sg(!0,e);return this.model.loadQuery(this.fieldDef.structSource.query,r,!1,!1),r.addPDT(n,this.dialect)}else return this.model.loadQuery(this.fieldDef.structSource.query,e,!1,!0).lastStageName}default:throw new Error(`unknown structSource ${this.fieldDef}`)}}root(){return this.parent===void 0?this:this.parent.root()}primaryKey(){if(this.fieldDef.primaryKey)return this.getDimensionByName([this.fieldDef.primaryKey])}getChildByName(e){return this.nameMap.get(e)}getFieldByName(e){return e.reduce((n,r)=>{const i=n.getChildByName(r);if(i===void 0)throw new Error(e.length===1?`'${r}' not found`:`'${r}' not found in '${e.join(".")}'`);return i},this)}getQueryFieldByName(e){const n=this.getFieldByName(e);if(n instanceof zr)throw new Error(`Cannot reference ${e} as a scalar'`);return n}getQueryFieldReference(e,n){const r=this.getQueryFieldByName(e);if(n){const i={...r.fieldDef};i.annotation=n,r.fieldDef=i}return r}getDimensionOrMeasureByName(e){const n=this.getFieldByName(e);if(n instanceof Hr)return n;throw new Error(`${e} is not of type a scalar'`)}getDimensionByName(e){const n=this.getFieldByName(e);if(n instanceof Hr&&Or(n))return n;throw new Error(`${e} is not of type a scalar'`)}getStructByName(e){const n=this.getFieldByName(e);if(n instanceof zr)return n;throw new Error(`Error: Path to structure not found '${e.join(".")}'`)}getDistinctKey(){if(this.fieldDef.structRelationship.type!=="inline")return this.getDimensionByName(["__distinct_key"]);if(this.parent)return this.parent.getDistinctKey();throw new Error("Internal Error. inline struct can not be top level")}applyStructFiltersToTurtleDef(e){let n=e.pipeline;const r=e.annotation,i=e.filterList||[];return n=structuredClone(n),n[0].filterList=i.concat(n[0].filterList||[],this.fieldDef.filterList||[]),{type:"turtle",name:e.name,pipeline:n,annotation:r,location:e.location}}}class YM{constructor(e){this.dialect=new Whe.StandardSQLDialect,this.modelDef=void 0,this.structs=new Map,this.exploreSearchSQLMap=new Map,e&&this.loadModelFromDef(e)}loadModelFromDef(e){this.modelDef=e;for(const n of Object.values(this.modelDef.contents)){let r;if(n.type==="struct")r=new zr(n,void 0,{model:this}),this.structs.set((0,Ue.getIdentifier)(n),r),r.resolveQueryFields();else if(n.type!=="query")throw new Error("Internal Error: Unknown structure type")}}getStructByName(e){let n;if(n=this.structs.get(e))return n;throw new Error(`Struct ${e} not found in model.`)}getStructFromRef(e,n){var r;let i;if(typeof e=="string"){const s=this.getStructByName(e);return n!==void 0?new zr(s.fieldDef,n,(r=s.parent)!==null&&r!==void 0?r:{model:this}):s}else if(e.type==="struct")i=e;else throw new Error("Broken for now");return new zr(i,n,{model:this})}loadQuery(e,n,r=!1,i=!1){const s="";n||(n=new Sg(!0,void 0));const o={type:"turtle",name:"ignoreme",pipeline:e.pipeline,filterList:e.filterList},u=eo.makeQuery(o,this.getStructFromRef(e.structRef,e.sourceArguments),n,i),a=u.generateSQLFromPipeline(n);if(r&&u.parent.dialect.hasFinalStage){const l=(0,Ue.getPhysicalFields)(a.outputStruct).map(c=>u.parent.dialect.sqlMaybeQuoteIdentifier(c.name));a.lastStageName=n.addStage(u.parent.dialect.sqlFinalStage(a.lastStageName,l))}return{lastStageName:a.lastStageName,malloy:s,stageWriter:n,structs:[a.outputStruct],connectionName:u.parent.connectionName}}compileQuery(e,n=!0){const i=this.loadQuery(e,void 0,n,!1),s=typeof e.structRef=="string"?e.structRef:e.structRef.type==="struct"?e.structRef.as||e.structRef.name:"(need to figure this out)";return n&&this.dialect.hasFinalStage&&(i.lastStageName=i.stageWriter.addStage(this.dialect.sqlFinalStage(i.lastStageName,[]))),{lastStageName:i.lastStageName,malloy:i.malloy,sql:i.stageWriter.generateSQLStages(),structs:i.structs,sourceExplore:s,sourceFilters:e.filterList,queryName:e.name,connectionName:i.connectionName,annotation:e.annotation}}async searchIndex(e,n,r,i=1e3,s=void 0){if(!e.canPersist())return;const o=this.getStructByName(n);let u=[];for(const[y,E]of o.nameMap)E instanceof zr||Or(E)&&E.includeInWildcard()&&u.push({type:"fieldref",path:[y]});u=u.sort((y,E)=>y.path[0].localeCompare(E.path[0]));const a={structRef:n,pipeline:[{type:"index",indexFields:u,sample:o.dialect.defaultSampling}]},l=o.dialect.sqlMaybeQuoteIdentifier("fieldName"),c=o.dialect.sqlMaybeQuoteIdentifier("fieldPath"),f=o.dialect.sqlMaybeQuoteIdentifier("fieldValue"),x=o.dialect.sqlMaybeQuoteIdentifier("fieldType"),h=o.dialect.sqlMaybeQuoteIdentifier("weight");let p=this.exploreSearchSQLMap.get(n);p===void 0&&(p=this.compileQuery(a,!1).sql,this.exploreSearchSQLMap.set(n,p));let m=`SELECT
|
|
377
|
+
`)),this.resultStage}getResultStructDef(){const e={type:"struct",name:this.resultStage||"result",dialect:this.parent.fieldDef.dialect,fields:[{type:"string",name:"fieldName"},{type:"string",name:"fieldPath"},{type:"string",name:"fieldValue"},{type:"string",name:"fieldType"},{type:"number",name:"weight",numberType:"integer"}],structRelationship:{type:"basetable",connectionName:this.parent.connectionName},structSource:{type:"query_result"}};return this.parent.fieldDef.modelAnnotation&&(e.modelAnnotation=this.parent.fieldDef.modelAnnotation),e}}class zr extends zM{constructor(e,n,r){if(super(e),this.sourceArguments=n,this.nameMap=new Map,this._arguments=void 0,this.setParent(r),"model"in r)if(this.model=r.model,this.pathAliasMap=new Map,e.structRelationship.type==="basetable")this.connectionName=e.structRelationship.connectionName;else throw new Error("All root StructDefs should be a baseTable");else this.model=this.getModel(),this.pathAliasMap=this.root().pathAliasMap,this.connectionName=this.root().connectionName;this.fieldDef=e,this.dialect=(0,Ghe.getDialect)(this.fieldDef.dialect),this.addFieldsFromFieldList(this.fieldDef.fields)}resolveParentParameterReferences(e){return{...e,value:e.value===null?null:(0,lr.exprMap)(e.value,n=>{if(typeof n=="string")return[n];if(n.type==="parameter"){if(this.parent===void 0)throw new Error("No parent from which to retrieve parameter value");const r=this.parent.arguments()[n.path[0]],i=this.parent.resolveParentParameterReferences(r);if(i.value===null)throw new Error("Invalid parameter value");return i.value}return[n]})}}arguments(){var e;if(this._arguments!==void 0)return this._arguments;this._arguments={};const n=(e=this.fieldDef.parameters)!==null&&e!==void 0?e:{};for(const i in n)this._arguments[i]=n[i];const r={...this.fieldDef.arguments,...this.sourceArguments};for(const i in r){const s=r[i];this._arguments[i]=this.resolveParentParameterReferences(s)}return this._arguments}addFieldsFromFieldList(e){for(const n of e){const r=(0,Ue.getIdentifier)(n);switch(n.type){case"struct":{this.addFieldToNameMap(r,new zr(n,void 0,{struct:this}));break}case"turtle":{this.addFieldToNameMap(r,eo.makeQuery(n,this,void 0,!1));break}default:this.addFieldToNameMap(r,this.makeQueryField(n))}}this.nameMap.has("__distinct_key")||this.addFieldToNameMap("__distinct_key",new tpe({type:"string",name:"__distinct_key"},this))}getAliasIdentifier(){const e=this.getFullOutputName(),n=this.pathAliasMap.get(e);if(n===void 0){const r=Array.from(this.pathAliasMap.values()),i=Vhe((0,Ue.getIdentifier)(this.fieldDef));let s=`${i}_0`,o=1;for(;r.includes(s)&&o<1e3;)o++,s=`${i}_${o}`;if(o<1e3)return this.pathAliasMap.set(e,s),s;throw new Error("Internal Error: cannot create unique alias name")}else return n}getSQLIdentifier(){return this.unnestWithNumbers()&&this.parent!==void 0?this.parent.getSQLIdentifier()+"."+(0,Ue.getIdentifier)(this.fieldDef)+`[${this.getIdentifier()}.__row_id]`:this.getIdentifier()}getIdentifier(){return this.fieldDef.structRelationship.type==="basetable"?"base":this.fieldDef.structRelationship.type==="inline"&&this.parent?this.parent.getSQLIdentifier()+"."+super.getIdentifier():this.getAliasIdentifier()}getFullOutputName(){return this.parent?this.parent.getFullOutputName()+(0,Ue.getIdentifier)(this.fieldDef)+".":""}needsSymetricCalculation(e){const n=this.getJoinableParent().getIdentifier(),r=e.root().joins.get(n);if(r)return!r.leafiest;throw new Error(`Join ${n} not found in result set`)}unnestWithNumbers(){return this.dialect.unnestWithNumbers&&this.fieldDef.structRelationship.type==="nested"}getJoinableParent(){if(this.fieldDef.structRelationship.type==="inline"){if(this.parent)return this.parent.getJoinableParent();throw new Error("Internal Error: inline struct cannot be root")}return this}addFieldToNameMap(e,n){if(this.nameMap.has(e))throw new Error(`Redefinition of ${e}`);this.nameMap.set(e,n)}getPrimaryKeyField(e){let n;if(n=this.primaryKey())return n;throw new Error(`Missing primary key for ${e}`)}resolveQueryFields(){if(this.fieldDef.structSource.type==="query"){const e=this.model.loadQuery(this.fieldDef.structSource.query,void 0).structs.pop();if(!e)throw new Error("Internal Error, query didn't produce a struct");const n={...this.fieldDef};for(const r of e.fields){let i;this.nameMap.has(i=(0,Ue.getIdentifier)(r))||(n.fields.push(r),this.nameMap.set(i,this.makeQueryField(r)))}this.fieldDef=n,!this.fieldDef.primaryKey&&e.primaryKey&&(this.fieldDef.primaryKey=e.primaryKey)}for(const[,e]of this.nameMap)e instanceof zr&&e.resolveQueryFields()}getModel(){if(this.model)return this.model;if(this.parent===void 0)throw new Error("Expected this query struct to have a parent, as no model was present.");return this.parent.getModel()}setParent(e){"struct"in e&&(this.parent=e.struct),"model"in e?this.model=e.model:this.model=this.getModel()}makeQueryField(e){switch(e.type){case"string":return new Khe(e,this);case"date":return new tF(e,this);case"timestamp":return new nF(e,this);case"number":return new Xhe(e,this);case"boolean":return new eF(e,this);case"json":return new Jhe(e,this);case"sql native":return new Zhe(e,this);case"turtle":return new VM(e,this);default:throw new Error(`unknown field definition ${JSON.stringify(e)}`)}}structSourceSQL(e){switch(this.fieldDef.structSource.type){case"table":{const n=this.fieldDef.structSource.tablePath;return this.dialect.quoteTablePath(n)}case"sql":if(this.fieldDef.structSource.method==="nested"||this.fieldDef.structSource.method==="lastStage")return this.fieldDef.name;if(this.fieldDef.structSource.method==="subquery")return`(${this.fieldDef.structSource.sqlBlock.selectStr})`;throw new Error("Internal Error: Unknown structSource type 'sql' method");case"nested":return"UNNEST(this.fieldDef.name)";case"inline":return"";case"query":{const n=(0,Ue.getIdentifier)(this.fieldDef);if(n.includes("cache")){const r=new Sg(!0,e);return this.model.loadQuery(this.fieldDef.structSource.query,r,!1,!1),r.addPDT(n,this.dialect)}else return this.model.loadQuery(this.fieldDef.structSource.query,e,!1,!0).lastStageName}default:throw new Error(`unknown structSource ${this.fieldDef}`)}}root(){return this.parent===void 0?this:this.parent.root()}primaryKey(){if(this.fieldDef.primaryKey)return this.getDimensionByName([this.fieldDef.primaryKey])}getChildByName(e){return this.nameMap.get(e)}getFieldByName(e){return e.reduce((n,r)=>{const i=n.getChildByName(r);if(i===void 0)throw new Error(e.length===1?`'${r}' not found`:`'${r}' not found in '${e.join(".")}'`);return i},this)}getQueryFieldByName(e){const n=this.getFieldByName(e);if(n instanceof zr)throw new Error(`Cannot reference ${e} as a scalar'`);return n}getQueryFieldReference(e,n){const r=this.getQueryFieldByName(e);if(n){const i={...r.fieldDef};i.annotation=n,r.fieldDef=i}return r}getDimensionOrMeasureByName(e){const n=this.getFieldByName(e);if(n instanceof Hr)return n;throw new Error(`${e} is not of type a scalar'`)}getDimensionByName(e){const n=this.getFieldByName(e);if(n instanceof Hr&&Or(n))return n;throw new Error(`${e} is not of type a scalar'`)}getStructByName(e){const n=this.getFieldByName(e);if(n instanceof zr)return n;throw new Error(`Error: Path to structure not found '${e.join(".")}'`)}getDistinctKey(){if(this.fieldDef.structRelationship.type!=="inline")return this.getDimensionByName(["__distinct_key"]);if(this.parent)return this.parent.getDistinctKey();throw new Error("Internal Error. inline struct can not be top level")}applyStructFiltersToTurtleDef(e){let n=e.pipeline;const r=e.annotation,i=e.filterList||[];return n=structuredClone(n),n[0].filterList=i.concat(n[0].filterList||[],this.fieldDef.filterList||[]),{type:"turtle",name:e.name,pipeline:n,annotation:r,location:e.location}}}class YM{constructor(e){this.dialect=new Whe.StandardSQLDialect,this.modelDef=void 0,this.structs=new Map,this.exploreSearchSQLMap=new Map,e&&this.loadModelFromDef(e)}loadModelFromDef(e){this.modelDef=e;for(const n of Object.values(this.modelDef.contents)){let r;if(n.type==="struct")r=new zr(n,void 0,{model:this}),this.structs.set((0,Ue.getIdentifier)(n),r),r.resolveQueryFields();else if(n.type!=="query")throw new Error("Internal Error: Unknown structure type")}}getStructByName(e){let n;if(n=this.structs.get(e))return n;throw new Error(`Struct ${e} not found in model.`)}getStructFromRef(e,n){var r;let i;if(typeof e=="string"){const s=this.getStructByName(e);return n!==void 0?new zr(s.fieldDef,n,(r=s.parent)!==null&&r!==void 0?r:{model:this}):s}else if(e.type==="struct")i=e;else throw new Error("Broken for now");return new zr(i,n,{model:this})}loadQuery(e,n,r=!1,i=!1){const s="";n||(n=new Sg(!0,void 0));const o={type:"turtle",name:"ignoreme",pipeline:e.pipeline,filterList:e.filterList},u=eo.makeQuery(o,this.getStructFromRef(e.structRef,e.sourceArguments),n,i),a=u.generateSQLFromPipeline(n);if(r&&u.parent.dialect.hasFinalStage){const l=(0,Ue.getPhysicalFields)(a.outputStruct).map(c=>u.parent.dialect.sqlMaybeQuoteIdentifier(c.name));a.lastStageName=n.addStage(u.parent.dialect.sqlFinalStage(a.lastStageName,l))}return{lastStageName:a.lastStageName,malloy:s,stageWriter:n,structs:[a.outputStruct],connectionName:u.parent.connectionName}}compileQuery(e,n=!0){const i=this.loadQuery(e,void 0,n,!1),s=typeof e.structRef=="string"?e.structRef:e.structRef.type==="struct"?e.structRef.as||e.structRef.name:"(need to figure this out)";return n&&this.dialect.hasFinalStage&&(i.lastStageName=i.stageWriter.addStage(this.dialect.sqlFinalStage(i.lastStageName,[]))),{lastStageName:i.lastStageName,malloy:i.malloy,sql:i.stageWriter.generateSQLStages(),structs:i.structs,sourceExplore:s,sourceFilters:e.filterList,queryName:e.name,connectionName:i.connectionName,annotation:e.annotation}}async searchIndex(e,n,r,i=1e3,s=void 0){if(!e.canPersist())return;const o=this.getStructByName(n);let u=[];for(const[y,E]of o.nameMap)E instanceof zr||Or(E)&&E.includeInWildcard()&&u.push({type:"fieldref",path:[y]});u=u.sort((y,E)=>y.path[0].localeCompare(E.path[0]));const a={structRef:n,pipeline:[{type:"index",indexFields:u,sample:o.dialect.defaultSampling}]},l=o.dialect.sqlMaybeQuoteIdentifier("fieldName"),c=o.dialect.sqlMaybeQuoteIdentifier("fieldPath"),f=o.dialect.sqlMaybeQuoteIdentifier("fieldValue"),x=o.dialect.sqlMaybeQuoteIdentifier("fieldType"),h=o.dialect.sqlMaybeQuoteIdentifier("weight");let p=this.exploreSearchSQLMap.get(n);p===void 0&&(p=this.compileQuery(a,!1).sql,this.exploreSearchSQLMap.set(n,p));let m=`SELECT
|
|
378
378
|
${l},
|
|
379
379
|
${c},
|
|
380
380
|
${f},
|
|
@@ -1296,7 +1296,7 @@ ${r} ${s}: [`,o.length>0&&(i+=`
|
|
|
1296
1296
|
`+o.map(u=>u.stringify("",n+4)).join(`
|
|
1297
1297
|
`)+`
|
|
1298
1298
|
${r} `),i+="]")}return i}*walk(){for(const e of Object.keys(this.children)){const n=this.children[e];if(n instanceof Gu)yield n;else for(const r of n)yield r}}varInfo(){let e="";for(const[n,r]of Object.entries(this))n!=="elementType"&&(typeof r=="boolean"?e+=r?` ${n}`:` !${n}`:(typeof r=="string"||typeof r=="number")&&(e+=` ${n}=${r}`));return e}internalError(e){return this.log(`INTERNAL ERROR IN TRANSLATION: ${e}`),new Error(e)}needs(e){for(const n of this.walk()){const r=n.needs(e);if(r)return r}}inExperiment(e,n=!1){var r;const i=(r=this.translator())===null||r===void 0?void 0:r.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(n||this.log(`Experimental flag '${e}' is not set, feature not available`),!1)}}Ve.MalloyElement=Gu;class sEe extends Gu{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}}Ve.Unimplemented=sEe;class N4 extends Gu{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}}Ve.ModelEntryReference=N4;class oEe extends Gu{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}}Ve.ExperimentalExperiment=oEe;function cz(t){return t.execute!==void 0}Ve.isDocStatement=cz;function uEe(t){return t instanceof S1||cz(t)}Ve.isDocStatementOrDocStatementList=uEe;class fz extends Gu{constructor(e){super(),this.elements=e,this.newContents()}newContents(){this.has({listOf:this.elements})}get list(){return this.elements}empty(){return this.elements.length===0}notEmpty(){return this.elements.length>0}push(...e){return this.elements.push(...e),this.newContents(),this.elements}needs(e){for(const n of this.elements){const r=n.needs(e);if(r)return r}}}Ve.ListOf=fz;class S1 extends fz{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=lz.extendNoteMethod,this.noteCursor=0}executeList(e){for(;this.execCursor<this.elements.length;){const n=this.elements[this.execCursor];if(this.noteCursor===this.execCursor&&(this.note&&(0,lz.isNoteable)(n)&&n.extendNote(this.note),this.noteCursor+=1),n instanceof S1){const r=n.executeList(e);if(r)return r}else{const r=n.needs(e);if(r)return r;n.execute(e)}this.execCursor+=1}}}Ve.DocStatementList=S1;const aEe="5a79a191-06bc-43cf-9b12-58741cd82970";function xz(t){const e=t.inherits?xz(t.inherits):[];return t.blockNotes&&e.push(...t.blockNotes.map(n=>n.text)),t.notes&&e.push(...t.notes.map(n=>n.text)),e}function lEe(t){const e=xz(t).join("");return(0,iEe.v5)(e,aEe)}class D4 extends Gu{constructor(e){super(),this.elementType="document",this.globalNameSpace=new rEe.GlobalNameSpace,this.documentModel={},this.queryList=[],this.sqlBlocks=[],this.didInitModel=!1,this.annotation={},this.experiments=new nEe.Tag({}),this.modelAnnotationTodoList=[],this.statements=new S1(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(const[n,r]of Object.entries(e.contents)){const i=structuredClone(r);if(i.type==="struct"||i.type==="query"||i.type==="function"){const s=e.exports.includes(n);this.setEntry(n,{entry:i,exported:s})}}}this.didInitModel=!0}}compile(){const e=this.statements.executeList(this),n=this.modelDef();if(e===void 0){for(const i of this.queryList)i.modelAnnotation===void 0&&n.annotation&&(i.modelAnnotation=n.annotation);for(const i of this.sqlBlocks)i.modelAnnotation===void 0&&n.annotation&&(i.modelAnnotation=n.annotation)}if(n.annotation)for(const i of this.modelAnnotationTodoList)i.modelAnnotation||(i.modelAnnotation=n.annotation);return{modelDef:n,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()){const e={...this.annotation,id:""};return e.id=lEe(e),e}}modelDef(){const e={name:"",exports:[],contents:{}};this.hasAnnotation()&&(e.annotation=this.currentModelAnnotation());for(const n in this.documentModel){const r=this.documentModel[n].entry;if(r.type==="struct"||r.type==="query"){this.documentModel[n].exported&&e.exports.push(n);const i=structuredClone(r);i.modelAnnotation===void 0&&e.annotation&&(i.modelAnnotation=e.annotation),e.contents[n]=i}}return e}defineSQL(e,n){const r={...e,as:`$${this.sqlBlocks.length}`,declaredSQLBlock:!0};if(n){if(this.getEntry(n))return!1;r.as=n,this.setEntry(n,{entry:r})}return this.sqlBlocks.push(r),!0}getEntry(e){var n;return(n=this.globalNameSpace.getEntry(e))!==null&&n!==void 0?n:this.documentModel[e]}setEntry(e,n){this.globalNameSpace.getEntry(e)!==void 0&&this.log(`Cannot redefine '${e}', which is in global namespace`),n.entry.type==="struct"&&this.checkExperimentalDialect(this,n.entry.dialect),this.documentModel[e]=n}checkExperimentalDialect(e,n){const r=this.translator();r&&r.firstReferenceToDialect(n)&&(0,eEe.getDialect)(n).experimental&&!r.experimentalDialectEnabled(n)&&e.log(`Requires compiler flag '##! experimental.dialect.${n}'`,"error")}}Ve.Document=D4;var q_={},Jh={},Kr={},F0={};Object.defineProperty(F0,"__esModule",{value:!0}),F0.canMakeEntry=F0.SpaceEntry=void 0;class cEe{}F0.SpaceEntry=cEe;function fEe(t){return"makeEntry"in t}F0.canMakeEntry=fEe,Object.defineProperty(Kr,"__esModule",{value:!0}),Kr.SpaceField=void 0;const xEe=Z,dEe=F0;class hEe extends dEe.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){const n={dataType:e.type,expressionType:"scalar",evalSpace:"input"};return(0,xEe.isFieldTypeDef)(e)&&e.expressionType&&(n.expressionType=e.expressionType),n.dataType==="sql native"&&e.type==="sql native"&&e.rawType&&(n.rawType=e.rawType),n}getQueryFieldDef(e){}fieldDef(){}}Kr.SpaceField=hEe,Object.defineProperty(Jh,"__esModule",{value:!0}),Jh.ViewField=void 0;const pEe=Kr;class gEe extends pEe.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){return{dataType:"turtle",expressionType:"scalar",evalSpace:"input"}}}Jh.ViewField=gEe,Object.defineProperty(q_,"__esModule",{value:!0}),q_.ASTViewField=void 0;const mEe=Jh;class yEe extends mEe.ViewField{constructor(e,n,r){super(e),this.view=n,this.name=r}getQueryFieldDef(e){return this.view.getFieldDef(e)}fieldDef(){return this.view.getFieldDef(this.inSpace)}}q_.ASTViewField=yEe,Object.defineProperty(g1,"__esModule",{value:!0}),g1.ViewFieldDeclaration=void 0;const EEe=Ve,AEe=Yr,SEe=Yh,vEe=q_;class _Ee extends EEe.MalloyElement{constructor(e,n){super({view:n}),this.name=e,this.view=n,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=AEe.extendNoteMethod}makeEntry(e){const n=new vEe.ASTViewField(e,this,this.name);e.newEntry(this.name,this,n)}getFieldDef(e){const{pipeline:n,annotation:r}=this.view.pipelineComp(e),i=(0,SEe.detectAndRemovePartialStages)(n,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:r},location:this.location}}}g1.ViewFieldDeclaration=_Ee;var Rn={};Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.LegalRefinementStage=Rn.QueryClass=void 0;var dz;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(dz||(Rn.QueryClass=dz={}));var hz;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(hz||(Rn.LegalRefinementStage=hz={})),Object.defineProperty(p1,"__esModule",{value:!0}),p1.NestFieldDeclaration=void 0;const CEe=Yh,bEe=g1,pz=Rn;class TEe extends bEe.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=pz.LegalRefinementStage.Single,this.forceQueryClass=pz.QueryClass.Grouping}queryExecute(e){e.resultFS.pushFields(this)}getFieldDef(e){if(e.isQueryFieldSpace()){const{pipeline:n,annotation:r}=this.view.pipelineComp(e,e.outputSpace()),i=(0,CEe.detectAndRemovePartialStages)(n,this);return{type:"turtle",name:this.name,pipeline:i,annotation:{...this.note,inherits:r},location:this.location}}throw this.internalError("Unexpected namespace for nest")}}p1.NestFieldDeclaration=TEe;var Zh={},Xr={};Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.ErrorFactory=void 0;const gz={type:"struct",name:"~malformed~",dialect:"~malformed~",structSource:{type:"table",tablePath:"//undefined_error_table_path"},structRelationship:{type:"basetable",connectionName:"//undefined_error_connection"},fields:[]};class F4{static get structDef(){return{...gz}}static isErrorStructDef(e){return e.name.includes(gz.name)}static get query(){return{structRef:F4.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}}Xr.ErrorFactory=F4,Object.defineProperty(Zh,"__esModule",{value:!0}),Zh.DefineSourceList=Zh.DefineSource=void 0;const REe=Xr,mz=Ve,OEe=Yr;class NEe extends mz.MalloyElement{constructor(e,n,r,i){super(),this.name=e,this.sourceExpr=n,this.exported=r,this.parameters=i,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=OEe.extendNoteMethod,n&&this.has({sourceExpr:n}),i&&this.has({parameters:i})}execute(e){var n;if(e.modelEntry(this.name))this.log(`Cannot redefine '${this.name}'`);else{const r=(n=this.sourceExpr)===null||n===void 0?void 0:n.getSource();if(r===void 0)return;const i=this.deduplicatedParameters(),s=r.withParameters(void 0,this.parameters);if(this.validateParameterShadowing(i,s),REe.ErrorFactory.isErrorStructDef(s))return;const o={...s,as:this.name,location:this.location};this.note&&(o.annotation=s.annotation?{...this.note,inherits:s.annotation}:this.note),e.setEntry(this.name,{entry:o,exported:this.exported})}}deduplicatedParameters(){if(this.parameters===void 0)return[];const e={},n=[];for(const r of this.parameters)r.name in e&&r.log(`Cannot redefine parameter \`${r.name}\``),e[r.name]=!0,n.push(r);return n}validateParameterShadowing(e,n){for(const r of e)n.fields.find(i=>{var s;return((s=i.as)!==null&&s!==void 0?s:i.name)===r.name})&&r.log(`Illegal shadowing of field \`${r.name}\` by parameter with the same name`)}}Zh.DefineSource=NEe;class DEe extends mz.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}}Zh.DefineSourceList=DEe;var ep={};Object.defineProperty(ep,"__esModule",{value:!0}),ep.DefineQueryList=ep.DefineQuery=void 0;const yz=Ve,FEe=Yr;class wEe extends yz.MalloyElement{constructor(e,n){super({queryExpr:n}),this.name=e,this.queryExpr=n,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=FEe.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.log(`'${this.name}' is already defined, cannot redefine`);return}const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("Cannot define a query from this expression");return}const i={...r.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})}}ep.DefineQuery=wEe;class LEe extends yz.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}}ep.DefineQueryList=LEe;var Uo={};Object.defineProperty(Uo,"__esModule",{value:!0}),Uo.Source=void 0;const IEe=Ve;class $Ee extends IEe.MalloyElement{structRef(e){return{structRef:this.structDef(e)}}packParameters(e){if(e===void 0)return;const n={};for(const r of e){const i=r.parameter();n[i.name]=i}return n}withParameters(e,n){return{...this.structDef(e),parameters:this.packParameters(n)}}}Uo.Source=$Ee;var v1={},tp={},H_={},w0={};Object.defineProperty(w0,"__esModule",{value:!0}),w0.mergeFields=w0.nameFromDef=void 0;function w4(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}w0.nameFromDef=w4;function BEe(t,e){if(t===void 0)return e;const n=new Set(e.map(i=>w4(i))),r=t.filter(i=>!n.has(w4(i)));return r.push(...e),r}w0.mergeFields=BEe;var _1={},Jr={},Wu={};Object.defineProperty(Wu,"__esModule",{value:!0}),Wu.DefinedParameter=Wu.AbstractParameter=Wu.SpaceParam=void 0;const kEe=F0;class L4 extends kEe.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}}Wu.SpaceParam=L4;class PEe extends L4{constructor(e){super(),this.astParam=e,this._parameter=void 0}parameter(){return this._parameter!==void 0?this._parameter:(this._parameter=this.astParam.parameter(),this._parameter)}typeDesc(){var e;return{dataType:(e=this.parameter().type)!==null&&e!==void 0?e:"error",expressionType:"scalar",evalSpace:"constant"}}}Wu.AbstractParameter=PEe;class MEe extends L4{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){return{dataType:this.paramDef.type,expressionType:"scalar",evalSpace:"input"}}}Wu.DefinedParameter=MEe;var ax={};Object.defineProperty(ax,"__esModule",{value:!0}),ax.StructSpaceFieldBase=void 0;const jEe=Kr;class UEe extends jEe.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"}}}ax.StructSpaceFieldBase=UEe;var C1={};Object.defineProperty(C1,"__esModule",{value:!0}),C1.ColumnSpaceField=void 0;const qEe=Kr;class HEe extends qEe.SpaceField{constructor(e){super(),this.haveFieldDef=e}fieldDef(){return this.haveFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.haveFieldDef)}}C1.ColumnSpaceField=HEe;var z_={};Object.defineProperty(z_,"__esModule",{value:!0}),z_.IRViewField=void 0;const zEe=Jh;class QEe extends zEe.ViewField{constructor(e,n){super(e),this.turtleDef=n,this.haveFieldDef=n}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}}z_.IRViewField=QEe,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.StructSpaceField=Jr.StaticSpace=void 0;const GEe=Tu,WEe=Z,VEe=Wu,YEe=Kr,Q_=ax,KEe=C1,XEe=z_;class Ez{constructor(e){this.type="fieldSpace",this.fromStruct=e}dialectObj(){try{return(0,GEe.getDialect)(this.fromStruct.dialect)}catch{return}}defToSpaceField(e){return e.type==="struct"?new Az(e):(0,WEe.isTurtleDef)(e)?new XEe.IRViewField(this,e):new KEe.ColumnSpaceField(e)}get map(){if(this.memoMap===void 0){this.memoMap={};for(const e of this.fromStruct.fields){const n=e.as||e.name;this.memoMap[n]=this.defToSpaceField(e)}if(this.fromStruct.parameters)for(const[e,n]of Object.entries(this.fromStruct.parameters))e in this.memoMap||(this.memoMap[e]=new VEe.DefinedParameter(n))}return this.memoMap}dropEntries(){this.memoMap={}}dropEntry(e){delete this.map[e]}entry(e){return this.map[e]}setEntry(e,n){this.map[e]=n}entries(){return Object.entries(this.map)}structDef(){return this.fromStruct}emptyStructDef(){return{...this.fromStruct,fields:[],parameters:{}}}lookup(e){const n=e[0],r=e.slice(1),i=this.entry(n.refString);if(!i)return{error:`'${n}' is not defined`,found:i};if(i instanceof YEe.SpaceField){const o=i.fieldDef();o&&n.addReference({type:i instanceof Q_.StructSpaceFieldBase?"joinReference":"fieldReference",definition:o,location:n.location,text:n.refString})}const s=i instanceof Q_.StructSpaceFieldBase?[{name:n.refString,structRelationship:i.structRelationship}]:[];if(r.length){if(i instanceof Q_.StructSpaceFieldBase){const o=i.fieldSpace.lookup(r);return o.found?{...o,relationship:[...s,...o.relationship]}:o}return{error:`'${n}' cannot contain a '${r[0]}'`,found:void 0}}return{found:i,error:void 0,relationship:s,isOutputField:!1}}isQueryFieldSpace(){return!1}}Jr.StaticSpace=Ez;class Az extends Q_.StructSpaceFieldBase{constructor(e){super(e)}get fieldSpace(){return new Ez(this.sourceDef)}}Jr.StructSpaceField=Az,Object.defineProperty(_1,"__esModule",{value:!0}),_1.JoinSpaceField=void 0;const JEe=Jr;class ZEe extends JEe.StructSpaceField{constructor(e,n){super(n.structDef(e)),this.parameterSpace=e,this.join=n}}_1.JoinSpaceField=ZEe;var b1={};Object.defineProperty(b1,"__esModule",{value:!0}),b1.SpaceSeed=void 0;const e3e=Jr;function Sz(t){return t.type==="fieldSpace"}class t3e{constructor(e){this.sourceSpec=e,this.spaceSpec=e}get structDef(){return Sz(this.spaceSpec)?(this.asStruct||(this.asStruct=this.spaceSpec.structDef()),this.asStruct):this.spaceSpec}get fieldSpace(){return Sz(this.spaceSpec)?this.spaceSpec:(this.asFS||(this.asFS=new e3e.StaticSpace(this.spaceSpec)),this.asFS)}}b1.SpaceSeed=t3e;var np={};Object.defineProperty(np,"__esModule",{value:!0}),np.ParameterSpace=void 0;const n3e=Wu;class r3e{constructor(e){this.type="fieldSpace",this._map={};for(const n of e)this._map[n.name]=new n3e.AbstractParameter(n)}structDef(){throw new Error("Parameter space does not have a structDef")}emptyStructDef(){throw new Error("Parameter space does not have an emptyStructDef")}entry(e){return this._map[e]}lookup(e){const n=e[0];if(n===void 0)return{error:"Invalid reference",found:void 0};const r=this.entry(n.refString);return r===void 0?{error:`\`${n}\` is not defined`,found:void 0}:e.length>1?{error:`\`${n}\` cannot contain a \`${e.slice(1).join(".")}\``,found:void 0}:{found:r,error:void 0,relationship:[],isOutputField:!1}}entries(){return Object.entries(this._map)}dialectObj(){}isQueryFieldSpace(){return!1}}np.ParameterSpace=r3e,Object.defineProperty(H_,"__esModule",{value:!0}),H_.DynamicSpace=void 0;const i3e=w0,s3e=Xr,o3e=Kr,u3e=_1,a3e=Jh,vz=Wu,l3e=b1,c3e=Jr,f3e=ax,x3e=np;class d3e extends c3e.StaticSpace{constructor(e){const n=new l3e.SpaceSeed(e);super(structuredClone(n.structDef)),this.completions=[],this.complete=!1,this.parameters=[],this.final=void 0,this.source=n}isComplete(){this.complete=!0}setEntry(e,n){if(this.final)throw new Error("Space already final");super.setEntry(e,n)}addParameters(e){for(const n of e)this.entry(n.name)===void 0&&(this.parameters.push(n),this.setEntry(n.name,new vz.AbstractParameter(n)));return this}parameterSpace(){return new x3e.ParameterSpace(this.parameters)}newEntry(e,n,r){if(this.entry(e)){n.log(`Cannot redefine '${e}'`);return}this.setEntry(e,r)}renameEntry(e,n,r){this.dropEntry(e),this.setEntry(n,r)}addFieldDef(e){this.setEntry((0,i3e.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){if(this.final===void 0){const e={};for(const[a,l]of this.entries())l instanceof vz.SpaceParam&&(e[a]=l.parameter());this.final={...this.fromStruct,fields:[],parameters:e};const n=[],r=[],i=[],s=[];for(const[a,l]of this.entries())l instanceof f3e.StructSpaceFieldBase?r.push([a,l]):l instanceof a3e.ViewField?i.push([a,l]):l instanceof o3e.SpaceField&&n.push([a,l]);const o=[...n,...r,...i],u=this.parameterSpace();for(const[,a]of o)if(a instanceof u3e.JoinSpaceField){const l=a.join.structDef(u);s3e.ErrorFactory.isErrorStructDef(l)||(this.final.fields.push(l),s.push([a.join,l]))}else{const l=a.fieldDef();l&&this.final.fields.push(l)}for(const[a,l]of s)a.fixupJoinOn(this,l)}return this.newTimezone&&(this.final.queryTimezone=this.newTimezone),this.isComplete(),this.final}}H_.DynamicSpace=d3e,Object.defineProperty(tp,"__esModule",{value:!0}),tp.RefinedSpace=void 0;const h3e=H_,p3e=F0;class I4 extends h3e.DynamicSpace{static filteredFrom(e,n,r){const i=new I4(e);if(n){const s=n.refs.list,o=i.entries();for(const u of s)o.find(([l])=>l===u.refString)===void 0&&(r!=null&&r.entry(u.refString)?u.log(`Illegal \`${n.edit}:\` of parameter`):u.log(`\`${u.refString}\` is not defined`));i.dropEntries();for(const[u,a]of o){const l=!!s.find(f=>f.refString===u),c=n.edit==="accept";l===c&&i.setEntry(u,a)}}return i}pushFields(...e){for(const n of e)(0,p3e.canMakeEntry)(n)?n.makeEntry(this):n.log(`Internal error, ${n.elementType} not expected in this context`)}}tp.RefinedSpace=I4;var L0={},Os={};Object.defineProperty(Os,"__esModule",{value:!0}),Os.DefinitionList=void 0;const g3e=Ve,_z=Yr;class m3e extends g3e.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,_z.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(const e of this.elements)(0,_z.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}}Os.DefinitionList=m3e,Object.defineProperty(L0,"__esModule",{value:!0}),L0.DeclareFields=void 0;const y3e=Os,E3e=Rn;class A3e extends y3e.DefinitionList{constructor(e){super(e),this.elementType="declareFields",this.queryRefinementStage=E3e.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(const n of this.list)e.inputFS.extendSource(n)}}L0.DeclareFields=A3e;var qo={},an={};Object.defineProperty(an,"__esModule",{value:!0}),an.nullsafeNot=an.compressExpr=an.compose=void 0;const S3e=Z;function Cz(t){return t.length>1?["(",...t,")"]:t.length===0?["__MISSING_VALUE__"]:t}function v3e(t,e,n){const r=e.match(/^[A-Za-z]/),i=t.length===1&&r?" ":"",s=n.length===1&&r?" ":"",o=i+e+s;return[...Cz(t),o,...Cz(n)]}an.compose=v3e;function _3e(t){const e=[];let n;for(const r of t.flat())typeof r=="string"?n=n?n+r:r:(n&&(e.push(n),n=void 0),e.push(r));return n&&e.push(n),e}an.compressExpr=_3e;function C3e(t,e){return e===void 0||e==="!="||e==="!~"?(0,S3e.mkExpr)`COALESCE(NOT(${t}),FALSE)`:t}an.nullsafeNot=C3e,Object.defineProperty(qo,"__esModule",{value:!0}),qo.Filter=qo.FilterElement=void 0;const bz=Z,b3e=an,Tz=Ve,$4=Rn;class T3e extends Tz.MalloyElement{constructor(e,n){super({expr:e}),this.expr=e,this.exprSrc=n,this.elementType="filterElement"}filterExpression(e){const n=this.expr.getExpression(e);return n.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,b3e.compressExpr)(n.value),expressionType:n.expressionType}}}qo.FilterElement=T3e;let R3e=class extends Tz.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=$4.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?$4.LegalRefinementStage.Tail:$4.LegalRefinementStage.Head}getFilterList(e){const n=[];for(const r of this.list){const i=r.filterExpression(e);if(this.havingClause!==void 0){const s=(0,bz.expressionIsAggregate)(i.expressionType),o=(0,bz.expressionIsAnalytic)(i.expressionType);if(this.havingClause){if(o){r.log("Analytic expressions are not allowed in `having:`");continue}}else if(o){r.log("Analytic expressions are not allowed in `where:`");continue}else s&&r.log("Aggregate expressions are not allowed in `where:`; use `having:`")}n.push(i)}return n}};qo.Filter=R3e;var ts={};Object.defineProperty(ts,"__esModule",{value:!0}),ts.Joins=ts.ExpressionJoin=ts.KeyJoin=ts.Join=void 0;const O3e=Z,N3e=an,D3e=_1,F3e=Os,w3e=Ve,L3e=Yr,I3e=Rn,Rz=Xr;class B4 extends w3e.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=L3e.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new D3e.JoinSpaceField(e.parameterSpace(),this))}getStructDefFromExpr(e){const n=this.sourceExpr.getSource();return n?n.structDef(e):(this.sourceExpr.sqLog("Cannot great a source to join from"),Rz.ErrorFactory.structDef)}}ts.Join=B4;class $3e extends B4{constructor(e,n,r){super({name:e,sourceExpr:n,keyExpr:r}),this.name=e,this.sourceExpr=n,this.keyExpr=r,this.elementType="joinOnKey"}structDef(e){var n;const r=this.getStructDefFromExpr(e),i={...r,structRelationship:{type:"one",matrixOperation:"left",onExpression:["('join fixup'='not done yet')"]},location:this.location};return r.structSource.type==="query"?i.name=this.name.refString:i.as=this.name.refString,this.note&&(i.annotation=this.note),(n=this.document())===null||n===void 0||n.rememberToAddModelAnnotations(i),i}fixupJoinOn(e,n){const r=this.keyExpr.getExpression(e);if(n.primaryKey){const i=n.fields.find(s=>(s.as||s.name)===n.primaryKey);if(i)if(i.type===r.dataType){n.structRelationship={type:"one",matrixOperation:"left",onExpression:[{type:"field",path:[this.name.refString,n.primaryKey]},"=",...r.value]};return}else this.log(`join_one: with type mismatch with primary key: ${r.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")}}ts.KeyJoin=$3e;class B3e extends B4{constructor(e,n){super({name:e,sourceExpr:n}),this.name=e,this.sourceExpr=n,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,n){if(this.expr===void 0)return;const r=this.expr.getExpression(e);if(r.dataType!=="boolean"){this.log("join conditions must be boolean expressions");return}const i=n.structRelationship;(0,O3e.isJoinOn)(i)&&(i.onExpression=(0,N3e.compressExpr)(r.value))}structDef(e){var n;const r=this.sourceExpr.getSource();if(!r)return this.sourceExpr.sqLog("Cannot create a source to join from"),Rz.ErrorFactory.structDef;const i=r.structDef(e);let s="left";this.inExperiment("join_types",!0)&&(s=this.matrixOperation);const o={...i,structRelationship:{type:this.joinType,matrixOperation:s},location:this.location};return i.structSource.type==="query"?(o.name=this.name.refString,delete o.as):o.as=this.name.refString,this.note&&(o.annotation=this.note),(n=this.document())===null||n===void 0||n.rememberToAddModelAnnotations(o),o}}ts.ExpressionJoin=B3e;class k3e extends F3e.DefinitionList{constructor(e){super(e),this.elementType="joinList",this.forceQueryClass=void 0,this.queryRefinementStage=I3e.LegalRefinementStage.Single}queryExecute(e){for(const n of this.list)e.inputFS.extendSource(n)}}ts.Joins=k3e;var rp={};Object.defineProperty(rp,"__esModule",{value:!0}),rp.FieldListEdit=void 0;const P3e=Ve;class M3e extends P3e.MalloyElement{constructor(e,n){super({refs:n}),this.edit=e,this.refs=n,this.elementType="fieldListEdit"}}rp.FieldListEdit=M3e;var ip={};Object.defineProperty(ip,"__esModule",{value:!0}),ip.PrimaryKey=void 0;const j3e=Ve;class U3e extends j3e.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}}ip.PrimaryKey=U3e;var sp={};Object.defineProperty(sp,"__esModule",{value:!0}),sp.Views=void 0;const q3e=Os;class H3e extends q3e.DefinitionList{constructor(){super(...arguments),this.elementType="turtleDefList"}}sp.Views=H3e;var op={};Object.defineProperty(op,"__esModule",{value:!0}),op.TimezoneStatement=void 0;const z3e=Ve;class Q3e extends z3e.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)}}op.TimezoneStatement=Q3e;var I0={};Object.defineProperty(I0,"__esModule",{value:!0}),I0.ModelAnnotation=I0.ObjectAnnotation=void 0;const G3e=fl,W3e=Ve;class Oz extends W3e.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}}I0.ObjectAnnotation=Oz;class V3e extends Oz{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,n){const r=G3e.Tag.annotationToTag({notes:this.notes},{prefix:/^##! /,extending:e});return r.log.forEach(i=>n.log(i)),r.tag}execute(e){e.annotation.notes===void 0&&(e.annotation.notes=[]),e.annotation.notes.push(...this.notes)}}I0.ModelAnnotation=V3e;var $0={},G_={};Object.defineProperty(G_,"__esModule",{value:!0}),G_.RenameSpaceField=void 0;const Y3e=Kr;class K3e extends Y3e.SpaceField{constructor(e,n,r){super(),this.otherField=e,this.newName=n,this.location=r}fieldDef(){const e=this.otherField.fieldDef();if(e!==void 0)return{...e,as:this.newName,location:this.location}}typeDesc(){return this.otherField.typeDesc()}}G_.RenameSpaceField=K3e,Object.defineProperty($0,"__esModule",{value:!0}),$0.Renames=$0.RenameField=void 0;const X3e=G_,Nz=Ve,J3e=Kr;class Z3e extends Nz.MalloyElement{constructor(e,n){super(),this.newName=e,this.oldName=n,this.elementType="renameField",this.has({oldName:n})}makeEntry(e){if(this.oldName.refString===this.newName){this.log("Can't rename field to itself");return}const n=this.oldName.getField(e);n.found?n.found instanceof J3e.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new X3e.RenameSpaceField(n.found,this.newName,this.location)):this.log(`'${this.oldName}' cannot be renamed`):this.log(`Can't rename '${this.oldName}', no such field`)}}$0.RenameField=Z3e;class eAe extends Nz.ListOf{constructor(){super(...arguments),this.elementType="renameFields"}}$0.Renames=eAe,Object.defineProperty(v1,"__esModule",{value:!0}),v1.RefinedSource=void 0;const tAe=Z,nAe=tp,rAe=L0,iAe=qo,sAe=ts,oAe=rp,uAe=ip,aAe=sp,lAe=Uo,cAe=op,fAe=I0,xAe=$0,dAe=np;class hAe extends lAe.Source{constructor(e,n){super({source:e,refinement:n}),this.source=e,this.refinement=n,this.elementType="refinedSource"}structDef(e){return this.withParameters(e,[])}withParameters(e,n){var r;let i,s;const o=[],u=[];let a;for(const m of this.refinement.list){if(m instanceof fAe.ObjectAnnotation)continue;const g=m;m instanceof uAe.PrimaryKey?(i&&(i.log("Primary key already defined"),m.log("Primary key redefined")),i=m):m instanceof oAe.FieldListEdit?(s&&(s.log("Too many accept/except statements"),m.log("Too many accept/except statements")),s=m):m instanceof rAe.DeclareFields||m instanceof sAe.Joins||m instanceof aAe.Views||m instanceof xAe.Renames?o.push(...m.list):m instanceof iAe.Filter?u.push(m):m instanceof cAe.TimezoneStatement?a=m.tz:g.log(`Unexpected source property: '${g.elementType}'`)}const l=n?new dAe.ParameterSpace(n):void 0,c=structuredClone(this.source.structDef(l));i&&(c.primaryKey=i.field.name);const f=nAe.RefinedSpace.filteredFrom(c,s,l);if(a&&f.setTimezone(a),n&&f.addParameters(n),f.pushFields(...o),i){const m=i.field.getField(f);m.error&&i.log(m.error)}const x=f.structDef(),h=x.filterList||[];let p=!1;for(const m of u)for(const g of m.list){const y=g.filterExpression(f);(0,tAe.expressionIsCalculation)(y.expressionType)?g.log("Can't use aggregate computations in top level filters"):(h.push(y),p=!0)}return p?{...x,filterList:h}:((r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(x),x)}}v1.RefinedSource=hAe;var Vu={};Object.defineProperty(Vu,"__esModule",{value:!0}),Vu.SourceQueryElement=void 0;const pAe=Ve;class k4 extends pAe.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(const n of this.walk())if(n instanceof k4&&n.errored){e=!1;break}return e}}Vu.SourceQueryElement=k4;var W_={},lx={};Object.defineProperty(lx,"__esModule",{value:!0}),lx.QuerySource=void 0;const gAe=Uo;class mAe extends gAe.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}structDef(e){return this.withParameters(e,void 0)}withParameters(e,n){var r;const i=this.query.queryComp(!1),s={...i.outputStruct,structSource:{type:"query",query:i.query}};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(s),{...s,parameters:this.packParameters(n)}}}lx.QuerySource=mAe;var up={},T1={};Object.defineProperty(T1,"__esModule",{value:!0}),T1.QueryBase=void 0;const yAe=Yh,EAe=Ve;class AAe extends EAe.MalloyElement{query(){const e=this.queryComp(!0).query;return{...e,pipeline:(0,yAe.detectAndRemovePartialStages)(e.pipeline,this)}}}T1.QueryBase=AAe,Object.defineProperty(up,"__esModule",{value:!0}),up.QueryArrow=void 0;const SAe=Z,vAe=Uo,Dz=Jr,_Ae=T1;class CAe extends _Ae.QueryBase{constructor(e,n){super({source:e,view:n}),this.source=e,this.view=n,this.elementType="arrow"}queryComp(e){let n,r,i;if(this.source instanceof vAe.Source){const l=e?this.source.structRef(void 0):{structRef:this.source.structDef(void 0)};r={type:"query",...l,pipeline:[],location:this.location},n=(0,SAe.refIsStructDef)(l.structRef)?l.structRef:this.source.structDef(void 0),i=new Dz.StaticSpace(n)}else{const l=this.source.queryComp(e);r=l.query,n=l.outputStruct,i=new Dz.StaticSpace(l.outputStruct)}const{pipeline:s,annotation:o,outputStruct:u,name:a}=this.view.pipelineComp(i);return{query:{...r,name:a,annotation:o,pipeline:[...r.pipeline,...s]},outputStruct:u,inputStruct:n}}}up.QueryArrow=CAe,Object.defineProperty(W_,"__esModule",{value:!0}),W_.SQArrow=void 0;const bAe=Vu,TAe=lx,RAe=up;class OAe extends bAe.SourceQueryElement{constructor(e,n){super({applyTo:e,operation:n}),this.applyTo=e,this.operation=n,this.elementType="sq-arrow"}getQuery(){const e=this.applyTo.isSource()?this.applyTo.getSource():this.applyTo.getQuery();if(e===void 0){this.sqLog("Could not get LHS of arrow operation");return}const n=new RAe.QueryArrow(e,this.operation);return this.has({query:n}),n}getSource(){const e=this.getQuery();if(!e){this.sqLog("Couldn't comprehend query well enough to make a source");return}const n=new TAe.QuerySource(e);return this.has({asSource:n}),n}}W_.SQArrow=OAe;var V_={},ap={},Ns={};Object.defineProperty(Ns,"__esModule",{value:!0}),Ns.getStructFieldDef=Ns.getFinalStruct=Ns.opOutputStruct=void 0;const NAe=p0,DAe=Cf,P4=Z,Fz=Xr;function wz(t,e,n){const r=Fz.ErrorFactory.isErrorStructDef(e)||(0,P4.structHasErrors)(e);(0,P4.isPartialSegment)(n)&&(n={...n,type:"reduce"});const i=(0,P4.segmentHasErrors)(n);if(!r&&!i)try{return DAe.Segment.nextStructDef(e,n)}catch(s){t.log(`INTERNAL ERROR model/Segment.nextStructDef: ${s.message}
|
|
1299
|
-
QUERY: ${(0,NAe.inspect)(n,{breakLength:72,depth:1/0})}`)}return{...Fz.ErrorFactory.structDef,dialect:e.dialect}}Ns.opOutputStruct=wz;function FAe(t,e,n){for(const r of n)e=wz(t,e,r);return e}Ns.getFinalStruct=FAe;function wAe(t,e){return t.fields.find(n=>(n.as||n.name)===e)}Ns.getStructFieldDef=wAe,Object.defineProperty(ap,"__esModule",{value:!0}),ap.QueryRefine=void 0;const LAe=Jr,IAe=Ns,$Ae=T1;class BAe extends $Ae.QueryBase{constructor(e,n){super({base:e,refinement:n}),this.base=e,this.refinement=n,this.elementType="query-refine"}queryComp(e){const n=this.base.queryComp(e),r=new LAe.StaticSpace(n.inputStruct),i=this.refinement.refine(r,n.query.pipeline,void 0);return{query:{...n.query,pipeline:i},outputStruct:(0,IAe.getFinalStruct)(this.refinement,n.inputStruct,i),inputStruct:n.inputStruct}}}ap.QueryRefine=BAe;var R1={},lp={},On={};Object.defineProperty(On,"__esModule",{value:!0}),On.dateOffset=On.timestampOffset=On.timeResult=On.resolution=On.castDateToTimestamp=On.castTimestampToDate=On.castTo=On.timeOffset=void 0;const kAe=Z,Lz=an;function PAe(t,e,n,r,i){return[{type:"dialect",function:"delta",base:{valueType:t,value:e},op:n,delta:r,units:i}]}On.timeOffset=PAe;function MAe(t,e,n,r=!1){const i={type:"dialect",function:"cast",dstType:t,expr:e,safe:r};return(0,kAe.isAtomicFieldType)(n)&&(i.srcType=n),[i]}On.castTo=MAe;function jAe(t,e=!1){return[{type:"dialect",function:"cast",dstType:"date",srcType:"timestamp",expr:t,safe:e}]}On.castTimestampToDate=jAe;function UAe(t,e=!1){return[{type:"dialect",function:"cast",dstType:"timestamp",srcType:"date",expr:t,safe:e}]}On.castDateToTimestamp=UAe;function qAe(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}On.resolution=qAe;function HAe(t,e){return e?{...t,timeframe:e}:t}On.timeResult=HAe;function zAe(t,e,n,r,i=!1){const s=["week","month","quarter","year"].includes(r),o=e==="+"?"_ADD":"_SUB",u=r.toUpperCase();if(s)return[`TIMESTAMP(DATETIME${o}(DATETIME(`,...t,"),INTERVAL ",...n,` ${u}))`];const a=i?["TIMESTAMP(",...t,")"]:t;return(0,Lz.compressExpr)([`TIMESTAMP${o}(`,...a,",INTERVAL ",...n,` ${u})`])}On.timestampOffset=zAe;function QAe(t,e,n,r){const i=e==="+"?"_ADD":"_SUB",s=r.toUpperCase();return(0,Lz.compressExpr)([`DATE${i}(`,...t,",INTERVAL ",...n,` ${s})`])}On.dateOffset=QAe;var cx={},hr={};Object.defineProperty(hr,"__esModule",{value:!0}),hr.errorFor=void 0;function GAe(t){return{dataType:"error",expressionType:"scalar",value:[`_ERROR_${t.replace(/ /g,"_")}`],evalSpace:"constant"}}hr.errorFor=GAe;var dt={},ln={};Object.defineProperty(ln,"__esModule",{value:!0}),ln.FT=void 0;const WAe=Ru;function fx(t,e="scalar",n="constant"){return{dataType:t,expressionType:e,evalSpace:n}}class wr{static in(e,n){return e?n.find(i=>wr.eq(i,e))!==void 0:!1}static eq(e,n){return n!==void 0&&e.dataType===n.dataType&&e.expressionType===n.expressionType}static typeIn(e,n){return e?n.find(i=>wr.typeEq(i,e))!==void 0:!1}static typeEq(e,n,r=!1,i=!0){const s=e.dataType===n.dataType,o=r&&(e.dataType==="null"||n.dataType==="null"),u=i&&(e.dataType==="error"||n.dataType==="error");return s||o||u}static inspect(...e){return e.map(r=>{if(r){let i=r.dataType;return(0,WAe.expressionIsScalar)(r.expressionType)||(i=`${r.expressionType} ${i}`),i}return"undefined"}).join(",")}}ln.FT=wr,wr.nullT=fx("null"),wr.numberT=fx("number"),wr.stringT=fx("string"),wr.dateT=fx("date"),wr.timestampT=fx("timestamp"),wr.boolT=fx("boolean"),wr.anyAtomicT=[wr.numberT,wr.stringT,wr.dateT,wr.timestampT,wr.boolT],wr.aggregateBoolT=fx("boolean","aggregate");var dl={};Object.defineProperty(dl,"__esModule",{value:!0}),dl.isComparison=dl.Comparison=void 0;var M4;(function(t){t.Like="~",t.NotLike="!~",t.LessThan="<",t.LessThanOrEqualTo="<=",t.EqualTo="=",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.NotEqualTo="!="})(M4||(dl.Comparison=M4={}));function VAe(t){return Object.values(M4).includes(t)}dl.isComparison=VAe;var cp={};Object.defineProperty(cp,"__esModule",{value:!0}),cp.isEquality=cp.Equality=void 0;var j4;(function(t){t.Like="~",t.NotLike="!~",t.Equals="=",t.NotEquals="!="})(j4||(cp.Equality=j4={}));function YAe(t){return Object.values(j4).includes(t)}cp.isEquality=YAe;var fp={};Object.defineProperty(fp,"__esModule",{value:!0}),fp.isGranularResult=void 0;function KAe(t){return t.dataType==="date"||t.dataType==="timestamp"?t.timeframe!==void 0:!1}fp.isGranularResult=KAe,Object.defineProperty(dt,"__esModule",{value:!0}),dt.applyBinary=dt.getMorphicValue=dt.ExprDuration=dt.ExpressionDef=void 0;const Nn=Z,xp=hr,hl=an,xx=ln,Y_=On,XAe=dl,JAe=cp,Iz=fp,ZAe=Ve;class eSe extends Error{}class $z extends ZAe.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=xx.FT.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,n){return n.dataType!=="error"&&!xx.FT.in(n,this.legalChildTypes)?(e.log(n.dataType==="sql native"?`'${this.elementType}' Can't be used with unsupported SQL native type '${n.rawType}'[unsupported-sql-native-type-not-allowed-in-expression]`:`'${this.elementType}' Can't use type ${xx.FT.inspect(n)}`),!1):!0}apply(e,n,r){return Uz(e,r,n,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,Nn.expressionIsAggregate)(e.expressionType)}}dt.ExpressionDef=$z;class U4 extends $z{constructor(e,n){super({n:e}),this.n=e,this.timeframe=n,this.elementType="duration",this.legalChildTypes=[xx.FT.timestampT,xx.FT.dateT]}apply(e,n,r){const i=r.getExpression(e);if(this.typeCheck(this,i),(0,Nn.isTimeFieldType)(i.dataType)&&(n==="+"||n==="-")){const s=this.n.getExpression(e);if(!xx.FT.typeEq(s,xx.FT.numberT))return this.log(`Duration units needs number not '${s.dataType}`),(0,xp.errorFor)("illegal unit expression");let o;if((0,Iz.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.dataType==="timestamp"){const u=(0,Y_.timeOffset)("timestamp",i.value,n,s.value,this.timeframe);return(0,Y_.timeResult)({dataType:"timestamp",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:u},o)}return(0,Nn.isDateUnit)(this.timeframe)?(0,Y_.timeResult)({dataType:"date",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,Y_.timeOffset)("date",i.value,n,s.value,this.timeframe)},o):(this.log(`Cannot offset date by ${this.timeframe}`),(0,xp.errorFor)("ofsset date error"))}return super.apply(e,n,r)}getExpression(e){return{dataType:"duration",expressionType:"scalar",value:["__ERROR_DURATION_IS_NOT_A_VALUE__"],evalSpace:"constant"}}}dt.ExprDuration=U4;function Bz(t,e){return t.dataType===e?t.value:t.morphic&&t.morphic[e]}function tSe(t,e){if(t.dataType===e)return t;if(t.morphic&&t.morphic[e])return{...t,dataType:e,value:t.morphic[e]}}dt.getMorphicValue=tSe;function kz(t,e,n,r){const i=(0,Nn.isTimeFieldType)(e.dataType),s=(0,Nn.isTimeFieldType)(r.dataType);if(i&&s)if(e.dataType!==r.dataType){const o=Bz(e,"timestamp"),u=Bz(r,"timestamp");if(o&&u)return(0,hl.compose)(o,n,u)}else return(0,hl.compose)(e.value,n,r.value);if((i||s)&&e.dataType!=="null"&&r.dataType!=="null")return t.log(`Cannot compare a ${e.dataType} to a ${r.dataType}`),["false"]}function Pz(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 nSe(t,e,n){const r=e==="!="||e==="!~";if(t.dataType==="null"||n.dataType==="null"){const i=r?" NOT":"";return t.dataType!=="null"?[...t.value,` IS${i} NULL`]:n.dataType!=="null"?[...n.value,`IS${i} NULL`]:[r?"false":"true"]}}function rSe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=O1("boolean",i,s);if(o)return o;if(i.dataType==="sql native"||s.dataType==="sql native"){const l=i.dataType==="null"||s.dataType==="null",c=i.rawType&&i.rawType===s.rawType;if(!(l||c)){const f=N1(e,i,r,s);if(f)return{...f,dataType:"boolean"}}}let a=kz(e,i,n,s)||(0,hl.compose)(i.value,n,s.value);if(i.dataType!=="error"&&s.dataType!=="error")switch(n){case"~":case"!~":{if(i.dataType==="string"&&s.dataType==="string")a=(0,hl.compose)(i.value,"LIKE",s.value);else{const l=Pz(i,s);if(l===void 0)throw new eSe("Incompatible types for match('~') operator");a=l}a=(0,hl.nullsafeNot)(a,n);break}case"=":case"!=":{const l=nSe(i,n,s);l?a=l:a=(0,hl.nullsafeNot)(Pz(i,s)||(0,hl.compose)(i.value,"=",s.value),n);break}}return{dataType:"boolean",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:a}}function iSe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=O1("boolean",i,s);if(o)return o;const u=(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),a=N1(e,i,r,s);if(a)return{...a,dataType:"boolean"};const l=kz(e,i,n,s)||(0,hl.compose)(i.value,n,s.value);return{dataType:"boolean",expressionType:u,evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:l}}function Mz(t,...e){return e.includes(t)}function jz(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=O1("number",i,s);if(o)return o;const u=N1(e,i,r,s);if(u)return u;const a=(0,Nn.maxExpressionType)(i.expressionType,s.expressionType);if(i.dataType!=="number")e.log(`The '${n}' operator requires a number, not a '${i.dataType}'`);else if(s.dataType!=="number")r.log(`The '${n}' operator requires a number, not a '${s.dataType}'`);else return{dataType:"number",expressionType:a,value:(0,hl.compose)(i.value,n,s.value),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace)};return(0,xp.errorFor)("numbers required")}function sSe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=N1(e,i,r,s);if(o)return o;const u=(0,Nn.isTimeFieldType)(i.dataType),a=O1(u?"error":"number",i,s);if(a)return a;if(u){let l=r;if(s.dataType!=="duration")if((0,Iz.isGranularResult)(i))l=new U4(r,i.timeframe);else if(i.dataType==="date")l=new U4(r,"day");else return e.log(`Can not offset time by '${s.dataType}'`),(0,xp.errorFor)(`time plus ${s.dataType}`);return l.apply(t,n,e)}return jz(t,e,n,r)}function Uz(t,e,n,r){if((0,JAe.isEquality)(n))return rSe(t,e,n,r);if((0,XAe.isComparison)(n))return iSe(t,e,n,r);if(Mz(n,"+","-"))return sSe(t,e,n,r);if(n==="*")return jz(t,e,n,r);if(Mz(n,"/","%")){const i=e.getExpression(t),s=r.getExpression(t),o=N1(e,i,r,s);if(o)return e.log(`Cannot use '${n}' with sql native type`),o;const u=O1("number",i,s);if(u)return u;if(i.dataType!=="number")e.log("Numerator must be a number");else if(s.dataType!=="number")r.log("Denominator must be a number");else{const a={type:"dialect",function:n==="/"?"div":"mod",numerator:i.value,denominator:s.value};return{dataType:"number",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:[a]}}return(0,xp.errorFor)("divide type mismatch")}return e.log(`Cannot use ${n} operator here`),(0,xp.errorFor)("applybinary bad operator")}dt.applyBinary=Uz;function O1(t,...e){if(e.some(n=>n.dataType==="error"))return{dataType:t,expressionType:(0,Nn.maxOfExpressionTypes)(e.map(n=>n.expressionType)),value:["'cascading error'"],evalSpace:(0,Nn.mergeEvalSpaces)(...e.map(n=>n.evalSpace))}}function N1(t,e,n,r){const i={dataType:e.dataType,expressionType:(0,Nn.maxExpressionType)(e.expressionType,r.expressionType),value:["'unsupported operation'"],evalSpace:(0,Nn.mergeEvalSpaces)(e.evalSpace,r.evalSpace)};if(e.dataType==="sql native")return t.log(`Unsupported SQL native type '${e.rawType}' not allowed in expression[unsupported-sql-native-type-not-allowed-in-expression]`),{...i,dataType:r.dataType};if(r.dataType==="sql native")return n.log(`Unsupported SQL native type '${r.rawType}' not allowed in expression[unsupported-sql-native-type-not-allowed-in-expression]`),i}Object.defineProperty(cx,"__esModule",{value:!0}),cx.ExprIdReference=void 0;const oSe=Z,uSe=hr,aSe=dt;class lSe extends aSe.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){const n=this.fieldReference.getField(e);if(n.found){const r=n.found.typeDesc();if(n.isOutputField)return{...r,evalSpace:r.evalSpace==="constant"?"constant":"output",value:[{type:"outputField",name:this.refString}]};const i=[{type:n.found.refType,path:this.fieldReference.path}],s=(0,oSe.expressionIsAggregate)(r.expressionType)?"output":r.evalSpace;return{...r,value:i,evalSpace:s}}return this.log(n.error),(0,uSe.errorFor)(n.error)}}cx.ExprIdReference=lSe,Object.defineProperty(lp,"__esModule",{value:!0}),lp.NamedSource=void 0;const q4=Z,cSe=Uo,fSe=Xr,xSe=On,H4=Ve,dSe=cx,hSe=np;class pSe extends cSe.Source{constructor(e,n,r){super(),this.ref=e,this.sourceArguments=n,this.args=r,this.elementType="namedSource",r&&this.has({args:r}),e instanceof H4.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof H4.ModelEntryReference?this.ref.name:this.ref}structRef(e){const n=this.modelEntry(this.ref);return n&&!n.exported?{structRef:this.structDef(e)}:{structRef:this.refName,sourceArguments:this.evaluateArgumentsForRef(e)}}refLog(e,n){typeof this.ref=="string"?this.log(e,n):this.ref.log(e,n)}modelStruct(){var e;const n=this.modelEntry(this.ref),r=n==null?void 0:n.entry;if(!r){const i=`Undefined source '${this.refName}'`;(this.ref instanceof H4.ModelEntryReference?this.ref:this).log(i);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,q4.isSQLBlockStruct)(r)&&r.declaredSQLBlock){this.log(`Must use 'from_sql()' for sql source '${this.refName}'`);return}else(e=this.document())===null||e===void 0||e.checkExperimentalDialect(this,r.dialect);return{...r}}evaluateArgumentsForRef(e){const n=this.modelStruct();return n===void 0?{}:this.evaluateArguments(e,n.parameters,[])}evaluateArguments(e,n,r){var i,s;const o={...this.sourceArguments},u=new Set;for(const a of(i=this.args)!==null&&i!==void 0?i:[]){const l=(s=a.id)!==null&&s!==void 0?s:a.value instanceof dSe.ExprIdReference?a.value.fieldReference:void 0;if(l===void 0){a.value.log("Parameterized source arguments must be named with `parameter_name is`");continue}const c=l.outputName;if(u.has(c)){a.log(`Cannot pass argument for \`${c}\` more than once`);continue}u.add(c);const f=(n??{})[c];if(!f)l.log(`\`${this.refName}\` has no declared parameter named \`${l.refString}\``);else{const x=e??new hSe.ParameterSpace(r??[]),h=a.value.getExpression(x);let p=h.value;h.dataType!==f.type&&(0,q4.isCastType)(f.type)&&(p=(0,xSe.castTo)(f.type,h.value,h.dataType,!0)),o[c]={...f,value:p}}}for(const a in n)a in o||(0,q4.paramHasValue)(n[a])||this.refLog(`Argument not provided for required parameter \`${a}\``);return o}structDef(e){return this.withParameters(e,[])}withParameters(e,n){var r;const i=this.modelStruct();if(!i){const a=fSe.ErrorFactory.structDef,l=`${this.refName}-undefined`;return a.name=a.name+l,a.dialect=a.dialect+l,a}const s={};for(const a of n??[]){const l=a.parameter();s[l.name]=l}const o=this.evaluateArguments(e,i.parameters,n),u={...i,parameters:s,arguments:o};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(u),u}}lp.NamedSource=pSe;var D1={},K_={};Object.defineProperty(K_,"__esModule",{value:!0}),K_.QueryHeadStruct=void 0;const gSe=Z,mSe=Uo,ySe=lp;class ESe extends mSe.Source{constructor(e,n){super(),this.fromRef=e,this.sourceArguments=n,this.elementType="internalOnlyQueryHead"}structRef(){return{structRef:this.fromRef}}structDef(e){if((0,gSe.refIsStructDef)(this.fromRef))return this.fromRef;const n=new ySe.NamedSource(this.fromRef,this.sourceArguments,void 0);return this.has({exploreReference:n}),n.structDef(e)}}K_.QueryHeadStruct=ESe,Object.defineProperty(D1,"__esModule",{value:!0}),D1.QueryReference=void 0;const z4=Xr,ASe=Ve,SSe=K_,vSe=Z,_Se=Ns;class CSe extends ASe.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){const n=this.modelEntry(this.name),r=n==null?void 0:n.entry,i=function(){return{inputStruct:z4.ErrorFactory.structDef,outputStruct:z4.ErrorFactory.structDef,query:z4.ErrorFactory.query}};if(!r)return this.log(`Reference to undefined query '${this.name.refString}'`),i();if(r.type==="query"){const s=new SSe.QueryHeadStruct(r.structRef,r.sourceArguments);this.has({queryHead:s});const o=s.structDef(void 0),u=(0,_Se.getFinalStruct)(this,o,r.pipeline);return{query:e||(0,vSe.refIsStructDef)(r.structRef)?r:{...r,structRef:o},outputStruct:u,inputStruct:o}}return this.log(`Illegal reference to '${this.name}', query expected`),i()}query(){return this.queryComp(!0).query}}D1.QueryReference=CSe,Object.defineProperty(R1,"__esModule",{value:!0}),R1.SQReference=void 0;const bSe=Vu,TSe=lx,RSe=lp,qz=D1;class OSe extends bSe.SourceQueryElement{constructor(e,n){super({ref:e}),this.ref=e,this.args=n,this.elementType="sq-reference",n!==void 0&&this.has({args:n})}getQuery(){const e=this.ref.getNamed();if(e)if(e.type==="query"){const n=new qz.QueryReference(this.ref);return this.has({query:n}),n}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;const e=this.ref.getNamed();if(!e){this.ref.log(`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){this.args!==void 0&&this.ref.log("Arguments cannot be passed to queries");const n=new qz.QueryReference(this.ref);this.asSource=new TSe.QuerySource(n)}else if(e.type==="struct")this.asSource=new RSe.NamedSource(this.ref,void 0,this.args);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}}R1.SQReference=OSe,Object.defineProperty(V_,"__esModule",{value:!0}),V_.SQRefine=void 0;const NSe=Vu,DSe=lx,FSe=ap,wSe=R1;class LSe extends NSe.SourceQueryElement{constructor(e,n){super({toRefine:e,refine:n}),this.toRefine=e,this.refine=n,this.elementType="sq-refine"}getQuery(){if(this.toRefine.isSource()){this.toRefine instanceof wSe.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}const e=this.toRefine.getQuery();if(e){const n=new FSe.QueryRefine(e,this.refine);return this.has({query:n}),n}}getSource(){const e=this.getQuery();if(e){const n=new DSe.QuerySource(e);return this.has({queryAsSource:n}),n}}}V_.SQRefine=LSe;var X_={},F1={};Object.defineProperty(F1,"__esModule",{value:!0}),F1.QueryRaw=void 0;const ISe=Z,$Se=Ve;class BSe extends $Se.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){const n=e?this.source.structRef(void 0):{structRef:this.source.structDef(void 0)},r=(0,ISe.refIsStructDef)(n.structRef)?n.structRef:this.source.structDef(void 0);return{query:{type:"query",...n,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:r,inputStruct:r}}query(){return this.queryComp(!0).query}}F1.QueryRaw=BSe;var w1={},J_={};Object.defineProperty(J_,"__esModule",{value:!0}),J_.makeSQLBlock=void 0;const kSe=Z,PSe=Vt;function MSe(t,e){const n={name:`md5:/${e||"$default"}//${jSe(t)}`,select:t};return e&&(n.connection=e),n}J_.makeSQLBlock=MSe;function jSe(t){const e=t.map(n=>(0,kSe.isSQLFragment)(n)?n.sql:JSON.stringify(n));return(0,PSe.generateHash)(e.join(";"))}Object.defineProperty(w1,"__esModule",{value:!0}),w1.SQLSource=void 0;const USe=J_,qSe=Uo,Z_=Xr;class HSe extends qSe.Source{constructor(e,n){super({connectionName:e,select:n}),this.connectionName=e,this.select=n,this.elementType="sqlSource",this.connectionNameInvalid=!1}sqlBlock(){return this.requestBlock||(this.requestBlock=(0,USe.makeSQLBlock)(this.select.sqlPhrases(),this.connectionName.refString)),this.requestBlock}structRef(){return{structRef:this.structDef()}}validateConnectionName(){var e;const n=this.modelEntry(this.connectionName),r=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(n===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(r,{entry:{type:"connection",name:r},exported:!0},!0);else if(n.entry.type!=="connection")return this.connectionName.log(`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var n;if(!this.validateConnectionName())return;const r=super.needs(e);if(r)return r;const i=this.sqlBlock(),s=(n=this.translator())===null||n===void 0?void 0:n.root.sqlQueryZone;if(!s){this.log("Cant't look up schema for sql block");return}s.reference(i.name,this.location);const o=s.getEntry(i.name);if(o.status==="reference")return{compileSQL:i,partialModel:this.select.containsQueries?e.modelDef():void 0};o.status==="present"&&e.checkExperimentalDialect(this,o.value.dialect)}structDef(){var e;if(!this.validateConnectionName())return Z_.ErrorFactory.structDef;const n=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!n)return this.log("Cant't look up schema for sql block"),Z_.ErrorFactory.structDef;const r=this.sqlBlock();n.reference(r.name,this.location);const i=n.getEntry(r.name);if(i.status==="error"){const s=i.message.split(/\r?\n/);return this.select.log("Invalid SQL, "+s.join(`
|
|
1299
|
+
QUERY: ${(0,NAe.inspect)(n,{breakLength:72,depth:1/0})}`)}return{...Fz.ErrorFactory.structDef,dialect:e.dialect}}Ns.opOutputStruct=wz;function FAe(t,e,n){for(const r of n)e=wz(t,e,r);return e}Ns.getFinalStruct=FAe;function wAe(t,e){return t.fields.find(n=>(n.as||n.name)===e)}Ns.getStructFieldDef=wAe,Object.defineProperty(ap,"__esModule",{value:!0}),ap.QueryRefine=void 0;const LAe=Jr,IAe=Ns,$Ae=T1;class BAe extends $Ae.QueryBase{constructor(e,n){super({base:e,refinement:n}),this.base=e,this.refinement=n,this.elementType="query-refine"}queryComp(e){const n=this.base.queryComp(e),r=new LAe.StaticSpace(n.inputStruct),i=this.refinement.refine(r,n.query.pipeline,void 0);return{query:{...n.query,pipeline:i},outputStruct:(0,IAe.getFinalStruct)(this.refinement,n.inputStruct,i),inputStruct:n.inputStruct}}}ap.QueryRefine=BAe;var R1={},lp={},On={};Object.defineProperty(On,"__esModule",{value:!0}),On.dateOffset=On.timestampOffset=On.timeResult=On.resolution=On.castDateToTimestamp=On.castTimestampToDate=On.castTo=On.timeOffset=void 0;const kAe=Z,Lz=an;function PAe(t,e,n,r,i){return[{type:"dialect",function:"delta",base:{valueType:t,value:e},op:n,delta:r,units:i}]}On.timeOffset=PAe;function MAe(t,e,n,r=!1){const i={type:"dialect",function:"cast",dstType:t,expr:e,safe:r};return(0,kAe.isAtomicFieldType)(n)&&(i.srcType=n),[i]}On.castTo=MAe;function jAe(t,e=!1){return[{type:"dialect",function:"cast",dstType:"date",srcType:"timestamp",expr:t,safe:e}]}On.castTimestampToDate=jAe;function UAe(t,e=!1){return[{type:"dialect",function:"cast",dstType:"timestamp",srcType:"date",expr:t,safe:e}]}On.castDateToTimestamp=UAe;function qAe(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}On.resolution=qAe;function HAe(t,e){return e?{...t,timeframe:e}:t}On.timeResult=HAe;function zAe(t,e,n,r,i=!1){const s=["week","month","quarter","year"].includes(r),o=e==="+"?"_ADD":"_SUB",u=r.toUpperCase();if(s)return[`TIMESTAMP(DATETIME${o}(DATETIME(`,...t,"),INTERVAL ",...n,` ${u}))`];const a=i?["TIMESTAMP(",...t,")"]:t;return(0,Lz.compressExpr)([`TIMESTAMP${o}(`,...a,",INTERVAL ",...n,` ${u})`])}On.timestampOffset=zAe;function QAe(t,e,n,r){const i=e==="+"?"_ADD":"_SUB",s=r.toUpperCase();return(0,Lz.compressExpr)([`DATE${i}(`,...t,",INTERVAL ",...n,` ${s})`])}On.dateOffset=QAe;var cx={},hr={};Object.defineProperty(hr,"__esModule",{value:!0}),hr.errorFor=void 0;function GAe(t){return{dataType:"error",expressionType:"scalar",value:[`_ERROR_${t.replace(/ /g,"_")}`],evalSpace:"constant"}}hr.errorFor=GAe;var dt={},ln={};Object.defineProperty(ln,"__esModule",{value:!0}),ln.FT=void 0;const WAe=Ru;function fx(t,e="scalar",n="constant"){return{dataType:t,expressionType:e,evalSpace:n}}class wr{static in(e,n){return e?n.find(i=>wr.eq(i,e))!==void 0:!1}static eq(e,n){return n!==void 0&&e.dataType===n.dataType&&e.expressionType===n.expressionType}static typeIn(e,n){return e?n.find(i=>wr.typeEq(i,e))!==void 0:!1}static typeEq(e,n,r=!1,i=!0){const s=e.dataType===n.dataType,o=r&&(e.dataType==="null"||n.dataType==="null"),u=i&&(e.dataType==="error"||n.dataType==="error");return s||o||u}static inspect(...e){return e.map(r=>{if(r){let i=r.dataType;return(0,WAe.expressionIsScalar)(r.expressionType)||(i=`${r.expressionType} ${i}`),i}return"undefined"}).join(",")}}ln.FT=wr,wr.nullT=fx("null"),wr.numberT=fx("number"),wr.stringT=fx("string"),wr.dateT=fx("date"),wr.timestampT=fx("timestamp"),wr.boolT=fx("boolean"),wr.anyAtomicT=[wr.numberT,wr.stringT,wr.dateT,wr.timestampT,wr.boolT],wr.aggregateBoolT=fx("boolean","aggregate");var dl={};Object.defineProperty(dl,"__esModule",{value:!0}),dl.isComparison=dl.Comparison=void 0;var M4;(function(t){t.Like="~",t.NotLike="!~",t.LessThan="<",t.LessThanOrEqualTo="<=",t.EqualTo="=",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.NotEqualTo="!="})(M4||(dl.Comparison=M4={}));function VAe(t){return Object.values(M4).includes(t)}dl.isComparison=VAe;var cp={};Object.defineProperty(cp,"__esModule",{value:!0}),cp.isEquality=cp.Equality=void 0;var j4;(function(t){t.Like="~",t.NotLike="!~",t.Equals="=",t.NotEquals="!="})(j4||(cp.Equality=j4={}));function YAe(t){return Object.values(j4).includes(t)}cp.isEquality=YAe;var fp={};Object.defineProperty(fp,"__esModule",{value:!0}),fp.isGranularResult=void 0;function KAe(t){return t.dataType==="date"||t.dataType==="timestamp"?t.timeframe!==void 0:!1}fp.isGranularResult=KAe,Object.defineProperty(dt,"__esModule",{value:!0}),dt.applyBinary=dt.getMorphicValue=dt.ExprDuration=dt.ExpressionDef=void 0;const Nn=Z,xp=hr,hl=an,xx=ln,Y_=On,XAe=dl,JAe=cp,Iz=fp,ZAe=Ve;class eSe extends Error{}class $z extends ZAe.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=xx.FT.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,n){return n.dataType!=="error"&&!xx.FT.in(n,this.legalChildTypes)?(e.log(n.dataType==="sql native"?`'${this.elementType}' Can't be used with unsupported SQL native type '${n.rawType}'[unsupported-sql-native-type-not-allowed-in-expression]`:`'${this.elementType}' Can't use type ${xx.FT.inspect(n)}`),!1):!0}apply(e,n,r){return Uz(e,r,n,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,Nn.expressionIsAggregate)(e.expressionType)}}dt.ExpressionDef=$z;class U4 extends $z{constructor(e,n){super({n:e}),this.n=e,this.timeframe=n,this.elementType="duration",this.legalChildTypes=[xx.FT.timestampT,xx.FT.dateT]}apply(e,n,r){const i=r.getExpression(e);if(this.typeCheck(this,i),(0,Nn.isTimeFieldType)(i.dataType)&&(n==="+"||n==="-")){const s=this.n.getExpression(e);if(!xx.FT.typeEq(s,xx.FT.numberT))return this.log(`Duration units needs number not '${s.dataType}`),(0,xp.errorFor)("illegal unit expression");let o;if((0,Iz.isGranularResult)(i)&&i.timeframe===this.timeframe&&(o=i.timeframe),i.dataType==="timestamp"){const u=(0,Y_.timeOffset)("timestamp",i.value,n,s.value,this.timeframe);return(0,Y_.timeResult)({dataType:"timestamp",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:u},o)}return(0,Nn.isDateUnit)(this.timeframe)?(0,Y_.timeResult)({dataType:"date",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,Y_.timeOffset)("date",i.value,n,s.value,this.timeframe)},o):(this.log(`Cannot offset date by ${this.timeframe}`),(0,xp.errorFor)("ofsset date error"))}return super.apply(e,n,r)}getExpression(e){return{dataType:"duration",expressionType:"scalar",value:["__ERROR_DURATION_IS_NOT_A_VALUE__"],evalSpace:"constant"}}}dt.ExprDuration=U4;function Bz(t,e){return t.dataType===e?t.value:t.morphic&&t.morphic[e]}function tSe(t,e){if(t.dataType===e)return t;if(t.morphic&&t.morphic[e])return{...t,dataType:e,value:t.morphic[e]}}dt.getMorphicValue=tSe;function kz(t,e,n,r){const i=(0,Nn.isTimeFieldType)(e.dataType),s=(0,Nn.isTimeFieldType)(r.dataType);if(i&&s)if(e.dataType!==r.dataType){const o=Bz(e,"timestamp"),u=Bz(r,"timestamp");if(o&&u)return(0,hl.compose)(o,n,u)}else return(0,hl.compose)(e.value,n,r.value);if((i||s)&&e.dataType!=="null"&&r.dataType!=="null")return t.log(`Cannot compare a ${e.dataType} to a ${r.dataType}`),["false"]}function Pz(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 nSe(t,e,n){const r=e==="!="||e==="!~";if(t.dataType==="null"||n.dataType==="null"){const i=r?" NOT":"";return t.dataType!=="null"?[...t.value,` IS${i} NULL`]:n.dataType!=="null"?[...n.value,`IS${i} NULL`]:[r?"false":"true"]}}function rSe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=O1("boolean",i,s);if(o)return o;if(i.dataType==="sql native"||s.dataType==="sql native"){const l=i.dataType==="null"||s.dataType==="null",c=i.rawType&&i.rawType===s.rawType;if(!(l||c)){const f=N1(e,i,r,s);if(f)return{...f,dataType:"boolean"}}}let a=kz(e,i,n,s)||(0,hl.compose)(i.value,n,s.value);if(i.dataType!=="error"&&s.dataType!=="error")switch(n){case"~":case"!~":{if(i.dataType==="string"&&s.dataType==="string")a=(0,hl.compose)(i.value,"LIKE",s.value);else{const l=Pz(i,s);if(l===void 0)throw new eSe("Incompatible types for match('~') operator");a=l}a=(0,hl.nullsafeNot)(a,n);break}case"=":case"!=":{const l=nSe(i,n,s);l?a=l:a=(0,hl.nullsafeNot)(Pz(i,s)||(0,hl.compose)(i.value,"=",s.value),n);break}}return{dataType:"boolean",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:a}}function iSe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=O1("boolean",i,s);if(o)return o;const u=(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),a=N1(e,i,r,s);if(a)return{...a,dataType:"boolean"};const l=kz(e,i,n,s)||(0,hl.compose)(i.value,n,s.value);return{dataType:"boolean",expressionType:u,evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:l}}function Mz(t,...e){return e.includes(t)}function jz(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=O1("number",i,s);if(o)return o;const u=N1(e,i,r,s);if(u)return u;const a=(0,Nn.maxExpressionType)(i.expressionType,s.expressionType);if(i.dataType!=="number")e.log(`The '${n}' operator requires a number, not a '${i.dataType}'`);else if(s.dataType!=="number")r.log(`The '${n}' operator requires a number, not a '${s.dataType}'`);else return{dataType:"number",expressionType:a,value:(0,hl.compose)(i.value,n,s.value),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace)};return(0,xp.errorFor)("numbers required")}function sSe(t,e,n,r){const i=e.getExpression(t),s=r.getExpression(t),o=N1(e,i,r,s);if(o)return o;const u=(0,Nn.isTimeFieldType)(i.dataType),a=O1(u?"error":"number",i,s);if(a)return a;if(u){let l=r;if(s.dataType!=="duration")if((0,Iz.isGranularResult)(i))l=new U4(r,i.timeframe);else if(i.dataType==="date")l=new U4(r,"day");else return e.log(`Can not offset time by '${s.dataType}'`),(0,xp.errorFor)(`time plus ${s.dataType}`);return l.apply(t,n,e)}return jz(t,e,n,r)}function Uz(t,e,n,r){if((0,JAe.isEquality)(n))return rSe(t,e,n,r);if((0,XAe.isComparison)(n))return iSe(t,e,n,r);if(Mz(n,"+","-"))return sSe(t,e,n,r);if(n==="*")return jz(t,e,n,r);if(Mz(n,"/","%")){const i=e.getExpression(t),s=r.getExpression(t),o=N1(e,i,r,s);if(o)return e.log(`Cannot use '${n}' with sql native type`),o;const u=O1("number",i,s);if(u)return u;if(i.dataType!=="number")e.log("Numerator must be a number");else if(s.dataType!=="number")r.log("Denominator must be a number");else{const a={type:"dialect",function:n==="/"?"div":"mod",numerator:i.value,denominator:s.value};return{dataType:"number",expressionType:(0,Nn.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,Nn.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:[a]}}return(0,xp.errorFor)("divide type mismatch")}return e.log(`Cannot use ${n} operator here`),(0,xp.errorFor)("applybinary bad operator")}dt.applyBinary=Uz;function O1(t,...e){if(e.some(n=>n.dataType==="error"))return{dataType:t,expressionType:(0,Nn.maxOfExpressionTypes)(e.map(n=>n.expressionType)),value:["'cascading error'"],evalSpace:(0,Nn.mergeEvalSpaces)(...e.map(n=>n.evalSpace))}}function N1(t,e,n,r){const i={dataType:e.dataType,expressionType:(0,Nn.maxExpressionType)(e.expressionType,r.expressionType),value:["'unsupported operation'"],evalSpace:(0,Nn.mergeEvalSpaces)(e.evalSpace,r.evalSpace)};if(e.dataType==="sql native")return t.log(`Unsupported SQL native type '${e.rawType}' not allowed in expression[unsupported-sql-native-type-not-allowed-in-expression]`),{...i,dataType:r.dataType};if(r.dataType==="sql native")return n.log(`Unsupported SQL native type '${r.rawType}' not allowed in expression[unsupported-sql-native-type-not-allowed-in-expression]`),i}Object.defineProperty(cx,"__esModule",{value:!0}),cx.ExprIdReference=void 0;const oSe=Z,uSe=hr,aSe=dt;class lSe extends aSe.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){const n=this.fieldReference.getField(e);if(n.found){const r=n.found.typeDesc();if(n.isOutputField)return{...r,evalSpace:r.evalSpace==="constant"?"constant":"output",value:[{type:"outputField",name:this.refString}]};const i=[{type:n.found.refType,path:this.fieldReference.path}],s=(0,oSe.expressionIsAggregate)(r.expressionType)?"output":r.evalSpace;return{...r,value:i,evalSpace:s}}return this.log(n.error),(0,uSe.errorFor)(n.error)}}cx.ExprIdReference=lSe,Object.defineProperty(lp,"__esModule",{value:!0}),lp.NamedSource=void 0;const q4=Z,cSe=Uo,fSe=Xr,xSe=On,H4=Ve,dSe=cx,hSe=np;class pSe extends cSe.Source{constructor(e,n,r){super(),this.ref=e,this.sourceArguments=n,this.args=r,this.elementType="namedSource",r&&this.has({args:r}),e instanceof H4.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof H4.ModelEntryReference?this.ref.name:this.ref}structRef(e){const n=this.modelEntry(this.ref);return n&&!n.exported?{structRef:this.structDef(e)}:{structRef:this.refName,sourceArguments:this.evaluateArgumentsForRef(e)}}refLog(e,n){typeof this.ref=="string"?this.log(e,n):this.ref.log(e,n)}modelStruct(){var e;const n=this.modelEntry(this.ref),r=n==null?void 0:n.entry;if(!r){const i=`Undefined source '${this.refName}'`;(this.ref instanceof H4.ModelEntryReference?this.ref:this).log(i);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,q4.isSQLBlockStruct)(r)&&r.declaredSQLBlock){this.log(`Must use 'from_sql()' for sql source '${this.refName}'`);return}else(e=this.document())===null||e===void 0||e.checkExperimentalDialect(this,r.dialect);return{...r}}evaluateArgumentsForRef(e){const n=this.modelStruct();return n===void 0?{}:this.evaluateArguments(e,n.parameters,[])}evaluateArguments(e,n,r){var i,s;const o={...this.sourceArguments},u=new Set;for(const a of(i=this.args)!==null&&i!==void 0?i:[]){const l=(s=a.id)!==null&&s!==void 0?s:a.value instanceof dSe.ExprIdReference?a.value.fieldReference:void 0;if(l===void 0){a.value.log("Parameterized source arguments must be named with `parameter_name is`");continue}const c=l.outputName;if(u.has(c)){a.log(`Cannot pass argument for \`${c}\` more than once`);continue}u.add(c);const f=(n??{})[c];if(!f)l.log(`\`${this.refName}\` has no declared parameter named \`${l.refString}\``);else{const x=e??new hSe.ParameterSpace(r??[]),h=a.value.getExpression(x);let p=h.value;h.dataType!==f.type&&(0,q4.isCastType)(f.type)&&(p=(0,xSe.castTo)(f.type,h.value,h.dataType,!0)),o[c]={...f,value:p}}}for(const a in n)a in o||((0,q4.paramHasValue)(n[a])?o[a]={...n[a]}:this.refLog(`Argument not provided for required parameter \`${a}\``));return o}structDef(e){return this.withParameters(e,[])}withParameters(e,n){var r;const i=this.modelStruct();if(!i){const a=fSe.ErrorFactory.structDef,l=`${this.refName}-undefined`;return a.name=a.name+l,a.dialect=a.dialect+l,a}const s={};for(const a of n??[]){const l=a.parameter();s[l.name]=l}const o=this.evaluateArguments(e,i.parameters,n),u={...i,parameters:s,arguments:o};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(u),u}}lp.NamedSource=pSe;var D1={},K_={};Object.defineProperty(K_,"__esModule",{value:!0}),K_.QueryHeadStruct=void 0;const gSe=Z,mSe=Uo,ySe=lp;class ESe extends mSe.Source{constructor(e,n){super(),this.fromRef=e,this.sourceArguments=n,this.elementType="internalOnlyQueryHead"}structRef(){return{structRef:this.fromRef}}structDef(e){if((0,gSe.refIsStructDef)(this.fromRef))return this.fromRef;const n=new ySe.NamedSource(this.fromRef,this.sourceArguments,void 0);return this.has({exploreReference:n}),n.structDef(e)}}K_.QueryHeadStruct=ESe,Object.defineProperty(D1,"__esModule",{value:!0}),D1.QueryReference=void 0;const z4=Xr,ASe=Ve,SSe=K_,vSe=Z,_Se=Ns;class CSe extends ASe.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){const n=this.modelEntry(this.name),r=n==null?void 0:n.entry,i=function(){return{inputStruct:z4.ErrorFactory.structDef,outputStruct:z4.ErrorFactory.structDef,query:z4.ErrorFactory.query}};if(!r)return this.log(`Reference to undefined query '${this.name.refString}'`),i();if(r.type==="query"){const s=new SSe.QueryHeadStruct(r.structRef,r.sourceArguments);this.has({queryHead:s});const o=s.structDef(void 0),u=(0,_Se.getFinalStruct)(this,o,r.pipeline);return{query:e||(0,vSe.refIsStructDef)(r.structRef)?r:{...r,structRef:o},outputStruct:u,inputStruct:o}}return this.log(`Illegal reference to '${this.name}', query expected`),i()}query(){return this.queryComp(!0).query}}D1.QueryReference=CSe,Object.defineProperty(R1,"__esModule",{value:!0}),R1.SQReference=void 0;const bSe=Vu,TSe=lx,RSe=lp,qz=D1;class OSe extends bSe.SourceQueryElement{constructor(e,n){super({ref:e}),this.ref=e,this.args=n,this.elementType="sq-reference",n!==void 0&&this.has({args:n})}getQuery(){const e=this.ref.getNamed();if(e)if(e.type==="query"){const n=new qz.QueryReference(this.ref);return this.has({query:n}),n}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;const e=this.ref.getNamed();if(!e){this.ref.log(`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){this.args!==void 0&&this.ref.log("Arguments cannot be passed to queries");const n=new qz.QueryReference(this.ref);this.asSource=new TSe.QuerySource(n)}else if(e.type==="struct")this.asSource=new RSe.NamedSource(this.ref,void 0,this.args);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}}R1.SQReference=OSe,Object.defineProperty(V_,"__esModule",{value:!0}),V_.SQRefine=void 0;const NSe=Vu,DSe=lx,FSe=ap,wSe=R1;class LSe extends NSe.SourceQueryElement{constructor(e,n){super({toRefine:e,refine:n}),this.toRefine=e,this.refine=n,this.elementType="sq-refine"}getQuery(){if(this.toRefine.isSource()){this.toRefine instanceof wSe.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}const e=this.toRefine.getQuery();if(e){const n=new FSe.QueryRefine(e,this.refine);return this.has({query:n}),n}}getSource(){const e=this.getQuery();if(e){const n=new DSe.QuerySource(e);return this.has({queryAsSource:n}),n}}}V_.SQRefine=LSe;var X_={},F1={};Object.defineProperty(F1,"__esModule",{value:!0}),F1.QueryRaw=void 0;const ISe=Z,$Se=Ve;class BSe extends $Se.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){const n=e?this.source.structRef(void 0):{structRef:this.source.structDef(void 0)},r=(0,ISe.refIsStructDef)(n.structRef)?n.structRef:this.source.structDef(void 0);return{query:{type:"query",...n,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:r,inputStruct:r}}query(){return this.queryComp(!0).query}}F1.QueryRaw=BSe;var w1={},J_={};Object.defineProperty(J_,"__esModule",{value:!0}),J_.makeSQLBlock=void 0;const kSe=Z,PSe=Vt;function MSe(t,e){const n={name:`md5:/${e||"$default"}//${jSe(t)}`,select:t};return e&&(n.connection=e),n}J_.makeSQLBlock=MSe;function jSe(t){const e=t.map(n=>(0,kSe.isSQLFragment)(n)?n.sql:JSON.stringify(n));return(0,PSe.generateHash)(e.join(";"))}Object.defineProperty(w1,"__esModule",{value:!0}),w1.SQLSource=void 0;const USe=J_,qSe=Uo,Z_=Xr;class HSe extends qSe.Source{constructor(e,n){super({connectionName:e,select:n}),this.connectionName=e,this.select=n,this.elementType="sqlSource",this.connectionNameInvalid=!1}sqlBlock(){return this.requestBlock||(this.requestBlock=(0,USe.makeSQLBlock)(this.select.sqlPhrases(),this.connectionName.refString)),this.requestBlock}structRef(){return{structRef:this.structDef()}}validateConnectionName(){var e;const n=this.modelEntry(this.connectionName),r=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(n===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(r,{entry:{type:"connection",name:r},exported:!0},!0);else if(n.entry.type!=="connection")return this.connectionName.log(`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var n;if(!this.validateConnectionName())return;const r=super.needs(e);if(r)return r;const i=this.sqlBlock(),s=(n=this.translator())===null||n===void 0?void 0:n.root.sqlQueryZone;if(!s){this.log("Cant't look up schema for sql block");return}s.reference(i.name,this.location);const o=s.getEntry(i.name);if(o.status==="reference")return{compileSQL:i,partialModel:this.select.containsQueries?e.modelDef():void 0};o.status==="present"&&e.checkExperimentalDialect(this,o.value.dialect)}structDef(){var e;if(!this.validateConnectionName())return Z_.ErrorFactory.structDef;const n=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!n)return this.log("Cant't look up schema for sql block"),Z_.ErrorFactory.structDef;const r=this.sqlBlock();n.reference(r.name,this.location);const i=n.getEntry(r.name);if(i.status==="error"){const s=i.message.split(/\r?\n/);return this.select.log("Invalid SQL, "+s.join(`
|
|
1300
1300
|
`)),Z_.ErrorFactory.structDef}else if(i.status==="present"){const s=this.select.location,o={...i.value,fields:i.value.fields.map(l=>({...l,location:s})),location:this.location},u=this.document(),a=u==null?void 0:u.currentModelAnnotation();return a&&(o.modelAnnotation=a),o}else return this.log("`connection_name.sql(...)` can currently only be used in top level source/query definitions"),Z_.ErrorFactory.structDef}}w1.SQLSource=HSe,Object.defineProperty(X_,"__esModule",{value:!0}),X_.SQSource=void 0;const zSe=Vu,QSe=F1,GSe=w1;class WSe extends zSe.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 GSe.SQLSource){const e=new QSe.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("This source cannot be used as a query")}}X_.SQSource=WSe;var eC={};Object.defineProperty(eC,"__esModule",{value:!0}),eC.SQExtend=void 0;const VSe=v1,YSe=Vu;class KSe extends YSe.SourceQueryElement{constructor(e,n){super({sqSrc:e,extend:n}),this.sqSrc=e,this.extend=n,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new VSe.RefinedSource(e,this.extend),this.has({asSource:this.asSource}),this.asSource;this.sqLog("Could not compute source to extend")}isSource(){return!0}}eC.SQExtend=KSe;var tC={},dp={},hp={};Object.defineProperty(hp,"__esModule",{value:!0}),hp.BinaryBoolean=void 0;const Hz=Z,XSe=hr,JSe=ln,ZSe=dt,eve=an;class tve extends ZSe.ExpressionDef{constructor(e,n,r){super({left:e,right:r}),this.left=e,this.op=n,this.right=r,this.elementType="abstract boolean binary",this.legalChildTypes=[JSe.FT.boolT]}getExpression(e){const n=this.left.getExpression(e),r=this.right.getExpression(e);if(this.typeCheck(this.left,n)&&this.typeCheck(this.right,r)){const i=(0,Hz.mergeEvalSpaces)(n.evalSpace,r.evalSpace);return{dataType:"boolean",expressionType:(0,Hz.maxExpressionType)(n.expressionType,r.expressionType),evalSpace:i,value:(0,eve.compose)(n.value,this.op,r.value)}}return(0,XSe.errorFor)("logial required boolean")}}hp.BinaryBoolean=tve,Object.defineProperty(dp,"__esModule",{value:!0}),dp.ExprCompare=void 0;const Yt=ln,nve=hp,rve={"~":[Yt.FT.stringT],"!~":[Yt.FT.stringT],"<":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],"<=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],"=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],"!=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],">=":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT],">":[Yt.FT.numberT,Yt.FT.stringT,Yt.FT.dateT,Yt.FT.timestampT]};class ive extends nve.BinaryBoolean{constructor(e,n,r){super(e,n,r),this.elementType="a<=>b",this.legalChildTypes=rve[n]}getExpression(e){return this.right.apply(e,this.op,this.left)}}dp.ExprCompare=ive;var L1={},pp={};Object.defineProperty(pp,"__esModule",{value:!0}),pp.ExprTime=void 0;const sve=Z,ove=an,uve=dt;class Q4 extends uve.ExpressionDef{constructor(e,n,r="scalar"){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue={dataType:e,expressionType:r,value:typeof n=="string"?[n]:n,evalSpace:"constant"}}getExpression(e){return this.translationValue}static fromValue(e,n){let r=n.value;if(e!==n.dataType){const i={type:"dialect",function:"cast",safe:!1,dstType:e,expr:n.value};(0,sve.isTimeFieldType)(n.dataType)&&(i.srcType=n.dataType),r=(0,ove.compressExpr)([i])}return new Q4(e,r,n.expressionType)}}pp.ExprTime=Q4;var B0={};Object.defineProperty(B0,"__esModule",{value:!0}),B0.Range=void 0;const zz=Z,ave=hr,lve=dt,cve=an;class fve extends lve.ExpressionDef{constructor(e,n){super({first:e,last:n}),this.first=e,this.last=n,this.elementType="range"}apply(e,n,r){switch(n){case"=":case"!=":{const i=n==="="?">=":"<",s=n==="="?"and":"or",o=n==="="?"<":">=",u=this.first.apply(e,i,r),a=this.last.apply(e,o,r);return{dataType:"boolean",expressionType:(0,zz.maxExpressionType)(u.expressionType,a.expressionType),evalSpace:(0,zz.mergeEvalSpaces)(u.evalSpace,a.evalSpace),value:(0,cve.compose)(u.value,s,a.value)}}case">":return this.last.apply(e,">=",r);case">=":return this.first.apply(e,">=",r);case"<":return this.first.apply(e,"<",r);case"<=":return this.last.apply(e,"<",r)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,ave.errorFor)("a range is not a value")}}B0.Range=fve,Object.defineProperty(L1,"__esModule",{value:!0}),L1.ExprGranularTime=void 0;const G4=Z,xve=hr,Qz=ln,Gz=On,dve=dt,nC=pp,Wz=B0;class hve extends dve.ExpressionDef{constructor(e,n,r){super({expr:e}),this.expr=e,this.units=n,this.truncate=r,this.elementType="granularTime",this.legalChildTypes=[Qz.FT.timestampT,Qz.FT.dateT]}granular(){return!0}getExpression(e){const n=this.units,r=this.expr.getExpression(e);if((0,G4.isTimeFieldType)(r.dataType)){const s={...r,dataType:r.dataType,timeframe:n};return this.truncate&&(s.value=[{type:"dialect",function:"trunc",expr:{value:r.value,valueType:r.dataType},units:n}]),s}r.dataType!=="error"&&this.log(`Cannot do time truncation on type '${r.dataType}'`);const i=r.dataType==="error"?(0,G4.isDateUnit)(n)?"date":"timestamp":r.dataType;return{...r,dataType:i,value:(0,xve.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const n=this.getExpression(e);if(n.dataType==="timestamp"){const o=nC.ExprTime.fromValue("timestamp",n),u=new nC.ExprTime("timestamp",(0,Gz.timeOffset)("timestamp",n.value,"+",(0,G4.mkExpr)`1`,this.units),n.expressionType);return new Wz.Range(o,u)}const r=new nC.ExprTime("date",n.value,n.expressionType),i=(0,Gz.timeOffset)("date",n.value,"+",["1"],this.units),s=new nC.ExprTime("date",i,n.expressionType);return new Wz.Range(r,s)}}L1.ExprGranularTime=hve,Object.defineProperty(tC,"__esModule",{value:!0}),tC.Apply=void 0;const pve=dl,gve=dp,mve=fp,Vz=L1;class yve extends gve.ExprCompare{constructor(e,n){super(e,pve.Comparison.EqualTo,n),this.left=e,this.right=n,this.elementType="apply"}getExpression(e){let n=this.right;if(!this.right.granular()){const r=this.right.requestExpression(e);r&&(0,mve.isGranularResult)(r)&&(n=new Vz.ExprGranularTime(this.right,r.timeframe,!1))}return n instanceof Vz.ExprGranularTime?n.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}tC.Apply=yve;var gp={};Object.defineProperty(gp,"__esModule",{value:!0}),gp.BinaryNumeric=void 0;const Eve=ln,Ave=dt;class Sve extends Ave.ExpressionDef{constructor(e,n,r){super({left:e,right:r}),this.left=e,this.op=n,this.right=r,this.elementType="numeric binary abstract",this.legalChildTypes=[Eve.FT.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}gp.BinaryNumeric=Sve;var rC={};Object.defineProperty(rC,"__esModule",{value:!0}),rC.Boolean=void 0;const vve=dt,_ve=ln;let Cve=class extends vve.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{..._ve.FT.boolT,value:[this.value]}}};rC.Boolean=Cve;var k0={};Object.defineProperty(k0,"__esModule",{value:!0}),k0.FunctionOrdering=k0.FunctionOrderBy=void 0;const W4=Z,Yz=Ve,bve=cx;class Tve extends Yz.MalloyElement{constructor(e,n){super(),this.field=e,this.dir=n,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};const n=this.field.getExpression(e);return(0,W4.expressionIsAggregate)(n.expressionType)||((0,W4.expressionIsScalar)(n.expressionType)?(!(this.field instanceof bve.ExprIdReference)||n.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:n.value,dir:this.dir}}getAggregateOrderBy(e,n){if(this.field){const r=this.field.getExpression(e);return(0,W4.expressionIsScalar)(r.expressionType)||this.field.log("aggregate `order_by` must be scalar"),n||this.field.log("`order_by` must be only `asc` or `desc` with no expression"),{e:r.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}}}k0.FunctionOrderBy=Tve;class Rve extends Yz.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(n=>n.getAnalyticOrderBy(e))}getAggregateOrderBy(e,n){return this.list.map(r=>r.getAggregateOrderBy(e,n))}}k0.FunctionOrdering=Rve;var iC={};Object.defineProperty(iC,"__esModule",{value:!0}),iC.ExprAddSub=void 0;const Ove=gp;class Nve extends Ove.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}iC.ExprAddSub=Nve;var pl={},ht={},I1={};Object.defineProperty(I1,"__esModule",{value:!0}),I1.ReferenceField=void 0;const Kz=Kr;class Dve extends Kz.SpaceField{constructor(e,n){super(),this.fieldRef=e,this.inFS=n,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){var n;if(!this.queryFieldDef){const r=this.fieldRef.getField(e);r.error&&this.fieldRef.log(r.error);const i=this.fieldRef.list.map(u=>u.name),s=((n=r.found)===null||n===void 0?void 0:n.refType)==="parameter"?{type:r.found.typeDesc().dataType,name:i[0],e:[{type:"parameter",path:i}]}:{type:"fieldref",path:i};this.queryFieldDef=s;const o=this.referenceTo;if(o instanceof Kz.SpaceField&&o.haveFieldDef){const u=o.haveFieldDef,a=this.fieldRef.note;if(u.annotation||a){const l=a||{};u.annotation&&(l.inherits=u.annotation),this.queryFieldDef.annotation=l}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;const e=this.referenceTo;return e?(this.memoTypeDesc=e.typeDesc(),this.memoTypeDesc):{dataType:"error",expressionType:"scalar",evalSpace:"input"}}}I1.ReferenceField=Dve;var Kn={};Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.typecheckGroupBy=Kn.typecheckAggregate=Kn.typecheckCalculate=Kn.typecheckDeclare=Kn.typecheckMeasure=Kn.typecheckDimension=Kn.typecheckIndex=Kn.typecheckProject=void 0;const Dn=Ru;function Fve(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsScalar)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in a select operation, did you mean to use ${n} operation instead?`)}}Kn.typecheckProject=Fve;function wve(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsScalar)(t.expressionType)){let n;if(t.dataType==="turtle")n="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="an analytic";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${n} field in an index operation`)}}Kn.typecheckIndex=wve;function Lve(t,e){if(!(0,Dn.expressionIsScalar)(t.expressionType))if((0,Dn.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,Dn.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`)}Kn.typecheckDimension=Lve;function Ive(t,e){if(!(0,Dn.expressionIsAggregate)(t.expressionType))if((0,Dn.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,Dn.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`)}Kn.typecheckMeasure=Ive;function $ve(t,e){t.dataType==="turtle"?e.log("Query fields cannot be used in a declare block"):(0,Dn.expressionIsAnalytic)(t.expressionType)&&e.log("Analytic expressions can not be used in a declare block")}Kn.typecheckDeclare=$ve;function Bve(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsAnalytic)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate";else if((0,Dn.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in a calculate operation, did you mean to use ${n} operation instead?`)}}Kn.typecheckCalculate=Bve;function kve(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsAggregate)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic";else if((0,Dn.expressionIsScalar)(t.expressionType))n="a group_by or select",r="a scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.log(`Cannot use ${r} field in an aggregate operation, did you mean to use ${n} operation instead?`)}}Kn.typecheckAggregate=kve;function Pve(t,e){if(t.dataType==="turtle"||!(0,Dn.expressionIsScalar)(t.expressionType)){let n,r;if(t.dataType==="turtle")n="a nest",r="a view";else if((0,Dn.expressionIsAnalytic)(t.expressionType))n="a calculate",r="an analytic";else if((0,Dn.expressionIsAggregate)(t.expressionType))n="an aggregate",r="an aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.log(`Cannot use ${r} field in a group_by operation, did you mean to use ${n} operation instead?`)}}Kn.typecheckGroupBy=Pve,Object.defineProperty(ht,"__esModule",{value:!0}),ht.FieldReferences=ht.WildcardFieldReference=ht.ViewOrScalarFieldReference=ht.DimensionFieldReference=ht.MeasureFieldReference=ht.DeclareFieldReference=ht.ProjectFieldReference=ht.GroupByFieldReference=ht.AggregateFieldReference=ht.IndexFieldReference=ht.CalculateFieldReference=ht.ParameterFieldReference=ht.PartitionByFieldReference=ht.ExpressionFieldReference=ht.AcceptExceptFieldReference=ht.FieldReference=void 0;const Mve=I1,jve=Os,Xz=Ve,Jz=Yr,P0=Kn;class ns extends Xz.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=Jz.extendNoteMethod}makeEntry(e){const n=this.outputName;if(e.entry(n))this.log(`Output already has a field named '${n}'`);else{const r=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(n,this,new Mve.ReferenceField(this,r))}}get refToField(){return{type:"fieldref",path:this.list.map(e=>e.refString)}}get refString(){return this.path.join(".")}get path(){return this.list.map(e=>e.refString)}get outputName(){return this.list[this.list.length-1].refString}get sourceString(){if(this.list.length>1)return this.list.slice(0,-1).map(e=>e.refString).join(".")}get nameString(){return this.list[this.list.length-1].refString}getField(e){const n=e.lookup(this.list);if(n.found){const r=n.found.typeDesc();this.typecheck(r)}return n}}ht.FieldReference=ns;class Uve extends ns{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}ht.AcceptExceptFieldReference=Uve;class qve extends ns{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}ht.ExpressionFieldReference=qve;class Hve extends ns{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}ht.PartitionByFieldReference=Hve;class zve extends ns{constructor(){super(...arguments),this.elementType="parameterFieldReference"}typecheck(){}}ht.ParameterFieldReference=zve;class Qve extends ns{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,P0.typecheckCalculate)(e,this)}}ht.CalculateFieldReference=Qve;class V4 extends ns{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,P0.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(n=>encodeURIComponent(n)).join("/")}get outputName(){return V4.indexOutputName(this.path)}}ht.IndexFieldReference=V4;class Gve extends ns{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,P0.typecheckAggregate)(e,this)}}ht.AggregateFieldReference=Gve;class Wve extends ns{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,P0.typecheckGroupBy)(e,this)}}ht.GroupByFieldReference=Wve;class Vve extends ns{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,P0.typecheckProject)(e,this)}}ht.ProjectFieldReference=Vve;class Yve extends ns{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,P0.typecheckDeclare)(e,this)}}ht.DeclareFieldReference=Yve;class Kve extends ns{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,P0.typecheckMeasure)(e,this)}}ht.MeasureFieldReference=Kve;class Xve extends ns{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,P0.typecheckDimension)(e,this)}}ht.DimensionFieldReference=Xve;class Jve extends ns{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}ht.ViewOrScalarFieldReference=Jve;class Zve extends Xz.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=Jz.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}.*`:"*"}}ht.WildcardFieldReference=Zve;class e_e extends jve.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}ht.FieldReferences=e_e,Object.defineProperty(pl,"__esModule",{value:!0}),pl.ExprAggregateFunction=void 0;const Zz=Z,t_e=Vt,$1=hr,n_e=Jr,r_e=ax,i_e=ln,s_e=ht,o_e=dt,u_e=Kr,a_e=cx;class l_e extends o_e.ExpressionDef{constructor(e,n,r){super(),this.func=e,this.legalChildTypes=[i_e.FT.numberT],this.elementType=e,this.explicitSource=r,n&&(this.expr=n,this.has({expr:n}))}returns(e){return"number"}getExpression(e){var n,r;const i=e.isQueryFieldSpace()?e.inputSpace():e;let s=this.expr,o=(n=this.expr)===null||n===void 0?void 0:n.getExpression(i),u=(r=this.source)===null||r===void 0?void 0:r.path,a=[];if(this.source){const c=this.source.getField(i);if(c.found){a=c.relationship;const f=c.found,x=f.typeDesc();if((0,Zz.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},u=this.source.path;const h=this.getJoinUsage(i);(h.length===1||h.length>1&&h.slice(1).every(m=>c_e(m,h[0])))&&(u=h[0].map(m=>m.name),a=h[0])}else if(!(f instanceof r_e.StructSpaceFieldBase))return this.log(`Aggregate source cannot be a ${x.dataType}`),(0,$1.errorFor)(`Aggregate source cannot be a ${x.dataType}`)}else return this.log(`Reference to undefined value ${this.source.refString}`),(0,$1.errorFor)(`Reference to undefined value ${this.source.refString}`)}if(o===void 0)return this.log("Missing expression for aggregate function"),(0,$1.errorFor)("agggregate without expression");if((0,Zz.expressionIsAggregate)(o.expressionType))return this.log("Aggregate expression cannot be aggregate"),(0,$1.errorFor)("reagggregate");if(!(o.dataType==="error")){const c=this.getJoinUsage(i),f=this.source!==void 0||this.explicitSource;if(s&&!(!this.source&&c.every(h=>h.length===0))&&!this.isSymmetricFunction()){const h=K4(a,c),p=X4(this.elementType,h),m=f?p:"Join path is required for this calculation";if(m){const g=f_e(m,c,s,this.elementType);this.log(g,p?"error":"warn")}}}if(this.typeCheck(this.expr||this,{...o,expressionType:"scalar"})){const c={type:"aggregate",function:this.func,e:o.value};return u&&u.length>0&&(c.structPath=u),{dataType:this.returns(o),expressionType:"aggregate",value:[c],evalSpace:"output"}}return(0,$1.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const n=[];if(this.source&&this.source.getField(e).found){const i=[{type:"field",path:this.source.path}];n.push(...Y4(e,i))}if(this.expr){const r=this.expr.getExpression(e).value;n.push(...Y4(e,r))}return n}}pl.ExprAggregateFunction=l_e;function c_e(t,e){let n=t.length;if(n!==e.length)return!1;for(;n>0;)if(n-=1,t[n].name!==e[n].name)return!1;return!0}function Y4(t,e){const n=[],r=(i,s)=>{const o=s[0],u=s.slice(1),a=i.entry(o);if(a===void 0)throw new Error(`Invalid field lookup ${o}`);if(a instanceof n_e.StructSpaceField&&u.length>0){const l=r(a.fieldSpace,u);return{...l,relationship:[{name:o,structRelationship:a.structRelationship},...l.relationship]}}else if(a instanceof u_e.SpaceField){if(u.length!==0)throw new Error(`${o} cannot contain a ${u.join(".")}`);const l=a.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,t_e.exprWalk)(e,i=>{if(typeof i!="string"){if(i.type==="field"){const s=r(t,i.path);if(s.def.type!=="struct"&&s.def.type!=="turtle")if(s.def.e){const o=Y4(s.fs,s.def.e);n.push(...o.map(u=>[...s.relationship,...u]))}else n.push(s.relationship)}else if(i.type==="source-reference")if(i.path){const s=r(t,i.path);n.push(s.relationship)}else n.push([])}}),n}function K4(t,e){const n=[];for(const r of e){let i=0;for(let a=0;a<t.length&&a<r.length&&t[a].name===r[a].name;a++)i=a+1;const s=t.slice(i),o=r.slice(i),u=[...s.map(a=>({...a,reverse:!0})),...o.map(a=>({...a,reverse:!1}))];n.push(u)}return n}function X4(t,e){for(const n of e)for(const r of n){if(r.structRelationship.type==="cross")return`Cannot compute \`${t}\` across \`join_cross\` relationship \`${r.name}\``;if(r.structRelationship.type==="many"&&!r.reverse)return`Cannot compute \`${t}\` across \`join_many\` relationship \`${r.name}\``;if(r.structRelationship.type==="nested"&&!r.reverse)return`Cannot compute \`${t}\` across repeated relationship \`${r.name}\``}}function f_e(t,e,n,r){if(e.length===0)return t;let i=e[0];for(const p of e.slice(1))for(let m=0;m<i.length;m++){const g=i[m],y=p[m];if(g.name!==y.name){i=i.slice(0,m);break}}const s=K4(i,e),o=X4(r,s),u=i.slice().reverse().findIndex(p=>p.structRelationship.type==="many"||p.structRelationship.type==="cross"),a=u===-1?0:i.length-u,l=i.slice(0,a),c=K4(l,e),f=X4(r,c),x=i.length>0?i.map(p=>p.name).join("."):"source",h=l.length>0?l.map(p=>p.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()`";{const p=n instanceof s_e.FieldReference?`${n.refString}.${r}()`:n instanceof a_e.ExprIdReference?`${n.fieldReference.refString}.${r}()`:`${x}.${r}(${n.code})`,m=`${h}.${r}(${n.code})`;let g=`${t}; use \`${p}\``;return f===void 0&&h!==x&&(g+=` or \`${m}\` to get a result weighted with respect to \`${h}\``),g}}var sC={};Object.defineProperty(sC,"__esModule",{value:!0}),sC.ExprAlternationTree=void 0;const eQ=Z,x_e=hr,d_e=hp,h_e=an;class p_e extends d_e.BinaryBoolean{constructor(e,n,r){super(e,n,r),this.elementType="alternation",this.elementType=`${n}alternation${n}`}apply(e,n,r){const i=this.left.apply(e,n,r),s=this.right.apply(e,n,r);return{dataType:"boolean",expressionType:(0,eQ.maxExpressionType)(i.expressionType,s.expressionType),evalSpace:(0,eQ.mergeEvalSpaces)(i.evalSpace,s.evalSpace),value:(0,h_e.compose)(i.value,this.op==="&"?"and":"or",s.value)}}requestExpression(e){}getExpression(e){return this.log("Alternation tree has no value"),(0,x_e.errorFor)("no value from alternation tree")}}sC.ExprAlternationTree=p_e;var mp={};Object.defineProperty(mp,"__esModule",{value:!0}),mp.ExprAsymmetric=void 0;const g_e=pl;class m_e extends g_e.ExprAggregateFunction{constructor(e,n,r,i){super(e,n,i),this.func=e,this.expr=n,this.source=r,this.has({source:r})}isSymmetricFunction(){return!1}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}mp.ExprAsymmetric=m_e;var oC={};Object.defineProperty(oC,"__esModule",{value:!0}),oC.ExprAvg=void 0;const y_e=mp;class E_e extends y_e.ExprAsymmetric{constructor(e,n,r){super("avg",e,n,r),this.has({source:n})}}oC.ExprAvg=E_e;var uC={};Object.defineProperty(uC,"__esModule",{value:!0}),uC.ExprCast=void 0;const A_e=On,S_e=dt,v_e=an;class __e extends S_e.ExpressionDef{constructor(e,n,r=!1){super({expr:e}),this.expr=e,this.castType=n,this.safe=r,this.elementType="cast"}getExpression(e){var n,r,i;const s=this.expr.getExpression(e);let o="sql native";if(typeof this.castType=="string")o=this.castType;else{const u=e.dialectObj();u&&(u.validateTypeName(this.castType.raw)?o=(i=(r=(n=e.dialectObj())===null||n===void 0?void 0:n.sqlTypeToMalloyType(this.castType.raw))===null||r===void 0?void 0:r.type)!==null&&i!==void 0?i:"sql native":this.log(`Cast type \`${this.castType.raw}\` is invalid for ${u.name} dialect`))}return{dataType:o,expressionType:s.expressionType,value:(0,v_e.compressExpr)((0,A_e.castTo)(this.castType,s.value,s.dataType,this.safe)),evalSpace:s.evalSpace}}}uC.ExprCast=__e;var aC={};Object.defineProperty(aC,"__esModule",{value:!0}),aC.ExprCoalesce=void 0;const J4=Ru,tQ=ln,C_e=dt;class b_e extends C_e.ExpressionDef{constructor(e,n){super({expr:e,altExpr:n}),this.expr=e,this.altExpr=n,this.elementType="coalesce expression",this.legalChildTypes=tQ.FT.anyAtomicT}getExpression(e){const n=this.expr.getExpression(e),r=this.altExpr.getExpression(e);return n.dataType==="null"?r:(tQ.FT.typeEq(n,r)||this.log(`Mismatched types for coalesce (${n.dataType}, ${r.dataType})`),{...r,dataType:n.dataType==="error"?r.dataType:n.dataType,expressionType:(0,J4.maxExpressionType)(n.expressionType,r.expressionType),value:(0,J4.mkExpr)`COALESCE(${n.value},${r.value})`,evalSpace:(0,J4.mergeEvalSpaces)(n.evalSpace,r.evalSpace)})}}aC.ExprCoalesce=b_e;var lC={};Object.defineProperty(lC,"__esModule",{value:!0}),lC.ExprCount=void 0;const T_e=pl;class R_e extends T_e.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){const n={type:"aggregate",function:"count",e:[]};return this.source&&(n.structPath=this.source.path),{dataType:"number",expressionType:"aggregate",value:[n],evalSpace:"output"}}}lC.ExprCount=R_e;var cC={};Object.defineProperty(cC,"__esModule",{value:!0}),cC.ExprCountDistinct=void 0;const fC=ln,O_e=pl;class N_e extends O_e.ExprAggregateFunction{constructor(e){super("count_distinct",e),this.legalChildTypes=[fC.FT.numberT,fC.FT.stringT,fC.FT.dateT,fC.FT.timestampT]}}cC.ExprCountDistinct=N_e;var xC={},M0={};Object.defineProperty(M0,"__esModule",{value:!0}),M0.Limit=void 0;const D_e=Ve,F_e=Rn;class w_e extends D_e.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=F_e.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}M0.Limit=w_e;var yp={};Object.defineProperty(yp,"__esModule",{value:!0}),yp.PartitionBy=void 0;const L_e=Ve;class I_e extends L_e.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}yp.PartitionBy=I_e;var B1={},j0={};Object.defineProperty(j0,"__esModule",{value:!0}),j0.FieldName=void 0;const $_e=Ve;class B_e extends $_e.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])}}j0.FieldName=B_e,Object.defineProperty(B1,"__esModule",{value:!0}),B1.ExprFunc=void 0;const so=Z,Yu=hr,k_e=ax,P_e=dt,M_e=j0,nQ=an;class j_e extends P_e.ExpressionDef{constructor(e,n,r,i,s){super({args:n}),this.name=e,this.args=n,this.isRaw=r,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,n){var r,i,s,o,u;const a=this.args.map(R=>R.getExpression(e));if(this.isRaw){let R="scalar",I;const M=[`${this.name}(`];for(const Y of a)R=(0,so.maxExpressionType)(R,Y.expressionType),I?M.push(","):I=Y.dataType,M.push(...Y.value);return M.push(")"),{dataType:(i=(r=this.rawType)!==null&&r!==void 0?r:I)!==null&&i!==void 0?i:"number",expressionType:R,value:(0,nQ.compressExpr)(M),evalSpace:(0,so.mergeEvalSpaces)(...a.map(Y=>Y.evalSpace))}}const 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,Yu.errorFor)("unknown function");if(l.type!=="function")return this.log(`Cannot call '${this.name}', which is of type ${l.type}`),(0,Yu.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){const R=this.source.getField(e).found;if(R){const I=R.typeDesc();if((0,so.isAtomicFieldType)(I.dataType))c={dataType:I.dataType,expressionType:I.expressionType,value:[{type:"field",path:this.source.path}],evalSpace:I.evalSpace},f=this.source.path.slice(0,-1);else if(!(R instanceof k_e.StructSpaceFieldBase)){const M=`Aggregate source cannot be a ${I.dataType}`;return this.log(M),(0,Yu.errorFor)(M)}}else{const I=`Reference to undefined value ${this.source.refString}`;return this.log(I),(0,Yu.errorFor)(I)}}const x=[...c?[c]:[],...a],h=U_e(l,x);if(h===void 0)return this.log(`No matching overload for function ${this.name}(${x.map(R=>R.dataType).join(", ")})`),(0,Yu.errorFor)("no matching overload");const{overload:p,expressionTypeErrors:m,evalSpaceErrors:g,nullabilityErrors:y}=h;for(const R of m){const I=R.argIndex-(c?1:0),M=(0,so.expressionIsScalar)(R.maxExpressionType)?"scalar":"scalar or aggregate";this.args[I].log(`Parameter ${R.argIndex+1} ('${R.param.name}') of ${this.name} must be ${M}, but received ${R.actualExpressionType}`)}for(const R of g){const I=R.argIndex-(c?1:0),M=R.maxEvalSpace==="literal"?"literal":R.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[I].log(`Parameter ${R.argIndex+1} ('${R.param.name}') of ${this.name} must be ${M}, but received ${R.actualEvalSpace}`)}for(const R of y){const I=R.argIndex-(c?1:0);this.args[I].log(`Parameter ${R.argIndex+1} ('${R.param.name}') of ${this.name} must not be a literal null`)}const E=p.returnType,A=(0,so.maxOfExpressionTypes)([E.expressionType,...x.map(R=>R.expressionType)]);if(!(0,so.expressionIsAggregate)(p.returnType.expressionType)&&this.source!==void 0)return this.log(`Cannot call function ${this.name}(${x.map(R=>R.dataType).join(", ")}) with source`),(0,Yu.errorFor)("cannot call with source");const S={type:"function_call",overload:p,name:this.name,args:x.map(R=>R.value),expressionType:A,structPath:f};let v=[S];const _=(u=e.dialectObj())===null||u===void 0?void 0:u.name,C=_?p.dialect[_]:void 0;if(C===void 0)this.log(`Function ${this.name} is not defined in dialect ${_}`);else{if(n!=null&&n.orderBys&&n.orderBys.length>0){const R=(0,so.expressionIsAnalytic)(p.returnType.expressionType);if(R||this.inExperiment("aggregate_order_by",!0)||n.orderBys[0].log("Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),C.supportsOrderBy||R){const I=C.supportsOrderBy!=="only_default",M=n.orderBys.flatMap(z=>R?z.getAnalyticOrderBy(e):z.getAggregateOrderBy(e,I));S.orderBy=M}else n.orderBys[0].log(`Function \`${this.name}\` does not support \`order_by\``)}(n==null?void 0:n.limit)!==void 0&&(C.supportsLimit?S.limit=n.limit.limit:this.log(`Function ${this.name} does not support limit`))}if(n!=null&&n.partitionBys&&n.partitionBys.length>0){const R=[];for(const I of n.partitionBys)for(const M of I.partitionFields){const z=M.getField(e);z.found===void 0?M.log(`${M.refString} is not defined`):(0,so.expressionIsAnalytic)(z.found.typeDesc().expressionType)||(0,so.expressionIsUngroupedAggregate)(z.found.typeDesc().expressionType)?M.log("Partition expression must be scalar or aggregate"):R.push(M.nameString)}S.partitionBy=R}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(l.name)){if(!this.inExperiment("sql_functions",!0)){const I=`Cannot use sql_function \`${l.name}\`; use \`sql_functions\` experiment to enable this behavior`;return this.log(I),(0,Yu.errorFor)("sql_function used without enabling")}const R=x[0].value;if(R.length!==1||typeof R[0]=="string"||R[0].type!=="dialect"||R[0].function!=="stringLiteral")this.log(`Invalid string literal for \`${l.name}\``);else{const I=R[0].literal,M=q_e(I),z=M.filter(Q=>Q.type==="interpolation"&&Q.name.includes(".")).map(Q=>Q.type==="interpolation"?`\${${Q.name}}`:`\${${Q.value}}`);if(z.length>0){const Q=z.length===1?`'.' paths are not yet supported in sql interpolations, found ${z.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${z.join(", ")})`;return this.log(Q),(0,Yu.errorFor)(`${Q}. See LookML \${...} documentation at https://cloud.google.com/looker/docs/reference/param-field-sql#sql_for_dimensions`)}const Y=[];for(const Q of M)if(Q.type==="string")Y.push(Q.value);else if(Q.name==="TABLE")Y.push({type:"source-reference"});else{const oe=new M_e.FieldName(Q.name);this.has({name:oe});const de=e.lookup([oe]);if(de.found===void 0)return this.log(`Invalid interpolation: ${de.error}`),(0,Yu.errorFor)("invalid interpolated field");de.found.refType==="parameter"?Y.push({type:"parameter",path:[Q.name]}):Y.push({type:"field",path:[Q.name]})}v=[{type:"sql-string",e:Y}]}}if(E.dataType==="any")return this.log(`Invalid return type ${E.dataType} for function '${this.name}'`),(0,Yu.errorFor)("invalid return type");const b=(0,so.mergeEvalSpaces)(...x.map(R=>R.evalSpace)),O=b==="constant"?"constant":(0,so.expressionIsScalar)(A)?b:"output";return{dataType:E.dataType,expressionType:A,value:(0,nQ.compressExpr)(v),evalSpace:O}}}B1.ExprFunc=j_e;function U_e(t,e){for(const n of t.overloads){let r=0,i=!0,s=!1;const o=[],u=[],a=[];for(let l=0;l<e.length;l++){const c=e[l],f=n.params[r];if(f===void 0){i=!1;break}if(!f.allowedTypes.some(h=>{const p=h.dataType===c.dataType||h.dataType==="any"||c.dataType==="null"||c.dataType==="error";return h.expressionType&&((0,so.isExpressionTypeLEQ)(c.expressionType,h.expressionType)||o.push({argIndex:l,maxExpressionType:h.expressionType,actualExpressionType:c.expressionType,param:f})),(h.evalSpace==="literal"&&c.evalSpace!=="literal"||h.evalSpace==="constant"&&(c.evalSpace==="input"||c.evalSpace==="output")||h.evalSpace==="output"&&c.evalSpace==="input")&&u.push({argIndex:l,param:f,maxEvalSpace:h.evalSpace,actualEvalSpace:c.evalSpace}),h.evalSpace==="literal"&&c.dataType==="null"&&a.push({argIndex:l,param:f}),p})){i=!1;break}f.isVariadic?l===e.length-1&&(s=!0):r++}if(!(!s&&(r!==e.length||r!==n.params.length))&&i)return{overload:n,expressionTypeErrors:o,evalSpaceErrors:u,nullabilityErrors:a}}}function q_e(t){const e=[];let n=t;for(;n.length;){const r=n.indexOf("${");if(r===-1){e.push({type:"string",value:n});break}else{const i=n.slice(r).indexOf("}");if(i===-1){e.push({type:"string",value:n});break}r>0&&e.push({type:"string",value:n.slice(0,r)}),e.push({type:"interpolation",name:n.slice(r+2,i+r)}),n=n.slice(i+r+1)}}return e}Object.defineProperty(xC,"__esModule",{value:!0}),xC.ExprProps=void 0;const H_e=Z,z_e=hr,Q_e=ln,G_e=k0,W_e=M0,V_e=yp,Y_e=dt,K_e=B1;class X_e extends Y_e.ExpressionDef{constructor(e,n){super({expr:e,statements:n}),this.expr=e,this.statements=n,this.elementType="expression with props",this.legalChildTypes=Q_e.FT.anyAtomicT}getFilteredExpression(e,n,r){if(r.length>0){if(!this.expr.supportsWhere(n))return this.expr.log("Filtered expression requires an aggregate computation"),n;const i=[];for(const s of r){const o=s.getFilterList(e);if(o.find(u=>(0,H_e.expressionIsCalculation)(u.expressionType)))return s.log("Cannot filter an expresion with an aggregate or analytical computation"),n;i.push(...o)}return this.typeCheck(this.expr,{...n,expressionType:"scalar"})?{...n,value:[{type:"filterExpression",e:n.value,filterList:i}]}:(this.expr.log(`Cannot filter '${n.dataType}' data`),(0,z_e.errorFor)("cannot filter type"))}return n}getExpression(e){const n=[];let r;const i=[],s=[];for(const u of this.statements)u instanceof V_e.PartitionBy?this.expr.canSupportPartitionBy()?n.push(u):u.log("`partition_by` is not supported for this kind of expression"):u instanceof W_e.Limit?r?u.log("limit already specified"):this.expr.canSupportLimit()?r=u:u.log("`limit` is not supported for this kind of expression"):u instanceof G_e.FunctionOrdering?this.expr.canSupportPartitionBy()?i.push(u):u.log("`order_by` is not supported for this kind of expression"):s.push(u);const o=this.expr instanceof K_e.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:n,limit:r,orderBys:i}):this.expr.getExpression(e);return this.getFilteredExpression(e,o,s)}}xC.ExprProps=X_e;var dC={};Object.defineProperty(dC,"__esModule",{value:!0}),dC.ExprLogicalOp=void 0;const J_e=hp,rQ=ln;class Z_e extends J_e.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[rQ.FT.boolT,rQ.FT.aggregateBoolT]}}dC.ExprLogicalOp=Z_e;var hC={};Object.defineProperty(hC,"__esModule",{value:!0}),hC.ExprMax=void 0;const pC=ln,eCe=pl;class tCe extends eCe.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[pC.FT.numberT,pC.FT.stringT,pC.FT.dateT,pC.FT.timestampT]}returns(e){return e.dataType}}hC.ExprMax=tCe;var gC={};Object.defineProperty(gC,"__esModule",{value:!0}),gC.ExprMin=void 0;const mC=ln,nCe=pl;class rCe extends nCe.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[mC.FT.numberT,mC.FT.stringT,mC.FT.dateT,mC.FT.timestampT]}returns(e){return e.dataType}}gC.ExprMin=rCe;var yC={};Object.defineProperty(yC,"__esModule",{value:!0}),yC.ExprMinus=void 0;const iCe=hr,iQ=ln,sCe=dt;class oCe extends sCe.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[iQ.FT.numberT]}getExpression(e){const n=this.expr.getExpression(e);return iQ.FT.typeIn(n,this.legalChildTypes)?n.value.length>1?{...n,dataType:"number",value:["-(",...n.value,")"]}:{...n,dataType:"number",value:["-",...n.value]}:(0,iCe.errorFor)("negate requires number")}}yC.ExprMinus=oCe;var EC={};Object.defineProperty(EC,"__esModule",{value:!0}),EC.ExprMulDiv=void 0;const uCe=gp;class aCe extends uCe.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}EC.ExprMulDiv=aCe;var AC={},k1={};Object.defineProperty(k1,"__esModule",{value:!0}),k1.Unary=void 0;const lCe=dt;class cCe extends lCe.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}k1.Unary=cCe,Object.defineProperty(AC,"__esModule",{value:!0}),AC.ExprNot=void 0;const sQ=ln,fCe=k1,xCe=an;class dCe extends fCe.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[sQ.FT.boolT,sQ.FT.nullT]}getExpression(e){const n=this.expr.getExpression(e),r=this.typeCheck(this.expr,n);return{...n,dataType:"boolean",value:r?(0,xCe.nullsafeNot)(n.value):["false"]}}}AC.ExprNot=dCe;var SC={};Object.defineProperty(SC,"__esModule",{value:!0}),SC.ExprNow=void 0;const hCe=dt;class pCe extends hCe.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{dataType:"timestamp",expressionType:"scalar",evalSpace:"constant",value:[{type:"dialect",function:"now"}]}}}SC.ExprNow=pCe;var vC={};Object.defineProperty(vC,"__esModule",{value:!0}),vC.ExprNULL=void 0;const gCe=dt;class mCe extends gCe.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return{dataType:"null",value:["NULL"],expressionType:"scalar",evalSpace:"literal"}}}vC.ExprNULL=mCe;var _C={};Object.defineProperty(_C,"__esModule",{value:!0}),_C.ExprNumber=void 0;const yCe=ln,ECe=dt;class ACe extends ECe.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){return{...yCe.FT.numberT,evalSpace:"literal",value:[{type:"dialect",function:"numberLiteral",literal:this.n}]}}}_C.ExprNumber=ACe;var CC={};Object.defineProperty(CC,"__esModule",{value:!0}),CC.ExprParens=void 0;const SCe=dt;class vCe extends SCe.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const n=this.expr.getExpression(e);return{...n,value:["(",...n.value,")"]}}}CC.ExprParens=vCe;var bC={};Object.defineProperty(bC,"__esModule",{value:!0}),bC.ExprRegEx=void 0;const _Ce=dt;class CCe extends _Ce.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"}}}bC.ExprRegEx=CCe;var TC={};Object.defineProperty(TC,"__esModule",{value:!0}),TC.ExprString=void 0;const bCe=dt,TCe=ln;class RCe extends bCe.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return{...TCe.FT.stringT,value:[{type:"dialect",function:"stringLiteral",literal:this.value}],evalSpace:"literal"}}}TC.ExprString=RCe;var RC={};Object.defineProperty(RC,"__esModule",{value:!0}),RC.ExprSum=void 0;const OCe=mp;class NCe extends OCe.ExprAsymmetric{constructor(e,n,r){super("sum",e,n,r),this.has({source:n})}}RC.ExprSum=NCe;var OC={};Object.defineProperty(OC,"__esModule",{value:!0}),OC.ExprTimeExtract=void 0;const dx=Z,U0=hr,Z4=dt,DCe=B0;class P1 extends Z4.ExpressionDef{static extractor(e){const n=P1.pluralMap[e];if(n)return n;if((0,dx.isExtractUnit)(e))return e}constructor(e,n){super({args:n}),this.extractText=e,this.args=n,this.elementType="timeExtract"}getExpression(e){const n=P1.extractor(this.extractText);if(n){if(this.args.length!==1)return this.log(`Extraction function ${n} requires one argument`),(0,U0.errorFor)("{this.name} arg count");const r=this.args[0];if(r instanceof DCe.Range){let i=r.first.getExpression(e),s=r.last.getExpression(e);const o=(0,dx.maxExpressionType)(i.expressionType,s.expressionType),u=(0,dx.mergeEvalSpaces)(i.evalSpace,s.evalSpace);if(i.dataType==="error"||s.dataType==="error")return{dataType:"number",expressionType:o,evalSpace:u,value:(0,U0.errorFor)("extract from error").value};if(!(0,dx.isTimeFieldType)(i.dataType))return r.first.log(`Can't extract ${n} from '${i.dataType}'`),(0,U0.errorFor)(`${n} bad type ${i.dataType}`);if(!(0,dx.isTimeFieldType)(s.dataType))return r.last.log(`Cannot extract ${n} from '${s.dataType}'`),(0,U0.errorFor)(`${n} bad type ${s.dataType}`);let a=i.dataType;if(i.dataType!==s.dataType){let l=!0;if(a="timestamp",i.dataType==="date"){const c=(0,Z4.getMorphicValue)(i,"timestamp");c&&(i=c,l=!1)}else{const c=(0,Z4.getMorphicValue)(s,"timestamp");c&&(s=c,l=!1)}if(l)return r.first.log(`Cannot measure from ${i.dataType} to ${s.dataType}`),(0,U0.errorFor)(`${n} range mismatch`)}return["week","month","quarter","year"].includes(n)?(this.log(`Cannot measure interval using '${n}'`),(0,U0.errorFor)(`${n} civil extraction`)):(0,dx.isTimestampUnit)(n)?{dataType:"number",expressionType:o,evalSpace:u,value:[{type:"dialect",function:"timeDiff",units:n,left:{valueType:a,value:i.value},right:{valueType:a,value:s.value}}]}:(this.log(`Cannot extract ${n} from a range`),(0,U0.errorFor)(`${n} bad extraction`))}else{const i=r.getExpression(e);return(0,dx.isTimeFieldType)(i.dataType)?{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:[{type:"dialect",function:"extract",expr:{value:i.value,valueType:i.dataType},units:n}]}:(i.dataType!=="error"&&this.log(`${this.extractText}() requires time type, not '${i.dataType}'`),{dataType:"number",expressionType:i.expressionType,evalSpace:i.evalSpace,value:(0,U0.errorFor)(`${this.extractText} bad type ${i.dataType}`).value})}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}OC.ExprTimeExtract=P1,P1.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var NC={},Ho={},DC={};Object.defineProperty(DC,"__esModule",{value:!0}),DC.QueryInputSpace=void 0;const FCe=ts,wCe=b1,LCe=tp;class ICe extends LCe.RefinedSpace{constructor(e,n){const r=new wCe.SpaceSeed(e);super(r.structDef),this.queryOutput=n,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof FCe.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}}DC.QueryInputSpace=ICe;var $Ce=F&&F.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),BCe=F&&F.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),kCe=F&&F.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&$Ce(e,t,n);return BCe(e,t),e};Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.ReduceFieldSpace=Ho.QuerySpace=Ho.QueryOperationSpace=void 0;const FC=kCe(Z),eL=w0,PCe=j0,MCe=Kr,jCe=ht,UCe=tp,qCe=C1,HCe=Jr,zCe=DC;class oQ extends UCe.RefinedSpace{constructor(e,n,r,i){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=r,this.astEl=i,this.expandedWild={},this.exprSpace=new zCe.QueryInputSpace(e,this),n&&this.addRefineFromFields(n)}log(e){this.astEl&&this.astEl.log(e)}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var n;let r=this.exprSpace;const i=[];if(e.joinPath)for(const u of e.joinPath.list){const a=u.refString;i.push(a);const l=r.entry(a);if(l)if(l instanceof HCe.StructSpaceField)r=l.fieldSpace;else{u.log(`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.log(`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries())if(!e.except.has(u)&&a.refType!=="parameter")if(this.entry(u)){const l=(n=this.expandedWild[u])===null||n===void 0?void 0:n.join(".");e.log(`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${l?` (conflicts with ${l})`:""}`)}else{const l=a.typeDesc();FC.isAtomicFieldType(l.dataType)&&FC.expressionIsScalar(l.expressionType)&&(s===void 0||!s.ignoreInProject(u))&&(o.push({name:u,entry:a}),this.expandedWild[u]=i.concat(u))}for(const u of o.sort((a,l)=>a.name.localeCompare(l.name)))this.setEntry(u.name,u.entry)}}Ho.QueryOperationSpace=oQ;class uQ extends oQ{addRefineFromFields(e){var n;if(FC.isQuerySegment(e))for(const r of e.queryFields)if(r.type==="fieldref"){const i=this.exprSpace.lookup(r.path.map(s=>new PCe.FieldName(s)));i.found&&this.setEntry(r.path[r.path.length-1],i.found)}else r.type!=="turtle"&&this.setEntry((n=r.as)!==null&&n!==void 0?n:r.name,new qCe.ColumnSpaceField(r))}pushFields(...e){for(const n of e)n instanceof jCe.WildcardFieldReference?this.addWild(n):super.pushFields(n)}canContain(e){return!0}queryFieldDefs(){const e=[];for(const[n,r]of this.entries())if(r instanceof MCe.SpaceField){const i=this.expandedWild[n];if(i){e.push({type:"fieldref",path:i});continue}const s=r.getQueryFieldDef(this.exprSpace);if(s){const o=r.typeDesc();o.dataType!=="error"&&this.canContain(o)&&!GCe(s)&&e.push(s)}}return this.isComplete(),e}getQuerySegment(e){const n=this.getPipeSegment(e);if(FC.isQuerySegment(n))return n;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!=null&&e.extendSource)for(const r of e.extendSource)this.exprSpace.addFieldDef(r);const n={type:this.segmentType,queryFields:this.queryFieldDefs()};if(n.queryFields=(0,eL.mergeFields)(e==null?void 0:e.queryFields,n.queryFields),e!=null&&e.extendSource&&(n.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const r=[],i=this.exprSpace.structDef();for(const s of this.exprSpace.extendList){const o=i.fields.find(u=>(0,eL.nameFromDef)(u)===s);o&&r.push(o)}n.extendSource=(0,eL.mergeFields)(n.extendSource,r)}return this.newTimezone&&(n.queryTimezone=this.newTimezone),this.isComplete(),n}lookup(e){const n=super.lookup(e);return n.found?{...n,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}Ho.QuerySpace=uQ;class QCe extends uQ{constructor(){super(...arguments),this.segmentType="reduce"}}Ho.ReduceFieldSpace=QCe;function GCe(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}Object.defineProperty(NC,"__esModule",{value:!0}),NC.ExprUngroup=void 0;const aQ=Z,tL=hr,WCe=Ho,VCe=ln,YCe=dt;class KCe extends YCe.ExpressionDef{constructor(e,n,r){super({expr:n,fields:r}),this.control=e,this.expr=n,this.fields=r,this.legalChildTypes=VCe.FT.anyAtomicT,this.elementType="ungroup"}returns(e){return"number"}getExpression(e){const n=this.expr.getExpression(e);if(!(0,aQ.expressionIsAggregate)(n.expressionType))return this.expr.log(`${this.control}() expression must be an aggregate`),(0,tL.errorFor)("ungrouped scalar");if((0,aQ.expressionIsUngroupedAggregate)(n.expressionType))return this.expr.log(`${this.control}() expression must not already be ungrouped`),(0,tL.errorFor)("doubly-ungrouped aggregate");const r={type:this.control,e:n.value};if(this.typeCheck(this.expr,{...n,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const i=[],s=this.control==="exclude";for(const o of this.fields){let u=e.outputSpace(),a=!0;for(;u;){const l=u.lookup([o]);if(l.found&&l.isOutputField)i.push(o.refString),a=!1;else if(u instanceof WCe.QuerySpace){u=u.nestParent;continue}break}if(a){const l=s?"exclude()":"all()";o.log(`${l} '${o.refString}' is missing from query output`)}}r.fields=i}return{dataType:this.returns(n),expressionType:"ungrouped_aggregate",value:[r],evalSpace:"output"}}return this.log(`${this.control}() incompatible type`),(0,tL.errorFor)("ungrouped type check")}}NC.ExprUngroup=KCe;var wC={};Object.defineProperty(wC,"__esModule",{value:!0}),wC.ForRange=void 0;const lQ=Ru,nL=hr,cQ=ln,LC=On,XCe=dt,IC=pp,fQ=B0;class JCe extends XCe.ExpressionDef{constructor(e,n,r){super({from:e,duration:n,timeframe:r}),this.from=e,this.duration=n,this.timeframe=r,this.elementType="forRange",this.legalChildTypes=[cQ.FT.timestampT,cQ.FT.dateT]}apply(e,n,r){const i=this.from.getExpression(e),s=r.getExpression(e);if(!this.typeCheck(r,s))return(0,nL.errorFor)("no time for range");const 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,lQ.mergeEvalSpaces)(i.evalSpace,s.evalSpace),expressionType:(0,lQ.maxExpressionType)(i.expressionType,s.expressionType),value:(0,nL.errorFor)("for not number").value};const u=this.timeframe.text;let a=(0,LC.resolution)(u);if(i.dataType==="timestamp"&&(a="timestamp"),s.dataType==="date"&&a==="date"){const p=this.from,m=(0,LC.timeOffset)("date",i.value,"+",o.value,u),g=new IC.ExprTime("date",m);return new fQ.Range(p,g).apply(e,n,r)}const l=IC.ExprTime.fromValue("timestamp",s);let c=this.from,f=i.value;if(i.dataType==="date"){const p=i.morphic&&i.morphic.timestamp;p?f=p:f=(0,LC.castDateToTimestamp)(f),c=new IC.ExprTime("timestamp",f,i.expressionType)}const x=(0,LC.timeOffset)("timestamp",f,"+",o.value,u),h=new IC.ExprTime("timestamp",x,i.expressionType);return new fQ.Range(c,h).apply(e,n,l)}requestExpression(e){}getExpression(e){return this.log("A Range is not a value"),(0,nL.errorFor)("range has no value")}}wC.ForRange=JCe;var pr={},rs={};Object.defineProperty(rs,"__esModule",{value:!0});class hx extends Error{}class ZCe extends hx{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class ebe extends hx{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class tbe extends hx{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class M1 extends hx{}class xQ extends hx{constructor(e){super(`Invalid unit ${e}`)}}class oo extends hx{}class q0 extends hx{constructor(){super("Zone is an abstract class")}}const ke="numeric",zo="short",Ds="long",rL={year:ke,month:ke,day:ke},dQ={year:ke,month:zo,day:ke},nbe={year:ke,month:zo,day:ke,weekday:zo},hQ={year:ke,month:Ds,day:ke},pQ={year:ke,month:Ds,day:ke,weekday:Ds},gQ={hour:ke,minute:ke},mQ={hour:ke,minute:ke,second:ke},yQ={hour:ke,minute:ke,second:ke,timeZoneName:zo},EQ={hour:ke,minute:ke,second:ke,timeZoneName:Ds},AQ={hour:ke,minute:ke,hourCycle:"h23"},SQ={hour:ke,minute:ke,second:ke,hourCycle:"h23"},vQ={hour:ke,minute:ke,second:ke,hourCycle:"h23",timeZoneName:zo},_Q={hour:ke,minute:ke,second:ke,hourCycle:"h23",timeZoneName:Ds},CQ={year:ke,month:ke,day:ke,hour:ke,minute:ke},bQ={year:ke,month:ke,day:ke,hour:ke,minute:ke,second:ke},TQ={year:ke,month:zo,day:ke,hour:ke,minute:ke},RQ={year:ke,month:zo,day:ke,hour:ke,minute:ke,second:ke},rbe={year:ke,month:zo,day:ke,weekday:zo,hour:ke,minute:ke},OQ={year:ke,month:Ds,day:ke,hour:ke,minute:ke,timeZoneName:zo},NQ={year:ke,month:Ds,day:ke,hour:ke,minute:ke,second:ke,timeZoneName:zo},DQ={year:ke,month:Ds,day:ke,weekday:Ds,hour:ke,minute:ke,timeZoneName:Ds},FQ={year:ke,month:Ds,day:ke,weekday:Ds,hour:ke,minute:ke,second:ke,timeZoneName:Ds};function St(t){return typeof t>"u"}function px(t){return typeof t=="number"}function $C(t){return typeof t=="number"&&t%1===0}function ibe(t){return typeof t=="string"}function sbe(t){return Object.prototype.toString.call(t)==="[object Date]"}function wQ(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function obe(t){return Array.isArray(t)?t:[t]}function LQ(t,e,n){if(t.length!==0)return t.reduce((r,i)=>{const s=[e(i),i];return r&&n(r[0],s[0])===r[0]?r:s},null)[1]}function ube(t,e){return e.reduce((n,r)=>(n[r]=t[r],n),{})}function Ep(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function gl(t,e,n){return $C(t)&&t>=e&&t<=n}function abe(t,e){return t-e*Math.floor(t/e)}function Hn(t,e=2){const n=t<0;let r;return n?r="-"+(""+-t).padStart(e,"0"):r=(""+t).padStart(e,"0"),r}function H0(t){if(!(St(t)||t===null||t===""))return parseInt(t,10)}function gx(t){if(!(St(t)||t===null||t===""))return parseFloat(t)}function iL(t){if(!(St(t)||t===null||t==="")){const e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function sL(t,e,n=!1){const r=10**e;return(n?Math.trunc:Math.round)(t*r)/r}function j1(t){return t%4===0&&(t%100!==0||t%400===0)}function U1(t){return j1(t)?366:365}function BC(t,e){const n=abe(e-1,12)+1,r=t+(e-n)/12;return n===2?j1(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function oL(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 kC(t){const e=(t+Math.floor(t/4)-Math.floor(t/100)+Math.floor(t/400))%7,n=t-1,r=(n+Math.floor(n/4)-Math.floor(n/100)+Math.floor(n/400))%7;return e===4||r===3?53:52}function uL(t){return t>99?t:t>60?1900+t:2e3+t}function IQ(t,e,n,r=null){const i=new Date(t),s={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};r&&(s.timeZone=r);const o={timeZoneName:e,...s},u=new Intl.DateTimeFormat(n,o).formatToParts(i).find(a=>a.type.toLowerCase()==="timezonename");return u?u.value:null}function PC(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);const r=parseInt(e,10)||0,i=n<0||Object.is(n,-0)?-r:r;return n*60+i}function $Q(t){const e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new oo(`Invalid unit value ${t}`);return e}function MC(t,e){const n={};for(const r in t)if(Ep(t,r)){const i=t[r];if(i==null)continue;n[e(r)]=$Q(i)}return n}function q1(t,e){const n=Math.trunc(Math.abs(t/60)),r=Math.trunc(Math.abs(t%60)),i=t>=0?"+":"-";switch(e){case"short":return`${i}${Hn(n,2)}:${Hn(r,2)}`;case"narrow":return`${i}${n}${r>0?`:${r}`:""}`;case"techie":return`${i}${Hn(n,2)}${Hn(r,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function jC(t){return ube(t,["hour","minute","second","millisecond"])}const BQ=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/,lbe=["January","February","March","April","May","June","July","August","September","October","November","December"],kQ=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],cbe=["J","F","M","A","M","J","J","A","S","O","N","D"];function PQ(t){switch(t){case"narrow":return[...cbe];case"short":return[...kQ];case"long":return[...lbe];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}}const MQ=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],jQ=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],fbe=["M","T","W","T","F","S","S"];function UQ(t){switch(t){case"narrow":return[...fbe];case"short":return[...jQ];case"long":return[...MQ];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const qQ=["AM","PM"],xbe=["Before Christ","Anno Domini"],dbe=["BC","AD"],hbe=["B","A"];function HQ(t){switch(t){case"narrow":return[...hbe];case"short":return[...dbe];case"long":return[...xbe];default:return null}}function pbe(t){return qQ[t.hour<12?0:1]}function gbe(t,e){return UQ(e)[t.weekday-1]}function mbe(t,e){return PQ(e)[t.month-1]}function ybe(t,e){return HQ(e)[t.year<0?0:1]}function Ebe(t,e,n="always",r=!1){const 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(n==="auto"&&s){const 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]}`}}const o=Object.is(e,-0)||e<0,u=Math.abs(e),a=u===1,l=i[t],c=r?a?l[1]:l[2]||l[1]:a?i[t][0]:t;return o?`${u} ${c} ago`:`in ${u} ${c}`}function zQ(t,e){let n="";for(const r of t)r.literal?n+=r.val:n+=e(r.val);return n}const Abe={D:rL,DD:dQ,DDD:hQ,DDDD:pQ,t:gQ,tt:mQ,ttt:yQ,tttt:EQ,T:AQ,TT:SQ,TTT:vQ,TTTT:_Q,f:CQ,ff:TQ,fff:OQ,ffff:DQ,F:bQ,FF:RQ,FFF:NQ,FFFF:FQ};class is{static create(e,n={}){return new is(e,n)}static parseFormat(e){let n=null,r="",i=!1;const s=[];for(let o=0;o<e.length;o++){const u=e.charAt(o);u==="'"?(r.length>0&&s.push({literal:i,val:r}),n=null,r="",i=!i):i||u===n?r+=u:(r.length>0&&s.push({literal:!1,val:r}),r=u,n=u)}return r.length>0&&s.push({literal:i,val:r}),s}static macroTokenToFormatOpts(e){return Abe[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}formatDateTime(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).format()}formatDateTimeParts(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).formatToParts()}resolvedOptions(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n}).resolvedOptions()}num(e,n=0){if(this.opts.forceSimple)return Hn(e,n);const r={...this.opts};return n>0&&(r.padTo=n),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){const r=this.loc.listingMode()==="en",i=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",s=(h,p)=>this.loc.extract(e,h,p),o=h=>e.isOffsetFixed&&e.offset===0&&h.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,h.format):"",u=()=>r?pbe(e):s({hour:"numeric",hourCycle:"h12"},"dayperiod"),a=(h,p)=>r?mbe(e,h):s(p?{month:h}:{month:h,day:"numeric"},"month"),l=(h,p)=>r?gbe(e,h):s(p?{weekday:h}:{weekday:h,month:"long",day:"numeric"},"weekday"),c=h=>{const p=is.macroTokenToFormatOpts(h);return p?this.formatWithSystemDefault(e,p):h},f=h=>r?ybe(e,h):s({era:h},"era"),x=h=>{switch(h){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 u();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 a("short",!0);case"LLLL":return a("long",!0);case"LLLLL":return a("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 a("short",!1);case"MMMM":return a("long",!1);case"MMMMM":return a("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(h)}};return zQ(is.parseFormat(n),x)}formatDurationFromString(e,n){const r=a=>{switch(a[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=a=>l=>{const c=r(l);return c?this.num(a.get(c),l.length):l},s=is.parseFormat(n),o=s.reduce((a,{literal:l,val:c})=>l?a:a.concat(c),[]),u=e.shiftTo(...o.map(r).filter(a=>a));return zQ(s,i(u))}}class Qo{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}let Ap=class{get type(){throw new q0}get name(){throw new q0}get ianaName(){return this.name}get isUniversal(){throw new q0}offsetName(e,n){throw new q0}formatOffset(e,n){throw new q0}offset(e){throw new q0}equals(e){throw new q0}get isValid(){throw new q0}},aL=null;class UC extends Ap{static get instance(){return aL===null&&(aL=new UC),aL}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return IQ(e,n,r)}formatOffset(e,n){return q1(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}let qC={};function Sbe(t){return qC[t]||(qC[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"})),qC[t]}const vbe={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function _be(t,e){const n=t.format(e).replace(/\u200E/g,""),r=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,i,s,o,u,a,l,c]=r;return[o,i,s,u,a,l,c]}function Cbe(t,e){const n=t.formatToParts(e),r=[];for(let i=0;i<n.length;i++){const{type:s,value:o}=n[i],u=vbe[s];s==="era"?r[u]=o:St(u)||(r[u]=parseInt(o,10))}return r}let HC={};class Ku extends Ap{static create(e){return HC[e]||(HC[e]=new Ku(e)),HC[e]}static resetCache(){HC={},qC={}}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=Ku.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return IQ(e,n,r,this.name)}formatOffset(e,n){return q1(this.offset(e),n)}offset(e){const n=new Date(e);if(isNaN(n))return NaN;const r=Sbe(this.name);let[i,s,o,u,a,l,c]=r.formatToParts?Cbe(r,n):_be(r,n);u==="BC"&&(i=-Math.abs(i)+1);const x=oL({year:i,month:s,day:o,hour:a===24?0:a,minute:l,second:c,millisecond:0});let h=+n;const p=h%1e3;return h-=p>=0?p:1e3+p,(x-h)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let lL=null;class Zr extends Ap{static get utcInstance(){return lL===null&&(lL=new Zr(0)),lL}static instance(e){return e===0?Zr.utcInstance:new Zr(e)}static parseSpecifier(e){if(e){const n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new Zr(PC(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${q1(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${q1(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return q1(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class QQ extends Ap{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 z0(t,e){if(St(t)||t===null)return e;if(t instanceof Ap)return t;if(ibe(t)){const n=t.toLowerCase();return n==="local"||n==="system"?e:n==="utc"||n==="gmt"?Zr.utcInstance:Zr.parseSpecifier(n)||Ku.create(t)}else return px(t)?Zr.instance(t):typeof t=="object"&&t.offset&&typeof t.offset=="number"?t:new QQ(t)}let GQ=()=>Date.now(),WQ="system",VQ=null,YQ=null,KQ=null,XQ;class zn{static get now(){return GQ}static set now(e){GQ=e}static set defaultZone(e){WQ=e}static get defaultZone(){return z0(WQ,UC.instance)}static get defaultLocale(){return VQ}static set defaultLocale(e){VQ=e}static get defaultNumberingSystem(){return YQ}static set defaultNumberingSystem(e){YQ=e}static get defaultOutputCalendar(){return KQ}static set defaultOutputCalendar(e){KQ=e}static get throwOnInvalid(){return XQ}static set throwOnInvalid(e){XQ=e}static resetCaches(){dn.resetCache(),Ku.resetCache()}}let JQ={};function bbe(t,e={}){const n=JSON.stringify([t,e]);let r=JQ[n];return r||(r=new Intl.ListFormat(t,e),JQ[n]=r),r}let cL={};function fL(t,e={}){const n=JSON.stringify([t,e]);let r=cL[n];return r||(r=new Intl.DateTimeFormat(t,e),cL[n]=r),r}let xL={};function Tbe(t,e={}){const n=JSON.stringify([t,e]);let r=xL[n];return r||(r=new Intl.NumberFormat(t,e),xL[n]=r),r}let dL={};function Rbe(t,e={}){const{base:n,...r}=e,i=JSON.stringify([t,r]);let s=dL[i];return s||(s=new Intl.RelativeTimeFormat(t,e),dL[i]=s),s}let H1=null;function Obe(){return H1||(H1=new Intl.DateTimeFormat().resolvedOptions().locale,H1)}function Nbe(t){const e=t.indexOf("-u-");if(e===-1)return[t];{let n;const r=t.substring(0,e);try{n=fL(t).resolvedOptions()}catch{n=fL(r).resolvedOptions()}const{numberingSystem:i,calendar:s}=n;return[r,i,s]}}function Dbe(t,e,n){return(n||e)&&(t+="-u",n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function Fbe(t){const e=[];for(let n=1;n<=12;n++){const r=st.utc(2016,n,1);e.push(t(r))}return e}function wbe(t){const e=[];for(let n=1;n<=7;n++){const r=st.utc(2016,11,13+n);e.push(t(r))}return e}function zC(t,e,n,r,i){const s=t.listingMode(n);return s==="error"?null:s==="en"?r(e):i(e)}function Lbe(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"}class Ibe{constructor(e,n,r){this.padTo=r.padTo||0,this.floor=r.floor||!1;const{padTo:i,floor:s,...o}=r;if(!n||Object.keys(o).length>0){const u={useGrouping:!1,...r};r.padTo>0&&(u.minimumIntegerDigits=r.padTo),this.inf=Tbe(e,u)}}format(e){if(this.inf){const n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{const n=this.floor?Math.floor(e):sL(e,3);return Hn(n,this.padTo)}}}class $be{constructor(e,n,r){this.opts=r;let i;if(e.zone.isUniversal){const o=-1*(e.offset/60),u=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&Ku.create(u).valid?(i=u,this.dt=e):(i="UTC",r.timeZoneName?this.dt=e:this.dt=e.offset===0?e:st.fromMillis(e.ts+e.offset*60*1e3))}else e.zone.type==="system"?this.dt=e:(this.dt=e,i=e.zone.name);const s={...this.opts};i&&(s.timeZone=i),this.dtf=fL(n,s)}format(){return this.dtf.format(this.dt.toJSDate())}formatToParts(){return this.dtf.formatToParts(this.dt.toJSDate())}resolvedOptions(){return this.dtf.resolvedOptions()}}class Bbe{constructor(e,n,r){this.opts={style:"long",...r},!n&&wQ()&&(this.rtf=Rbe(e,r))}format(e,n){return this.rtf?this.rtf.format(e,n):Ebe(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}}class dn{static fromOpts(e){return dn.create(e.locale,e.numberingSystem,e.outputCalendar,e.defaultToEN)}static create(e,n,r,i=!1){const s=e||zn.defaultLocale,o=s||(i?"en-US":Obe()),u=n||zn.defaultNumberingSystem,a=r||zn.defaultOutputCalendar;return new dn(o,u,a,s)}static resetCache(){H1=null,cL={},xL={},dL={}}static fromObject({locale:e,numberingSystem:n,outputCalendar:r}={}){return dn.create(e,n,r)}constructor(e,n,r,i){const[s,o,u]=Nbe(e);this.locale=s,this.numberingSystem=n||o||null,this.outputCalendar=r||u||null,this.intl=Dbe(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=Lbe(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:dn.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,n=!1,r=!0){return zC(this,e,r,PQ,()=>{const i=n?{month:e,day:"numeric"}:{month:e},s=n?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=Fbe(o=>this.extract(o,i,"month"))),this.monthsCache[s][e]})}weekdays(e,n=!1,r=!0){return zC(this,e,r,UQ,()=>{const i=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=n?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=wbe(o=>this.extract(o,i,"weekday"))),this.weekdaysCache[s][e]})}meridiems(e=!0){return zC(this,void 0,e,()=>qQ,()=>{if(!this.meridiemCache){const n={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[st.utc(2016,11,13,9),st.utc(2016,11,13,19)].map(r=>this.extract(r,n,"dayperiod"))}return this.meridiemCache})}eras(e,n=!0){return zC(this,e,n,HQ,()=>{const r={era:e};return this.eraCache[e]||(this.eraCache[e]=[st.utc(-40,1,1),st.utc(2017,1,1)].map(i=>this.extract(i,r,"era"))),this.eraCache[e]})}extract(e,n,r){const i=this.dtFormatter(e,n),s=i.formatToParts(),o=s.find(u=>u.type.toLowerCase()===r);return o?o.value:null}numberFormatter(e={}){return new Ibe(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new $be(e,this.intl,n)}relFormatter(e={}){return new Bbe(this.intl,this.isEnglish(),e)}listFormatter(e={}){return bbe(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 Sp(...t){const e=t.reduce((n,r)=>n+r.source,"");return RegExp(`^${e}$`)}function vp(...t){return e=>t.reduce(([n,r,i],s)=>{const[o,u,a]=s(e,i);return[{...n,...o},u||r,a]},[{},null,1]).slice(0,2)}function _p(t,...e){if(t==null)return[null,null];for(const[n,r]of e){const i=n.exec(t);if(i)return r(i)}return[null,null]}function ZQ(...t){return(e,n)=>{const r={};let i;for(i=0;i<t.length;i++)r[t[i]]=H0(e[n+i]);return[r,null,n+i]}}const eG=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,kbe=`(?:${eG.source}?(?:\\[(${BQ.source})\\])?)?`,hL=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,tG=RegExp(`${hL.source}${kbe}`),pL=RegExp(`(?:T${tG.source})?`),Pbe=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Mbe=/(\d{4})-?W(\d\d)(?:-?(\d))?/,jbe=/(\d{4})-?(\d{3})/,Ube=ZQ("weekYear","weekNumber","weekDay"),qbe=ZQ("year","ordinal"),Hbe=/(\d{4})-(\d\d)-(\d\d)/,nG=RegExp(`${hL.source} ?(?:${eG.source}|(${BQ.source}))?`),zbe=RegExp(`(?: ${nG.source})?`);function Cp(t,e,n){const r=t[e];return St(r)?n:H0(r)}function Qbe(t,e){return[{year:Cp(t,e),month:Cp(t,e+1,1),day:Cp(t,e+2,1)},null,e+3]}function bp(t,e){return[{hours:Cp(t,e,0),minutes:Cp(t,e+1,0),seconds:Cp(t,e+2,0),milliseconds:iL(t[e+3])},null,e+4]}function z1(t,e){const n=!t[e]&&!t[e+1],r=PC(t[e+1],t[e+2]),i=n?null:Zr.instance(r);return[{},i,e+3]}function Q1(t,e){const n=t[e]?Ku.create(t[e]):null;return[{},n,e+1]}const Gbe=RegExp(`^T?${hL.source}$`),Wbe=/^-?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 Vbe(t){const[e,n,r,i,s,o,u,a,l]=t,c=e[0]==="-",f=a&&a[0]==="-",x=(h,p=!1)=>h!==void 0&&(p||h&&c)?-h:h;return[{years:x(gx(n)),months:x(gx(r)),weeks:x(gx(i)),days:x(gx(s)),hours:x(gx(o)),minutes:x(gx(u)),seconds:x(gx(a),a==="-0"),milliseconds:x(iL(l),f)}]}const Ybe={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 gL(t,e,n,r,i,s,o){const u={year:e.length===2?uL(H0(e)):H0(e),month:kQ.indexOf(n)+1,day:H0(r),hour:H0(i),minute:H0(s)};return o&&(u.second=H0(o)),t&&(u.weekday=t.length>3?MQ.indexOf(t)+1:jQ.indexOf(t)+1),u}const Kbe=/^(?:(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 Xbe(t){const[,e,n,r,i,s,o,u,a,l,c,f]=t,x=gL(e,i,r,n,s,o,u);let h;return a?h=Ybe[a]:l?h=0:h=PC(c,f),[x,new Zr(h)]}function Jbe(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Zbe=/^(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$/,eTe=/^(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$/,tTe=/^(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 rG(t){const[,e,n,r,i,s,o,u]=t;return[gL(e,i,r,n,s,o,u),Zr.utcInstance]}function nTe(t){const[,e,n,r,i,s,o,u]=t;return[gL(e,u,n,r,i,s,o),Zr.utcInstance]}const rTe=Sp(Pbe,pL),iTe=Sp(Mbe,pL),sTe=Sp(jbe,pL),oTe=Sp(tG),iG=vp(Qbe,bp,z1,Q1),uTe=vp(Ube,bp,z1,Q1),aTe=vp(qbe,bp,z1,Q1),lTe=vp(bp,z1,Q1);function cTe(t){return _p(t,[rTe,iG],[iTe,uTe],[sTe,aTe],[oTe,lTe])}function fTe(t){return _p(Jbe(t),[Kbe,Xbe])}function xTe(t){return _p(t,[Zbe,rG],[eTe,rG],[tTe,nTe])}function dTe(t){return _p(t,[Wbe,Vbe])}const hTe=vp(bp);function pTe(t){return _p(t,[Gbe,hTe])}const gTe=Sp(Hbe,zbe),mTe=Sp(nG),yTe=vp(bp,z1,Q1);function ETe(t){return _p(t,[gTe,iG],[mTe,yTe])}const ATe="Invalid Duration",sG={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}},STe={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},...sG},uo=146097/400,Tp=146097/4800,vTe={years:{quarters:4,months:12,weeks:uo/7,days:uo,hours:uo*24,minutes:uo*24*60,seconds:uo*24*60*60,milliseconds:uo*24*60*60*1e3},quarters:{months:3,weeks:uo/28,days:uo/4,hours:uo*24/4,minutes:uo*24*60/4,seconds:uo*24*60*60/4,milliseconds:uo*24*60*60*1e3/4},months:{weeks:Tp/7,days:Tp,hours:Tp*24,minutes:Tp*24*60,seconds:Tp*24*60*60,milliseconds:Tp*24*60*60*1e3},...sG},mx=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],_Te=mx.slice(0).reverse();function yx(t,e,n=!1){const r={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy};return new vt(r)}function CTe(t){return t<0?Math.floor(t):Math.ceil(t)}function oG(t,e,n,r,i){const s=t[i][n],o=e[n]/s,u=Math.sign(o)===Math.sign(r[i]),a=!u&&r[i]!==0&&Math.abs(o)<=1?CTe(o):Math.trunc(o);r[i]+=a,e[n]-=a*s}function bTe(t,e){_Te.reduce((n,r)=>St(e[r])?n:(n&&oG(t,e,n,e,r),r),null)}class vt{constructor(e){const n=e.conversionAccuracy==="longterm"||!1;this.values=e.values,this.loc=e.loc||dn.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n?vTe:STe,this.isLuxonDuration=!0}static fromMillis(e,n){return vt.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new oo(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new vt({values:MC(e,vt.normalizeUnit),loc:dn.fromObject(n),conversionAccuracy:n.conversionAccuracy})}static fromDurationLike(e){if(px(e))return vt.fromMillis(e);if(vt.isDuration(e))return e;if(typeof e=="object")return vt.fromObject(e);throw new oo(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){const[r]=dTe(e);return r?vt.fromObject(r,n):vt.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){const[r]=pTe(e);return r?vt.fromObject(r,n):vt.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new oo("need to specify a reason the Duration is invalid");const r=e instanceof Qo?e:new Qo(e,n);if(zn.throwOnInvalid)throw new tbe(r);return new vt({invalid:r})}static normalizeUnit(e){const n={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(!n)throw new xQ(e);return n}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,n={}){const r={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?is.create(this.loc,r).formatDurationFromString(this,e):ATe}toHuman(e={}){const n=mx.map(r=>{const i=this.values[r];return St(i)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(n)}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+=sL(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const n=this.toMillis();if(n<0||n>=864e5)return null;e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e};const r=this.shiftTo("hours","minutes","seconds","milliseconds");let i=e.format==="basic"?"hhmm":"hh:mm";(!e.suppressSeconds||r.seconds!==0||r.milliseconds!==0)&&(i+=e.format==="basic"?"ss":":ss",(!e.suppressMilliseconds||r.milliseconds!==0)&&(i+=".SSS"));let s=r.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;const n=vt.fromDurationLike(e),r={};for(const i of mx)(Ep(n.values,i)||Ep(this.values,i))&&(r[i]=n.get(i)+this.get(i));return yx(this,{values:r},!0)}minus(e){if(!this.isValid)return this;const n=vt.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;const n={};for(const r of Object.keys(this.values))n[r]=$Q(e(this.values[r],r));return yx(this,{values:n},!0)}get(e){return this[vt.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const n={...this.values,...MC(e,vt.normalizeUnit)};return yx(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:r}={}){const i=this.loc.clone({locale:e,numberingSystem:n}),s={loc:i};return r&&(s.conversionAccuracy=r),yx(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return bTe(this.matrix,e),yx(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>vt.normalizeUnit(o));const n={},r={},i=this.toObject();let s;for(const o of mx)if(e.indexOf(o)>=0){s=o;let u=0;for(const l in r)u+=this.matrix[l][o]*r[l],r[l]=0;px(i[o])&&(u+=i[o]);const a=Math.trunc(u);n[o]=a,r[o]=(u*1e3-a*1e3)/1e3;for(const l in i)mx.indexOf(l)>mx.indexOf(o)&&oG(this.matrix,i,l,n,o)}else px(i[o])&&(r[o]=i[o]);for(const o in r)r[o]!==0&&(n[s]+=o===s?r[o]:r[o]/this.matrix[s][o]);return yx(this,{values:n},!0).normalize()}negate(){if(!this.isValid)return this;const e={};for(const n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return yx(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 n(r,i){return r===void 0||r===0?i===void 0||i===0:r===i}for(const r of mx)if(!n(this.values[r],e.values[r]))return!1;return!0}}const G1="Invalid Interval";function TTe(t,e){return!t||!t.isValid?hn.invalid("missing or invalid start"):!e||!e.isValid?hn.invalid("missing or invalid end"):e<t?hn.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}class hn{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new oo("need to specify a reason the Interval is invalid");const r=e instanceof Qo?e:new Qo(e,n);if(zn.throwOnInvalid)throw new ebe(r);return new hn({invalid:r})}static fromDateTimes(e,n){const r=K1(e),i=K1(n),s=TTe(r,i);return s??new hn({start:r,end:i})}static after(e,n){const r=vt.fromDurationLike(n),i=K1(e);return hn.fromDateTimes(i,i.plus(r))}static before(e,n){const r=vt.fromDurationLike(n),i=K1(e);return hn.fromDateTimes(i.minus(r),i)}static fromISO(e,n){const[r,i]=(e||"").split("/",2);if(r&&i){let s,o;try{s=st.fromISO(r,n),o=s.isValid}catch{o=!1}let u,a;try{u=st.fromISO(i,n),a=u.isValid}catch{a=!1}if(o&&a)return hn.fromDateTimes(s,u);if(o){const l=vt.fromISO(i,n);if(l.isValid)return hn.after(s,l)}else if(a){const l=vt.fromISO(r,n);if(l.isValid)return hn.before(u,l)}}return hn.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;const n=this.start.startOf(e),r=this.end.startOf(e);return Math.floor(r.diff(n,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:n}={}){return this.isValid?hn.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];const n=e.map(K1).filter(o=>this.contains(o)).sort(),r=[];let{s:i}=this,s=0;for(;i<this.e;){const o=n[s]||this.e,u=+o>+this.e?this.e:o;r.push(hn.fromDateTimes(i,u)),i=u,s+=1}return r}splitBy(e){const n=vt.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s:r}=this,i=1,s;const o=[];for(;r<this.e;){const u=this.start.plus(n.mapUnits(a=>a*i));s=+u>+this.e?this.e:u,o.push(hn.fromDateTimes(r,s)),r=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;const n=this.s>e.s?this.s:e.s,r=this.e<e.e?this.e:e.e;return n>=r?null:hn.fromDateTimes(n,r)}union(e){if(!this.isValid)return this;const n=this.s<e.s?this.s:e.s,r=this.e>e.e?this.e:e.e;return hn.fromDateTimes(n,r)}static merge(e){const[n,r]=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 r&&n.push(r),n}static xor(e){let n=null,r=0;const i=[],s=e.map(a=>[{time:a.s,type:"s"},{time:a.e,type:"e"}]),o=Array.prototype.concat(...s),u=o.sort((a,l)=>a.time-l.time);for(const a of u)r+=a.type==="s"?1:-1,r===1?n=a.time:(n&&+n!=+a.time&&i.push(hn.fromDateTimes(n,a.time)),n=null);return hn.merge(i)}difference(...e){return hn.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:G1}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:G1}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:G1}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:G1}toFormat(e,{separator:n=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:G1}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):vt.invalid(this.invalidReason)}mapEndpoints(e){return hn.fromDateTimes(e(this.s),e(this.e))}}let W1=class{static hasDST(e=zn.defaultZone){const n=st.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return Ku.isValidZone(e)}static normalizeZone(e){return z0(e,zn.defaultZone)}static months(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||dn.create(n,r,s)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null,outputCalendar:s="gregory"}={}){return(i||dn.create(n,r,s)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||dn.create(n,r,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:i=null}={}){return(i||dn.create(n,r,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return dn.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return dn.create(n,null,"gregory").eras(e)}static features(){return{relative:wQ()}}};function uG(t,e){const n=i=>i.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),r=n(e)-n(t);return Math.floor(vt.fromMillis(r).as("days"))}function RTe(t,e,n){const r=[["years",(u,a)=>a.year-u.year],["quarters",(u,a)=>a.quarter-u.quarter],["months",(u,a)=>a.month-u.month+(a.year-u.year)*12],["weeks",(u,a)=>{const l=uG(u,a);return(l-l%7)/7}],["days",uG]],i={};let s,o;for(const[u,a]of r)if(n.indexOf(u)>=0){s=u;let l=a(t,e);o=t.plus({[u]:l}),o>e?(t=t.plus({[u]:l-1}),l-=1):t=o,i[u]=l}return[t,i,o,s]}function OTe(t,e,n,r){let[i,s,o,u]=RTe(t,e,n);const a=e-i,l=n.filter(f=>["hours","minutes","seconds","milliseconds"].indexOf(f)>=0);l.length===0&&(o<e&&(o=i.plus({[u]:1})),o!==i&&(s[u]=(s[u]||0)+a/(o-i)));const c=vt.fromObject(s,r);return l.length>0?vt.fromMillis(a,r).shiftTo(...l).plus(c):c}const mL={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},aG={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]},NTe=mL.hanidec.replace(/[\[|\]]/g,"").split("");function DTe(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);if(t[n].search(mL.hanidec)!==-1)e+=NTe.indexOf(t[n]);else for(const i in aG){const[s,o]=aG[i];r>=s&&r<=o&&(e+=r-s)}}return parseInt(e,10)}else return e}function Go({numberingSystem:t},e=""){return new RegExp(`${mL[t||"latn"]}${e}`)}const FTe="missing Intl.DateTimeFormat.formatToParts support";function Lt(t,e=n=>n){return{regex:t,deser:([n])=>e(DTe(n))}}const lG="[ ]",cG=new RegExp(lG,"g");function wTe(t){return t.replace(/\./g,"\\.?").replace(cG,lG)}function fG(t){return t.replace(/\./g,"").replace(cG," ").toLowerCase()}function Wo(t,e){return t===null?null:{regex:RegExp(t.map(wTe).join("|")),deser:([n])=>t.findIndex(r=>fG(n)===fG(r))+e}}function xG(t,e){return{regex:t,deser:([,n,r])=>PC(n,r),groups:e}}function yL(t){return{regex:t,deser:([e])=>e}}function LTe(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function ITe(t,e){const n=Go(e),r=Go(e,"{2}"),i=Go(e,"{3}"),s=Go(e,"{4}"),o=Go(e,"{6}"),u=Go(e,"{1,2}"),a=Go(e,"{1,3}"),l=Go(e,"{1,6}"),c=Go(e,"{1,9}"),f=Go(e,"{2,4}"),x=Go(e,"{4,6}"),h=g=>({regex:RegExp(LTe(g.val)),deser:([y])=>y,literal:!0}),m=(g=>{if(t.literal)return h(g);switch(g.val){case"G":return Wo(e.eras("short",!1),0);case"GG":return Wo(e.eras("long",!1),0);case"y":return Lt(l);case"yy":return Lt(f,uL);case"yyyy":return Lt(s);case"yyyyy":return Lt(x);case"yyyyyy":return Lt(o);case"M":return Lt(u);case"MM":return Lt(r);case"MMM":return Wo(e.months("short",!0,!1),1);case"MMMM":return Wo(e.months("long",!0,!1),1);case"L":return Lt(u);case"LL":return Lt(r);case"LLL":return Wo(e.months("short",!1,!1),1);case"LLLL":return Wo(e.months("long",!1,!1),1);case"d":return Lt(u);case"dd":return Lt(r);case"o":return Lt(a);case"ooo":return Lt(i);case"HH":return Lt(r);case"H":return Lt(u);case"hh":return Lt(r);case"h":return Lt(u);case"mm":return Lt(r);case"m":return Lt(u);case"q":return Lt(u);case"qq":return Lt(r);case"s":return Lt(u);case"ss":return Lt(r);case"S":return Lt(a);case"SSS":return Lt(i);case"u":return yL(c);case"uu":return yL(u);case"uuu":return Lt(n);case"a":return Wo(e.meridiems(),0);case"kkkk":return Lt(s);case"kk":return Lt(f,uL);case"W":return Lt(u);case"WW":return Lt(r);case"E":case"c":return Lt(n);case"EEE":return Wo(e.weekdays("short",!1,!1),1);case"EEEE":return Wo(e.weekdays("long",!1,!1),1);case"ccc":return Wo(e.weekdays("short",!0,!1),1);case"cccc":return Wo(e.weekdays("long",!0,!1),1);case"Z":case"ZZ":return xG(new RegExp(`([+-]${u.source})(?::(${r.source}))?`),2);case"ZZZ":return xG(new RegExp(`([+-]${u.source})(${r.source})?`),2);case"z":return yL(/[a-z_+-/]{1,256}?/i);default:return h(g)}})(t)||{invalidReason:FTe};return m.token=t,m}const $Te={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 BTe(t,e,n){const{type:r,value:i}=t;if(r==="literal")return{literal:!0,val:i};const s=n[r];let o=$Te[r];if(typeof o=="object"&&(o=o[s]),o)return{literal:!1,val:o}}function kTe(t){return[`^${t.map(n=>n.regex).reduce((n,r)=>`${n}(${r.source})`,"")}$`,t]}function PTe(t,e,n){const r=t.match(e);if(r){const i={};let s=1;for(const o in n)if(Ep(n,o)){const u=n[o],a=u.groups?u.groups+1:1;!u.literal&&u.token&&(i[u.token.val[0]]=u.deser(r.slice(s,s+a))),s+=a}return[r,i]}else return[r,{}]}function MTe(t){const 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}};let n=null,r;return St(t.z)||(n=Ku.create(t.z)),St(t.Z)||(n||(n=new Zr(t.Z)),r=t.Z),St(t.q)||(t.M=(t.q-1)*3+1),St(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),St(t.u)||(t.S=iL(t.u)),[Object.keys(t).reduce((s,o)=>{const u=e(o);return u&&(s[u]=t[o]),s},{}),n,r]}let EL=null;function jTe(){return EL||(EL=st.fromMillis(1555555555555)),EL}function UTe(t,e){if(t.literal)return t;const n=is.macroTokenToFormatOpts(t.val);if(!n)return t;const s=is.create(e,n).formatDateTimeParts(jTe()).map(o=>BTe(o,e,n));return s.includes(void 0)?t:s}function qTe(t,e){return Array.prototype.concat(...t.map(n=>UTe(n,e)))}function dG(t,e,n){const r=qTe(is.parseFormat(n),t),i=r.map(o=>ITe(o,t)),s=i.find(o=>o.invalidReason);if(s)return{input:e,tokens:r,invalidReason:s.invalidReason};{const[o,u]=kTe(i),a=RegExp(o,"i"),[l,c]=PTe(e,a,u),[f,x,h]=c?MTe(c):[null,null,void 0];if(Ep(c,"a")&&Ep(c,"H"))throw new M1("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:r,regex:a,rawMatches:l,matches:c,result:f,zone:x,specificOffset:h}}}function HTe(t,e,n){const{result:r,zone:i,specificOffset:s,invalidReason:o}=dG(t,e,n);return[r,i,s,o]}const hG=[0,31,59,90,120,151,181,212,243,273,304,334],pG=[0,31,60,91,121,152,182,213,244,274,305,335];function ao(t,e){return new Qo("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function gG(t,e,n){const r=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);const i=r.getUTCDay();return i===0?7:i}function mG(t,e,n){return n+(j1(t)?pG:hG)[e-1]}function yG(t,e){const n=j1(t)?pG:hG,r=n.findIndex(s=>s<e),i=e-n[r];return{month:r+1,day:i}}function AL(t){const{year:e,month:n,day:r}=t,i=mG(e,n,r),s=gG(e,n,r);let o=Math.floor((i-s+10)/7),u;return o<1?(u=e-1,o=kC(u)):o>kC(e)?(u=e+1,o=1):u=e,{weekYear:u,weekNumber:o,weekday:s,...jC(t)}}function EG(t){const{weekYear:e,weekNumber:n,weekday:r}=t,i=gG(e,1,4),s=U1(e);let o=n*7+r-i-3,u;o<1?(u=e-1,o+=U1(u)):o>s?(u=e+1,o-=U1(e)):u=e;const{month:a,day:l}=yG(u,o);return{year:u,month:a,day:l,...jC(t)}}function SL(t){const{year:e,month:n,day:r}=t,i=mG(e,n,r);return{year:e,ordinal:i,...jC(t)}}function AG(t){const{year:e,ordinal:n}=t,{month:r,day:i}=yG(e,n);return{year:e,month:r,day:i,...jC(t)}}function zTe(t){const e=$C(t.weekYear),n=gl(t.weekNumber,1,kC(t.weekYear)),r=gl(t.weekday,1,7);return e?n?r?!1:ao("weekday",t.weekday):ao("week",t.week):ao("weekYear",t.weekYear)}function QTe(t){const e=$C(t.year),n=gl(t.ordinal,1,U1(t.year));return e?n?!1:ao("ordinal",t.ordinal):ao("year",t.year)}function SG(t){const e=$C(t.year),n=gl(t.month,1,12),r=gl(t.day,1,BC(t.year,t.month));return e?n?r?!1:ao("day",t.day):ao("month",t.month):ao("year",t.year)}function vG(t){const{hour:e,minute:n,second:r,millisecond:i}=t,s=gl(e,0,23)||e===24&&n===0&&r===0&&i===0,o=gl(n,0,59),u=gl(r,0,59),a=gl(i,0,999);return s?o?u?a?!1:ao("millisecond",i):ao("second",r):ao("minute",n):ao("hour",e)}const vL="Invalid DateTime",_G=864e13;function QC(t){return new Qo("unsupported zone",`the zone "${t.name}" is not supported`)}function _L(t){return t.weekData===null&&(t.weekData=AL(t.c)),t.weekData}function V1(t,e){const n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new st({...n,...e,old:n})}function CG(t,e,n){let r=t-e*60*1e3;const i=n.offset(r);if(e===i)return[r,e];r-=(i-e)*60*1e3;const s=n.offset(r);return i===s?[r,i]:[t-Math.min(i,s)*60*1e3,Math.max(i,s)]}function bG(t,e){t+=e*60*1e3;const n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function GC(t,e,n){return CG(oL(t),e,n)}function TG(t,e){const n=t.o,r=t.c.year+Math.trunc(e.years),i=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,s={...t.c,year:r,month:i,day:Math.min(t.c.day,BC(r,i))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=vt.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"),u=oL(s);let[a,l]=CG(u,n,t.zone);return o!==0&&(a+=o,l=t.zone.offset(a)),{ts:a,o:l}}function Y1(t,e,n,r,i,s){const{setZone:o,zone:u}=n;if(t&&Object.keys(t).length!==0){const a=e||u,l=st.fromObject(t,{...n,zone:a,specificOffset:s});return o?l:l.setZone(u)}else return st.invalid(new Qo("unparsable",`the input "${i}" can't be parsed as ${r}`))}function WC(t,e,n=!0){return t.isValid?is.create(dn.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function CL(t,e){const n=t.c.year>9999||t.c.year<0;let r="";return n&&t.c.year>=0&&(r+="+"),r+=Hn(t.c.year,n?6:4),e?(r+="-",r+=Hn(t.c.month),r+="-",r+=Hn(t.c.day)):(r+=Hn(t.c.month),r+=Hn(t.c.day)),r}function RG(t,e,n,r,i,s){let o=Hn(t.c.hour);return e?(o+=":",o+=Hn(t.c.minute),(t.c.second!==0||!n)&&(o+=":")):o+=Hn(t.c.minute),(t.c.second!==0||!n)&&(o+=Hn(t.c.second),(t.c.millisecond!==0||!r)&&(o+=".",o+=Hn(t.c.millisecond,3))),i&&(t.isOffsetFixed&&t.offset===0&&!s?o+="Z":t.o<0?(o+="-",o+=Hn(Math.trunc(-t.o/60)),o+=":",o+=Hn(Math.trunc(-t.o%60))):(o+="+",o+=Hn(Math.trunc(t.o/60)),o+=":",o+=Hn(Math.trunc(t.o%60)))),s&&(o+="["+t.zone.ianaName+"]"),o}const OG={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},GTe={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},WTe={ordinal:1,hour:0,minute:0,second:0,millisecond:0},NG=["year","month","day","hour","minute","second","millisecond"],VTe=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],YTe=["year","ordinal","hour","minute","second","millisecond"];function DG(t){const 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 xQ(t);return e}function FG(t,e){const n=z0(e.zone,zn.defaultZone),r=dn.fromObject(e),i=zn.now();let s,o;if(St(t.year))s=i;else{for(const l of NG)St(t[l])&&(t[l]=OG[l]);const u=SG(t)||vG(t);if(u)return st.invalid(u);const a=n.offset(i);[s,o]=GC(t,a,n)}return new st({ts:s,zone:n,loc:r,o})}function wG(t,e,n){const r=St(n.round)?!0:n.round,i=(o,u)=>(o=sL(o,r||n.calendary?0:2,!0),e.loc.clone(n).relFormatter(n).format(o,u)),s=o=>n.calendary?e.hasSame(t,o)?0:e.startOf(o).diff(t.startOf(o),o).get(o):e.diff(t,o).get(o);if(n.unit)return i(s(n.unit),n.unit);for(const o of n.units){const u=s(o);if(Math.abs(u)>=1)return i(u,o)}return i(t>e?-0:0,n.units[n.units.length-1])}function LG(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}class st{constructor(e){const n=e.zone||zn.defaultZone;let r=e.invalid||(Number.isNaN(e.ts)?new Qo("invalid input"):null)||(n.isValid?null:QC(n));this.ts=St(e.ts)?zn.now():e.ts;let i=null,s=null;if(!r)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[i,s]=[e.old.c,e.old.o];else{const u=n.offset(this.ts);i=bG(this.ts,u),r=Number.isNaN(i.year)?new Qo("invalid input"):null,i=r?null:i,s=r?null:u}this._zone=n,this.loc=e.loc||dn.create(),this.invalid=r,this.weekData=null,this.c=i,this.o=s,this.isLuxonDateTime=!0}static now(){return new st({})}static local(){const[e,n]=LG(arguments),[r,i,s,o,u,a,l]=n;return FG({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static utc(){const[e,n]=LG(arguments),[r,i,s,o,u,a,l]=n;return e.zone=Zr.utcInstance,FG({year:r,month:i,day:s,hour:o,minute:u,second:a,millisecond:l},e)}static fromJSDate(e,n={}){const r=sbe(e)?e.valueOf():NaN;if(Number.isNaN(r))return st.invalid("invalid input");const i=z0(n.zone,zn.defaultZone);return i.isValid?new st({ts:r,zone:i,loc:dn.fromObject(n)}):st.invalid(QC(i))}static fromMillis(e,n={}){if(px(e))return e<-_G||e>_G?st.invalid("Timestamp out of range"):new st({ts:e,zone:z0(n.zone,zn.defaultZone),loc:dn.fromObject(n)});throw new oo(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(px(e))return new st({ts:e*1e3,zone:z0(n.zone,zn.defaultZone),loc:dn.fromObject(n)});throw new oo("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};const r=z0(n.zone,zn.defaultZone);if(!r.isValid)return st.invalid(QC(r));const i=zn.now(),s=St(n.specificOffset)?r.offset(i):n.specificOffset,o=MC(e,DG),u=!St(o.ordinal),a=!St(o.year),l=!St(o.month)||!St(o.day),c=a||l,f=o.weekYear||o.weekNumber,x=dn.fromObject(n);if((c||u)&&f)throw new M1("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&u)throw new M1("Can't mix ordinal dates with month/day");const h=f||o.weekday&&!c;let p,m,g=bG(i,s);h?(p=VTe,m=GTe,g=AL(g)):u?(p=YTe,m=WTe,g=SL(g)):(p=NG,m=OG);let y=!1;for(const b of p){const O=o[b];St(O)?y?o[b]=m[b]:o[b]=g[b]:y=!0}const E=h?zTe(o):u?QTe(o):SG(o),A=E||vG(o);if(A)return st.invalid(A);const S=h?EG(o):u?AG(o):o,[v,_]=GC(S,s,r),C=new st({ts:v,zone:r,o:_,loc:x});return o.weekday&&c&&e.weekday!==C.weekday?st.invalid("mismatched weekday",`you can't specify both a weekday of ${o.weekday} and a date of ${C.toISO()}`):C}static fromISO(e,n={}){const[r,i]=cTe(e);return Y1(r,i,n,"ISO 8601",e)}static fromRFC2822(e,n={}){const[r,i]=fTe(e);return Y1(r,i,n,"RFC 2822",e)}static fromHTTP(e,n={}){const[r,i]=xTe(e);return Y1(r,i,n,"HTTP",n)}static fromFormat(e,n,r={}){if(St(e)||St(n))throw new oo("fromFormat requires an input string and a format");const{locale:i=null,numberingSystem:s=null}=r,o=dn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0}),[u,a,l,c]=HTe(o,e,n);return c?st.invalid(c):Y1(u,a,r,`format ${n}`,e,l)}static fromString(e,n,r={}){return st.fromFormat(e,n,r)}static fromSQL(e,n={}){const[r,i]=ETe(e);return Y1(r,i,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new oo("need to specify a reason the DateTime is invalid");const r=e instanceof Qo?e:new Qo(e,n);if(zn.throwOnInvalid)throw new ZCe(r);return new st({invalid:r})}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?_L(this).weekYear:NaN}get weekNumber(){return this.isValid?_L(this).weekNumber:NaN}get weekday(){return this.isValid?_L(this).weekday:NaN}get ordinal(){return this.isValid?SL(this.c).ordinal:NaN}get monthShort(){return this.isValid?W1.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?W1.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?W1.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?W1.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 j1(this.year)}get daysInMonth(){return BC(this.year,this.month)}get daysInYear(){return this.isValid?U1(this.year):NaN}get weeksInWeekYear(){return this.isValid?kC(this.weekYear):NaN}resolvedLocaleOptions(e={}){const{locale:n,numberingSystem:r,calendar:i}=is.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:r,outputCalendar:i}}toUTC(e=0,n={}){return this.setZone(Zr.instance(e),n)}toLocal(){return this.setZone(zn.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(e=z0(e,zn.defaultZone),e.equals(this.zone))return this;if(e.isValid){let i=this.ts;if(n||r){const s=e.offset(this.ts),o=this.toObject();[i]=GC(o,s,e)}return V1(this,{ts:i,zone:e})}else return st.invalid(QC(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:r}={}){const i=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:r});return V1(this,{loc:i})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const n=MC(e,DG),r=!St(n.weekYear)||!St(n.weekNumber)||!St(n.weekday),i=!St(n.ordinal),s=!St(n.year),o=!St(n.month)||!St(n.day),u=s||o,a=n.weekYear||n.weekNumber;if((u||i)&&a)throw new M1("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(o&&i)throw new M1("Can't mix ordinal dates with month/day");let l;r?l=EG({...AL(this.c),...n}):St(n.ordinal)?(l={...this.toObject(),...n},St(n.day)&&(l.day=Math.min(BC(l.year,l.month),l.day))):l=AG({...SL(this.c),...n});const[c,f]=GC(l,this.o,this.zone);return V1(this,{ts:c,o:f})}plus(e){if(!this.isValid)return this;const n=vt.fromDurationLike(e);return V1(this,TG(this,n))}minus(e){if(!this.isValid)return this;const n=vt.fromDurationLike(e).negate();return V1(this,TG(this,n))}startOf(e){if(!this.isValid)return this;const n={},r=vt.normalizeUnit(e);switch(r){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break}if(r==="weeks"&&(n.weekday=1),r==="quarters"){const i=Math.ceil(this.month/3);n.month=(i-1)*3+1}return this.set(n)}endOf(e){return this.isValid?this.plus({[e]:1}).startOf(e).minus(1):this}toFormat(e,n={}){return this.isValid?is.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):vL}toLocaleString(e=rL,n={}){return this.isValid?is.create(this.loc.clone(n),e).formatDateTime(this):vL}toLocaleParts(e={}){return this.isValid?is.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:r=!1,includeOffset:i=!0,extendedZone:s=!1}={}){if(!this.isValid)return null;const o=e==="extended";let u=CL(this,o);return u+="T",u+=RG(this,o,n,r,i,s),u}toISODate({format:e="extended"}={}){return this.isValid?CL(this,e==="extended"):null}toISOWeekDate(){return WC(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:r=!0,includePrefix:i=!1,extendedZone:s=!1,format:o="extended"}={}){return this.isValid?(i?"T":"")+RG(this,o==="extended",n,e,r,s):null}toRFC2822(){return WC(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return WC(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?CL(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:r=!0}={}){let i="HH:mm:ss.SSS";return(n||e)&&(r&&(i+=" "),n?i+="z":e&&(i+="ZZ")),WC(this,i,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():vL}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{};const n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",r={}){if(!this.isValid||!e.isValid)return vt.invalid("created by diffing an invalid DateTime");const i={locale:this.locale,numberingSystem:this.numberingSystem,...r},s=obe(n).map(vt.normalizeUnit),o=e.valueOf()>this.valueOf(),u=o?this:e,a=o?e:this,l=OTe(u,a,s,i);return o?l.negate():l}diffNow(e="milliseconds",n={}){return this.diff(st.now(),e,n)}until(e){return this.isValid?hn.fromDateTimes(this,e):this}hasSame(e,n){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n)<=r&&r<=i.endOf(n)}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;const n=e.base||st.fromObject({},{zone:this.zone}),r=e.padding?this<n?-e.padding:e.padding:0;let i=["years","months","days","hours","minutes","seconds"],s=e.unit;return Array.isArray(e.unit)&&(i=e.unit,s=void 0),wG(n,this.plus(r),{...e,numeric:"always",units:i,unit:s})}toRelativeCalendar(e={}){return this.isValid?wG(e.base||st.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(st.isDateTime))throw new oo("min requires all arguments be DateTimes");return LQ(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(st.isDateTime))throw new oo("max requires all arguments be DateTimes");return LQ(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,r={}){const{locale:i=null,numberingSystem:s=null}=r,o=dn.fromOpts({locale:i,numberingSystem:s,defaultToEN:!0});return dG(o,e,n)}static fromStringExplain(e,n,r={}){return st.fromFormatExplain(e,n,r)}static get DATE_SHORT(){return rL}static get DATE_MED(){return dQ}static get DATE_MED_WITH_WEEKDAY(){return nbe}static get DATE_FULL(){return hQ}static get DATE_HUGE(){return pQ}static get TIME_SIMPLE(){return gQ}static get TIME_WITH_SECONDS(){return mQ}static get TIME_WITH_SHORT_OFFSET(){return yQ}static get TIME_WITH_LONG_OFFSET(){return EQ}static get TIME_24_SIMPLE(){return AQ}static get TIME_24_WITH_SECONDS(){return SQ}static get TIME_24_WITH_SHORT_OFFSET(){return vQ}static get TIME_24_WITH_LONG_OFFSET(){return _Q}static get DATETIME_SHORT(){return CQ}static get DATETIME_SHORT_WITH_SECONDS(){return bQ}static get DATETIME_MED(){return TQ}static get DATETIME_MED_WITH_SECONDS(){return RQ}static get DATETIME_MED_WITH_WEEKDAY(){return rbe}static get DATETIME_FULL(){return OQ}static get DATETIME_FULL_WITH_SECONDS(){return NQ}static get DATETIME_HUGE(){return DQ}static get DATETIME_HUGE_WITH_SECONDS(){return FQ}}function K1(t){if(st.isDateTime(t))return t;if(t&&t.valueOf&&px(t.valueOf()))return st.fromJSDate(t);if(t&&typeof t=="object")return st.fromObject(t);throw new oo(`Unknown datetime argument: ${t}, of type ${typeof t}`)}const KTe="2.5.2";rs.DateTime=st,rs.Duration=vt,rs.FixedOffsetZone=Zr,rs.IANAZone=Ku,rs.Info=W1,rs.Interval=hn,rs.InvalidZone=QQ,rs.Settings=zn,rs.SystemZone=UC,rs.VERSION=KTe,rs.Zone=Ap,Object.defineProperty(pr,"__esModule",{value:!0}),pr.LiteralYear=pr.LiteralQuarter=pr.LiteralMonth=pr.LiteralWeek=pr.LiteralDay=pr.LiteralHour=pr.LiteralTimestamp=pr.TimeFormatError=void 0;const Q0=rs,XTe=Z,JTe=B0,IG=pp,bL=dt;class ZTe extends Error{}pr.TimeFormatError=ZTe;function Ex(t,e){const n=t.slice(1);if(e){const r=n.match(/\[[^\]]+]$/);if(r)return{tzSpec:r[0].slice(1,-1),text:n.slice(0,-r[0].length)}}return{text:n}}const $G="yyyy",BG=`${$G}-LL`,lo=`${BG}-dd`,kG=`${lo} HH`,PG=`${kG}:mm`,TL=`${PG}:ss`;class MG extends bL.ExpressionDef{constructor(e,n,r){super(),this.units=n,this.timeType=r,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,n){const r={type:"dialect",function:"timeLiteral",literal:e,literalType:n};return this.timeZone&&(r.timezone=this.timeZone),r}makeValue(e,n){const r=this.makeLiteral(e,n),i="scalar",s=[r];return this.units?{dataType:n,expressionType:i,value:s,timeframe:this.units,evalSpace:"literal"}:{dataType:n,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}}class RL extends MG{constructor(e,n){super(e,n,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let n;const r=Ex(e,!0);e=r.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),r.text=e);const i=e.match(/^([^.,]+)[,.](\d+)$/);i&&(e=i[1]);let s=Q0.DateTime.fromFormat(e,TL);if(s.isValid)return new RL(r,n);if(s=Q0.DateTime.fromFormat(e,PG),s.isValid){r.text=r.text+":00",n="minute";const o=s.plus({minute:1}).toFormat(TL);return new OL(r,n,"timestamp",o)}}}pr.LiteralTimestamp=RL;class OL extends MG{constructor(e,n,r,i){super(e,n,r),this.nextLit=i,this.elementType="granularTimeLiteral"}apply(e,n,r){let i=this.getExpression(e),s=this.getNext();if(s){const o=r.getExpression(e);if(o.dataType==="timestamp"){const u=(0,bL.getMorphicValue)(i,"timestamp"),a=(0,bL.getMorphicValue)(s,"timestamp");if(u&&a)i=u,s=a;else return super.apply(e,n,r)}if((0,XTe.isTimeFieldType)(o.dataType)){const u=o.dataType;return new JTe.Range(new IG.ExprTime(u,i.value),new IG.ExprTime(u,s.value)).apply(e,n,r)}}return super.apply(e,n,r)}}class NL extends OL{constructor(e,n){super(e,"hour","timestamp",n),this.elementType="literal:hour"}static parse(e){const n=Ex(e,!1);let r=n.text;const i=Q0.DateTime.fromFormat(n.text,kG);if(i.isValid)return n.text=n.text+":00:00",r=i.plus({hour:1}).toFormat(TL),new NL(n,r)}}pr.LiteralHour=NL;class X1 extends OL{constructor(e,n,r){super(e,n,"date",r)}getExpression(e){const n=this.makeValue(this.literalPart,"date"),r=[this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp")];return{...n,morphic:{timestamp:r},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),n=[this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp")];return{...e,morphic:{timestamp:n}}}}class DL extends X1{constructor(e,n){super(e,"day",n),this.elementType="literal:day"}static parse(e){const n=Ex(e,!1);let r=n.text;const i=Q0.DateTime.fromFormat(n.text,lo);if(i.isValid)return r=i.plus({day:1}).toFormat(lo),new DL(n,r)}}pr.LiteralDay=DL;class FL extends X1{constructor(e,n){super(e,"week",n),this.elementType="literal:week"}static parse(e){const n=Ex(e,!1);let r=n.text;const i=n.text.slice(0,10),s=Q0.DateTime.fromFormat(i,lo);if(s.isValid&&s.weekday===7){const u=s.plus({days:7});return n.text=s.toFormat(lo),r=u.toFormat(lo),new FL(n,r)}}}pr.LiteralWeek=FL;class wL extends X1{constructor(e,n){super(e,"month",n),this.elementType="literal:month"}static parse(e){const n=Ex(e,!1);let r=n.text;const i=Q0.DateTime.fromFormat(n.text,BG);if(i.isValid){const s=i.plus({months:1});return n.text=i.toFormat(lo),r=s.toFormat(lo),new wL(n,r)}}}pr.LiteralMonth=wL;class LL extends X1{constructor(e,n){super(e,"quarter",n),this.elementType="literal:quarter"}static parse(e){const n=Ex(e,!1);let r=n.text;const i=n.text.match(/(^\d{4})-[qQ](\d)$/);if(i){const s=Number.parseInt(i[2])-1;let o=Q0.DateTime.fromFormat(i[1],"yyyy");s>0&&(o=o.plus({quarters:s}));const u=o.plus({quarter:1});return n.text=o.toFormat(lo),r=u.toFormat(lo),new LL(n,r)}}}pr.LiteralQuarter=LL;class IL extends X1{constructor(e,n){super(e,"year",n),this.elementType="literal:year"}static parse(e){const n=Ex(e,!1);let r=n.text;const i=Q0.DateTime.fromFormat(n.text,$G);if(i.isValid){const s=i.plus({year:1});return n.text=i.toFormat(lo),r=s.toFormat(lo),new IL(n,r)}}}pr.LiteralYear=IL;var VC={};Object.defineProperty(VC,"__esModule",{value:!0}),VC.PartialCompare=void 0;const eRe=hr,tRe=dt;class nRe extends tRe.ExpressionDef{constructor(e,n){super({right:n}),this.op=e,this.right=n,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,n,r){return this.right.apply(e,this.op,r)}requestExpression(e){}getExpression(e){return this.log("Partial comparison does not have a value"),(0,eRe.errorFor)("no value for partial compare")}}VC.PartialCompare=nRe;var Rp={};Object.defineProperty(Rp,"__esModule",{value:!0}),Rp.PickWhen=Rp.Pick=void 0;const Xu=Z,G0=hr,Vo=ln,rRe=dt,iRe=Ve,jG=an;function YC(t,e){return t===void 0||t.dataType==="null"||t.dataType==="error"?e:t}class sRe extends rRe.ExpressionDef{constructor(e,n){super({choices:e}),this.choices=e,this.elsePick=n,this.elementType="pick",this.has({elsePick:n})}requestExpression(e){if(this.elsePick!==void 0){for(const n of this.choices){if(n.pick===void 0)return;const r=n.when.requestExpression(e);if(r===void 0||r.dataType!=="boolean")return}return this.getExpression(e)}}apply(e,n,r){const i=["CASE"];let s,o="scalar",u="constant";for(const c of this.choices){const f=c.when.apply(e,"=",r),x=c.pick?c.pick.getExpression(e):r.getExpression(e);if(o=(0,Xu.maxExpressionType)(o,(0,Xu.maxExpressionType)(f.expressionType,x.expressionType)),u=(0,Xu.mergeEvalSpaces)(u,f.evalSpace,x.evalSpace),s&&!Vo.FT.typeEq(s,x,!0)){const h=Vo.FT.inspect(x);return this.log(`pick type '${h}', expected '${s.dataType}'[pick-values-must-match]`),(0,G0.errorFor)("pick when type")}s=YC(s,x),i.push(" WHEN ",...f.value," THEN ",...x.value)}const l=(this.elsePick||r).getExpression(e);if(s=YC(s,l),!Vo.FT.typeEq(s,l,!0)){const c=this.elsePick?"else":"pick default";return this.log(`${c} type '${Vo.FT.inspect(l)}', expected '${s.dataType}'[pick-values-must-match]`),(0,G0.errorFor)("pick else type")}return{dataType:s.dataType,expressionType:(0,Xu.maxExpressionType)(o,l.expressionType),evalSpace:(0,Xu.mergeEvalSpaces)(u,l.evalSpace),value:(0,jG.compressExpr)([...i," ELSE ",...l.value," END"])}}getExpression(e){if(this.elsePick===void 0)return this.log("pick incomplete, missing 'else'"),(0,G0.errorFor)("no value for partial pick");const n=[];for(const a of this.choices){if(a.pick===void 0)return this.log("pick with no value can only be used with apply"),(0,G0.errorFor)("no value for partial pick");if(a.when.requestExpression(e)===void 0)return this.log("pick with partial when can only be used with apply"),(0,G0.errorFor)("partial when");n.push({pick:a.pick.getExpression(e),when:a.when.getExpression(e)})}let r;const i=["CASE"];let s="scalar",o="constant";for(const a of n){if(!Vo.FT.typeEq(a.when,Vo.FT.boolT))return this.log(`when expression must be boolean, not '${Vo.FT.inspect(a.when)}`),(0,G0.errorFor)("pick when type");if(r&&!Vo.FT.typeEq(r,a.pick,!0)){const l=Vo.FT.inspect(a.pick);return this.log(`pick type '${l}', expected '${r.dataType}'[pick-values-must-match]`),(0,G0.errorFor)("pick value type")}r=YC(r,a.pick),s=(0,Xu.maxExpressionType)(s,(0,Xu.maxExpressionType)(a.pick.expressionType,a.when.expressionType)),o=(0,Xu.mergeEvalSpaces)(o,a.pick.evalSpace,a.when.evalSpace),i.push(" WHEN ",...a.when.value," THEN ",...a.pick.value)}const u=this.elsePick.getExpression(e);return s=(0,Xu.maxExpressionType)(s,u.expressionType),o=(0,Xu.mergeEvalSpaces)(o,u.evalSpace),r=YC(r,u),Vo.FT.typeEq(r,u,!0)?(i.push(" ELSE ",...u.value," END"),{dataType:r.dataType,expressionType:s,value:(0,jG.compressExpr)(i),evalSpace:o}):(this.elsePick.log(`else type '${Vo.FT.inspect(u)}', expected '${r.dataType}'[pick-values-must-match]`),(0,G0.errorFor)("pick value type mismatch"))}}Rp.Pick=sRe;class oRe extends iRe.MalloyElement{constructor(e,n){super({when:n}),this.pick=e,this.when=n,this.elementType="pickWhen",this.has({pick:e})}}Rp.PickWhen=oRe;var KC={};Object.defineProperty(KC,"__esModule",{value:!0}),KC.Timeframe=void 0;const uRe=Z,aRe=Ve;class lRe extends aRe.MalloyElement{constructor(e){super(),this.elementType="timeframe";let n=e.toLowerCase();n.endsWith("s")&&(n=n.slice(0,-1)),this.text=(0,uRe.isTimestampUnit)(n)?n:"second"}}KC.Timeframe=lRe;var XC={};Object.defineProperty(XC,"__esModule",{value:!0}),XC.TopBy=void 0;const cRe=Z,UG=dt,fRe=Ve,xRe=an;class dRe extends fRe.MalloyElement{constructor(e){super(),this.by=e,this.elementType="topBy",e instanceof UG.ExpressionDef&&this.has({by:e})}getBy(e){if(this.by instanceof UG.ExpressionDef){const n=this.by.getExpression(e);return(0,cRe.expressionIsAggregate)(n.expressionType)||this.log("top by expression must be an aggregate"),{by:"expression",e:(0,xRe.compressExpr)(n.value)}}return{by:"name",name:this.by}}}XC.TopBy=dRe;var W0={};Object.defineProperty(W0,"__esModule",{value:!0}),W0.ImportStatement=W0.ImportSelect=W0.ImportSourceName=void 0;const $L=Ve;class hRe extends $L.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}W0.ImportSourceName=hRe;class pRe extends $L.MalloyElement{constructor(e,n){super(),this.text=e,this.from=n,this.elementType="importName",n&&this.has({from:n})}}W0.ImportSelect=pRe;class gRe extends $L.ListOf{constructor(e,n){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,n).toString())}catch{this.log("Invalid URI in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const r=e.childRequest(this.fullURL);if(r)return r}}execute(e){const n=this.translator();if(!n)this.log("Cannot import without translation context");else if(this.fullURL){const r=n.root.importZone.getEntry(this.fullURL);if(r.status==="present"){const i=n.getChildExports(this.fullURL);if(this.notEmpty())for(const s of this.list){const o=s.from||s;if(e.getEntry(s.text))s.log(`Cannot redefine '${s.text}'`);else if(i[o.text]){const u={...i[o.text]};s.from&&(u.as=s.text),e.setEntry(s.text,{entry:u,exported:!1})}else o.log(`Cannot find '${o.text}', not imported`)}else for(const[s,o]of Object.entries(n.getChildExports(this.fullURL)))e.getEntry(s)?this.log(`Cannot redefine '${s}'`):e.setEntry(s,{entry:o,exported:!1})}else r.status==="error"?this.log(`import failed: '${r.message}'`):this.log(`import failed with status: '${r.status}'`)}}}W0.ImportStatement=gRe;var J1={};Object.defineProperty(J1,"__esModule",{value:!0}),J1.ExtendBlock=void 0;const mRe=Ve,yRe=Rn;class ERe extends mRe.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=yRe.LegalRefinementStage.Single}queryExecute(e){for(const n of this.list)for(const r of n.list)e.inputFS.extendSource(r)}}J1.ExtendBlock=ERe;var JC={};Object.defineProperty(JC,"__esModule",{value:!0}),JC.Argument=void 0;const ARe=Ve;class SRe extends ARe.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}JC.Argument=SRe;var ZC={};Object.defineProperty(ZC,"__esModule",{value:!0}),ZC.HasParameter=void 0;const qG=Z,vRe=Ve;class _Re extends vRe.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,qG.isCastType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default}))}parameter(){var e;if(this.default!==void 0){const n=this.default.constantValue();return this.type&&this.type!==n.dataType&&n.dataType!=="null"&&n.dataType!=="error"&&this.default.log(`Default value for parameter does not match declared type \`${this.type}\``),n.dataType==="null"?this.type?{value:n.value,name:this.name,type:this.type}:(this.default.log("Default value cannot have type `null` unless parameter type is also specified"),{value:n.value,name:this.name,type:"error"}):!(0,qG.isCastType)(n.dataType)&&n.dataType!=="error"?(this.default.log(`Default value cannot have type \`${n.dataType}\``),{value:n.value,name:this.name,type:"error"}):{value:n.value,name:this.name,type:n.dataType}}return this.type===void 0&&this.log("Parameter must have default value or declared type"),{value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"}}}ZC.HasParameter=_Re;var eb={};Object.defineProperty(eb,"__esModule",{value:!0}),eb.AnonymousQuery=void 0;const CRe=Ve,bRe=Yr;class TRe extends CRe.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=bRe.extendNoteMethod,this.has({queryExpr:e})}execute(e){const n=this.queryExpr.getQuery();if(!n){this.queryExpr.sqLog("Cannot run this object as a query");return}const r={...n.query()},i=this.note||{};r.annotation&&(i.inherits=r.annotation),(i.notes||i.blockNotes||i.inherits)&&(r.annotation=i),e.queryList.push(r)}}eb.AnonymousQuery=TRe;var V0={};Object.defineProperty(V0,"__esModule",{value:!0}),V0.View=void 0;const RRe=Ve;let ORe=class extends RRe.MalloyElement{pipeline(e,n){return this.pipelineComp(e,n).pipeline}};V0.View=ORe;var tb={};Object.defineProperty(tb,"__esModule",{value:!0}),tb.ViewArrow=void 0;const NRe=Jr,DRe=V0;class FRe extends DRe.View{constructor(e,n){super({base:e,operation:n}),this.base=e,this.operation=n,this.elementType="viewArrow"}pipelineComp(e){const n=this.base.pipelineComp(e),r=new NRe.StaticSpace(n.outputStruct),i=this.operation.pipelineComp(r);return{pipeline:[...n.pipeline,...i.pipeline],outputStruct:i.outputStruct}}refine(e,n,r){return this.log("A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}tb.ViewArrow=FRe;var nb={},Z1={};Object.defineProperty(Z1,"__esModule",{value:!0}),Z1.refine=void 0;const BL=Ru,kL=w0;function wRe(t,e,n){var r,i;if(e.length!==1)return t.log("Named refinements of multi-stage views are not supported"),e;const s={...e[0]},o=n;if((0,BL.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?[...(r=s.filterList)!==null&&r!==void 0?r:[],...(i=o.filterList)!==null&&i!==void 0?i:[]]:void 0,(0,BL.isQuerySegment)(o)&&(0,BL.isQuerySegment)(s)){const u=[],a=[],l=new Map(s.queryFields.map(c=>[(0,kL.nameFromDef)(c),c]));for(const c of o.queryFields)l.has((0,kL.nameFromDef)(c))?u.push(c):a.push(c);s.queryFields=[...s.queryFields,...a],u.length>0&&t.log(`overlapping fields in refinement: ${u.map(kL.nameFromDef)}`)}else o.type==="index"&&s.type==="index"&&(s.indexFields=[...o.indexFields,...s.indexFields]);return[s]}Z1.refine=wRe,Object.defineProperty(nb,"__esModule",{value:!0}),nb.ViewRefine=void 0;const LRe=Xr,IRe=Ns,$Re=Z1,BRe=V0;class kRe extends BRe.View{constructor(e,n){super({base:e,refinement:n}),this.base=e,this.refinement=n,this.elementType="refine"}pipelineComp(e,n){const r=this.base.pipelineComp(e),i=this.refinement.refine(e,r.pipeline,n);return{pipeline:i,annotation:r.annotation,outputStruct:i.length>0?(0,IRe.getFinalStruct)(this.refinement,e.structDef(),i):LRe.ErrorFactory.structDef}}refine(e,n,r){const i=this.pipeline(e,r);return i.length!==1?(this.refinement.log("refinement must have exactly one stage"),n):(0,$Re.refine)(this,n,i[0])}getImplicitName(){return this.base.getImplicitName()}}nb.ViewRefine=kRe;var rb={};Object.defineProperty(rb,"__esModule",{value:!0}),rb.ReferenceView=void 0;const HG=Z,zG=Xr,PRe=Ns,MRe=Kr,jRe=Z1,URe=V0;class qRe extends URe.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,n){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:n}={forRefinement:!1}){const r=this.reference.getField(e),i=function(){return{inputStruct:zG.ErrorFactory.structDef,outputStruct:zG.ErrorFactory.structDef,pipeline:[],error:!0}};if(!r.found)return this.log(`\`${this.reference.refString}\` is not defined`),i();if(!(r.found instanceof MRe.SpaceField))throw new Error("Expected space field");const s=r.found.fieldDef();if(s===void 0)throw new Error("Expected field to have definition");if((0,HG.isAtomicFieldType)(s.type)){const o={type:"reduce",queryFields:[this.reference.refToField]},{dialect:u,queryTimezone:a,structRelationship:l}=e.structDef(),c=this.reference.nameString;return{pipeline:[o],name:c,outputStruct:{type:"struct",dialect:u,queryTimezone:a,name:c,fields:[s],structRelationship:l,structSource:{type:"query_result"}}}}else return(0,HG.isTurtleDef)(s)?this.reference.list.length>1?(n?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,PRe.getFinalStruct)(this.reference,e.structDef(),s.pipeline)}:(n?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){const{pipeline:n,error:r}=this._pipelineComp(e,{forRefinement:!0});if(!r){if(n.length!==1){this.reference.log(`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return n[0]}}refine(e,n,r){const i=this.getRefinementSegment(e);return i?(0,jRe.refine)(this,n,i):n}getImplicitName(){return this.reference.nameString}}rb.ReferenceView=qRe;var ib={},ey={},sb={},ty={};Object.defineProperty(ty,"__esModule",{value:!0}),ty.Index=void 0;const HRe=Ve,zRe=Rn;let QRe=class extends HRe.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=zRe.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}};ty.Index=QRe;var ny={};Object.defineProperty(ny,"__esModule",{value:!0}),ny.SampleProperty=void 0;const GRe=Ve,QG=Rn;class WRe extends GRe.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=QG.LegalRefinementStage.Tail,this.forceQueryClass=QG.QueryClass.Index}sampling(){return this.sample}}ny.SampleProperty=WRe;var ob={};Object.defineProperty(ob,"__esModule",{value:!0}),ob.IndexFieldSpace=void 0;const GG=Z,PL=ht,VRe=Kr,YRe=Ho,KRe=I1,XRe=Jr;class JRe extends YRe.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const n of e)n instanceof PL.FieldReference?super.pushFields(n):n instanceof PL.WildcardFieldReference?this.addWild(n):n.log("Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.log("index query operations cannot be refined"),{type:"index",indexFields:[]};const n=[];for(const[r,i]of this.entries())if(i instanceof VRe.SpaceField){const s=this.expandedWild[r];if(s){n.push({type:"fieldref",path:s});continue}if(i instanceof KRe.ReferenceField){const o=i.fieldRef,u=o.getField(this.exprSpace);u.error?o.log(u.error):n.push(o.refToField)}}return{type:"index",indexFields:n}}addRefineFromFields(e){}addWild(e){var n;let r=this.exprSpace;const i=[];if(e.joinPath)for(const u of e.joinPath.list){const a=u.refString;i.push(a);const l=r.entry(a);if(l)if(l instanceof XRe.StructSpaceField)r=l.fieldSpace;else{u.log(`Field '${a}' does not contain rows and cannot be expanded with '*'`);return}else{u.log(`No such field as '${a}'`);return}}const s=this.dialectObj(),o=[];for(const[u,a]of r.entries()){if(e.except.has(u)||a.refType==="parameter")continue;const l=PL.IndexFieldReference.indexOutputName([...i,u]);if(this.entry(l)){const c=(n=this.expandedWild[l])===null||n===void 0?void 0:n.join(".");e.log(`Cannot expand '${u}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=a.typeDesc();(0,GG.isAtomicFieldType)(c.dataType)&&(0,GG.expressionIsScalar)(c.expressionType)&&(s===void 0||!s.ignoreInProject(u))&&(o.push({name:l,entry:a}),this.expandedWild[l]=i.concat(u))}}for(const u of o.sort((a,l)=>a.name.localeCompare(l.name)))this.setEntry(u.name,u.entry)}}ob.IndexFieldSpace=JRe,Object.defineProperty(sb,"__esModule",{value:!0}),sb.IndexBuilder=void 0;const ML=Z,ZRe=Xr,eOe=qo,tOe=ty,nOe=M0,rOe=ny,iOe=ob;class sOe{constructor(e,n,r,i){this.filters=[],this.type="index",this.resultFS=new iOe.IndexFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof eOe.Filter?this.filters.push(...e.getFilterList(this.inputFS)):e instanceof nOe.Limit?(this.limit&&this.limit.log("Ignored, too many limit: statements"),this.limit=e):e instanceof tOe.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.log("Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof rOe.SampleProperty?this.sample=e.sampling():e.log("Not legal in an index query operation")}finalize(e){if(e&&!(0,ML.isIndexSegment)(e)&&!(0,ML.isPartialSegment)(e))return this.resultFS.log(`Can't refine index with ${e.type}`),ZRe.ErrorFactory.indexSegment;const n=this.resultFS.getPipeSegment(e),r=(e==null?void 0:e.filterList)||[];return this.filters.length>0&&!r?n.filterList=this.filters:r&&(n.filterList=[...r,...this.filters]),e!=null&&e.limit&&(n.limit=e.limit),this.limit&&(n.limit=this.limit.limit),this.indexOn&&(n.weightMeasure=this.indexOn.refString),e&&(0,ML.isIndexSegment)(e)&&(e!=null&&e.sample)&&(n.sample=e.sample),this.sample&&(n.sample=this.sample),n}}sb.IndexBuilder=sOe;var ub={},ry={};Object.defineProperty(ry,"__esModule",{value:!0}),ry.GroupBy=void 0;const oOe=Os,WG=Rn;class uOe extends oOe.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=WG.LegalRefinementStage.Single,this.forceQueryClass=WG.QueryClass.Grouping}}ry.GroupBy=uOe;var ab={};Object.defineProperty(ab,"__esModule",{value:!0}),ab.ProjectFieldSpace=void 0;const jL=Z,aOe=Ho;class lOe extends aOe.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e.dataType==="turtle"||(0,jL.expressionIsAggregate)(e.expressionType)?!1:(0,jL.expressionInvolvesAggregate)(e.expressionType)&&(0,jL.expressionIsAnalytic)(e.expressionType)?(this.log("Cannot add aggregate analyics to project"),!1):!0}}ab.ProjectFieldSpace=lOe;var Y0={},Ax={};Object.defineProperty(Ax,"__esModule",{value:!0}),Ax.Ordering=Ax.OrderBy=void 0;const cOe=Z,VG=j0,YG=Ve,fOe=Rn;class xOe extends YG.MalloyElement{constructor(e,n){super(),this.field=e,this.dir=n,this.elementType="orderBy",e instanceof VG.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var n;if(this.field instanceof VG.FieldName&&e.isQueryFieldSpace()){const 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,cOe.expressionIsAnalytic)((n=s.found)===null||n===void 0?void 0:n.typeDesc().expressionType)&&this.log(`Illegal order by of analytic field ${this.field.refString}`)}const r={field:this.modelField};return this.dir&&(r.dir=this.dir),r}}Ax.OrderBy=xOe;class dOe extends YG.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=fOe.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(n=>n.getOrderBy(e))}}Ax.Ordering=dOe;var iy={};Object.defineProperty(iy,"__esModule",{value:!0}),iy.Top=void 0;const KG=Z,hOe=an,pOe=j0,gOe=Ve,mOe=Rn;let yOe=class extends gOe.MalloyElement{constructor(e,n){super(),this.limit=e,this.by=n,this.elementType="top",this.queryRefinementStage=mOe.LegalRefinementStage.Tail,this.forceQueryClass=void 0,this.has({by:n})}getBy(e){var n;if(this.by)if(this.by instanceof pOe.FieldName){if(e.isQueryFieldSpace()){const r=e.outputSpace(),i=this.by.getField(r);i.error&&this.by.log(i.error),(!i.found||!i.isOutputField)&&this.by.log(`Unknown field ${this.by.refString} in output space`),(0,KG.expressionIsAnalytic)((n=i.found)===null||n===void 0?void 0:n.typeDesc().expressionType)&&this.by.log(`Illegal order by of analytic field ${this.by.refString}`)}return{by:"name",name:this.by.refString}}else{const r=this.by.getExpression(e);return(0,KG.expressionIsAggregate)(r.expressionType)&&this.by.log("top by expression must be an aggregate"),r.evalSpace==="output"&&this.by.log("top by expression must be an output expression"),{by:"expression",e:(0,hOe.compressExpr)(r.value)}}}};iy.Top=yOe,Object.defineProperty(Y0,"__esModule",{value:!0}),Y0.ReduceBuilder=Y0.QuerySegmentBuilder=void 0;const XG=Z,EOe=Xr,AOe=qo,SOe=M0,JG=Ax,ZG=iy,vOe=Ho,_Oe=Os;class eW{constructor(){this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}if(e instanceof _Oe.DefinitionList)this.resultFS.pushFields(...e.list);else if(e instanceof AOe.Filter){const n=e.havingClause?this.resultFS:this.inputFS;this.filters.push(...e.getFilterList(n))}else e instanceof ZG.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 SOe.Limit?this.limit?e.log("Query operation already limited"):this.limit=e.limit:e instanceof JG.Ordering&&(this.order?e.log("Query operation already sorted"):this.order=e)}refineFrom(e,n){if(e&&e.type!=="index"&&e.type!=="raw"&&(this.order||(e.orderBy?n.orderBy=e.orderBy:e.by&&(n.by=e.by)),!this.limit&&e.limit&&(n.limit=e.limit)),this.limit&&(n.limit=this.limit),this.order instanceof ZG.Top){const i=this.order.getBy(this.inputFS);i&&(n.by=i)}this.order instanceof JG.Ordering&&(n.orderBy=this.order.getOrderBy(this.inputFS));const r=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!r?n.filterList=this.filters:r&&(n.filterList=[...r,...this.filters])}}Y0.QuerySegmentBuilder=eW;class COe extends eW{constructor(e,n,r,i){super(),this.type="grouping",this.resultFS=new vOe.ReduceFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}finalize(e){let n;if(e)if((0,XG.isReduceSegment)(e)||(0,XG.isPartialSegment)(e))n=e;else return this.resultFS.log(`Can't refine reduce with ${e.type}`),EOe.ErrorFactory.reduceSegment;const r=this.resultFS.getQuerySegment(n);return this.refineFrom(n,r),r}}Y0.ReduceBuilder=COe,Object.defineProperty(ub,"__esModule",{value:!0}),ub.ProjectBuilder=void 0;const tW=Z,bOe=Xr,TOe=ry,ROe=ab,OOe=Y0;class NOe extends OOe.QuerySegmentBuilder{constructor(e,n,r,i){super(),this.type="project",this.resultFS=new ROe.ProjectFieldSpace(e,n,r,i),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof TOe.GroupBy?e.log("Illegal statement in a select query operation"):super.execute(e)}finalize(e){let n;if(e)if((0,tW.isProjectSegment)(e)||(0,tW.isPartialSegment)(e))n=e;else return this.resultFS.log(`Can't refine select with ${e.type}`),bOe.ErrorFactory.projectSegment;const r=this.resultFS.getQuerySegment(n);return this.refineFrom(n,r),r}}ub.ProjectBuilder=NOe;var lb={};Object.defineProperty(lb,"__esModule",{value:!0}),lb.PartialBuilder=void 0;const DOe=Ru,FOe=Y0;class wOe extends FOe.ReduceBuilder{finalize(e){const n=super.finalize(e);if((0,DOe.isQuerySegment)(n))return{...n,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${n.type}`)}}lb.PartialBuilder=wOe,Object.defineProperty(ey,"__esModule",{value:!0}),ey.QOpDesc=void 0;const LOe=sb,IOe=ub,$Oe=Y0,BOe=Ve,kOe=Ns,POe=Jr,Sx=Rn,MOe=lb;class jOe extends BOe.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let n,r=!1;this.refineThis&&(this.refineThis.type==="reduce"?n=Sx.QueryClass.Grouping:this.refineThis.type==="project"?n=Sx.QueryClass.Project:this.refineThis.type==="index"&&(n=Sx.QueryClass.Index));for(const i of this.list)i.forceQueryClass&&(n?n!==i.forceQueryClass&&i.log(`Not legal in ${n} query`):n=i.forceQueryClass),r||(r=(e=i.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return n===void 0&&r&&(this.log("Can't determine view type (`group_by` / `aggregate` / `nest`, `project`, `index`)"),n=Sx.QueryClass.Project),this.opClass=n,n}refineFrom(e){this.refineThis=e}getBuilder(e,n,r){switch(this.computeType()){case Sx.QueryClass.Grouping:return new $Oe.ReduceBuilder(e,this.refineThis,n,r);case Sx.QueryClass.Project:return new IOe.ProjectBuilder(e,this.refineThis,n,r);case Sx.QueryClass.Index:return new LOe.IndexBuilder(e,this.refineThis,n,r);case void 0:return new MOe.PartialBuilder(e,this.refineThis,n,r)}}getOp(e,n){const r=this.getBuilder(e,n,this);for(const s of this.list)r.execute(s);const i=r.finalize(this.refineThis);return{segment:i,outputSpace:()=>new POe.StaticSpace((0,kOe.opOutputStruct)(this,e.structDef(),i))}}}ey.QOpDesc=jOe,Object.defineProperty(ib,"__esModule",{value:!0}),ib.QOpDescView=void 0;const UOe=Z,qOe=Jr,nW=ey,HOe=Ns,UL=Rn,zOe=V0;class QOe extends zOe.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,n){const r=this.operation.getOp(e,n);return{pipeline:[r.segment],outputStruct:r.outputSpace().structDef()}}getOp(e,n,r,i){return(0,UOe.isRawSegment)(i)?(this.log("A raw query cannot be refined"),i):(r.refineFrom(i),r.getOp(e,n).segment)}refine(e,n,r){const i=[...n];if(i.length===0)return i;if(i.length===1)return this.operation.refineFrom(i[0]),[this.getOp(e,r,this.operation,i[0])];const s=new nW.QOpDesc([]),o=new nW.QOpDesc([]);for(const u of this.operation.list)switch(u.queryRefinementStage){case UL.LegalRefinementStage.Head:s.push(u);break;case UL.LegalRefinementStage.Single:u.log("Illegal in refinement of a query with more than one stage");break;case UL.LegalRefinementStage.Tail:o.push(u);break;default:u.log("Illegal query refinement")}if(s.notEmpty()&&(this.has({headRefinements:s}),i[0]=this.getOp(e,void 0,s,i[0])),o.notEmpty()){const u=i.length-1;this.has({tailRefinements:o});const a=(0,HOe.getFinalStruct)(this,e.structDef(),i.slice(-1));i[u]=this.getOp(new qOe.StaticSpace(a),void 0,o,i[u])}return i}getImplicitName(){}}ib.QOpDescView=QOe;var pn={};Object.defineProperty(pn,"__esModule",{value:!0}),pn.FieldDefinitionValue=pn.DefSpace=pn.DimensionFieldDeclaration=pn.MeasureFieldDeclaration=pn.DeclareFieldDeclaration=pn.ProjectFieldDeclaration=pn.GroupByFieldDeclaration=pn.AggregateFieldDeclaration=pn.CalculateFieldDeclaration=pn.AtomicFieldDeclaration=void 0;const GOe=Z,WOe=an,VOe=ln,YOe=fp,KOe=Ve,vx=Kn,XOe=Yr,JOe=Kr;class K0 extends KOe.MalloyElement{constructor(e,n,r){super({expr:e}),this.expr=e,this.defineName=n,this.exprSrc=r,this.isNoteableObj=!0,this.extendNote=XOe.extendNoteMethod}fieldDef(e,n){return this.queryFieldDef(new qL(e,this),n)}executesInOutputSpace(){return!1}queryFieldDef(e,n){let r;function i(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const a=this.executesInOutputSpace()?i():e;r=this.expr.getExpression(a)}catch(a){return this.log(`Cannot define '${n}', ${a.message}`),{name:n,type:"error"}}const s=(0,WOe.compressExpr)(r.value);let o=r.dataType;if(o==="null"&&(this.expr.log('null value defaults to type number, use "null::TYPE" to specify correct type',"warn"),o="number"),(0,GOe.isAtomicFieldType)(o)&&o!=="error"){const a={name:n,type:o,location:this.location};return s.length>0&&(a.e=s),r.expressionType&&(a.expressionType=r.expressionType),this.typecheckExprValue(r),this.exprSrc&&(a.code=this.exprSrc),(0,YOe.isGranularResult)(r)&&a.type==="timestamp"&&(a.timeframe=r.timeframe),this.note&&(a.annotation=this.note),a}if(!(e instanceof qL&&e.foundCircle)&&r.dataType!=="error"){const a=VOe.FT.inspect(r);this.log(`Cannot define '${n}', unexpected type: ${a}`)}return{name:n,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new rW(e,this))}}pn.AtomicFieldDeclaration=K0;class ZOe extends K0{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,vx.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}pn.CalculateFieldDeclaration=ZOe;class eNe extends K0{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,vx.typecheckAggregate)(e,this)}}pn.AggregateFieldDeclaration=eNe;class tNe extends K0{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,vx.typecheckGroupBy)(e,this)}}pn.GroupByFieldDeclaration=tNe;class nNe extends K0{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,vx.typecheckProject)(e,this)}}pn.ProjectFieldDeclaration=nNe;class rNe extends K0{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,vx.typecheckDeclare)(e,this)}}pn.DeclareFieldDeclaration=rNe;class iNe extends K0{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,vx.typecheckMeasure)(e,this)}}pn.MeasureFieldDeclaration=iNe;class sNe extends K0{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,vx.typecheckDimension)(e,this)}}pn.DimensionFieldDeclaration=sNe;class qL{constructor(e,n){this.realFS=e,this.circular=n,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")}}pn.DefSpace=qL;class rW extends JOe.SpaceField{constructor(e,n){super(),this.space=e,this.exprDef=n,this.fieldName=n.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){const n=this.exprDef.queryFieldDef(e,this.name);this.qfd=n}return this.qfd}typeDesc(){const e=this.qfd||this.fieldDef();return this.fieldTypeFromFieldDef(e)}}pn.FieldDefinitionValue=rW;var cb={};Object.defineProperty(cb,"__esModule",{value:!0}),cb.Aggregate=void 0;const oNe=Os,iW=Rn;let uNe=class extends oNe.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=iW.LegalRefinementStage.Single,this.forceQueryClass=iW.QueryClass.Grouping}};cb.Aggregate=uNe;var fb={};Object.defineProperty(fb,"__esModule",{value:!0}),fb.Calculate=void 0;const aNe=Os,lNe=Rn;class cNe extends aNe.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=lNe.LegalRefinementStage.Single}}fb.Calculate=cNe;var sy={};Object.defineProperty(sy,"__esModule",{value:!0}),sy.Dimensions=void 0;const fNe=L0;class xNe extends fNe.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}sy.Dimensions=xNe;var oy={};Object.defineProperty(oy,"__esModule",{value:!0}),oy.Measures=void 0;const dNe=L0;class hNe extends dNe.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}oy.Measures=hNe;var xb={};Object.defineProperty(xb,"__esModule",{value:!0}),xb.Nests=void 0;const pNe=Os,sW=Rn;class gNe extends pNe.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=sW.LegalRefinementStage.Single,this.forceQueryClass=sW.QueryClass.Grouping}}xb.Nests=gNe;var db={};Object.defineProperty(db,"__esModule",{value:!0}),db.ProjectStatement=void 0;const mNe=Os,oW=Rn;class yNe extends mNe.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=oW.QueryClass.Project,this.queryRefinementStage=oW.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}db.ProjectStatement=yNe;var X0={},ml={};Object.defineProperty(ml,"__esModule",{value:!0}),ml.findReferences=ml.deprecatedParseTableURI=ml.constructTableKey=void 0;const ENe=ox,HL=Bn;function zL(t){const e=(0,HL.getStringIfShort)(t);if(e)return e;const n=[],r=t.string().sqlString();if(r){for(const i of(0,HL.getStringParts)(r))typeof i=="string"&&n.push(i);return n.join("")}return""}class ANe{constructor(e,n){this.trans=e,this.tokens=n,this.needTables={},this.needImports={}}registerTableReference(e,n,r){const i=uW(e,n);this.needTables[i]||(this.needTables[i]={connectionName:e,tablePath:n,firstReference:r})}enterTableMethod(e){const n=(0,HL.getId)(e.connectionId()),r=zL(e.tablePath()),i=this.trans.rangeFromContext(e);this.registerTableReference(n,r,i)}enterTableFunction(e){const n=zL(e.tableURI()),{connectionName:r,tablePath:i}=aW(n),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterImportURL(e){const n=zL(e);this.needImports[n]||(this.needImports[n]=this.trans.rangeFromContext(e))}}function uW(t,e){return t===void 0?e:`${t}:${e}`}ml.constructTableKey=uW;function aW(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,n,r]=e;return{connectionName:n,tablePath:r}}else return{tablePath:t}}ml.deprecatedParseTableURI=aW;function SNe(t,e,n){const r=new ANe(t,e),i=r;return ENe.ParseTreeWalker.DEFAULT.walk(i,n),{tables:r.needTables,urls:r.needImports}}ml.findReferences=SNe,Object.defineProperty(X0,"__esModule",{value:!0}),X0.TableFunctionSource=X0.TableMethodSource=X0.TableSource=void 0;const lW=ml,vNe=Uo,cW=Xr;class QL extends vNe.Source{structDef(){var e,n,r;const i=this.getTableInfo();if(i===void 0)return cW.ErrorFactory.structDef;const{tablePath:s,connectionName:o}=i,u=(0,lW.constructTableKey)(o,s),a=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(u);let l=`Schema read failure for table '${s}' for connection '${o}'`;if(a){if(a.status==="present"){(n=this.document())===null||n===void 0||n.checkExperimentalDialect(this,a.value.dialect),a.value.location=this.location,a.value.fields.forEach(f=>{f.location=this.location});const c={...a.value,fields:a.value.fields.map(f=>({...f,location:this.location})),location:this.location};return(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(c),c}a.status==="error"&&(l=a.message)}return this.log(l),cW.ErrorFactory.structDef}}X0.TableSource=QL;class _Ne extends QL{constructor(e,n){super(),this.connectionName=e,this.tablePath=n,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const n=this.modelEntry(this.connectionName),r=this.connectionName.refString;if(n===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(r,{entry:{type:"connection",name:r},exported:!0},!0);else if(n.entry.type!=="connection"){this.connectionName.log(`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}X0.TableMethodSource=_Ne;class CNe extends QL{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,lW.deprecatedParseTableURI)(this.tableURI)}}X0.TableFunctionSource=CNe;var hb={};Object.defineProperty(hb,"__esModule",{value:!0}),hb.SQLString=void 0;const bNe=Ve,fW=Vu;class TNe extends bNe.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter(RNe)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof fW.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.log("This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const n of this.elements)if(typeof n=="string")e.push({sql:n});else{const r=n.getQuery();r?e.push(r.query()):n.sqLog("Cannot expand into a query")}return e}}hb.SQLString=TNe;function RNe(t){return t instanceof fW.SourceQueryElement}var pb={};Object.defineProperty(pb,"__esModule",{value:!0}),pb.SourceDesc=void 0;const ONe=Ve;class NNe extends ONe.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}pb.SourceDesc=NNe;var gb={};Object.defineProperty(gb,"__esModule",{value:!0}),gb.isSourceProperty=void 0;const DNe=qo,FNe=ts,wNe=L0,LNe=rp,INe=$0,$Ne=ip,BNe=sp,kNe=op,PNe=I0;function MNe(t){return t instanceof DNe.Filter||t instanceof FNe.Joins||t instanceof wNe.DeclareFields||t instanceof LNe.FieldListEdit||t instanceof INe.Renames||t instanceof $Ne.PrimaryKey||t instanceof PNe.ObjectAnnotation||t instanceof BNe.Views||t instanceof kNe.TimezoneStatement}gb.isSourceProperty=MNe;var mb={};Object.defineProperty(mb,"__esModule",{value:!0}),mb.isFieldCollectionMember=void 0;const jNe=pn,xW=ht;function UNe(t){return t instanceof xW.FieldReference||t instanceof xW.WildcardFieldReference||t instanceof jNe.AtomicFieldDeclaration}mb.isFieldCollectionMember=UNe;var yb={};Object.defineProperty(yb,"__esModule",{value:!0}),yb.isQueryElement=void 0;const qNe=up,HNe=ap,zNe=D1,QNe=F1;function GNe(t){return t instanceof qNe.QueryArrow||t instanceof HNe.QueryRefine||t instanceof zNe.QueryReference||t instanceof QNe.QueryRaw}yb.isQueryElement=GNe;var dW={};Object.defineProperty(dW,"__esModule",{value:!0});var Eb={};Object.defineProperty(Eb,"__esModule",{value:!0}),Eb.isQueryProperty=void 0;function WNe(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}Eb.isQueryProperty=WNe;var Ab={};Object.defineProperty(Ab,"__esModule",{value:!0}),Ab.isQueryExtendProperty=void 0;const VNe=sy,YNe=ts,KNe=oy;function XNe(t){return t instanceof VNe.Dimensions||t instanceof KNe.Measures||t instanceof YNe.Joins}Ab.isQueryExtendProperty=XNe;var Sb={};Object.defineProperty(Sb,"__esModule",{value:!0}),Sb.isFieldPropStatement=void 0;const JNe=k0,ZNe=qo,eDe=M0,tDe=yp;function nDe(t){return t instanceof ZNe.Filter||t instanceof eDe.Limit||t instanceof tDe.PartitionBy||t instanceof JNe.FunctionOrdering}Sb.isFieldPropStatement=nDe,function(t){var e=F&&F.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=F&&F.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(p1,t),n(Zh,t),n(ep,t),n(Uo,t),n(v1,t),n(Vu,t),n(W_,t),n(V_,t),n(X_,t),n(R1,t),n(eC,t),n(rp,t),n(ip,t),n($0,t),n(sp,t),n(op,t),n(tC,t),n(gp,t),n(rC,t),n(k0,t),n(iC,t),n(pl,t),n(sC,t),n(mp,t),n(oC,t),n(uC,t),n(aC,t),n(dp,t),n(lC,t),n(cC,t),n(xC,t),n(B1,t),n(L1,t),n(cx,t),n(dC,t),n(hC,t),n(gC,t),n(yC,t),n(EC,t),n(AC,t),n(SC,t),n(vC,t),n(_C,t),n(CC,t),n(bC,t),n(TC,t),n(RC,t),n(OC,t),n(NC,t),n(wC,t),n(pr,t),n(VC,t),n(yp,t),n(Rp,t),n(B0,t),n(KC,t),n(XC,t),n(k1,t),n(an,t),n(W0,t),n(J1,t),n(JC,t),n(ZC,t),n(eb,t),n(ap,t),n(up,t),n(V0,t),n(tb,t),n(nb,t),n(rb,t),n(ib,t),n(pn,t),n(ht,t),n(cb,t),n(fb,t),n(L0,t),n(sy,t),n(J1,t),n(qo,t),n(ry,t),n(ty,t),n(ts,t),n(g1,t),n(M0,t),n(oy,t),n(p1,t),n(xb,t),n(Ax,t),n(db,t),n(ey,t),n(ny,t),n(iy,t),n(lp,t),n(lx,t),n(w1,t),n(X0,t),n(hb,t),n(I0,t),n(dl,t),n(pb,t),n(gb,t),n(dt,t),n(mb,t),n(j0,t),n(Ve,t),n(yb,t),n(dW,t),n(Eb,t),n(Ab,t),n(Sb,t)}(w_);var vb={},Op={};Object.defineProperty(Op,"__esModule",{value:!0}),Op.ConstantExpression=Op.ConstantFieldSpace=void 0;const rDe=dl,hW=dt,iDe=dp,sDe=an;class pW{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:"Only constants allowed in parameter default values",found:void 0}}entries(){return[]}entry(){}dialectObj(){}isQueryFieldSpace(){return!1}}Op.ConstantFieldSpace=pW;class oDe extends hW.ExpressionDef{constructor(e){super(),this.refType=e,this.elementType="$"}getExpression(e){return{dataType:this.refType,value:[{type:"applyVal"}],expressionType:"scalar",evalSpace:"constant"}}}class uDe extends hW.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new pW),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}constantCondition(e){const r=new iDe.ExprCompare(new oDe(e),rDe.Comparison.EqualTo,this.expr).getExpression(this.constantFs);return{...r,value:(0,sDe.compressExpr)(r.value)}}apply(e,n,r){return this.expr.apply(e,n,r)}requestExpression(e){return this.expr.requestExpression(e)}}Op.ConstantExpression=uDe;var aDe=F&&F.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),lDe=F&&F.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),cDe=F&&F.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&aDe(e,t,n);return lDe(e,t),e};Object.defineProperty(vb,"__esModule",{value:!0}),vb.MalloyToAST=void 0;const gW=IS,fDe=m1,ee=cDe(w_),xDe=xr,dDe=w_,kn=Bn,GL=Z,hDe=fl,pDe=Op;class mW extends ee.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class WL extends ee.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const gDe=["##! m4warnings=error"];class mDe extends fDe.AbstractParseTreeVisitor{constructor(e,n,r){super(),this.parseInfo=e,this.msgLog=n,this.compilerFlags=r;for(const i of gDe){const s=hDe.Tag.fromTagline(i,this.compilerFlags);this.compilerFlags=s.tag}}internalError(e,n){const r=`Internal Translator Error: ${n}`;return this.contextError(e,r),new Error(r)}astError(e,n,r="error"){this.msgLog.log({message:n,at:e.location,severity:r})}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}contextError(e,n,r="error"){this.msgLog.log({message:n,at:this.getLocation(e),severity:r})}inExperiment(e,n){const r=this.compilerFlags.tag("experimental");return r&&(r.bare()||r.has(e))?!0:(this.contextError(n,`Experimental flag '${e}' required to enable this feature`),!1)}m4Severity(){const e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,n){const r=this.m4Severity();r&&this.contextError(e,n,r)}only(e,n,r){const i=[];for(const s of e){const o=n(s);o?i.push(o):s instanceof WL||this.astError(s,`Parser enountered unexpected statement type '${s.elementType}' when it needed '${r}'`)}return i}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new ee.FieldName((0,kn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new ee.ModelEntryReference((0,kn.getId)(e)),e.id())}defaultResult(){return new ee.Unimplemented}astAt(e,n){return e.location={url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(n)},e}getSourceCode(e){const n=e.start.startIndex,r=e.stop||e.start,i=new xDe.Interval(n,r.stopIndex);return this.parseInfo.sourceStream.getText(i)}getFilterElement(e){const n=this.getFieldExpr(e),r=new ee.FilterElement(n,this.getSourceCode(e));return this.astAt(r,e)}getFieldDefs(e,n){return e.map(r=>this.getFieldDef(r,n))}getFieldExpr(e){const n=this.visit(e);if(n instanceof ee.ExpressionDef)return this.astAt(n,e);throw this.internalError(e,`expression node unknown type '${n.elementType}'`)}getFilterShortcut(e){const n=this.getFilterElement(e.fieldExpr());return this.m4advisory(e,"Filter shortcut `{? condition }` is deprecated; use `{ where: condition } instead"),new ee.Filter([n])}getPlainString(e){const n=(0,kn.getStringIfShort)(e);if(n)return n;const r=[],i=e.string().sqlString();if(i){for(const s of(0,kn.getStringParts)(i))s instanceof gW.ParserRuleContext?this.contextError(s,"%{ query } illegal in this string"):r.push(s);return(0,kn.unIndent)(r),r.join("")}return""}makeSqlString(e,n){for(const r of e.sqlInterpolation())r.CLOSE_CODE()&&this.m4advisory(r,"Use %{ ... } instead of %{ ... }%");for(const r of(0,kn.getStringParts)(e))r instanceof gW.ParserRuleContext?n.push(this.visit(r)):n.push(r);n.complete(),this.astAt(n,e)}parseTime(e,n){let r=n(e.text);return r||(this.contextError(e,"Time data parse error"),r=new ee.LiteralTimestamp({text:e.text})),this.astAt(r,e)}getNotes(e){return e.ANNOTATION().map(n=>({text:n.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const n=this.only(e.malloyStatement().map(r=>this.visit(r)),r=>ee.isDocStatementOrDocStatementList(r)&&r,"statement");return new ee.Document(n)}visitDefineSourceStatement(e){const r=e.sourcePropertyList().sourceDefinition().map(o=>this.visitSourceDefinition(o)),i=this.getNotes(e.tags()),s=new ee.DefineSourceList(r);return s.extendNote({blockNotes:i}),s}getSourceParameter(e){const n=e.fieldExpr(),r=n?this.astAt(new pDe.ConstantExpression(this.getFieldExpr(n)),n):void 0,i=e.malloyType(),s=i?this.getMalloyType(i):void 0;return this.astAt(new ee.HasParameter({name:(0,kn.getId)(e.parameterNameDef()),type:s,default:r}),e)}getSourceParameters(e){return e===void 0?[]:(this.inExperiment("parameters",e),e.sourceParameter().map(n=>this.getSourceParameter(n)))}visitSourceDefinition(e){const n=this.visit(e.sqExplore()),r=this.getSourceParameters(e.sourceParameters()),i=new ee.DefineSource((0,kn.getId)(e.sourceNameDef()),n instanceof ee.SourceQueryElement?n:void 0,!0,r),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const n=e.filterShortcut(),r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>ee.isSourceProperty(s)&&s,"source property"),i=new ee.SourceDesc(r);return n&&i.push(this.getFilterShortcut(n)),i}visitTableFunction(e){const n=this.getPlainString(e.tableURI()),r=this.astAt(new ee.TableFunctionSource(n),e);return this.m4advisory(e,"`table('connection_name:table_path')` is deprecated; use `connection_name.table('table_path')`"),r}visitTableMethod(e){const n=e.connectionId(),r=this.astAt(this.getModelEntryName(n),n),i=this.getPlainString(e.tablePath());return this.astAt(new ee.TableMethodSource(r,i),e)}visitSqlSource(e){const n=e.connectionId(),r=this.astAt(this.getModelEntryName(n),n),i=new ee.SQLString,s=e.sqlString();s&&this.makeSqlString(s,i);const o=e.shortString();o&&i.push((0,kn.getShortString)(o));const u=new ee.SQLSource(r,i);return this.astAt(u,e)}visitDefJoinMany(e){const n=[];for(const i of e.joinList().joinDef()){const s=this.visit(i);s instanceof ee.Join&&(n.push(s),s instanceof ee.ExpressionJoin?(s.joinType="many",s.joinOn===void 0&&this.contextError(e,"join_many: requires ON expression")):s instanceof ee.KeyJoin&&this.contextError(e,"Foreign key join not legal in join_many:"))}const r=new ee.Joins(n);return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitDefJoinOne(e){const n=this.getJoinList(e.joinList()),r=[];for(const s of n)s instanceof ee.Join&&(r.push(s),s instanceof ee.ExpressionJoin&&(s.joinType="one"));const i=new ee.Joins(r);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}visitDefJoinCross(e){const n=this.getJoinList(e.joinList()),r=[];for(const s of n)s instanceof ee.Join&&(r.push(s),s instanceof ee.ExpressionJoin?s.joinType="cross":s.log("Foreign key join not legal in join_cross:"));const i=new ee.Joins(r);return i.extendNote({blockNotes:this.getNotes(e.tags())}),i}getJoinList(e){return e.joinDef().map(n=>this.visit(n))}getJoinSource(e,n){if(n){const r=this.getSqExpr(n.sqExpr()),i=this.getNotes(n._before_is).concat(this.getNotes(n._after_is));return{joinFrom:r,notes:i}}return{joinFrom:new ee.SQReference(e),notes:[]}}visitQueryJoinStatement(e){const n=this.astAt(this.visit(e.joinStatement()),e);return this.m4advisory(e,"Joins in queries are deprecated, move into an `extend:` block."),n}visitJoinOn(e){var n;const r=this.getModelEntryName(e.joinNameDef()),{joinFrom:i,notes:s}=this.getJoinSource(r,e.isExplore()),o=new ee.ExpressionJoin(r,i),u=e.joinExpression(),a=((n=e.matrixOperation())===null||n===void 0?void 0:n.text.toLocaleLowerCase())||"left";return(0,GL.isMatrixOperation)(a)?o.matrixOperation=a:this.contextError(e,"Internal Error: Unknown matrixOperation"),u&&(o.joinOn=this.getFieldExpr(u)),o.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(o,e)}visitJoinWith(e){const n=this.getModelEntryName(e.joinNameDef()),{joinFrom:r,notes:i}=this.getJoinSource(n,e.isExplore()),s=this.getFieldExpr(e.fieldExpr()),o=new ee.KeyJoin(n,r,s);return o.extendNote({notes:this.getNotes(e).concat(i)}),this.astAt(o,e)}getFieldDef(e,n){const r=e.fieldExpr(),i=(0,kn.getId)(e.fieldNameDef()),s=this.getFieldExpr(r),o=new n(s,i,this.getSourceCode(r)),u=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return o.extendNote({notes:u}),this.astAt(o,e)}visitDefDimensions(e){const n=this.getFieldDefs(e.defList().fieldDef(),ee.DimensionFieldDeclaration),r=new ee.Dimensions(n);return r.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(r,e)}visitDefMeasures(e){const n=this.getFieldDefs(e.defList().fieldDef(),ee.MeasureFieldDeclaration),r=new ee.Measures(n);return r.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(r,e)}visitQueryExtend(e){const n=[],r=e.queryExtendStatementList().queryExtendStatement().map(s=>this.visit(s));for(const s of r)if(ee.isQueryExtendProperty(s))n.push(s);else throw this.internalError(e,`Query extend matched, but ${s.elementType} found`);const i=new ee.ExtendBlock(n);return this.astAt(i,e)}visitDeclareStatement(e){const n=this.getFieldDefs(e.defList().fieldDef(),ee.DeclareFieldDeclaration),r=new ee.DeclareFields(n),i=this.astAt(r,e);return this.m4advisory(e,"`declare:` is deprecated; use `dimension:` or `measure:` inside a source or `extend:` block"),i}visitExploreRenameDef(e){const n=e.fieldName(0),r=e.fieldName(1),i=new ee.RenameField((0,kn.getId)(n),this.getFieldName(r));return this.astAt(i,e)}visitDefExploreRename(e){const r=e.renameList().exploreRenameDef().map(s=>this.visitExploreRenameDef(s)),i=new ee.Renames(r);return this.astAt(i,e)}visitFilterClauseList(e){return new ee.Filter(e.fieldExpr().map(n=>this.getFilterElement(n)))}visitWhereStatement(e){const n=this.visitFilterClauseList(e.filterClauseList());return n.having=!1,this.astAt(n,e)}visitHavingStatement(e){const n=this.visitFilterClauseList(e.filterClauseList());return n.having=!0,this.astAt(n,e)}visitSubQueryDefList(e){const n=e.exploreQueryDef().map(r=>this.visitExploreQueryDef(r));return new ee.Views(n)}visitDefExploreQuery(e){const n=this.visitSubQueryDefList(e.subQueryDefList()),r=this.getNotes(e.tags());return n.extendNote({blockNotes:r}),e.QUERY()&&this.m4advisory(e,"Use view: inside of a source instead of query:"),n}visitDefExplorePrimaryKey(e){const n=new ee.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(n,e)}visitFieldNameList(e){const n=e.fieldName().map(r=>new ee.AcceptExceptFieldReference([this.getFieldName(r)]));return new ee.FieldReferences(n)}visitDefExploreEditField(e){const n=e.ACCEPT()?"accept":"except";return new ee.FieldListEdit(n,this.visitFieldNameList(e.fieldNameList()))}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const n=this.getPlainString(e),r=this.astAt(new ee.TimezoneStatement(n),e.string());return r.isValid||this.astError(r,`Invalid timezone: ${r.tz}`),this.astAt(r,e)}visitQueryProperties(e){const n=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>ee.isQueryProperty(i)&&i,"query statement"),r=e.filterShortcut();return r&&n.push(this.getFilterShortcut(r)),new ee.QOpDesc(n)}getFieldPath(e,n){const r=e.fieldName().map(i=>this.getFieldName(i));return this.astAt(new n(r),e)}getQueryFieldDef(e,n){const r=this.getFieldDef(e,n);return this.astAt(r,e)}getQueryFieldEntry(e,n,r){const i=e.taggedRef();if(i)return this.getTaggedRef(i,n,r);const s=e.fieldDef();if(s)return this.getQueryFieldDef(s,n);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,n,r){return this.only(e.queryFieldEntry().map(i=>this.getQueryFieldEntry(i,n,r)),i=>i instanceof ee.FieldReference||i instanceof ee.AtomicFieldDeclaration?i:!1,"view field")}visitAggregateStatement(e){const n=new ee.Aggregate(this.getQueryItems(e.queryFieldList(),ee.AggregateFieldDeclaration,ee.AggregateFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitGroupByStatement(e){const n=new ee.GroupBy(this.getQueryItems(e.queryFieldList(),ee.GroupByFieldDeclaration,ee.GroupByFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitCalculateStatement(e){const n=new ee.Calculate(this.getQueryItems(e.queryFieldList(),ee.CalculateFieldDeclaration,ee.CalculateFieldReference));return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}getTaggedRef(e,n,r){const i=e.refExpr();if(i){const o=this.getFieldPath(e.fieldPath(),ee.ExpressionFieldReference);let u;const a=i.timeframe();a&&(u=new ee.ExprGranularTime(new ee.ExprIdReference(o),this.visitTimeframe(a).text,!0));const l=i.aggregate();if(l){const f=l.text.toLowerCase();if(f==="sum")u=new ee.ExprSum(void 0,o);else return this.contextError(l,`\`${f}\` is not legal in a reference-only aggregation`),o}const c=new n(u,o.outputName);return c.extendNote({notes:this.getNotes(e.tags())}),c}const s=this.getFieldPath(e.fieldPath(),r);return s.extendNote({notes:this.getNotes(e.tags())}),s}getFieldCollectionMember(e,n,r){const i=e.fieldDef();if(i)return this.getFieldDef(i,n);const s=e.taggedRef();if(s)return this.getTaggedRef(s,n,r);const o=e.collectionWildCard();if(o)return this.visitCollectionWildCard(o);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const n=e.collectionMember().map(r=>this.getFieldCollectionMember(r,ee.ProjectFieldDeclaration,ee.ProjectFieldReference));return this.astAt(new ee.ProjectStatement(n),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project: keyword is deprecated, use select:");const n=this.visitFieldCollection(e.fieldCollection());return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitCollectionWildCard(e){var n;const r=e.fieldPath(),i=r?this.getFieldPath(r,ee.ProjectFieldReference):void 0,s=this.astAt(new ee.WildcardFieldReference(i),e),o=((n=e.starQualified())===null||n===void 0?void 0:n.fieldNameList())||[];for(const u of o)for(const a of u.fieldName())s.except.add((0,kn.getId)(a));return s}visitIndexFields(e){const n=e.indexElement().map(r=>{const i=r.fieldPath();if(!i)return this.astAt(new ee.WildcardFieldReference(void 0),e);const s=this.getFieldPath(i,ee.IndexFieldReference);return r.STAR()?this.astAt(new ee.WildcardFieldReference(s),e):this.astAt(s,e)});return new ee.FieldReferences(n)}visitIndexStatement(e){const n=this.visitIndexFields(e.indexFields()),r=new ee.Index(n),i=e.fieldName();return i&&r.useWeight(this.getFieldName(i)),this.astAt(r,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new ee.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const n=e.ASC()?"asc":e.DESC()?"desc":void 0,r=e.fieldExpr(),i=r?this.getFieldExpr(r):void 0;return this.astAt(new ee.FunctionOrderBy(i,n),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const n=e.aggregateOrderBySpec().map(r=>this.visitAggregateOrderBySpec(r));return this.astAt(new ee.FunctionOrdering(n),e)}visitOrderBySpec(e){const n=e.ASC()?"asc":e.DESC()?"desc":void 0,r=e.INTEGER_LITERAL();if(r)return new ee.OrderBy(this.getNumber(r),n);const i=e.fieldName();if(i)return new ee.OrderBy(this.getFieldName(i),n);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const n=e.orderBySpec().map(r=>this.visitOrderBySpec(r));return this.astAt(new ee.Ordering(n),e)}visitTopStatement(e){const n=e.bySpec(),r=this.getNumber(e.INTEGER_LITERAL());let i;if(n){this.m4advisory(n,"by clause of top statement unupported. Use order_by instead");const s=n.fieldName();if(s){const u=this.getFieldName(s);i=new ee.Top(r,u)}const o=n.fieldExpr();o&&(i=new ee.Top(r,this.getFieldExpr(o)))}return i||(i=new ee.Top(r,void 0)),this.astAt(i,e)}visitTopLevelQueryDefs(e){const n=e.topLevelQueryDef().map(s=>this.visitTopLevelQueryDef(s)),r=this.getNotes(e.tags()),i=new ee.DefineQueryList(n);return i.extendNote({blockNotes:r}),i}visitTopLevelQueryDef(e){const n=(0,kn.getId)(e.queryName()),r=this.visit(e.sqExpr()),i=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(r instanceof ee.SourceQueryElement){const s=new ee.DefineQuery(n,r);return s.extendNote({notes:i}),this.astAt(s,e)}throw this.internalError(e,`Expected query definition, got a '${r.elementType}'`)}visitAnonymousQuery(e){const n=e.topLevelAnonQueryDef(),r=this.getSqExpr(n.sqExpr()),i=this.astAt(new ee.AnonymousQuery(r),n),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.m4advisory(n,"Anonymous `query:` statements are deprecated, use `run:` instead"),this.astAt(i,e)}visitRunStatement(e){const n=e.topLevelAnonQueryDef(),r=this.getSqExpr(n.sqExpr()),i=this.astAt(new ee.AnonymousQuery(r),n),s=this.getNotes(e.topLevelAnonQueryDef().tags()),o=this.getNotes(e.tags());return i.extendNote({notes:s,blockNotes:o}),this.astAt(i,e)}visitNestStatement(e){const n=this.visitNestedQueryList(e.nestedQueryList());return n.extendNote({blockNotes:this.getNotes(e.tags())}),n}visitNestedQueryList(e){return new ee.Nests(this.only(e.nestEntry().map(n=>this.visit(n)),n=>n instanceof ee.NestFieldDeclaration&&n,"query"))}visitNestDef(e){const n=e.queryName();let r;const i=this.getVExpr(e.vExpr());if(n)r=(0,kn.getId)(n);else{const u=i.getImplicitName();u===void 0&&this.contextError(e,"`nest:` view requires a name (add `nest_name is ...`)"),r=u??"__unnamed__"}const s=new ee.NestFieldDeclaration(r,i),o=e.isDefine();return s.extendNote({notes:this.getNotes(e.tags()).concat(o?this.getIsNotes(o):[])}),this.astAt(s,e)}visitExploreQueryDef(e){const n=(0,kn.getId)(e.exploreQueryNameDef()),r=new ee.ViewFieldDeclaration(n,this.getVExpr(e.vExpr())),i=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return r.extendNote({notes:i}),this.astAt(r,e)}visitExprNot(e){return new ee.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new ee.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(n=>this.getFieldExpr(n))}visitExprLogicalOr(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1));return new ee.ExprLogicalOp(n,"or",r)}visitExprLogicalAnd(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1));return new ee.ExprLogicalOp(n,"and",r)}visitExprOrTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ee.ExprAlternationTree(n,"|",r),e)}visitExprAndTree(e){const n=this.getFieldExpr(e.fieldExpr()),r=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ee.ExprAlternationTree(n,"&",r),e)}visitExprCoalesce(e){const n=this.getFieldExpr(e.fieldExpr()[0]),r=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new ee.ExprCoalesce(n,r),e)}visitPartialAllowedFieldExpr(e){var n;const r=this.getFieldExpr(e.fieldExpr()),i=(n=e.compareOp())===null||n===void 0?void 0:n.text;if(i){if(ee.isComparison(i))return this.astAt(new ee.PartialCompare(i,r),e);throw this.internalError(e,`partial comparison '${i}' not recognized`)}return r}visitExprString(e){const n=this.getPlainString(e);return new ee.ExprString(n)}visitExprRegex(e){const n=e.HACKY_REGEX().text;return new ee.ExprRegEx(n.slice(2,-1))}visitExprNow(e){return new ee.ExprNow}visitExprNumber(e){return new ee.ExprNumber(e.text)}visitExprFieldPath(e){const n=new ee.ExprIdReference(this.getFieldPath(e.fieldPath(),ee.ExpressionFieldReference));return this.astAt(n,e)}visitExprNULL(e){return new ee.ExprNULL}visitExprExpr(e){return new ee.ExprParens(this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprMinus(e){return new ee.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){const n=this.getFieldExpr(e.fieldExpr(0)),r=this.getFieldExpr(e.fieldExpr(1)),i=e.PLUS()?"+":"-";return new ee.ExprAddSub(n,i,r)}visitExprMulDiv(e){const n=e.STAR()?"*":e.SLASH()?"/":"%";return new ee.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),n,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){const n=e.compareOp().text;if(ee.isComparison(n))return new ee.ExprCompare(this.getFieldExpr(e.fieldExpr(0)),n,this.getFieldExpr(e.fieldExpr(1)));throw this.internalError(e,`untranslatable comparison operator '${n}'`)}visitExprCountDisinct(e){return this.m4advisory(e,"`count(distinct expression)` deprecated, use `count(expression)` instead"),this.astAt(new ee.ExprCountDistinct(this.getFieldExpr(e.fieldExpr())),e)}visitExprUngroup(e){const n=e.fieldName().map(i=>this.getFieldName(i)),r=e.ungroup().text.toLowerCase();return this.astAt(new ee.ExprUngroup(r==="all"?r:"exclude",this.getFieldExpr(e.fieldExpr()),n),e)}symmetricAggregateUsageError(e){return`Symmetric aggregate function \`${e}\` must be written as \`${e}(expression)\` or \`path.to.field.${e}()\``}asymmetricAggregateUsageError(e){return`Asymmetric aggregate function \`${e}\` must be written as \`path.to.field.${e}()\`, \`path.to.join.${e}(expression)\`, or \`${e}(expression)\``}visitExprAggregate(e){const n=e.fieldPath(),r=this.getFieldPath(n,ee.ExpressionFieldReference),i=n&&r?this.astAt(r,n):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 ee.ExprCount(i);const u=o?this.getFieldExpr(o):void 0;if(s==="min"||s==="max")if(u)this.contextError(e,this.symmetricAggregateUsageError(s));else{const a=this.astAt(new ee.ExprIdReference(r),n);return s==="min"?new ee.ExprMin(a):new ee.ExprMax(a)}else{if(s==="avg")return new ee.ExprAvg(u,i);if(s==="sum")return new ee.ExprSum(u,i);this.contextError(e,`Cannot parse aggregate function ${s}`)}return new ee.ExprNULL}visitExprPathlessAggregate(e){const n=e.fieldExpr(),r=n?this.getFieldExpr(n):void 0,i=void 0,s=e.aggregate().text.toLowerCase();if(e.STAR()&&this.m4advisory(e,`* illegal inside ${s}()`),s==="count")return this.astAt(r?new ee.ExprCountDistinct(r):new ee.ExprCount,e);if(s==="min"){if(r)return new ee.ExprMin(r);this.contextError(e,this.symmetricAggregateUsageError(s))}else if(s==="max"){if(r)return new ee.ExprMax(r);this.contextError(e,this.symmetricAggregateUsageError(s))}else{if(r===void 0)return this.contextError(e,this.asymmetricAggregateUsageError(s)),new ee.ExprNULL;const o=e.SOURCE_KW()!==void 0;if(s==="avg")return new ee.ExprAvg(r,i,o);if(s==="sum")return new ee.ExprSum(r,i,o)}return new ee.ExprNULL}visitExprApply(e){return new ee.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new ee.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const n=this.getMalloyOrSQLType(e.malloyOrSQLType());return new ee.ExprCast(this.getFieldExpr(e.fieldExpr()),n)}getMalloyType(e){const n=e.text;if((0,GL.isCastType)(n))return n;throw this.internalError(e,`unknown type '${n}'`)}getMalloyOrSQLType(e){const n=e.malloyType();if(n)return this.getMalloyType(n);const r=e.string();if(r)return{raw:this.getPlainString({string:()=>r})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){const n=this.getMalloyOrSQLType(e.malloyOrSQLType());return new ee.ExprCast(this.getFieldExpr(e.fieldExpr()),n,!0)}visitExprTimeTrunc(e){return new ee.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new ee.Timeframe(e.text)}visitExprForRange(e){const n=this.getFieldExpr(e._startAt),r=this.getFieldExpr(e._duration),i=this.visitTimeframe(e.timeframe());return new ee.ForRange(n,r,i)}visitExprAggFunc(e){const n=e.argumentList(),r=n?this.allFieldExpressions(n.fieldExpr()):[],i=(0,kn.getId)(e),s=e.fieldPath(),o=s?this.getFieldPath(s,ee.ExpressionFieldReference):void 0,u=s&&o?this.astAt(o,s):void 0;return ee.ExprTimeExtract.extractor(i)?this.astAt(new ee.ExprTimeExtract(i,r),e):this.astAt(new ee.ExprFunc(i,r,!1,void 0,u),e)}visitExprFunc(e){var n,r;const i=e.argumentList(),s=i?this.allFieldExpressions(i.fieldExpr()):[],o=e.EXCLAM()!==void 0,u=(n=e.malloyType())===null||n===void 0?void 0:n.text;let a;u&&((0,GL.isCastType)(u)?a=u:(this.contextError(e,`'#' assertion for unknown type '${u}'`),a=void 0));let l=(0,kn.getOptionalId)(e)||((r=e.timeframe())===null||r===void 0?void 0:r.text);return l===void 0&&(this.contextError(e,"Function name error"),l="FUNCTION_NAME_ERROR"),ee.ExprTimeExtract.extractor(l)?this.astAt(new ee.ExprTimeExtract(l,s),e):this.astAt(new ee.ExprFunc(l,s,o,a),e)}visitExprDuration(e){return new ee.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitPickStatement(e){const n=e.pick().map(r=>{let i;return r._pickValue&&(i=this.getFieldExpr(r._pickValue)),new ee.PickWhen(i,this.getFieldExpr(r._pickWhen))});return e.ELSE()?new ee.Pick(n,this.getFieldExpr(e._pickElse)):new ee.Pick(n)}visitExprFieldProps(e){const n=this.only(e.fieldProperties().fieldPropertyStatement().map(r=>this.visit(r)),r=>ee.isFieldPropStatement(r)&&r,"field property statement");return new ee.ExprProps(this.getFieldExpr(e.fieldExpr()),n)}visitPartitionByStatement(e){return this.astAt(new ee.PartitionBy(e.id().map(n=>this.astAt(new ee.PartitionByFieldReference([this.astAt(new ee.FieldName((0,kn.idToStr)(n)),n)]),n))),e)}visitLiteralTimestamp(e){return this.parseTime(e,ee.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,ee.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,ee.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,ee.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,ee.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,ee.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,ee.LiteralYear.parse)}visitImportStatement(e){const n=this.getPlainString(e.importURL()),r=this.astAt(new ee.ImportStatement(n,this.parseInfo.importBaseURL),e),i=e.importSelect();if(i)for(const s of i.importItem()){const o=s.id(),u=o[1]?this.astAt(new ee.ImportSourceName((0,kn.idToStr)(o[1])),o[1]):void 0;r.push(this.astAt(new ee.ImportSelect((0,kn.idToStr)(o[0]),u),o[0]))}return r}visitJustExpr(e){return this.getFieldExpr(e.fieldExpr())}visitSampleStatement(e){const n=e.sampleSpec().INTEGER_LITERAL();if(n)return new ee.SampleProperty({rows:this.getNumber(n)});const r=e.sampleSpec().PERCENT_LITERAL();if(r)return new ee.SampleProperty({percent:this.getNumber(r)});const i=e.sampleSpec().TRUE()!==void 0;return new ee.SampleProperty({enable:i})}visitDocAnnotations(e){const n=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)})),r=new ee.ModelAnnotation(n);return this.compilerFlags=r.getCompilerFlags(this.compilerFlags,this.msgLog),r}visitIgnoredObjectAnnotations(e){return this.contextError(e,"Object annotation not connected to any object"),new WL(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"Model annotations not allowed at this scope"),new WL(e.text)}visitDefExploreAnnotation(e){const n=this.getNotes(e);return new ee.ObjectAnnotation(n)}getSQArgument(e){const n=e.argumentId(),r=n?this.astAt(new ee.PartitionByFieldReference([this.astAt(new ee.FieldName((0,kn.idToStr)(n.id())),n)]),n):void 0;return this.astAt(new ee.Argument({id:r,value:this.getFieldExpr(e.fieldExpr())}),e)}getSQArguments(e){if(e!==void 0)return this.inExperiment("parameters",e),e.sourceArgument().map(n=>this.getSQArgument(n))}visitSQID(e){const n=this.getModelEntryName(e),r=this.getSQArguments(e.sourceArguments());return this.astAt(new ee.SQReference(n,r),e.id())}getSqExpr(e){const n=this.visit(e);return n instanceof ee.SourceQueryElement?n:(this.contextError(e,`Expected a source/query expression, not '${n.elementType}'`),new mW)}visitSQExtendedSource(e){const n=this.getSqExpr(e.sqExpr()),r=new ee.SQExtend(n,this.getSourceExtensions(e.exploreProperties()));return this.astAt(r,e)}visitSQParens(e){const n=this.getSqExpr(e.sqExpr());return this.astAt(n,e)}visitSQArrow(e){const n=this.getSqExpr(e.sqExpr()),r=e.segExpr(),i=new ee.SQArrow(n,this.getVExpr(r));return this.astAt(i,e)}getVExpr(e){const n=this.visit(e);if(n instanceof ee.View)return n;throw this.internalError(e,`Expected view, got a '${n.elementType}'`)}visitSegField(e){return new ee.ReferenceView(this.getFieldPath(e.fieldPath(),ee.ViewOrScalarFieldReference))}visitSegOps(e){return new ee.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new ee.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new ee.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const n=this.getSqExpr(e.sqExpr()),r=e.segExpr(),i=new ee.SQRefine(n,this.getVExpr(r));return this.astAt(i,e)}visitSQTable(e){const n=this.visit(e.exploreTable());if(n instanceof dDe.TableSource){const r=new ee.SQSource(n);return this.astAt(r,e)}return new mW}visitSQSQL(e){const n=new ee.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(n,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new ee.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}}vb.MalloyToAST=mDe;var _b={};Object.defineProperty(_b,"__esModule",{value:!0}),_b.MessageLog=void 0;class yDe{constructor(){this.rawLog=[]}getLog(){return this.rawLog}log(e){const n=e.message;if(n.endsWith("]")){const r=n.lastIndexOf("[");r>0&&(e.message=n.slice(0,r),e.errorTag=n.slice(r+1,-1))}this.rawLog.push(e)}reset(){this.rawLog.length=0}noErrors(){return!this.hasErrors()}hasErrors(){return this.rawLog.find(n=>n.severity!=="warn")!==void 0}empty(){return this.rawLog.length===0}}_b.MessageLog=yDe;var Cb={};Object.defineProperty(Cb,"__esModule",{value:!0}),Cb.Zone=void 0;class EDe{constructor(){this.location={},this.zone=new Map}get(e){const n=this.zone.get(e);if((n==null?void 0:n.status)==="present")return n.value}getEntry(e){const n=this.zone.get(e);return n?n.firstReference||!this.location[e]?n:{...n,firstReference:this.location[e]}:{status:"error",message:"import reference failure"}}define(e,n){this.zone.set(e,{status:"present",value:n})}reference(e,n){const r=this.zone.get(e);(r==null?void 0:r.status)===void 0&&(this.zone.set(e,{status:"reference",firstReference:n}),this.location[e]=n)}getUndefined(){const e=[];for(const[n,r]of this.zone)r.status==="reference"&&e.push(n);return e.length>0?e:void 0}updateFrom(e,n){if(e)for(const[r,i]of Object.entries(e))i!==void 0&&this.define(r,i);if(n)for(const[r,i]of Object.entries(n))this.zone.set(r,{status:"error",message:i})}}Cb.Zone=EDe;var bb={};Object.defineProperty(bb,"__esModule",{value:!0}),bb.walkForDocumentSymbols=void 0;const ADe=ox,SDe=Bn;class vDe{constructor(e,n,r,i){this.translator=e,this.tokens=n,this.scopes=r,this.symbols=i}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){const n=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=n)}enterTopLevelQueryDef(e){this.symbols.push({range:this.translator.rangeFromContext(e),name:e.queryName().text,type:"query",children:[],lensRange:this.blockRange}),this.blockRange=void 0}enterRunStatement(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterAnonymousQuery(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef().sqExpr()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterDefineSourceStatement(e){const n=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=n)}enterSourceDefinition(e){const n=this.translator.rangeFromContext(e);this.scopes.push({range:n,name:e.sourceNameDef().id().text,type:"explore",children:[],lensRange:this.blockRange}),this.blockRange=void 0}exitSourceDefinition(e){const n=this.popScope();n&&this.symbols.push(n)}enterDefExploreQuery(e){const n=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=n)}enterExploreQueryDef(e){const n={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},r=this.peekScope();r&&r.children.push(n),this.scopes.push(n),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}getNestDefName(e){const n=e.queryName();if(n)return n.id().text;let r,i=!1;const s={enterVArrow(u){u.vExpr().enterRule(s)},enterVSeg(u){u.segExpr().enterRule(o)}},o={enterSegField(u){const a=u.fieldPath().fieldName();i||(r??(r=a[a.length-1].id().text))},enterSegParen(u){u.vExpr().enterRule(s)},enterSegRefine(u){u._lhs.enterRule(o)},enterSegOps(){r=void 0,i=!0}};return e.vExpr().enterRule(s),r}handleNestEntry(e){const n=this.getNestDefName(e);if(n===void 0)return;const r={range:this.translator.rangeFromContext(e),name:n,type:"query",children:[]},i=this.peekScope();return i&&i.children.push(r),r}enterNestDef(e){const n=this.handleNestEntry(e);n&&this.scopes.push(n)}exitNestDef(e){this.popScope()}enterFieldDef(e){const n={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},r=this.peekScope();r&&r.children.push(n)}enterQueryFieldEntry(e){var n;const r=(n=e.taggedRef())===null||n===void 0?void 0:n.fieldPath();if(r===void 0)return;const i={range:this.translator.rangeFromContext(e),name:r.text,type:"field",children:[]},s=this.peekScope();s&&s.children.push(i)}enterExploreRenameDef(e){const n={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},r=this.peekScope();r&&r.children.push(n)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){const n={range:this.translator.rangeFromContext(e),name:e.joinNameDef().id().text,type:"join",children:[]},r=this.peekScope();r&&r.children.push(n)}enterImportStatement(e){const n=(0,SDe.getStringIfShort)(e.importURL());n&&this.scopes.push({range:this.translator.rangeFromContext(e),name:n,type:"import",children:[]})}exitImportStatement(){const e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){const n=this.peekScope();if(n)for(const r of e.importItem()){const i={range:this.translator.rangeFromContext(e),name:r.text,type:"import_item",children:[]};n.children.push(i)}}}function _De(t,e,n){const r=new vDe(t,e,[],[]),i=r;return ADe.ParseTreeWalker.DEFAULT.walk(i,n),r.symbols}bb.walkForDocumentSymbols=_De;var Tb={};Object.defineProperty(Tb,"__esModule",{value:!0}),Tb.walkForDocumentCompletions=void 0;const CDe=ox,bDe=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],TDe=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],RDe=["source","explore","query","sql"];class ODe{constructor(e,n,r){this.tokens=e,this.completions=n,this.position=r}rangeOf(e){const n=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:n.line-1,character:n.stopIndex-(n.startIndex-n.charPositionInLine)+1}}}inRange(e){const{start:n,end:r}=e,i=this.position.line>n.line||this.position.line===n.line&&this.position.character>=n.character,s=this.position.line<r.line||this.position.line===r.line&&this.position.character<=r.character;return i&&s}enterExploreProperties(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.exploreStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of bDe)this.completions.push({type:"explore_property",text:`${r}: `})}}enterQueryProperties(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.queryStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of TDe)this.completions.push({type:"query_property",text:`${r}: `})}}enterMalloyDocument(e){if(this.inRange(this.rangeOf(e))){let n=!1;for(const r of e.malloyStatement())this.inRange(this.rangeOf(r))&&(n=!0);if(!n)for(const r of RDe)this.completions.push({type:"model_property",text:`${r}: `})}}}function NDe(t,e,n){const r=new ODe(t,[],n),i=r;return CDe.ParseTreeWalker.DEFAULT.walk(i,e),r.completions}Tb.walkForDocumentCompletions=NDe;var Rb={};Object.defineProperty(Rb,"__esModule",{value:!0}),Rb.walkForDocumentHelpContext=void 0;const DDe=b4;class FDe extends DDe.AbstractParseTreeVisitor{constructor(e){super(),this.position=e,this.type=""}rangeOf(e){const n=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:n.line-1,character:n.stopIndex-(n.startIndex-n.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 n=this.defaultResult();if(this.inRange(this.rangeOf(e))){n={type:this.type,token:e.start.text};const r=e.childCount;for(let i=0;i<r;i++){const o=e.getChild(i).accept(this);o&&(n=this.aggregateResult(n,o))}}return n}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,n){return n}}function wDe(t,e){return new FDe(e).visit(t)}Rb.walkForDocumentHelpContext=wDe;var Ob={},uy={};Object.defineProperty(uy,"__esModule",{value:!0}),uy.locationContainsPosition=void 0;function LDe(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)}uy.locationContainsPosition=LDe,Object.defineProperty(Ob,"__esModule",{value:!0}),Ob.ReferenceList=void 0;const IDe=uy;class $De{constructor(e){this.sourceURL=e,this.references=[]}findIndexBefore(e){let n=0,r=this.references.length;for(;n<r;){const i=Math.floor((n+r)/2),s=this.references[i].location.range.end;s.line<e.line||s.line===e.line&&s.character<e.character?n=i+1:r=i}return n}add(e){if(e.location.url!==this.sourceURL)return;const n=this.findIndexBefore(e.location.range.end);n<this.references.length&&this.isPositionEqual(e,this.references[n])||this.references.splice(n,0,e)}isPositionEqual(e,n){const r=e.location.range,i=n.location.range;return r.start.line===i.start.line&&r.start.character===i.start.character&&r.end.line===i.end.line&&r.end.character===i.end.character}find(e){const n=this.findIndexBefore(e);if(n===this.references.length)return;const r=this.references[n];if((0,IDe.locationContainsPosition)(r.location,e))return r}}Ob.ReferenceList=$De;var Nb={};Object.defineProperty(Nb,"__esModule",{value:!0}),Nb.isNeedResponse=void 0;function BDe(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}Nb.isNeedResponse=BDe;var Db={};Object.defineProperty(Db,"__esModule",{value:!0}),Db.walkForModelAnnotation=void 0;const kDe=ox;class PDe{constructor(e,n,r){this.translator=e,this.tokens=n,this.parseInfo=r,this.notes=[]}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.parseInfo.rangeFromContext(e)}}enterDocAnnotations(e){const n=e.DOC_ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}));this.notes.push(...n)}get annotation(){return{notes:this.notes}}}function MDe(t,e,n){const r=new PDe(t,e,n),i=r;return kDe.ParseTreeWalker.DEFAULT.walk(i,n.root),r.annotation}Db.walkForModelAnnotation=MDe;var jDe=F&&F.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),UDe=F&&F.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),qDe=F&&F.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&jDe(e,t,n);return UDe(e,t),e};Object.defineProperty(Nu,"__esModule",{value:!0}),Nu.MalloyParserErrorHandler=Nu.MalloyTranslator=Nu.MalloyChildTranslator=Nu.MalloyTranslation=void 0;const yW=IS,HDe=Wv,zDe=w,EW=qDe(w_),QDe=vb,GDe=_b,WDe=ml,VL=Cb,VDe=bb,YDe=Tb,KDe=Rb,XDe=Ob,Fb=Nb,JDe=uy,AW=fl,ZDe=Db;class eFe extends HDe.MalloyLexer{popMode(){return this._modeStack.isEmpty?this._mode:super.popMode()}}class tFe{step(e){if(this.response)return this.response;if(e.urlIsFullPath===void 0)try{const s=new URL(e.sourceURL);e.urlIsFullPath=!0}catch(s){const 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();const n=e.root.importZone.getEntry(e.sourceURL);if(n.status!=="present"){if(n.status==="error"){const s=n.message.includes(e.sourceURL)?`import error: ${n.message}`:`import '${e.sourceURL}' error: ${n.message}`,o=n.firstReference||e.defaultLocation();return e.root.logger.log({message:s,at:o,severity:"error"}),this.response=e.fatalResponse(),this.response}return{urls:[e.sourceURL]}}const r=n.value===""?`
|
|
1301
1301
|
`:n.value;this.sourceInfo=this.getSourceInfo(r);let i;try{i=this.runParser(r,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){const n=/\r?\n/,r={at:[],lines:[],length:e.length};let i=e,s=0;for(;i!=="";){const o=i.match(n);if(o&&o.index!==void 0){r.lines.push(i.slice(0,o.index));const u=o.index+o[0].length;r.at.push({begin:s,end:s+u}),s+=u,i=i.slice(u)}else{r.lines.push(i),r.at.push({begin:s,end:s+i.length});break}}return r}runParser(e,n){const r=yW.CharStreams.fromString(e),i=new eFe(r),s=new yW.CommonTokenStream(i),o=new zDe.MalloyParser(s);o.removeErrorListeners(),o.addErrorListener(new vW(n,n.root.logger));const u=o[n.grammarRule];if(!u)throw new Error(`No such parse rule as ${n.grammarRule}`);return{root:u.call(o),tokenStream:s,sourceStream:r,sourceURL:n.sourceURL,importBaseURL:n.importBaseURL||n.sourceURL,rangeFromContext:a=>n.rangeFromContext(a),malloyVersion:"4.0.0"}}}class nFe{constructor(e){this.parseStep=e,this.parseReferences=void 0}step(e){const n=this.parseStep.step(e);if(n.parse===void 0)return n;if(!this.parseReferences){this.parseReferences=(0,WDe.findReferences)(e,n.parse.tokenStream,n.parse.root);for(const o in this.parseReferences.tables)e.root.schemaZone.reference(o,{url:e.sourceURL,range:this.parseReferences.tables[o].firstReference});for(const o in this.parseReferences.urls){const u=this.parseReferences.urls[o];try{const a=decodeURI(new URL(o,e.importBaseURL||e.sourceURL).toString());e.addChild(a),e.imports.push({importURL:a,location:{url:e.sourceURL,range:u}}),e.root.importZone.reference(a,{url:e.sourceURL,range:u})}catch{e.root.logger.log({message:`Malformed URL '${o}'"`,at:{url:e.sourceURL,range:u},severity:"error"})}}}if(e.root.logger.hasErrors())return null;let r={};const i=e.root.schemaZone.getUndefined();if(i){const o={};for(const u of i){const a=this.parseReferences.tables[u];o[u]={connectionName:a.connectionName,tablePath:a.tablePath}}r={tables:o}}const s=e.root.importZone.getUndefined();if(s&&(r={...r,urls:s}),(0,Fb.isNeedResponse)(r))return r;for(const o of e.childTranslators.values()){const u=o.importsAndTablesStep.step(o);if((0,Fb.isNeedResponse)(u))return u}return null}}class rFe{constructor(e){this.importStep=e,this.walked=!1}step(e){if(this.response)return this.response;const n=this.importStep.step(e);if(n)return n;const r=e.parseStep.response;if(e.root.logger.hasErrors())return this.response=e.fatalResponse(),this.response;const i=r==null?void 0:r.parse;if(!i)throw new Error("TRANSLATOR INTERNAL ERROR: Translator parse response had no errors, but also no parser");const s=new QDe.MalloyToAST(i,e.root.logger,e.compilerFlags),o=s.visit(i.root);if(e.compilerFlags=s.compilerFlags,o.elementType==="unimplemented"&&o.log("INTERNAL COMPILER ERROR: Untranslated parse node"),!this.walked){for(const u of o.walk())u instanceof EW.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(const u of e.childTranslators.values()){const a=u.astStep.step(u);if((0,Fb.isNeedResponse)(a))return a}return o.setTranslator(e),this.response={...e.problemResponse(),ast:o,final:!0},this.response}}class iFe{constructor(e){this.parseStep=e}step(e){if(!this.response){const n=this.parseStep.step(e);if(n.parse){let r;try{r=(0,VDe.walkForDocumentSymbols)(e,n.parse.tokenStream,n.parse.root)}catch{}this.response={symbols:r,final:!0}}else return n}return this.response}}class sFe{constructor(e){this.parseStep=e}step(e,n){const r=this.parseStep.step(e);if(r.parse){let i=[];if(n!==void 0)try{i=(0,YDe.walkForDocumentCompletions)(r.parse.tokenStream,r.parse.root,n)}catch{}return{...r,completions:i}}else return r}}class oFe{constructor(e){this.parseStep=e}step(e,n){const r=this.parseStep.step(e);if(r.parse){let i;if(n!==void 0)try{i=(0,KDe.walkForDocumentHelpContext)(r.parse.root,n)}catch{}return{...r,helpContext:i}}else return r}}class uFe{constructor(e){this.parseStep=e}step(e,n){if(!this.response){const r=this.parseStep.step(e);if(!r.parse||r.final)return r;{const i=(0,ZDe.walkForModelAnnotation)(e,r.parse.tokenStream,r.parse);this.response={modelAnnotation:{...i,inherits:n==null?void 0:n.annotation}}}}return this.response}}class aFe{constructor(e){this.astStep=e,this.importedAnnotations=!1}step(e,n){if(this.response)return this.response;if(n&&!this.importedAnnotations){const i=AW.Tag.annotationToTag(n.annotation,{prefix:/^##! /});e.compilerFlags=i.tag,this.importedAnnotations=!0}const r=this.astStep.step(e);if((0,Fb.isNeedResponse)(r))return r;if(!r.ast)return this.response=r,this.response;if(e.grammarRule==="malloyDocument")if(r.ast instanceof EW.Document){const i=r.ast;for(i.initModelDef(n);;){const 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}}class YL{constructor(e,n=null,r="malloyDocument"){this.sourceURL=e,this.importBaseURL=n,this.grammarRule=r,this.queryList=[],this.sqlBlocks=[],this.imports=[],this.compilerFlags=new AW.Tag,this.dialectAlreadyChecked={},this.allDialectsEnabled=!1,this.childTranslators=new Map,this.modelDef={name:e,exports:[],contents:{}},this.parseStep=new tFe,this.modelAnnotationStep=new uFe(this.parseStep),this.metadataStep=new iFe(this.parseStep),this.completionsStep=new sFe(this.parseStep),this.helpContextStep=new oFe(this.parseStep),this.importsAndTablesStep=new nFe(this.parseStep),this.astStep=new rFe(this.importsAndTablesStep),this.translateStep=new aFe(this.astStep),this.references=new XDe.ReferenceList(e)}addChild(e){this.childTranslators.get(e)||this.childTranslators.set(e,new SW(e,this.root))}getDependencies(){const e=[this.sourceURL];for(const[n,r]of this.childTranslators)e.push(...r.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 n,r;if(e===this.sourceURL)return(n=this.parseStep.sourceInfo)===null||n===void 0?void 0:n.lines;const i=this.childTranslators.get(e);if(i)return(r=i.parseStep.sourceInfo)===null||r===void 0?void 0:r.lines}codeAtLocation(e){const n=this.getLineMap(e.url)||[];if(e.range.start.line===e.range.end.line)return n[e.range.start.line].slice(e.range.start.character,e.range.end.character);let r="";r+=n[e.range.start.line].slice(e.range.start.character);for(let i=e.range.start.line+1;i<e.range.end.line;i++)r+=n[i];return r+=n[e.range.end.line].slice(0,e.range.end.character),r}prettyErrors(){let e="",n="";for(const r of this.root.logger.getLog()){let i=r.message,s=this.sourceURL;if(r.at){s=r.at.url;const o=r.at.range.start.line,u=r.at.range.start.character,a=this.getLineMap(r.at.url);if(a){const l=a[o];i=`line ${o+1}: ${r.message}
|
|
1302
1302
|
| ${l}`,u>0&&(i=i+`
|