@malloydata/render 0.0.421 → 0.0.422

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.
@@ -81611,7 +81611,7 @@ function aF() {
81611
81611
  */
81612
81612
  getSQL(M) {
81613
81613
  const B = this.persistableDef, L = this.model.queryModel;
81614
- return B.type === "sql_select" ? (0, e.getCompiledSQL)(B, M ?? {}, (k, U) => L.compileQuery(k, U).sql) : L.compileQuery(B.query, M).sql;
81614
+ return B.type === "sql_select" ? (0, e.getCompiledSQL)(B, M ?? {}, (k, U) => L.compileQuery(k, U, !1).sql) : L.compileQuery(B.query, M, !1).sql;
81615
81615
  }
81616
81616
  /**
81617
81617
  * Get the underlying persistable source definition.
@@ -83311,7 +83311,7 @@ function Lj() {
83311
83311
  }
83312
83312
  var X1 = {}, SA = {}, zae;
83313
83313
  function s9e() {
83314
- return zae || (zae = 1, Object.defineProperty(SA, "__esModule", { value: !0 }), SA.MALLOY_VERSION = void 0, SA.MALLOY_VERSION = "0.0.421"), SA;
83314
+ return zae || (zae = 1, Object.defineProperty(SA, "__esModule", { value: !0 }), SA.MALLOY_VERSION = void 0, SA.MALLOY_VERSION = "0.0.422"), SA;
83315
83315
  }
83316
83316
  var Hae;
83317
83317
  function P1e() {
@@ -1360,14 +1360,14 @@ z\fzzט\vzzz{{{\x07{ן
1360
1360
  | ${" ".repeat(j)}^`)}else fe=`line ${q+1}: char ${j}: ${se.message}`}X!==I&&(fe=`FILE: ${I}
1361
1361
  `+fe,X=I),z!==""?z=`${z}
1362
1362
  ${fe}`:z=fe}return z}childRequest(z){var X;const se=decodeURI(new URL(z,this.sourceURL).toString()),fe=(X=this.childTranslators.get(se))===null||X===void 0?void 0:X.translate();if(fe!=null&&fe.compileSQL)return{compileSQL:fe.compileSQL}}importModelDef(z){const X=decodeURI(new URL(z,this.sourceURL).toString()),se=this.childTranslators.get(X);if(se)return se.translate().modelDef}translate(z){if(this.finalAnswer)return this.finalAnswer;const X=this.translateStep.step(this,z);return X.final&&(this.finalAnswer=X),X}translatorForDependency(z){return this.childTranslators.get(z)}importAt(z){for(let X=0;X<this.imports.length;X++){const se=this.imports[X];if((0,g.locationContainsPosition)(se.location,z))return se}}metadata(){return this.metadataStep.step(this)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(z){return this.completionsStep.step(this,z)}helpContext(z){return this.helpContextStep.step(this,z)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(z){return(0,g.rangeFromContext)(this.parseStep.sourceInfo,z)}firstReferenceToDialect(z){return this.dialectAlreadyChecked[z]?!1:(this.dialectAlreadyChecked[z]=!0,!0)}experimentalDialectEnabled(z){if(this.allDialectsEnabled)return!0;const X=this.getCompilerFlags().tag("experimental");return X!==void 0&&(X.bare()||X.has("dialect",z))}}Ks.MalloyTranslation=$;class V extends ${constructor(z,X){super(z),this.root=X}}Ks.MalloyChildTranslator=V;class K extends ${constructor(z,X=null,se=null,fe=null,I=!1){super(z,X),this.eventStream=fe,this.restrictedMode=I,this.schemaZone=new l.Zone,this.importZone=new l.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new l.Zone,this.connectionDialectZone=new l.Zone,this.root=this,this.logger=new a.BaseMessageLogger(fe),se&&this.update(se)}update(z){var X,se,fe,I;this.schemaZone.updateFrom(z.tables,(X=z.errors)===null||X===void 0?void 0:X.tables),this.importZone.updateFrom(z.urls,(se=z.errors)===null||se===void 0?void 0:se.urls),this.sqlQueryZone.updateFrom(z.compileSQL,(fe=z.errors)===null||fe===void 0?void 0:fe.compileSQL),this.connectionDialectZone.updateFrom(z.connectionDialects,(I=z.errors)===null||I===void 0?void 0:I.connectionDialects);for(const q in z.translations)this.pretranslatedModels.set(q,z.translations[q])}lockZonesIfRestricted(){this.restrictedMode&&(this.schemaZone.lock(),this.importZone.lock(),this.sqlQueryZone.lock(),this.connectionDialectZone.lock())}translate(z){return this.lockZonesIfRestricted(),super.translate(z)}logError(z,X,se){return this.logger.log((0,a.makeLogMessage)(z,X,{severity:"error",...se})),z}}Ks.MalloyTranslator=K;function ne(le){return[...Object.keys(le),...Object.keys(le).map(z=>ne(le[z])).flat()]}return Ks}var qy={},hce;function YIe(){if(hce)return qy;hce=1,Object.defineProperty(qy,"__esModule",{value:!0}),qy.ExploreQueryWalker=void 0,qy.exploreQueryWalkerBuilder=n;const e=Iy();class t{constructor(i){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=i}exploreQueryAtOffset(i){return this.exploreClauseRefs.find(s=>s.range[0]===void 0||s.range[1]===void 0?!1:s.range[0]<=i&&s.range[1]>=i)}filterAtOffset(i){const s=this.exploreQueryAtOffset(i);if(s)return s.filterRefs.find(o=>o.range[0]===void 0||o.range[1]===void 0?!1:o.range[0]<=i&&o.range[1]>=i)}hasFilterListAtOffset(i){const s=this.exploreQueryAtOffset(i);return s?!!s.filterLists.find(o=>o.range[0]===void 0||o.range[1]===void 0?!1:o.range[0]<=i&&o.range[1]>=i):!1}enterMalloyDocument(){this.inDocument=!0}}qy.ExploreQueryWalker=t;function n(r,i){const s=new t(r),o=s;return e.ParseTreeWalker.DEFAULT.walk(o,i),s}return qy}var Wa={},wk={},Uy={},xce;function Dk(){if(xce)return Uy;xce=1,Object.defineProperty(Uy,"__esModule",{value:!0}),Uy.validateCanonicalTablePath=t,Uy.validateCanonicalTablePathAnyDialect=n,Uy.requireCanonicalTablePathAnyDialect=r;const e=u4();function t(i,s){let o;try{o=(0,e.getDialect)(i)}catch{return`tablePath '${s}' cannot be validated: unknown dialect '${i}'`}const a=o.sqlValidateTableName(s);if(!a.ok)return`tablePath '${s}' is not canonical SQL for the ${i} dialect; the translator must validate before passing it here. (${a.error})`;if(a.canonical!==s)return`tablePath '${s}' is not canonical SQL for the ${i} dialect; the translator must validate before passing it here.`}function n(i){let s;for(const o of(0,e.getDialects)()){const a=o.sqlValidateTableName(i);if(a.ok){if(a.canonical===i)return;s===void 0&&(s=a.canonical)}}return s!==void 0?`value '${i}' is not canonical SQL; did you mean '${s}'?`:`value '${i}' is not a valid canonical table path in any registered dialect`}function r(i,s){const o=n(i);if(o!==void 0)throw new Error(`${s}: ${o}`)}return Uy}var to={},F1={},BA={},pce;function mce(){return pce||(pce=1,Object.defineProperty(BA,"__esModule",{value:!0}),BA.MALLOY_INTERFACE_TYPES=void 0,BA.MALLOY_INTERFACE_TYPES={Aggregate:{type:"struct",name:"Aggregate",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},Annotation:{type:"struct",name:"Annotation",fields:{value:{type:"string",optional:!1,array:!1}}},AnonymousQueryInfo:{type:"struct",name:"AnonymousQueryInfo",fields:{schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},ArrayCell:{type:"struct",name:"ArrayCell",fields:{array_value:{type:"Cell",array:!0,optional:!1}}},ArrayType:{type:"struct",name:"ArrayType",fields:{element_type:{type:"AtomicType",optional:!1,array:!1}}},AtomicType:{type:"union",name:"AtomicType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType",timestamptz_type:"TimestamptzType"}},BooleanCell:{type:"struct",name:"BooleanCell",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanLiteral:{type:"struct",name:"BooleanLiteral",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanType:{type:"struct",name:"BooleanType",fields:{}},CalculateInfo:{type:"struct",name:"CalculateInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},CalculateOperation:{type:"struct",name:"CalculateOperation",fields:{name:{type:"string",optional:!1,array:!1},field:{type:"Field",optional:!1,array:!1}}},Cell:{type:"union",name:"Cell",options:{string_cell:"StringCell",boolean_cell:"BooleanCell",date_cell:"DateCell",timestamp_cell:"TimestampCell",number_cell:"NumberCell",json_cell:"JSONCell",record_cell:"RecordCell",array_cell:"ArrayCell",null_cell:"NullCell",sql_native_cell:"SQLNativeCell"}},CompileModelRequest:{type:"struct",name:"CompileModelRequest",fields:{model_url:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileModelResponse:{type:"struct",name:"CompileModelResponse",fields:{model:{type:"ModelInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},CompileQueryRequest:{type:"struct",name:"CompileQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!0,array:!1},query_malloy:{type:"string",optional:!0,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileQueryResponse:{type:"struct",name:"CompileQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},CompileSourceRequest:{type:"struct",name:"CompileSourceRequest",fields:{model_url:{type:"string",optional:!1,array:!1},name:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileSourceResponse:{type:"struct",name:"CompileSourceResponse",fields:{source:{type:"SourceInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},CompilerNeeds:{type:"struct",name:"CompilerNeeds",fields:{table_schemas:{type:"SQLTable",array:!0,optional:!0},sql_schemas:{type:"SQLQuery",array:!0,optional:!0},files:{type:"File",array:!0,optional:!0},connections:{type:"Connection",array:!0,optional:!0},translations:{type:"Translation",array:!0,optional:!0}}},Connection:{type:"struct",name:"Connection",fields:{name:{type:"string",optional:!1,array:!1},dialect:{type:"string",optional:!0,array:!1}}},Data:{type:"union",name:"Data",options:{record_cell:"RecordCell",array_cell:"ArrayCell"}},DateCell:{type:"struct",name:"DateCell",fields:{date_value:{type:"string",optional:!1,array:!1}}},DateLiteral:{type:"struct",name:"DateLiteral",fields:{date_value:{type:"string",optional:!1,array:!1},granularity:{type:"DateTimeframe",optional:!0,array:!1},timezone:{type:"string",optional:!0,array:!1}}},DateTimeframe:{type:"enum",name:"DateTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5}},DateType:{type:"struct",name:"DateType",fields:{timeframe:{type:"DateTimeframe",optional:!0,array:!1}}},DimensionInfo:{type:"struct",name:"DimensionInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},DocumentPosition:{type:"struct",name:"DocumentPosition",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},DocumentRange:{type:"struct",name:"DocumentRange",fields:{start:{type:"DocumentPosition",optional:!1,array:!1},end:{type:"DocumentPosition",optional:!1,array:!1}}},DrillOperation:{type:"struct",name:"DrillOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},Expression:{type:"union",name:"Expression",options:{field_reference:"Reference",time_truncation:"TimeTruncationFieldReference",filtered_field:"FilteredField",literal_value:"LiteralValueExpression",moving_average:"MovingAverage"}},Field:{type:"struct",name:"Field",fields:{expression:{type:"Expression",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},FieldInfo:{type:"union",name:"FieldInfo",options:{dimension:"DimensionInfo",measure:"MeasureInfo",join:"JoinInfo",view:"ViewInfo",calculate:"CalculateInfo"}},File:{type:"struct",name:"File",fields:{url:{type:"string",optional:!1,array:!1},contents:{type:"string",optional:!0,array:!1},invalidation_key:{type:"string",optional:!0,array:!1}}},Filter:{type:"union",name:"Filter",options:{filter_string:"FilterStringApplication",literal_equality:"LiteralEqualityComparison"}},FilterExpressionLiteral:{type:"struct",name:"FilterExpressionLiteral",fields:{filter_expression_value:{type:"string",optional:!1,array:!1}}},FilterExpressionType:{type:"struct",name:"FilterExpressionType",fields:{filter_type:{type:"FilterableType",optional:!1,array:!1}}},FilterOperation:{type:"struct",name:"FilterOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},FilterStringApplication:{type:"struct",name:"FilterStringApplication",fields:{expression:{type:"Expression",optional:!1,array:!1},filter:{type:"string",optional:!1,array:!1}}},FilterableType:{type:"union",name:"FilterableType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",date_type:"DateType",timestamp_type:"TimestampType",timestamptz_type:"TimestamptzType"}},FilteredField:{type:"struct",name:"FilteredField",fields:{field_reference:{type:"Reference",optional:!1,array:!1},where:{type:"FilterOperation",array:!0,optional:!1}}},GroupBy:{type:"struct",name:"GroupBy",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},JSONCell:{type:"struct",name:"JSONCell",fields:{json_value:{type:"string",optional:!1,array:!1}}},JSONType:{type:"struct",name:"JSONType",fields:{}},JoinInfo:{type:"struct",name:"JoinInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},relationship:{type:"Relationship",optional:!1,array:!1}}},Limit:{type:"struct",name:"Limit",fields:{limit:{type:"number",optional:!1,array:!1}}},LiteralEqualityComparison:{type:"struct",name:"LiteralEqualityComparison",fields:{expression:{type:"Expression",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},LiteralValue:{type:"union",name:"LiteralValue",options:{string_literal:"StringLiteral",number_literal:"NumberLiteral",date_literal:"DateLiteral",timestamp_literal:"TimestampLiteral",boolean_literal:"BooleanLiteral",null_literal:"NullLiteral",filter_expression_literal:"FilterExpressionLiteral"}},LiteralValueExpression:{type:"struct",name:"LiteralValueExpression",fields:{literal_value:{type:"LiteralValue",optional:!1,array:!1}}},Location:{type:"struct",name:"Location",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"Range",optional:!1,array:!1}}},LogMessage:{type:"struct",name:"LogMessage",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"DocumentRange",optional:!1,array:!1},severity:{type:"LogSeverity",optional:!1,array:!1},message:{type:"string",optional:!1,array:!1}}},LogSeverity:{type:"enum",name:"LogSeverity",values:{debug:1,info:2,warn:3,error:4}},MeasureInfo:{type:"struct",name:"MeasureInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ModelEntryValue:{type:"union",name:"ModelEntryValue",options:{source:"SourceInfo",query:"QueryInfo"}},ModelInfo:{type:"struct",name:"ModelInfo",fields:{entries:{type:"ModelEntryValue",array:!0,optional:!1},annotations:{type:"Annotation",array:!0,optional:!0},anonymous_queries:{type:"AnonymousQueryInfo",array:!0,optional:!1}}},MovingAverage:{type:"struct",name:"MovingAverage",fields:{field_reference:{type:"Reference",optional:!1,array:!1},rows_preceding:{type:"number",optional:!0,array:!1},rows_following:{type:"number",optional:!0,array:!1},partition_fields:{type:"Reference",array:!0,optional:!0}}},Nest:{type:"struct",name:"Nest",fields:{name:{type:"string",optional:!0,array:!1},view:{type:"View",optional:!1,array:!1}}},NullCell:{type:"struct",name:"NullCell",fields:{}},NullLiteral:{type:"struct",name:"NullLiteral",fields:{}},NumberCell:{type:"struct",name:"NumberCell",fields:{number_value:{type:"number",optional:!1,array:!1},subtype:{type:"NumberSubtype",optional:!0,array:!1},string_value:{type:"string",optional:!0,array:!1}}},NumberLiteral:{type:"struct",name:"NumberLiteral",fields:{number_value:{type:"number",optional:!1,array:!1},string_value:{type:"string",optional:!0,array:!1}}},NumberSubtype:{type:"enum",name:"NumberSubtype",values:{integer:1,decimal:2,bigint:3}},NumberType:{type:"struct",name:"NumberType",fields:{subtype:{type:"NumberSubtype",optional:!0,array:!1}}},OrderBy:{type:"struct",name:"OrderBy",fields:{field_reference:{type:"Reference",optional:!1,array:!1},direction:{type:"OrderByDirection",optional:!0,array:!1}}},OrderByDirection:{type:"enum",name:"OrderByDirection",values:{asc:1,desc:2}},ParameterInfo:{type:"struct",name:"ParameterInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"ParameterType",optional:!1,array:!1},default_value:{type:"LiteralValue",optional:!0,array:!1}}},ParameterType:{type:"union",name:"ParameterType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType",filter_expression_type:"FilterExpressionType",timestamptz_type:"TimestamptzType"}},ParameterValue:{type:"struct",name:"ParameterValue",fields:{name:{type:"string",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},Position:{type:"struct",name:"Position",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},Query:{type:"struct",name:"Query",fields:{definition:{type:"QueryDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},QueryArrow:{type:"struct",name:"QueryArrow",fields:{source:{type:"QueryArrowSource",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},QueryArrowSource:{type:"union",name:"QueryArrowSource",options:{refinement:"QueryRefinement",source_reference:"Reference"}},QueryDefinition:{type:"union",name:"QueryDefinition",options:{arrow:"QueryArrow",query_reference:"Reference",refinement:"QueryRefinement"}},QueryInfo:{type:"struct",name:"QueryInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},QueryRefinement:{type:"struct",name:"QueryRefinement",fields:{base:{type:"QueryDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},Range:{type:"struct",name:"Range",fields:{start:{type:"Position",optional:!1,array:!1},end:{type:"Position",optional:!1,array:!1}}},RecordCell:{type:"struct",name:"RecordCell",fields:{record_value:{type:"Cell",array:!0,optional:!1}}},RecordType:{type:"struct",name:"RecordType",fields:{fields:{type:"DimensionInfo",array:!0,optional:!1}}},Reference:{type:"struct",name:"Reference",fields:{name:{type:"string",optional:!1,array:!1},path:{type:"string",array:!0,optional:!0},parameters:{type:"ParameterValue",array:!0,optional:!0}}},Relationship:{type:"enum",name:"Relationship",values:{one:1,many:2,cross:3}},Result:{type:"struct",name:"Result",fields:{data:{type:"Data",optional:!0,array:!1},schema:{type:"Schema",optional:!1,array:!1},sql:{type:"string",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},model_annotations:{type:"Annotation",array:!0,optional:!0},query_timezone:{type:"string",optional:!0,array:!1},source_annotations:{type:"Annotation",array:!0,optional:!0}}},RunIndexQueryRequest:{type:"struct",name:"RunIndexQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},source_name:{type:"string",optional:!1,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunIndexQueryResponse:{type:"struct",name:"RunIndexQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},RunQueryRequest:{type:"struct",name:"RunQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!0,array:!1},query_malloy:{type:"string",optional:!0,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryResponse:{type:"struct",name:"RunQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},SQLNativeCell:{type:"struct",name:"SQLNativeCell",fields:{sql_native_value:{type:"string",optional:!1,array:!1}}},SQLNativeType:{type:"struct",name:"SQLNativeType",fields:{sql_type:{type:"string",optional:!0,array:!1}}},SQLQuery:{type:"struct",name:"SQLQuery",fields:{sql:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},SQLTable:{type:"struct",name:"SQLTable",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},Schema:{type:"struct",name:"Schema",fields:{fields:{type:"FieldInfo",array:!0,optional:!1}}},SourceInfo:{type:"struct",name:"SourceInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},parameters:{type:"ParameterInfo",array:!0,optional:!0}}},StringCell:{type:"struct",name:"StringCell",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringLiteral:{type:"struct",name:"StringLiteral",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringType:{type:"struct",name:"StringType",fields:{}},TimeTruncationFieldReference:{type:"struct",name:"TimeTruncationFieldReference",fields:{field_reference:{type:"Reference",optional:!1,array:!1},truncation:{type:"TimestampTimeframe",optional:!1,array:!1}}},TimestampCell:{type:"struct",name:"TimestampCell",fields:{timestamp_value:{type:"string",optional:!1,array:!1}}},TimestampLiteral:{type:"struct",name:"TimestampLiteral",fields:{timestamp_value:{type:"string",optional:!1,array:!1},granularity:{type:"TimestampTimeframe",optional:!0,array:!1},timezone:{type:"string",optional:!0,array:!1}}},TimestampTimeframe:{type:"enum",name:"TimestampTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5,hour:6,minute:7,second:8}},TimestampType:{type:"struct",name:"TimestampType",fields:{timeframe:{type:"TimestampTimeframe",optional:!0,array:!1}}},TimestamptzType:{type:"struct",name:"TimestamptzType",fields:{timeframe:{type:"TimestampTimeframe",optional:!0,array:!1}}},TimingInfo:{type:"struct",name:"TimingInfo",fields:{name:{type:"string",optional:!1,array:!1},duration_ms:{type:"number",optional:!1,array:!1},detailed_timing:{type:"TimingInfo",array:!0,optional:!0}}},Translation:{type:"struct",name:"Translation",fields:{url:{type:"string",optional:!1,array:!1},compiled_model_json:{type:"string",optional:!0,array:!1}}},View:{type:"struct",name:"View",fields:{definition:{type:"ViewDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ViewArrow:{type:"struct",name:"ViewArrow",fields:{source:{type:"ViewDefinition",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},ViewDefinition:{type:"union",name:"ViewDefinition",options:{arrow:"ViewArrow",view_reference:"Reference",refinement:"ViewRefinement",segment:"ViewSegment"}},ViewInfo:{type:"struct",name:"ViewInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"View",optional:!0,array:!1}}},ViewOperation:{type:"union",name:"ViewOperation",options:{group_by:"GroupBy",aggregate:"Aggregate",order_by:"OrderBy",limit:"Limit",where:"FilterOperation",nest:"Nest",having:"FilterOperation",drill:"DrillOperation",calculate:"CalculateOperation"}},ViewRefinement:{type:"struct",name:"ViewRefinement",fields:{base:{type:"ViewDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},ViewSegment:{type:"struct",name:"ViewSegment",fields:{operations:{type:"ViewOperation",array:!0,optional:!1}}}}),BA}var qA={},rw={},UA={},gce;function KIe(){return gce||(gce=1,Object.defineProperty(UA,"__esModule",{value:!0}),UA.RESERVED_WORDS=void 0,UA.RESERVED_WORDS=["all","and","as","asc","avg","boolean","by","case","cast","compose","count","date","day","days","desc","distinct","else","end","exclude","export","extend","false","filter","for","from","full","has","hour","hours","import","in","include","inner","internal","is","json","left","like","max","min","minute","minutes","month","months","not","now","null","number","on","or","pick","private","public","quarter","quarters","right","second","seconds","source","sql","string","sum","table","then","this","timestamp","timestamptz","to","true","virtual","week","weeks","when","with","year","years"]),UA}var yce;function XIe(){if(yce)return rw;yce=1,Object.defineProperty(rw,"__esModule",{value:!0}),rw.maybeQuoteIdentifier=n;const e=KIe();function t(r){const i=!r.match(/^[A-Za-z_][A-Za-z_0-9]*$/),s=e.RESERVED_WORDS.includes(r.toLowerCase());return i||s}function n(r){return t(r)?`\`${r}\``:r}return rw}var Ece;function JIe(){if(Ece)return qA;Ece=1,Object.defineProperty(qA,"__esModule",{value:!0}),qA.queryToMalloy=t,qA.filterToMalloy=n;const e=XIe();function t(L,{tabWidth:k}={tabWidth:2}){const U=m(L);return a(U,{tabWidth:k})}function n(L,{tabWidth:k}={tabWidth:2}){const U=q(L);return a(U,{tabWidth:k})}const r=Symbol("indent"),i=Symbol("newline"),s=Symbol("outdent"),o=Symbol("optional_newline_indent");function a(L,{tabWidth:k}={tabWidth:2}){let U="",Q=0,J=!0;for(const W of L)if(W===i)U+=`
1363
- `,J=!0;else if(W===s)Q--;else if(W===r)Q++;else{if(W===o)continue;J&&(U+=" ".repeat(Q*k),J=!1),U+=W}return U}function u(L,k,U,Q){var J;if(k.includes(i))return[L,i,r,...k,i,s,U];const ie=((J=Q==null?void 0:Q.spaces)!==null&&J!==void 0?J:!0)?" ":"";return[L,ie,...k,ie,U]}function c(L){return{contents:L,quoteCharacter:'"'}}function l(L,k){const U=[];for(let Q=0;Q<L.length;Q++){const J=L[Q];U.push(J),Q<L.length-1&&U.push(k)}return U}function f(L){var k,U;switch(L.kind){case"filter_expression_literal":return[fe(L.filter_expression_value)];case"boolean_literal":return[L.boolean_value.toString()];case"string_literal":{const{contents:Q,quoteCharacter:J}=c(L.string_value);return[J,Q,J]}case"number_literal":return[L.number_value.toString()];case"null_literal":return["null"];case"date_literal":return[p(d(L.date_value),(k=L.granularity)!==null&&k!==void 0?k:"day",L.timezone)];case"timestamp_literal":return[p(d(L.timestamp_value),(U=L.granularity)!==null&&U!==void 0?U:"second",L.timezone)]}}function d(L){let k;if(k=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)/.exec(L)){const[U,Q,J,W,ie,ae,de]=k;return[Q,J,W,ie,ae,de]}else if(k=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d)/.exec(L)){const[U,Q,J,W,ie,ae]=k;return[Q,J,W,ie,ae,"00"]}else if(k=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d)(?:00)?/.exec(L)){const[U,Q,J,W,ie]=k;return[Q,J,W,ie,"00","00"]}else if(k=/(\d\d\d\d)-(\d\d)-(\d\d)/.exec(L)){const[U,Q,J,W]=k;return[Q,J,W,"00","00","00"]}else if(k=/(\d\d\d\d)-(\d\d)/.exec(L)){const[U,Q,J]=k;return[Q,J,"01","00","00","00"]}else if(k=/(\d\d\d\d)/.exec(L)){const[U,Q]=k;return[Q,"01","01","00","00","00"]}return["1970","01","01","00","00","00"]}function p([L,k,U,Q,J,W],ie,ae){switch(ie){case"year":return`@${L}`;case"quarter":{const de=Math.floor(+k/3)+1;return`@${L}-Q${de}`}case"month":return`@${L}-${k}`;case"week":return`@${L}-${k}-${U}-WK`;case"day":return`@${L}-${k}-${U}`;case"hour":return`@${L}-${k}-${U} ${Q}`;case"minute":return`@${L}-${k}-${U} ${Q}:${J}`;case"second":return ae!==void 0?`@${L}-${k}-${U} ${Q}:${J}:${W}[${ae}]`:`@${L}-${k}-${U} ${Q}:${J}:${W}`;default:throw new Error("Unknown timeframe.")}}function x(L){var k;const U=[];for(const Q of(k=L.path)!==null&&k!==void 0?k:[])U.push((0,e.maybeQuoteIdentifier)(Q)),U.push(".");if(U.push((0,e.maybeQuoteIdentifier)(L.name)),L.parameters){const Q=[];for(let J=0;J<L.parameters.length;J++){const W=L.parameters[J];Q.push((0,e.maybeQuoteIdentifier)(W.name)),Q.push(" is "),Q.push(...f(W.value)),J<L.parameters.length-1&&Q.push(",",i)}U.push(...u("(",Q,")",{spaces:!1}))}return U}function m(L){const k=[];return k.push(...M(L.annotations)),k.push("run: "),k.push(...y(L.definition)),k}function g(L){const k=[];switch(L.kind){case"source_reference":{k.push(...x(L));break}case"refinement":k.push(...y(L));break}return k}function y(L){const k=[];switch(L.kind){case"arrow":{k.push(...g(L.source)),k.push(" -> "),k.push(...E(L.view));break}case"query_reference":{k.push(...x(L));break}case"refinement":{const U=y(L.base);L.base.kind==="arrow"?k.push(...u("(",U,")",{spaces:!1})):k.push(...U),k.push(" + "),k.push(...E(L.refinement));break}}return k}function E(L){const k=[];switch(L.kind){case"arrow":{k.push(...E(L.source)),k.push(" -> "),k.push(...E(L.view));break}case"view_reference":{k.push(...x(L));break}case"refinement":{k.push(...E(L.base)),k.push(" + "),k.push(...E(L.refinement));break}case"segment":{k.push(...v(L));break}}return k}function v(L){if(L.operations.length===0)return["{ }"];const k=L.operations.length>1,U=[];for(let Q=0;Q<L.operations.length;Q++){const J=L.operations[Q],W=[J];for(;Q<L.operations.length-1;){const ie=L.operations[Q+1];if(ie.kind===J.kind)W.push(ie),Q++;else break}U.push(...S(W)),k&&Q<L.operations.length-1&&U.push(i)}return u("{",U,"}")}function S(L){switch(L[0].kind){case"aggregate":return R(L,"aggregate");case"group_by":return R(L,"group_by");case"order_by":return O(L);case"nest":return F(L);case"limit":return ne(L);case"where":return le(L);case"having":return X(L);case"drill":return z(L);case"calculate":return R(L,"calculate")}}function b(L,k,U=""){const Q=[];Q.push(`${L}:`);const J=k.length>1||k.some(W=>W.includes(i));J?Q.push(i,r):Q.push(" ");for(let W=0;W<k.length;W++){const ie=k[W];Q.push(...ie),k.length>1&&W<k.length-1&&Q.push(U),J&&W<k.length-1&&Q.push(i)}return J&&Q.push(s),Q}function C(L){const k=[];return k.push(...T(L.expression)),k}function _(L){return L}function T(L){var k;switch(L.kind){case"field_reference":return x(L);case"time_truncation":return[...x(L.field_reference),".",L.truncation];case"filtered_field":return[...x(L.field_reference),...u(" {",le(L.where),"}")];case"literal_value":return f(L.literal_value);case"moving_average":{const U=["avg_moving",...u("(",[...x(L.field_reference),L.rows_preceding!==void 0?`, ${L.rows_preceding}`:", 0",L.rows_following!==void 0?`, ${L.rows_following}`:""],")",{spaces:!1})];return!((k=L.partition_fields)===null||k===void 0)&&k.length&&U.push(...u(" {",["partition_by",": ",...l(L.partition_fields.flatMap(Q=>x(Q)),", ")],"}")),U}}}function w(L,k=!1){const U=[];return k||U.push(...M(L.field.annotations)),L.name&&(U.push((0,e.maybeQuoteIdentifier)(L.name)),U.push(" is ")),U.push(...C(L.field)),U}function R(L,k){const U=[],Q=L.length===1;return Q&&U.push(...M(L[0].field.annotations)),U.push(...b(k,L.map(J=>w(J,Q)))),U}function O(L){return b("order_by",L.map(N),",")}function N(L){const k=[];return k.push(...x(L.field_reference)),L.direction&&(k.push(" "),k.push(L.direction)),k}function F(L){const k=[],U=L.length===1;return U&&k.push(...M(L[0].view.annotations)),k.push(...b("nest",L.map(Q=>$(Q,U)))),k}function $(L,k=!1){const U=[];return k||U.push(...M(L.view.annotations)),L.name&&(U.push((0,e.maybeQuoteIdentifier)(L.name)),U.push(" is ")),U.push(...V(L.view)),U}function V(L){return E(L.definition)}function K(L){return[`limit: ${L.limit}`]}function ne(L){const k=[];for(let U=0;U<L.length;U++)U!==0&&k.push(i),k.push(...K(L[U]));return k}function le(L){return b("where",L.map(j),",")}function z(L){return b("drill",L.map(j),",")}function X(L){return b("having",L.map(j),",")}const se=["`","'",'"'];function fe(L){let k,U;for(const Q of se){const J=I(L,Q);if(J===L)return`f${Q}${L}${Q}`;(U===void 0||J.length<U.length)&&(k=Q,U=J)}return`f${k}${U}${k}`}function I(L,k){let U="";for(let Q=0;Q<L.length;Q++)L.slice(Q).startsWith(k)?(U+="\\"+k,Q+=k.length):(U+=L[Q],L[Q]==="\\"&&(U+=L[++Q]));return U}function q(L){switch(L.kind){case"filter_string":return[...T(L.expression)," ~ ",fe(L.filter)];case"literal_equality":return[...T(L.expression)," = ",...f(L.value)]}}function j(L){return q(L.filter)}function M(L){return L?L.flatMap(B):[]}function B(L){return[L.value.trim(),i]}return qA}var L1={},vce;function ZIe(){if(vce)return L1;vce=1,Object.defineProperty(L1,"__esModule",{value:!0}),L1.nestUnions=t,L1.unnestUnions=n,L1.convertFromThrift=r,L1.convertToThrift=s;const e=mce();function t(o){if(o==null)return o;if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(Array.isArray(o))return o.map(t);{const a={};let u;for(const c in o)c==="kind"?u=o[c]:a[c]=t(o[c]);return u===void 0?a:{[u]:a}}}function n(o,a){if(o==null)return o;if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(Array.isArray(o))return o.map(u=>n(u,a));{const u=i(a);if(u.type==="union"){for(const c in u.options)if(o[c]!==void 0){const l=n(o[c],u.options[c]);if(typeof l=="object")return{kind:c,...l}}}else if(u.type==="struct"){const c={};for(const l in o){const f=u.fields[l];if(f===void 0)throw new Error(`Unknown field ${l} in ${a}`);c[l]=n(o[l],f.type)}return c}else throw new Error(`Cannot unnest unions in an enum type ${a}`)}}function r(o,a){if(o==null)return o;if(typeof o=="string"||typeof o=="boolean")return o;if(typeof o=="number"){if(a==="number")return o;const u=i(a);if(u.type!=="enum")throw new Error(`Found a number where a ${a} was expected`);const c=Object.entries(u.values).find(([,l])=>l===o);if(c===void 0)throw new Error(`${o} is not a valid enum value for ${a}`);return c[0]}else{if(Array.isArray(o))return o.map(u=>r(u,a));{const u=i(a);if(u.type==="union"){for(const c in u.options)if(o[c]!==void 0&&o[c]!==null){const l=r(o[c],u.options[c]);if(typeof l=="object")return{kind:c,...l}}}else if(u.type==="struct"){const c={};for(const l in o){const f=u.fields[l];if(f===void 0)throw new Error(`Unknown field ${l} in ${a}`);c[l]=r(o[l],f.type)}return c}else throw new Error(`Cannot unnest unions in an enum type ${a}`)}}}function i(o){const a=e.MALLOY_INTERFACE_TYPES[o];if(a===void 0)throw new Error(`Unknown Malloy interface type ${o}`);return a}function s(o,a){if(o==null)return o;if(typeof o=="number"||typeof o=="boolean")return o;if(typeof o=="string"){if(a==="string")return o;const u=i(a);if(u.type==="enum"){const c=u.values[o];if(c===void 0)throw new Error(`${o} is not a valid enum value for ${a}`);return c}}else{if(Array.isArray(o))return o.map(u=>s(u,a));{const u=i(a);if(u.type==="union"){const c=o.kind,l=u.options[c];if(l===void 0)throw new Error(`${c} is not a valid union of ${a}`);const f=i(l);if(f.type!=="struct")throw new Error("Union fields must be structs");const d={};for(const p in o){if(p==="kind")continue;const x=f.fields[p];d[p]=s(o[p],x.type)}return{[c]:d}}else if(u.type==="struct"){const c={};for(const l in o){const f=u.fields[l];if(f===void 0)throw new Error(`Unknown field ${l} in ${a}`);c[l]=s(o[l],f.type)}return c}}}}return L1}var _ce;function iw(){return _ce||(_ce=1,function(e){var t=F1&&F1.__createBinding||(Object.create?function(s,o,a,u){u===void 0&&(u=a);var c=Object.getOwnPropertyDescriptor(o,a);(!c||("get"in c?!o.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(s,u,c)}:function(s,o,a,u){u===void 0&&(u=a),s[u]=o[a]}),n=F1&&F1.__exportStar||function(s,o){for(var a in s)a!=="default"&&!Object.prototype.hasOwnProperty.call(o,a)&&t(o,s,a)};Object.defineProperty(e,"__esModule",{value:!0}),e.thingy4sddfdfsd=e.thingy4sdfsd=e.thingy4dfdsfs=e.thingy4asdfas=e.thingy4asdfasdf=e.thingy3dfdf=e.thingy3=e.thingy2asdf=e.thingyssdfg=e.thingy123r=e.thingy1=e.res=e.test=e.convertToThrift=e.convertFromThrift=e.unnestUnions=e.nestUnions=e.filterToMalloy=e.queryToMalloy=void 0,n(mce(),e);var r=JIe();Object.defineProperty(e,"queryToMalloy",{enumerable:!0,get:function(){return r.queryToMalloy}}),Object.defineProperty(e,"filterToMalloy",{enumerable:!0,get:function(){return r.filterToMalloy}});var i=ZIe();Object.defineProperty(e,"nestUnions",{enumerable:!0,get:function(){return i.nestUnions}}),Object.defineProperty(e,"unnestUnions",{enumerable:!0,get:function(){return i.unnestUnions}}),Object.defineProperty(e,"convertFromThrift",{enumerable:!0,get:function(){return i.convertFromThrift}}),Object.defineProperty(e,"convertToThrift",{enumerable:!0,get:function(){return i.convertToThrift}}),e.test={entries:[{kind:"source",name:"flights",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"boolean_type"},annotations:[{value:"# foo=1"}]},{kind:"dimension",name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}},{kind:"dimension",name:"arr_rec",type:{kind:"array_type",element_type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}}},{kind:"dimension",name:"rec",type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}},{kind:"join",name:"carriers",relationship:"one",schema:{fields:[{kind:"dimension",name:"code",type:{kind:"string_type"}}]}},{kind:"view",name:"by_carrier",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]}}]},parameters:[{name:"param",type:{kind:"number_type"},default_value:{kind:"number_literal",number_value:7}}]}],anonymous_queries:[]},e.res={connection_name:"foo",data:{kind:"array_cell",array_value:[{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"UA"},{kind:"number_cell",number_value:12341234}]},{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"AA"},{kind:"number_cell",number_value:2343}]}]},schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]},sql:"SELECT * ..."},e.thingy1={definition:{kind:"query_reference",name:"flights_by_carrier"}},e.thingy123r={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},e.thingyssdfg={definition:{kind:"refinement",base:{kind:"query_reference",name:"flights"},refinement:{kind:"view_reference",name:"by_carrier"}}},e.thingy2asdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"where",filter:{kind:"filter_string",expression:{kind:"field_reference",name:"carrier"},filter:"WN"}}]}}}},e.thingy3={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}}},e.thingy3dfdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"view_reference",name:"top10"}}}},e.thingy4asdfasdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}},e.thingy4asdfas={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},e.thingy4dfdsfs={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"limit",limit:10}]}}}},e.thingy4sdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"limit",limit:10}]}}},e.thingy4sddfdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[]}}}}(F1)),F1}var Sce;function sw(){if(Sce)return to;Sce=1;var e=to&&to.__createBinding||(Object.create?function(R,O,N,F){F===void 0&&(F=N);var $=Object.getOwnPropertyDescriptor(O,N);(!$||("get"in $?!O.__esModule:$.writable||$.configurable))&&($={enumerable:!0,get:function(){return O[N]}}),Object.defineProperty(R,F,$)}:function(R,O,N,F){F===void 0&&(F=N),R[F]=O[N]}),t=to&&to.__setModuleDefault||(Object.create?function(R,O){Object.defineProperty(R,"default",{enumerable:!0,value:O})}:function(R,O){R.default=O}),n=to&&to.__importStar||function(){var R=function(O){return R=Object.getOwnPropertyNames||function(N){var F=[];for(var $ in N)Object.prototype.hasOwnProperty.call(N,$)&&(F[F.length]=$);return F},R(O)};return function(O){if(O&&O.__esModule)return O;var N={};if(O!=null)for(var F=R(O),$=0;$<F.length;$++)F[$]!=="default"&&e(N,O,F[$]);return t(N,O),N}}();Object.defineProperty(to,"__esModule",{value:!0}),to.sourceDefToSourceInfo=a,to.modelDefToModelInfo=u,to.toStableAnnotations=l,to.convertFieldInfos=f,to.writeLiteralToTag=m,to.getResultStructMetadataAnnotation=E;const r=n(iw()),i=Si(),s=cm(),o=kc();function a(R){const O=R.parameters&&Object.entries(R.parameters).length>0?Object.entries(R.parameters).map(([F,$])=>(0,i.isAtomic)($)?{name:F,type:v($),default_value:c($.value)}:{name:F,type:{kind:"filter_expression_type",filter_type:{kind:`${$.filterType}_type`}},default_value:c($.value)}):void 0;return{name:(0,i.activeName)(R),schema:{fields:f(R,R.fields)},parameters:O,annotations:l(R.annotations)}}function u(R){const O={entries:[],anonymous_queries:[]};for(const[N,F]of Object.entries(R.contents))if(R.exports.includes(N)){if((0,i.isSourceDef)(F)){const $=a(F);O.entries.push({kind:"source",...$})}else if(F.type==="query"){const $=(0,i.getResultStructDefForQuery)(R,F),V=l(F.annotations),K=$.resultMetadata?E($,$.resultMetadata):void 0,ne=[...V??[],...K?[K]:[]],le={kind:"source",name:N,schema:{fields:f($,$.fields)},annotations:ne.length>0?ne:void 0};O.entries.push(le)}}for(const N of R.queryList){const F=(0,i.getResultStructDefForQuery)(R,N),$=l(N.annotations),V=F.resultMetadata?E(F,F.resultMetadata):void 0,K=[...$??[],...V?[V]:[]],ne={schema:{fields:f(F,F.fields)},annotations:K.length>0?K:void 0};O.anonymous_queries.push(ne)}return O}function c(R){if(R!==null)switch(R.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(R.literal)};case"stringLiteral":return{kind:"string_literal",string_value:R.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:R.filterSrc};case"dateLiteral":return{kind:"date_literal",date_value:R.literal};case"timestampLiteral":case"timestamptzLiteral":return{kind:"timestamp_literal",timestamp_value:R.literal,timezone:R.timezone};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 l(R){return new s.Annotations(R).texts().map(O=>({value:O}))}function f(R,O){const N=[];for(const F of O){if(!(F.accessModifier===void 0))continue;const V=l(F.annotations),K=V.length>0?V:void 0;if((0,i.isTurtle)(F)){const ne=(0,i.getResultStructDefForView)(R,F),le=ne.resultMetadata?E(ne,ne.resultMetadata):void 0,z=[...K??[],...le?[le]:[]],X={kind:"view",name:(0,i.activeName)(F),annotations:z.length>0?z:void 0,schema:{fields:f(ne,ne.fields)}};N.push(X)}else if((0,i.isAtomic)(F)){const ne=(0,i.expressionIsAggregate)(F.expressionType),le=(0,i.expressionIsScalar)(F.expressionType);if(!ne&&!le||F.type==="error")continue;const z=F.resultMetadata?d(F,F.resultMetadata):void 0;let X;if((0,i.isRecordOrRepeatedRecord)(F)&&F.queryTimezone){const I=o.Tag.withPrefix("#(malloy) ");I.set(["query_timezone"],F.queryTimezone),X={value:I.toString()}}const se=[...K??[],...z?[z]:[],...X?[X]:[]],fe={kind:ne?"measure":"dimension",name:(0,i.activeName)(F),type:v(F),annotations:se.length>0?se:void 0};N.push(fe)}else if((0,i.isJoinedSource)(F)){const ne={kind:"join",name:(0,i.activeName)(F),annotations:K,schema:{fields:f(F,F.fields)},relationship:F.join};N.push(ne)}}return N}function d(R,O){const N=o.Tag.withPrefix("#(malloy) ");let F=!1;if(O.referenceId!==void 0&&(N.set(["reference_id"],O.referenceId),F=!0),O.fieldKind==="measure"&&(N.set(["calculation"]),F=!0),O.drillable&&(N.set(["drillable"]),F=!0),O.filterList&&(p(N,O.filterList),F=!0),O.drillExpression&&(x(N,["drill_expression"],O.drillExpression),F=!0),O.fieldKind==="dimension"){const V=(O==null?void 0:O.sourceExpression)||(O!=null&&O.sourceField.includes(".")?O==null?void 0:O.sourceField:y(R.name));N.set(["drill_expression","code"],V),F=!0}return F?{value:N.toString()}:void 0}function p(R,O){for(let N=0;N<O.length;N++){const F=O[N];F.expressionType!=="scalar"||F.isSourceFilter||(R.set(["drill_filters",N,"code"],F.code),F.filterView&&R.set(["drill_filters",N,"filter_view"],F.filterView),F.filterView===void 0&&F.stableFilter!==void 0&&(x(R,["drill_filters",N,"expression"],F.stableFilter.expression),F.stableFilter.kind==="filter_string"?(R.set(["drill_filters",N,"kind"],"filter_expression"),R.set(["drill_filters",N,"filter_expression"],F.stableFilter.filter)):(R.set(["drill_filters",N,"kind"],"literal_equality"),m(R,["drill_filters",N,"value"],F.stableFilter.value))))}}function x(R,O,N){w(R,O,N,"Expression")}function m(R,O,N){w(R,O,N,"LiteralValue")}function g(R){return R.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function y(R){return R.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?R:`\`${g(R)}\``}function E(R,O){var N;const F=o.Tag.withPrefix("#(malloy) ");let $=!1;if(O.limit!==void 0&&(F.set(["limit"],O.limit),$=!0),O.filterList&&(p(F,O.filterList),$=!0),O.drillable&&(F.set(["drillable"]),$=!0),O.orderBy){for(let V=0;V<O.orderBy.length;V++){const K=O.orderBy[V],ne=typeof K.field=="number"?(0,i.activeName)(R.fields[K.field-1]):K.field,le=(N=K.dir)!==null&&N!==void 0?N:null;F.set(["ordered_by",V,ne],le)}$=!0}return R.queryTimezone&&(F.set(["query_timezone"],R.queryTimezone),$=!0),$?{value:F.toString()}:void 0}function v(R){if((0,i.isBasicAtomic)(R))switch(R.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:R.numberType==="float"?"decimal":R.numberType==="integer"?"integer":R.numberType==="bigint"?"bigint":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const O=R.timeframe;return O&&!b(O)?{kind:"timestamp_type",timeframe:R.timeframe}:{kind:"date_type",timeframe:C(R.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:R.timeframe};case"timestamptz":return{kind:"timestamptz_type",timeframe:R.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:R.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,i.isRepeatedRecord)(R))return{kind:"array_type",element_type:S(R)};if(R.type==="record")return S(R);if(R.type==="array")return{kind:"array_type",element_type:v(R.elementTypeDef)}}throw new Error("Unexpected field type")}function S(R){return{kind:"record_type",fields:R.fields.map(O=>{const N=[];if("resultMetadata"in O&&O.resultMetadata){const F=d(O,O.resultMetadata);F&&N.push(F)}if(O.annotations&&N.push(...l(O.annotations)),(0,i.isAtomic)(O))return{name:O.name,annotations:N.length>0?N:void 0,type:v(O)};throw new Error("Expected record type to not have a table as its child")})}}function b(R){switch(R){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function C(R){switch(R){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return R;default:throw new Error(`Invalid date timeframe ${R}`)}}function _(R){return R}function T(R){return R}function w(R,O,N,F){if(F==="string"){R.set(O,N);return}else if(F==="number"){R.set(O,N);return}else if(F==="boolean"){R.set(O,N.toString());return}const $=r.MALLOY_INTERFACE_TYPES[F];if($===void 0)throw new Error(`Unknown Malloy interface type ${F}`);if($.type==="enum")if(typeof N=="string")R.set(O,N);else throw new Error(`Expected string for enum ${F}`);else if($.type==="struct")for(const V in $.fields){const K=$.fields[V],ne=N[V];if(ne===void 0){if(!K.optional)throw new Error(`Mising value for non-optional field ${V} in type ${F}`)}else if(K.array)if(Array.isArray(ne))for(let le=0;le<ne.length;le++)w(R,[...O,V,le],ne[le],K.type);else throw new Error(`Expected array for field ${V} of type ${F} but got ${typeof N}`);else w(R,[...O,V],ne,K.type)}else{const V=N.kind;R.set([...O,"kind"],V);const K=$.options[V];if(K===void 0)throw new Error(`Unknown Malloy interface union kind ${V} for type ${F}`);w(R,O,N,K)}}return to}var Ace;function jA(){return Ace||(Ace=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_LOG_RANGE=void 0,e.wrapLegacyInfoConnection=i,e.wrapLegacyConnection=s,e.mapData=o,e.wrapResult=a,e.nodeToLiteralValue=u,e.mapLogs=c;const t=Dk(),n=sw(),r=Vv();function i(l){return{get dialectName(){return l.dialectName},async fetchSchemaForSQLQuery(f){const d=await l.fetchSchemaForSQLStruct({connection:l.name,selectStr:f},{}),p=d.structDef;if(p===void 0)throw new Error(d.error);return{fields:(0,n.convertFieldInfos)(p,p.fields)}},async fetchSchemaForTable(f){const d=(0,t.validateCanonicalTablePath)(l.dialectName,f);if(d!==void 0)throw new Error(d);const p=`${l.name}:${f}`,x=await l.fetchSchemaForTables({[p]:f},{}),m=x.schemas[p];if(m===void 0)throw new Error(x.errors[p]);return{fields:(0,n.convertFieldInfos)(m,m.fields)}}}}function s(l){return{...i(l),runSQL:async(f,d)=>{const p=await l.runSQL(f);return o(p.rows,d)}}}function o(l,f){function d(m,g){if(m===null)return{kind:"null_cell"};if(g.type.kind==="date_type"||g.type.kind==="timestamp_type"||g.type.kind==="timestamptz_type"){const y=(0,r.rowDataToDate)(m).toISOString();return g.type.kind==="date_type"?{kind:"date_cell",date_value:y}:{kind:"timestamp_cell",timestamp_value:y}}else if(g.type.kind==="boolean_type"){if(typeof m=="number"||typeof m=="bigint")return{kind:"boolean_cell",boolean_value:m!==0};if(typeof m=="string")return{kind:"boolean_cell",boolean_value:m!=="0"&&m!==""};if(typeof m!="boolean")throw new Error(`Invalid boolean ${m}`);return{kind:"boolean_cell",boolean_value:m}}else if(g.type.kind==="number_type"){const y=g.type.subtype,E=y==="bigint"?(0,r.rowDataToSerializedBigint)(m):void 0;return{kind:"number_cell",number_value:(0,r.rowDataToNumber)(m),subtype:y,string_value:E}}else if(g.type.kind==="string_type"){if(typeof m!="string")throw new Error(`Invalid string ${m}`);return{kind:"string_cell",string_value:m}}else if(g.type.kind==="array_type"){if(!Array.isArray(m))throw new Error(`Invalid array ${m}`);return{kind:"array_cell",array_value:m.map(y=>d(y,{name:"array_element",type:g.type.element_type}))}}else{if(g.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(m)};if(g.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(m)};{const y=g.type;if(y.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(g)}, ${JSON.stringify(m)}`);return p(m,{schema:{fields:y.fields.map(E=>({kind:"dimension",...E}))}})}}}function p(m,g){const y=[];for(const E of g.schema.fields){const v=m[E.name];if(E.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const S=d(v,E);y.push(S)}return{kind:"record_cell",record_value:y}}const x={schema:f};return{kind:"array_cell",array_value:l.map(m=>p(m,x))}}function a(l){const f=l._queryResult.structs,d=f[f.length-1],p={fields:(0,n.convertFieldInfos)(d,d.fields)};return l.toStableResult(o(l.data.rawData,p))}function u(l){switch(l==null?void 0:l.node){case"numberLiteral":return{kind:"number_literal",number_value:Number.parseFloat(l.literal)};case"null":return{kind:"null_literal"};case"stringLiteral":return{kind:"string_literal",string_value:l.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:l.filterSrc};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"dateLiteral":return{kind:"date_literal",date_value:l.literal,granularity:l.typeDef.timeframe};case"timestampLiteral":case"timestamptzLiteral":return{kind:"timestamp_literal",timestamp_value:l.literal,timezone:l.timezone,granularity:l.typeDef.timeframe};default:return}}e.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function c(l,f){return l.map(d=>{var p,x,m,g;return{severity:d.severity,message:d.message,range:(x=(p=d.at)===null||p===void 0?void 0:p.range)!==null&&x!==void 0?x:e.DEFAULT_LOG_RANGE,url:(g=(m=d.at)===null||m===void 0?void 0:m.url)!==null&&g!==void 0?g:f}})}}(wk)),wk}var bce;function e9e(){if(bce)return Wa;bce=1;var e=Wa&&Wa.__createBinding||(Object.create?function(g,y,E,v){v===void 0&&(v=E);var S=Object.getOwnPropertyDescriptor(y,E);(!S||("get"in S?!y.__esModule:S.writable||S.configurable))&&(S={enumerable:!0,get:function(){return y[E]}}),Object.defineProperty(g,v,S)}:function(g,y,E,v){v===void 0&&(v=E),g[v]=y[E]}),t=Wa&&Wa.__setModuleDefault||(Object.create?function(g,y){Object.defineProperty(g,"default",{enumerable:!0,value:y})}:function(g,y){g.default=y}),n=Wa&&Wa.__importStar||function(){var g=function(y){return g=Object.getOwnPropertyNames||function(E){var v=[];for(var S in E)Object.prototype.hasOwnProperty.call(E,S)&&(v[v.length]=S);return v},g(y)};return function(y){if(y&&y.__esModule)return y;var E={};if(y!=null)for(var v=g(y),S=0;S<v.length;S++)v[S]!=="default"&&e(E,y,v[S]);return t(E,y),E}}();Object.defineProperty(Wa,"__esModule",{value:!0}),Wa.MalloyToQuery=void 0,Wa.malloyToQuery=m;const r=OA(),i=vk(),s=n(AA()),o=Kv(),a=bA(),u=mt(),c=fce(),l=Vu(),f=jA(),d=X4(),p="Malloy query documents";class x extends i.AbstractParseTreeVisitor{constructor(y,E){super(),this.parseInfo=y,this.msgLog=E}internalError(y,E){return this.contextError(y,"internal-translator-error",{message:E}),new Error(`Internal Translator Error: ${E}`)}getLocation(y){return{url:this.parseInfo.sourceURL,range:(0,l.rangeFromContext)(this.parseInfo.sourceInfo,y)}}contextError(y,E,v,S){this.msgLog.log((0,o.makeLogMessage)(E,v,{at:this.getLocation(y),...S}))}getNumber(y){return Number.parseInt(y.text)}defaultResult(){return null}getAnnotations(y){const E=y.annotation().map(v=>({value:(0,a.getAnnotationText)(v)}));return E.length>0?E:void 0}getIsAnnotations(y){var E,v;if(y===void 0)return;const b=((E=this.getAnnotations(y._beforeIs))!==null&&E!==void 0?E:[]).concat((v=this.getAnnotations(y._afterIs))!==null&&v!==void 0?v:[]);return b.length>0?b:void 0}notAllowed(y,E){this.illegal(y,`${E} are not allowed in ${p}`)}illegal(y,E){this.contextError(y,"invalid-malloy-query-document",E)}visitMalloyDocument(y){const E=y.malloyStatement();let v;for(const S of E)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"):v===void 0?v=S.runStatement():this.illegal(S,`${p} may only have one run statement`);return v===void 0?(this.illegal(y,`${p} must have a run statement`),null):this.visitRunStatement(v)}visitRunStatement(y){const E=y.topLevelAnonQueryDef(),v=this.getQueryDefinition(E.sqExpr()),S=this.getAnnotations(y.tags()),b=this.getAnnotations(y.topLevelAnonQueryDef().tags()),C=this.combineAnnotations(S,b);return v!==null?{annotations:C,definition:v}:null}getSourceArguments(y){const E=[];for(const v of y.sourceArgument()){const S=v.argumentId();if(S===void 0)return this.contextError(v,"unnamed-source-argument","Source argument must be named"),null;const b=(0,a.getId)(S),C=this.getLiteralIncludingNegativeNumber(v.fieldExpr());if(C===null)return null;E.push({name:b,value:C})}return E}getQueryReference(y){const E=y.sourceArguments(),v=(0,a.getId)(y);if(E){const S=this.getSourceArguments(E);return S===null?null:{name:v,parameters:S}}else return{name:v}}getQueryDefinition(y){if(y instanceof s.SQIDContext){const E=this.getQueryReference(y);if(E!==null)return{kind:"query_reference",...E}}else{if(y instanceof s.SQParensContext)return this.getQueryDefinition(y.sqExpr());if(y instanceof s.SQComposeContext)this.notAllowed(y,"Source compositions");else if(y instanceof s.SQRefinedQueryContext){const E=y.sqExpr(),v=this.getQueryDefinition(E),S=this.getRefinementSegment(y.segExpr());return S===null||v===null?null:(S.kind==="arrow"&&this.notAllowed(y,"Queries against refined queries"),{kind:"refinement",base:v,refinement:S})}else if(y instanceof s.SQExtendedSourceContext)this.notAllowed(y,"Source extensions");else if(y instanceof s.SQIncludeContext)this.notAllowed(y,"Source inclusions");else if(y instanceof s.SQTableContext)this.notAllowed(y,"Table statements");else if(y instanceof s.SQSQLContext)this.notAllowed(y,"SQL statements");else if(y instanceof s.SQArrowContext){const E=y.sqExpr(),v=this.getQueryDefinition(E),S=this.getRefinementSegment(y.segExpr());return S===null||v===null?null:v.kind==="query_reference"?{kind:"arrow",source:{...v,kind:"source_reference"},view:S}:v.kind==="arrow"?{kind:"arrow",source:v.source,view:{kind:"arrow",source:v.view,view:S}}:{kind:"arrow",source:v,view:S}}}return null}getRefinementSegment(y){if(y instanceof s.SegOpsContext){const E=y.queryProperties().queryStatement().flatMap(v=>this.getSegmentOperation(v));return E.some(v=>v===null)?null:{kind:"segment",operations:E}}else if(y instanceof s.SegFieldContext){const{name:E,path:v}=this.getFieldPath(y.fieldPath());return{kind:"view_reference",name:E,path:v}}else{if(y instanceof s.SegParenContext)return this.getViewExpression(y.vExpr());if(y instanceof s.SegRefineContext){const E=this.getRefinementSegment(y._lhs),v=this.getRefinementSegment(y._rhs);return E===null||v===null?null:{kind:"refinement",base:E,refinement:v}}}return null}getGroupByStatement(y){const E=this.getAnnotations(y.tags()),S=y.queryFieldList().queryFieldEntry().map(b=>this.getQueryField(b));return S.some(b=>b===null)||S===null?null:S.map(b=>{var C;const _=[...E??[],...(C=b.field.annotations)!==null&&C!==void 0?C:[]];return{kind:"group_by",name:b.name,field:{...b.field,annotations:_.length>0?_:void 0}}})}getAggregateStatement(y){const E=this.getAnnotations(y.tags()),S=y.queryFieldList().queryFieldEntry().map(b=>this.getQueryField(b));return S.some(b=>b===null)||S===null?null:S.map(b=>{var C;const _=[...E??[],...(C=b.field.annotations)!==null&&C!==void 0?C:[]];return{kind:"aggregate",name:b.name,field:{...b.field,annotations:_.length>0?_:void 0}}})}getOrderByStatement(y){var E,v;const S=y.ordering().orderBySpec(),b=[];for(const C of S){if(C.INTEGER_LITERAL()){this.notAllowed(C,"Indexed order by statements");continue}const _=(v=(E=C.possibleBadPath())===null||E===void 0?void 0:E.badWord())!==null&&v!==void 0?v:[],T=_.length===1?_[0].fieldName():void 0;if(!T)return null;const w=(0,a.getId)(T),R=C.ASC()?"asc":C.DESC()?"desc":void 0;b.push({kind:"order_by",direction:R,field_reference:{name:w}})}return b}getNestStatement(y){const E=this.getAnnotations(y.tags()),v=y.nestedQueryList().nestEntry(),S=[];for(const b of v){if(!(b instanceof s.NestDefContext))return this.internalError(b,"Expected nestDef"),null;const C=this.getAnnotations(b.tags()),_=this.getIsAnnotations(b.isDefine()),T=b.queryName(),w=T?(0,a.getId)(T):void 0,R=this.getViewExpression(b.vExpr());if(R===null)return null;S.push({kind:"nest",name:w,view:{definition:R,annotations:this.combineAnnotations(E,C,_)}})}return S}getViewExpression(y){if(y instanceof s.VSegContext)return this.getRefinementSegment(y.segExpr());if(y instanceof s.VArrowContext){const E=this.getRefinementSegment(y),v=this.getViewExpression(y._rhs);return E===null||v===null?null:{kind:"arrow",source:E,view:v}}else return this.internalError(y,"Unexpected VExpr node"),null}getLimitStatement(y){return{kind:"limit",limit:this.getNumber(y.INTEGER_LITERAL())}}getSegmentOperation(y){if(y.groupByStatement()){const E=y.groupByStatement();return this.getGroupByStatement(E)}else if(y.aggregateStatement()){const E=y.aggregateStatement();return this.getAggregateStatement(E)}else if(y.limitStatement()){const E=y.limitStatement(),v=this.getLimitStatement(E);return v===null?null:[v]}else if(y.declareStatement())this.notAllowed(y,"Declare statements");else if(y.queryJoinStatement())this.notAllowed(y,"Query join statements");else if(y.queryExtend())this.notAllowed(y,"Query extend statements");else if(y.projectStatement())this.notAllowed(y,"Select statements");else if(y.indexStatement())this.notAllowed(y,"Index statements");else if(y.calculateStatement())this.notAllowed(y,"Calculate statements");else if(y.topStatement())this.notAllowed(y,"Top statements");else if(y.orderByStatement()){const E=y.orderByStatement();return this.getOrderByStatement(E)}else if(y.whereStatement()){const E=y.whereStatement(),v=this.getWhere(E);return v===null?null:v.map(S=>({kind:"where",...S}))}else if(y.drillStatement()){const E=y.drillStatement(),v=this.getDrill(E);return v===null?null:v.map(S=>({kind:"drill",...S}))}else if(y.havingStatement()){const E=y.havingStatement(),v=this.getHaving(E);return v===null?null:v.map(S=>({kind:"having",...S}))}else if(y.nestStatement()){const E=y.nestStatement();return this.getNestStatement(E)}else y.sampleStatement()?this.notAllowed(y,"Sample statements"):y.timezoneStatement()?this.notAllowed(y,"Timezone statements"):(y.queryAnnotation()||y.ignoredModelAnnotations())&&this.notAllowed(y,"Detached annotation statements");return null}getFieldPath(y){const E=y.fieldName().map(b=>(0,a.getId)(b)),v=E[E.length-1],S=E.slice(0,-1);return{name:v,path:S.length>0?S:void 0}}getTimeframe(y){const E=y.text;return(0,u.isTimestampUnit)(E)?E:(this.illegal(y,`Invalid timeframe ${E}`),null)}getQueryField(y){if(y.taggedRef()){const E=y.taggedRef(),v=this.getAnnotations(E.tags()),{name:S,path:b}=this.getFieldPath(E.fieldPath());if(E.refExpr()){const C=E.refExpr();if(C.timeframe()){const _=this.getTimeframe(C.timeframe());return _===null?null:{name:void 0,field:{annotations:v,expression:{kind:"time_truncation",field_reference:{name:S,path:b},truncation:_}}}}else C.aggregate()&&this.notAllowed(C,"Aggregate expressions")}else return{name:void 0,field:{annotations:v,expression:{kind:"field_reference",name:S,path:b}}}}else if(y.fieldDef()){const E=y.fieldDef(),v=this.getAnnotations(E.tags()),S=this.getIsAnnotations(E.isDefine()),b=(0,a.getId)(E.fieldNameDef()),C=this.getFieldExpression(E.fieldExpr());return C===null?null:{name:b,field:{expression:C,annotations:this.combineAnnotations(v,S)}}}return null}getFieldExpression(y){if(y instanceof s.ExprFieldPathContext){const{name:E,path:v}=this.getFieldPath(y.fieldPath());return{kind:"field_reference",name:E,path:v}}else if(y instanceof s.ExprTimeTruncContext){const E=this.getTimeframe(y.timeframe()),v=y.fieldExpr(),S=this.getFieldExpression(v);return S===null||E===null?null:S.kind!=="field_reference"?(this.illegal(v,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:E,field_reference:{name:S.name,path:S.path,parameters:S.parameters}}}else if(y instanceof s.ExprFieldPropsContext){const E=y.fieldExpr(),v=this.getFieldExpression(E);if(v===null)return null;if(v.kind!=="field_reference")return this.illegal(E,"Left hand side of filtered field must be a field reference"),null;const S=y.fieldProperties().fieldPropertyStatement(),b=[];for(const C of S){const _=C.whereStatement();if(_){const T=this.getWhere(_);if(T===null)return null;b.push(...T)}}return{kind:"filtered_field",field_reference:{name:v.name,path:v.path,parameters:v.parameters},where:b}}else{const E=this.getLiteralIncludingNegativeNumber(y);return E===null?null:{kind:"literal_value",literal_value:E}}}stripQuote(y,E){return y.slice(y.indexOf(E)+E.length,y.lastIndexOf(E))}getFilterString(y){const E=y.tripFilterString(),v=y.tickFilterString();if(E){const S=E.BQ3_FILTER(),b=E.DQ3_FILTER(),C=E.SQ3_FILTER();if(S)return this.stripQuote(S.text,"```");if(b)return this.stripQuote(b.text,'"""');if(C)return this.stripQuote(C.text,"'''")}else if(v){const S=v.BQ_FILTER(),b=v.DQ_FILTER(),C=v.SQ_FILTER();if(S)return this.stripQuote(S.text,"`");if(b)return this.stripQuote(b.text,'"');if(C)return this.stripQuote(C.text,"'")}return null}getFilterExpr(y){if(y instanceof s.ExprCompareContext){if(y.compareOp().MATCH()){const E=y.fieldExpr()[0],v=y.fieldExpr()[1];if(E instanceof s.ExprFieldPathContext&&v instanceof s.ExprLiteralContext){const{path:S,name:b}=this.getFieldPath(E.fieldPath()),C=v.literal();if(C instanceof s.FilterString_stubContext){const _=this.getFilterString(C.filterString());return _===null?null:{filter:{kind:"filter_string",expression:{kind:"field_reference",name:b,path:S},filter:_}}}}}else if(y.compareOp().EQ()){const E=y.fieldExpr()[0],v=y.fieldExpr()[1];if(E instanceof s.ExprFieldPathContext){const{path:S,name:b}=this.getFieldPath(E.fieldPath()),C=this.getLiteralIncludingNegativeNumber(v);return C===null?(this.notAllowed(y,"Filters other than comparisons with filter strings or equality with literals"),null):{filter:{kind:"literal_equality",expression:{kind:"field_reference",name:b,path:S},value:C}}}}}return this.notAllowed(y,"Filters other than comparisons with filter strings or equality with literals"),null}getTimeLiteral(y,E){const v=E(y.text);if(!v)return this.contextError(y,"failed-to-parse-time-literal","Time data parse error"),null;const S=v.getValue(),b=S.timeframe,C=S.value;return(0,u.isTimeLiteral)(C)?C.node==="dateLiteral"?b==="hour"||b==="minute"||b==="second"?null:{kind:"date_literal",date_value:C.literal,granularity:b}:{kind:"timestamp_literal",timestamp_value:C.literal,granularity:b,timezone:C.timezone}:null}getLiteralIncludingNegativeNumber(y){if(y instanceof s.ExprLiteralContext)return this.getLiteral(y.literal());if(y instanceof s.ExprMinusContext){const E=y.fieldExpr();if(E instanceof s.ExprLiteralContext){const v=this.getLiteral(E.literal());return v===null||v.kind!=="number_literal"?null:{kind:"number_literal",number_value:-v.number_value}}}return null}getLiteral(y){if(y instanceof s.ExprTimeContext){const E=y.dateLiteral();return E instanceof s.LiteralTimestampContext?this.getTimeLiteral(E,d.LiteralTimestamp.parse):E instanceof s.LiteralHourContext?this.getTimeLiteral(E,d.LiteralHour.parse):E instanceof s.LiteralDayContext?this.getTimeLiteral(E,d.LiteralDay.parse):E instanceof s.LiteralWeekContext?this.getTimeLiteral(E,d.LiteralWeek.parse):E instanceof s.LiteralMonthContext?this.getTimeLiteral(E,d.LiteralMonth.parse):E instanceof s.LiteralQuarterContext?this.getTimeLiteral(E,d.LiteralQuarter.parse):E instanceof s.LiteralYearContext?this.getTimeLiteral(E,d.LiteralYear.parse):null}else{if(y instanceof s.ExprArrayLiteralContext)return this.notAllowed(y,"array literals"),null;if(y instanceof s.ExprLiteralRecordContext)return this.notAllowed(y,"record literals"),null;if(y instanceof s.ExprStringContext){const[E,v]=(0,a.getPlainString)(y);for(const S of v)S instanceof r.ParserRuleContext&&this.contextError(S,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return{kind:"string_literal",string_value:E??""}}else{if(y instanceof s.ExprBoolContext)return{kind:"boolean_literal",boolean_value:y.TRUE()!==null};if(y instanceof s.ExprNumberContext)return{kind:"number_literal",number_value:Number(y.text)};if(y instanceof s.ExprNULLContext)return{kind:"null_literal"};if(y instanceof s.FilterString_stubContext){const E=y.getChild(0);if(E instanceof s.FilterStringContext){const v=this.getFilterString(E);if(v)return{kind:"filter_expression_literal",filter_expression_value:v}}}}}return null}getDrill(y){const v=y.drillClauseList().fieldExpr().map(S=>this.getFilterExpr(S));return v.some(S=>S===null)?null:v}getWhere(y){const v=y.filterClauseList().fieldExpr().map(S=>this.getFilterExpr(S));return v.some(S=>S===null)?null:v}getHaving(y){const v=y.filterClauseList().fieldExpr().map(S=>this.getFilterExpr(S));return v.some(S=>S===null)?null:v}combineAnnotations(...y){const E=y.flatMap(v=>v??[]);return E.length>0?E:void 0}}Wa.MalloyToQuery=x;function m(g){const y=(0,l.getSourceInfo)(g),E=new o.BaseMessageLogger(null),v="internal://query.malloy",S=(0,c.runMalloyParser)(g,v,y,E),C=new x(S,E).visit(S.root),_=(0,f.mapLogs)(E.getLog(),v);if(C===null)return{logs:_};if(!("definition"in C))throw new Error("Expected a query");return{query:C,logs:_}}return Wa}var Cce;function Ok(){return Cce||(Cce=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.malloyToQuery=e.exploreQueryWalkerBuilder=e.MalloyTranslation=e.MalloyTranslator=void 0;var t=WIe();Object.defineProperty(e,"MalloyTranslator",{enumerable:!0,get:function(){return t.MalloyTranslator}}),Object.defineProperty(e,"MalloyTranslation",{enumerable:!0,get:function(){return t.MalloyTranslation}});var n=YIe();Object.defineProperty(e,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}});var r=e9e();Object.defineProperty(e,"malloyToQuery",{enumerable:!0,get:function(){return r.malloyToQuery}})}(kI)),kI}var Nk={},zA={},Tce;function t9e(){return Tce||(Tce=1,Object.defineProperty(zA,"__esModule",{value:!0}),zA.EMPTY_BUILD_MANIFEST=void 0,zA.EMPTY_BUILD_MANIFEST=Object.freeze({entries:Object.freeze({}),strict:!1})),zA}var ya={},Rce;function ow(){if(Rce)return ya;Rce=1,Object.defineProperty(ya,"__esModule",{value:!0}),ya.FixedConnectionMap=ya.InMemoryURLReader=ya.EmptyURLReader=void 0,ya.hashForInvalidationKey=t,ya.isInternalURL=n,ya.readURL=r,ya.getInvalidationKey=i;const e=Gp();function t(u){return(0,e.v5)(u,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}function n(u){return u.startsWith("internal://")}async function r(u,c){const l=await u.readURL(c),{contents:f,invalidationKey:d}=typeof l=="string"?{contents:l,invalidationKey:void 0}:l;return{contents:f,invalidationKey:n(c.toString())?null:d??t(f)}}async function i(u,c){return n(c.toString())?null:u.getInvalidationKey!==void 0?await u.getInvalidationKey(c):(await r(u,c)).invalidationKey}class s{async readURL(c){throw new Error("No files.")}async getInvalidationKey(c){throw new Error("No files.")}}ya.EmptyURLReader=s;class o{constructor(c){this.files=c}async readURL(c){const l=this.files.get(c.toString());if(l!==void 0)return Promise.resolve({contents:l,invalidationKey:this.invalidationKey(c,l)});throw new Error(`File not found '${c}'`)}async getInvalidationKey(c){const l=this.files.get(c.toString());if(l!==void 0)return Promise.resolve(this.invalidationKey(c,l));throw new Error(`File not found '${c}'`)}invalidationKey(c,l){return n(c.toString())?null:t(l)}}ya.InMemoryURLReader=o;class a{constructor(c,l){this.connections=c,this.defaultConnectionName=l}async getConnection(c){if(c===void 0)if(this.defaultConnectionName!==void 0)c=this.defaultConnectionName;else throw new Error("No default connection.");const l=this.connections.get(c);if(l!==void 0)return Promise.resolve(l);throw new Error(`No connection found with name ${c}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(c){return this.getConnection(c)}static fromArray(c){return new a(new Map(c.map(l=>[l.name,l])))}}return ya.FixedConnectionMap=a,ya}var I1={},wce;function n9e(){if(wce)return I1;wce=1,Object.defineProperty(I1,"__esModule",{value:!0}),I1.InMemoryModelCache=I1.CacheManager=void 0;const e=ow();class t{constructor(s){this.modelCache=s,this.modelDependencies=new Map,this.modelInvalidationKeys=new Map}async getCachedModelDef(s,o){const a=this.modelDependencies.get(o);if(a===void 0)return;const u=[o,...n(a)],c={};for(const f of u){const d=this.modelInvalidationKeys.get(f);if(d==null)return;c[f]=d}for(const f of u)if(await(0,e.getInvalidationKey)(s,new URL(f))!==c[f])return;const l=await this.modelCache.getModel(new URL(o));if(l!==void 0){for(const f of u)if(l.invalidationKeys[f]!==c[f])return;return{modelDef:l.modelDef,invalidationKeys:c}}}async setCachedModelDef(s,o){this.modelDependencies.set(s,o.modelDef.dependencies);const a={};for(const c of[s,...n(o.modelDef.dependencies)]){if(o.invalidationKeys[c]===null)return!1;if(o.invalidationKeys[c]===void 0)throw new Error(`Missing invalidation key for dependency ${c}`);this.modelInvalidationKeys.set(c,o.invalidationKeys[c]),a[c]=o.invalidationKeys[c]}return!!await this.modelCache.setModel(new URL(s),{modelDef:o.modelDef,invalidationKeys:a})}}I1.CacheManager=t;function n(i){return[...Object.keys(i),...Object.values(i).map(n).flat()]}class r{constructor(){this.models=new Map}async getModel(s){return Promise.resolve(this.models.get(s.toString()))}async setModel(s,o){return this.models.set(s.toString(),o),Promise.resolve(!0)}}return I1.InMemoryModelCache=r,I1}var no={},Dce;function Oce(){if(Dce)return no;Dce=1,Object.defineProperty(no,"__esModule",{value:!0}),no.DocumentCompletion=no.DocumentSymbol=no.DocumentPosition=no.DocumentRange=no.DocumentTablePath=no.Parse=void 0;class e{constructor(a,u){this.translator=a,this.invalidationKey=u}get symbols(){return(this.translator.metadata().symbols||[]).map(a=>new i(a))}get tablePathInfo(){var a;return((a=this.translator.tablePathInfo().pathInfo)!==null&&a!==void 0?a:[]).map(c=>new t(c))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(a){return(this.translator.completions(a).completions||[]).map(u=>new s(u))}helpContext(a){return this.translator.helpContext(a).helpContext}}no.Parse=e;class t{constructor(a){this._range=n.fromJSON(a.range),this._connectionId=a.connectionId,this._tablePath=a.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}no.DocumentTablePath=t;class n{constructor(a,u){this._start=a,this._end=u}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(a){return new n(new r(a.start.line,a.start.character),new r(a.end.line,a.end.character))}}no.DocumentRange=n;class r{constructor(a,u){this._line=a,this._character=u}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}no.DocumentPosition=r;class i{constructor(a){this._range=n.fromJSON(a.range),this._lensRange=a.lensRange?n.fromJSON(a.lensRange):void 0,this._type=a.type,this._name=a.name,this._children=a.children.map(u=>new i(u))}get range(){return this._range}get lensRange(){var a;return(a=this._lensRange)!==null&&a!==void 0?a:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}no.DocumentSymbol=i;class s{constructor(a){this.type=a.type,this.text=a.text}}return no.DocumentCompletion=s,no}var sn={},Nce;function aw(){if(Nce)return sn;Nce=1,Object.defineProperty(sn,"__esModule",{value:!0}),sn.PreparedResult=sn.PreparedQuery=sn.Given=sn.PersistSource=sn.Model=sn.Reference=sn.ExploreField=sn.QueryField=sn.Query=sn.StringField=sn.UnsupportedField=sn.JSONField=sn.BooleanField=sn.NumberField=sn.TimestampField=sn.DateField=sn.AtomicField=sn.Explore=sn.JoinRelationship=sn.TimestampTimeframe=sn.DateTimeframe=sn.AtomicFieldType=sn.SourceRelationship=void 0,sn.pseudoModelFor=x;const e=Si(),t=xr(),n=i0(),r=QI(),i=Mc(),s=ree(),o=kc(),a=cm(),u=sw(),c=jA(),l=Vu(),f=ece();function d(j){return j.type==="table"||j.type==="sql_select"||j.type==="query_source"}const p="internal://generated-model";function x(j,M=p,B={}){if(!(0,e.isSourceDef)(j))throw new Error(`Cannot create pseudo model for struct type ${j.type}`);const L=(0,t.mkModelDef)("generated_model",M);return L.modelAnnotations=B,L.contents[j.name]=j,L}class m{constructor(M,B,L){this._name=M,this._parent=B,this._source=L}get source(){return this._source}get name(){return this._name}get sourceClasses(){const M=[];return this.source&&M.push(this.source.name),M.push(this.name),M}get fieldPath(){const M=[this.name];let B=this._parent;for(;B;)M.unshift(B.name),B=B._parent;return M}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof b}isQuery(){return this instanceof V}}var g;(function(j){j.Nested="nested",j.BaseTable="base_table",j.Cross="cross",j.One="one",j.Many="many",j.Inline="inline"})(g||(sn.SourceRelationship=g={}));var y;(function(j){j.String="string",j.Number="number",j.Boolean="boolean",j.Date="date",j.Timestamp="timestamp",j.Timestamptz="timestamptz",j.Json="json",j.NativeUnsupported="sql native",j.Error="error"})(y||(sn.AtomicFieldType=y={}));var E;(function(j){j.Day="day",j.Week="week",j.Month="month",j.Quarter="quarter",j.Year="year"})(E||(sn.DateTimeframe=E={}));var v;(function(j){j.Day="day",j.Week="week",j.Month="month",j.Quarter="quarter",j.Year="year",j.Second="second",j.Hour="hour",j.Minute="minute"})(v||(sn.TimestampTimeframe=v={}));var S;(function(j){j.OneToOne="one_to_one",j.OneToMany="one_to_many",j.ManyToOne="many_to_one"})(S||(sn.JoinRelationship=S={}));class b extends m{constructor(M,B,L,k){super((0,e.activeName)(B),L,k),this._ownerModelDef=M,this._structDef=B,this._parentExplore=L,this.sourceExplore=k}get _modelDef(){return this._ownerModelDef}get source(){return this.sourceExplore}get referenceSourceID(){return(0,e.isSourceDef)(this._structDef)?this._structDef.referenceID:void 0}referencedSource(){if(!(0,e.isSourceDef)(this._structDef))return;const M=(0,i.sourceNamespaceReference)(this._ownerModelDef,this._structDef);return M?new b(this._ownerModelDef,M.source):void 0}isIntrinsic(){return(0,e.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(M){return(0,a.annotationToTag)(this._structDef.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this._structDef.annotations,M)}get annotations(){return new a.Annotations(this._structDef.annotations)}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this._ownerModelDef))}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=this.modelAnnotations.parseAsTag().tag),this.parsedModelTag}get name(){return(0,e.activeName)(this.structDef)}getQueryByName(M){const B=this.sourceStructDef;if(!B)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const L=B.fields.find(U=>(0,e.activeName)(U)===M);if(L===void 0)throw new Error(`No such view named \`${M}\``);if(L.type!=="turtle")throw new Error(`\`${M}\` is not a view`);const k={type:"query",structRef:B,pipeline:L.pipeline};return new I(k,this.getSingleExploreModel(),[],M)}getSingleExploreModel(){return new z(this._ownerModelDef,[],[])}get fieldMap(){var M;if(this._fieldMap===void 0){const B=((M=this.source)===null||M===void 0?void 0:M.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(L=>{const k=(0,e.activeName)(L),U=B.get(L.name);if((0,e.isJoined)(L))return[k,new K(L,this,U)];if(L.type==="turtle")return[k,new V(L,this,U)];if(L.type==="string")return[k,new F(L,this,U)];if(L.type==="number")return[k,new w(L,this,U)];if(L.type==="date")return L.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(L.timeframe)?[k,new w({...L,type:"number"},this,U)]:[k,new _(L,this,U)];if(L.type==="timestamp")return[k,new T(L,this,U)];if(L.type==="timestamptz")return[k,new T(L,this,U)];if(L.type==="boolean")return[k,new R(L,this,U)];if(L.type==="json")return[k,new O(L,this,U)];if(L.type==="sql native")return[k,new N(L,this,U)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var M,B,L;if(!this._allFieldsWithOrder){const k=[...((L=(B=(M=this.sourceStructDef)===null||M===void 0?void 0:M.resultMetadata)===null||B===void 0?void 0:B.orderBy)===null||L===void 0?void 0:L.map(Q=>{if(typeof Q.field=="string")return{field:this.fieldMap.get(Q.field),dir:Q.dir};throw new Error("Does not support mapping order by from number.")}))||[]],U=new Set(k.map(Q=>Q.field.name));this._allFieldsWithOrder=[...k,...this.allFields.filter(Q=>!U.has(Q.name)).map(Q=>({field:Q,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(M=>M.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(M=>M.field.isAtomicField()&&M.field.sourceWasDimension())}getFieldByName(M){const B=this.fieldMap.get(M);if(B===void 0)throw new Error(`No such field ${M}.`);return B}getFieldByNameIfExists(M){return this.fieldMap.get(M)}get primaryKey(){var M;return(M=this.sourceStructDef)===null||M===void 0?void 0:M.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof K}get filters(){var M;return(0,e.isSourceDef)(this.structDef)?((M=this.structDef.resultMetadata)===null||M===void 0?void 0:M.filterList)||[]:[]}get limit(){var M,B;return(B=(M=this.sourceStructDef)===null||M===void 0?void 0:M.resultMetadata)===null||B===void 0?void 0:B.limit}get structDef(){return this._structDef}get queryTimezone(){var M;return(M=this.sourceStructDef)===null||M===void 0?void 0:M.queryTimezone}get sourceStructDef(){if((0,e.isSourceDef)(this.structDef))return this.structDef}toJSON(){var M,B;return{_structDef:this._structDef,modelID:this._ownerModelDef.modelID,modelAnnotations:this._ownerModelDef.modelAnnotations,sourceExplore:(M=this.sourceExplore)===null||M===void 0?void 0:M.toJSON(),_parentExplore:(B=this._parentExplore)===null||B===void 0?void 0:B.toJSON()}}static fromJSON(M){const B=M._parentExplore!==void 0?b.fromJSON(M._parentExplore):void 0,L=M.sourceExplore!==void 0?b.fromJSON(M.sourceExplore):void 0;return new b(x(M._structDef,M.modelID,M.modelAnnotations),M._structDef,B,L)}get location(){return this.structDef.location}collectSourceComponents(M){const B=[];if(M.type==="composite"){for(const L of M.sources)B.push(...this.collectSourceComponents(L));return B}if(d(M)){if(M.type==="table")B.push({type:"table",tableName:M.tablePath,componentID:`${M.connection}:${M.tablePath}`,sourceID:`${M.connection}:${M.tablePath}`});else if(M.type==="sql_select")B.push({type:"sql",selectStatement:M.selectStr,componentID:`${M.connection}:${M.selectStr}`,sourceID:`${M.connection}:${M.selectStr}`});else if(M.type==="query_source"){let L;try{L=new I(M.query,this.getSingleExploreModel(),[]).getPreparedResult().sql}catch(U){L=`-- Could not compile SQL for query ${M.query.name||"unnamed query"}: ${U instanceof Error?U.message:String(U)}`}const k=`${M.connection}:${L}`;B.push({type:"sql",selectStatement:L,componentID:k,sourceID:k})}}else return[];for(const L of M.fields)(0,e.isJoined)(L)&&B.push(...this.collectSourceComponents(L));return B}getSourceComponents(){const M={};if((0,e.isSourceDef)(this.structDef)){const B=this.collectSourceComponents(this.structDef);for(const L of B)L.componentID?M[L.componentID]=L:L.sourceID&&(M[L.sourceID]=L)}return Object.values(M)}}sn.Explore=b;class C extends m{constructor(M,B,L){super((0,e.activeName)(M),B,L),this.fieldTypeDef=M,this.parent=B}get type(){switch(this.fieldTypeDef.type){case"string":return y.String;case"boolean":return y.Boolean;case"date":return y.Date;case"timestamp":return y.Timestamp;case"timestamptz":return y.Timestamptz;case"number":return y.Number;case"json":return y.Json;case"sql native":return y.NativeUnsupported;case"error":return y.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const M=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${M}`)}}}tagParse(M){return(0,a.annotationToTag)(this.fieldTypeDef.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this.fieldTypeDef.annotations,M)}get annotations(){return new a.Annotations(this.fieldTypeDef.annotations)}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this.parent._modelDef))}isIntrinsic(){return(0,e.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,e.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const M=this.fieldTypeDef.name||this.fieldTypeDef.as;return M?[M]:[]}get referenceId(){var M;return(M=this.fieldTypeDef.resultMetadata)===null||M===void 0?void 0:M.referenceId}sourceWasMeasure(){var M;return((M=this.fieldTypeDef.resultMetadata)===null||M===void 0?void 0:M.fieldKind)==="measure"}sourceWasMeasureLike(){var M,B;return((M=this.fieldTypeDef.resultMetadata)===null||M===void 0?void 0:M.fieldKind)==="measure"||((B=this.fieldTypeDef.resultMetadata)===null||B===void 0?void 0:B.fieldKind)==="struct"}sourceWasDimension(){var M;return((M=this.fieldTypeDef.resultMetadata)===null||M===void 0?void 0:M.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof F}isNumber(){return this instanceof w}isDate(){return this instanceof _}isBoolean(){return this instanceof R}isJSON(){return this instanceof O}isTimestamp(){return this instanceof T}isUnsupported(){return this instanceof N}get parentExplore(){return this.parent}get expression(){const M=".",B=this.fieldTypeDef.resultMetadata;return(B==null?void 0:B.sourceExpression)||(B!=null&&B.sourceField.includes(M)?B==null?void 0:B.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}sn.AtomicField=C;class _ extends C{constructor(M,B,L){super(M,B,L),this.fieldDateDef=M}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return E.Day;case"week":return E.Week;case"month":return E.Month;case"quarter":return E.Quarter;case"year":return E.Year}}}sn.DateField=_;class T extends C{constructor(M,B,L){super(M,B,L),this.fieldTimestampDef=M}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return v.Day;case"week":return v.Week;case"month":return v.Month;case"quarter":return v.Quarter;case"year":return v.Year;case"second":return v.Second;case"hour":return v.Hour;case"minute":return v.Minute}}}sn.TimestampField=T;class w extends C{constructor(M,B,L){super(M,B,L),this.fieldNumberDef=M}}sn.NumberField=w;class R extends C{constructor(M,B,L){super(M,B,L),this.fieldBooleanDef=M}}sn.BooleanField=R;class O extends C{constructor(M,B,L){super(M,B,L),this.fieldJSONDef=M}}sn.JSONField=O;class N extends C{constructor(M,B,L){super(M,B,L),this.fieldUnsupportedDef=M}get rawType(){return this.fieldUnsupportedDef.rawType}}sn.UnsupportedField=N;class F extends C{constructor(M,B,L){super(M,B,L),this.fieldStringDef=M}}sn.StringField=F;class $ extends m{constructor(M,B,L){super((0,e.activeName)(M),B,L),this.turtleDef=M}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}tagParse(M){return(0,a.annotationToTag)(this.turtleDef.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this.turtleDef.annotations,M)}get annotations(){return new a.Annotations(this.turtleDef.annotations)}get modelAnnotations(){var M;const B=(M=this._parent)===null||M===void 0?void 0:M._modelDef;return new a.Annotations(B&&(0,e.getModelAnnotations)(B))}}sn.Query=$;class V extends ${constructor(M,B,L){super(M,B,L),this.parent=B}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const M=this.turtleDef.name||this.turtleDef.as;return M?[M]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}sn.QueryField=V;class K extends b{constructor(M,B,L){super(B._modelDef,M,B,L),this._parentExplore=B}get joinRelationship(){if((0,e.isJoined)(this.structDef))switch(this.structDef.join){case"one":return S.OneToOne;case"many":case"cross":return S.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===S.OneToOne}get isArray(){return this.joinRelationship!==S.OneToOne}tagParse(M){return(0,a.annotationToTag)(this._structDef.annotations,M)}get annotations(){return new a.Annotations(this._structDef.annotations)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const M=this.structDef.name||this.structDef.as;return M?[M]:[]}get queryTimezone(){return(0,e.isRecordOrRepeatedRecord)(this._structDef)?this._structDef.queryTimezone:super.queryTimezone}}sn.ExploreField=K;const ne={fieldReference:"field",joinReference:"join",exploreReference:"explore",queryReference:"query",sqlBlockReference:"sqlBlock",givenReference:"given"};class le{constructor(M){this._ref=M}get text(){return this._ref.text}get kind(){return ne[this._ref.type]}get location(){return this._ref.location}get definitionLocation(){return this._ref.definition.location}get definitionType(){return this._ref.definition.type}get defaultText(){if(this._ref.type==="givenReference")return this._ref.definition.defaultText}get annotations(){return new a.Annotations(this._ref.definition.annotations)}}sn.Reference=le;class z{constructor(M,B,L,k,U){var Q,J;this.modelDef=M,this.problems=B,this.fromSources=L,this.runtimeContext=U,this.references=new f.ReferenceList((Q=L[0])!==null&&Q!==void 0?Q:"",(J=M.references)!==null&&J!==void 0?J:[]),this._queryModel=k,this.contentsMap=new Map(Object.entries(M.contents))}getContent(M){return this.contentsMap.get(M)}get queryModel(){return this._queryModel||(this._queryModel=new e.QueryModel(this.modelDef)),this._queryModel}getExistingQueryModel(){return this._queryModel}get givens(){var M,B;const L=new Map,k=this.modelDef.givens;if(!k)return L;for(const[U,Q]of this.contentsMap){if(Q.type!=="given"||!((B=(M=this.runtimeContext)===null||M===void 0?void 0:M.finalizedGivens)===null||B===void 0)&&B.has(U))continue;const J=k[Q.id];J&&!J.inline&&L.set(U,new se(U,Q.id,J,this.modelDef))}return L}get _ownModelAnnotations(){var M;return(M=this.modelDef.modelAnnotations[this.modelDef.modelID])===null||M===void 0?void 0:M.ownNotes}tagParse(M){return(0,a.annotationToTag)(this._ownModelAnnotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this._ownModelAnnotations,M)}get annotations(){return new a.Annotations(this._ownModelAnnotations)}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this.modelDef))}referenceAt(M){const B=this.references.find(M);return B?new le(B):void 0}getReference(M){return this.references.find(M)}getImport(M){var B;return(B=this.modelDef.imports)===null||B===void 0?void 0:B.find(L=>(0,l.locationContainsPosition)(L.location,M))}getPreparedQueryByName(M){const B=this.getContent(M);if((B==null?void 0:B.type)==="query")return new I(B,this,this.problems,M);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(M){if(M<0)throw new Error(`Invalid index ${M}.`);if(M>=this.modelDef.queryList.length)throw new Error(`Query index ${M} is out of bounds.`);return new I(this.modelDef.queryList[M],this,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new I(this.modelDef.queryList[this.modelDef.queryList.length-1],this,this.problems)}getExploreByName(M){const B=this.getContent(M);if(B&&(0,e.isSourceDef)(B))return new b(this.modelDef,B);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(e.isSourceDef).map(M=>new b(this.modelDef,M))}queries(){const M=[];for(const B of Object.values(this.modelDef.contents))B.type==="query"&&M.push(B.name);return{named:M,unnamed:this.modelDef.queryList.length}}get namedQueries(){const M=B=>B.type==="query";return Object.values(this.modelDef.contents).filter(M)}get exportedExplores(){return this.explores.filter(M=>this.modelDef.exports.includes(M.name))}get _modelDef(){return this.modelDef}getBuildPlan(){if(!this.modelAnnotations.parseAsTag("!").tag.has("experimental","persistence"))throw new Error("Model must have ##! experimental.persistence to use getBuildPlan()");const B=[],L=[];for(const ie of Object.values(this.modelDef.contents))(ie.type==="query"||(0,e.isSourceDef)(ie))&&B.push(...(0,r.findPersistentDependencies)(ie,this.modelDef,L));for(const ie of this.modelDef.queryList)B.push(...(0,r.findPersistentDependencies)(ie,this.modelDef,L));if(B.length===0)return{graphs:[],sources:{},tagParseLog:L};const k=(0,r.minimalBuildGraph)(B),U={},Q=ie=>{for(const ae of ie){if(!(ae.sourceID in U)){const de=(0,i.resolveSourceID)(this.modelDef,ae.sourceID);de&&(U[ae.sourceID]=new X(new b(this.modelDef,de),this))}Q(ae.dependsOn)}};Q(k);const J=new Map;for(const ie of k){const ae=U[ie.sourceID];if(!ae)continue;const de=ae.connectionName;J.has(de)||J.set(de,[]),J.get(de).push(ie)}const W=[];for(const[ie,ae]of J)W.push({connectionName:ie,nodes:[ae]});return{graphs:W,sources:U,tagParseLog:L}}}sn.Model=z;class X{constructor(M,B){this.explore=M,this.model=B;const L=M.structDef;if(!(0,e.isSourceDef)(L))throw new Error("Cannot create PersistSource from non-source type");if(!(0,e.isPersistableSourceDef)(L))throw new Error(`Cannot persist source '${M.name}' of type '${L.type}'. Only query_source and sql_select sources can be persisted.`);this.persistableDef=L}get name(){return this.explore.name}get sourceID(){const M=this.persistableDef.sourceID;if(!M)throw new Error(`PersistSource '${this.name}' has no sourceID. This should not happen - sourceID is set at translation time.`);return M}get _explore(){return this.explore}get annotation(){return this.persistableDef.annotations}tagParse(M){return this.explore.tagParse(M)}getTaglines(M){return this.explore.getTaglines(M)}get annotations(){return this.explore.annotations}get modelAnnotations(){return this.explore.modelAnnotations}get connectionName(){return this.persistableDef.connection}get dialectName(){return this.persistableDef.dialect}get dialect(){return(0,n.getDialect)(this.dialectName)}makeBuildId(M,B){return(0,i.mkBuildID)(M,B)}getSQL(M){const B=this.persistableDef,L=this.model.queryModel;return B.type==="sql_select"?(0,e.getCompiledSQL)(B,M??{},(k,U)=>L.compileQuery(k,U).sql):L.compileQuery(B.query,M).sql}get _sourceDef(){return this.persistableDef}get _model(){return this.model}}sn.PersistSource=X;class se{constructor(M,B,L,k){this.name=M,this.id=B,this._internal=L,this._modelDef=k}get type(){return this._internal.type}get default(){return this._internal.default}get location(){return this._internal.location}tagParse(M){return(0,a.annotationToTag)(this._internal.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this._internal.annotations,M)}get annotations(){return new a.Annotations(this._internal.annotations)}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this._modelDef))}}sn.Given=se;class fe{constructor(M){this.pipelineDef=M}get annotations(){return new a.Annotations(this.pipelineDef.annotations)}get location(){return this.pipelineDef.location}tagParse(M){return(0,a.annotationToTag)(this.pipelineDef.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this.pipelineDef.annotations,M)}}class I extends fe{constructor(M,B,L,k){super(M),this._model=B,this.problems=L,this.name=k}get _query(){return this.pipelineDef}get _modelDef(){return this._model._modelDef}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this._modelDef))}get preparedResult(){return this.getPreparedResult()}getPreparedResult(M){const B=this._model.queryModel,L=M!=null&&M.givens?(0,s.resolveSuppliedGivens)(M.givens,this._modelDef):new Map;(0,s.evaluateInlineGivens)(L,this._modelDef);const k={...M,resolvedGivens:L.size>0?L:void 0},U=B.compileQuery(this._query,k);return new q({...U,queryName:this.name||U.queryName},this._modelDef)}get dialect(){const M=this._query.structRef,B=typeof M=="string"?this._model.getContent(M):M;if(B===void 0||!(0,e.isSourceDef)(B))throw new Error("Invalid source for query");return B.dialect}getFlattenedQuery(M){return this}get model(){return this._model}get givens(){const M=new Map,B=this._query.givenUsage;if(!B||B.length===0)return M;const L=new Set(B.map(k=>k.id));for(const[k,U]of this._model.givens)L.has(U.id)&&M.set(k,U);return M}}sn.PreparedQuery=I;class q{constructor(M,B){this.modelDef=B,this.inner=M}static fromJson({query:M,modelDef:B}){if(!M||!B)throw new Error("Missing required properties in JSON data");return new q(M,B)}tagParse(M){return(0,a.annotationToTag)(this.inner.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this.inner.annotations,M)}get annotations(){return new a.Annotations(this.inner.annotations)}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this.modelDef))}get annotation(){return this.inner.annotations}get modelAnnotation(){return(0,e.getModelAnnotations)(this.modelDef)}get modelTag(){return new a.Annotations((0,e.getModelAnnotations)(this.modelDef)).parseAsTag().tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const M=this.inner.structs[this.inner.structs.length-1],B={...M,annotations:this.inner.annotations,name:this.inner.queryName||M.name};try{return new b(this.modelDef,B,this.sourceExplore)}catch{return new b(this.modelDef,B)}}get sourceExplore(){const M=this.inner.sourceExplore,B=(0,e.safeRecordGet)(this.modelDef.contents,M);if(B&&(0,e.isSourceDef)(B))return new b(this.modelDef,B)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceArguments(){return this.inner.sourceArguments}get _sourceFilters(){return this.inner.sourceFilters||[]}get hasSchema(){return this.inner.structs.length>0}toStableResult(M){const B=this.inner.structs,L=B[B.length-1],k={fields:(0,u.convertFieldInfos)(L,L.fields)},U=(0,u.toStableAnnotations)(this.inner.annotations),Q=L.resultMetadata?(0,u.getResultStructMetadataAnnotation)(L,L.resultMetadata):void 0;Q&&U.push(Q);const J=o.Tag.withPrefix("#(malloy) "),W=this.sourceExplore;if(W&&J.set(["source","name"],W.name),this._sourceArguments){const ae=Object.entries(this._sourceArguments);for(let de=0;de<ae.length;de++){const[pe,Se]=ae[de],ye=(0,c.nodeToLiteralValue)(Se.value);ye!==void 0&&(0,u.writeLiteralToTag)(J,["source","parameters",de,"value"],ye),J.set(["source","parameters",de,"name"],pe)}}U.push({value:J.toString()}),U.push({value:o.Tag.withPrefix("#(malloy) ").set(["query_name"],this.inner.queryName||L.name).toString()});const ie=(0,u.toStableAnnotations)((0,e.getModelAnnotations)(this.modelDef));return{schema:k,data:M,connection_name:this.inner.connectionName,annotations:U.length>0?U:void 0,model_annotations:ie.length>0?ie:void 0,query_timezone:L.queryTimezone,sql:this.inner.sql}}}return sn.PreparedResult=q,sn}var yd={},Fce;function Lce(){if(Fce)return yd;Fce=1,Object.defineProperty(yd,"__esModule",{value:!0}),yd.DataRecord=yd.DataArray=yd.Result=void 0;const e=Si(),t=Vv(),n=aw();class r extends n.PreparedResult{constructor(O,N){super(O,N),this.inner=O}get _queryResult(){return this.inner}get data(){return new T(this.inner.result,this.resultExplore,void 0,void 0)}get totalRows(){return this.inner.totalRows}get runStats(){return this.inner.runStats}get profilingUrl(){return this.inner.profilingUrl}toJSON(){return this.hasSchema?{queryResult:{...this.inner,result:this.data.toJSON()},modelDef:this._modelDef}:{queryResult:this.inner,modelDef:this._modelDef}}static fromJSON({queryResult:O,modelDef:N}){return new r(O,N)}}yd.Result=r;class i{constructor(O,N,F){this.parent=N,this.parentRecord=F,this._field=O}get field(){return this._field}isString(){return this instanceof o}get string(){if(this.isString())return this;throw new Error("Not a string.")}isBoolean(){return this instanceof u}get boolean(){if(this.isBoolean())return this;throw new Error("Not a boolean.")}isNumber(){return this instanceof l}get number(){if(this.isNumber())return this;throw new Error("Not a number.")}isTimestamp(){return this instanceof f}get timestamp(){if(this.isTimestamp())return this;throw new Error("Not a timestamp.")}isDate(){return this instanceof d}get date(){if(this.isDate())return this;throw new Error("Not a date.")}isNull(){return this instanceof x}isBytes(){return this instanceof p}get bytes(){if(this.isBytes())return this;throw new Error("Not bytes.")}isRecord(){return this instanceof w}get record(){if(this.isRecord())return this;throw new Error("Not a record.")}isUnsupported(){return this instanceof a}get unsupported(){if(this.isUnsupported())return this;throw new Error("Not unsupported.")}isArray(){return this instanceof T}get array(){if(this.isArray())return this;throw new Error("Not an array.")}isArrayOrRecord(){if(this instanceof T||this instanceof w)return this;throw new Error("No Array or Record")}isScalar(){return!0}}class s extends i{constructor(O,N,F,$){super(N,F,$),this._value=O,this._field=N}get value(){return this._value}get field(){return this._field}isScalar(){return this instanceof s}}class o extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get field(){return this._field}get key(){return this.value}compareTo(O){return this.value.toLocaleLowerCase().localeCompare(O.value.toLocaleLowerCase())}}class a extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get field(){return this._field}get key(){return"<unsupported>"}compareTo(O){return 0}}class u extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get field(){return this._field}get key(){return`${this.value}`}compareTo(O){return this.value===O.value?0:this.value?1:-1}}class c extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get field(){return this._field}get key(){return this.value}compareTo(O){const N=this.value.toString(),F=O.toString();return N===F?0:N>F?1:-1}}class l extends s{constructor(O,N,F,$){super((0,t.rowDataToNumber)(O),N,F,$),this._field=N}get field(){return this._field}get key(){return`${this.value}`}compareTo(O){const N=this.value-O.value;return N>0?1:N===0?0:-1}}class f extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get value(){return(0,t.rowDataToDate)(this._value)}get field(){return this._field}get key(){return`${this.value.toLocaleString()}`}compareTo(O){return this.value>O.value?1:this.value<O.value?-1:0}}class d extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get value(){return(0,t.rowDataToDate)(this._value)}get field(){return this._field}get key(){return`${this.value.toLocaleString()}`}compareTo(O){return this.value>O.value?1:this.value<O.value?-1:0}}class p extends s{get key(){return this.value.toString()}compareTo(O){const N=this.value.toString(),F=O.toString();return N===F?0:N>F?1:-1}}class x extends i{get value(){return null}get key(){return"<null>"}}function m(R){const O=(0,t.rowDataToSerializedBigint)(R);if(O.includes(".")||O.includes("e")||O.includes("E"))return(0,t.rowDataToNumber)(R);try{return BigInt(O)}catch{return(0,t.rowDataToNumber)(R)}}function g(R){const O=(0,t.rowDataToSerializedBigint)(R);return O.includes(".")||O.includes("e")||O.includes("E")?(0,t.rowDataToNumber)(R):O}const y={number:t.rowDataToNumber,bigint:m,date:t.rowDataToDate},E={number:t.rowDataToNumber,bigint:g,date:R=>(0,t.rowDataToDate)(R).toISOString()};function v(R,O,N){return R.map(F=>S(F,O,N))}function S(R,O,N){const F={};for(const $ of O.fields){const V=(0,e.activeName)($),K=R[V];F[V]=b(K,$,N)}return F}function b(R,O,N){if(R==null)return null;if(O.type==="number")return O.numberType==="bigint"?N.bigint(R):N.number(R);if(O.type==="date"||O.type==="timestamp"||O.type==="timestamptz")return N.date(R);if(O.type==="string"||O.type==="boolean"||O.type==="json"||O.type==="sql native")return O.type==="boolean"&&typeof R=="number"?R!==0:R;if(O.type==="array"){if(!Array.isArray(R))return R;if((0,e.isRepeatedRecord)(O))return R.map(F=>S(F,O,N));if((0,e.isBasicArray)(O)){const F=O.elementTypeDef;return R.map($=>C($,F,N))}}return O.type==="record"&&typeof R=="object"&&R!==null&&!Array.isArray(R)?S(R,O,N):R}function C(R,O,N){if(R==null)return null;if(O.type==="number")return O.numberType==="bigint"?N.bigint(R):N.number(R);if(O.type==="date"||O.type==="timestamp"||O.type==="timestamptz")return N.date(R);if(O.type==="boolean"&&typeof R=="number")return R!==0;if(O.type==="array"&&Array.isArray(R)){if((0,e.isBasicArray)(O)){const F=O.elementTypeDef;return R.map($=>C($,F,N))}else if((0,e.isRepeatedRecord)(O))return R.map(F=>S(F,O,N))}return R}function _(R,O){for(const N of O)typeof N=="number"?R=R.array.row(N):R=R.record.cell(N);return R}class T extends i{constructor(O,N,F,$){super(N,F,$),this.rowCache=new Map,this.queryData=O,this._field=N}get field(){return this._field}get rawData(){return this.queryData}toObject(){return v(this.queryData,this._field.structDef,y)}toJSON(){return v(this.queryData,this._field.structDef,E)}path(...O){return _(this,O)}row(O){let N=this.rowCache.get(O);return N||(N=new w(this.queryData[O],O,this.field,this,this.parentRecord),this.rowCache.set(O,N)),N}get rowCount(){return this.queryData.length}get value(){return this.toObject()}[Symbol.iterator](){let O=0;const N=this.queryData,F=$=>this.row($);return{next(){return O<N.length?{value:F(O++),done:!1}:{value:void 0,done:!0}}}}async*inMemoryStream(){for(let O=0;O<this.queryData.length;O++)yield this.row(O)}}yd.DataArray=T;class w extends i{constructor(O,N,F,$,V){super(F,$,V),this.cellCache=new Map,this.queryDataRow=O,this._field=F,this.index=N}toObject(){return S(this.queryDataRow,this._field.structDef,y)}toJSON(){return S(this.queryDataRow,this._field.structDef,E)}path(...O){return _(this,O)}cell(O){const N=typeof O=="string"?O:O.name,F=this._field.getFieldByName(N);let $=this.cellCache.get(N);if(!$){const V=this.queryDataRow[N];V===null?$=new x(F,this,this):F.isAtomicField()?F.isBoolean()?$=new u(V,F,this,this):F.isDate()?$=new d(V,F,this,this):F.isJSON()?$=new c(V,F,this,this):F.isTimestamp()?$=new f(V,F,this,this):F.isNumber()?$=new l(V,F,this,this):F.isString()?$=new o(V,F,this,this):F.isUnsupported()&&($=new a(V,F,this,this)):F.isExploreField()&&((0,e.isCompoundArrayData)(V)?$=new T(V,F,this,this):$=new w(V,void 0,F,this,this)),$&&this.cellCache.set(N,$)}if($)return $;throw new Error(`Internal Error: could not construct data column for field '${N}'.`)}get value(){throw new Error("Not implemented;")}get field(){return this._field}[Symbol.iterator](){let O=!1;const N=()=>this;return{next(){return O?{value:void 0,done:!0}:(O=!0,{value:N(),done:!1})}}}}return yd.DataRecord=w,yd}var Ed={},Ice;function r9e(){if(Ice)return Ed;Ice=1,Object.defineProperty(Ed,"__esModule",{value:!0}),Ed.CSVWriter=Ed.JSONWriter=Ed.DataWriter=void 0;const e=Si();class t{constructor(s){this.stream=s}}Ed.DataWriter=t;class n extends t{async process(s){this.stream.write(`[
1363
+ `,J=!0;else if(W===s)Q--;else if(W===r)Q++;else{if(W===o)continue;J&&(U+=" ".repeat(Q*k),J=!1),U+=W}return U}function u(L,k,U,Q){var J;if(k.includes(i))return[L,i,r,...k,i,s,U];const ie=((J=Q==null?void 0:Q.spaces)!==null&&J!==void 0?J:!0)?" ":"";return[L,ie,...k,ie,U]}function c(L){return{contents:L,quoteCharacter:'"'}}function l(L,k){const U=[];for(let Q=0;Q<L.length;Q++){const J=L[Q];U.push(J),Q<L.length-1&&U.push(k)}return U}function f(L){var k,U;switch(L.kind){case"filter_expression_literal":return[fe(L.filter_expression_value)];case"boolean_literal":return[L.boolean_value.toString()];case"string_literal":{const{contents:Q,quoteCharacter:J}=c(L.string_value);return[J,Q,J]}case"number_literal":return[L.number_value.toString()];case"null_literal":return["null"];case"date_literal":return[p(d(L.date_value),(k=L.granularity)!==null&&k!==void 0?k:"day",L.timezone)];case"timestamp_literal":return[p(d(L.timestamp_value),(U=L.granularity)!==null&&U!==void 0?U:"second",L.timezone)]}}function d(L){let k;if(k=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)/.exec(L)){const[U,Q,J,W,ie,ae,de]=k;return[Q,J,W,ie,ae,de]}else if(k=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d)/.exec(L)){const[U,Q,J,W,ie,ae]=k;return[Q,J,W,ie,ae,"00"]}else if(k=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d)(?:00)?/.exec(L)){const[U,Q,J,W,ie]=k;return[Q,J,W,ie,"00","00"]}else if(k=/(\d\d\d\d)-(\d\d)-(\d\d)/.exec(L)){const[U,Q,J,W]=k;return[Q,J,W,"00","00","00"]}else if(k=/(\d\d\d\d)-(\d\d)/.exec(L)){const[U,Q,J]=k;return[Q,J,"01","00","00","00"]}else if(k=/(\d\d\d\d)/.exec(L)){const[U,Q]=k;return[Q,"01","01","00","00","00"]}return["1970","01","01","00","00","00"]}function p([L,k,U,Q,J,W],ie,ae){switch(ie){case"year":return`@${L}`;case"quarter":{const de=Math.floor(+k/3)+1;return`@${L}-Q${de}`}case"month":return`@${L}-${k}`;case"week":return`@${L}-${k}-${U}-WK`;case"day":return`@${L}-${k}-${U}`;case"hour":return`@${L}-${k}-${U} ${Q}`;case"minute":return`@${L}-${k}-${U} ${Q}:${J}`;case"second":return ae!==void 0?`@${L}-${k}-${U} ${Q}:${J}:${W}[${ae}]`:`@${L}-${k}-${U} ${Q}:${J}:${W}`;default:throw new Error("Unknown timeframe.")}}function x(L){var k;const U=[];for(const Q of(k=L.path)!==null&&k!==void 0?k:[])U.push((0,e.maybeQuoteIdentifier)(Q)),U.push(".");if(U.push((0,e.maybeQuoteIdentifier)(L.name)),L.parameters){const Q=[];for(let J=0;J<L.parameters.length;J++){const W=L.parameters[J];Q.push((0,e.maybeQuoteIdentifier)(W.name)),Q.push(" is "),Q.push(...f(W.value)),J<L.parameters.length-1&&Q.push(",",i)}U.push(...u("(",Q,")",{spaces:!1}))}return U}function m(L){const k=[];return k.push(...M(L.annotations)),k.push("run: "),k.push(...y(L.definition)),k}function g(L){const k=[];switch(L.kind){case"source_reference":{k.push(...x(L));break}case"refinement":k.push(...y(L));break}return k}function y(L){const k=[];switch(L.kind){case"arrow":{k.push(...g(L.source)),k.push(" -> "),k.push(...E(L.view));break}case"query_reference":{k.push(...x(L));break}case"refinement":{const U=y(L.base);L.base.kind==="arrow"?k.push(...u("(",U,")",{spaces:!1})):k.push(...U),k.push(" + "),k.push(...E(L.refinement));break}}return k}function E(L){const k=[];switch(L.kind){case"arrow":{k.push(...E(L.source)),k.push(" -> "),k.push(...E(L.view));break}case"view_reference":{k.push(...x(L));break}case"refinement":{k.push(...E(L.base)),k.push(" + "),k.push(...E(L.refinement));break}case"segment":{k.push(...v(L));break}}return k}function v(L){if(L.operations.length===0)return["{ }"];const k=L.operations.length>1,U=[];for(let Q=0;Q<L.operations.length;Q++){const J=L.operations[Q],W=[J];for(;Q<L.operations.length-1;){const ie=L.operations[Q+1];if(ie.kind===J.kind)W.push(ie),Q++;else break}U.push(...S(W)),k&&Q<L.operations.length-1&&U.push(i)}return u("{",U,"}")}function S(L){switch(L[0].kind){case"aggregate":return R(L,"aggregate");case"group_by":return R(L,"group_by");case"order_by":return O(L);case"nest":return F(L);case"limit":return ne(L);case"where":return le(L);case"having":return X(L);case"drill":return z(L);case"calculate":return R(L,"calculate")}}function b(L,k,U=""){const Q=[];Q.push(`${L}:`);const J=k.length>1||k.some(W=>W.includes(i));J?Q.push(i,r):Q.push(" ");for(let W=0;W<k.length;W++){const ie=k[W];Q.push(...ie),k.length>1&&W<k.length-1&&Q.push(U),J&&W<k.length-1&&Q.push(i)}return J&&Q.push(s),Q}function C(L){const k=[];return k.push(...T(L.expression)),k}function _(L){return L}function T(L){var k;switch(L.kind){case"field_reference":return x(L);case"time_truncation":return[...x(L.field_reference),".",L.truncation];case"filtered_field":return[...x(L.field_reference),...u(" {",le(L.where),"}")];case"literal_value":return f(L.literal_value);case"moving_average":{const U=["avg_moving",...u("(",[...x(L.field_reference),L.rows_preceding!==void 0?`, ${L.rows_preceding}`:", 0",L.rows_following!==void 0?`, ${L.rows_following}`:""],")",{spaces:!1})];return!((k=L.partition_fields)===null||k===void 0)&&k.length&&U.push(...u(" {",["partition_by",": ",...l(L.partition_fields.flatMap(Q=>x(Q)),", ")],"}")),U}}}function w(L,k=!1){const U=[];return k||U.push(...M(L.field.annotations)),L.name&&(U.push((0,e.maybeQuoteIdentifier)(L.name)),U.push(" is ")),U.push(...C(L.field)),U}function R(L,k){const U=[],Q=L.length===1;return Q&&U.push(...M(L[0].field.annotations)),U.push(...b(k,L.map(J=>w(J,Q)))),U}function O(L){return b("order_by",L.map(N),",")}function N(L){const k=[];return k.push(...x(L.field_reference)),L.direction&&(k.push(" "),k.push(L.direction)),k}function F(L){const k=[],U=L.length===1;return U&&k.push(...M(L[0].view.annotations)),k.push(...b("nest",L.map(Q=>$(Q,U)))),k}function $(L,k=!1){const U=[];return k||U.push(...M(L.view.annotations)),L.name&&(U.push((0,e.maybeQuoteIdentifier)(L.name)),U.push(" is ")),U.push(...V(L.view)),U}function V(L){return E(L.definition)}function K(L){return[`limit: ${L.limit}`]}function ne(L){const k=[];for(let U=0;U<L.length;U++)U!==0&&k.push(i),k.push(...K(L[U]));return k}function le(L){return b("where",L.map(j),",")}function z(L){return b("drill",L.map(j),",")}function X(L){return b("having",L.map(j),",")}const se=["`","'",'"'];function fe(L){let k,U;for(const Q of se){const J=I(L,Q);if(J===L)return`f${Q}${L}${Q}`;(U===void 0||J.length<U.length)&&(k=Q,U=J)}return`f${k}${U}${k}`}function I(L,k){let U="";for(let Q=0;Q<L.length;Q++)L.slice(Q).startsWith(k)?(U+="\\"+k,Q+=k.length):(U+=L[Q],L[Q]==="\\"&&(U+=L[++Q]));return U}function q(L){switch(L.kind){case"filter_string":return[...T(L.expression)," ~ ",fe(L.filter)];case"literal_equality":return[...T(L.expression)," = ",...f(L.value)]}}function j(L){return q(L.filter)}function M(L){return L?L.flatMap(B):[]}function B(L){return[L.value.trim(),i]}return qA}var L1={},vce;function ZIe(){if(vce)return L1;vce=1,Object.defineProperty(L1,"__esModule",{value:!0}),L1.nestUnions=t,L1.unnestUnions=n,L1.convertFromThrift=r,L1.convertToThrift=s;const e=mce();function t(o){if(o==null)return o;if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(Array.isArray(o))return o.map(t);{const a={};let u;for(const c in o)c==="kind"?u=o[c]:a[c]=t(o[c]);return u===void 0?a:{[u]:a}}}function n(o,a){if(o==null)return o;if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(Array.isArray(o))return o.map(u=>n(u,a));{const u=i(a);if(u.type==="union"){for(const c in u.options)if(o[c]!==void 0){const l=n(o[c],u.options[c]);if(typeof l=="object")return{kind:c,...l}}}else if(u.type==="struct"){const c={};for(const l in o){const f=u.fields[l];if(f===void 0)throw new Error(`Unknown field ${l} in ${a}`);c[l]=n(o[l],f.type)}return c}else throw new Error(`Cannot unnest unions in an enum type ${a}`)}}function r(o,a){if(o==null)return o;if(typeof o=="string"||typeof o=="boolean")return o;if(typeof o=="number"){if(a==="number")return o;const u=i(a);if(u.type!=="enum")throw new Error(`Found a number where a ${a} was expected`);const c=Object.entries(u.values).find(([,l])=>l===o);if(c===void 0)throw new Error(`${o} is not a valid enum value for ${a}`);return c[0]}else{if(Array.isArray(o))return o.map(u=>r(u,a));{const u=i(a);if(u.type==="union"){for(const c in u.options)if(o[c]!==void 0&&o[c]!==null){const l=r(o[c],u.options[c]);if(typeof l=="object")return{kind:c,...l}}}else if(u.type==="struct"){const c={};for(const l in o){const f=u.fields[l];if(f===void 0)throw new Error(`Unknown field ${l} in ${a}`);c[l]=r(o[l],f.type)}return c}else throw new Error(`Cannot unnest unions in an enum type ${a}`)}}}function i(o){const a=e.MALLOY_INTERFACE_TYPES[o];if(a===void 0)throw new Error(`Unknown Malloy interface type ${o}`);return a}function s(o,a){if(o==null)return o;if(typeof o=="number"||typeof o=="boolean")return o;if(typeof o=="string"){if(a==="string")return o;const u=i(a);if(u.type==="enum"){const c=u.values[o];if(c===void 0)throw new Error(`${o} is not a valid enum value for ${a}`);return c}}else{if(Array.isArray(o))return o.map(u=>s(u,a));{const u=i(a);if(u.type==="union"){const c=o.kind,l=u.options[c];if(l===void 0)throw new Error(`${c} is not a valid union of ${a}`);const f=i(l);if(f.type!=="struct")throw new Error("Union fields must be structs");const d={};for(const p in o){if(p==="kind")continue;const x=f.fields[p];d[p]=s(o[p],x.type)}return{[c]:d}}else if(u.type==="struct"){const c={};for(const l in o){const f=u.fields[l];if(f===void 0)throw new Error(`Unknown field ${l} in ${a}`);c[l]=s(o[l],f.type)}return c}}}}return L1}var _ce;function iw(){return _ce||(_ce=1,function(e){var t=F1&&F1.__createBinding||(Object.create?function(s,o,a,u){u===void 0&&(u=a);var c=Object.getOwnPropertyDescriptor(o,a);(!c||("get"in c?!o.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(s,u,c)}:function(s,o,a,u){u===void 0&&(u=a),s[u]=o[a]}),n=F1&&F1.__exportStar||function(s,o){for(var a in s)a!=="default"&&!Object.prototype.hasOwnProperty.call(o,a)&&t(o,s,a)};Object.defineProperty(e,"__esModule",{value:!0}),e.thingy4sddfdfsd=e.thingy4sdfsd=e.thingy4dfdsfs=e.thingy4asdfas=e.thingy4asdfasdf=e.thingy3dfdf=e.thingy3=e.thingy2asdf=e.thingyssdfg=e.thingy123r=e.thingy1=e.res=e.test=e.convertToThrift=e.convertFromThrift=e.unnestUnions=e.nestUnions=e.filterToMalloy=e.queryToMalloy=void 0,n(mce(),e);var r=JIe();Object.defineProperty(e,"queryToMalloy",{enumerable:!0,get:function(){return r.queryToMalloy}}),Object.defineProperty(e,"filterToMalloy",{enumerable:!0,get:function(){return r.filterToMalloy}});var i=ZIe();Object.defineProperty(e,"nestUnions",{enumerable:!0,get:function(){return i.nestUnions}}),Object.defineProperty(e,"unnestUnions",{enumerable:!0,get:function(){return i.unnestUnions}}),Object.defineProperty(e,"convertFromThrift",{enumerable:!0,get:function(){return i.convertFromThrift}}),Object.defineProperty(e,"convertToThrift",{enumerable:!0,get:function(){return i.convertToThrift}}),e.test={entries:[{kind:"source",name:"flights",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"boolean_type"},annotations:[{value:"# foo=1"}]},{kind:"dimension",name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}},{kind:"dimension",name:"arr_rec",type:{kind:"array_type",element_type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}}},{kind:"dimension",name:"rec",type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}},{kind:"join",name:"carriers",relationship:"one",schema:{fields:[{kind:"dimension",name:"code",type:{kind:"string_type"}}]}},{kind:"view",name:"by_carrier",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]}}]},parameters:[{name:"param",type:{kind:"number_type"},default_value:{kind:"number_literal",number_value:7}}]}],anonymous_queries:[]},e.res={connection_name:"foo",data:{kind:"array_cell",array_value:[{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"UA"},{kind:"number_cell",number_value:12341234}]},{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"AA"},{kind:"number_cell",number_value:2343}]}]},schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]},sql:"SELECT * ..."},e.thingy1={definition:{kind:"query_reference",name:"flights_by_carrier"}},e.thingy123r={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},e.thingyssdfg={definition:{kind:"refinement",base:{kind:"query_reference",name:"flights"},refinement:{kind:"view_reference",name:"by_carrier"}}},e.thingy2asdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"where",filter:{kind:"filter_string",expression:{kind:"field_reference",name:"carrier"},filter:"WN"}}]}}}},e.thingy3={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}}},e.thingy3dfdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"view_reference",name:"top10"}}}},e.thingy4asdfasdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}},e.thingy4asdfas={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},e.thingy4dfdsfs={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"limit",limit:10}]}}}},e.thingy4sdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"limit",limit:10}]}}},e.thingy4sddfdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[]}}}}(F1)),F1}var Sce;function sw(){if(Sce)return to;Sce=1;var e=to&&to.__createBinding||(Object.create?function(R,O,N,F){F===void 0&&(F=N);var $=Object.getOwnPropertyDescriptor(O,N);(!$||("get"in $?!O.__esModule:$.writable||$.configurable))&&($={enumerable:!0,get:function(){return O[N]}}),Object.defineProperty(R,F,$)}:function(R,O,N,F){F===void 0&&(F=N),R[F]=O[N]}),t=to&&to.__setModuleDefault||(Object.create?function(R,O){Object.defineProperty(R,"default",{enumerable:!0,value:O})}:function(R,O){R.default=O}),n=to&&to.__importStar||function(){var R=function(O){return R=Object.getOwnPropertyNames||function(N){var F=[];for(var $ in N)Object.prototype.hasOwnProperty.call(N,$)&&(F[F.length]=$);return F},R(O)};return function(O){if(O&&O.__esModule)return O;var N={};if(O!=null)for(var F=R(O),$=0;$<F.length;$++)F[$]!=="default"&&e(N,O,F[$]);return t(N,O),N}}();Object.defineProperty(to,"__esModule",{value:!0}),to.sourceDefToSourceInfo=a,to.modelDefToModelInfo=u,to.toStableAnnotations=l,to.convertFieldInfos=f,to.writeLiteralToTag=m,to.getResultStructMetadataAnnotation=E;const r=n(iw()),i=Si(),s=cm(),o=kc();function a(R){const O=R.parameters&&Object.entries(R.parameters).length>0?Object.entries(R.parameters).map(([F,$])=>(0,i.isAtomic)($)?{name:F,type:v($),default_value:c($.value)}:{name:F,type:{kind:"filter_expression_type",filter_type:{kind:`${$.filterType}_type`}},default_value:c($.value)}):void 0;return{name:(0,i.activeName)(R),schema:{fields:f(R,R.fields)},parameters:O,annotations:l(R.annotations)}}function u(R){const O={entries:[],anonymous_queries:[]};for(const[N,F]of Object.entries(R.contents))if(R.exports.includes(N)){if((0,i.isSourceDef)(F)){const $=a(F);O.entries.push({kind:"source",...$})}else if(F.type==="query"){const $=(0,i.getResultStructDefForQuery)(R,F),V=l(F.annotations),K=$.resultMetadata?E($,$.resultMetadata):void 0,ne=[...V??[],...K?[K]:[]],le={kind:"source",name:N,schema:{fields:f($,$.fields)},annotations:ne.length>0?ne:void 0};O.entries.push(le)}}for(const N of R.queryList){const F=(0,i.getResultStructDefForQuery)(R,N),$=l(N.annotations),V=F.resultMetadata?E(F,F.resultMetadata):void 0,K=[...$??[],...V?[V]:[]],ne={schema:{fields:f(F,F.fields)},annotations:K.length>0?K:void 0};O.anonymous_queries.push(ne)}return O}function c(R){if(R!==null)switch(R.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(R.literal)};case"stringLiteral":return{kind:"string_literal",string_value:R.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:R.filterSrc};case"dateLiteral":return{kind:"date_literal",date_value:R.literal};case"timestampLiteral":case"timestamptzLiteral":return{kind:"timestamp_literal",timestamp_value:R.literal,timezone:R.timezone};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 l(R){return new s.Annotations(R).texts().map(O=>({value:O}))}function f(R,O){const N=[];for(const F of O){if(!(F.accessModifier===void 0))continue;const V=l(F.annotations),K=V.length>0?V:void 0;if((0,i.isTurtle)(F)){const ne=(0,i.getResultStructDefForView)(R,F),le=ne.resultMetadata?E(ne,ne.resultMetadata):void 0,z=[...K??[],...le?[le]:[]],X={kind:"view",name:(0,i.activeName)(F),annotations:z.length>0?z:void 0,schema:{fields:f(ne,ne.fields)}};N.push(X)}else if((0,i.isAtomic)(F)){const ne=(0,i.expressionIsAggregate)(F.expressionType),le=(0,i.expressionIsScalar)(F.expressionType);if(!ne&&!le||F.type==="error")continue;const z=F.resultMetadata?d(F,F.resultMetadata):void 0;let X;if((0,i.isRecordOrRepeatedRecord)(F)&&F.queryTimezone){const I=o.Tag.withPrefix("#(malloy) ");I.set(["query_timezone"],F.queryTimezone),X={value:I.toString()}}const se=[...K??[],...z?[z]:[],...X?[X]:[]],fe={kind:ne?"measure":"dimension",name:(0,i.activeName)(F),type:v(F),annotations:se.length>0?se:void 0};N.push(fe)}else if((0,i.isJoinedSource)(F)){const ne={kind:"join",name:(0,i.activeName)(F),annotations:K,schema:{fields:f(F,F.fields)},relationship:F.join};N.push(ne)}}return N}function d(R,O){const N=o.Tag.withPrefix("#(malloy) ");let F=!1;if(O.referenceId!==void 0&&(N.set(["reference_id"],O.referenceId),F=!0),O.fieldKind==="measure"&&(N.set(["calculation"]),F=!0),O.drillable&&(N.set(["drillable"]),F=!0),O.filterList&&(p(N,O.filterList),F=!0),O.drillExpression&&(x(N,["drill_expression"],O.drillExpression),F=!0),O.fieldKind==="dimension"){const V=(O==null?void 0:O.sourceExpression)||(O!=null&&O.sourceField.includes(".")?O==null?void 0:O.sourceField:y(R.name));N.set(["drill_expression","code"],V),F=!0}return F?{value:N.toString()}:void 0}function p(R,O){for(let N=0;N<O.length;N++){const F=O[N];F.expressionType!=="scalar"||F.isSourceFilter||(R.set(["drill_filters",N,"code"],F.code),F.filterView&&R.set(["drill_filters",N,"filter_view"],F.filterView),F.filterView===void 0&&F.stableFilter!==void 0&&(x(R,["drill_filters",N,"expression"],F.stableFilter.expression),F.stableFilter.kind==="filter_string"?(R.set(["drill_filters",N,"kind"],"filter_expression"),R.set(["drill_filters",N,"filter_expression"],F.stableFilter.filter)):(R.set(["drill_filters",N,"kind"],"literal_equality"),m(R,["drill_filters",N,"value"],F.stableFilter.value))))}}function x(R,O,N){w(R,O,N,"Expression")}function m(R,O,N){w(R,O,N,"LiteralValue")}function g(R){return R.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function y(R){return R.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?R:`\`${g(R)}\``}function E(R,O){var N;const F=o.Tag.withPrefix("#(malloy) ");let $=!1;if(O.limit!==void 0&&(F.set(["limit"],O.limit),$=!0),O.filterList&&(p(F,O.filterList),$=!0),O.drillable&&(F.set(["drillable"]),$=!0),O.orderBy){for(let V=0;V<O.orderBy.length;V++){const K=O.orderBy[V],ne=typeof K.field=="number"?(0,i.activeName)(R.fields[K.field-1]):K.field,le=(N=K.dir)!==null&&N!==void 0?N:null;F.set(["ordered_by",V,ne],le)}$=!0}return R.queryTimezone&&(F.set(["query_timezone"],R.queryTimezone),$=!0),$?{value:F.toString()}:void 0}function v(R){if((0,i.isBasicAtomic)(R))switch(R.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:R.numberType==="float"?"decimal":R.numberType==="integer"?"integer":R.numberType==="bigint"?"bigint":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const O=R.timeframe;return O&&!b(O)?{kind:"timestamp_type",timeframe:R.timeframe}:{kind:"date_type",timeframe:C(R.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:R.timeframe};case"timestamptz":return{kind:"timestamptz_type",timeframe:R.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:R.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,i.isRepeatedRecord)(R))return{kind:"array_type",element_type:S(R)};if(R.type==="record")return S(R);if(R.type==="array")return{kind:"array_type",element_type:v(R.elementTypeDef)}}throw new Error("Unexpected field type")}function S(R){return{kind:"record_type",fields:R.fields.map(O=>{const N=[];if("resultMetadata"in O&&O.resultMetadata){const F=d(O,O.resultMetadata);F&&N.push(F)}if(O.annotations&&N.push(...l(O.annotations)),(0,i.isAtomic)(O))return{name:O.name,annotations:N.length>0?N:void 0,type:v(O)};throw new Error("Expected record type to not have a table as its child")})}}function b(R){switch(R){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function C(R){switch(R){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return R;default:throw new Error(`Invalid date timeframe ${R}`)}}function _(R){return R}function T(R){return R}function w(R,O,N,F){if(F==="string"){R.set(O,N);return}else if(F==="number"){R.set(O,N);return}else if(F==="boolean"){R.set(O,N.toString());return}const $=r.MALLOY_INTERFACE_TYPES[F];if($===void 0)throw new Error(`Unknown Malloy interface type ${F}`);if($.type==="enum")if(typeof N=="string")R.set(O,N);else throw new Error(`Expected string for enum ${F}`);else if($.type==="struct")for(const V in $.fields){const K=$.fields[V],ne=N[V];if(ne===void 0){if(!K.optional)throw new Error(`Mising value for non-optional field ${V} in type ${F}`)}else if(K.array)if(Array.isArray(ne))for(let le=0;le<ne.length;le++)w(R,[...O,V,le],ne[le],K.type);else throw new Error(`Expected array for field ${V} of type ${F} but got ${typeof N}`);else w(R,[...O,V],ne,K.type)}else{const V=N.kind;R.set([...O,"kind"],V);const K=$.options[V];if(K===void 0)throw new Error(`Unknown Malloy interface union kind ${V} for type ${F}`);w(R,O,N,K)}}return to}var Ace;function jA(){return Ace||(Ace=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_LOG_RANGE=void 0,e.wrapLegacyInfoConnection=i,e.wrapLegacyConnection=s,e.mapData=o,e.wrapResult=a,e.nodeToLiteralValue=u,e.mapLogs=c;const t=Dk(),n=sw(),r=Vv();function i(l){return{get dialectName(){return l.dialectName},async fetchSchemaForSQLQuery(f){const d=await l.fetchSchemaForSQLStruct({connection:l.name,selectStr:f},{}),p=d.structDef;if(p===void 0)throw new Error(d.error);return{fields:(0,n.convertFieldInfos)(p,p.fields)}},async fetchSchemaForTable(f){const d=(0,t.validateCanonicalTablePath)(l.dialectName,f);if(d!==void 0)throw new Error(d);const p=`${l.name}:${f}`,x=await l.fetchSchemaForTables({[p]:f},{}),m=x.schemas[p];if(m===void 0)throw new Error(x.errors[p]);return{fields:(0,n.convertFieldInfos)(m,m.fields)}}}}function s(l){return{...i(l),runSQL:async(f,d)=>{const p=await l.runSQL(f);return o(p.rows,d)}}}function o(l,f){function d(m,g){if(m===null)return{kind:"null_cell"};if(g.type.kind==="date_type"||g.type.kind==="timestamp_type"||g.type.kind==="timestamptz_type"){const y=(0,r.rowDataToDate)(m).toISOString();return g.type.kind==="date_type"?{kind:"date_cell",date_value:y}:{kind:"timestamp_cell",timestamp_value:y}}else if(g.type.kind==="boolean_type"){if(typeof m=="number"||typeof m=="bigint")return{kind:"boolean_cell",boolean_value:m!==0};if(typeof m=="string")return{kind:"boolean_cell",boolean_value:m!=="0"&&m!==""};if(typeof m!="boolean")throw new Error(`Invalid boolean ${m}`);return{kind:"boolean_cell",boolean_value:m}}else if(g.type.kind==="number_type"){const y=g.type.subtype,E=y==="bigint"?(0,r.rowDataToSerializedBigint)(m):void 0;return{kind:"number_cell",number_value:(0,r.rowDataToNumber)(m),subtype:y,string_value:E}}else if(g.type.kind==="string_type"){if(typeof m!="string")throw new Error(`Invalid string ${m}`);return{kind:"string_cell",string_value:m}}else if(g.type.kind==="array_type"){if(!Array.isArray(m))throw new Error(`Invalid array ${m}`);return{kind:"array_cell",array_value:m.map(y=>d(y,{name:"array_element",type:g.type.element_type}))}}else{if(g.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(m)};if(g.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(m)};{const y=g.type;if(y.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(g)}, ${JSON.stringify(m)}`);return p(m,{schema:{fields:y.fields.map(E=>({kind:"dimension",...E}))}})}}}function p(m,g){const y=[];for(const E of g.schema.fields){const v=m[E.name];if(E.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const S=d(v,E);y.push(S)}return{kind:"record_cell",record_value:y}}const x={schema:f};return{kind:"array_cell",array_value:l.map(m=>p(m,x))}}function a(l){const f=l._queryResult.structs,d=f[f.length-1],p={fields:(0,n.convertFieldInfos)(d,d.fields)};return l.toStableResult(o(l.data.rawData,p))}function u(l){switch(l==null?void 0:l.node){case"numberLiteral":return{kind:"number_literal",number_value:Number.parseFloat(l.literal)};case"null":return{kind:"null_literal"};case"stringLiteral":return{kind:"string_literal",string_value:l.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:l.filterSrc};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"dateLiteral":return{kind:"date_literal",date_value:l.literal,granularity:l.typeDef.timeframe};case"timestampLiteral":case"timestamptzLiteral":return{kind:"timestamp_literal",timestamp_value:l.literal,timezone:l.timezone,granularity:l.typeDef.timeframe};default:return}}e.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function c(l,f){return l.map(d=>{var p,x,m,g;return{severity:d.severity,message:d.message,range:(x=(p=d.at)===null||p===void 0?void 0:p.range)!==null&&x!==void 0?x:e.DEFAULT_LOG_RANGE,url:(g=(m=d.at)===null||m===void 0?void 0:m.url)!==null&&g!==void 0?g:f}})}}(wk)),wk}var bce;function e9e(){if(bce)return Wa;bce=1;var e=Wa&&Wa.__createBinding||(Object.create?function(g,y,E,v){v===void 0&&(v=E);var S=Object.getOwnPropertyDescriptor(y,E);(!S||("get"in S?!y.__esModule:S.writable||S.configurable))&&(S={enumerable:!0,get:function(){return y[E]}}),Object.defineProperty(g,v,S)}:function(g,y,E,v){v===void 0&&(v=E),g[v]=y[E]}),t=Wa&&Wa.__setModuleDefault||(Object.create?function(g,y){Object.defineProperty(g,"default",{enumerable:!0,value:y})}:function(g,y){g.default=y}),n=Wa&&Wa.__importStar||function(){var g=function(y){return g=Object.getOwnPropertyNames||function(E){var v=[];for(var S in E)Object.prototype.hasOwnProperty.call(E,S)&&(v[v.length]=S);return v},g(y)};return function(y){if(y&&y.__esModule)return y;var E={};if(y!=null)for(var v=g(y),S=0;S<v.length;S++)v[S]!=="default"&&e(E,y,v[S]);return t(E,y),E}}();Object.defineProperty(Wa,"__esModule",{value:!0}),Wa.MalloyToQuery=void 0,Wa.malloyToQuery=m;const r=OA(),i=vk(),s=n(AA()),o=Kv(),a=bA(),u=mt(),c=fce(),l=Vu(),f=jA(),d=X4(),p="Malloy query documents";class x extends i.AbstractParseTreeVisitor{constructor(y,E){super(),this.parseInfo=y,this.msgLog=E}internalError(y,E){return this.contextError(y,"internal-translator-error",{message:E}),new Error(`Internal Translator Error: ${E}`)}getLocation(y){return{url:this.parseInfo.sourceURL,range:(0,l.rangeFromContext)(this.parseInfo.sourceInfo,y)}}contextError(y,E,v,S){this.msgLog.log((0,o.makeLogMessage)(E,v,{at:this.getLocation(y),...S}))}getNumber(y){return Number.parseInt(y.text)}defaultResult(){return null}getAnnotations(y){const E=y.annotation().map(v=>({value:(0,a.getAnnotationText)(v)}));return E.length>0?E:void 0}getIsAnnotations(y){var E,v;if(y===void 0)return;const b=((E=this.getAnnotations(y._beforeIs))!==null&&E!==void 0?E:[]).concat((v=this.getAnnotations(y._afterIs))!==null&&v!==void 0?v:[]);return b.length>0?b:void 0}notAllowed(y,E){this.illegal(y,`${E} are not allowed in ${p}`)}illegal(y,E){this.contextError(y,"invalid-malloy-query-document",E)}visitMalloyDocument(y){const E=y.malloyStatement();let v;for(const S of E)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"):v===void 0?v=S.runStatement():this.illegal(S,`${p} may only have one run statement`);return v===void 0?(this.illegal(y,`${p} must have a run statement`),null):this.visitRunStatement(v)}visitRunStatement(y){const E=y.topLevelAnonQueryDef(),v=this.getQueryDefinition(E.sqExpr()),S=this.getAnnotations(y.tags()),b=this.getAnnotations(y.topLevelAnonQueryDef().tags()),C=this.combineAnnotations(S,b);return v!==null?{annotations:C,definition:v}:null}getSourceArguments(y){const E=[];for(const v of y.sourceArgument()){const S=v.argumentId();if(S===void 0)return this.contextError(v,"unnamed-source-argument","Source argument must be named"),null;const b=(0,a.getId)(S),C=this.getLiteralIncludingNegativeNumber(v.fieldExpr());if(C===null)return null;E.push({name:b,value:C})}return E}getQueryReference(y){const E=y.sourceArguments(),v=(0,a.getId)(y);if(E){const S=this.getSourceArguments(E);return S===null?null:{name:v,parameters:S}}else return{name:v}}getQueryDefinition(y){if(y instanceof s.SQIDContext){const E=this.getQueryReference(y);if(E!==null)return{kind:"query_reference",...E}}else{if(y instanceof s.SQParensContext)return this.getQueryDefinition(y.sqExpr());if(y instanceof s.SQComposeContext)this.notAllowed(y,"Source compositions");else if(y instanceof s.SQRefinedQueryContext){const E=y.sqExpr(),v=this.getQueryDefinition(E),S=this.getRefinementSegment(y.segExpr());return S===null||v===null?null:(S.kind==="arrow"&&this.notAllowed(y,"Queries against refined queries"),{kind:"refinement",base:v,refinement:S})}else if(y instanceof s.SQExtendedSourceContext)this.notAllowed(y,"Source extensions");else if(y instanceof s.SQIncludeContext)this.notAllowed(y,"Source inclusions");else if(y instanceof s.SQTableContext)this.notAllowed(y,"Table statements");else if(y instanceof s.SQSQLContext)this.notAllowed(y,"SQL statements");else if(y instanceof s.SQArrowContext){const E=y.sqExpr(),v=this.getQueryDefinition(E),S=this.getRefinementSegment(y.segExpr());return S===null||v===null?null:v.kind==="query_reference"?{kind:"arrow",source:{...v,kind:"source_reference"},view:S}:v.kind==="arrow"?{kind:"arrow",source:v.source,view:{kind:"arrow",source:v.view,view:S}}:{kind:"arrow",source:v,view:S}}}return null}getRefinementSegment(y){if(y instanceof s.SegOpsContext){const E=y.queryProperties().queryStatement().flatMap(v=>this.getSegmentOperation(v));return E.some(v=>v===null)?null:{kind:"segment",operations:E}}else if(y instanceof s.SegFieldContext){const{name:E,path:v}=this.getFieldPath(y.fieldPath());return{kind:"view_reference",name:E,path:v}}else{if(y instanceof s.SegParenContext)return this.getViewExpression(y.vExpr());if(y instanceof s.SegRefineContext){const E=this.getRefinementSegment(y._lhs),v=this.getRefinementSegment(y._rhs);return E===null||v===null?null:{kind:"refinement",base:E,refinement:v}}}return null}getGroupByStatement(y){const E=this.getAnnotations(y.tags()),S=y.queryFieldList().queryFieldEntry().map(b=>this.getQueryField(b));return S.some(b=>b===null)||S===null?null:S.map(b=>{var C;const _=[...E??[],...(C=b.field.annotations)!==null&&C!==void 0?C:[]];return{kind:"group_by",name:b.name,field:{...b.field,annotations:_.length>0?_:void 0}}})}getAggregateStatement(y){const E=this.getAnnotations(y.tags()),S=y.queryFieldList().queryFieldEntry().map(b=>this.getQueryField(b));return S.some(b=>b===null)||S===null?null:S.map(b=>{var C;const _=[...E??[],...(C=b.field.annotations)!==null&&C!==void 0?C:[]];return{kind:"aggregate",name:b.name,field:{...b.field,annotations:_.length>0?_:void 0}}})}getOrderByStatement(y){var E,v;const S=y.ordering().orderBySpec(),b=[];for(const C of S){if(C.INTEGER_LITERAL()){this.notAllowed(C,"Indexed order by statements");continue}const _=(v=(E=C.possibleBadPath())===null||E===void 0?void 0:E.badWord())!==null&&v!==void 0?v:[],T=_.length===1?_[0].fieldName():void 0;if(!T)return null;const w=(0,a.getId)(T),R=C.ASC()?"asc":C.DESC()?"desc":void 0;b.push({kind:"order_by",direction:R,field_reference:{name:w}})}return b}getNestStatement(y){const E=this.getAnnotations(y.tags()),v=y.nestedQueryList().nestEntry(),S=[];for(const b of v){if(!(b instanceof s.NestDefContext))return this.internalError(b,"Expected nestDef"),null;const C=this.getAnnotations(b.tags()),_=this.getIsAnnotations(b.isDefine()),T=b.queryName(),w=T?(0,a.getId)(T):void 0,R=this.getViewExpression(b.vExpr());if(R===null)return null;S.push({kind:"nest",name:w,view:{definition:R,annotations:this.combineAnnotations(E,C,_)}})}return S}getViewExpression(y){if(y instanceof s.VSegContext)return this.getRefinementSegment(y.segExpr());if(y instanceof s.VArrowContext){const E=this.getRefinementSegment(y),v=this.getViewExpression(y._rhs);return E===null||v===null?null:{kind:"arrow",source:E,view:v}}else return this.internalError(y,"Unexpected VExpr node"),null}getLimitStatement(y){return{kind:"limit",limit:this.getNumber(y.INTEGER_LITERAL())}}getSegmentOperation(y){if(y.groupByStatement()){const E=y.groupByStatement();return this.getGroupByStatement(E)}else if(y.aggregateStatement()){const E=y.aggregateStatement();return this.getAggregateStatement(E)}else if(y.limitStatement()){const E=y.limitStatement(),v=this.getLimitStatement(E);return v===null?null:[v]}else if(y.declareStatement())this.notAllowed(y,"Declare statements");else if(y.queryJoinStatement())this.notAllowed(y,"Query join statements");else if(y.queryExtend())this.notAllowed(y,"Query extend statements");else if(y.projectStatement())this.notAllowed(y,"Select statements");else if(y.indexStatement())this.notAllowed(y,"Index statements");else if(y.calculateStatement())this.notAllowed(y,"Calculate statements");else if(y.topStatement())this.notAllowed(y,"Top statements");else if(y.orderByStatement()){const E=y.orderByStatement();return this.getOrderByStatement(E)}else if(y.whereStatement()){const E=y.whereStatement(),v=this.getWhere(E);return v===null?null:v.map(S=>({kind:"where",...S}))}else if(y.drillStatement()){const E=y.drillStatement(),v=this.getDrill(E);return v===null?null:v.map(S=>({kind:"drill",...S}))}else if(y.havingStatement()){const E=y.havingStatement(),v=this.getHaving(E);return v===null?null:v.map(S=>({kind:"having",...S}))}else if(y.nestStatement()){const E=y.nestStatement();return this.getNestStatement(E)}else y.sampleStatement()?this.notAllowed(y,"Sample statements"):y.timezoneStatement()?this.notAllowed(y,"Timezone statements"):(y.queryAnnotation()||y.ignoredModelAnnotations())&&this.notAllowed(y,"Detached annotation statements");return null}getFieldPath(y){const E=y.fieldName().map(b=>(0,a.getId)(b)),v=E[E.length-1],S=E.slice(0,-1);return{name:v,path:S.length>0?S:void 0}}getTimeframe(y){const E=y.text;return(0,u.isTimestampUnit)(E)?E:(this.illegal(y,`Invalid timeframe ${E}`),null)}getQueryField(y){if(y.taggedRef()){const E=y.taggedRef(),v=this.getAnnotations(E.tags()),{name:S,path:b}=this.getFieldPath(E.fieldPath());if(E.refExpr()){const C=E.refExpr();if(C.timeframe()){const _=this.getTimeframe(C.timeframe());return _===null?null:{name:void 0,field:{annotations:v,expression:{kind:"time_truncation",field_reference:{name:S,path:b},truncation:_}}}}else C.aggregate()&&this.notAllowed(C,"Aggregate expressions")}else return{name:void 0,field:{annotations:v,expression:{kind:"field_reference",name:S,path:b}}}}else if(y.fieldDef()){const E=y.fieldDef(),v=this.getAnnotations(E.tags()),S=this.getIsAnnotations(E.isDefine()),b=(0,a.getId)(E.fieldNameDef()),C=this.getFieldExpression(E.fieldExpr());return C===null?null:{name:b,field:{expression:C,annotations:this.combineAnnotations(v,S)}}}return null}getFieldExpression(y){if(y instanceof s.ExprFieldPathContext){const{name:E,path:v}=this.getFieldPath(y.fieldPath());return{kind:"field_reference",name:E,path:v}}else if(y instanceof s.ExprTimeTruncContext){const E=this.getTimeframe(y.timeframe()),v=y.fieldExpr(),S=this.getFieldExpression(v);return S===null||E===null?null:S.kind!=="field_reference"?(this.illegal(v,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:E,field_reference:{name:S.name,path:S.path,parameters:S.parameters}}}else if(y instanceof s.ExprFieldPropsContext){const E=y.fieldExpr(),v=this.getFieldExpression(E);if(v===null)return null;if(v.kind!=="field_reference")return this.illegal(E,"Left hand side of filtered field must be a field reference"),null;const S=y.fieldProperties().fieldPropertyStatement(),b=[];for(const C of S){const _=C.whereStatement();if(_){const T=this.getWhere(_);if(T===null)return null;b.push(...T)}}return{kind:"filtered_field",field_reference:{name:v.name,path:v.path,parameters:v.parameters},where:b}}else{const E=this.getLiteralIncludingNegativeNumber(y);return E===null?null:{kind:"literal_value",literal_value:E}}}stripQuote(y,E){return y.slice(y.indexOf(E)+E.length,y.lastIndexOf(E))}getFilterString(y){const E=y.tripFilterString(),v=y.tickFilterString();if(E){const S=E.BQ3_FILTER(),b=E.DQ3_FILTER(),C=E.SQ3_FILTER();if(S)return this.stripQuote(S.text,"```");if(b)return this.stripQuote(b.text,'"""');if(C)return this.stripQuote(C.text,"'''")}else if(v){const S=v.BQ_FILTER(),b=v.DQ_FILTER(),C=v.SQ_FILTER();if(S)return this.stripQuote(S.text,"`");if(b)return this.stripQuote(b.text,'"');if(C)return this.stripQuote(C.text,"'")}return null}getFilterExpr(y){if(y instanceof s.ExprCompareContext){if(y.compareOp().MATCH()){const E=y.fieldExpr()[0],v=y.fieldExpr()[1];if(E instanceof s.ExprFieldPathContext&&v instanceof s.ExprLiteralContext){const{path:S,name:b}=this.getFieldPath(E.fieldPath()),C=v.literal();if(C instanceof s.FilterString_stubContext){const _=this.getFilterString(C.filterString());return _===null?null:{filter:{kind:"filter_string",expression:{kind:"field_reference",name:b,path:S},filter:_}}}}}else if(y.compareOp().EQ()){const E=y.fieldExpr()[0],v=y.fieldExpr()[1];if(E instanceof s.ExprFieldPathContext){const{path:S,name:b}=this.getFieldPath(E.fieldPath()),C=this.getLiteralIncludingNegativeNumber(v);return C===null?(this.notAllowed(y,"Filters other than comparisons with filter strings or equality with literals"),null):{filter:{kind:"literal_equality",expression:{kind:"field_reference",name:b,path:S},value:C}}}}}return this.notAllowed(y,"Filters other than comparisons with filter strings or equality with literals"),null}getTimeLiteral(y,E){const v=E(y.text);if(!v)return this.contextError(y,"failed-to-parse-time-literal","Time data parse error"),null;const S=v.getValue(),b=S.timeframe,C=S.value;return(0,u.isTimeLiteral)(C)?C.node==="dateLiteral"?b==="hour"||b==="minute"||b==="second"?null:{kind:"date_literal",date_value:C.literal,granularity:b}:{kind:"timestamp_literal",timestamp_value:C.literal,granularity:b,timezone:C.timezone}:null}getLiteralIncludingNegativeNumber(y){if(y instanceof s.ExprLiteralContext)return this.getLiteral(y.literal());if(y instanceof s.ExprMinusContext){const E=y.fieldExpr();if(E instanceof s.ExprLiteralContext){const v=this.getLiteral(E.literal());return v===null||v.kind!=="number_literal"?null:{kind:"number_literal",number_value:-v.number_value}}}return null}getLiteral(y){if(y instanceof s.ExprTimeContext){const E=y.dateLiteral();return E instanceof s.LiteralTimestampContext?this.getTimeLiteral(E,d.LiteralTimestamp.parse):E instanceof s.LiteralHourContext?this.getTimeLiteral(E,d.LiteralHour.parse):E instanceof s.LiteralDayContext?this.getTimeLiteral(E,d.LiteralDay.parse):E instanceof s.LiteralWeekContext?this.getTimeLiteral(E,d.LiteralWeek.parse):E instanceof s.LiteralMonthContext?this.getTimeLiteral(E,d.LiteralMonth.parse):E instanceof s.LiteralQuarterContext?this.getTimeLiteral(E,d.LiteralQuarter.parse):E instanceof s.LiteralYearContext?this.getTimeLiteral(E,d.LiteralYear.parse):null}else{if(y instanceof s.ExprArrayLiteralContext)return this.notAllowed(y,"array literals"),null;if(y instanceof s.ExprLiteralRecordContext)return this.notAllowed(y,"record literals"),null;if(y instanceof s.ExprStringContext){const[E,v]=(0,a.getPlainString)(y);for(const S of v)S instanceof r.ParserRuleContext&&this.contextError(S,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return{kind:"string_literal",string_value:E??""}}else{if(y instanceof s.ExprBoolContext)return{kind:"boolean_literal",boolean_value:y.TRUE()!==null};if(y instanceof s.ExprNumberContext)return{kind:"number_literal",number_value:Number(y.text)};if(y instanceof s.ExprNULLContext)return{kind:"null_literal"};if(y instanceof s.FilterString_stubContext){const E=y.getChild(0);if(E instanceof s.FilterStringContext){const v=this.getFilterString(E);if(v)return{kind:"filter_expression_literal",filter_expression_value:v}}}}}return null}getDrill(y){const v=y.drillClauseList().fieldExpr().map(S=>this.getFilterExpr(S));return v.some(S=>S===null)?null:v}getWhere(y){const v=y.filterClauseList().fieldExpr().map(S=>this.getFilterExpr(S));return v.some(S=>S===null)?null:v}getHaving(y){const v=y.filterClauseList().fieldExpr().map(S=>this.getFilterExpr(S));return v.some(S=>S===null)?null:v}combineAnnotations(...y){const E=y.flatMap(v=>v??[]);return E.length>0?E:void 0}}Wa.MalloyToQuery=x;function m(g){const y=(0,l.getSourceInfo)(g),E=new o.BaseMessageLogger(null),v="internal://query.malloy",S=(0,c.runMalloyParser)(g,v,y,E),C=new x(S,E).visit(S.root),_=(0,f.mapLogs)(E.getLog(),v);if(C===null)return{logs:_};if(!("definition"in C))throw new Error("Expected a query");return{query:C,logs:_}}return Wa}var Cce;function Ok(){return Cce||(Cce=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.malloyToQuery=e.exploreQueryWalkerBuilder=e.MalloyTranslation=e.MalloyTranslator=void 0;var t=WIe();Object.defineProperty(e,"MalloyTranslator",{enumerable:!0,get:function(){return t.MalloyTranslator}}),Object.defineProperty(e,"MalloyTranslation",{enumerable:!0,get:function(){return t.MalloyTranslation}});var n=YIe();Object.defineProperty(e,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}});var r=e9e();Object.defineProperty(e,"malloyToQuery",{enumerable:!0,get:function(){return r.malloyToQuery}})}(kI)),kI}var Nk={},zA={},Tce;function t9e(){return Tce||(Tce=1,Object.defineProperty(zA,"__esModule",{value:!0}),zA.EMPTY_BUILD_MANIFEST=void 0,zA.EMPTY_BUILD_MANIFEST=Object.freeze({entries:Object.freeze({}),strict:!1})),zA}var ya={},Rce;function ow(){if(Rce)return ya;Rce=1,Object.defineProperty(ya,"__esModule",{value:!0}),ya.FixedConnectionMap=ya.InMemoryURLReader=ya.EmptyURLReader=void 0,ya.hashForInvalidationKey=t,ya.isInternalURL=n,ya.readURL=r,ya.getInvalidationKey=i;const e=Gp();function t(u){return(0,e.v5)(u,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}function n(u){return u.startsWith("internal://")}async function r(u,c){const l=await u.readURL(c),{contents:f,invalidationKey:d}=typeof l=="string"?{contents:l,invalidationKey:void 0}:l;return{contents:f,invalidationKey:n(c.toString())?null:d??t(f)}}async function i(u,c){return n(c.toString())?null:u.getInvalidationKey!==void 0?await u.getInvalidationKey(c):(await r(u,c)).invalidationKey}class s{async readURL(c){throw new Error("No files.")}async getInvalidationKey(c){throw new Error("No files.")}}ya.EmptyURLReader=s;class o{constructor(c){this.files=c}async readURL(c){const l=this.files.get(c.toString());if(l!==void 0)return Promise.resolve({contents:l,invalidationKey:this.invalidationKey(c,l)});throw new Error(`File not found '${c}'`)}async getInvalidationKey(c){const l=this.files.get(c.toString());if(l!==void 0)return Promise.resolve(this.invalidationKey(c,l));throw new Error(`File not found '${c}'`)}invalidationKey(c,l){return n(c.toString())?null:t(l)}}ya.InMemoryURLReader=o;class a{constructor(c,l){this.connections=c,this.defaultConnectionName=l}async getConnection(c){if(c===void 0)if(this.defaultConnectionName!==void 0)c=this.defaultConnectionName;else throw new Error("No default connection.");const l=this.connections.get(c);if(l!==void 0)return Promise.resolve(l);throw new Error(`No connection found with name ${c}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(c){return this.getConnection(c)}static fromArray(c){return new a(new Map(c.map(l=>[l.name,l])))}}return ya.FixedConnectionMap=a,ya}var I1={},wce;function n9e(){if(wce)return I1;wce=1,Object.defineProperty(I1,"__esModule",{value:!0}),I1.InMemoryModelCache=I1.CacheManager=void 0;const e=ow();class t{constructor(s){this.modelCache=s,this.modelDependencies=new Map,this.modelInvalidationKeys=new Map}async getCachedModelDef(s,o){const a=this.modelDependencies.get(o);if(a===void 0)return;const u=[o,...n(a)],c={};for(const f of u){const d=this.modelInvalidationKeys.get(f);if(d==null)return;c[f]=d}for(const f of u)if(await(0,e.getInvalidationKey)(s,new URL(f))!==c[f])return;const l=await this.modelCache.getModel(new URL(o));if(l!==void 0){for(const f of u)if(l.invalidationKeys[f]!==c[f])return;return{modelDef:l.modelDef,invalidationKeys:c}}}async setCachedModelDef(s,o){this.modelDependencies.set(s,o.modelDef.dependencies);const a={};for(const c of[s,...n(o.modelDef.dependencies)]){if(o.invalidationKeys[c]===null)return!1;if(o.invalidationKeys[c]===void 0)throw new Error(`Missing invalidation key for dependency ${c}`);this.modelInvalidationKeys.set(c,o.invalidationKeys[c]),a[c]=o.invalidationKeys[c]}return!!await this.modelCache.setModel(new URL(s),{modelDef:o.modelDef,invalidationKeys:a})}}I1.CacheManager=t;function n(i){return[...Object.keys(i),...Object.values(i).map(n).flat()]}class r{constructor(){this.models=new Map}async getModel(s){return Promise.resolve(this.models.get(s.toString()))}async setModel(s,o){return this.models.set(s.toString(),o),Promise.resolve(!0)}}return I1.InMemoryModelCache=r,I1}var no={},Dce;function Oce(){if(Dce)return no;Dce=1,Object.defineProperty(no,"__esModule",{value:!0}),no.DocumentCompletion=no.DocumentSymbol=no.DocumentPosition=no.DocumentRange=no.DocumentTablePath=no.Parse=void 0;class e{constructor(a,u){this.translator=a,this.invalidationKey=u}get symbols(){return(this.translator.metadata().symbols||[]).map(a=>new i(a))}get tablePathInfo(){var a;return((a=this.translator.tablePathInfo().pathInfo)!==null&&a!==void 0?a:[]).map(c=>new t(c))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(a){return(this.translator.completions(a).completions||[]).map(u=>new s(u))}helpContext(a){return this.translator.helpContext(a).helpContext}}no.Parse=e;class t{constructor(a){this._range=n.fromJSON(a.range),this._connectionId=a.connectionId,this._tablePath=a.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}no.DocumentTablePath=t;class n{constructor(a,u){this._start=a,this._end=u}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(a){return new n(new r(a.start.line,a.start.character),new r(a.end.line,a.end.character))}}no.DocumentRange=n;class r{constructor(a,u){this._line=a,this._character=u}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}no.DocumentPosition=r;class i{constructor(a){this._range=n.fromJSON(a.range),this._lensRange=a.lensRange?n.fromJSON(a.lensRange):void 0,this._type=a.type,this._name=a.name,this._children=a.children.map(u=>new i(u))}get range(){return this._range}get lensRange(){var a;return(a=this._lensRange)!==null&&a!==void 0?a:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}no.DocumentSymbol=i;class s{constructor(a){this.type=a.type,this.text=a.text}}return no.DocumentCompletion=s,no}var sn={},Nce;function aw(){if(Nce)return sn;Nce=1,Object.defineProperty(sn,"__esModule",{value:!0}),sn.PreparedResult=sn.PreparedQuery=sn.Given=sn.PersistSource=sn.Model=sn.Reference=sn.ExploreField=sn.QueryField=sn.Query=sn.StringField=sn.UnsupportedField=sn.JSONField=sn.BooleanField=sn.NumberField=sn.TimestampField=sn.DateField=sn.AtomicField=sn.Explore=sn.JoinRelationship=sn.TimestampTimeframe=sn.DateTimeframe=sn.AtomicFieldType=sn.SourceRelationship=void 0,sn.pseudoModelFor=x;const e=Si(),t=xr(),n=i0(),r=QI(),i=Mc(),s=ree(),o=kc(),a=cm(),u=sw(),c=jA(),l=Vu(),f=ece();function d(j){return j.type==="table"||j.type==="sql_select"||j.type==="query_source"}const p="internal://generated-model";function x(j,M=p,B={}){if(!(0,e.isSourceDef)(j))throw new Error(`Cannot create pseudo model for struct type ${j.type}`);const L=(0,t.mkModelDef)("generated_model",M);return L.modelAnnotations=B,L.contents[j.name]=j,L}class m{constructor(M,B,L){this._name=M,this._parent=B,this._source=L}get source(){return this._source}get name(){return this._name}get sourceClasses(){const M=[];return this.source&&M.push(this.source.name),M.push(this.name),M}get fieldPath(){const M=[this.name];let B=this._parent;for(;B;)M.unshift(B.name),B=B._parent;return M}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof b}isQuery(){return this instanceof V}}var g;(function(j){j.Nested="nested",j.BaseTable="base_table",j.Cross="cross",j.One="one",j.Many="many",j.Inline="inline"})(g||(sn.SourceRelationship=g={}));var y;(function(j){j.String="string",j.Number="number",j.Boolean="boolean",j.Date="date",j.Timestamp="timestamp",j.Timestamptz="timestamptz",j.Json="json",j.NativeUnsupported="sql native",j.Error="error"})(y||(sn.AtomicFieldType=y={}));var E;(function(j){j.Day="day",j.Week="week",j.Month="month",j.Quarter="quarter",j.Year="year"})(E||(sn.DateTimeframe=E={}));var v;(function(j){j.Day="day",j.Week="week",j.Month="month",j.Quarter="quarter",j.Year="year",j.Second="second",j.Hour="hour",j.Minute="minute"})(v||(sn.TimestampTimeframe=v={}));var S;(function(j){j.OneToOne="one_to_one",j.OneToMany="one_to_many",j.ManyToOne="many_to_one"})(S||(sn.JoinRelationship=S={}));class b extends m{constructor(M,B,L,k){super((0,e.activeName)(B),L,k),this._ownerModelDef=M,this._structDef=B,this._parentExplore=L,this.sourceExplore=k}get _modelDef(){return this._ownerModelDef}get source(){return this.sourceExplore}get referenceSourceID(){return(0,e.isSourceDef)(this._structDef)?this._structDef.referenceID:void 0}referencedSource(){if(!(0,e.isSourceDef)(this._structDef))return;const M=(0,i.sourceNamespaceReference)(this._ownerModelDef,this._structDef);return M?new b(this._ownerModelDef,M.source):void 0}isIntrinsic(){return(0,e.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(M){return(0,a.annotationToTag)(this._structDef.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this._structDef.annotations,M)}get annotations(){return new a.Annotations(this._structDef.annotations)}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this._ownerModelDef))}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=this.modelAnnotations.parseAsTag().tag),this.parsedModelTag}get name(){return(0,e.activeName)(this.structDef)}getQueryByName(M){const B=this.sourceStructDef;if(!B)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const L=B.fields.find(U=>(0,e.activeName)(U)===M);if(L===void 0)throw new Error(`No such view named \`${M}\``);if(L.type!=="turtle")throw new Error(`\`${M}\` is not a view`);const k={type:"query",structRef:B,pipeline:L.pipeline};return new I(k,this.getSingleExploreModel(),[],M)}getSingleExploreModel(){return new z(this._ownerModelDef,[],[])}get fieldMap(){var M;if(this._fieldMap===void 0){const B=((M=this.source)===null||M===void 0?void 0:M.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(L=>{const k=(0,e.activeName)(L),U=B.get(L.name);if((0,e.isJoined)(L))return[k,new K(L,this,U)];if(L.type==="turtle")return[k,new V(L,this,U)];if(L.type==="string")return[k,new F(L,this,U)];if(L.type==="number")return[k,new w(L,this,U)];if(L.type==="date")return L.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(L.timeframe)?[k,new w({...L,type:"number"},this,U)]:[k,new _(L,this,U)];if(L.type==="timestamp")return[k,new T(L,this,U)];if(L.type==="timestamptz")return[k,new T(L,this,U)];if(L.type==="boolean")return[k,new R(L,this,U)];if(L.type==="json")return[k,new O(L,this,U)];if(L.type==="sql native")return[k,new N(L,this,U)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var M,B,L;if(!this._allFieldsWithOrder){const k=[...((L=(B=(M=this.sourceStructDef)===null||M===void 0?void 0:M.resultMetadata)===null||B===void 0?void 0:B.orderBy)===null||L===void 0?void 0:L.map(Q=>{if(typeof Q.field=="string")return{field:this.fieldMap.get(Q.field),dir:Q.dir};throw new Error("Does not support mapping order by from number.")}))||[]],U=new Set(k.map(Q=>Q.field.name));this._allFieldsWithOrder=[...k,...this.allFields.filter(Q=>!U.has(Q.name)).map(Q=>({field:Q,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(M=>M.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(M=>M.field.isAtomicField()&&M.field.sourceWasDimension())}getFieldByName(M){const B=this.fieldMap.get(M);if(B===void 0)throw new Error(`No such field ${M}.`);return B}getFieldByNameIfExists(M){return this.fieldMap.get(M)}get primaryKey(){var M;return(M=this.sourceStructDef)===null||M===void 0?void 0:M.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof K}get filters(){var M;return(0,e.isSourceDef)(this.structDef)?((M=this.structDef.resultMetadata)===null||M===void 0?void 0:M.filterList)||[]:[]}get limit(){var M,B;return(B=(M=this.sourceStructDef)===null||M===void 0?void 0:M.resultMetadata)===null||B===void 0?void 0:B.limit}get structDef(){return this._structDef}get queryTimezone(){var M;return(M=this.sourceStructDef)===null||M===void 0?void 0:M.queryTimezone}get sourceStructDef(){if((0,e.isSourceDef)(this.structDef))return this.structDef}toJSON(){var M,B;return{_structDef:this._structDef,modelID:this._ownerModelDef.modelID,modelAnnotations:this._ownerModelDef.modelAnnotations,sourceExplore:(M=this.sourceExplore)===null||M===void 0?void 0:M.toJSON(),_parentExplore:(B=this._parentExplore)===null||B===void 0?void 0:B.toJSON()}}static fromJSON(M){const B=M._parentExplore!==void 0?b.fromJSON(M._parentExplore):void 0,L=M.sourceExplore!==void 0?b.fromJSON(M.sourceExplore):void 0;return new b(x(M._structDef,M.modelID,M.modelAnnotations),M._structDef,B,L)}get location(){return this.structDef.location}collectSourceComponents(M){const B=[];if(M.type==="composite"){for(const L of M.sources)B.push(...this.collectSourceComponents(L));return B}if(d(M)){if(M.type==="table")B.push({type:"table",tableName:M.tablePath,componentID:`${M.connection}:${M.tablePath}`,sourceID:`${M.connection}:${M.tablePath}`});else if(M.type==="sql_select")B.push({type:"sql",selectStatement:M.selectStr,componentID:`${M.connection}:${M.selectStr}`,sourceID:`${M.connection}:${M.selectStr}`});else if(M.type==="query_source"){let L;try{L=new I(M.query,this.getSingleExploreModel(),[]).getPreparedResult().sql}catch(U){L=`-- Could not compile SQL for query ${M.query.name||"unnamed query"}: ${U instanceof Error?U.message:String(U)}`}const k=`${M.connection}:${L}`;B.push({type:"sql",selectStatement:L,componentID:k,sourceID:k})}}else return[];for(const L of M.fields)(0,e.isJoined)(L)&&B.push(...this.collectSourceComponents(L));return B}getSourceComponents(){const M={};if((0,e.isSourceDef)(this.structDef)){const B=this.collectSourceComponents(this.structDef);for(const L of B)L.componentID?M[L.componentID]=L:L.sourceID&&(M[L.sourceID]=L)}return Object.values(M)}}sn.Explore=b;class C extends m{constructor(M,B,L){super((0,e.activeName)(M),B,L),this.fieldTypeDef=M,this.parent=B}get type(){switch(this.fieldTypeDef.type){case"string":return y.String;case"boolean":return y.Boolean;case"date":return y.Date;case"timestamp":return y.Timestamp;case"timestamptz":return y.Timestamptz;case"number":return y.Number;case"json":return y.Json;case"sql native":return y.NativeUnsupported;case"error":return y.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const M=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${M}`)}}}tagParse(M){return(0,a.annotationToTag)(this.fieldTypeDef.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this.fieldTypeDef.annotations,M)}get annotations(){return new a.Annotations(this.fieldTypeDef.annotations)}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this.parent._modelDef))}isIntrinsic(){return(0,e.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,e.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const M=this.fieldTypeDef.name||this.fieldTypeDef.as;return M?[M]:[]}get referenceId(){var M;return(M=this.fieldTypeDef.resultMetadata)===null||M===void 0?void 0:M.referenceId}sourceWasMeasure(){var M;return((M=this.fieldTypeDef.resultMetadata)===null||M===void 0?void 0:M.fieldKind)==="measure"}sourceWasMeasureLike(){var M,B;return((M=this.fieldTypeDef.resultMetadata)===null||M===void 0?void 0:M.fieldKind)==="measure"||((B=this.fieldTypeDef.resultMetadata)===null||B===void 0?void 0:B.fieldKind)==="struct"}sourceWasDimension(){var M;return((M=this.fieldTypeDef.resultMetadata)===null||M===void 0?void 0:M.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof F}isNumber(){return this instanceof w}isDate(){return this instanceof _}isBoolean(){return this instanceof R}isJSON(){return this instanceof O}isTimestamp(){return this instanceof T}isUnsupported(){return this instanceof N}get parentExplore(){return this.parent}get expression(){const M=".",B=this.fieldTypeDef.resultMetadata;return(B==null?void 0:B.sourceExpression)||(B!=null&&B.sourceField.includes(M)?B==null?void 0:B.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}sn.AtomicField=C;class _ extends C{constructor(M,B,L){super(M,B,L),this.fieldDateDef=M}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return E.Day;case"week":return E.Week;case"month":return E.Month;case"quarter":return E.Quarter;case"year":return E.Year}}}sn.DateField=_;class T extends C{constructor(M,B,L){super(M,B,L),this.fieldTimestampDef=M}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return v.Day;case"week":return v.Week;case"month":return v.Month;case"quarter":return v.Quarter;case"year":return v.Year;case"second":return v.Second;case"hour":return v.Hour;case"minute":return v.Minute}}}sn.TimestampField=T;class w extends C{constructor(M,B,L){super(M,B,L),this.fieldNumberDef=M}}sn.NumberField=w;class R extends C{constructor(M,B,L){super(M,B,L),this.fieldBooleanDef=M}}sn.BooleanField=R;class O extends C{constructor(M,B,L){super(M,B,L),this.fieldJSONDef=M}}sn.JSONField=O;class N extends C{constructor(M,B,L){super(M,B,L),this.fieldUnsupportedDef=M}get rawType(){return this.fieldUnsupportedDef.rawType}}sn.UnsupportedField=N;class F extends C{constructor(M,B,L){super(M,B,L),this.fieldStringDef=M}}sn.StringField=F;class $ extends m{constructor(M,B,L){super((0,e.activeName)(M),B,L),this.turtleDef=M}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}tagParse(M){return(0,a.annotationToTag)(this.turtleDef.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this.turtleDef.annotations,M)}get annotations(){return new a.Annotations(this.turtleDef.annotations)}get modelAnnotations(){var M;const B=(M=this._parent)===null||M===void 0?void 0:M._modelDef;return new a.Annotations(B&&(0,e.getModelAnnotations)(B))}}sn.Query=$;class V extends ${constructor(M,B,L){super(M,B,L),this.parent=B}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const M=this.turtleDef.name||this.turtleDef.as;return M?[M]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}sn.QueryField=V;class K extends b{constructor(M,B,L){super(B._modelDef,M,B,L),this._parentExplore=B}get joinRelationship(){if((0,e.isJoined)(this.structDef))switch(this.structDef.join){case"one":return S.OneToOne;case"many":case"cross":return S.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===S.OneToOne}get isArray(){return this.joinRelationship!==S.OneToOne}tagParse(M){return(0,a.annotationToTag)(this._structDef.annotations,M)}get annotations(){return new a.Annotations(this._structDef.annotations)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const M=this.structDef.name||this.structDef.as;return M?[M]:[]}get queryTimezone(){return(0,e.isRecordOrRepeatedRecord)(this._structDef)?this._structDef.queryTimezone:super.queryTimezone}}sn.ExploreField=K;const ne={fieldReference:"field",joinReference:"join",exploreReference:"explore",queryReference:"query",sqlBlockReference:"sqlBlock",givenReference:"given"};class le{constructor(M){this._ref=M}get text(){return this._ref.text}get kind(){return ne[this._ref.type]}get location(){return this._ref.location}get definitionLocation(){return this._ref.definition.location}get definitionType(){return this._ref.definition.type}get defaultText(){if(this._ref.type==="givenReference")return this._ref.definition.defaultText}get annotations(){return new a.Annotations(this._ref.definition.annotations)}}sn.Reference=le;class z{constructor(M,B,L,k,U){var Q,J;this.modelDef=M,this.problems=B,this.fromSources=L,this.runtimeContext=U,this.references=new f.ReferenceList((Q=L[0])!==null&&Q!==void 0?Q:"",(J=M.references)!==null&&J!==void 0?J:[]),this._queryModel=k,this.contentsMap=new Map(Object.entries(M.contents))}getContent(M){return this.contentsMap.get(M)}get queryModel(){return this._queryModel||(this._queryModel=new e.QueryModel(this.modelDef)),this._queryModel}getExistingQueryModel(){return this._queryModel}get givens(){var M,B;const L=new Map,k=this.modelDef.givens;if(!k)return L;for(const[U,Q]of this.contentsMap){if(Q.type!=="given"||!((B=(M=this.runtimeContext)===null||M===void 0?void 0:M.finalizedGivens)===null||B===void 0)&&B.has(U))continue;const J=k[Q.id];J&&!J.inline&&L.set(U,new se(U,Q.id,J,this.modelDef))}return L}get _ownModelAnnotations(){var M;return(M=this.modelDef.modelAnnotations[this.modelDef.modelID])===null||M===void 0?void 0:M.ownNotes}tagParse(M){return(0,a.annotationToTag)(this._ownModelAnnotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this._ownModelAnnotations,M)}get annotations(){return new a.Annotations(this._ownModelAnnotations)}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this.modelDef))}referenceAt(M){const B=this.references.find(M);return B?new le(B):void 0}getReference(M){return this.references.find(M)}getImport(M){var B;return(B=this.modelDef.imports)===null||B===void 0?void 0:B.find(L=>(0,l.locationContainsPosition)(L.location,M))}getPreparedQueryByName(M){const B=this.getContent(M);if((B==null?void 0:B.type)==="query")return new I(B,this,this.problems,M);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(M){if(M<0)throw new Error(`Invalid index ${M}.`);if(M>=this.modelDef.queryList.length)throw new Error(`Query index ${M} is out of bounds.`);return new I(this.modelDef.queryList[M],this,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new I(this.modelDef.queryList[this.modelDef.queryList.length-1],this,this.problems)}getExploreByName(M){const B=this.getContent(M);if(B&&(0,e.isSourceDef)(B))return new b(this.modelDef,B);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(e.isSourceDef).map(M=>new b(this.modelDef,M))}queries(){const M=[];for(const B of Object.values(this.modelDef.contents))B.type==="query"&&M.push(B.name);return{named:M,unnamed:this.modelDef.queryList.length}}get namedQueries(){const M=B=>B.type==="query";return Object.values(this.modelDef.contents).filter(M)}get exportedExplores(){return this.explores.filter(M=>this.modelDef.exports.includes(M.name))}get _modelDef(){return this.modelDef}getBuildPlan(){if(!this.modelAnnotations.parseAsTag("!").tag.has("experimental","persistence"))throw new Error("Model must have ##! experimental.persistence to use getBuildPlan()");const B=[],L=[];for(const ie of Object.values(this.modelDef.contents))(ie.type==="query"||(0,e.isSourceDef)(ie))&&B.push(...(0,r.findPersistentDependencies)(ie,this.modelDef,L));for(const ie of this.modelDef.queryList)B.push(...(0,r.findPersistentDependencies)(ie,this.modelDef,L));if(B.length===0)return{graphs:[],sources:{},tagParseLog:L};const k=(0,r.minimalBuildGraph)(B),U={},Q=ie=>{for(const ae of ie){if(!(ae.sourceID in U)){const de=(0,i.resolveSourceID)(this.modelDef,ae.sourceID);de&&(U[ae.sourceID]=new X(new b(this.modelDef,de),this))}Q(ae.dependsOn)}};Q(k);const J=new Map;for(const ie of k){const ae=U[ie.sourceID];if(!ae)continue;const de=ae.connectionName;J.has(de)||J.set(de,[]),J.get(de).push(ie)}const W=[];for(const[ie,ae]of J)W.push({connectionName:ie,nodes:[ae]});return{graphs:W,sources:U,tagParseLog:L}}}sn.Model=z;class X{constructor(M,B){this.explore=M,this.model=B;const L=M.structDef;if(!(0,e.isSourceDef)(L))throw new Error("Cannot create PersistSource from non-source type");if(!(0,e.isPersistableSourceDef)(L))throw new Error(`Cannot persist source '${M.name}' of type '${L.type}'. Only query_source and sql_select sources can be persisted.`);this.persistableDef=L}get name(){return this.explore.name}get sourceID(){const M=this.persistableDef.sourceID;if(!M)throw new Error(`PersistSource '${this.name}' has no sourceID. This should not happen - sourceID is set at translation time.`);return M}get _explore(){return this.explore}get annotation(){return this.persistableDef.annotations}tagParse(M){return this.explore.tagParse(M)}getTaglines(M){return this.explore.getTaglines(M)}get annotations(){return this.explore.annotations}get modelAnnotations(){return this.explore.modelAnnotations}get connectionName(){return this.persistableDef.connection}get dialectName(){return this.persistableDef.dialect}get dialect(){return(0,n.getDialect)(this.dialectName)}makeBuildId(M,B){return(0,i.mkBuildID)(M,B)}getSQL(M){const B=this.persistableDef,L=this.model.queryModel;return B.type==="sql_select"?(0,e.getCompiledSQL)(B,M??{},(k,U)=>L.compileQuery(k,U,!1).sql):L.compileQuery(B.query,M,!1).sql}get _sourceDef(){return this.persistableDef}get _model(){return this.model}}sn.PersistSource=X;class se{constructor(M,B,L,k){this.name=M,this.id=B,this._internal=L,this._modelDef=k}get type(){return this._internal.type}get default(){return this._internal.default}get location(){return this._internal.location}tagParse(M){return(0,a.annotationToTag)(this._internal.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this._internal.annotations,M)}get annotations(){return new a.Annotations(this._internal.annotations)}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this._modelDef))}}sn.Given=se;class fe{constructor(M){this.pipelineDef=M}get annotations(){return new a.Annotations(this.pipelineDef.annotations)}get location(){return this.pipelineDef.location}tagParse(M){return(0,a.annotationToTag)(this.pipelineDef.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this.pipelineDef.annotations,M)}}class I extends fe{constructor(M,B,L,k){super(M),this._model=B,this.problems=L,this.name=k}get _query(){return this.pipelineDef}get _modelDef(){return this._model._modelDef}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this._modelDef))}get preparedResult(){return this.getPreparedResult()}getPreparedResult(M){const B=this._model.queryModel,L=M!=null&&M.givens?(0,s.resolveSuppliedGivens)(M.givens,this._modelDef):new Map;(0,s.evaluateInlineGivens)(L,this._modelDef);const k={...M,resolvedGivens:L.size>0?L:void 0},U=B.compileQuery(this._query,k);return new q({...U,queryName:this.name||U.queryName},this._modelDef)}get dialect(){const M=this._query.structRef,B=typeof M=="string"?this._model.getContent(M):M;if(B===void 0||!(0,e.isSourceDef)(B))throw new Error("Invalid source for query");return B.dialect}getFlattenedQuery(M){return this}get model(){return this._model}get givens(){const M=new Map,B=this._query.givenUsage;if(!B||B.length===0)return M;const L=new Set(B.map(k=>k.id));for(const[k,U]of this._model.givens)L.has(U.id)&&M.set(k,U);return M}}sn.PreparedQuery=I;class q{constructor(M,B){this.modelDef=B,this.inner=M}static fromJson({query:M,modelDef:B}){if(!M||!B)throw new Error("Missing required properties in JSON data");return new q(M,B)}tagParse(M){return(0,a.annotationToTag)(this.inner.annotations,M)}getTaglines(M){return(0,a.annotationToTaglines)(this.inner.annotations,M)}get annotations(){return new a.Annotations(this.inner.annotations)}get modelAnnotations(){return new a.Annotations((0,e.getModelAnnotations)(this.modelDef))}get annotation(){return this.inner.annotations}get modelAnnotation(){return(0,e.getModelAnnotations)(this.modelDef)}get modelTag(){return new a.Annotations((0,e.getModelAnnotations)(this.modelDef)).parseAsTag().tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const M=this.inner.structs[this.inner.structs.length-1],B={...M,annotations:this.inner.annotations,name:this.inner.queryName||M.name};try{return new b(this.modelDef,B,this.sourceExplore)}catch{return new b(this.modelDef,B)}}get sourceExplore(){const M=this.inner.sourceExplore,B=(0,e.safeRecordGet)(this.modelDef.contents,M);if(B&&(0,e.isSourceDef)(B))return new b(this.modelDef,B)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceArguments(){return this.inner.sourceArguments}get _sourceFilters(){return this.inner.sourceFilters||[]}get hasSchema(){return this.inner.structs.length>0}toStableResult(M){const B=this.inner.structs,L=B[B.length-1],k={fields:(0,u.convertFieldInfos)(L,L.fields)},U=(0,u.toStableAnnotations)(this.inner.annotations),Q=L.resultMetadata?(0,u.getResultStructMetadataAnnotation)(L,L.resultMetadata):void 0;Q&&U.push(Q);const J=o.Tag.withPrefix("#(malloy) "),W=this.sourceExplore;if(W&&J.set(["source","name"],W.name),this._sourceArguments){const ae=Object.entries(this._sourceArguments);for(let de=0;de<ae.length;de++){const[pe,Se]=ae[de],ye=(0,c.nodeToLiteralValue)(Se.value);ye!==void 0&&(0,u.writeLiteralToTag)(J,["source","parameters",de,"value"],ye),J.set(["source","parameters",de,"name"],pe)}}U.push({value:J.toString()}),U.push({value:o.Tag.withPrefix("#(malloy) ").set(["query_name"],this.inner.queryName||L.name).toString()});const ie=(0,u.toStableAnnotations)((0,e.getModelAnnotations)(this.modelDef));return{schema:k,data:M,connection_name:this.inner.connectionName,annotations:U.length>0?U:void 0,model_annotations:ie.length>0?ie:void 0,query_timezone:L.queryTimezone,sql:this.inner.sql}}}return sn.PreparedResult=q,sn}var yd={},Fce;function Lce(){if(Fce)return yd;Fce=1,Object.defineProperty(yd,"__esModule",{value:!0}),yd.DataRecord=yd.DataArray=yd.Result=void 0;const e=Si(),t=Vv(),n=aw();class r extends n.PreparedResult{constructor(O,N){super(O,N),this.inner=O}get _queryResult(){return this.inner}get data(){return new T(this.inner.result,this.resultExplore,void 0,void 0)}get totalRows(){return this.inner.totalRows}get runStats(){return this.inner.runStats}get profilingUrl(){return this.inner.profilingUrl}toJSON(){return this.hasSchema?{queryResult:{...this.inner,result:this.data.toJSON()},modelDef:this._modelDef}:{queryResult:this.inner,modelDef:this._modelDef}}static fromJSON({queryResult:O,modelDef:N}){return new r(O,N)}}yd.Result=r;class i{constructor(O,N,F){this.parent=N,this.parentRecord=F,this._field=O}get field(){return this._field}isString(){return this instanceof o}get string(){if(this.isString())return this;throw new Error("Not a string.")}isBoolean(){return this instanceof u}get boolean(){if(this.isBoolean())return this;throw new Error("Not a boolean.")}isNumber(){return this instanceof l}get number(){if(this.isNumber())return this;throw new Error("Not a number.")}isTimestamp(){return this instanceof f}get timestamp(){if(this.isTimestamp())return this;throw new Error("Not a timestamp.")}isDate(){return this instanceof d}get date(){if(this.isDate())return this;throw new Error("Not a date.")}isNull(){return this instanceof x}isBytes(){return this instanceof p}get bytes(){if(this.isBytes())return this;throw new Error("Not bytes.")}isRecord(){return this instanceof w}get record(){if(this.isRecord())return this;throw new Error("Not a record.")}isUnsupported(){return this instanceof a}get unsupported(){if(this.isUnsupported())return this;throw new Error("Not unsupported.")}isArray(){return this instanceof T}get array(){if(this.isArray())return this;throw new Error("Not an array.")}isArrayOrRecord(){if(this instanceof T||this instanceof w)return this;throw new Error("No Array or Record")}isScalar(){return!0}}class s extends i{constructor(O,N,F,$){super(N,F,$),this._value=O,this._field=N}get value(){return this._value}get field(){return this._field}isScalar(){return this instanceof s}}class o extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get field(){return this._field}get key(){return this.value}compareTo(O){return this.value.toLocaleLowerCase().localeCompare(O.value.toLocaleLowerCase())}}class a extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get field(){return this._field}get key(){return"<unsupported>"}compareTo(O){return 0}}class u extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get field(){return this._field}get key(){return`${this.value}`}compareTo(O){return this.value===O.value?0:this.value?1:-1}}class c extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get field(){return this._field}get key(){return this.value}compareTo(O){const N=this.value.toString(),F=O.toString();return N===F?0:N>F?1:-1}}class l extends s{constructor(O,N,F,$){super((0,t.rowDataToNumber)(O),N,F,$),this._field=N}get field(){return this._field}get key(){return`${this.value}`}compareTo(O){const N=this.value-O.value;return N>0?1:N===0?0:-1}}class f extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get value(){return(0,t.rowDataToDate)(this._value)}get field(){return this._field}get key(){return`${this.value.toLocaleString()}`}compareTo(O){return this.value>O.value?1:this.value<O.value?-1:0}}class d extends s{constructor(O,N,F,$){super(O,N,F,$),this._field=N}get value(){return(0,t.rowDataToDate)(this._value)}get field(){return this._field}get key(){return`${this.value.toLocaleString()}`}compareTo(O){return this.value>O.value?1:this.value<O.value?-1:0}}class p extends s{get key(){return this.value.toString()}compareTo(O){const N=this.value.toString(),F=O.toString();return N===F?0:N>F?1:-1}}class x extends i{get value(){return null}get key(){return"<null>"}}function m(R){const O=(0,t.rowDataToSerializedBigint)(R);if(O.includes(".")||O.includes("e")||O.includes("E"))return(0,t.rowDataToNumber)(R);try{return BigInt(O)}catch{return(0,t.rowDataToNumber)(R)}}function g(R){const O=(0,t.rowDataToSerializedBigint)(R);return O.includes(".")||O.includes("e")||O.includes("E")?(0,t.rowDataToNumber)(R):O}const y={number:t.rowDataToNumber,bigint:m,date:t.rowDataToDate},E={number:t.rowDataToNumber,bigint:g,date:R=>(0,t.rowDataToDate)(R).toISOString()};function v(R,O,N){return R.map(F=>S(F,O,N))}function S(R,O,N){const F={};for(const $ of O.fields){const V=(0,e.activeName)($),K=R[V];F[V]=b(K,$,N)}return F}function b(R,O,N){if(R==null)return null;if(O.type==="number")return O.numberType==="bigint"?N.bigint(R):N.number(R);if(O.type==="date"||O.type==="timestamp"||O.type==="timestamptz")return N.date(R);if(O.type==="string"||O.type==="boolean"||O.type==="json"||O.type==="sql native")return O.type==="boolean"&&typeof R=="number"?R!==0:R;if(O.type==="array"){if(!Array.isArray(R))return R;if((0,e.isRepeatedRecord)(O))return R.map(F=>S(F,O,N));if((0,e.isBasicArray)(O)){const F=O.elementTypeDef;return R.map($=>C($,F,N))}}return O.type==="record"&&typeof R=="object"&&R!==null&&!Array.isArray(R)?S(R,O,N):R}function C(R,O,N){if(R==null)return null;if(O.type==="number")return O.numberType==="bigint"?N.bigint(R):N.number(R);if(O.type==="date"||O.type==="timestamp"||O.type==="timestamptz")return N.date(R);if(O.type==="boolean"&&typeof R=="number")return R!==0;if(O.type==="array"&&Array.isArray(R)){if((0,e.isBasicArray)(O)){const F=O.elementTypeDef;return R.map($=>C($,F,N))}else if((0,e.isRepeatedRecord)(O))return R.map(F=>S(F,O,N))}return R}function _(R,O){for(const N of O)typeof N=="number"?R=R.array.row(N):R=R.record.cell(N);return R}class T extends i{constructor(O,N,F,$){super(N,F,$),this.rowCache=new Map,this.queryData=O,this._field=N}get field(){return this._field}get rawData(){return this.queryData}toObject(){return v(this.queryData,this._field.structDef,y)}toJSON(){return v(this.queryData,this._field.structDef,E)}path(...O){return _(this,O)}row(O){let N=this.rowCache.get(O);return N||(N=new w(this.queryData[O],O,this.field,this,this.parentRecord),this.rowCache.set(O,N)),N}get rowCount(){return this.queryData.length}get value(){return this.toObject()}[Symbol.iterator](){let O=0;const N=this.queryData,F=$=>this.row($);return{next(){return O<N.length?{value:F(O++),done:!1}:{value:void 0,done:!0}}}}async*inMemoryStream(){for(let O=0;O<this.queryData.length;O++)yield this.row(O)}}yd.DataArray=T;class w extends i{constructor(O,N,F,$,V){super(F,$,V),this.cellCache=new Map,this.queryDataRow=O,this._field=F,this.index=N}toObject(){return S(this.queryDataRow,this._field.structDef,y)}toJSON(){return S(this.queryDataRow,this._field.structDef,E)}path(...O){return _(this,O)}cell(O){const N=typeof O=="string"?O:O.name,F=this._field.getFieldByName(N);let $=this.cellCache.get(N);if(!$){const V=this.queryDataRow[N];V===null?$=new x(F,this,this):F.isAtomicField()?F.isBoolean()?$=new u(V,F,this,this):F.isDate()?$=new d(V,F,this,this):F.isJSON()?$=new c(V,F,this,this):F.isTimestamp()?$=new f(V,F,this,this):F.isNumber()?$=new l(V,F,this,this):F.isString()?$=new o(V,F,this,this):F.isUnsupported()&&($=new a(V,F,this,this)):F.isExploreField()&&((0,e.isCompoundArrayData)(V)?$=new T(V,F,this,this):$=new w(V,void 0,F,this,this)),$&&this.cellCache.set(N,$)}if($)return $;throw new Error(`Internal Error: could not construct data column for field '${N}'.`)}get value(){throw new Error("Not implemented;")}get field(){return this._field}[Symbol.iterator](){let O=!1;const N=()=>this;return{next(){return O?{value:void 0,done:!0}:(O=!0,{value:N(),done:!1})}}}}return yd.DataRecord=w,yd}var Ed={},Ice;function r9e(){if(Ice)return Ed;Ice=1,Object.defineProperty(Ed,"__esModule",{value:!0}),Ed.CSVWriter=Ed.JSONWriter=Ed.DataWriter=void 0;const e=Si();class t{constructor(s){this.stream=s}}Ed.DataWriter=t;class n extends t{async process(s){this.stream.write(`[
1364
1364
  `);for await(const o of s){o.index!==void 0&&o.index>0&&this.stream.write(`,
1365
1365
  `);const u=JSON.stringify(o.toJSON(),null,2).split(`
1366
1366
  `);for(let c=0;c<u.length;c++){const l=u[c];this.stream.write(` ${l}`),c<u.length-1&&this.stream.write(`
1367
1367
  `)}}this.stream.write(`
1368
1368
  ]
1369
1369
  `),this.stream.close()}}Ed.JSONWriter=n;class r extends t{constructor(){super(...arguments),this.columnSeparator=",",this.rowSeparator=`
1370
- `,this.quoteCharacter='"',this.includeHeader=!0,this.emptyCell=""}escape(s){const o=s.includes(this.quoteCharacter),a=s.includes(this.columnSeparator),u=s.includes(this.rowSeparator),c=a||o||u;return o&&(s=s.replace(new RegExp(this.quoteCharacter,"g"),this.quoteCharacter+this.quoteCharacter)),c&&(s=this.quoteCharacter+s+this.quoteCharacter),s}stringify(s){return s===null?this.emptyCell:s instanceof Date?s.toISOString():typeof s=="boolean"||typeof s=="number"?JSON.stringify(s):typeof s=="bigint"?s.toString():`${s}`}getColWeight(s){let o=s;Array.isArray(s)&&(o=s[0]);let a=0;for(const u in o){a=a+1;const c=o[u];if((0,e.isCompoundArrayData)(c)){const l=this.getColWeight(c)-1;a=a+l}}return a}getHeaderRow(s){const o=[];let a=0;for(const u in s){o.push(this.escape(u));const c=s[u];if(a++,(0,e.isCompoundArrayData)(c)){const l=this.getColWeight(c)-1;a=a+l;for(let f=0;f<l;f++)o.push(this.emptyCell)}}return{rows:[o.join(this.columnSeparator)],length:1,width:a}}mergeMatrices(s){const o=Math.max(...s.map(c=>c.length)),a=s.reduce((c,l)=>c+l.width,0),u=[];for(let c=0;c<o;c++){const l=[];for(const f of s)if(c<f.length)l.push(f.rows[c]);else{const d=Array(f.width).fill(this.emptyCell);l.push(...d)}u.push(l.join(this.columnSeparator))}return{rows:u,length:o,width:a}}getChildMatrix(s){if(Array.isArray(s)){if(s.length===0)return{rows:[""],length:1,width:1}}else return{rows:["Invalid data found, value is not an array"],length:1,width:1};const o=[],a=this.getHeaderRow(s[0]);o.push(...a.rows);const u=a.width;let c=1;for(const l of s){const f=this.getRowMatrix(l);c=c+f.length,o.push(...f.rows)}return{rows:o,length:c,width:u}}getRowMatrix(s){const o=[];for(const a in s){const u=s[a];if((0,e.isCompoundArrayData)(u)){const c=this.getChildMatrix(u);o.push(c)}else{const c={rows:[this.stringify(u)],length:1,width:1};o.push(c)}}return this.mergeMatrices(o)}async process(s){let o=!1;for await(const a of s){if(!o&&this.includeHeader){const c=this.getHeaderRow(a.toObject());this.stream.write(c.rows[0]),this.stream.write(this.rowSeparator),o=!0}const u=this.getRowMatrix(a.toObject());for(const c of u.rows)this.stream.write(c),this.stream.write(this.rowSeparator)}this.stream.close()}}return Ed.CSVWriter=r,Ed}var ss={},fx={},uw={},Ea={},Mce;function HA(){if(Mce)return Ea;Mce=1,Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.isConnectionConfigEntry=e,Ea.registerConnectionType=n,Ea.getConnectionProperties=r,Ea.getConnectionTypeDisplayName=i,Ea.getRegisteredConnectionTypes=s,Ea.getConnectionTypeDef=o,Ea.validateConnectionConfigProperties=a,Ea.readConnectionsConfig=u,Ea.writeConnectionsConfig=c,Ea.createConnectionsFromConfig=l;function e(f){return typeof f=="object"&&f!==null&&typeof f.is=="string"}const t=new Map;function n(f,d){t.set(f,d)}function r(f){var d;return(d=t.get(f))===null||d===void 0?void 0:d.properties}function i(f){var d;return(d=t.get(f))===null||d===void 0?void 0:d.displayName}function s(){return[...t.keys()]}function o(f){return t.get(f)}function a(f,d,p){var x,m;const g=(m=(x=t.get(d))===null||x===void 0?void 0:x.properties)!==null&&m!==void 0?m:[];for(const y of g){if(!y.requireLiteralString)continue;const E=p[y.name];if(E!==void 0&&typeof E!="string")throw new Error(`Connection "${f}" property "${y.name}" must be a literal string`)}}function u(f){var d;const p=JSON.parse(f),x=Object.fromEntries(Object.entries((d=p.connections)!==null&&d!==void 0?d:{}).filter(([,m])=>e(m)));return{...p,connections:x}}function c(f){return JSON.stringify(f,null,2)}function l(f,d){const p=Object.entries(f.connections),x=p.length>0?p[0][0]:void 0,m=new Map;return{async lookupConnection(g){if(g===void 0&&(g=x),g===void 0)throw new Error("No connections defined in config");const y=m.get(g);if(y)return y;const E=f.connections[g];if(!E)throw new Error(`No connection named "${g}" found in config`);const v=t.get(E.is);if(!v)throw new Error(`No registered connection type "${E.is}" for connection "${g}". Did you forget to import the connection package?`);const S={name:g};for(const[C,_]of Object.entries(E))C!=="is"&&_!=null&&(S[C]=_);a(g,E.is,S);const b=await v.factory(S);return d&&d(g,b),m.set(g,b),b},async close(){const g=[...m.values()];m.clear();for(const y of g)await y.close()},async idle(){for(const g of m.values())await g.idle()}}}return Ea}var kce;function i9e(){if(kce)return uw;kce=1,Object.defineProperty(uw,"__esModule",{value:!0}),uw.compileConfig=i;const e=HA(),t=ZZ(),n={connections:s,manifestPath:u,givensPath:c,finalizeGivens:l,virtualMap:f,includeDefaultConnections:d},r=new Set(Object.keys(n));function i(E){const v=[],S={kind:"dict",entries:{}};if(!x(E))return v.push({message:"config is not a JSON object",severity:"error",code:"config-validation"}),{compiled:S,log:v};for(const[b,C]of Object.entries(E)){const _=n[b];if(!_){const w=(0,t.closestMatch)(b,[...r]),R=w?`. Did you mean "${w}"?`:"";v.push(m(b,`unknown config key "${b}"${R}`));continue}const T=_(C,v);T!==void 0&&(S.entries[b]=T)}return{compiled:S,log:v}}function s(E,v){if(!x(E)){v.push(m("connections",'"connections" should be an object'));return}const S=new Set((0,e.getRegisteredConnectionTypes)()),b={kind:"dict",entries:{}};for(const[C,_]of Object.entries(E)){const T=`connections.${C}`;if(!x(_)){v.push(m(T,"should be an object"));continue}const w=_.is;if(w==null||w===""){v.push(m(T,'missing required "is" field (connection type)'));continue}if(typeof w!="string"){v.push(m(`${T}.is`,'"is" should be a string'));continue}if(!S.has(w)){const O=(0,t.closestMatch)(w,[...S]),N=O?` Did you mean "${O}"?`:"";v.push(m(`${T}.is`,`unknown connection type "${w}".${N} Available types: ${[...S].join(", ")}`));continue}const R=o(T,w,_,v);b.entries[C]=R}return b}function o(E,v,S,b){var C;const _=(C=(0,e.getConnectionProperties)(v))!==null&&C!==void 0?C:[],T=new Map(_.map(R=>[R.name,R])),w={kind:"dict",entries:{}};w.entries.is={kind:"value",value:v};for(const[R,O]of Object.entries(S)){if(R==="is")continue;const N=T.get(R);if(!N){const $=(0,t.closestMatch)(R,[...T.keys()]),V=$?`. Did you mean "${$}"?`:"";b.push(m(`${E}.${R}`,`unknown property "${R}" for connection type "${v}"${V}`));continue}const F=a(`${E}.${R}`,N,O,b);F!==void 0&&(w.entries[R]=F)}return w}function a(E,v,S,b){if(S==null)return;if(v.type==="json")return{kind:"value",value:S};const C=p(S);if(C!==void 0)return v.requireLiteralString?(b.push(m(E,"must be a literal string and cannot use an overlay reference")),{kind:"value",value:S}):C;const _=y(S,v.type);if(_){if(v.requireLiteralString)return b.push(m(E,`must be a literal string, got ${g(S)}`)),{kind:"value",value:S};b.push(m(E,`${_} (expected ${v.type})`));return}return{kind:"value",value:S}}function u(E,v){const S=p(E);if(S!==void 0)return S;if(typeof E!="string"){v.push(m("manifestPath",'"manifestPath" should be a string or an overlay reference'));return}return{kind:"value",value:E}}function c(E,v){const S=p(E);if(S!==void 0)return S;if(typeof E!="string"){v.push(m("givensPath",'"givensPath" should be a string or an overlay reference'));return}return{kind:"value",value:E}}function l(E,v){if(!Array.isArray(E)||!E.every(S=>typeof S=="string")){v.push(m("finalizeGivens",'"finalizeGivens" should be an array of given names'));return}return{kind:"value",value:E}}function f(E,v){return{kind:"value",value:E}}function d(E,v){return{kind:"value",value:E}}function p(E){if(typeof E!="object"||E===null||Array.isArray(E))return;const v=Object.keys(E);if(v.length!==1)return;const S=v[0],b=E[S];if(typeof b=="string")return{kind:"reference",source:S,path:[b]};if(Array.isArray(b)&&b.every(C=>typeof C=="string"))return{kind:"reference",source:S,path:b}}function x(E){return typeof E=="object"&&E!==null&&!Array.isArray(E)}function m(E,v){return{message:`${E}: ${v}`,severity:"warn",code:"config-validation"}}function g(E){return Array.isArray(E)?"array":typeof E}function y(E,v){switch(v){case"number":if(typeof E!="number")return`should be a number, got ${typeof E}`;break;case"boolean":if(typeof E!="boolean")return`should be a boolean, got ${typeof E}`;break;case"string":case"password":case"secret":case"file":case"text":if(typeof E!="string")return`should be a string, got ${typeof E}`;break}}return uw}var lw={},M1={},Pce;function Fk(){if(Pce)return M1;Pce=1;var e={};Object.defineProperty(M1,"__esModule",{value:!0}),M1.envOverlay=t,M1.contextOverlay=n,M1.defaultConfigOverlays=r,M1.isThenable=i;function t(){return typeof process>"u"||!e?()=>{}:s=>e[s[0]]}function n(s){return o=>s[o[0]]}function r(){return{env:t(),config:()=>{}}}function i(s){return typeof s=="object"&&s!==null&&"then"in s&&typeof s.then=="function"}return M1}var $ce;function s9e(){if($ce)return lw;$ce=1,Object.defineProperty(lw,"__esModule",{value:!0}),lw.prepareConfig=n;const e=HA(),t=Fk();function n(a,u,c){let l={},f,d,p,x,m=!1;for(const[g,y]of Object.entries(a.entries))switch(g){case"connections":{if(y.kind!=="dict")break;l=i(y);break}case"manifestPath":{f=o(y,u,c,"manifestPath");break}case"givensPath":{d=o(y,u,c,"givensPath");break}case"finalizeGivens":{y.kind==="value"&&r(y.value)&&(p=y.value);break}case"virtualMap":{y.kind==="value"&&(x=y.value);break}case"includeDefaultConnections":{y.kind==="value"&&typeof y.value=="boolean"&&(m=y.value);break}}return m&&s(l),{compiledConnections:l,manifestPath:f,givensPath:d,finalizeGivens:p,virtualMap:x}}function r(a){return Array.isArray(a)&&a.every(u=>typeof u=="string")}function i(a){const u={};for(const[c,l]of Object.entries(a.entries))l.kind==="dict"&&(u[c]=l);return u}function s(a){for(const u of(0,e.getRegisteredConnectionTypes)())a[u]||(a[u]={kind:"dict",entries:{is:{kind:"value",value:u}}})}function o(a,u,c,l){if(a.kind==="value")return typeof a.value=="string"?a.value:void 0;if(a.kind==="reference"){const f=u[a.source];if(!f){c.push({message:`unknown overlay source "${a.source}" for "${l}"`,severity:"warn",code:"config-overlay"});return}const d=f(a.path);if((0,t.isThenable)(d)){c.push({message:`the \`${a.source}\` overlay returned a Promise for "${l}"; top-level string settings must resolve synchronously`,severity:"warn",code:"config-overlay"});return}return typeof d=="string"?d:void 0}}return lw}var cw={},Bce;function o9e(){if(Bce)return cw;Bce=1,Object.defineProperty(cw,"__esModule",{value:!0}),cw.buildManagedLookup=t;const e=HA();function t(a,u,c){const l=Object.entries(a),f=l.length>0?l[0][0]:void 0,d=new Map;return{async lookupConnection(p){if(p===void 0&&(p=f),p===void 0)throw new Error("No connections defined in config");const x=d.get(p);if(x)return x;const m=a[p];if(!m)throw new Error(`No connection named "${p}" found in config`);const g=await n(m,u,c);if(typeof g.is!="string")throw new Error(`Connection "${p}" is missing a valid "is" field`);const y=(0,e.getConnectionTypeDef)(g.is);if(!y)throw new Error(`No registered connection type "${g.is}" for connection "${p}". Did you forget to import the connection package?`);const E={name:p};for(const[S,b]of Object.entries(g))S!=="is"&&b!=null&&(E[S]=b);(0,e.validateConnectionConfigProperties)(p,g.is,E);const v=await y.factory(E);return d.set(p,v),v},async close(){const p=[...d.values()];d.clear();for(const x of p)await x.close()},async idle(){for(const p of d.values())await p.idle()}}}async function n(a,u,c){const l=await r(a,u,c);if(!(0,e.isConnectionConfigEntry)(l))throw new Error("Connection entry did not resolve to a valid {is: string, ...} dict");return await s(l,u),l}async function r(a,u,c){switch(a.kind){case"value":return a.value;case"reference":return i(a,u,c);case"dict":{const l={};for(const[f,d]of Object.entries(a.entries)){const p=await r(d,u,c);p!==void 0&&(l[f]=p)}return l}}}async function i(a,u,c){const l=u[a.source];if(!l){c.push({message:`unknown overlay source "${a.source}" for reference path ${JSON.stringify(a.path)}`,severity:"warn",code:"config-overlay"});return}return await l(a.path)}async function s(a,u){var c;const l=a.is;if(typeof l!="string")return;const f=(c=(0,e.getConnectionProperties)(l))!==null&&c!==void 0?c:[];for(const d of f){if(d.default===void 0||a[d.name]!==void 0)continue;const p=await o(d.default,u);p!==void 0&&(a[d.name]=p)}}async function o(a,u){if(typeof a!="object")return a;const c=Object.keys(a);if(c.length!==1)return;const l=c[0],f=a[l],d=typeof f=="string"?[f]:f;if(!Array.isArray(d))return;const p=u[l];if(p)return await p(d)}return cw}var qce;function Lk(){if(qce)return fx;qce=1,Object.defineProperty(fx,"__esModule",{value:!0}),fx.MalloyConfig=fx.Manifest=void 0,fx.isBuildManifestEntry=E;const e=i9e(),t=s9e(),n=o9e(),r=Fk(),i=Dk();class s{constructor(){this._manifest={entries:{},strict:!1},this._touched=new Set}loadText(S){this._clearEntries(),this._touched.clear(),this._manifest.strict=!1,this._loadParsed(JSON.parse(S))}get buildManifest(){return this._manifest}get strict(){var S;return(S=this._manifest.strict)!==null&&S!==void 0?S:!1}set strict(S){this._manifest.strict=S}update(S,b){(0,i.requireCanonicalTablePathAnyDialect)(b.tableName,`Manifest entry '${S}'`),this._manifest.entries[S]=b,this._touched.add(S)}touch(S){this._touched.add(S)}get activeEntries(){const S={};for(const b of this._touched)this._manifest.entries[b]&&(S[b]=this._manifest.entries[b]);return{entries:S,strict:this._manifest.strict}}_clearEntries(){for(const S of Object.keys(this._manifest.entries))delete this._manifest.entries[S]}_loadParsed(S){typeof S.strict=="boolean"&&(this._manifest.strict=S.strict);const b=y(S.entries)?S.entries:S;for(const[C,_]of Object.entries(b))C==="strict"||!E(_)||((0,i.requireCanonicalTablePathAnyDialect)(_.tableName,`Manifest entry '${C}'`),this._manifest.entries[C]=_)}}fx.Manifest=s;class o{constructor(S,b){const C=[];let _;if(typeof S=="string")try{_=JSON.parse(S)}catch($){C.push({message:`Invalid JSON: ${$ instanceof Error?$.message:String($)}`,severity:"error",code:"config-validation"}),_={}}else _=S;const T=(0,e.compileConfig)(_);C.push(...T.log);const w=f(b,C),R=m(w.configURL,"configURL",C),O=w.rootDirectory,N={...(0,r.defaultConfigOverlays)(),...w.overlays,config:(0,r.contextOverlay)({configURL:R,rootDirectory:O})},F=(0,t.prepareConfig)(T.compiled,N,C);this._managedLookup=(0,n.buildManagedLookup)(F.compiledConnections,N,C),this._connections=this._managedLookup,this._overlays=N,this.virtualMap=g(F.virtualMap,C),this.configURL=R,this.rootDirectory=O,this.manifestPath=F.manifestPath,this.manifestURL=c(F.manifestPath,R),this.givensPath=F.givensPath,this.givensURL=l(F.givensPath,R,C),this.finalizeGivens=F.finalizeGivens,this.log=C}get connections(){return this._connections}wrapConnections(S){this._connections=S(this._connections)}async shutdown(S="close"){S==="idle"?await this._managedLookup.idle():await this._managedLookup.close()}async releaseConnections(){await this.shutdown("close")}async readOverlay(S,...b){var C,_;return await((_=(C=this._overlays)[S])===null||_===void 0?void 0:_.call(C,b))}}fx.MalloyConfig=o;const a="MANIFESTS",u="malloy-manifest.json";function c(v,S){if(!S)return;let b;try{b=new URL(S)}catch{return}const C=v??a;let _;try{_=new URL(C,b)}catch{return}const T=_.toString(),w=T.endsWith("/")?_:new URL(T+"/");return new URL(u,w).toString()}function l(v,S,b){if(!v)return;if(!S){b.push({message:"givensPath is set but no configURL is available; per-runtime givens will not be loaded. Pass `configURL` (or use an absolute URL such as `file:///...`).",severity:"warn",code:"config-overlay"});return}let C;try{C=new URL(S)}catch{return}try{return new URL(v,C).toString()}catch(_){const T=_ instanceof Error?_.message:String(_);b.push({message:`givensPath '${v}' could not be resolved against configURL '${S}': ${T}`,severity:"warn",code:"config-validation"});return}}function f(v,S){if(v===void 0)return{};if(d(v))return p(v,S);const b=v;if(b.overlays&&"config"in b.overlays){S.push({message:"`config` is reserved by MalloyConfig; pass `configURL` and `rootDirectory` directly instead. Supplied `overlays.config` ignored.",severity:"warn",code:"config-overlay"});const{config:C,..._}=b.overlays;return{...b,overlays:_}}return b}function d(v){for(const S of Object.values(v))if(typeof S=="function")return!0;return!1}function p(v,S){const b=v.config;if(!b)return{overlays:v};const C=x(b,"configURL",S),_=x(b,"rootDirectory",S),{config:T,...w}=v;return{configURL:C,rootDirectory:_,overlays:w}}function x(v,S,b){const C=v([S]);if((0,r.isThenable)(C)){b.push({message:`the legacy \`config\` overlay returned a Promise for \`${S}\`; top-level FS context must resolve synchronously. ${S} will be undefined.`,severity:"warn",code:"config-overlay"});return}return typeof C=="string"?C:void 0}function m(v,S,b){if(v!==void 0)try{return new URL(v),v}catch{b.push({message:`${S} must be a URL-shaped string (e.g. 'file:///path/to/...'), got '${v}'. In Node, use \`url.pathToFileURL(path).toString()\`.`,severity:"warn",code:"config-validation"});return}}function g(v,S){if(!y(v))return;const b=new Map;for(const[C,_]of Object.entries(v)){if(!y(_))continue;const T=new Map;for(const[w,R]of Object.entries(_)){if(typeof R!="string")continue;const O=(0,i.validateCanonicalTablePathAnyDialect)(R);if(O!==void 0){S.push({message:`virtualMap entry '${C}.${w}': ${O}`,severity:"error",code:"config-validation"});continue}T.set(w,R)}T.size>0&&b.set(C,T)}return b.size>0?b:void 0}function y(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function E(v){return y(v)&&typeof v.tableName=="string"}return fx}var k1={},VA={},Uce;function a9e(){return Uce||(Uce=1,Object.defineProperty(VA,"__esModule",{value:!0}),VA.MALLOY_VERSION=void 0,VA.MALLOY_VERSION="0.0.421"),VA}var jce;function zce(){if(jce)return k1;jce=1,Object.defineProperty(k1,"__esModule",{value:!0}),k1.Malloy=k1.MalloyError=void 0;const e=Ok(),t=HA(),n=Si(),r=T4(),i=a9e(),s=ow(),o=Oce(),a=Gp(),u=aw(),c=Lce();function l(x="loadModel"){return`internal://${x}/${(0,a.v4)()}`}function f(x){return[...Object.keys(x),...Object.values(x).map(f).flat()]}class d extends Error{constructor(m,g=[]){super(m),this.problems=g}}k1.MalloyError=d;class p{static get version(){return i.MALLOY_VERSION}static registerConnectionType(m,g){(0,t.registerConnectionType)(m,g)}static getConnectionProperties(m){return(0,t.getConnectionProperties)(m)}static getConnectionTypeDisplayName(m){return(0,t.getConnectionTypeDisplayName)(m)}static getRegisteredConnectionTypes(){return(0,t.getRegisteredConnectionTypes)()}static _parse(m,g,y,E,v){var S;g===void 0&&(g=new URL(l(E==null?void 0:E.method)));let b=g;E!=null&&E.importBaseURL&&(b=E==null?void 0:E.importBaseURL);const C=new e.MalloyTranslator(g.toString(),b.toString(),{urls:{[g.toString()]:m}},y,(S=E==null?void 0:E.restrictedMode)!==null&&S!==void 0?S:!1);return E!=null&&E.testEnvironment&&(C.allDialectsEnabled=!0),new o.Parse(C,v)}static parse({url:m,urlReader:g,source:y,eventStream:E,options:v}){if(y!==void 0)return p._parse(y,m,E,v);if(g===void 0)throw new Error("Internal Error: urlReader is required.");if(m===void 0)throw new Error("Internal Error: url is required if source not present.");return(0,s.readURL)(g,m).then(({contents:S,invalidationKey:b})=>p._parse(S,m,E,v,b))}static async compile(m){var g,y,E,v,S;let{url:b,source:C,importBaseURL:_,cacheManager:T}=m;const{parse:w,urlReader:R,connections:O,model:N,refreshSchemaCache:F,noThrowOnError:$,eventStream:V,restrictedMode:K,method:ne}=m;K&&(T=void 0);let le;if(F&&(le=typeof F=="number"?F:Date.now()),b===void 0&&C===void 0&&w===void 0)throw new Error("Internal Error: url, source, or parse required.");b===void 0&&(w!==void 0?b=new URL(w._translator.sourceURL):b=new URL(l(ne)));const z={};if(C===void 0&&T!==void 0){const fe=await T.getCachedModelDef(R,b.toString());if(fe)return new u.Model(fe.modelDef,[],[b.toString(),...f(fe.modelDef.dependencies)])}_??(_=b);let X;const se=b.toString();if(w!==void 0){if(K!==void 0&&w._translator.restrictedMode!==K)throw new Error(`Malloy.compile: restrictedMode (${K}) does not match the pre-parsed translator's restrictedMode (${w._translator.restrictedMode}). Set restrictedMode at parse time.`);X=w._translator;const fe=(g=w._invalidationKey)!==null&&g!==void 0?g:await(0,s.getInvalidationKey)(R,b);z[se]=fe}else{if(C===void 0){const{contents:fe,invalidationKey:I}=await(0,s.readURL)(R,b);z[se]=I,C=fe}else{const fe=await(0,s.getInvalidationKey)(R,b);z[se]=fe}X=new e.MalloyTranslator(se,_.toString(),{urls:{[se]:C}},V,K??!1)}for(;;){const fe=X.translate(N==null?void 0:N._modelDef);if(fe.final)if(fe.modelDef){await(T==null?void 0:T.setCachedModelDef(b.toString(),{modelDef:fe.modelDef,invalidationKeys:z}));for(const q of X.newlyTranslatedDependencies())await(T==null?void 0:T.setCachedModelDef(q.url,{modelDef:q.modelDef,invalidationKeys:z}));const I=!fe.modelWasModified&&N?N.getExistingQueryModel():void 0;return new u.Model(fe.modelDef,fe.problems||[],[...(y=N==null?void 0:N.fromSources)!==null&&y!==void 0?y:[],...(E=fe.fromSources)!==null&&E!==void 0?E:[]],I)}else if($){const I=(0,n.mkModelDef)("modelDidNotCompile"),q=(N==null?void 0:N._modelDef)||I;return new u.Model(q,fe.problems||[],[...(v=N==null?void 0:N.fromSources)!==null&&v!==void 0?v:[],...(S=fe.fromSources)!==null&&S!==void 0?S:[]])}else{const I=fe.problems||[],q=X.prettyErrors();throw new d(`Error(s) compiling model:
1370
+ `,this.quoteCharacter='"',this.includeHeader=!0,this.emptyCell=""}escape(s){const o=s.includes(this.quoteCharacter),a=s.includes(this.columnSeparator),u=s.includes(this.rowSeparator),c=a||o||u;return o&&(s=s.replace(new RegExp(this.quoteCharacter,"g"),this.quoteCharacter+this.quoteCharacter)),c&&(s=this.quoteCharacter+s+this.quoteCharacter),s}stringify(s){return s===null?this.emptyCell:s instanceof Date?s.toISOString():typeof s=="boolean"||typeof s=="number"?JSON.stringify(s):typeof s=="bigint"?s.toString():`${s}`}getColWeight(s){let o=s;Array.isArray(s)&&(o=s[0]);let a=0;for(const u in o){a=a+1;const c=o[u];if((0,e.isCompoundArrayData)(c)){const l=this.getColWeight(c)-1;a=a+l}}return a}getHeaderRow(s){const o=[];let a=0;for(const u in s){o.push(this.escape(u));const c=s[u];if(a++,(0,e.isCompoundArrayData)(c)){const l=this.getColWeight(c)-1;a=a+l;for(let f=0;f<l;f++)o.push(this.emptyCell)}}return{rows:[o.join(this.columnSeparator)],length:1,width:a}}mergeMatrices(s){const o=Math.max(...s.map(c=>c.length)),a=s.reduce((c,l)=>c+l.width,0),u=[];for(let c=0;c<o;c++){const l=[];for(const f of s)if(c<f.length)l.push(f.rows[c]);else{const d=Array(f.width).fill(this.emptyCell);l.push(...d)}u.push(l.join(this.columnSeparator))}return{rows:u,length:o,width:a}}getChildMatrix(s){if(Array.isArray(s)){if(s.length===0)return{rows:[""],length:1,width:1}}else return{rows:["Invalid data found, value is not an array"],length:1,width:1};const o=[],a=this.getHeaderRow(s[0]);o.push(...a.rows);const u=a.width;let c=1;for(const l of s){const f=this.getRowMatrix(l);c=c+f.length,o.push(...f.rows)}return{rows:o,length:c,width:u}}getRowMatrix(s){const o=[];for(const a in s){const u=s[a];if((0,e.isCompoundArrayData)(u)){const c=this.getChildMatrix(u);o.push(c)}else{const c={rows:[this.stringify(u)],length:1,width:1};o.push(c)}}return this.mergeMatrices(o)}async process(s){let o=!1;for await(const a of s){if(!o&&this.includeHeader){const c=this.getHeaderRow(a.toObject());this.stream.write(c.rows[0]),this.stream.write(this.rowSeparator),o=!0}const u=this.getRowMatrix(a.toObject());for(const c of u.rows)this.stream.write(c),this.stream.write(this.rowSeparator)}this.stream.close()}}return Ed.CSVWriter=r,Ed}var ss={},fx={},uw={},Ea={},Mce;function HA(){if(Mce)return Ea;Mce=1,Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.isConnectionConfigEntry=e,Ea.registerConnectionType=n,Ea.getConnectionProperties=r,Ea.getConnectionTypeDisplayName=i,Ea.getRegisteredConnectionTypes=s,Ea.getConnectionTypeDef=o,Ea.validateConnectionConfigProperties=a,Ea.readConnectionsConfig=u,Ea.writeConnectionsConfig=c,Ea.createConnectionsFromConfig=l;function e(f){return typeof f=="object"&&f!==null&&typeof f.is=="string"}const t=new Map;function n(f,d){t.set(f,d)}function r(f){var d;return(d=t.get(f))===null||d===void 0?void 0:d.properties}function i(f){var d;return(d=t.get(f))===null||d===void 0?void 0:d.displayName}function s(){return[...t.keys()]}function o(f){return t.get(f)}function a(f,d,p){var x,m;const g=(m=(x=t.get(d))===null||x===void 0?void 0:x.properties)!==null&&m!==void 0?m:[];for(const y of g){if(!y.requireLiteralString)continue;const E=p[y.name];if(E!==void 0&&typeof E!="string")throw new Error(`Connection "${f}" property "${y.name}" must be a literal string`)}}function u(f){var d;const p=JSON.parse(f),x=Object.fromEntries(Object.entries((d=p.connections)!==null&&d!==void 0?d:{}).filter(([,m])=>e(m)));return{...p,connections:x}}function c(f){return JSON.stringify(f,null,2)}function l(f,d){const p=Object.entries(f.connections),x=p.length>0?p[0][0]:void 0,m=new Map;return{async lookupConnection(g){if(g===void 0&&(g=x),g===void 0)throw new Error("No connections defined in config");const y=m.get(g);if(y)return y;const E=f.connections[g];if(!E)throw new Error(`No connection named "${g}" found in config`);const v=t.get(E.is);if(!v)throw new Error(`No registered connection type "${E.is}" for connection "${g}". Did you forget to import the connection package?`);const S={name:g};for(const[C,_]of Object.entries(E))C!=="is"&&_!=null&&(S[C]=_);a(g,E.is,S);const b=await v.factory(S);return d&&d(g,b),m.set(g,b),b},async close(){const g=[...m.values()];m.clear();for(const y of g)await y.close()},async idle(){for(const g of m.values())await g.idle()}}}return Ea}var kce;function i9e(){if(kce)return uw;kce=1,Object.defineProperty(uw,"__esModule",{value:!0}),uw.compileConfig=i;const e=HA(),t=ZZ(),n={connections:s,manifestPath:u,givensPath:c,finalizeGivens:l,virtualMap:f,includeDefaultConnections:d},r=new Set(Object.keys(n));function i(E){const v=[],S={kind:"dict",entries:{}};if(!x(E))return v.push({message:"config is not a JSON object",severity:"error",code:"config-validation"}),{compiled:S,log:v};for(const[b,C]of Object.entries(E)){const _=n[b];if(!_){const w=(0,t.closestMatch)(b,[...r]),R=w?`. Did you mean "${w}"?`:"";v.push(m(b,`unknown config key "${b}"${R}`));continue}const T=_(C,v);T!==void 0&&(S.entries[b]=T)}return{compiled:S,log:v}}function s(E,v){if(!x(E)){v.push(m("connections",'"connections" should be an object'));return}const S=new Set((0,e.getRegisteredConnectionTypes)()),b={kind:"dict",entries:{}};for(const[C,_]of Object.entries(E)){const T=`connections.${C}`;if(!x(_)){v.push(m(T,"should be an object"));continue}const w=_.is;if(w==null||w===""){v.push(m(T,'missing required "is" field (connection type)'));continue}if(typeof w!="string"){v.push(m(`${T}.is`,'"is" should be a string'));continue}if(!S.has(w)){const O=(0,t.closestMatch)(w,[...S]),N=O?` Did you mean "${O}"?`:"";v.push(m(`${T}.is`,`unknown connection type "${w}".${N} Available types: ${[...S].join(", ")}`));continue}const R=o(T,w,_,v);b.entries[C]=R}return b}function o(E,v,S,b){var C;const _=(C=(0,e.getConnectionProperties)(v))!==null&&C!==void 0?C:[],T=new Map(_.map(R=>[R.name,R])),w={kind:"dict",entries:{}};w.entries.is={kind:"value",value:v};for(const[R,O]of Object.entries(S)){if(R==="is")continue;const N=T.get(R);if(!N){const $=(0,t.closestMatch)(R,[...T.keys()]),V=$?`. Did you mean "${$}"?`:"";b.push(m(`${E}.${R}`,`unknown property "${R}" for connection type "${v}"${V}`));continue}const F=a(`${E}.${R}`,N,O,b);F!==void 0&&(w.entries[R]=F)}return w}function a(E,v,S,b){if(S==null)return;if(v.type==="json")return{kind:"value",value:S};const C=p(S);if(C!==void 0)return v.requireLiteralString?(b.push(m(E,"must be a literal string and cannot use an overlay reference")),{kind:"value",value:S}):C;const _=y(S,v.type);if(_){if(v.requireLiteralString)return b.push(m(E,`must be a literal string, got ${g(S)}`)),{kind:"value",value:S};b.push(m(E,`${_} (expected ${v.type})`));return}return{kind:"value",value:S}}function u(E,v){const S=p(E);if(S!==void 0)return S;if(typeof E!="string"){v.push(m("manifestPath",'"manifestPath" should be a string or an overlay reference'));return}return{kind:"value",value:E}}function c(E,v){const S=p(E);if(S!==void 0)return S;if(typeof E!="string"){v.push(m("givensPath",'"givensPath" should be a string or an overlay reference'));return}return{kind:"value",value:E}}function l(E,v){if(!Array.isArray(E)||!E.every(S=>typeof S=="string")){v.push(m("finalizeGivens",'"finalizeGivens" should be an array of given names'));return}return{kind:"value",value:E}}function f(E,v){return{kind:"value",value:E}}function d(E,v){return{kind:"value",value:E}}function p(E){if(typeof E!="object"||E===null||Array.isArray(E))return;const v=Object.keys(E);if(v.length!==1)return;const S=v[0],b=E[S];if(typeof b=="string")return{kind:"reference",source:S,path:[b]};if(Array.isArray(b)&&b.every(C=>typeof C=="string"))return{kind:"reference",source:S,path:b}}function x(E){return typeof E=="object"&&E!==null&&!Array.isArray(E)}function m(E,v){return{message:`${E}: ${v}`,severity:"warn",code:"config-validation"}}function g(E){return Array.isArray(E)?"array":typeof E}function y(E,v){switch(v){case"number":if(typeof E!="number")return`should be a number, got ${typeof E}`;break;case"boolean":if(typeof E!="boolean")return`should be a boolean, got ${typeof E}`;break;case"string":case"password":case"secret":case"file":case"text":if(typeof E!="string")return`should be a string, got ${typeof E}`;break}}return uw}var lw={},M1={},Pce;function Fk(){if(Pce)return M1;Pce=1;var e={};Object.defineProperty(M1,"__esModule",{value:!0}),M1.envOverlay=t,M1.contextOverlay=n,M1.defaultConfigOverlays=r,M1.isThenable=i;function t(){return typeof process>"u"||!e?()=>{}:s=>e[s[0]]}function n(s){return o=>s[o[0]]}function r(){return{env:t(),config:()=>{}}}function i(s){return typeof s=="object"&&s!==null&&"then"in s&&typeof s.then=="function"}return M1}var $ce;function s9e(){if($ce)return lw;$ce=1,Object.defineProperty(lw,"__esModule",{value:!0}),lw.prepareConfig=n;const e=HA(),t=Fk();function n(a,u,c){let l={},f,d,p,x,m=!1;for(const[g,y]of Object.entries(a.entries))switch(g){case"connections":{if(y.kind!=="dict")break;l=i(y);break}case"manifestPath":{f=o(y,u,c,"manifestPath");break}case"givensPath":{d=o(y,u,c,"givensPath");break}case"finalizeGivens":{y.kind==="value"&&r(y.value)&&(p=y.value);break}case"virtualMap":{y.kind==="value"&&(x=y.value);break}case"includeDefaultConnections":{y.kind==="value"&&typeof y.value=="boolean"&&(m=y.value);break}}return m&&s(l),{compiledConnections:l,manifestPath:f,givensPath:d,finalizeGivens:p,virtualMap:x}}function r(a){return Array.isArray(a)&&a.every(u=>typeof u=="string")}function i(a){const u={};for(const[c,l]of Object.entries(a.entries))l.kind==="dict"&&(u[c]=l);return u}function s(a){for(const u of(0,e.getRegisteredConnectionTypes)())a[u]||(a[u]={kind:"dict",entries:{is:{kind:"value",value:u}}})}function o(a,u,c,l){if(a.kind==="value")return typeof a.value=="string"?a.value:void 0;if(a.kind==="reference"){const f=u[a.source];if(!f){c.push({message:`unknown overlay source "${a.source}" for "${l}"`,severity:"warn",code:"config-overlay"});return}const d=f(a.path);if((0,t.isThenable)(d)){c.push({message:`the \`${a.source}\` overlay returned a Promise for "${l}"; top-level string settings must resolve synchronously`,severity:"warn",code:"config-overlay"});return}return typeof d=="string"?d:void 0}}return lw}var cw={},Bce;function o9e(){if(Bce)return cw;Bce=1,Object.defineProperty(cw,"__esModule",{value:!0}),cw.buildManagedLookup=t;const e=HA();function t(a,u,c){const l=Object.entries(a),f=l.length>0?l[0][0]:void 0,d=new Map;return{async lookupConnection(p){if(p===void 0&&(p=f),p===void 0)throw new Error("No connections defined in config");const x=d.get(p);if(x)return x;const m=a[p];if(!m)throw new Error(`No connection named "${p}" found in config`);const g=await n(m,u,c);if(typeof g.is!="string")throw new Error(`Connection "${p}" is missing a valid "is" field`);const y=(0,e.getConnectionTypeDef)(g.is);if(!y)throw new Error(`No registered connection type "${g.is}" for connection "${p}". Did you forget to import the connection package?`);const E={name:p};for(const[S,b]of Object.entries(g))S!=="is"&&b!=null&&(E[S]=b);(0,e.validateConnectionConfigProperties)(p,g.is,E);const v=await y.factory(E);return d.set(p,v),v},async close(){const p=[...d.values()];d.clear();for(const x of p)await x.close()},async idle(){for(const p of d.values())await p.idle()}}}async function n(a,u,c){const l=await r(a,u,c);if(!(0,e.isConnectionConfigEntry)(l))throw new Error("Connection entry did not resolve to a valid {is: string, ...} dict");return await s(l,u),l}async function r(a,u,c){switch(a.kind){case"value":return a.value;case"reference":return i(a,u,c);case"dict":{const l={};for(const[f,d]of Object.entries(a.entries)){const p=await r(d,u,c);p!==void 0&&(l[f]=p)}return l}}}async function i(a,u,c){const l=u[a.source];if(!l){c.push({message:`unknown overlay source "${a.source}" for reference path ${JSON.stringify(a.path)}`,severity:"warn",code:"config-overlay"});return}return await l(a.path)}async function s(a,u){var c;const l=a.is;if(typeof l!="string")return;const f=(c=(0,e.getConnectionProperties)(l))!==null&&c!==void 0?c:[];for(const d of f){if(d.default===void 0||a[d.name]!==void 0)continue;const p=await o(d.default,u);p!==void 0&&(a[d.name]=p)}}async function o(a,u){if(typeof a!="object")return a;const c=Object.keys(a);if(c.length!==1)return;const l=c[0],f=a[l],d=typeof f=="string"?[f]:f;if(!Array.isArray(d))return;const p=u[l];if(p)return await p(d)}return cw}var qce;function Lk(){if(qce)return fx;qce=1,Object.defineProperty(fx,"__esModule",{value:!0}),fx.MalloyConfig=fx.Manifest=void 0,fx.isBuildManifestEntry=E;const e=i9e(),t=s9e(),n=o9e(),r=Fk(),i=Dk();class s{constructor(){this._manifest={entries:{},strict:!1},this._touched=new Set}loadText(S){this._clearEntries(),this._touched.clear(),this._manifest.strict=!1,this._loadParsed(JSON.parse(S))}get buildManifest(){return this._manifest}get strict(){var S;return(S=this._manifest.strict)!==null&&S!==void 0?S:!1}set strict(S){this._manifest.strict=S}update(S,b){(0,i.requireCanonicalTablePathAnyDialect)(b.tableName,`Manifest entry '${S}'`),this._manifest.entries[S]=b,this._touched.add(S)}touch(S){this._touched.add(S)}get activeEntries(){const S={};for(const b of this._touched)this._manifest.entries[b]&&(S[b]=this._manifest.entries[b]);return{entries:S,strict:this._manifest.strict}}_clearEntries(){for(const S of Object.keys(this._manifest.entries))delete this._manifest.entries[S]}_loadParsed(S){typeof S.strict=="boolean"&&(this._manifest.strict=S.strict);const b=y(S.entries)?S.entries:S;for(const[C,_]of Object.entries(b))C==="strict"||!E(_)||((0,i.requireCanonicalTablePathAnyDialect)(_.tableName,`Manifest entry '${C}'`),this._manifest.entries[C]=_)}}fx.Manifest=s;class o{constructor(S,b){const C=[];let _;if(typeof S=="string")try{_=JSON.parse(S)}catch($){C.push({message:`Invalid JSON: ${$ instanceof Error?$.message:String($)}`,severity:"error",code:"config-validation"}),_={}}else _=S;const T=(0,e.compileConfig)(_);C.push(...T.log);const w=f(b,C),R=m(w.configURL,"configURL",C),O=w.rootDirectory,N={...(0,r.defaultConfigOverlays)(),...w.overlays,config:(0,r.contextOverlay)({configURL:R,rootDirectory:O})},F=(0,t.prepareConfig)(T.compiled,N,C);this._managedLookup=(0,n.buildManagedLookup)(F.compiledConnections,N,C),this._connections=this._managedLookup,this._overlays=N,this.virtualMap=g(F.virtualMap,C),this.configURL=R,this.rootDirectory=O,this.manifestPath=F.manifestPath,this.manifestURL=c(F.manifestPath,R),this.givensPath=F.givensPath,this.givensURL=l(F.givensPath,R,C),this.finalizeGivens=F.finalizeGivens,this.log=C}get connections(){return this._connections}wrapConnections(S){this._connections=S(this._connections)}async shutdown(S="close"){S==="idle"?await this._managedLookup.idle():await this._managedLookup.close()}async releaseConnections(){await this.shutdown("close")}async readOverlay(S,...b){var C,_;return await((_=(C=this._overlays)[S])===null||_===void 0?void 0:_.call(C,b))}}fx.MalloyConfig=o;const a="MANIFESTS",u="malloy-manifest.json";function c(v,S){if(!S)return;let b;try{b=new URL(S)}catch{return}const C=v??a;let _;try{_=new URL(C,b)}catch{return}const T=_.toString(),w=T.endsWith("/")?_:new URL(T+"/");return new URL(u,w).toString()}function l(v,S,b){if(!v)return;if(!S){b.push({message:"givensPath is set but no configURL is available; per-runtime givens will not be loaded. Pass `configURL` (or use an absolute URL such as `file:///...`).",severity:"warn",code:"config-overlay"});return}let C;try{C=new URL(S)}catch{return}try{return new URL(v,C).toString()}catch(_){const T=_ instanceof Error?_.message:String(_);b.push({message:`givensPath '${v}' could not be resolved against configURL '${S}': ${T}`,severity:"warn",code:"config-validation"});return}}function f(v,S){if(v===void 0)return{};if(d(v))return p(v,S);const b=v;if(b.overlays&&"config"in b.overlays){S.push({message:"`config` is reserved by MalloyConfig; pass `configURL` and `rootDirectory` directly instead. Supplied `overlays.config` ignored.",severity:"warn",code:"config-overlay"});const{config:C,..._}=b.overlays;return{...b,overlays:_}}return b}function d(v){for(const S of Object.values(v))if(typeof S=="function")return!0;return!1}function p(v,S){const b=v.config;if(!b)return{overlays:v};const C=x(b,"configURL",S),_=x(b,"rootDirectory",S),{config:T,...w}=v;return{configURL:C,rootDirectory:_,overlays:w}}function x(v,S,b){const C=v([S]);if((0,r.isThenable)(C)){b.push({message:`the legacy \`config\` overlay returned a Promise for \`${S}\`; top-level FS context must resolve synchronously. ${S} will be undefined.`,severity:"warn",code:"config-overlay"});return}return typeof C=="string"?C:void 0}function m(v,S,b){if(v!==void 0)try{return new URL(v),v}catch{b.push({message:`${S} must be a URL-shaped string (e.g. 'file:///path/to/...'), got '${v}'. In Node, use \`url.pathToFileURL(path).toString()\`.`,severity:"warn",code:"config-validation"});return}}function g(v,S){if(!y(v))return;const b=new Map;for(const[C,_]of Object.entries(v)){if(!y(_))continue;const T=new Map;for(const[w,R]of Object.entries(_)){if(typeof R!="string")continue;const O=(0,i.validateCanonicalTablePathAnyDialect)(R);if(O!==void 0){S.push({message:`virtualMap entry '${C}.${w}': ${O}`,severity:"error",code:"config-validation"});continue}T.set(w,R)}T.size>0&&b.set(C,T)}return b.size>0?b:void 0}function y(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function E(v){return y(v)&&typeof v.tableName=="string"}return fx}var k1={},VA={},Uce;function a9e(){return Uce||(Uce=1,Object.defineProperty(VA,"__esModule",{value:!0}),VA.MALLOY_VERSION=void 0,VA.MALLOY_VERSION="0.0.422"),VA}var jce;function zce(){if(jce)return k1;jce=1,Object.defineProperty(k1,"__esModule",{value:!0}),k1.Malloy=k1.MalloyError=void 0;const e=Ok(),t=HA(),n=Si(),r=T4(),i=a9e(),s=ow(),o=Oce(),a=Gp(),u=aw(),c=Lce();function l(x="loadModel"){return`internal://${x}/${(0,a.v4)()}`}function f(x){return[...Object.keys(x),...Object.values(x).map(f).flat()]}class d extends Error{constructor(m,g=[]){super(m),this.problems=g}}k1.MalloyError=d;class p{static get version(){return i.MALLOY_VERSION}static registerConnectionType(m,g){(0,t.registerConnectionType)(m,g)}static getConnectionProperties(m){return(0,t.getConnectionProperties)(m)}static getConnectionTypeDisplayName(m){return(0,t.getConnectionTypeDisplayName)(m)}static getRegisteredConnectionTypes(){return(0,t.getRegisteredConnectionTypes)()}static _parse(m,g,y,E,v){var S;g===void 0&&(g=new URL(l(E==null?void 0:E.method)));let b=g;E!=null&&E.importBaseURL&&(b=E==null?void 0:E.importBaseURL);const C=new e.MalloyTranslator(g.toString(),b.toString(),{urls:{[g.toString()]:m}},y,(S=E==null?void 0:E.restrictedMode)!==null&&S!==void 0?S:!1);return E!=null&&E.testEnvironment&&(C.allDialectsEnabled=!0),new o.Parse(C,v)}static parse({url:m,urlReader:g,source:y,eventStream:E,options:v}){if(y!==void 0)return p._parse(y,m,E,v);if(g===void 0)throw new Error("Internal Error: urlReader is required.");if(m===void 0)throw new Error("Internal Error: url is required if source not present.");return(0,s.readURL)(g,m).then(({contents:S,invalidationKey:b})=>p._parse(S,m,E,v,b))}static async compile(m){var g,y,E,v,S;let{url:b,source:C,importBaseURL:_,cacheManager:T}=m;const{parse:w,urlReader:R,connections:O,model:N,refreshSchemaCache:F,noThrowOnError:$,eventStream:V,restrictedMode:K,method:ne}=m;K&&(T=void 0);let le;if(F&&(le=typeof F=="number"?F:Date.now()),b===void 0&&C===void 0&&w===void 0)throw new Error("Internal Error: url, source, or parse required.");b===void 0&&(w!==void 0?b=new URL(w._translator.sourceURL):b=new URL(l(ne)));const z={};if(C===void 0&&T!==void 0){const fe=await T.getCachedModelDef(R,b.toString());if(fe)return new u.Model(fe.modelDef,[],[b.toString(),...f(fe.modelDef.dependencies)])}_??(_=b);let X;const se=b.toString();if(w!==void 0){if(K!==void 0&&w._translator.restrictedMode!==K)throw new Error(`Malloy.compile: restrictedMode (${K}) does not match the pre-parsed translator's restrictedMode (${w._translator.restrictedMode}). Set restrictedMode at parse time.`);X=w._translator;const fe=(g=w._invalidationKey)!==null&&g!==void 0?g:await(0,s.getInvalidationKey)(R,b);z[se]=fe}else{if(C===void 0){const{contents:fe,invalidationKey:I}=await(0,s.readURL)(R,b);z[se]=I,C=fe}else{const fe=await(0,s.getInvalidationKey)(R,b);z[se]=fe}X=new e.MalloyTranslator(se,_.toString(),{urls:{[se]:C}},V,K??!1)}for(;;){const fe=X.translate(N==null?void 0:N._modelDef);if(fe.final)if(fe.modelDef){await(T==null?void 0:T.setCachedModelDef(b.toString(),{modelDef:fe.modelDef,invalidationKeys:z}));for(const q of X.newlyTranslatedDependencies())await(T==null?void 0:T.setCachedModelDef(q.url,{modelDef:q.modelDef,invalidationKeys:z}));const I=!fe.modelWasModified&&N?N.getExistingQueryModel():void 0;return new u.Model(fe.modelDef,fe.problems||[],[...(y=N==null?void 0:N.fromSources)!==null&&y!==void 0?y:[],...(E=fe.fromSources)!==null&&E!==void 0?E:[]],I)}else if($){const I=(0,n.mkModelDef)("modelDidNotCompile"),q=(N==null?void 0:N._modelDef)||I;return new u.Model(q,fe.problems||[],[...(v=N==null?void 0:N.fromSources)!==null&&v!==void 0?v:[],...(S=fe.fromSources)!==null&&S!==void 0?S:[]])}else{const I=fe.problems||[],q=X.prettyErrors();throw new d(`Error(s) compiling model:
1371
1371
  ${q}`,I)}else{if(fe.urls)for(const I of fe.urls)try{if((0,s.isInternalURL)(I))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(T!==void 0){const B=await T.getCachedModelDef(R,I);if(B){for(const L in B.invalidationKeys)z[L]=B.invalidationKeys[L];X.update({translations:{[I]:B.modelDef}});continue}}const{contents:q,invalidationKey:j}=await(0,s.readURL)(R,new URL(I)),M={[I]:q};z[I]=j,X.update({urls:M})}catch(q){X.update({errors:{urls:{[I]:q.message}}})}if(fe.tables){const I=new Map;for(const q in fe.tables){const{connectionName:j,tablePath:M}=fe.tables[q],B=I.get(j);B===void 0?I.set(j,{[q]:M}):B[q]=M}for(const[q,j]of I)try{const M=await O.lookupConnection(q),{schemas:B,errors:L}=await p.safelyFetchTableSchema(M,j,{refreshTimestamp:le});X.update({tables:B,errors:{tables:L}})}catch(M){const B={},L={};for(const k in j)L[k]=M.toString();X.update({tables:B,errors:{tables:L}})}}if(fe.connectionDialects)for(const I in fe.connectionDialects){const{connectionName:q}=fe.connectionDialects[I];try{const j=await O.lookupConnection(q);X.update({connectionDialects:{[I]:j.dialectName}})}catch(j){X.update({errors:{connectionDialects:{[I]:j.toString()}}})}}if(fe.compileSQL){const I=fe.compileSQL,q=I.connection,j=(0,r.sqlKey)(I.connection,I.selectStr);try{const B=await(await O.lookupConnection(q)).fetchSchemaForSQLStruct(I,{refreshTimestamp:le});B.error&&X.update({errors:{compileSQL:{[j]:B.error}}}),B.structDef&&X.update({compileSQL:{[j]:B.structDef}})}catch(M){const B={};B[j]=M.toString(),X.update({errors:{compileSQL:B}})}}}}}static async safelyFetchTableSchema(m,g,y){const E=await m.fetchSchemaForTables(g,y);for(const v of Object.keys(g))if(E.schemas[v]===void 0&&E.errors[v]===void 0)throw new Error(`Schema fetch error for ${m.name}, no response for ${v} from ${m.dialectName}`);return E}static async run({connections:m,preparedResult:g,sqlStruct:y,connection:E,options:v}){if(!E){if(!m)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const S=(y==null?void 0:y.connection)||(g==null?void 0:g.connectionName);E=await m.lookupConnection(S)}if(y){const S=await E.runSQL(y.selectStr);return new c.Result({structs:[y],sql:y.selectStr,result:S.rows,totalRows:S.totalRows,runStats:S.runStats,lastStageName:y.name,malloy:"",connectionName:y.connection,sourceExplore:"",sourceFilters:[],profilingUrl:S.profilingUrl},(0,n.mkModelDef)("empty_model"))}else if(g){const S=await E.runSQL(g.sql,v);return new c.Result({...g._rawQuery,result:S.rows,totalRows:S.totalRows,runStats:S.runStats,profilingUrl:S.profilingUrl},g._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:m,preparedResult:g,sqlStruct:y,connection:E,options:v}){if(y===void 0&&g===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const S=(y==null?void 0:y.connection)||(g==null?void 0:g.connectionName);if(E===void 0){if(m===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");E=await m.lookupConnection(S)}if(!E.canStream())throw new Error(`Connection '${S}' cannot stream results.`);let b,C;if(y)C=new u.Explore((0,u.pseudoModelFor)(y),y),b=y.selectStr;else if(g!==void 0)C=g.resultExplore,b=g.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let _=0;for await(const T of E.runSQLStream(b,v))yield new c.DataRecord(T,_,C,void 0,void 0),_+=1}static async estimateQueryCost({connections:m,preparedResult:g,sqlStruct:y}){if(!m)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const E=(y==null?void 0:y.connection)||(g==null?void 0:g.connectionName),v=await m.lookupConnection(E);if(y)return await v.estimateQueryCost(y.selectStr);if(g)return await v.estimateQueryCost(g.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}return k1.Malloy=p,k1}var Hce;function u9e(){if(Hce)return ss;Hce=1,Object.defineProperty(ss,"__esModule",{value:!0}),ss.ExploreMaterializer=ss.PreparedResultMaterializer=ss.QueryMaterializer=ss.ModelMaterializer=ss.SingleConnectionRuntime=ss.ConnectionRuntime=ss.Runtime=void 0;const e=Si(),t=i0(),n=Dk(),r=Lk(),i=Vv(),s=ow(),o=aw(),a=zce();class u{constructor(S,b){this.runtime=S,this._materialize=b}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(S,b){return new p(this.runtime,S,b)}makeExploreMaterializer(S,b){return new m(this.runtime,S,b)}makePreparedResultMaterializer(S){return new x(this.runtime,S)}}class c{constructor({urlReader:S,connections:b,connection:C,config:_,buildManifest:T,eventStream:w,cacheManager:R,givens:O}){var N,F;if(this.isTestRuntime=!1,_!==void 0)this._config=_,b=b??_.connections;else if(b===void 0){if(C===void 0)throw new Error("A MalloyConfig, LookupConnection<Connection>, or Connection is required.");b={lookupConnection:()=>Promise.resolve(C)}}if(S===void 0&&(S=new s.EmptyURLReader),this._urlReader=S,this._connections=b,this._buildManifest=T,this._eventStream=w,this._cacheManager=R,O){for(const[$,V]of Object.entries(O))if(V===void 0)throw new Error(`Runtime givens.${$}: explicit undefined is not a valid value. Omit the key to defer to declaration default or the file layer; use null for an explicit null value.`)}this._constructorGivensMap=O?new Map(Object.entries(O)):new Map,this._finalizedGivensSet=new Set((F=(N=this._config)===null||N===void 0?void 0:N.finalizeGivens)!==null&&F!==void 0?F:[])}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}get _constructorGivens(){return this._constructorGivensMap}async getGivens(){const S=await this._resolveGivens(),b=new Map;if(S)for(const[C,_]of Object.entries(S))b.set(C,_);for(const[C,_]of this._constructorGivensMap)b.set(C,_);return b}get _finalizedGivens(){return this._finalizedGivensSet}set buildManifest(S){this._buildManifest=S,this._resolvedBuildManifestPromise=void 0}_resolveBuildManifest(){var S;if(this._buildManifest)return Promise.resolve(this._buildManifest);const b=(S=this._config)===null||S===void 0?void 0:S.manifestURL;return b?(this._resolvedBuildManifestPromise||(this._resolvedBuildManifestPromise=(async()=>{let C;try{const _=await this._urlReader.readURL(new URL(b));C=typeof _=="string"?_:_.contents}catch{return}try{const _=JSON.parse(C);if(!g(_))throw new Error('manifest is not an object with an "entries" map');for(const[T,w]of Object.entries(_.entries)){if(!(0,r.isBuildManifestEntry)(w))throw new Error(`Manifest entry '${T}' is missing a string tableName`);(0,n.requireCanonicalTablePathAnyDialect)(w.tableName,`Manifest entry '${T}'`)}return _}catch(_){const T=_ instanceof Error?_.message:String(_);return{entries:{},loadError:`Manifest file at ${b} could not be parsed: ${T}`}}})()),this._resolvedBuildManifestPromise):Promise.resolve(void 0)}_resolveGivens(){var S;const b=(S=this._config)===null||S===void 0?void 0:S.givensURL;return b?(this._resolvedGivensPromise||(this._resolvedGivensPromise=(async()=>{let C;try{const T=await this._urlReader.readURL(new URL(b));C=typeof T=="string"?T:T.contents}catch(T){const w=T instanceof Error?T.message:String(T);throw new Error(`givens: failed to read givens file at ${b}: ${w}`)}let _;try{_=JSON.parse(C)}catch(T){const w=T instanceof Error?T.message:String(T);throw new Error(`givens: failed to parse JSON at ${b}: ${w}`)}if(!y(_)){const T=Array.isArray(_)?"array":_===null?"null":typeof _;throw new Error(`givens: file at ${b} must be a JSON object of name → value pairs, got ${T}`)}return _})()),this._resolvedGivensPromise):Promise.resolve(void 0)}_invalidateGivensCache(){this._resolvedGivensPromise=void 0}get virtualMap(){var S,b;return(S=this._virtualMap)!==null&&S!==void 0?S:(b=this._config)===null||b===void 0?void 0:b.virtualMap}set virtualMap(S){this._virtualMap=S}async shutdown(S="close"){var b;await((b=this._config)===null||b===void 0?void 0:b.shutdown(S))}async releaseConnections(){await this.shutdown("close")}loadModel(S,b){const{refreshSchemaCache:C,noThrowOnError:_}=b||{};this.isTestRuntime&&(b===void 0?b={testEnvironment:!0}:b={...b,testEnvironment:!0});const T=S instanceof URL?{url:S}:{source:S};return new d(this,async()=>{const w=await a.Malloy.compile({...T,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:C,noThrowOnError:_,eventStream:this.eventStream,importBaseURL:b==null?void 0:b.importBaseURL,testEnvironment:b==null?void 0:b.testEnvironment,cacheManager:this.cacheManager});return this._withRuntimeContext(w)},b)}_withRuntimeContext(S){return this._finalizedGivensSet.size===0?S:new o.Model(S._modelDef,S.problems,S.fromSources,S.getExistingQueryModel(),{finalizedGivens:this._finalizedGivensSet})}_loadModelFromModelDef(S,b){return new d(this,async()=>new o.Model(S,[],[],void 0,this._finalizedGivensSet.size>0?{finalizedGivens:this._finalizedGivensSet}:void 0),b)}loadQuery(S,b){return this.loadModel(S,b).loadFinalQuery()}loadQueryByIndex(S,b,C){return this.loadModel(S,C).loadQueryByIndex(b,C)}loadQueryByName(S,b,C){return this.loadModel(S,C).loadQueryByName(b,C)}getModel(S,b){return this.loadModel(S,b).getModel()}getQuery(S,b){return this.loadQuery(S,b).getPreparedQuery()}getQueryByIndex(S,b,C){return this.loadQueryByIndex(S,b,C).getPreparedQuery()}getQueryByName(S,b,C){return this.loadQueryByName(S,b,C).getPreparedQuery()}}ss.Runtime=c;class l extends c{constructor({urlReader:S,connections:b}){super({connections:s.FixedConnectionMap.fromArray(b),urlReader:S}),this.rawConnections=b}}ss.ConnectionRuntime=l;class f extends c{constructor({urlReader:S,connection:b,eventStream:C,cacheManager:_}){super({urlReader:S,eventStream:C,cacheManager:_,connection:b}),this.connection=b}get supportsNesting(){return(0,t.getDialect)(this.connection.dialectName).supportsNesting}quote(S){return(0,t.getDialect)(this.connection.dialectName).sqlQuoteIdentifier(S)}get dialect(){return(0,t.getDialect)(this.connection.dialectName)}getQuoter(){return S=>this.quote(S.toString())}}ss.SingleConnectionRuntime=f;class d extends u{constructor(S,b,C){super(S,b),this.runtime=S,this.compileQueryOptions=C}loadFinalQuery(S){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...S})}loadQueryByIndex(S,b){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(S),{...this.compileQueryOptions,...b})}loadQueryByName(S,b){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(S),{...this.compileQueryOptions,...b})}loadQuery(S,b){const{refreshSchemaCache:C,noThrowOnError:_}=b||{};return this.makeQueryMaterializer(async()=>{const T=this.runtime.urlReader,w=this.runtime.connections;this.runtime.isTestRuntime&&(b===void 0?b={testEnvironment:!0}:b={...b,testEnvironment:!0});const R=S instanceof URL?{url:S}:{source:S},O=await this.getModel();return(await a.Malloy.compile({...R,urlReader:T,connections:w,model:O,refreshSchemaCache:C,noThrowOnError:_,importBaseURL:b==null?void 0:b.importBaseURL,testEnvironment:b==null?void 0:b.testEnvironment,...this.compileQueryOptions})).preparedQuery})}loadRestrictedQuery(S){return this.makeQueryMaterializer(async()=>{const b=this.runtime.urlReader,C=this.runtime.connections,_=this.runtime.isTestRuntime?!0:void 0,T=await this.getModel();return(await a.Malloy.compile({source:S,restrictedMode:!0,method:"query",urlReader:b,connections:C,model:T,testEnvironment:_,...this.compileQueryOptions})).preparedQuery})}extendModel(S,b){return this.runtime.isTestRuntime&&(b===void 0?b={testEnvironment:!0}:b={...b,testEnvironment:!0}),new d(this.runtime,async()=>{const C=this.runtime.urlReader,_=this.runtime.connections,T=S instanceof URL?{url:S}:{source:S},w=await this.getModel(),R=await a.Malloy.compile({...T,urlReader:C,connections:_,model:w,method:"extendModel",refreshSchemaCache:b==null?void 0:b.refreshSchemaCache,noThrowOnError:b==null?void 0:b.noThrowOnError,importBaseURL:b==null?void 0:b.importBaseURL,testEnvironment:b==null?void 0:b.testEnvironment,...this.compileQueryOptions});return this.runtime._withRuntimeContext(R)},b)}async search(S,b,C=1e3,_=void 0){const T=await this.materialize(),w=T.queryModel,R=T.getExploreByName(S).structDef;if(!(0,e.isSourceDef)(R))throw new Error("Source to be searched was unexpectedly, not a source");const O=R.connection,N=await this.runtime.connections.lookupConnection(O);return await w.searchIndex(N,S,b,C,_)}async searchValueMap(S,b=10,C){const T=(await this.materialize()).getExploreByName(S);if(!(0,e.isSourceDef)(T.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let w="{index: *}";T.getFieldByNameIfExists("search_index")&&(w="search_index");const R=`
1372
1372
  run: ${S}
1373
1373
  -> ${w}
@@ -4,10 +4,14 @@ build: {
4
4
  "src/**/*.tsx",
5
5
  "src/**/*.css",
6
6
  "vite.config.mts",
7
- "tsconfig.json"
7
+ "tsconfig.json",
8
+ "tsconfig.type-check.json"
8
9
  ]
9
10
  outputs = ["dist/module/index.mjs"]
10
11
  commands = [
12
+ # vite bundles the renderer but its dts pass only PRINTS type errors (exit 0).
13
+ # Run a real tsc first so a type error fails the build. See tsconfig.type-check.json.
14
+ "npx tsc -p tsconfig.type-check.json",
11
15
  "npx vite build --outDir 'dist/module' --config vite.config.mts"
12
16
  ]
13
17
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/render",
3
- "version": "0.0.421",
3
+ "version": "0.0.422",
4
4
  "license": "MIT",
5
5
  "main": "dist/module/index.umd.js",
6
6
  "types": "dist/module/index.d.ts",
@@ -31,8 +31,8 @@
31
31
  "generate-flow": "ts-node ../../scripts/gen-flow.ts"
32
32
  },
33
33
  "dependencies": {
34
- "@malloydata/malloy-interfaces": "0.0.421",
35
- "@malloydata/malloy-tag": "0.0.421",
34
+ "@malloydata/malloy-interfaces": "0.0.422",
35
+ "@malloydata/malloy-tag": "0.0.422",
36
36
  "@tanstack/solid-virtual": "^3.13.29",
37
37
  "lodash": "^4.18.1",
38
38
  "luxon": "^3.7.2",
@@ -44,8 +44,8 @@
44
44
  "vega-lite": "^5.2.0"
45
45
  },
46
46
  "devDependencies": {
47
- "@malloydata/db-duckdb": "0.0.421",
48
- "@malloydata/malloy": "0.0.421",
47
+ "@malloydata/db-duckdb": "0.0.422",
48
+ "@malloydata/malloy": "0.0.422",
49
49
  "@storybook/addon-essentials": "^8.6.18",
50
50
  "@storybook/addon-interactions": "^8.6.18",
51
51
  "@storybook/addon-links": "^8.6.15",