@malloydata/render 0.0.274 → 0.0.275

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.
@@ -150179,7 +150179,7 @@ Sp.malloyToQuery = Sdt;
150179
150179
  var we = {}, yD = {};
150180
150180
  Object.defineProperty(yD, "__esModule", { value: !0 });
150181
150181
  yD.MALLOY_VERSION = void 0;
150182
- yD.MALLOY_VERSION = "0.0.274";
150182
+ yD.MALLOY_VERSION = "0.0.275";
150183
150183
  Object.defineProperty(we, "__esModule", { value: !0 });
150184
150184
  we.InMemoryModelCache = we.CacheManager = we.CSVWriter = we.JSONWriter = we.DataWriter = we.DataRecord = we.DataArray = we.Result = we.ExploreMaterializer = we.PreparedResultMaterializer = we.QueryMaterializer = we.ModelMaterializer = we.SingleConnectionRuntime = we.ConnectionRuntime = we.Runtime = we.ExploreField = we.JoinRelationship = we.QueryField = we.Query = we.StringField = we.UnsupportedField = we.JSONField = we.BooleanField = we.NumberField = we.TimestampField = we.DateField = we.TimestampTimeframe = we.DateTimeframe = we.AtomicField = we.AtomicFieldType = we.Explore = we.SourceRelationship = we.FixedConnectionMap = we.InMemoryURLReader = we.EmptyURLReader = we.PreparedResult = we.DocumentCompletion = we.DocumentSymbol = we.DocumentPosition = we.DocumentRange = we.DocumentTablePath = we.Parse = we.PreparedQuery = we.Model = we.MalloyError = we.Malloy = void 0;
150185
150185
  const EY = CT, Kr = ji, AY = tE, RO = y2, bdt = yD, Tdt = E2, Ln = si, Rdt = $l, Ddt = Gn, Odt = DE, _Y = "internal://internal.malloy";
@@ -1470,7 +1470,7 @@ yzz{{||}}~~Ӂ
1470
1470
  | ${c}`,a>0&&(s=s+`
1471
1471
  | ${" ".repeat(a)}^`)}else s=`line ${u+1}: char ${a}: ${i.message}`}r!==o&&(s=`FILE: ${o}
1472
1472
  `+s,r=o),e!==""?e=`${e}
1473
- ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,pxt.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,ZP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,ZP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Rc.MalloyTranslation=eM;class Exe extends eM{constructor(e,r){super(e),this.root=r}}Rc.MalloyChildTranslator=Exe;class Bxt extends eM{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new XP.Zone,this.importZone=new XP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new XP.Zone,this.root=this,this.logger=new yxe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,yxe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Rc.MalloyTranslator=Bxt;function Axe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Axe(t[e])).flat()]}var L2={};Object.defineProperty(L2,"__esModule",{value:!0}),L2.exploreQueryWalkerBuilder=L2.ExploreQueryWalker=void 0;const kxt=ac;class _xe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}L2.ExploreQueryWalker=_xe;function Pxt(t,e){const r=new _xe(t),i=r;return kxt.ParseTreeWalker.DEFAULT.walk(i,e),r}L2.exploreQueryWalkerBuilder=Pxt;var I2={},TE={},Ia={};Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.getResultStructMetadataAnnotation=Ia.convertFieldInfos=Ia.modelDefToModelInfo=void 0;const $a=Pi,tM=Ls,nM=si,vxe=tu;function Mxt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,$a.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,$a.isAtomic)(a)?{name:u,type:IR(a),default_value:Cxe(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:Cxe(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:$2(i,i.fields)},parameters:s,annotations:rM(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,tM.getResultStructDefForQuery)(t,i),o=rM(i),u=s.resultMetadata?LR(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:$2(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,tM.getResultStructDefForQuery)(t,r),s=rM(r),o=i.resultMetadata?LR(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:$2(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ia.modelDefToModelInfo=Mxt;function Cxe(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function rM(t){return(0,nM.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function $2(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,nM.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,$a.isTurtle)(u)){const x=(0,tM.getResultStructDefForView)(t,u),h=x.resultMetadata?LR(x,x.resultMetadata):void 0,p=[...f??[],...h?[h]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:$2(x,x.fields)}};o.push(m)}else if((0,$a.isAtomic)(u)){const x=(0,$a.expressionIsAggregate)(u.expressionType),h=(0,$a.expressionIsScalar)(u.expressionType);if(!x&&!h||u.type==="error")continue;const p=u.resultMetadata?Sxe(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:IR(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,$a.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:$2(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ia.convertFieldInfos=$2;function Sxe(t,e){const r=vxe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:jxt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Uxt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function jxt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Uxt(t)}\``}function LR(t,e){var r,i;const s=vxe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ia.getResultStructMetadataAnnotation=LR;function IR(t){if((0,$a.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!qxt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Hxt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,$a.isRepeatedRecord)(t))return{kind:"array_type",element_type:bxe(t)};if(t.type==="record")return bxe(t);if(t.type==="array")return{kind:"array_type",element_type:IR(t.elementTypeDef)}}throw new Error("Unexpected field type")}function bxe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Sxe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,nM.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,$a.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:IR(e)};throw new Error("Expected record type to not have a table as its child")})}}function qxt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Hxt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function opt(t){return t}function upt(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=tu,r=si,i=Ia,s=Ny;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(y,E){const A=[];for(const _ of E.schema.fields){const v=y[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const g={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(TE);var Qxt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),zxt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Gxt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Qxt(e,t,r);return zxt(e,t),e};Object.defineProperty(I2,"__esModule",{value:!0}),I2.malloyToQuery=I2.MalloyToQuery=void 0;const Wxt=ep,Dn=Gxt(w),Txe=Xp,RE=In,Vxt=Ke,Yxt=yE,Rxe=Vn,Kxt=TE,iM="Malloy query documents";class Dxe extends Wxt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,Rxe.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Txe.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${iM}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${iM} may only have one run statement`);return i===void 0?(this.illegal(e,`${iM} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,RE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Dn.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Dn.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Dn.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Dn.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Dn.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Dn.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Dn.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Dn.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Dn.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Dn.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Dn.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Dn.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Dn.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,RE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Dn.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,RE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Dn.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Dn.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,RE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,Vxt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,RE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Dn.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Dn.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Dn.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof Dn.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Dn.ExprFieldPathContext&&i instanceof Dn.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Dn.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}I2.MalloyToQuery=Dxe;function Jxt(t){const e=(0,Rxe.getSourceInfo)(t),r=new Txe.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Yxt.runMalloyParser)(t,i,e,r),u=new Dxe(s,r).visit(s.root),a=(0,Kxt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}I2.malloyToQuery=Jxt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Rc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=L2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=I2;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Z4);var we={},$R={};Object.defineProperty($R,"__esModule",{value:!0}),$R.MALLOY_VERSION=void 0,$R.MALLOY_VERSION="0.0.274",Object.defineProperty(we,"__esModule",{value:!0}),we.InMemoryModelCache=we.CacheManager=we.CSVWriter=we.JSONWriter=we.DataWriter=we.DataRecord=we.DataArray=we.Result=we.ExploreMaterializer=we.PreparedResultMaterializer=we.QueryMaterializer=we.ModelMaterializer=we.SingleConnectionRuntime=we.ConnectionRuntime=we.Runtime=we.ExploreField=we.JoinRelationship=we.QueryField=we.Query=we.StringField=we.UnsupportedField=we.JSONField=we.BooleanField=we.NumberField=we.TimestampField=we.DateField=we.TimestampTimeframe=we.DateTimeframe=we.AtomicField=we.AtomicFieldType=we.Explore=we.SourceRelationship=we.FixedConnectionMap=we.InMemoryURLReader=we.EmptyURLReader=we.PreparedResult=we.DocumentCompletion=we.DocumentSymbol=we.DocumentPosition=we.DocumentRange=we.DocumentTablePath=we.Parse=we.PreparedQuery=we.Model=we.MalloyError=we.Malloy=void 0;const Oxe=Z4,ai=Pi,Fxe=Ny,sM=jp,Xxt=$R,Zxt=Hp,$n=si,edt=Kl,tdt=Vn,ndt=gE,wxe="internal://internal.malloy";let r0=class FD{static get version(){return Xxt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(wxe));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new Oxe.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new Lxe(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return FD._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return HR(r,e).then(({contents:u,invalidationKey:a})=>FD._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(wxe));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new B2(C.modelDef,[],[e.toString(),...qR(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await yM(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:b}=await HR(s,e);A[v]=b,r=C}else{const C=await yM(s,e);A[v]=C}_=new Oxe.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const b of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:A}));return new B2(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},S=(u==null?void 0:u._modelDef)||b;return new B2(S,C.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=C.fromSources)!==null&&y!==void 0?y:[]])}else{const b=C.problems||[],S=_.prettyErrors();throw new Nxe(`Error(s) compiling model:
1473
+ ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,pxt.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,ZP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,ZP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Rc.MalloyTranslation=eM;class Exe extends eM{constructor(e,r){super(e),this.root=r}}Rc.MalloyChildTranslator=Exe;class Bxt extends eM{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new XP.Zone,this.importZone=new XP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new XP.Zone,this.root=this,this.logger=new yxe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,yxe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Rc.MalloyTranslator=Bxt;function Axe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Axe(t[e])).flat()]}var L2={};Object.defineProperty(L2,"__esModule",{value:!0}),L2.exploreQueryWalkerBuilder=L2.ExploreQueryWalker=void 0;const kxt=ac;class _xe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}L2.ExploreQueryWalker=_xe;function Pxt(t,e){const r=new _xe(t),i=r;return kxt.ParseTreeWalker.DEFAULT.walk(i,e),r}L2.exploreQueryWalkerBuilder=Pxt;var I2={},TE={},Ia={};Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.getResultStructMetadataAnnotation=Ia.convertFieldInfos=Ia.modelDefToModelInfo=void 0;const $a=Pi,tM=Ls,nM=si,vxe=tu;function Mxt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,$a.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,$a.isAtomic)(a)?{name:u,type:IR(a),default_value:Cxe(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:Cxe(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:$2(i,i.fields)},parameters:s,annotations:rM(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,tM.getResultStructDefForQuery)(t,i),o=rM(i),u=s.resultMetadata?LR(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:$2(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,tM.getResultStructDefForQuery)(t,r),s=rM(r),o=i.resultMetadata?LR(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:$2(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ia.modelDefToModelInfo=Mxt;function Cxe(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function rM(t){return(0,nM.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function $2(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,nM.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,$a.isTurtle)(u)){const x=(0,tM.getResultStructDefForView)(t,u),h=x.resultMetadata?LR(x,x.resultMetadata):void 0,p=[...f??[],...h?[h]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:$2(x,x.fields)}};o.push(m)}else if((0,$a.isAtomic)(u)){const x=(0,$a.expressionIsAggregate)(u.expressionType),h=(0,$a.expressionIsScalar)(u.expressionType);if(!x&&!h||u.type==="error")continue;const p=u.resultMetadata?Sxe(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:IR(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,$a.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:$2(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ia.convertFieldInfos=$2;function Sxe(t,e){const r=vxe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:jxt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Uxt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function jxt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Uxt(t)}\``}function LR(t,e){var r,i;const s=vxe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ia.getResultStructMetadataAnnotation=LR;function IR(t){if((0,$a.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!qxt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Hxt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,$a.isRepeatedRecord)(t))return{kind:"array_type",element_type:bxe(t)};if(t.type==="record")return bxe(t);if(t.type==="array")return{kind:"array_type",element_type:IR(t.elementTypeDef)}}throw new Error("Unexpected field type")}function bxe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Sxe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,nM.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,$a.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:IR(e)};throw new Error("Expected record type to not have a table as its child")})}}function qxt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Hxt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function opt(t){return t}function upt(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=tu,r=si,i=Ia,s=Ny;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(y,E){const A=[];for(const _ of E.schema.fields){const v=y[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const g={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(TE);var Qxt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),zxt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Gxt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Qxt(e,t,r);return zxt(e,t),e};Object.defineProperty(I2,"__esModule",{value:!0}),I2.malloyToQuery=I2.MalloyToQuery=void 0;const Wxt=ep,Dn=Gxt(w),Txe=Xp,RE=In,Vxt=Ke,Yxt=yE,Rxe=Vn,Kxt=TE,iM="Malloy query documents";class Dxe extends Wxt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,Rxe.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Txe.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${iM}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${iM} may only have one run statement`);return i===void 0?(this.illegal(e,`${iM} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,RE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Dn.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Dn.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Dn.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Dn.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Dn.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Dn.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Dn.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Dn.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Dn.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Dn.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Dn.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Dn.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Dn.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,RE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Dn.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,RE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Dn.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Dn.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,RE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,Vxt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,RE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Dn.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Dn.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Dn.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof Dn.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Dn.ExprFieldPathContext&&i instanceof Dn.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Dn.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}I2.MalloyToQuery=Dxe;function Jxt(t){const e=(0,Rxe.getSourceInfo)(t),r=new Txe.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Yxt.runMalloyParser)(t,i,e,r),u=new Dxe(s,r).visit(s.root),a=(0,Kxt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}I2.malloyToQuery=Jxt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Rc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=L2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=I2;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Z4);var we={},$R={};Object.defineProperty($R,"__esModule",{value:!0}),$R.MALLOY_VERSION=void 0,$R.MALLOY_VERSION="0.0.275",Object.defineProperty(we,"__esModule",{value:!0}),we.InMemoryModelCache=we.CacheManager=we.CSVWriter=we.JSONWriter=we.DataWriter=we.DataRecord=we.DataArray=we.Result=we.ExploreMaterializer=we.PreparedResultMaterializer=we.QueryMaterializer=we.ModelMaterializer=we.SingleConnectionRuntime=we.ConnectionRuntime=we.Runtime=we.ExploreField=we.JoinRelationship=we.QueryField=we.Query=we.StringField=we.UnsupportedField=we.JSONField=we.BooleanField=we.NumberField=we.TimestampField=we.DateField=we.TimestampTimeframe=we.DateTimeframe=we.AtomicField=we.AtomicFieldType=we.Explore=we.SourceRelationship=we.FixedConnectionMap=we.InMemoryURLReader=we.EmptyURLReader=we.PreparedResult=we.DocumentCompletion=we.DocumentSymbol=we.DocumentPosition=we.DocumentRange=we.DocumentTablePath=we.Parse=we.PreparedQuery=we.Model=we.MalloyError=we.Malloy=void 0;const Oxe=Z4,ai=Pi,Fxe=Ny,sM=jp,Xxt=$R,Zxt=Hp,$n=si,edt=Kl,tdt=Vn,ndt=gE,wxe="internal://internal.malloy";let r0=class FD{static get version(){return Xxt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(wxe));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new Oxe.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new Lxe(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return FD._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return HR(r,e).then(({contents:u,invalidationKey:a})=>FD._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(wxe));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new B2(C.modelDef,[],[e.toString(),...qR(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await yM(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:b}=await HR(s,e);A[v]=b,r=C}else{const C=await yM(s,e);A[v]=C}_=new Oxe.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const b of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:A}));return new B2(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},S=(u==null?void 0:u._modelDef)||b;return new B2(S,C.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=C.fromSources)!==null&&y!==void 0?y:[]])}else{const b=C.problems||[],S=_.prettyErrors();throw new Nxe(`Error(s) compiling model:
1474
1474
  ${S}`,b)}else{if(C.urls)for(const S of C.urls)try{if(QR(S))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(x!==void 0){const D=await x.getCachedModelDef(s,S);if(D){for(const k in D.invalidationKeys)A[k]=D.invalidationKeys[k];_.update({translations:{[S]:D.modelDef}});continue}}const{contents:R,invalidationKey:O}=await HR(s,new URL(S)),I={[S]:R};A[S]=O,_.update({urls:I})}catch(R){_.update({errors:{urls:{[S]:R.message}}})}const{modelAnnotation:b}=_.modelAnnotation(u==null?void 0:u._modelDef);if(C.tables){const S=new Map;for(const R in C.tables){const{connectionName:O,tablePath:I}=C.tables[R],D=S.get(O);D===void 0?S.set(O,{[R]:I}):D[R]=I}for(const[R,O]of S)try{const I=await o.lookupConnection(R),{schemas:D,errors:k}=await FD.safelyFetchTableSchema(I,O,{refreshTimestamp:E,modelAnnotation:b});_.update({tables:D,errors:{tables:k}})}catch(I){const D={},k={};for(const U in O)k[U]=I.toString();_.update({tables:D,errors:{tables:k}})}}if(C.compileSQL){const S=C.compileSQL,R=S.connection,O=(0,edt.sqlKey)(S.connection,S.selectStr);try{const D=await(await o.lookupConnection(R)).fetchSchemaForSQLStruct(S,{refreshTimestamp:E,modelAnnotation:b});D.error&&_.update({errors:{compileSQL:{[O]:D.error}}}),D.structDef&&_.update({compileSQL:{[O]:D.structDef}})}catch(I){const D={};D[O]=I.toString(),_.update({errors:{compileSQL:D}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new FE({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new FE({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new Us(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new pd(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};we.Malloy=r0;class Nxe extends Error{constructor(e,r=[]){super(e),this.problems=r}}we.MalloyError=Nxe;class B2{constructor(e,r,i){var s,o;this.modelDef=e,this.problems=r,this.fromSources=i,this.references=new ndt.ReferenceList((s=i[0])!==null&&s!==void 0?s:"",(o=e.references)!==null&&o!==void 0?o:[])}tagParse(e){return(0,$n.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this.references.find(e)}getImport(e){var r;return(r=this.modelDef.imports)===null||r===void 0?void 0:r.find(i=>(0,tdt.locationContainsPosition)(i.location,e))}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new k2(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new k2(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new k2(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if((0,ai.isSourceDef)(r))return new Us(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(ai.isSourceDef).map(e=>new Us(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}we.Model=B2;class k2{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,$n.annotationToTag)(this._modelDef.annotation).tag;return e=(0,$n.addModelScope)(e,r),(0,$n.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new ai.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new DE({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,ai.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}we.PreparedQuery=k2;class Lxe{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new BR(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new Ixe(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new $xe(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}we.Parse=Lxe;class Ixe{constructor(e){this._range=P2.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}we.DocumentTablePath=Ixe;class P2{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new P2(new oM(e.start.line,e.start.character),new oM(e.end.line,e.end.character))}}we.DocumentRange=P2;class oM{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}we.DocumentPosition=oM;class BR{constructor(e){this._range=P2.fromJSON(e.range),this._lensRange=e.lensRange?P2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new BR(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}we.DocumentSymbol=BR;class $xe{constructor(e){this.type=e.type,this.text=e.text}}we.DocumentCompletion=$xe;class DE{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new DE(e,r)}tagParse(e){const r=(0,$n.annotationToTag)(this.modelDef.annotation).tag;return e=(0,$n.addModelScope)(e,r),(0,$n.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,$n.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new Us(r,this.sourceExplore)}catch{return new Us(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,ai.isSourceDef)(r))return new Us(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}we.PreparedResult=DE;class Bxe{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}we.EmptyURLReader=Bxe;class rdt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return QR(e.toString())?null:Jxe(r)}}we.InMemoryURLReader=rdt;class kR{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new kR(new Map(e.map(r=>[r.name,r])))}}we.FixedConnectionMap=kR;var kxe;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(kxe||(we.SourceRelationship=kxe={}));class uM{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Us}isQuery(){return this instanceof hM}}class Us extends uM{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,ai.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,$n.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,$n.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i={type:"query",structRef:r,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new k2(i,this.modelDef,[],e)}get modelDef(){if(!(0,ai.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new B2(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,ai.isJoined)(i))return[s,new pM(i,this,o)];if(i.type==="turtle")return[s,new hM(i,this,o)];if(i.type==="string")return[s,new dM(i,this,o)];if(i.type==="number")return[s,new PR(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new PR({...i,type:"number"},this,o)]:[s,new aM(i,this,o)];if(i.type==="timestamp")return[s,new lM(i,this,o)];if(i.type==="boolean")return[s,new cM(i,this,o)];if(i.type==="json")return[s,new fM(i,this,o)];if(i.type==="sql native")return[s,new xM(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(u=>{if(typeof u.field=="string")return{field:this.fieldMap.get(u.field),dir:u.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(u=>u.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(u=>!o.has(u.name)).map(u=>({field:u,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof pM}get filters(){var e;return(0,ai.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,ai.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?Us.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?Us.fromJSON(e.sourceExplore):void 0;return new Us(e._structDef,r,i)}get location(){return this.structDef.location}}we.Explore=Us;var Ba;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(Ba||(we.AtomicFieldType=Ba={}));class Vc extends uM{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return Ba.String;case"boolean":return Ba.Boolean;case"date":return Ba.Date;case"timestamp":return Ba.Timestamp;case"number":return Ba.Number;case"json":return Ba.Json;case"sql native":return Ba.NativeUnsupported;case"error":return Ba.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,$n.addModelScope)(e,this.parent.modelTag),(0,$n.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,ai.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,ai.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof dM}isNumber(){return this instanceof PR}isDate(){return this instanceof aM}isBoolean(){return this instanceof cM}isJSON(){return this instanceof fM}isTimestamp(){return this instanceof lM}isUnsupported(){return this instanceof xM}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}we.AtomicField=Vc;var hd;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(hd||(we.DateTimeframe=hd={}));var ka;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(ka||(we.TimestampTimeframe=ka={}));class aM extends Vc{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return hd.Day;case"week":return hd.Week;case"month":return hd.Month;case"quarter":return hd.Quarter;case"year":return hd.Year}}}we.DateField=aM;class lM extends Vc{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return ka.Day;case"week":return ka.Week;case"month":return ka.Month;case"quarter":return ka.Quarter;case"year":return ka.Year;case"second":return ka.Second;case"hour":return ka.Hour;case"minute":return ka.Minute}}}we.TimestampField=lM;class PR extends Vc{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}}we.NumberField=PR;class cM extends Vc{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}}we.BooleanField=cM;class fM extends Vc{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}}we.JSONField=fM;class xM extends Vc{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}we.UnsupportedField=xM;class dM extends Vc{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}}we.StringField=dM;class Pxe extends uM{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}we.Query=Pxe;class hM extends Pxe{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,$n.addModelScope)(e,this.parent.modelTag),(0,$n.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,$n.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}we.QueryField=hM;var M2;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(M2||(we.JoinRelationship=M2={}));class pM extends Us{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,ai.isJoined)(this.structDef))switch(this.structDef.join){case"one":return M2.OneToOne;case"many":case"cross":return M2.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===M2.OneToOne}get isArray(){return this.joinRelationship!==M2.OneToOne}tagParse(e){return e=(0,$n.addModelScope)(e,this._parentExplore.modelTag),(0,$n.annotationToTag)(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}we.ExploreField=pM;class mM{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new Bxe),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new OE(this,async()=>r0.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new OE(this,async()=>new B2(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}we.Runtime=mM;class idt extends mM{constructor({urlReader:e,connections:r}){super({connections:kR.fromArray(r),urlReader:e}),this.rawConnections=r}}we.ConnectionRuntime=idt;class sdt extends mM{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,sM.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,sM.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,sM.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}we.SingleConnectionRuntime=sdt;class MR{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new Mxe(this.runtime,e,r)}makeExploreMaterializer(e,r){return new jxe(this.runtime,e,r)}makePreparedResultMaterializer(e){return new Uxe(this.runtime,e)}}class OE extends MR{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await r0.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new OE(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await r0.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new ai.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,ai.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,ai.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
1475
1475
  run: ${e}
1476
1476
  -> ${u}
@@ -154057,7 +154057,7 @@ n2.malloyToQuery = A2t;
154057
154057
  var $e = {}, QD = {};
154058
154058
  Object.defineProperty(QD, "__esModule", { value: !0 });
154059
154059
  QD.MALLOY_VERSION = void 0;
154060
- QD.MALLOY_VERSION = "0.0.274";
154060
+ QD.MALLOY_VERSION = "0.0.275";
154061
154061
  Object.defineProperty($e, "__esModule", { value: !0 });
154062
154062
  $e.InMemoryModelCache = $e.CacheManager = $e.CSVWriter = $e.JSONWriter = $e.DataWriter = $e.DataRecord = $e.DataArray = $e.Result = $e.ExploreMaterializer = $e.PreparedResultMaterializer = $e.QueryMaterializer = $e.ModelMaterializer = $e.SingleConnectionRuntime = $e.ConnectionRuntime = $e.Runtime = $e.ExploreField = $e.JoinRelationship = $e.QueryField = $e.Query = $e.StringField = $e.UnsupportedField = $e.JSONField = $e.BooleanField = $e.NumberField = $e.TimestampField = $e.DateField = $e.TimestampTimeframe = $e.DateTimeframe = $e.AtomicField = $e.AtomicFieldType = $e.Explore = $e.SourceRelationship = $e.FixedConnectionMap = $e.InMemoryURLReader = $e.EmptyURLReader = $e.PreparedResult = $e.DocumentCompletion = $e.DocumentSymbol = $e.DocumentPosition = $e.DocumentRange = $e.DocumentTablePath = $e.Parse = $e.PreparedQuery = $e.Model = $e.MalloyError = $e.Malloy = void 0;
154063
154063
  const XY = KT, ri = Yi, ZY = zr, sw = J2, S2t = QD, C2t = X2, kn = di, b2t = n0, T2t = Kn, R2t = u_, eK = "internal://internal.malloy";
@@ -1861,7 +1861,7 @@ yzz{{||}}~~Ӂ
1861
1861
  | ${c}`,a>0&&(s=s+`
1862
1862
  | ${" ".repeat(a)}^`)}else s=`line ${u+1}: char ${a}: ${i.message}`}r!==o&&(s=`FILE: ${o}
1863
1863
  `+s,r=o),e!==""?e=`${e}
1864
- ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,fpt.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,EP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,EP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Wc.MalloyTranslation=_P;class Ade extends _P{constructor(e,r){super(e),this.root=r}}Wc.MalloyChildTranslator=Ade;class Npt extends _P{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new yP.Zone,this.importZone=new yP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new yP.Zone,this.root=this,this.logger=new vde.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,vde.makeLogMessage)(e,r,{severity:"error",...i})),e}}Wc.MalloyTranslator=Npt;function Sde(t){return[...Object.keys(t),...Object.keys(t).map(e=>Sde(t[e])).flat()]}var c1={};Object.defineProperty(c1,"__esModule",{value:!0}),c1.exploreQueryWalkerBuilder=c1.ExploreQueryWalker=void 0;const Lpt=R0;class Cde{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}c1.ExploreQueryWalker=Cde;function Ipt(t,e){const r=new Cde(t),i=r;return Lpt.ParseTreeWalker.DEFAULT.walk(i,e),r}c1.exploreQueryWalkerBuilder=Ipt;var f1={},o_={},Ya={};Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.getResultStructMetadataAnnotation=Ya.convertFieldInfos=Ya.modelDefToModelInfo=void 0;const Ka=Gi,vP=js,AP=hi,bde=ko;function $pt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ka.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,Ka.isAtomic)(a)?{name:u,type:wD(a),default_value:Tde(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:Tde(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:x1(i,i.fields)},parameters:s,annotations:SP(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,vP.getResultStructDefForQuery)(t,i),o=SP(i),u=s.resultMetadata?OD(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:x1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,vP.getResultStructDefForQuery)(t,r),s=SP(r),o=i.resultMetadata?OD(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:x1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ya.modelDefToModelInfo=$pt;function Tde(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function SP(t){return(0,AP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function x1(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,AP.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,Ka.isTurtle)(u)){const x=(0,vP.getResultStructDefForView)(t,u),d=x.resultMetadata?OD(x,x.resultMetadata):void 0,p=[...f??[],...d?[d]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:x1(x,x.fields)}};o.push(m)}else if((0,Ka.isAtomic)(u)){const x=(0,Ka.expressionIsAggregate)(u.expressionType),d=(0,Ka.expressionIsScalar)(u.expressionType);if(!x&&!d||u.type==="error")continue;const p=u.resultMetadata?Rde(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:wD(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,Ka.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:x1(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ya.convertFieldInfos=x1;function Rde(t,e){const r=bde.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:kpt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Bpt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function kpt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Bpt(t)}\``}function OD(t,e){var r,i;const s=bde.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ya.getResultStructMetadataAnnotation=OD;function wD(t){if((0,Ka.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Mpt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Ppt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ka.isRepeatedRecord)(t))return{kind:"array_type",element_type:Dde(t)};if(t.type==="record")return Dde(t);if(t.type==="array")return{kind:"array_type",element_type:wD(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Dde(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Rde(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,AP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ka.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:wD(e)};throw new Error("Expected record type to not have a table as its child")})}}function Mpt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Ppt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function rmt(t){return t}function imt(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=ko,r=hi,i=Ya,s=jr;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(d){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:d},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(d){const p=`${x.name}:${d}`,m=await x.fetchSchemaForTables({[p]:d},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(d,p)=>{const m=await x.runSQL(d);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,d){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const _=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:_}:{kind:"timestamp_cell",timestamp_value:_}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(_=>p(_,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const _=E.type;if(_.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:_.fields.map(v=>({kind:"dimension",...v}))}})}}}function m(y,E){const _=[];for(const v of E.schema.fields){const A=y[v.name];if(v.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const S=p(A,v);_.push(S)}return{kind:"record_cell",record_value:_}}const g={kind:"join",schema:d,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const d=x._queryResult.structs,p=d[d.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,d){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:d}})}t.mapLogs=f})(o_);var Upt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),jpt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),qpt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Upt(e,t,r);return jpt(e,t),e};Object.defineProperty(f1,"__esModule",{value:!0}),f1.malloyToQuery=f1.MalloyToQuery=void 0;const Hpt=Gd,Nn=qpt(I),Ode=O2,u_=Mn,zpt=Ze,Qpt=XE,wde=Jn,Gpt=o_,CP="Malloy query documents";class Fde extends Hpt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,wde.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Ode.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${CP}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${CP} may only have one run statement`);return i===void 0?(this.illegal(e,`${CP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,u_.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Nn.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Nn.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Nn.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Nn.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Nn.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Nn.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Nn.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Nn.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Nn.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Nn.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Nn.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Nn.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Nn.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,u_.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Nn.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,u_.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Nn.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Nn.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,u_.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,zpt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,u_.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Nn.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Nn.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Nn.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof Nn.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Nn.ExprFieldPathContext&&i instanceof Nn.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Nn.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}f1.MalloyToQuery=Fde;function Wpt(t){const e=(0,wde.getSourceInfo)(t),r=new Ode.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Qpt.runMalloyParser)(t,i,e,r),u=new Fde(s,r).visit(s.root),a=(0,Gpt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}f1.malloyToQuery=Wpt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Wc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=c1;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=f1;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Y4);var $e={},FD={};Object.defineProperty(FD,"__esModule",{value:!0}),FD.MALLOY_VERSION=void 0,FD.MALLOY_VERSION="0.0.274",Object.defineProperty($e,"__esModule",{value:!0}),$e.InMemoryModelCache=$e.CacheManager=$e.CSVWriter=$e.JSONWriter=$e.DataWriter=$e.DataRecord=$e.DataArray=$e.Result=$e.ExploreMaterializer=$e.PreparedResultMaterializer=$e.QueryMaterializer=$e.ModelMaterializer=$e.SingleConnectionRuntime=$e.ConnectionRuntime=$e.Runtime=$e.ExploreField=$e.JoinRelationship=$e.QueryField=$e.Query=$e.StringField=$e.UnsupportedField=$e.JSONField=$e.BooleanField=$e.NumberField=$e.TimestampField=$e.DateField=$e.TimestampTimeframe=$e.DateTimeframe=$e.AtomicField=$e.AtomicFieldType=$e.Explore=$e.SourceRelationship=$e.FixedConnectionMap=$e.InMemoryURLReader=$e.EmptyURLReader=$e.PreparedResult=$e.DocumentCompletion=$e.DocumentSymbol=$e.DocumentPosition=$e.DocumentRange=$e.DocumentTablePath=$e.Parse=$e.PreparedQuery=$e.Model=$e.MalloyError=$e.Malloy=void 0;const Nde=Y4,gi=Gi,Lde=jr,bP=y2,Vpt=FD,Ypt=_2,Pn=hi,Kpt=y0,Jpt=Jn,Xpt=JE,Ide="internal://internal.malloy";let b0=class iO{static get version(){return Vpt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(Ide));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new Nde.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new Bde(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return iO._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return PD(r,e).then(({contents:u,invalidationKey:a})=>iO._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var d,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(Ide));const _={};if(r===void 0&&x!==void 0){const S=await x.getCachedModelDef(s,e.toString());if(S)return new d1(S.modelDef,[],[e.toString(),...MD(S.modelDef.dependencies)])}f??(f=e);let v;const A=e.toString();if(i!==void 0){v=i._translator;const S=(d=i._invalidationKey)!==null&&d!==void 0?d:await MP(s,e);_[A]=S}else{if(r===void 0){const{contents:S,invalidationKey:b}=await PD(s,e);_[A]=b,r=S}else{const S=await MP(s,e);_[A]=S}v=new Nde.MalloyTranslator(A,f.toString(),{urls:{[A]:r}},c)}for(;;){const S=v.translate(u==null?void 0:u._modelDef);if(S.final)if(S.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:S.modelDef,invalidationKeys:_}));for(const b of v.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:_}));return new d1(S.modelDef,S.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=S.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},C=(u==null?void 0:u._modelDef)||b;return new d1(C,S.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=S.fromSources)!==null&&y!==void 0?y:[]])}else{const b=S.problems||[],C=v.prettyErrors();throw new $de(`Error(s) compiling model:
1864
+ ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,fpt.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,EP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,EP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Wc.MalloyTranslation=_P;class Ade extends _P{constructor(e,r){super(e),this.root=r}}Wc.MalloyChildTranslator=Ade;class Npt extends _P{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new yP.Zone,this.importZone=new yP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new yP.Zone,this.root=this,this.logger=new vde.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,vde.makeLogMessage)(e,r,{severity:"error",...i})),e}}Wc.MalloyTranslator=Npt;function Sde(t){return[...Object.keys(t),...Object.keys(t).map(e=>Sde(t[e])).flat()]}var c1={};Object.defineProperty(c1,"__esModule",{value:!0}),c1.exploreQueryWalkerBuilder=c1.ExploreQueryWalker=void 0;const Lpt=R0;class Cde{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}c1.ExploreQueryWalker=Cde;function Ipt(t,e){const r=new Cde(t),i=r;return Lpt.ParseTreeWalker.DEFAULT.walk(i,e),r}c1.exploreQueryWalkerBuilder=Ipt;var f1={},o_={},Ya={};Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.getResultStructMetadataAnnotation=Ya.convertFieldInfos=Ya.modelDefToModelInfo=void 0;const Ka=Gi,vP=js,AP=hi,bde=ko;function $pt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ka.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,Ka.isAtomic)(a)?{name:u,type:wD(a),default_value:Tde(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:Tde(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:x1(i,i.fields)},parameters:s,annotations:SP(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,vP.getResultStructDefForQuery)(t,i),o=SP(i),u=s.resultMetadata?OD(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:x1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,vP.getResultStructDefForQuery)(t,r),s=SP(r),o=i.resultMetadata?OD(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:x1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ya.modelDefToModelInfo=$pt;function Tde(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function SP(t){return(0,AP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function x1(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,AP.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,Ka.isTurtle)(u)){const x=(0,vP.getResultStructDefForView)(t,u),d=x.resultMetadata?OD(x,x.resultMetadata):void 0,p=[...f??[],...d?[d]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:x1(x,x.fields)}};o.push(m)}else if((0,Ka.isAtomic)(u)){const x=(0,Ka.expressionIsAggregate)(u.expressionType),d=(0,Ka.expressionIsScalar)(u.expressionType);if(!x&&!d||u.type==="error")continue;const p=u.resultMetadata?Rde(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:wD(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,Ka.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:x1(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ya.convertFieldInfos=x1;function Rde(t,e){const r=bde.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:kpt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Bpt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function kpt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Bpt(t)}\``}function OD(t,e){var r,i;const s=bde.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ya.getResultStructMetadataAnnotation=OD;function wD(t){if((0,Ka.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Mpt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Ppt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ka.isRepeatedRecord)(t))return{kind:"array_type",element_type:Dde(t)};if(t.type==="record")return Dde(t);if(t.type==="array")return{kind:"array_type",element_type:wD(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Dde(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Rde(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,AP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ka.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:wD(e)};throw new Error("Expected record type to not have a table as its child")})}}function Mpt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Ppt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function rmt(t){return t}function imt(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=ko,r=hi,i=Ya,s=jr;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(d){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:d},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(d){const p=`${x.name}:${d}`,m=await x.fetchSchemaForTables({[p]:d},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(d,p)=>{const m=await x.runSQL(d);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,d){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const _=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:_}:{kind:"timestamp_cell",timestamp_value:_}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(_=>p(_,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const _=E.type;if(_.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:_.fields.map(v=>({kind:"dimension",...v}))}})}}}function m(y,E){const _=[];for(const v of E.schema.fields){const A=y[v.name];if(v.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const S=p(A,v);_.push(S)}return{kind:"record_cell",record_value:_}}const g={kind:"join",schema:d,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const d=x._queryResult.structs,p=d[d.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,d){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:d}})}t.mapLogs=f})(o_);var Upt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),jpt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),qpt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Upt(e,t,r);return jpt(e,t),e};Object.defineProperty(f1,"__esModule",{value:!0}),f1.malloyToQuery=f1.MalloyToQuery=void 0;const Hpt=Gd,Nn=qpt(I),Ode=O2,u_=Mn,zpt=Ze,Qpt=XE,wde=Jn,Gpt=o_,CP="Malloy query documents";class Fde extends Hpt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,wde.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Ode.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${CP}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${CP} may only have one run statement`);return i===void 0?(this.illegal(e,`${CP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,u_.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Nn.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Nn.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Nn.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Nn.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Nn.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Nn.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Nn.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Nn.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Nn.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Nn.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Nn.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Nn.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Nn.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,u_.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Nn.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,u_.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Nn.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Nn.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,u_.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,zpt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,u_.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Nn.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Nn.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Nn.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof Nn.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Nn.ExprFieldPathContext&&i instanceof Nn.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Nn.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}f1.MalloyToQuery=Fde;function Wpt(t){const e=(0,wde.getSourceInfo)(t),r=new Ode.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Qpt.runMalloyParser)(t,i,e,r),u=new Fde(s,r).visit(s.root),a=(0,Gpt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}f1.malloyToQuery=Wpt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Wc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=c1;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=f1;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Y4);var $e={},FD={};Object.defineProperty(FD,"__esModule",{value:!0}),FD.MALLOY_VERSION=void 0,FD.MALLOY_VERSION="0.0.275",Object.defineProperty($e,"__esModule",{value:!0}),$e.InMemoryModelCache=$e.CacheManager=$e.CSVWriter=$e.JSONWriter=$e.DataWriter=$e.DataRecord=$e.DataArray=$e.Result=$e.ExploreMaterializer=$e.PreparedResultMaterializer=$e.QueryMaterializer=$e.ModelMaterializer=$e.SingleConnectionRuntime=$e.ConnectionRuntime=$e.Runtime=$e.ExploreField=$e.JoinRelationship=$e.QueryField=$e.Query=$e.StringField=$e.UnsupportedField=$e.JSONField=$e.BooleanField=$e.NumberField=$e.TimestampField=$e.DateField=$e.TimestampTimeframe=$e.DateTimeframe=$e.AtomicField=$e.AtomicFieldType=$e.Explore=$e.SourceRelationship=$e.FixedConnectionMap=$e.InMemoryURLReader=$e.EmptyURLReader=$e.PreparedResult=$e.DocumentCompletion=$e.DocumentSymbol=$e.DocumentPosition=$e.DocumentRange=$e.DocumentTablePath=$e.Parse=$e.PreparedQuery=$e.Model=$e.MalloyError=$e.Malloy=void 0;const Nde=Y4,gi=Gi,Lde=jr,bP=y2,Vpt=FD,Ypt=_2,Pn=hi,Kpt=y0,Jpt=Jn,Xpt=JE,Ide="internal://internal.malloy";let b0=class iO{static get version(){return Vpt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(Ide));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new Nde.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new Bde(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return iO._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return PD(r,e).then(({contents:u,invalidationKey:a})=>iO._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var d,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(Ide));const _={};if(r===void 0&&x!==void 0){const S=await x.getCachedModelDef(s,e.toString());if(S)return new d1(S.modelDef,[],[e.toString(),...MD(S.modelDef.dependencies)])}f??(f=e);let v;const A=e.toString();if(i!==void 0){v=i._translator;const S=(d=i._invalidationKey)!==null&&d!==void 0?d:await MP(s,e);_[A]=S}else{if(r===void 0){const{contents:S,invalidationKey:b}=await PD(s,e);_[A]=b,r=S}else{const S=await MP(s,e);_[A]=S}v=new Nde.MalloyTranslator(A,f.toString(),{urls:{[A]:r}},c)}for(;;){const S=v.translate(u==null?void 0:u._modelDef);if(S.final)if(S.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:S.modelDef,invalidationKeys:_}));for(const b of v.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:_}));return new d1(S.modelDef,S.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=S.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},C=(u==null?void 0:u._modelDef)||b;return new d1(C,S.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=S.fromSources)!==null&&y!==void 0?y:[]])}else{const b=S.problems||[],C=v.prettyErrors();throw new $de(`Error(s) compiling model:
1865
1865
  ${C}`,b)}else{if(S.urls)for(const C of S.urls)try{if(UD(C))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(x!==void 0){const D=await x.getCachedModelDef(s,C);if(D){for(const k in D.invalidationKeys)_[k]=D.invalidationKeys[k];v.update({translations:{[C]:D.modelDef}});continue}}const{contents:R,invalidationKey:O}=await PD(s,new URL(C)),B={[C]:R};_[C]=O,v.update({urls:B})}catch(R){v.update({errors:{urls:{[C]:R.message}}})}const{modelAnnotation:b}=v.modelAnnotation(u==null?void 0:u._modelDef);if(S.tables){const C=new Map;for(const R in S.tables){const{connectionName:O,tablePath:B}=S.tables[R],D=C.get(O);D===void 0?C.set(O,{[R]:B}):D[R]=B}for(const[R,O]of C)try{const B=await o.lookupConnection(R),{schemas:D,errors:k}=await iO.safelyFetchTableSchema(B,O,{refreshTimestamp:E,modelAnnotation:b});v.update({tables:D,errors:{tables:k}})}catch(B){const D={},k={};for(const M in O)k[M]=B.toString();v.update({tables:D,errors:{tables:k}})}}if(S.compileSQL){const C=S.compileSQL,R=C.connection,O=(0,Kpt.sqlKey)(C.connection,C.selectStr);try{const D=await(await o.lookupConnection(R)).fetchSchemaForSQLStruct(C,{refreshTimestamp:E,modelAnnotation:b});D.error&&v.update({errors:{compileSQL:{[O]:D.error}}}),D.structDef&&v.update({compileSQL:{[O]:D.structDef}})}catch(B){const D={};D[O]=B.toString(),v.update({errors:{compileSQL:D}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new c_({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new c_({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new Vs(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new Ud(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};$e.Malloy=b0;class $de extends Error{constructor(e,r=[]){super(e),this.problems=r}}$e.MalloyError=$de;class d1{constructor(e,r,i){var s,o;this.modelDef=e,this.problems=r,this.fromSources=i,this.references=new Xpt.ReferenceList((s=i[0])!==null&&s!==void 0?s:"",(o=e.references)!==null&&o!==void 0?o:[])}tagParse(e){return(0,Pn.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this.references.find(e)}getImport(e){var r;return(r=this.modelDef.imports)===null||r===void 0?void 0:r.find(i=>(0,Jpt.locationContainsPosition)(i.location,e))}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new h1(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new h1(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new h1(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if((0,gi.isSourceDef)(r))return new Vs(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(gi.isSourceDef).map(e=>new Vs(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}$e.Model=d1;class h1{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,Pn.annotationToTag)(this._modelDef.annotation).tag;return e=(0,Pn.addModelScope)(e,r),(0,Pn.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new gi.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new a_({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,gi.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}$e.PreparedQuery=h1;class Bde{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new ND(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new kde(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new Mde(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}$e.Parse=Bde;class kde{constructor(e){this._range=p1.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}$e.DocumentTablePath=kde;class p1{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new p1(new TP(e.start.line,e.start.character),new TP(e.end.line,e.end.character))}}$e.DocumentRange=p1;class TP{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}$e.DocumentPosition=TP;class ND{constructor(e){this._range=p1.fromJSON(e.range),this._lensRange=e.lensRange?p1.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new ND(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}$e.DocumentSymbol=ND;class Mde{constructor(e){this.type=e.type,this.text=e.text}}$e.DocumentCompletion=Mde;class a_{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new a_(e,r)}tagParse(e){const r=(0,Pn.annotationToTag)(this.modelDef.annotation).tag;return e=(0,Pn.addModelScope)(e,r),(0,Pn.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,Pn.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new Vs(r,this.sourceExplore)}catch{return new Vs(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,gi.isSourceDef)(r))return new Vs(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}$e.PreparedResult=a_;class Pde{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}$e.EmptyURLReader=Pde;class Zpt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return UD(e.toString())?null:ehe(r)}}$e.InMemoryURLReader=Zpt;class LD{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new LD(new Map(e.map(r=>[r.name,r])))}}$e.FixedConnectionMap=LD;var Ude;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(Ude||($e.SourceRelationship=Ude={}));class RP{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Vs}isQuery(){return this instanceof IP}}class Vs extends RP{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,gi.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,Pn.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,Pn.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i={type:"query",structRef:r,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new h1(i,this.modelDef,[],e)}get modelDef(){if(!(0,gi.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new d1(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,gi.isJoined)(i))return[s,new $P(i,this,o)];if(i.type==="turtle")return[s,new IP(i,this,o)];if(i.type==="string")return[s,new LP(i,this,o)];if(i.type==="number")return[s,new ID(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new ID({...i,type:"number"},this,o)]:[s,new DP(i,this,o)];if(i.type==="timestamp")return[s,new OP(i,this,o)];if(i.type==="boolean")return[s,new wP(i,this,o)];if(i.type==="json")return[s,new FP(i,this,o)];if(i.type==="sql native")return[s,new NP(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(u=>{if(typeof u.field=="string")return{field:this.fieldMap.get(u.field),dir:u.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(u=>u.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(u=>!o.has(u.name)).map(u=>({field:u,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof $P}get filters(){var e;return(0,gi.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,gi.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?Vs.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?Vs.fromJSON(e.sourceExplore):void 0;return new Vs(e._structDef,r,i)}get location(){return this.structDef.location}}$e.Explore=Vs;var Ja;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(Ja||($e.AtomicFieldType=Ja={}));class pf extends RP{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return Ja.String;case"boolean":return Ja.Boolean;case"date":return Ja.Date;case"timestamp":return Ja.Timestamp;case"number":return Ja.Number;case"json":return Ja.Json;case"sql native":return Ja.NativeUnsupported;case"error":return Ja.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,Pn.addModelScope)(e,this.parent.modelTag),(0,Pn.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,gi.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,gi.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof LP}isNumber(){return this instanceof ID}isDate(){return this instanceof DP}isBoolean(){return this instanceof wP}isJSON(){return this instanceof FP}isTimestamp(){return this instanceof OP}isUnsupported(){return this instanceof NP}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}$e.AtomicField=pf;var Pd;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Pd||($e.DateTimeframe=Pd={}));var Xa;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(Xa||($e.TimestampTimeframe=Xa={}));class DP extends pf{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Pd.Day;case"week":return Pd.Week;case"month":return Pd.Month;case"quarter":return Pd.Quarter;case"year":return Pd.Year}}}$e.DateField=DP;class OP extends pf{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Xa.Day;case"week":return Xa.Week;case"month":return Xa.Month;case"quarter":return Xa.Quarter;case"year":return Xa.Year;case"second":return Xa.Second;case"hour":return Xa.Hour;case"minute":return Xa.Minute}}}$e.TimestampField=OP;class ID extends pf{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}}$e.NumberField=ID;class wP extends pf{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}}$e.BooleanField=wP;class FP extends pf{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}}$e.JSONField=FP;class NP extends pf{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}$e.UnsupportedField=NP;class LP extends pf{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}}$e.StringField=LP;class jde extends RP{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}$e.Query=jde;class IP extends jde{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,Pn.addModelScope)(e,this.parent.modelTag),(0,Pn.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}$e.QueryField=IP;var m1;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(m1||($e.JoinRelationship=m1={}));class $P extends Vs{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,gi.isJoined)(this.structDef))switch(this.structDef.join){case"one":return m1.OneToOne;case"many":case"cross":return m1.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===m1.OneToOne}get isArray(){return this.joinRelationship!==m1.OneToOne}tagParse(e){return e=(0,Pn.addModelScope)(e,this._parentExplore.modelTag),(0,Pn.annotationToTag)(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}$e.ExploreField=$P;class BP{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new Pde),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new l_(this,async()=>b0.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new l_(this,async()=>new d1(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}$e.Runtime=BP;class e2t extends BP{constructor({urlReader:e,connections:r}){super({connections:LD.fromArray(r),urlReader:e}),this.rawConnections=r}}$e.ConnectionRuntime=e2t;class t2t extends BP{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,bP.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,bP.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,bP.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}$e.SingleConnectionRuntime=t2t;class $D{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new qde(this.runtime,e,r)}makeExploreMaterializer(e,r){return new zde(this.runtime,e,r)}makePreparedResultMaterializer(e){return new Hde(this.runtime,e)}}class l_ extends $D{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await b0.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new l_(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await b0.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new gi.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,gi.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,gi.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
1866
1866
  run: ${e}
1867
1867
  -> ${u}
@@ -154057,7 +154057,7 @@ n2.malloyToQuery = A2t;
154057
154057
  var $e = {}, QD = {};
154058
154058
  Object.defineProperty(QD, "__esModule", { value: !0 });
154059
154059
  QD.MALLOY_VERSION = void 0;
154060
- QD.MALLOY_VERSION = "0.0.274";
154060
+ QD.MALLOY_VERSION = "0.0.275";
154061
154061
  Object.defineProperty($e, "__esModule", { value: !0 });
154062
154062
  $e.InMemoryModelCache = $e.CacheManager = $e.CSVWriter = $e.JSONWriter = $e.DataWriter = $e.DataRecord = $e.DataArray = $e.Result = $e.ExploreMaterializer = $e.PreparedResultMaterializer = $e.QueryMaterializer = $e.ModelMaterializer = $e.SingleConnectionRuntime = $e.ConnectionRuntime = $e.Runtime = $e.ExploreField = $e.JoinRelationship = $e.QueryField = $e.Query = $e.StringField = $e.UnsupportedField = $e.JSONField = $e.BooleanField = $e.NumberField = $e.TimestampField = $e.DateField = $e.TimestampTimeframe = $e.DateTimeframe = $e.AtomicField = $e.AtomicFieldType = $e.Explore = $e.SourceRelationship = $e.FixedConnectionMap = $e.InMemoryURLReader = $e.EmptyURLReader = $e.PreparedResult = $e.DocumentCompletion = $e.DocumentSymbol = $e.DocumentPosition = $e.DocumentRange = $e.DocumentTablePath = $e.Parse = $e.PreparedQuery = $e.Model = $e.MalloyError = $e.Malloy = void 0;
154063
154063
  const XY = KT, ri = Yi, ZY = zr, sw = J2, S2t = QD, C2t = X2, kn = di, b2t = n0, T2t = Kn, R2t = u_, eK = "internal://internal.malloy";
@@ -1861,7 +1861,7 @@ yzz{{||}}~~Ӂ
1861
1861
  | ${c}`,a>0&&(s=s+`
1862
1862
  | ${" ".repeat(a)}^`)}else s=`line ${u+1}: char ${a}: ${i.message}`}r!==o&&(s=`FILE: ${o}
1863
1863
  `+s,r=o),e!==""?e=`${e}
1864
- ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,fpt.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,yP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,yP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Wc.MalloyTranslation=EP;class vde extends EP{constructor(e,r){super(e),this.root=r}}Wc.MalloyChildTranslator=vde;class Npt extends EP{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new gP.Zone,this.importZone=new gP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new gP.Zone,this.root=this,this.logger=new _de.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,_de.makeLogMessage)(e,r,{severity:"error",...i})),e}}Wc.MalloyTranslator=Npt;function Ade(t){return[...Object.keys(t),...Object.keys(t).map(e=>Ade(t[e])).flat()]}var c1={};Object.defineProperty(c1,"__esModule",{value:!0}),c1.exploreQueryWalkerBuilder=c1.ExploreQueryWalker=void 0;const Lpt=R0;class Sde{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}c1.ExploreQueryWalker=Sde;function Ipt(t,e){const r=new Sde(t),i=r;return Lpt.ParseTreeWalker.DEFAULT.walk(i,e),r}c1.exploreQueryWalkerBuilder=Ipt;var f1={},i_={},Ya={};Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.getResultStructMetadataAnnotation=Ya.convertFieldInfos=Ya.modelDefToModelInfo=void 0;const Ka=Gi,_P=js,vP=hi,Cde=ko;function $pt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ka.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,Ka.isAtomic)(a)?{name:u,type:OD(a),default_value:bde(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:bde(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:x1(i,i.fields)},parameters:s,annotations:AP(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,_P.getResultStructDefForQuery)(t,i),o=AP(i),u=s.resultMetadata?DD(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:x1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,_P.getResultStructDefForQuery)(t,r),s=AP(r),o=i.resultMetadata?DD(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:x1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ya.modelDefToModelInfo=$pt;function bde(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function AP(t){return(0,vP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function x1(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,vP.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,Ka.isTurtle)(u)){const x=(0,_P.getResultStructDefForView)(t,u),d=x.resultMetadata?DD(x,x.resultMetadata):void 0,p=[...f??[],...d?[d]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:x1(x,x.fields)}};o.push(m)}else if((0,Ka.isAtomic)(u)){const x=(0,Ka.expressionIsAggregate)(u.expressionType),d=(0,Ka.expressionIsScalar)(u.expressionType);if(!x&&!d||u.type==="error")continue;const p=u.resultMetadata?Tde(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:OD(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,Ka.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:x1(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ya.convertFieldInfos=x1;function Tde(t,e){const r=Cde.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:kpt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Bpt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function kpt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Bpt(t)}\``}function DD(t,e){var r,i;const s=Cde.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ya.getResultStructMetadataAnnotation=DD;function OD(t){if((0,Ka.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Mpt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Ppt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ka.isRepeatedRecord)(t))return{kind:"array_type",element_type:Rde(t)};if(t.type==="record")return Rde(t);if(t.type==="array")return{kind:"array_type",element_type:OD(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Rde(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Tde(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,vP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ka.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:OD(e)};throw new Error("Expected record type to not have a table as its child")})}}function Mpt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Ppt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function rmt(t){return t}function imt(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=ko,r=hi,i=Ya,s=jr;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(d){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:d},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(d){const p=`${x.name}:${d}`,m=await x.fetchSchemaForTables({[p]:d},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(d,p)=>{const m=await x.runSQL(d);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,d){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const _=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:_}:{kind:"timestamp_cell",timestamp_value:_}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(_=>p(_,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const _=E.type;if(_.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:_.fields.map(v=>({kind:"dimension",...v}))}})}}}function m(y,E){const _=[];for(const v of E.schema.fields){const A=y[v.name];if(v.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const S=p(A,v);_.push(S)}return{kind:"record_cell",record_value:_}}const g={kind:"join",schema:d,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const d=x._queryResult.structs,p=d[d.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,d){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:d}})}t.mapLogs=f})(i_);var Upt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),jpt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),qpt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Upt(e,t,r);return jpt(e,t),e};Object.defineProperty(f1,"__esModule",{value:!0}),f1.malloyToQuery=f1.MalloyToQuery=void 0;const Hpt=Gd,Nn=qpt(I),Dde=O2,s_=Mn,zpt=Ze,Qpt=KE,Ode=Jn,Gpt=i_,SP="Malloy query documents";class wde extends Hpt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,Ode.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Dde.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${SP}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${SP} may only have one run statement`);return i===void 0?(this.illegal(e,`${SP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,s_.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Nn.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Nn.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Nn.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Nn.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Nn.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Nn.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Nn.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Nn.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Nn.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Nn.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Nn.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Nn.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Nn.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,s_.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Nn.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,s_.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Nn.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Nn.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,s_.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,zpt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,s_.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Nn.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Nn.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Nn.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof Nn.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Nn.ExprFieldPathContext&&i instanceof Nn.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Nn.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}f1.MalloyToQuery=wde;function Wpt(t){const e=(0,Ode.getSourceInfo)(t),r=new Dde.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Qpt.runMalloyParser)(t,i,e,r),u=new wde(s,r).visit(s.root),a=(0,Gpt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}f1.malloyToQuery=Wpt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Wc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=c1;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=f1;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(V4);var $e={},wD={};Object.defineProperty(wD,"__esModule",{value:!0}),wD.MALLOY_VERSION=void 0,wD.MALLOY_VERSION="0.0.274",Object.defineProperty($e,"__esModule",{value:!0}),$e.InMemoryModelCache=$e.CacheManager=$e.CSVWriter=$e.JSONWriter=$e.DataWriter=$e.DataRecord=$e.DataArray=$e.Result=$e.ExploreMaterializer=$e.PreparedResultMaterializer=$e.QueryMaterializer=$e.ModelMaterializer=$e.SingleConnectionRuntime=$e.ConnectionRuntime=$e.Runtime=$e.ExploreField=$e.JoinRelationship=$e.QueryField=$e.Query=$e.StringField=$e.UnsupportedField=$e.JSONField=$e.BooleanField=$e.NumberField=$e.TimestampField=$e.DateField=$e.TimestampTimeframe=$e.DateTimeframe=$e.AtomicField=$e.AtomicFieldType=$e.Explore=$e.SourceRelationship=$e.FixedConnectionMap=$e.InMemoryURLReader=$e.EmptyURLReader=$e.PreparedResult=$e.DocumentCompletion=$e.DocumentSymbol=$e.DocumentPosition=$e.DocumentRange=$e.DocumentTablePath=$e.Parse=$e.PreparedQuery=$e.Model=$e.MalloyError=$e.Malloy=void 0;const Fde=V4,gi=Gi,Nde=jr,CP=y2,Vpt=wD,Ypt=_2,Pn=hi,Kpt=y0,Jpt=Jn,Xpt=YE,Lde="internal://internal.malloy";let b0=class rO{static get version(){return Vpt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(Lde));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new Fde.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new $de(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return rO._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return MD(r,e).then(({contents:u,invalidationKey:a})=>rO._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var d,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(Lde));const _={};if(r===void 0&&x!==void 0){const S=await x.getCachedModelDef(s,e.toString());if(S)return new d1(S.modelDef,[],[e.toString(),...kD(S.modelDef.dependencies)])}f??(f=e);let v;const A=e.toString();if(i!==void 0){v=i._translator;const S=(d=i._invalidationKey)!==null&&d!==void 0?d:await kP(s,e);_[A]=S}else{if(r===void 0){const{contents:S,invalidationKey:b}=await MD(s,e);_[A]=b,r=S}else{const S=await kP(s,e);_[A]=S}v=new Fde.MalloyTranslator(A,f.toString(),{urls:{[A]:r}},c)}for(;;){const S=v.translate(u==null?void 0:u._modelDef);if(S.final)if(S.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:S.modelDef,invalidationKeys:_}));for(const b of v.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:_}));return new d1(S.modelDef,S.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=S.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},C=(u==null?void 0:u._modelDef)||b;return new d1(C,S.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=S.fromSources)!==null&&y!==void 0?y:[]])}else{const b=S.problems||[],C=v.prettyErrors();throw new Ide(`Error(s) compiling model:
1864
+ ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,fpt.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,yP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,yP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Wc.MalloyTranslation=EP;class vde extends EP{constructor(e,r){super(e),this.root=r}}Wc.MalloyChildTranslator=vde;class Npt extends EP{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new gP.Zone,this.importZone=new gP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new gP.Zone,this.root=this,this.logger=new _de.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,_de.makeLogMessage)(e,r,{severity:"error",...i})),e}}Wc.MalloyTranslator=Npt;function Ade(t){return[...Object.keys(t),...Object.keys(t).map(e=>Ade(t[e])).flat()]}var c1={};Object.defineProperty(c1,"__esModule",{value:!0}),c1.exploreQueryWalkerBuilder=c1.ExploreQueryWalker=void 0;const Lpt=R0;class Sde{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}c1.ExploreQueryWalker=Sde;function Ipt(t,e){const r=new Sde(t),i=r;return Lpt.ParseTreeWalker.DEFAULT.walk(i,e),r}c1.exploreQueryWalkerBuilder=Ipt;var f1={},i_={},Ya={};Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.getResultStructMetadataAnnotation=Ya.convertFieldInfos=Ya.modelDefToModelInfo=void 0;const Ka=Gi,_P=js,vP=hi,Cde=ko;function $pt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ka.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,Ka.isAtomic)(a)?{name:u,type:OD(a),default_value:bde(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:bde(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:x1(i,i.fields)},parameters:s,annotations:AP(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,_P.getResultStructDefForQuery)(t,i),o=AP(i),u=s.resultMetadata?DD(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:x1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,_P.getResultStructDefForQuery)(t,r),s=AP(r),o=i.resultMetadata?DD(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:x1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ya.modelDefToModelInfo=$pt;function bde(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function AP(t){return(0,vP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function x1(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,vP.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,Ka.isTurtle)(u)){const x=(0,_P.getResultStructDefForView)(t,u),d=x.resultMetadata?DD(x,x.resultMetadata):void 0,p=[...f??[],...d?[d]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:x1(x,x.fields)}};o.push(m)}else if((0,Ka.isAtomic)(u)){const x=(0,Ka.expressionIsAggregate)(u.expressionType),d=(0,Ka.expressionIsScalar)(u.expressionType);if(!x&&!d||u.type==="error")continue;const p=u.resultMetadata?Tde(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:OD(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,Ka.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:x1(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ya.convertFieldInfos=x1;function Tde(t,e){const r=Cde.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:kpt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Bpt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function kpt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Bpt(t)}\``}function DD(t,e){var r,i;const s=Cde.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ya.getResultStructMetadataAnnotation=DD;function OD(t){if((0,Ka.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Mpt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Ppt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ka.isRepeatedRecord)(t))return{kind:"array_type",element_type:Rde(t)};if(t.type==="record")return Rde(t);if(t.type==="array")return{kind:"array_type",element_type:OD(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Rde(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Tde(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,vP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ka.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:OD(e)};throw new Error("Expected record type to not have a table as its child")})}}function Mpt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Ppt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function rmt(t){return t}function imt(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=ko,r=hi,i=Ya,s=jr;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(d){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:d},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(d){const p=`${x.name}:${d}`,m=await x.fetchSchemaForTables({[p]:d},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(d,p)=>{const m=await x.runSQL(d);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,d){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const _=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:_}:{kind:"timestamp_cell",timestamp_value:_}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(_=>p(_,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const _=E.type;if(_.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:_.fields.map(v=>({kind:"dimension",...v}))}})}}}function m(y,E){const _=[];for(const v of E.schema.fields){const A=y[v.name];if(v.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const S=p(A,v);_.push(S)}return{kind:"record_cell",record_value:_}}const g={kind:"join",schema:d,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const d=x._queryResult.structs,p=d[d.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,d){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:d}})}t.mapLogs=f})(i_);var Upt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),jpt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),qpt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Upt(e,t,r);return jpt(e,t),e};Object.defineProperty(f1,"__esModule",{value:!0}),f1.malloyToQuery=f1.MalloyToQuery=void 0;const Hpt=Gd,Nn=qpt(I),Dde=O2,s_=Mn,zpt=Ze,Qpt=KE,Ode=Jn,Gpt=i_,SP="Malloy query documents";class wde extends Hpt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,Ode.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Dde.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${SP}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${SP} may only have one run statement`);return i===void 0?(this.illegal(e,`${SP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,s_.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Nn.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Nn.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Nn.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Nn.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Nn.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Nn.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Nn.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Nn.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Nn.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Nn.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Nn.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Nn.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Nn.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,s_.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Nn.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,s_.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Nn.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Nn.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,s_.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,zpt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,s_.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Nn.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Nn.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Nn.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof Nn.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Nn.ExprFieldPathContext&&i instanceof Nn.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Nn.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}f1.MalloyToQuery=wde;function Wpt(t){const e=(0,Ode.getSourceInfo)(t),r=new Dde.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Qpt.runMalloyParser)(t,i,e,r),u=new wde(s,r).visit(s.root),a=(0,Gpt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}f1.malloyToQuery=Wpt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Wc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=c1;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=f1;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(V4);var $e={},wD={};Object.defineProperty(wD,"__esModule",{value:!0}),wD.MALLOY_VERSION=void 0,wD.MALLOY_VERSION="0.0.275",Object.defineProperty($e,"__esModule",{value:!0}),$e.InMemoryModelCache=$e.CacheManager=$e.CSVWriter=$e.JSONWriter=$e.DataWriter=$e.DataRecord=$e.DataArray=$e.Result=$e.ExploreMaterializer=$e.PreparedResultMaterializer=$e.QueryMaterializer=$e.ModelMaterializer=$e.SingleConnectionRuntime=$e.ConnectionRuntime=$e.Runtime=$e.ExploreField=$e.JoinRelationship=$e.QueryField=$e.Query=$e.StringField=$e.UnsupportedField=$e.JSONField=$e.BooleanField=$e.NumberField=$e.TimestampField=$e.DateField=$e.TimestampTimeframe=$e.DateTimeframe=$e.AtomicField=$e.AtomicFieldType=$e.Explore=$e.SourceRelationship=$e.FixedConnectionMap=$e.InMemoryURLReader=$e.EmptyURLReader=$e.PreparedResult=$e.DocumentCompletion=$e.DocumentSymbol=$e.DocumentPosition=$e.DocumentRange=$e.DocumentTablePath=$e.Parse=$e.PreparedQuery=$e.Model=$e.MalloyError=$e.Malloy=void 0;const Fde=V4,gi=Gi,Nde=jr,CP=y2,Vpt=wD,Ypt=_2,Pn=hi,Kpt=y0,Jpt=Jn,Xpt=YE,Lde="internal://internal.malloy";let b0=class rO{static get version(){return Vpt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(Lde));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new Fde.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new $de(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return rO._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return MD(r,e).then(({contents:u,invalidationKey:a})=>rO._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var d,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(Lde));const _={};if(r===void 0&&x!==void 0){const S=await x.getCachedModelDef(s,e.toString());if(S)return new d1(S.modelDef,[],[e.toString(),...kD(S.modelDef.dependencies)])}f??(f=e);let v;const A=e.toString();if(i!==void 0){v=i._translator;const S=(d=i._invalidationKey)!==null&&d!==void 0?d:await kP(s,e);_[A]=S}else{if(r===void 0){const{contents:S,invalidationKey:b}=await MD(s,e);_[A]=b,r=S}else{const S=await kP(s,e);_[A]=S}v=new Fde.MalloyTranslator(A,f.toString(),{urls:{[A]:r}},c)}for(;;){const S=v.translate(u==null?void 0:u._modelDef);if(S.final)if(S.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:S.modelDef,invalidationKeys:_}));for(const b of v.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:_}));return new d1(S.modelDef,S.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=S.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},C=(u==null?void 0:u._modelDef)||b;return new d1(C,S.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=S.fromSources)!==null&&y!==void 0?y:[]])}else{const b=S.problems||[],C=v.prettyErrors();throw new Ide(`Error(s) compiling model:
1865
1865
  ${C}`,b)}else{if(S.urls)for(const C of S.urls)try{if(PD(C))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(x!==void 0){const D=await x.getCachedModelDef(s,C);if(D){for(const k in D.invalidationKeys)_[k]=D.invalidationKeys[k];v.update({translations:{[C]:D.modelDef}});continue}}const{contents:R,invalidationKey:O}=await MD(s,new URL(C)),B={[C]:R};_[C]=O,v.update({urls:B})}catch(R){v.update({errors:{urls:{[C]:R.message}}})}const{modelAnnotation:b}=v.modelAnnotation(u==null?void 0:u._modelDef);if(S.tables){const C=new Map;for(const R in S.tables){const{connectionName:O,tablePath:B}=S.tables[R],D=C.get(O);D===void 0?C.set(O,{[R]:B}):D[R]=B}for(const[R,O]of C)try{const B=await o.lookupConnection(R),{schemas:D,errors:k}=await rO.safelyFetchTableSchema(B,O,{refreshTimestamp:E,modelAnnotation:b});v.update({tables:D,errors:{tables:k}})}catch(B){const D={},k={};for(const M in O)k[M]=B.toString();v.update({tables:D,errors:{tables:k}})}}if(S.compileSQL){const C=S.compileSQL,R=C.connection,O=(0,Kpt.sqlKey)(C.connection,C.selectStr);try{const D=await(await o.lookupConnection(R)).fetchSchemaForSQLStruct(C,{refreshTimestamp:E,modelAnnotation:b});D.error&&v.update({errors:{compileSQL:{[O]:D.error}}}),D.structDef&&v.update({compileSQL:{[O]:D.structDef}})}catch(B){const D={};D[O]=B.toString(),v.update({errors:{compileSQL:D}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new a_({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new a_({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new Vs(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new Ud(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};$e.Malloy=b0;class Ide extends Error{constructor(e,r=[]){super(e),this.problems=r}}$e.MalloyError=Ide;class d1{constructor(e,r,i){var s,o;this.modelDef=e,this.problems=r,this.fromSources=i,this.references=new Xpt.ReferenceList((s=i[0])!==null&&s!==void 0?s:"",(o=e.references)!==null&&o!==void 0?o:[])}tagParse(e){return(0,Pn.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this.references.find(e)}getImport(e){var r;return(r=this.modelDef.imports)===null||r===void 0?void 0:r.find(i=>(0,Jpt.locationContainsPosition)(i.location,e))}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new h1(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new h1(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new h1(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if((0,gi.isSourceDef)(r))return new Vs(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(gi.isSourceDef).map(e=>new Vs(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}$e.Model=d1;class h1{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,Pn.annotationToTag)(this._modelDef.annotation).tag;return e=(0,Pn.addModelScope)(e,r),(0,Pn.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new gi.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new o_({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,gi.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}$e.PreparedQuery=h1;class $de{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new FD(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new Bde(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new kde(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}$e.Parse=$de;class Bde{constructor(e){this._range=p1.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}$e.DocumentTablePath=Bde;class p1{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new p1(new bP(e.start.line,e.start.character),new bP(e.end.line,e.end.character))}}$e.DocumentRange=p1;class bP{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}$e.DocumentPosition=bP;class FD{constructor(e){this._range=p1.fromJSON(e.range),this._lensRange=e.lensRange?p1.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new FD(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}$e.DocumentSymbol=FD;class kde{constructor(e){this.type=e.type,this.text=e.text}}$e.DocumentCompletion=kde;class o_{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new o_(e,r)}tagParse(e){const r=(0,Pn.annotationToTag)(this.modelDef.annotation).tag;return e=(0,Pn.addModelScope)(e,r),(0,Pn.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,Pn.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new Vs(r,this.sourceExplore)}catch{return new Vs(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,gi.isSourceDef)(r))return new Vs(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}$e.PreparedResult=o_;class Mde{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}$e.EmptyURLReader=Mde;class Zpt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return PD(e.toString())?null:Zde(r)}}$e.InMemoryURLReader=Zpt;class ND{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new ND(new Map(e.map(r=>[r.name,r])))}}$e.FixedConnectionMap=ND;var Pde;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(Pde||($e.SourceRelationship=Pde={}));class TP{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Vs}isQuery(){return this instanceof LP}}class Vs extends TP{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,gi.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,Pn.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,Pn.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i={type:"query",structRef:r,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new h1(i,this.modelDef,[],e)}get modelDef(){if(!(0,gi.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new d1(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,gi.isJoined)(i))return[s,new IP(i,this,o)];if(i.type==="turtle")return[s,new LP(i,this,o)];if(i.type==="string")return[s,new NP(i,this,o)];if(i.type==="number")return[s,new LD(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new LD({...i,type:"number"},this,o)]:[s,new RP(i,this,o)];if(i.type==="timestamp")return[s,new DP(i,this,o)];if(i.type==="boolean")return[s,new OP(i,this,o)];if(i.type==="json")return[s,new wP(i,this,o)];if(i.type==="sql native")return[s,new FP(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(u=>{if(typeof u.field=="string")return{field:this.fieldMap.get(u.field),dir:u.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(u=>u.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(u=>!o.has(u.name)).map(u=>({field:u,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof IP}get filters(){var e;return(0,gi.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,gi.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?Vs.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?Vs.fromJSON(e.sourceExplore):void 0;return new Vs(e._structDef,r,i)}get location(){return this.structDef.location}}$e.Explore=Vs;var Ja;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(Ja||($e.AtomicFieldType=Ja={}));class pf extends TP{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return Ja.String;case"boolean":return Ja.Boolean;case"date":return Ja.Date;case"timestamp":return Ja.Timestamp;case"number":return Ja.Number;case"json":return Ja.Json;case"sql native":return Ja.NativeUnsupported;case"error":return Ja.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,Pn.addModelScope)(e,this.parent.modelTag),(0,Pn.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,gi.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,gi.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof NP}isNumber(){return this instanceof LD}isDate(){return this instanceof RP}isBoolean(){return this instanceof OP}isJSON(){return this instanceof wP}isTimestamp(){return this instanceof DP}isUnsupported(){return this instanceof FP}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}$e.AtomicField=pf;var Pd;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Pd||($e.DateTimeframe=Pd={}));var Xa;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(Xa||($e.TimestampTimeframe=Xa={}));class RP extends pf{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Pd.Day;case"week":return Pd.Week;case"month":return Pd.Month;case"quarter":return Pd.Quarter;case"year":return Pd.Year}}}$e.DateField=RP;class DP extends pf{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Xa.Day;case"week":return Xa.Week;case"month":return Xa.Month;case"quarter":return Xa.Quarter;case"year":return Xa.Year;case"second":return Xa.Second;case"hour":return Xa.Hour;case"minute":return Xa.Minute}}}$e.TimestampField=DP;class LD extends pf{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}}$e.NumberField=LD;class OP extends pf{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}}$e.BooleanField=OP;class wP extends pf{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}}$e.JSONField=wP;class FP extends pf{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}$e.UnsupportedField=FP;class NP extends pf{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}}$e.StringField=NP;class Ude extends TP{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}$e.Query=Ude;class LP extends Ude{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,Pn.addModelScope)(e,this.parent.modelTag),(0,Pn.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}$e.QueryField=LP;var m1;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(m1||($e.JoinRelationship=m1={}));class IP extends Vs{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,gi.isJoined)(this.structDef))switch(this.structDef.join){case"one":return m1.OneToOne;case"many":case"cross":return m1.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===m1.OneToOne}get isArray(){return this.joinRelationship!==m1.OneToOne}tagParse(e){return e=(0,Pn.addModelScope)(e,this._parentExplore.modelTag),(0,Pn.annotationToTag)(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}$e.ExploreField=IP;class $P{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new Mde),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new u_(this,async()=>b0.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new u_(this,async()=>new d1(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}$e.Runtime=$P;class e2t extends $P{constructor({urlReader:e,connections:r}){super({connections:ND.fromArray(r),urlReader:e}),this.rawConnections=r}}$e.ConnectionRuntime=e2t;class t2t extends $P{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,CP.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,CP.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,CP.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}$e.SingleConnectionRuntime=t2t;class ID{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new jde(this.runtime,e,r)}makeExploreMaterializer(e,r){return new Hde(this.runtime,e,r)}makePreparedResultMaterializer(e){return new qde(this.runtime,e)}}class u_ extends ID{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await b0.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new u_(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await b0.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new gi.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,gi.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,gi.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
1866
1866
  run: ${e}
1867
1867
  -> ${u}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/render",
3
- "version": "0.0.274",
3
+ "version": "0.0.275",
4
4
  "license": "MIT",
5
5
  "main": "dist/module/index.umd.js",
6
6
  "types": "dist/index.d.ts",
@@ -41,9 +41,9 @@
41
41
  "generate-flow": "ts-node ../../scripts/gen-flow.ts"
42
42
  },
43
43
  "dependencies": {
44
- "@malloydata/malloy": "0.0.274",
45
- "@malloydata/malloy-interfaces": "0.0.274",
46
- "@malloydata/malloy-tag": "0.0.274",
44
+ "@malloydata/malloy": "0.0.275",
45
+ "@malloydata/malloy-interfaces": "0.0.275",
46
+ "@malloydata/malloy-tag": "0.0.275",
47
47
  "@tanstack/solid-virtual": "^3.10.4",
48
48
  "component-register": "^0.8.6",
49
49
  "lodash": "^4.17.20",
@@ -56,7 +56,7 @@
56
56
  "vega-lite": "^5.2.0"
57
57
  },
58
58
  "devDependencies": {
59
- "@malloydata/db-duckdb": "0.0.274",
59
+ "@malloydata/db-duckdb": "0.0.275",
60
60
  "@storybook/addon-essentials": "^8.5.8",
61
61
  "@storybook/addon-interactions": "^8.5.8",
62
62
  "@storybook/addon-links": "^8.5.8",