@malloydata/render 0.0.253 → 0.0.254-dev250401010409
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/module/index.mjs
CHANGED
|
@@ -149097,7 +149097,7 @@ Ap.malloyToQuery = Lxt;
|
|
|
149097
149097
|
var Fe = {}, uD = {};
|
|
149098
149098
|
Object.defineProperty(uD, "__esModule", { value: !0 });
|
|
149099
149099
|
uD.MALLOY_VERSION = void 0;
|
|
149100
|
-
uD.MALLOY_VERSION = "0.0.
|
|
149100
|
+
uD.MALLOY_VERSION = "0.0.254";
|
|
149101
149101
|
Object.defineProperty(Fe, "__esModule", { value: !0 });
|
|
149102
149102
|
Fe.InMemoryModelCache = Fe.CacheManager = Fe.CSVWriter = Fe.JSONWriter = Fe.DataWriter = Fe.DataRecord = Fe.DataArray = Fe.Result = Fe.ExploreMaterializer = Fe.PreparedResultMaterializer = Fe.QueryMaterializer = Fe.ModelMaterializer = Fe.SingleConnectionRuntime = Fe.ConnectionRuntime = Fe.Runtime = Fe.ExploreField = Fe.JoinRelationship = Fe.QueryField = Fe.Query = Fe.StringField = Fe.UnsupportedField = Fe.JSONField = Fe.BooleanField = Fe.NumberField = Fe.TimestampField = Fe.DateField = Fe.TimestampTimeframe = Fe.DateTimeframe = Fe.AtomicField = Fe.AtomicFieldType = Fe.Explore = Fe.SourceRelationship = Fe.FixedConnectionMap = Fe.InMemoryURLReader = Fe.EmptyURLReader = Fe.PreparedResult = Fe.DocumentCompletion = Fe.DocumentSymbol = Fe.DocumentPosition = Fe.DocumentRange = Fe.DocumentTablePath = Fe.Parse = Fe.PreparedQuery = Fe.Model = Fe.MalloyError = Fe.Malloy = void 0;
|
|
149103
149103
|
const tY = dT, Xr = ji, nY = Qy, A7 = h2, Ixt = uD, $xt = p2, In = ui, Bxt = $l, rY = "internal://internal.malloy";
|
package/dist/module/index.umd.js
CHANGED
|
@@ -1465,7 +1465,7 @@ wxxyyzz{{||}}}Ҩ
|
|
|
1465
1465
|
| ${c}`,a>0&&(s=s+`
|
|
1466
1466
|
| ${" ".repeat(a)}^`)}else s=`line ${u+1}: char ${a}: ${i.message}`}r!==o&&(s=`FILE: ${o}
|
|
1467
1467
|
`+s,r=o),e!==""?e=`${e}
|
|
1468
|
-
${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,Sft.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,PM.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,PM.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Rc.MalloyTranslation=UM;class Wfe extends UM{constructor(e,r){super(e),this.root=r}}Rc.MalloyChildTranslator=Wfe;class zft extends UM{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new MM.Zone,this.importZone=new MM.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new MM.Zone,this.root=this,this.logger=new Gfe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,Gfe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Rc.MalloyTranslator=zft;function Vfe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Vfe(t[e])).flat()]}var R2={};Object.defineProperty(R2,"__esModule",{value:!0}),R2.exploreQueryWalkerBuilder=R2.ExploreQueryWalker=void 0;const Gft=ac;class Yfe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}R2.ExploreQueryWalker=Yfe;function Wft(t,e){const r=new Yfe(t),i=r;return Gft.ParseTreeWalker.DEFAULT.walk(i,e),r}R2.exploreQueryWalkerBuilder=Wft;var D2={},pE={},Ia={};Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.getResultStructMetadataAnnotation=Ia.convertFieldInfos=Ia.modelDefToModelInfo=void 0;const n0=Pi,jM=Is,qM=ui,Kfe=eu;function Vft(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,n0.isSourceDef)(i)){const s={kind:"source",name:r,schema:{fields:O2(i,i.fields)}};e.entries.push(s)}else if(i.type==="query"){const s=(0,jM.getResultStructDefForQuery)(t,i),o=Jfe(i),u=s.resultMetadata?vR(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:O2(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,jM.getResultStructDefForQuery)(t,r),s=Jfe(r),o=i.resultMetadata?vR(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:O2(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ia.modelDefToModelInfo=Vft;function Jfe(t){return(0,qM.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function O2(t,e){var r,i,s;const o=[];for(const u of e){const l=(0,qM.annotationToTaglines)(u.annotation).map(f=>({value:f})),c=l.length>0?l:void 0;if((0,n0.isTurtle)(u)){const f=(0,jM.getResultStructDefForView)(t,u),x=f.resultMetadata?vR(f,f.resultMetadata):void 0,h=[...c??[],...x?[x]:[]],p={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:h.length>0?h:void 0,schema:{fields:O2(f,f.fields)}};o.push(p)}else if((0,n0.isAtomic)(u)){const f=(0,n0.expressionIsAggregate)(u.expressionType),x=(0,n0.expressionIsScalar)(u.expressionType);if(!f&&!x||u.type==="error")continue;const h=u.resultMetadata?Xfe(u,u.resultMetadata):void 0,p=[...c??[],...h?[h]:[]],m={kind:f?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:HM(u),annotations:p.length>0?p:void 0};o.push(m)}else if((0,n0.isJoinedSource)(u)){const f={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:c,schema:{fields:O2(u,u.fields)},relationship:u.join};o.push(f)}}return o}Ia.convertFieldInfos=O2;function Xfe(t,e){const r=Kfe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Kft(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Yft(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Kft(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Yft(t)}\``}function vR(t,e){var r,i;const s=Kfe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ia.getResultStructMetadataAnnotation=vR;function HM(t){if((0,n0.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Jft(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Xft(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,n0.isRepeatedRecord)(t))return{kind:"array_type",element_type:Zfe(t)};if(t.type==="record")return Zfe(t);if(t.type==="array")return{kind:"array_type",element_type:HM(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Zfe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Xfe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,qM.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,n0.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:HM(e)};throw new Error("Expected record type to not have a table as its child")})}}function Jft(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Xft(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function pht(t){return t}function mht(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=eu,r=ui,i=Ia,s=by;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),y=m.schemas[p];if(y===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(y,y.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(g,E){if(g===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(g).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof g=="number")return{kind:"boolean_cell",boolean_value:g!==0};if(typeof g!="boolean")throw new Error(`Invalid boolean ${g}`);return{kind:"boolean_cell",boolean_value:g}}else if(E.type.kind==="number_type"){if(typeof g!="number")throw new Error(`Invalid number ${g}`);return{kind:"number_cell",number_value:g}}else if(E.type.kind==="string_type"){if(typeof g!="string")throw new Error(`Invalid string ${g}`);return{kind:"string_cell",string_value:g}}else if(E.type.kind==="array_type"){if(!Array.isArray(g))throw new Error(`Invalid array ${g}`);return{kind:"array_cell",array_value:g.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(g)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(g)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(g)}`);return m(g,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(g,E){const A=[];for(const _ of E.schema.fields){const v=g[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const y={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(g=>m(g,y))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},y=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),g=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return g&&y.push(g),y.push(...p.resultMetadata?[]:[]),x.sourceExplore&&y.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),y.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:y.length>0?y:void 0,query_timezone:x.data.field.queryTimezone}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,y,g,E;return{severity:p.severity,message:p.message,range:(y=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&y!==void 0?y:t.DEFAULT_LOG_RANGE,url:(E=(g=p.at)===null||g===void 0?void 0:g.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(pE);var Zft=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),ext=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),txt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zft(e,t,r);return ext(e,t),e};Object.defineProperty(D2,"__esModule",{value:!0}),D2.malloyToQuery=D2.MalloyToQuery=void 0;const nxt=Jh,On=txt(w),exe=Kp,mE=$n,rxt=Xe,ixt=uE,txe=Vn,sxt=pE,QM="Malloy query documents";class nxe extends nxt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,txe.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,exe.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${QM}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${QM} may only have one run statement`);return i===void 0?(this.illegal(e,`${QM} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,mE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof On.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof On.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof On.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof On.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof On.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof On.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof On.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof On.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof On.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof On.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof On.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof On.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof On.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,mE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof On.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,mE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof On.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof On.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement())this.notAllowed(e,"Having statements");else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,mE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,rxt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,mE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof On.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof On.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof On.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getWhereExpr(e){if(e instanceof On.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof On.ExprFieldPathContext&&i instanceof On.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof On.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getWhereExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}D2.MalloyToQuery=nxe;function oxt(t){const e=(0,txe.getSourceInfo)(t),r=new exe.BaseMessageLogger(null),i="internal://query.malloy",s=(0,ixt.runMalloyParser)(t,i,e,r),u=new nxe(s,r).visit(s.root),a=(0,sxt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}D2.malloyToQuery=oxt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Rc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=R2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=D2;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Q4);var Fe={},CR={};Object.defineProperty(CR,"__esModule",{value:!0}),CR.MALLOY_VERSION=void 0,CR.MALLOY_VERSION="0.0.253",Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.InMemoryModelCache=Fe.CacheManager=Fe.CSVWriter=Fe.JSONWriter=Fe.DataWriter=Fe.DataRecord=Fe.DataArray=Fe.Result=Fe.ExploreMaterializer=Fe.PreparedResultMaterializer=Fe.QueryMaterializer=Fe.ModelMaterializer=Fe.SingleConnectionRuntime=Fe.ConnectionRuntime=Fe.Runtime=Fe.ExploreField=Fe.JoinRelationship=Fe.QueryField=Fe.Query=Fe.StringField=Fe.UnsupportedField=Fe.JSONField=Fe.BooleanField=Fe.NumberField=Fe.TimestampField=Fe.DateField=Fe.TimestampTimeframe=Fe.DateTimeframe=Fe.AtomicField=Fe.AtomicFieldType=Fe.Explore=Fe.SourceRelationship=Fe.FixedConnectionMap=Fe.InMemoryURLReader=Fe.EmptyURLReader=Fe.PreparedResult=Fe.DocumentCompletion=Fe.DocumentSymbol=Fe.DocumentPosition=Fe.DocumentRange=Fe.DocumentTablePath=Fe.Parse=Fe.PreparedQuery=Fe.Model=Fe.MalloyError=Fe.Malloy=void 0;const rxe=Q4,li=Pi,ixe=by,zM=Mp,uxt=CR,axt=Up,Bn=ui,lxt=Yl,sxe="internal://internal.malloy";let r0=class ED{static get version(){return uxt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(sxe));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new rxe.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new uxe(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return ED._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return NR(r,e).then(({contents:u,invalidationKey:a})=>ED._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,y,g;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(sxe));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new F2(C.modelDef,[],[e.toString(),...wR(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await iP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:b}=await NR(s,e);A[v]=b,r=C}else{const C=await iP(s,e);A[v]=C}_=new rxe.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const b of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:A}));return new F2(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]],b=>_.referenceAt(b),b=>_.importAt(b))}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},S=(u==null?void 0:u._modelDef)||b;return new F2(S,C.problems||[],[...(y=u==null?void 0:u.fromSources)!==null&&y!==void 0?y:[],...(g=C.fromSources)!==null&&g!==void 0?g:[]],R=>_.referenceAt(R),R=>_.importAt(R))}else{const b=C.problems||[],S=_.prettyErrors();throw new oxe(`Error(s) compiling model:
|
|
1468
|
+
${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,Sft.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,PM.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,PM.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Rc.MalloyTranslation=UM;class Wfe extends UM{constructor(e,r){super(e),this.root=r}}Rc.MalloyChildTranslator=Wfe;class zft extends UM{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new MM.Zone,this.importZone=new MM.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new MM.Zone,this.root=this,this.logger=new Gfe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,Gfe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Rc.MalloyTranslator=zft;function Vfe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Vfe(t[e])).flat()]}var R2={};Object.defineProperty(R2,"__esModule",{value:!0}),R2.exploreQueryWalkerBuilder=R2.ExploreQueryWalker=void 0;const Gft=ac;class Yfe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}R2.ExploreQueryWalker=Yfe;function Wft(t,e){const r=new Yfe(t),i=r;return Gft.ParseTreeWalker.DEFAULT.walk(i,e),r}R2.exploreQueryWalkerBuilder=Wft;var D2={},pE={},Ia={};Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.getResultStructMetadataAnnotation=Ia.convertFieldInfos=Ia.modelDefToModelInfo=void 0;const n0=Pi,jM=Is,qM=ui,Kfe=eu;function Vft(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,n0.isSourceDef)(i)){const s={kind:"source",name:r,schema:{fields:O2(i,i.fields)}};e.entries.push(s)}else if(i.type==="query"){const s=(0,jM.getResultStructDefForQuery)(t,i),o=Jfe(i),u=s.resultMetadata?vR(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:O2(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,jM.getResultStructDefForQuery)(t,r),s=Jfe(r),o=i.resultMetadata?vR(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:O2(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ia.modelDefToModelInfo=Vft;function Jfe(t){return(0,qM.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function O2(t,e){var r,i,s;const o=[];for(const u of e){const l=(0,qM.annotationToTaglines)(u.annotation).map(f=>({value:f})),c=l.length>0?l:void 0;if((0,n0.isTurtle)(u)){const f=(0,jM.getResultStructDefForView)(t,u),x=f.resultMetadata?vR(f,f.resultMetadata):void 0,h=[...c??[],...x?[x]:[]],p={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:h.length>0?h:void 0,schema:{fields:O2(f,f.fields)}};o.push(p)}else if((0,n0.isAtomic)(u)){const f=(0,n0.expressionIsAggregate)(u.expressionType),x=(0,n0.expressionIsScalar)(u.expressionType);if(!f&&!x||u.type==="error")continue;const h=u.resultMetadata?Xfe(u,u.resultMetadata):void 0,p=[...c??[],...h?[h]:[]],m={kind:f?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:HM(u),annotations:p.length>0?p:void 0};o.push(m)}else if((0,n0.isJoinedSource)(u)){const f={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:c,schema:{fields:O2(u,u.fields)},relationship:u.join};o.push(f)}}return o}Ia.convertFieldInfos=O2;function Xfe(t,e){const r=Kfe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Kft(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Yft(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Kft(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Yft(t)}\``}function vR(t,e){var r,i;const s=Kfe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ia.getResultStructMetadataAnnotation=vR;function HM(t){if((0,n0.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Jft(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Xft(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,n0.isRepeatedRecord)(t))return{kind:"array_type",element_type:Zfe(t)};if(t.type==="record")return Zfe(t);if(t.type==="array")return{kind:"array_type",element_type:HM(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Zfe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Xfe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,qM.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,n0.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:HM(e)};throw new Error("Expected record type to not have a table as its child")})}}function Jft(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Xft(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function pht(t){return t}function mht(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=eu,r=ui,i=Ia,s=by;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),y=m.schemas[p];if(y===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(y,y.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(g,E){if(g===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(g).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof g=="number")return{kind:"boolean_cell",boolean_value:g!==0};if(typeof g!="boolean")throw new Error(`Invalid boolean ${g}`);return{kind:"boolean_cell",boolean_value:g}}else if(E.type.kind==="number_type"){if(typeof g!="number")throw new Error(`Invalid number ${g}`);return{kind:"number_cell",number_value:g}}else if(E.type.kind==="string_type"){if(typeof g!="string")throw new Error(`Invalid string ${g}`);return{kind:"string_cell",string_value:g}}else if(E.type.kind==="array_type"){if(!Array.isArray(g))throw new Error(`Invalid array ${g}`);return{kind:"array_cell",array_value:g.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(g)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(g)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(g)}`);return m(g,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(g,E){const A=[];for(const _ of E.schema.fields){const v=g[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const y={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(g=>m(g,y))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},y=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),g=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return g&&y.push(g),y.push(...p.resultMetadata?[]:[]),x.sourceExplore&&y.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),y.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:y.length>0?y:void 0,query_timezone:x.data.field.queryTimezone}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,y,g,E;return{severity:p.severity,message:p.message,range:(y=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&y!==void 0?y:t.DEFAULT_LOG_RANGE,url:(E=(g=p.at)===null||g===void 0?void 0:g.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(pE);var Zft=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),ext=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),txt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zft(e,t,r);return ext(e,t),e};Object.defineProperty(D2,"__esModule",{value:!0}),D2.malloyToQuery=D2.MalloyToQuery=void 0;const nxt=Jh,On=txt(w),exe=Kp,mE=$n,rxt=Xe,ixt=uE,txe=Vn,sxt=pE,QM="Malloy query documents";class nxe extends nxt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,txe.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,exe.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${QM}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${QM} may only have one run statement`);return i===void 0?(this.illegal(e,`${QM} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,mE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof On.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof On.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof On.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof On.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof On.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof On.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof On.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof On.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof On.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof On.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof On.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof On.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof On.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,mE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof On.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,mE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof On.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof On.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement())this.notAllowed(e,"Having statements");else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,mE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,rxt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,mE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof On.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof On.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof On.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getWhereExpr(e){if(e instanceof On.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof On.ExprFieldPathContext&&i instanceof On.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof On.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getWhereExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}D2.MalloyToQuery=nxe;function oxt(t){const e=(0,txe.getSourceInfo)(t),r=new exe.BaseMessageLogger(null),i="internal://query.malloy",s=(0,ixt.runMalloyParser)(t,i,e,r),u=new nxe(s,r).visit(s.root),a=(0,sxt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}D2.malloyToQuery=oxt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Rc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=R2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=D2;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Q4);var Fe={},CR={};Object.defineProperty(CR,"__esModule",{value:!0}),CR.MALLOY_VERSION=void 0,CR.MALLOY_VERSION="0.0.254",Object.defineProperty(Fe,"__esModule",{value:!0}),Fe.InMemoryModelCache=Fe.CacheManager=Fe.CSVWriter=Fe.JSONWriter=Fe.DataWriter=Fe.DataRecord=Fe.DataArray=Fe.Result=Fe.ExploreMaterializer=Fe.PreparedResultMaterializer=Fe.QueryMaterializer=Fe.ModelMaterializer=Fe.SingleConnectionRuntime=Fe.ConnectionRuntime=Fe.Runtime=Fe.ExploreField=Fe.JoinRelationship=Fe.QueryField=Fe.Query=Fe.StringField=Fe.UnsupportedField=Fe.JSONField=Fe.BooleanField=Fe.NumberField=Fe.TimestampField=Fe.DateField=Fe.TimestampTimeframe=Fe.DateTimeframe=Fe.AtomicField=Fe.AtomicFieldType=Fe.Explore=Fe.SourceRelationship=Fe.FixedConnectionMap=Fe.InMemoryURLReader=Fe.EmptyURLReader=Fe.PreparedResult=Fe.DocumentCompletion=Fe.DocumentSymbol=Fe.DocumentPosition=Fe.DocumentRange=Fe.DocumentTablePath=Fe.Parse=Fe.PreparedQuery=Fe.Model=Fe.MalloyError=Fe.Malloy=void 0;const rxe=Q4,li=Pi,ixe=by,zM=Mp,uxt=CR,axt=Up,Bn=ui,lxt=Yl,sxe="internal://internal.malloy";let r0=class ED{static get version(){return uxt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(sxe));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new rxe.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new uxe(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return ED._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return NR(r,e).then(({contents:u,invalidationKey:a})=>ED._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,y,g;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(sxe));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new F2(C.modelDef,[],[e.toString(),...wR(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await iP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:b}=await NR(s,e);A[v]=b,r=C}else{const C=await iP(s,e);A[v]=C}_=new rxe.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const b of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:A}));return new F2(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]],b=>_.referenceAt(b),b=>_.importAt(b))}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},S=(u==null?void 0:u._modelDef)||b;return new F2(S,C.problems||[],[...(y=u==null?void 0:u.fromSources)!==null&&y!==void 0?y:[],...(g=C.fromSources)!==null&&g!==void 0?g:[]],R=>_.referenceAt(R),R=>_.importAt(R))}else{const b=C.problems||[],S=_.prettyErrors();throw new oxe(`Error(s) compiling model:
|
|
1469
1469
|
${S}`,b)}else{if(C.urls)for(const S of C.urls)try{if(LR(S))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(x!==void 0){const D=await x.getCachedModelDef(s,S);if(D){for(const B in D.invalidationKeys)A[B]=D.invalidationKeys[B];_.update({translations:{[S]:D.modelDef}});continue}}const{contents:R,invalidationKey:O}=await NR(s,new URL(S)),$={[S]:R};A[S]=O,_.update({urls:$})}catch(R){_.update({errors:{urls:{[S]:R.message}}})}const{modelAnnotation:b}=_.modelAnnotation(u==null?void 0:u._modelDef);if(C.tables){const S=new Map;for(const R in C.tables){const{connectionName:O,tablePath:$}=C.tables[R],D=S.get(O);D===void 0?S.set(O,{[R]:$}):D[R]=$}for(const[R,O]of S)try{const $=await o.lookupConnection(R),{schemas:D,errors:B}=await ED.safelyFetchTableSchema($,O,{refreshTimestamp:E,modelAnnotation:b});_.update({tables:D,errors:{tables:B}})}catch($){const D={},B={};for(const q in O)B[q]=$.toString();_.update({tables:D,errors:{tables:B}})}}if(C.compileSQL){const S=C.compileSQL,R=S.connection,O=(0,lxt.sqlKey)(S.connection,S.selectStr);try{const D=await(await o.lookupConnection(R)).fetchSchemaForSQLStruct(S,{refreshTimestamp:E,modelAnnotation:b});D.error&&_.update({errors:{compileSQL:{[O]:D.error}}}),D.structDef&&_.update({compileSQL:{[O]:D.structDef}})}catch($){const D={};D[O]=$.toString(),_.update({errors:{compileSQL:D}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new EE({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new EE({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new Us(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new dd(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};Fe.Malloy=r0;class oxe extends Error{constructor(e,r=[]){super(e),this.problems=r}}Fe.MalloyError=oxe;class F2{constructor(e,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return(0,Bn.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,Bn.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new w2(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new w2(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new w2(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if((0,li.isSourceDef)(r))return new Us(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(li.isSourceDef).map(e=>new Us(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}Fe.Model=F2;class w2{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,Bn.annotationToTag)(this._modelDef.annotation).tag;return e=(0,Bn.addModelScope)(e,r),(0,Bn.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,Bn.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new li.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new gE({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,li.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}Fe.PreparedQuery=w2;class uxe{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new SR(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new axe(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new lxe(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}Fe.Parse=uxe;class axe{constructor(e){this._range=N2.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}Fe.DocumentTablePath=axe;class N2{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new N2(new GM(e.start.line,e.start.character),new GM(e.end.line,e.end.character))}}Fe.DocumentRange=N2;class GM{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Fe.DocumentPosition=GM;class SR{constructor(e){this._range=N2.fromJSON(e.range),this._lensRange=e.lensRange?N2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new SR(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}Fe.DocumentSymbol=SR;class lxe{constructor(e){this.type=e.type,this.text=e.text}}Fe.DocumentCompletion=lxe;class gE{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new gE(e,r)}tagParse(e){const r=(0,Bn.annotationToTag)(this.modelDef.annotation).tag;return e=(0,Bn.addModelScope)(e,r),(0,Bn.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,Bn.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,Bn.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new Us(r,this.sourceExplore)}catch{return new Us(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,li.isSourceDef)(r))return new Us(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Fe.PreparedResult=gE;class cxe{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}Fe.EmptyURLReader=cxe;class cxt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return LR(e.toString())?null:bxe(r)}}Fe.InMemoryURLReader=cxt;class bR{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new bR(new Map(e.map(r=>[r.name,r])))}}Fe.FixedConnectionMap=bR;var fxe;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(fxe||(Fe.SourceRelationship=fxe={}));class WM{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Us}isQuery(){return this instanceof eP}}class Us extends WM{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,li.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,Bn.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,Bn.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,Bn.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i={type:"query",structRef:r,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new w2(i,this.modelDef,[],e)}get modelDef(){if(!(0,li.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new F2(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,li.isJoined)(i))return[s,new tP(i,this,o)];if(i.type==="turtle")return[s,new eP(i,this,o)];if(i.type==="string")return[s,new ZM(i,this,o)];if(i.type==="number")return[s,new TR(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new TR({...i,type:"number"},this,o)]:[s,new VM(i,this,o)];if(i.type==="timestamp")return[s,new YM(i,this,o)];if(i.type==="boolean")return[s,new KM(i,this,o)];if(i.type==="json")return[s,new JM(i,this,o)];if(i.type==="sql native")return[s,new XM(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(u=>{if(typeof u.field=="string")return{field:this.fieldMap.get(u.field),dir:u.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(u=>u.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(u=>!o.has(u.name)).map(u=>({field:u,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof tP}get filters(){var e;return(0,li.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,li.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?Us.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?Us.fromJSON(e.sourceExplore):void 0;return new Us(e._structDef,r,i)}get location(){return this.structDef.location}}Fe.Explore=Us;var $a;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})($a||(Fe.AtomicFieldType=$a={}));class Wc extends WM{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return $a.String;case"boolean":return $a.Boolean;case"date":return $a.Date;case"timestamp":return $a.Timestamp;case"number":return $a.Number;case"json":return $a.Json;case"sql native":return $a.NativeUnsupported;case"error":return $a.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,Bn.addModelScope)(e,this.parent.modelTag),(0,Bn.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,Bn.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,li.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,li.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof ZM}isNumber(){return this instanceof TR}isDate(){return this instanceof VM}isBoolean(){return this instanceof KM}isJSON(){return this instanceof JM}isTimestamp(){return this instanceof YM}isUnsupported(){return this instanceof XM}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Fe.AtomicField=Wc;var xd;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(xd||(Fe.DateTimeframe=xd={}));var Ba;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(Ba||(Fe.TimestampTimeframe=Ba={}));class VM extends Wc{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return xd.Day;case"week":return xd.Week;case"month":return xd.Month;case"quarter":return xd.Quarter;case"year":return xd.Year}}}Fe.DateField=VM;class YM extends Wc{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Ba.Day;case"week":return Ba.Week;case"month":return Ba.Month;case"quarter":return Ba.Quarter;case"year":return Ba.Year;case"second":return Ba.Second;case"hour":return Ba.Hour;case"minute":return Ba.Minute}}}Fe.TimestampField=YM;class TR extends Wc{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}}Fe.NumberField=TR;class KM extends Wc{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}}Fe.BooleanField=KM;class JM extends Wc{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}}Fe.JSONField=JM;class XM extends Wc{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Fe.UnsupportedField=XM;class ZM extends Wc{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}}Fe.StringField=ZM;class xxe extends WM{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Fe.Query=xxe;class eP extends xxe{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,Bn.addModelScope)(e,this.parent.modelTag),(0,Bn.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,Bn.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}Fe.QueryField=eP;var L2;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(L2||(Fe.JoinRelationship=L2={}));class tP extends Us{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,li.isJoined)(this.structDef))switch(this.structDef.join){case"one":return L2.OneToOne;case"many":case"cross":return L2.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===L2.OneToOne}get isArray(){return this.joinRelationship!==L2.OneToOne}tagParse(e){return e=(0,Bn.addModelScope)(e,this._parentExplore.modelTag),(0,Bn.annotationToTag)(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}Fe.ExploreField=tP;class nP{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new cxe),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new yE(this,async()=>r0.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new yE(this,async()=>new F2(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}Fe.Runtime=nP;class fxt extends nP{constructor({urlReader:e,connections:r}){super({connections:bR.fromArray(r),urlReader:e}),this.rawConnections=r}}Fe.ConnectionRuntime=fxt;class xxt extends nP{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,zM.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,zM.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,zM.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Fe.SingleConnectionRuntime=xxt;class RR{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new dxe(this.runtime,e,r)}makeExploreMaterializer(e,r){return new pxe(this.runtime,e,r)}makePreparedResultMaterializer(e){return new hxe(this.runtime,e)}}class yE extends RR{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await r0.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new yE(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await r0.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new li.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,li.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,li.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
|
|
1470
1470
|
run: ${e}
|
|
1471
1471
|
-> ${u}
|
|
@@ -152909,7 +152909,7 @@ Xp.malloyToQuery = Rpt;
|
|
|
152909
152909
|
var Le = {}, ID = {};
|
|
152910
152910
|
Object.defineProperty(ID, "__esModule", { value: !0 });
|
|
152911
152911
|
ID.MALLOY_VERSION = void 0;
|
|
152912
|
-
ID.MALLOY_VERSION = "0.0.
|
|
152912
|
+
ID.MALLOY_VERSION = "0.0.254";
|
|
152913
152913
|
Object.defineProperty(Le, "__esModule", { value: !0 });
|
|
152914
152914
|
Le.InMemoryModelCache = Le.CacheManager = Le.CSVWriter = Le.JSONWriter = Le.DataWriter = Le.DataRecord = Le.DataArray = Le.Result = Le.ExploreMaterializer = Le.PreparedResultMaterializer = Le.QueryMaterializer = Le.ModelMaterializer = Le.SingleConnectionRuntime = Le.ConnectionRuntime = Le.Runtime = Le.ExploreField = Le.JoinRelationship = Le.QueryField = Le.Query = Le.StringField = Le.UnsupportedField = Le.JSONField = Le.BooleanField = Le.NumberField = Le.TimestampField = Le.DateField = Le.TimestampTimeframe = Le.DateTimeframe = Le.AtomicField = Le.AtomicFieldType = Le.Explore = Le.SourceRelationship = Le.FixedConnectionMap = Le.InMemoryURLReader = Le.EmptyURLReader = Le.PreparedResult = Le.DocumentCompletion = Le.DocumentSymbol = Le.DocumentPosition = Le.DocumentRange = Le.DocumentTablePath = Le.Parse = Le.PreparedQuery = Le.Model = Le.MalloyError = Le.Malloy = void 0;
|
|
152915
152915
|
const NY = UT, si = Yi, LY = Wr, X7 = G2, Dpt = ID, Opt = V2, Mn = pi, wpt = n0, IY = "internal://internal.malloy";
|
|
@@ -1860,7 +1860,7 @@ wxxyyzz{{||}}}Ҩ
|
|
|
1860
1860
|
| ${c}`,a>0&&(s=s+`
|
|
1861
1861
|
| ${" ".repeat(a)}^`)}else s=`line ${u+1}: char ${a}: ${i.message}`}r!==o&&(s=`FILE: ${o}
|
|
1862
1862
|
`+s,r=o),e!==""?e=`${e}
|
|
1863
|
-
${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,mht.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,sP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,sP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Gc.MalloyTranslation=oP;class Vxe extends oP{constructor(e,r){super(e),this.root=r}}Gc.MalloyChildTranslator=Vxe;class kht extends oP{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new iP.Zone,this.importZone=new iP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new iP.Zone,this.root=this,this.logger=new Gxe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,Gxe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Gc.MalloyTranslator=kht;function Yxe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Yxe(t[e])).flat()]}var i1={};Object.defineProperty(i1,"__esModule",{value:!0}),i1.exploreQueryWalkerBuilder=i1.ExploreQueryWalker=void 0;const Mht=R0;class Kxe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}i1.ExploreQueryWalker=Kxe;function Pht(t,e){const r=new Kxe(t),i=r;return Mht.ParseTreeWalker.DEFAULT.walk(i,e),r}i1.exploreQueryWalkerBuilder=Pht;var s1={},YE={},Ya={};Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.getResultStructMetadataAnnotation=Ya.convertFieldInfos=Ya.modelDefToModelInfo=void 0;const S0=Gi,uP=qs,aP=mi,Jxe=Bo;function Uht(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,S0.isSourceDef)(i)){const s={kind:"source",name:r,schema:{fields:o1(i,i.fields)}};e.entries.push(s)}else if(i.type==="query"){const s=(0,uP.getResultStructDefForQuery)(t,i),o=Xxe(i),u=s.resultMetadata?ED(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:o1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,uP.getResultStructDefForQuery)(t,r),s=Xxe(r),o=i.resultMetadata?ED(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:o1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ya.modelDefToModelInfo=Uht;function Xxe(t){return(0,aP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function o1(t,e){var r,i,s;const o=[];for(const u of e){const l=(0,aP.annotationToTaglines)(u.annotation).map(f=>({value:f})),c=l.length>0?l:void 0;if((0,S0.isTurtle)(u)){const f=(0,uP.getResultStructDefForView)(t,u),x=f.resultMetadata?ED(f,f.resultMetadata):void 0,h=[...c??[],...x?[x]:[]],p={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:h.length>0?h:void 0,schema:{fields:o1(f,f.fields)}};o.push(p)}else if((0,S0.isAtomic)(u)){const f=(0,S0.expressionIsAggregate)(u.expressionType),x=(0,S0.expressionIsScalar)(u.expressionType);if(!f&&!x||u.type==="error")continue;const h=u.resultMetadata?Zxe(u,u.resultMetadata):void 0,p=[...c??[],...h?[h]:[]],m={kind:f?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:lP(u),annotations:p.length>0?p:void 0};o.push(m)}else if((0,S0.isJoinedSource)(u)){const f={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:c,schema:{fields:o1(u,u.fields)},relationship:u.join};o.push(f)}}return o}Ya.convertFieldInfos=o1;function Zxe(t,e){const r=Jxe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:qht(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function jht(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function qht(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${jht(t)}\``}function ED(t,e){var r,i;const s=Jxe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ya.getResultStructMetadataAnnotation=ED;function lP(t){if((0,S0.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Hht(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:zht(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,S0.isRepeatedRecord)(t))return{kind:"array_type",element_type:ede(t)};if(t.type==="record")return ede(t);if(t.type==="array")return{kind:"array_type",element_type:lP(t.elementTypeDef)}}throw new Error("Unexpected field type")}function ede(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Zxe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,aP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,S0.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:lP(e)};throw new Error("Expected record type to not have a table as its child")})}}function Hht(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function zht(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function a1t(t){return t}function l1t(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=Bo,r=mi,i=Ya,s=qr;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),y=m.schemas[p];if(y===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(y,y.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(g,E){if(g===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(g).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof g=="number")return{kind:"boolean_cell",boolean_value:g!==0};if(typeof g!="boolean")throw new Error(`Invalid boolean ${g}`);return{kind:"boolean_cell",boolean_value:g}}else if(E.type.kind==="number_type"){if(typeof g!="number")throw new Error(`Invalid number ${g}`);return{kind:"number_cell",number_value:g}}else if(E.type.kind==="string_type"){if(typeof g!="string")throw new Error(`Invalid string ${g}`);return{kind:"string_cell",string_value:g}}else if(E.type.kind==="array_type"){if(!Array.isArray(g))throw new Error(`Invalid array ${g}`);return{kind:"array_cell",array_value:g.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(g)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(g)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(g)}`);return m(g,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(g,E){const A=[];for(const _ of E.schema.fields){const v=g[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const y={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(g=>m(g,y))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},y=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),g=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return g&&y.push(g),y.push(...p.resultMetadata?[]:[]),x.sourceExplore&&y.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),y.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:y.length>0?y:void 0,query_timezone:x.data.field.queryTimezone}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,y,g,E;return{severity:p.severity,message:p.message,range:(y=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&y!==void 0?y:t.DEFAULT_LOG_RANGE,url:(E=(g=p.at)===null||g===void 0?void 0:g.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(YE);var Qht=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Wht=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ght=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Qht(e,t,r);return Wht(e,t),e};Object.defineProperty(s1,"__esModule",{value:!0}),s1.malloyToQuery=s1.MalloyToQuery=void 0;const Vht=Hd,Ln=Ght(I),tde=R2,KE=Pn,Yht=et,Kht=jE,nde=Jn,Jht=YE,cP="Malloy query documents";class rde extends Vht.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,nde.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,tde.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${cP}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${cP} may only have one run statement`);return i===void 0?(this.illegal(e,`${cP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,KE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Ln.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Ln.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Ln.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Ln.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Ln.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Ln.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Ln.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Ln.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Ln.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Ln.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Ln.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Ln.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Ln.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,KE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Ln.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,KE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Ln.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Ln.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement())this.notAllowed(e,"Having statements");else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,KE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,Yht.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,KE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Ln.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Ln.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Ln.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getWhereExpr(e){if(e instanceof Ln.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Ln.ExprFieldPathContext&&i instanceof Ln.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Ln.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getWhereExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}s1.MalloyToQuery=rde;function Xht(t){const e=(0,nde.getSourceInfo)(t),r=new tde.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Kht.runMalloyParser)(t,i,e,r),u=new rde(s,r).visit(s.root),a=(0,Jht.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}s1.malloyToQuery=Xht,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Gc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=i1;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=s1;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(U4);var Le={},AD={};Object.defineProperty(AD,"__esModule",{value:!0}),AD.MALLOY_VERSION=void 0,AD.MALLOY_VERSION="0.0.253",Object.defineProperty(Le,"__esModule",{value:!0}),Le.InMemoryModelCache=Le.CacheManager=Le.CSVWriter=Le.JSONWriter=Le.DataWriter=Le.DataRecord=Le.DataArray=Le.Result=Le.ExploreMaterializer=Le.PreparedResultMaterializer=Le.QueryMaterializer=Le.ModelMaterializer=Le.SingleConnectionRuntime=Le.ConnectionRuntime=Le.Runtime=Le.ExploreField=Le.JoinRelationship=Le.QueryField=Le.Query=Le.StringField=Le.UnsupportedField=Le.JSONField=Le.BooleanField=Le.NumberField=Le.TimestampField=Le.DateField=Le.TimestampTimeframe=Le.DateTimeframe=Le.AtomicField=Le.AtomicFieldType=Le.Explore=Le.SourceRelationship=Le.FixedConnectionMap=Le.InMemoryURLReader=Le.EmptyURLReader=Le.PreparedResult=Le.DocumentCompletion=Le.DocumentSymbol=Le.DocumentPosition=Le.DocumentRange=Le.DocumentTablePath=Le.Parse=Le.PreparedQuery=Le.Model=Le.MalloyError=Le.Malloy=void 0;const ide=U4,yi=Gi,sde=qr,fP=p2,Zht=AD,ept=g2,Un=mi,tpt=g0,ode="internal://internal.malloy";let b0=class GD{static get version(){return Zht.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(ode));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new ide.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new ade(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return GD._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return DD(r,e).then(({contents:u,invalidationKey:a})=>GD._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,y,g;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(ode));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new u1(C.modelDef,[],[e.toString(),...RD(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await SP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:S}=await DD(s,e);A[v]=S,r=C}else{const C=await SP(s,e);A[v]=C}_=new ide.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const S of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(S.url,{modelDef:S.modelDef,invalidationKeys:A}));return new u1(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]],S=>_.referenceAt(S),S=>_.importAt(S))}else if(l){const S={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},b=(u==null?void 0:u._modelDef)||S;return new u1(b,C.problems||[],[...(y=u==null?void 0:u.fromSources)!==null&&y!==void 0?y:[],...(g=C.fromSources)!==null&&g!==void 0?g:[]],R=>_.referenceAt(R),R=>_.importAt(R))}else{const S=C.problems||[],b=_.prettyErrors();throw new ude(`Error(s) compiling model:
|
|
1863
|
+
${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,mht.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,sP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,sP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Gc.MalloyTranslation=oP;class Vxe extends oP{constructor(e,r){super(e),this.root=r}}Gc.MalloyChildTranslator=Vxe;class kht extends oP{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new iP.Zone,this.importZone=new iP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new iP.Zone,this.root=this,this.logger=new Gxe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,Gxe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Gc.MalloyTranslator=kht;function Yxe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Yxe(t[e])).flat()]}var i1={};Object.defineProperty(i1,"__esModule",{value:!0}),i1.exploreQueryWalkerBuilder=i1.ExploreQueryWalker=void 0;const Mht=R0;class Kxe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}i1.ExploreQueryWalker=Kxe;function Pht(t,e){const r=new Kxe(t),i=r;return Mht.ParseTreeWalker.DEFAULT.walk(i,e),r}i1.exploreQueryWalkerBuilder=Pht;var s1={},YE={},Ya={};Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.getResultStructMetadataAnnotation=Ya.convertFieldInfos=Ya.modelDefToModelInfo=void 0;const S0=Gi,uP=qs,aP=mi,Jxe=Bo;function Uht(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,S0.isSourceDef)(i)){const s={kind:"source",name:r,schema:{fields:o1(i,i.fields)}};e.entries.push(s)}else if(i.type==="query"){const s=(0,uP.getResultStructDefForQuery)(t,i),o=Xxe(i),u=s.resultMetadata?ED(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:o1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,uP.getResultStructDefForQuery)(t,r),s=Xxe(r),o=i.resultMetadata?ED(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:o1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ya.modelDefToModelInfo=Uht;function Xxe(t){return(0,aP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function o1(t,e){var r,i,s;const o=[];for(const u of e){const l=(0,aP.annotationToTaglines)(u.annotation).map(f=>({value:f})),c=l.length>0?l:void 0;if((0,S0.isTurtle)(u)){const f=(0,uP.getResultStructDefForView)(t,u),x=f.resultMetadata?ED(f,f.resultMetadata):void 0,h=[...c??[],...x?[x]:[]],p={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:h.length>0?h:void 0,schema:{fields:o1(f,f.fields)}};o.push(p)}else if((0,S0.isAtomic)(u)){const f=(0,S0.expressionIsAggregate)(u.expressionType),x=(0,S0.expressionIsScalar)(u.expressionType);if(!f&&!x||u.type==="error")continue;const h=u.resultMetadata?Zxe(u,u.resultMetadata):void 0,p=[...c??[],...h?[h]:[]],m={kind:f?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:lP(u),annotations:p.length>0?p:void 0};o.push(m)}else if((0,S0.isJoinedSource)(u)){const f={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:c,schema:{fields:o1(u,u.fields)},relationship:u.join};o.push(f)}}return o}Ya.convertFieldInfos=o1;function Zxe(t,e){const r=Jxe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:qht(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function jht(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function qht(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${jht(t)}\``}function ED(t,e){var r,i;const s=Jxe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ya.getResultStructMetadataAnnotation=ED;function lP(t){if((0,S0.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Hht(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:zht(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,S0.isRepeatedRecord)(t))return{kind:"array_type",element_type:ede(t)};if(t.type==="record")return ede(t);if(t.type==="array")return{kind:"array_type",element_type:lP(t.elementTypeDef)}}throw new Error("Unexpected field type")}function ede(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Zxe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,aP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,S0.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:lP(e)};throw new Error("Expected record type to not have a table as its child")})}}function Hht(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function zht(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function a1t(t){return t}function l1t(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=Bo,r=mi,i=Ya,s=qr;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),y=m.schemas[p];if(y===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(y,y.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(g,E){if(g===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(g).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof g=="number")return{kind:"boolean_cell",boolean_value:g!==0};if(typeof g!="boolean")throw new Error(`Invalid boolean ${g}`);return{kind:"boolean_cell",boolean_value:g}}else if(E.type.kind==="number_type"){if(typeof g!="number")throw new Error(`Invalid number ${g}`);return{kind:"number_cell",number_value:g}}else if(E.type.kind==="string_type"){if(typeof g!="string")throw new Error(`Invalid string ${g}`);return{kind:"string_cell",string_value:g}}else if(E.type.kind==="array_type"){if(!Array.isArray(g))throw new Error(`Invalid array ${g}`);return{kind:"array_cell",array_value:g.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(g)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(g)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(g)}`);return m(g,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(g,E){const A=[];for(const _ of E.schema.fields){const v=g[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const y={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(g=>m(g,y))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},y=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),g=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return g&&y.push(g),y.push(...p.resultMetadata?[]:[]),x.sourceExplore&&y.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),y.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:y.length>0?y:void 0,query_timezone:x.data.field.queryTimezone}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,y,g,E;return{severity:p.severity,message:p.message,range:(y=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&y!==void 0?y:t.DEFAULT_LOG_RANGE,url:(E=(g=p.at)===null||g===void 0?void 0:g.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(YE);var Qht=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Wht=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ght=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Qht(e,t,r);return Wht(e,t),e};Object.defineProperty(s1,"__esModule",{value:!0}),s1.malloyToQuery=s1.MalloyToQuery=void 0;const Vht=Hd,Ln=Ght(I),tde=R2,KE=Pn,Yht=et,Kht=jE,nde=Jn,Jht=YE,cP="Malloy query documents";class rde extends Vht.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,nde.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,tde.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${cP}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${cP} may only have one run statement`);return i===void 0?(this.illegal(e,`${cP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,KE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Ln.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Ln.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Ln.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Ln.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Ln.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Ln.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Ln.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Ln.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Ln.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Ln.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Ln.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Ln.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Ln.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,KE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Ln.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,KE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Ln.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Ln.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement())this.notAllowed(e,"Having statements");else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,KE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,Yht.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,KE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Ln.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Ln.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Ln.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getWhereExpr(e){if(e instanceof Ln.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Ln.ExprFieldPathContext&&i instanceof Ln.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Ln.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getWhereExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}s1.MalloyToQuery=rde;function Xht(t){const e=(0,nde.getSourceInfo)(t),r=new tde.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Kht.runMalloyParser)(t,i,e,r),u=new rde(s,r).visit(s.root),a=(0,Jht.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}s1.malloyToQuery=Xht,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Gc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=i1;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=s1;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(U4);var Le={},AD={};Object.defineProperty(AD,"__esModule",{value:!0}),AD.MALLOY_VERSION=void 0,AD.MALLOY_VERSION="0.0.254",Object.defineProperty(Le,"__esModule",{value:!0}),Le.InMemoryModelCache=Le.CacheManager=Le.CSVWriter=Le.JSONWriter=Le.DataWriter=Le.DataRecord=Le.DataArray=Le.Result=Le.ExploreMaterializer=Le.PreparedResultMaterializer=Le.QueryMaterializer=Le.ModelMaterializer=Le.SingleConnectionRuntime=Le.ConnectionRuntime=Le.Runtime=Le.ExploreField=Le.JoinRelationship=Le.QueryField=Le.Query=Le.StringField=Le.UnsupportedField=Le.JSONField=Le.BooleanField=Le.NumberField=Le.TimestampField=Le.DateField=Le.TimestampTimeframe=Le.DateTimeframe=Le.AtomicField=Le.AtomicFieldType=Le.Explore=Le.SourceRelationship=Le.FixedConnectionMap=Le.InMemoryURLReader=Le.EmptyURLReader=Le.PreparedResult=Le.DocumentCompletion=Le.DocumentSymbol=Le.DocumentPosition=Le.DocumentRange=Le.DocumentTablePath=Le.Parse=Le.PreparedQuery=Le.Model=Le.MalloyError=Le.Malloy=void 0;const ide=U4,yi=Gi,sde=qr,fP=p2,Zht=AD,ept=g2,Un=mi,tpt=g0,ode="internal://internal.malloy";let b0=class GD{static get version(){return Zht.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(ode));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new ide.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new ade(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return GD._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return DD(r,e).then(({contents:u,invalidationKey:a})=>GD._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,y,g;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(ode));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new u1(C.modelDef,[],[e.toString(),...RD(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await SP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:S}=await DD(s,e);A[v]=S,r=C}else{const C=await SP(s,e);A[v]=C}_=new ide.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const S of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(S.url,{modelDef:S.modelDef,invalidationKeys:A}));return new u1(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]],S=>_.referenceAt(S),S=>_.importAt(S))}else if(l){const S={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},b=(u==null?void 0:u._modelDef)||S;return new u1(b,C.problems||[],[...(y=u==null?void 0:u.fromSources)!==null&&y!==void 0?y:[],...(g=C.fromSources)!==null&&g!==void 0?g:[]],R=>_.referenceAt(R),R=>_.importAt(R))}else{const S=C.problems||[],b=_.prettyErrors();throw new ude(`Error(s) compiling model:
|
|
1864
1864
|
${b}`,S)}else{if(C.urls)for(const b of C.urls)try{if(OD(b))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(x!==void 0){const D=await x.getCachedModelDef(s,b);if(D){for(const $ in D.invalidationKeys)A[$]=D.invalidationKeys[$];_.update({translations:{[b]:D.modelDef}});continue}}const{contents:R,invalidationKey:O}=await DD(s,new URL(b)),B={[b]:R};A[b]=O,_.update({urls:B})}catch(R){_.update({errors:{urls:{[b]:R.message}}})}const{modelAnnotation:S}=_.modelAnnotation(u==null?void 0:u._modelDef);if(C.tables){const b=new Map;for(const R in C.tables){const{connectionName:O,tablePath:B}=C.tables[R],D=b.get(O);D===void 0?b.set(O,{[R]:B}):D[R]=B}for(const[R,O]of b)try{const B=await o.lookupConnection(R),{schemas:D,errors:$}=await GD.safelyFetchTableSchema(B,O,{refreshTimestamp:E,modelAnnotation:S});_.update({tables:D,errors:{tables:$}})}catch(B){const D={},$={};for(const U in O)$[U]=B.toString();_.update({tables:D,errors:{tables:$}})}}if(C.compileSQL){const b=C.compileSQL,R=b.connection,O=(0,tpt.sqlKey)(b.connection,b.selectStr);try{const D=await(await o.lookupConnection(R)).fetchSchemaForSQLStruct(b,{refreshTimestamp:E,modelAnnotation:S});D.error&&_.update({errors:{compileSQL:{[O]:D.error}}}),D.structDef&&_.update({compileSQL:{[O]:D.structDef}})}catch(B){const D={};D[O]=B.toString(),_.update({errors:{compileSQL:D}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new ZE({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new ZE({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new Vs(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new Md(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};Le.Malloy=b0;class ude extends Error{constructor(e,r=[]){super(e),this.problems=r}}Le.MalloyError=ude;class u1{constructor(e,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return(0,Un.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new a1(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new a1(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new a1(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if((0,yi.isSourceDef)(r))return new Vs(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(yi.isSourceDef).map(e=>new Vs(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}Le.Model=u1;class a1{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,Un.annotationToTag)(this._modelDef.annotation).tag;return e=(0,Un.addModelScope)(e,r),(0,Un.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new yi.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new JE({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,yi.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}Le.PreparedQuery=a1;class ade{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new _D(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new lde(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new cde(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}Le.Parse=ade;class lde{constructor(e){this._range=l1.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}Le.DocumentTablePath=lde;class l1{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new l1(new xP(e.start.line,e.start.character),new xP(e.end.line,e.end.character))}}Le.DocumentRange=l1;class xP{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Le.DocumentPosition=xP;class _D{constructor(e){this._range=l1.fromJSON(e.range),this._lensRange=e.lensRange?l1.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new _D(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}Le.DocumentSymbol=_D;class cde{constructor(e){this.type=e.type,this.text=e.text}}Le.DocumentCompletion=cde;class JE{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new JE(e,r)}tagParse(e){const r=(0,Un.annotationToTag)(this.modelDef.annotation).tag;return e=(0,Un.addModelScope)(e,r),(0,Un.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,Un.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new Vs(r,this.sourceExplore)}catch{return new Vs(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,yi.isSourceDef)(r))return new Vs(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Le.PreparedResult=JE;class fde{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}Le.EmptyURLReader=fde;class npt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return OD(e.toString())?null:Tde(r)}}Le.InMemoryURLReader=npt;class vD{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new vD(new Map(e.map(r=>[r.name,r])))}}Le.FixedConnectionMap=vD;var xde;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(xde||(Le.SourceRelationship=xde={}));class dP{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Vs}isQuery(){return this instanceof AP}}class Vs extends dP{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,yi.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,Un.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,Un.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i={type:"query",structRef:r,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new a1(i,this.modelDef,[],e)}get modelDef(){if(!(0,yi.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new u1(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,yi.isJoined)(i))return[s,new _P(i,this,o)];if(i.type==="turtle")return[s,new AP(i,this,o)];if(i.type==="string")return[s,new EP(i,this,o)];if(i.type==="number")return[s,new CD(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new CD({...i,type:"number"},this,o)]:[s,new hP(i,this,o)];if(i.type==="timestamp")return[s,new pP(i,this,o)];if(i.type==="boolean")return[s,new mP(i,this,o)];if(i.type==="json")return[s,new gP(i,this,o)];if(i.type==="sql native")return[s,new yP(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(u=>{if(typeof u.field=="string")return{field:this.fieldMap.get(u.field),dir:u.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(u=>u.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(u=>!o.has(u.name)).map(u=>({field:u,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof _P}get filters(){var e;return(0,yi.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,yi.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?Vs.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?Vs.fromJSON(e.sourceExplore):void 0;return new Vs(e._structDef,r,i)}get location(){return this.structDef.location}}Le.Explore=Vs;var Ka;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(Ka||(Le.AtomicFieldType=Ka={}));class hf extends dP{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return Ka.String;case"boolean":return Ka.Boolean;case"date":return Ka.Date;case"timestamp":return Ka.Timestamp;case"number":return Ka.Number;case"json":return Ka.Json;case"sql native":return Ka.NativeUnsupported;case"error":return Ka.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,Un.addModelScope)(e,this.parent.modelTag),(0,Un.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,yi.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,yi.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof EP}isNumber(){return this instanceof CD}isDate(){return this instanceof hP}isBoolean(){return this instanceof mP}isJSON(){return this instanceof gP}isTimestamp(){return this instanceof pP}isUnsupported(){return this instanceof yP}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Le.AtomicField=hf;var kd;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(kd||(Le.DateTimeframe=kd={}));var Ja;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(Ja||(Le.TimestampTimeframe=Ja={}));class hP extends hf{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return kd.Day;case"week":return kd.Week;case"month":return kd.Month;case"quarter":return kd.Quarter;case"year":return kd.Year}}}Le.DateField=hP;class pP extends hf{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Ja.Day;case"week":return Ja.Week;case"month":return Ja.Month;case"quarter":return Ja.Quarter;case"year":return Ja.Year;case"second":return Ja.Second;case"hour":return Ja.Hour;case"minute":return Ja.Minute}}}Le.TimestampField=pP;class CD extends hf{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}}Le.NumberField=CD;class mP extends hf{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}}Le.BooleanField=mP;class gP extends hf{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}}Le.JSONField=gP;class yP extends hf{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Le.UnsupportedField=yP;class EP extends hf{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}}Le.StringField=EP;class dde extends dP{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Le.Query=dde;class AP extends dde{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,Un.addModelScope)(e,this.parent.modelTag),(0,Un.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}Le.QueryField=AP;var c1;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(c1||(Le.JoinRelationship=c1={}));class _P extends Vs{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,yi.isJoined)(this.structDef))switch(this.structDef.join){case"one":return c1.OneToOne;case"many":case"cross":return c1.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===c1.OneToOne}get isArray(){return this.joinRelationship!==c1.OneToOne}tagParse(e){return e=(0,Un.addModelScope)(e,this._parentExplore.modelTag),(0,Un.annotationToTag)(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}Le.ExploreField=_P;class vP{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new fde),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new XE(this,async()=>b0.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new XE(this,async()=>new u1(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}Le.Runtime=vP;class rpt extends vP{constructor({urlReader:e,connections:r}){super({connections:vD.fromArray(r),urlReader:e}),this.rawConnections=r}}Le.ConnectionRuntime=rpt;class ipt extends vP{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,fP.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,fP.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,fP.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Le.SingleConnectionRuntime=ipt;class SD{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new hde(this.runtime,e,r)}makeExploreMaterializer(e,r){return new mde(this.runtime,e,r)}makePreparedResultMaterializer(e){return new pde(this.runtime,e)}}class XE extends SD{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await b0.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new XE(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await b0.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new yi.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,yi.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,yi.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
|
|
1865
1865
|
run: ${e}
|
|
1866
1866
|
-> ${u}
|
|
@@ -152909,7 +152909,7 @@ Xp.malloyToQuery = Rpt;
|
|
|
152909
152909
|
var Le = {}, ID = {};
|
|
152910
152910
|
Object.defineProperty(ID, "__esModule", { value: !0 });
|
|
152911
152911
|
ID.MALLOY_VERSION = void 0;
|
|
152912
|
-
ID.MALLOY_VERSION = "0.0.
|
|
152912
|
+
ID.MALLOY_VERSION = "0.0.254";
|
|
152913
152913
|
Object.defineProperty(Le, "__esModule", { value: !0 });
|
|
152914
152914
|
Le.InMemoryModelCache = Le.CacheManager = Le.CSVWriter = Le.JSONWriter = Le.DataWriter = Le.DataRecord = Le.DataArray = Le.Result = Le.ExploreMaterializer = Le.PreparedResultMaterializer = Le.QueryMaterializer = Le.ModelMaterializer = Le.SingleConnectionRuntime = Le.ConnectionRuntime = Le.Runtime = Le.ExploreField = Le.JoinRelationship = Le.QueryField = Le.Query = Le.StringField = Le.UnsupportedField = Le.JSONField = Le.BooleanField = Le.NumberField = Le.TimestampField = Le.DateField = Le.TimestampTimeframe = Le.DateTimeframe = Le.AtomicField = Le.AtomicFieldType = Le.Explore = Le.SourceRelationship = Le.FixedConnectionMap = Le.InMemoryURLReader = Le.EmptyURLReader = Le.PreparedResult = Le.DocumentCompletion = Le.DocumentSymbol = Le.DocumentPosition = Le.DocumentRange = Le.DocumentTablePath = Le.Parse = Le.PreparedQuery = Le.Model = Le.MalloyError = Le.Malloy = void 0;
|
|
152915
152915
|
const NY = UT, si = Yi, LY = Wr, X7 = G2, Dpt = ID, Opt = V2, Mn = pi, wpt = n0, IY = "internal://internal.malloy";
|
|
@@ -1860,7 +1860,7 @@ wxxyyzz{{||}}}Ҩ
|
|
|
1860
1860
|
| ${c}`,a>0&&(s=s+`
|
|
1861
1861
|
| ${" ".repeat(a)}^`)}else s=`line ${u+1}: char ${a}: ${i.message}`}r!==o&&(s=`FILE: ${o}
|
|
1862
1862
|
`+s,r=o),e!==""?e=`${e}
|
|
1863
|
-
${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,mht.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,iP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,iP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Gc.MalloyTranslation=sP;class Gxe extends sP{constructor(e,r){super(e),this.root=r}}Gc.MalloyChildTranslator=Gxe;class kht extends sP{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new rP.Zone,this.importZone=new rP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new rP.Zone,this.root=this,this.logger=new Wxe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,Wxe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Gc.MalloyTranslator=kht;function Vxe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Vxe(t[e])).flat()]}var i1={};Object.defineProperty(i1,"__esModule",{value:!0}),i1.exploreQueryWalkerBuilder=i1.ExploreQueryWalker=void 0;const Mht=R0;class Yxe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}i1.ExploreQueryWalker=Yxe;function Pht(t,e){const r=new Yxe(t),i=r;return Mht.ParseTreeWalker.DEFAULT.walk(i,e),r}i1.exploreQueryWalkerBuilder=Pht;var s1={},GE={},Ya={};Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.getResultStructMetadataAnnotation=Ya.convertFieldInfos=Ya.modelDefToModelInfo=void 0;const S0=Gi,oP=qs,uP=mi,Kxe=Bo;function Uht(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,S0.isSourceDef)(i)){const s={kind:"source",name:r,schema:{fields:o1(i,i.fields)}};e.entries.push(s)}else if(i.type==="query"){const s=(0,oP.getResultStructDefForQuery)(t,i),o=Jxe(i),u=s.resultMetadata?yD(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:o1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,oP.getResultStructDefForQuery)(t,r),s=Jxe(r),o=i.resultMetadata?yD(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:o1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ya.modelDefToModelInfo=Uht;function Jxe(t){return(0,uP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function o1(t,e){var r,i,s;const o=[];for(const u of e){const l=(0,uP.annotationToTaglines)(u.annotation).map(f=>({value:f})),c=l.length>0?l:void 0;if((0,S0.isTurtle)(u)){const f=(0,oP.getResultStructDefForView)(t,u),x=f.resultMetadata?yD(f,f.resultMetadata):void 0,h=[...c??[],...x?[x]:[]],p={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:h.length>0?h:void 0,schema:{fields:o1(f,f.fields)}};o.push(p)}else if((0,S0.isAtomic)(u)){const f=(0,S0.expressionIsAggregate)(u.expressionType),x=(0,S0.expressionIsScalar)(u.expressionType);if(!f&&!x||u.type==="error")continue;const h=u.resultMetadata?Xxe(u,u.resultMetadata):void 0,p=[...c??[],...h?[h]:[]],m={kind:f?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:aP(u),annotations:p.length>0?p:void 0};o.push(m)}else if((0,S0.isJoinedSource)(u)){const f={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:c,schema:{fields:o1(u,u.fields)},relationship:u.join};o.push(f)}}return o}Ya.convertFieldInfos=o1;function Xxe(t,e){const r=Kxe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:qht(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function jht(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function qht(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${jht(t)}\``}function yD(t,e){var r,i;const s=Kxe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ya.getResultStructMetadataAnnotation=yD;function aP(t){if((0,S0.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Hht(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:zht(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,S0.isRepeatedRecord)(t))return{kind:"array_type",element_type:Zxe(t)};if(t.type==="record")return Zxe(t);if(t.type==="array")return{kind:"array_type",element_type:aP(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Zxe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Xxe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,uP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,S0.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:aP(e)};throw new Error("Expected record type to not have a table as its child")})}}function Hht(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function zht(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function a1t(t){return t}function l1t(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=Bo,r=mi,i=Ya,s=qr;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),y=m.schemas[p];if(y===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(y,y.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(g,E){if(g===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(g).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof g=="number")return{kind:"boolean_cell",boolean_value:g!==0};if(typeof g!="boolean")throw new Error(`Invalid boolean ${g}`);return{kind:"boolean_cell",boolean_value:g}}else if(E.type.kind==="number_type"){if(typeof g!="number")throw new Error(`Invalid number ${g}`);return{kind:"number_cell",number_value:g}}else if(E.type.kind==="string_type"){if(typeof g!="string")throw new Error(`Invalid string ${g}`);return{kind:"string_cell",string_value:g}}else if(E.type.kind==="array_type"){if(!Array.isArray(g))throw new Error(`Invalid array ${g}`);return{kind:"array_cell",array_value:g.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(g)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(g)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(g)}`);return m(g,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(g,E){const A=[];for(const _ of E.schema.fields){const v=g[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const y={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(g=>m(g,y))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},y=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),g=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return g&&y.push(g),y.push(...p.resultMetadata?[]:[]),x.sourceExplore&&y.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),y.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:y.length>0?y:void 0,query_timezone:x.data.field.queryTimezone}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,y,g,E;return{severity:p.severity,message:p.message,range:(y=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&y!==void 0?y:t.DEFAULT_LOG_RANGE,url:(E=(g=p.at)===null||g===void 0?void 0:g.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(GE);var Qht=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Wht=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ght=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Qht(e,t,r);return Wht(e,t),e};Object.defineProperty(s1,"__esModule",{value:!0}),s1.malloyToQuery=s1.MalloyToQuery=void 0;const Vht=Hd,Ln=Ght(I),ede=R2,VE=Pn,Yht=et,Kht=PE,tde=Jn,Jht=GE,lP="Malloy query documents";class nde extends Vht.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,tde.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,ede.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${lP}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${lP} may only have one run statement`);return i===void 0?(this.illegal(e,`${lP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,VE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Ln.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Ln.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Ln.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Ln.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Ln.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Ln.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Ln.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Ln.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Ln.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Ln.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Ln.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Ln.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Ln.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,VE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Ln.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,VE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Ln.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Ln.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement())this.notAllowed(e,"Having statements");else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,VE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,Yht.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,VE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Ln.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Ln.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Ln.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getWhereExpr(e){if(e instanceof Ln.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Ln.ExprFieldPathContext&&i instanceof Ln.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Ln.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getWhereExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}s1.MalloyToQuery=nde;function Xht(t){const e=(0,tde.getSourceInfo)(t),r=new ede.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Kht.runMalloyParser)(t,i,e,r),u=new nde(s,r).visit(s.root),a=(0,Jht.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}s1.malloyToQuery=Xht,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Gc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=i1;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=s1;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(P4);var Le={},ED={};Object.defineProperty(ED,"__esModule",{value:!0}),ED.MALLOY_VERSION=void 0,ED.MALLOY_VERSION="0.0.253",Object.defineProperty(Le,"__esModule",{value:!0}),Le.InMemoryModelCache=Le.CacheManager=Le.CSVWriter=Le.JSONWriter=Le.DataWriter=Le.DataRecord=Le.DataArray=Le.Result=Le.ExploreMaterializer=Le.PreparedResultMaterializer=Le.QueryMaterializer=Le.ModelMaterializer=Le.SingleConnectionRuntime=Le.ConnectionRuntime=Le.Runtime=Le.ExploreField=Le.JoinRelationship=Le.QueryField=Le.Query=Le.StringField=Le.UnsupportedField=Le.JSONField=Le.BooleanField=Le.NumberField=Le.TimestampField=Le.DateField=Le.TimestampTimeframe=Le.DateTimeframe=Le.AtomicField=Le.AtomicFieldType=Le.Explore=Le.SourceRelationship=Le.FixedConnectionMap=Le.InMemoryURLReader=Le.EmptyURLReader=Le.PreparedResult=Le.DocumentCompletion=Le.DocumentSymbol=Le.DocumentPosition=Le.DocumentRange=Le.DocumentTablePath=Le.Parse=Le.PreparedQuery=Le.Model=Le.MalloyError=Le.Malloy=void 0;const rde=P4,yi=Gi,ide=qr,cP=p2,Zht=ED,ept=g2,Un=mi,tpt=g0,sde="internal://internal.malloy";let b0=class WD{static get version(){return Zht.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(sde));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new rde.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new ude(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return WD._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return RD(r,e).then(({contents:u,invalidationKey:a})=>WD._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,y,g;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(sde));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new u1(C.modelDef,[],[e.toString(),...TD(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await CP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:S}=await RD(s,e);A[v]=S,r=C}else{const C=await CP(s,e);A[v]=C}_=new rde.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const S of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(S.url,{modelDef:S.modelDef,invalidationKeys:A}));return new u1(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]],S=>_.referenceAt(S),S=>_.importAt(S))}else if(l){const S={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},b=(u==null?void 0:u._modelDef)||S;return new u1(b,C.problems||[],[...(y=u==null?void 0:u.fromSources)!==null&&y!==void 0?y:[],...(g=C.fromSources)!==null&&g!==void 0?g:[]],R=>_.referenceAt(R),R=>_.importAt(R))}else{const S=C.problems||[],b=_.prettyErrors();throw new ode(`Error(s) compiling model:
|
|
1863
|
+
${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,mht.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,iP.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,iP.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Gc.MalloyTranslation=sP;class Gxe extends sP{constructor(e,r){super(e),this.root=r}}Gc.MalloyChildTranslator=Gxe;class kht extends sP{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new rP.Zone,this.importZone=new rP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new rP.Zone,this.root=this,this.logger=new Wxe.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,Wxe.makeLogMessage)(e,r,{severity:"error",...i})),e}}Gc.MalloyTranslator=kht;function Vxe(t){return[...Object.keys(t),...Object.keys(t).map(e=>Vxe(t[e])).flat()]}var i1={};Object.defineProperty(i1,"__esModule",{value:!0}),i1.exploreQueryWalkerBuilder=i1.ExploreQueryWalker=void 0;const Mht=R0;class Yxe{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}i1.ExploreQueryWalker=Yxe;function Pht(t,e){const r=new Yxe(t),i=r;return Mht.ParseTreeWalker.DEFAULT.walk(i,e),r}i1.exploreQueryWalkerBuilder=Pht;var s1={},GE={},Ya={};Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.getResultStructMetadataAnnotation=Ya.convertFieldInfos=Ya.modelDefToModelInfo=void 0;const S0=Gi,oP=qs,uP=mi,Kxe=Bo;function Uht(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,S0.isSourceDef)(i)){const s={kind:"source",name:r,schema:{fields:o1(i,i.fields)}};e.entries.push(s)}else if(i.type==="query"){const s=(0,oP.getResultStructDefForQuery)(t,i),o=Jxe(i),u=s.resultMetadata?yD(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:o1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,oP.getResultStructDefForQuery)(t,r),s=Jxe(r),o=i.resultMetadata?yD(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:o1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ya.modelDefToModelInfo=Uht;function Jxe(t){return(0,uP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function o1(t,e){var r,i,s;const o=[];for(const u of e){const l=(0,uP.annotationToTaglines)(u.annotation).map(f=>({value:f})),c=l.length>0?l:void 0;if((0,S0.isTurtle)(u)){const f=(0,oP.getResultStructDefForView)(t,u),x=f.resultMetadata?yD(f,f.resultMetadata):void 0,h=[...c??[],...x?[x]:[]],p={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:h.length>0?h:void 0,schema:{fields:o1(f,f.fields)}};o.push(p)}else if((0,S0.isAtomic)(u)){const f=(0,S0.expressionIsAggregate)(u.expressionType),x=(0,S0.expressionIsScalar)(u.expressionType);if(!f&&!x||u.type==="error")continue;const h=u.resultMetadata?Xxe(u,u.resultMetadata):void 0,p=[...c??[],...h?[h]:[]],m={kind:f?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:aP(u),annotations:p.length>0?p:void 0};o.push(m)}else if((0,S0.isJoinedSource)(u)){const f={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:c,schema:{fields:o1(u,u.fields)},relationship:u.join};o.push(f)}}return o}Ya.convertFieldInfos=o1;function Xxe(t,e){const r=Kxe.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:qht(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function jht(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function qht(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${jht(t)}\``}function yD(t,e){var r,i;const s=Kxe.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ya.getResultStructMetadataAnnotation=yD;function aP(t){if((0,S0.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Hht(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:zht(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,S0.isRepeatedRecord)(t))return{kind:"array_type",element_type:Zxe(t)};if(t.type==="record")return Zxe(t);if(t.type==="array")return{kind:"array_type",element_type:aP(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Zxe(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=Xxe(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,uP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,S0.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:aP(e)};throw new Error("Expected record type to not have a table as its child")})}}function Hht(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function zht(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function a1t(t){return t}function l1t(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=Bo,r=mi,i=Ya,s=qr;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(h){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:h},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(h){const p=`${x.name}:${h}`,m=await x.fetchSchemaForTables({[p]:h},{}),y=m.schemas[p];if(y===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(y,y.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(h,p)=>{const m=await x.runSQL(h);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,h){function p(g,E){if(g===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const A=a(g).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(E.type.kind==="boolean_type"){if(typeof g=="number")return{kind:"boolean_cell",boolean_value:g!==0};if(typeof g!="boolean")throw new Error(`Invalid boolean ${g}`);return{kind:"boolean_cell",boolean_value:g}}else if(E.type.kind==="number_type"){if(typeof g!="number")throw new Error(`Invalid number ${g}`);return{kind:"number_cell",number_value:g}}else if(E.type.kind==="string_type"){if(typeof g!="string")throw new Error(`Invalid string ${g}`);return{kind:"string_cell",string_value:g}}else if(E.type.kind==="array_type"){if(!Array.isArray(g))throw new Error(`Invalid array ${g}`);return{kind:"array_cell",array_value:g.map(A=>p(A,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(g)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(g)};{const A=E.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(g)}`);return m(g,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(_=>({kind:"dimension",..._}))}})}}}function m(g,E){const A=[];for(const _ of E.schema.fields){const v=g[_.name];if(_.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=p(v,_);A.push(C)}return{kind:"record_cell",record_value:A}}const y={kind:"join",schema:h,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(g=>m(g,y))}}t.mapData=l;function c(x){const h=x._queryResult.structs,p=h[h.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},y=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),g=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return g&&y.push(g),y.push(...p.resultMetadata?[]:[]),x.sourceExplore&&y.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),y.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:y.length>0?y:void 0,query_timezone:x.data.field.queryTimezone}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,h){return x.map(p=>{var m,y,g,E;return{severity:p.severity,message:p.message,range:(y=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&y!==void 0?y:t.DEFAULT_LOG_RANGE,url:(E=(g=p.at)===null||g===void 0?void 0:g.url)!==null&&E!==void 0?E:h}})}t.mapLogs=f})(GE);var Qht=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Wht=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ght=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Qht(e,t,r);return Wht(e,t),e};Object.defineProperty(s1,"__esModule",{value:!0}),s1.malloyToQuery=s1.MalloyToQuery=void 0;const Vht=Hd,Ln=Ght(I),ede=R2,VE=Pn,Yht=et,Kht=PE,tde=Jn,Jht=GE,lP="Malloy query documents";class nde extends Vht.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,tde.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,ede.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${lP}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${lP} may only have one run statement`);return i===void 0?(this.illegal(e,`${lP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,VE.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Ln.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Ln.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Ln.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Ln.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Ln.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Ln.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Ln.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Ln.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Ln.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Ln.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Ln.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Ln.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Ln.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,VE.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Ln.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,VE.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Ln.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Ln.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement())this.notAllowed(e,"Having statements");else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,VE.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,Yht.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,VE.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Ln.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Ln.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Ln.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getWhereExpr(e){if(e instanceof Ln.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Ln.ExprFieldPathContext&&i instanceof Ln.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Ln.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getWhereExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}s1.MalloyToQuery=nde;function Xht(t){const e=(0,tde.getSourceInfo)(t),r=new ede.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Kht.runMalloyParser)(t,i,e,r),u=new nde(s,r).visit(s.root),a=(0,Jht.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}s1.malloyToQuery=Xht,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Gc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=i1;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=s1;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(P4);var Le={},ED={};Object.defineProperty(ED,"__esModule",{value:!0}),ED.MALLOY_VERSION=void 0,ED.MALLOY_VERSION="0.0.254",Object.defineProperty(Le,"__esModule",{value:!0}),Le.InMemoryModelCache=Le.CacheManager=Le.CSVWriter=Le.JSONWriter=Le.DataWriter=Le.DataRecord=Le.DataArray=Le.Result=Le.ExploreMaterializer=Le.PreparedResultMaterializer=Le.QueryMaterializer=Le.ModelMaterializer=Le.SingleConnectionRuntime=Le.ConnectionRuntime=Le.Runtime=Le.ExploreField=Le.JoinRelationship=Le.QueryField=Le.Query=Le.StringField=Le.UnsupportedField=Le.JSONField=Le.BooleanField=Le.NumberField=Le.TimestampField=Le.DateField=Le.TimestampTimeframe=Le.DateTimeframe=Le.AtomicField=Le.AtomicFieldType=Le.Explore=Le.SourceRelationship=Le.FixedConnectionMap=Le.InMemoryURLReader=Le.EmptyURLReader=Le.PreparedResult=Le.DocumentCompletion=Le.DocumentSymbol=Le.DocumentPosition=Le.DocumentRange=Le.DocumentTablePath=Le.Parse=Le.PreparedQuery=Le.Model=Le.MalloyError=Le.Malloy=void 0;const rde=P4,yi=Gi,ide=qr,cP=p2,Zht=ED,ept=g2,Un=mi,tpt=g0,sde="internal://internal.malloy";let b0=class WD{static get version(){return Zht.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(sde));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new rde.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new ude(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return WD._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return RD(r,e).then(({contents:u,invalidationKey:a})=>WD._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var h,p,m,y,g;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(sde));const A={};if(r===void 0&&x!==void 0){const C=await x.getCachedModelDef(s,e.toString());if(C)return new u1(C.modelDef,[],[e.toString(),...TD(C.modelDef.dependencies)])}f??(f=e);let _;const v=e.toString();if(i!==void 0){_=i._translator;const C=(h=i._invalidationKey)!==null&&h!==void 0?h:await CP(s,e);A[v]=C}else{if(r===void 0){const{contents:C,invalidationKey:S}=await RD(s,e);A[v]=S,r=C}else{const C=await CP(s,e);A[v]=C}_=new rde.MalloyTranslator(v,f.toString(),{urls:{[v]:r}},c)}for(;;){const C=_.translate(u==null?void 0:u._modelDef);if(C.final)if(C.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:C.modelDef,invalidationKeys:A}));for(const S of _.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(S.url,{modelDef:S.modelDef,invalidationKeys:A}));return new u1(C.modelDef,C.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=C.fromSources)!==null&&m!==void 0?m:[]],S=>_.referenceAt(S),S=>_.importAt(S))}else if(l){const S={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},b=(u==null?void 0:u._modelDef)||S;return new u1(b,C.problems||[],[...(y=u==null?void 0:u.fromSources)!==null&&y!==void 0?y:[],...(g=C.fromSources)!==null&&g!==void 0?g:[]],R=>_.referenceAt(R),R=>_.importAt(R))}else{const S=C.problems||[],b=_.prettyErrors();throw new ode(`Error(s) compiling model:
|
|
1864
1864
|
${b}`,S)}else{if(C.urls)for(const b of C.urls)try{if(DD(b))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(x!==void 0){const D=await x.getCachedModelDef(s,b);if(D){for(const $ in D.invalidationKeys)A[$]=D.invalidationKeys[$];_.update({translations:{[b]:D.modelDef}});continue}}const{contents:R,invalidationKey:O}=await RD(s,new URL(b)),B={[b]:R};A[b]=O,_.update({urls:B})}catch(R){_.update({errors:{urls:{[b]:R.message}}})}const{modelAnnotation:S}=_.modelAnnotation(u==null?void 0:u._modelDef);if(C.tables){const b=new Map;for(const R in C.tables){const{connectionName:O,tablePath:B}=C.tables[R],D=b.get(O);D===void 0?b.set(O,{[R]:B}):D[R]=B}for(const[R,O]of b)try{const B=await o.lookupConnection(R),{schemas:D,errors:$}=await WD.safelyFetchTableSchema(B,O,{refreshTimestamp:E,modelAnnotation:S});_.update({tables:D,errors:{tables:$}})}catch(B){const D={},$={};for(const U in O)$[U]=B.toString();_.update({tables:D,errors:{tables:$}})}}if(C.compileSQL){const b=C.compileSQL,R=b.connection,O=(0,tpt.sqlKey)(b.connection,b.selectStr);try{const D=await(await o.lookupConnection(R)).fetchSchemaForSQLStruct(b,{refreshTimestamp:E,modelAnnotation:S});D.error&&_.update({errors:{compileSQL:{[O]:D.error}}}),D.structDef&&_.update({compileSQL:{[O]:D.structDef}})}catch(B){const D={};D[O]=B.toString(),_.update({errors:{compileSQL:D}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new JE({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new JE({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new Vs(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new Md(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};Le.Malloy=b0;class ode extends Error{constructor(e,r=[]){super(e),this.problems=r}}Le.MalloyError=ode;class u1{constructor(e,r,i,s=()=>{},o=()=>{}){this.modelDef=e,this.problems=r,this.fromSources=i,this._referenceAt=s,this._importAt=o}tagParse(e){return(0,Un.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new a1(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new a1(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new a1(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if((0,yi.isSourceDef)(r))return new Vs(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(yi.isSourceDef).map(e=>new Vs(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}Le.Model=u1;class a1{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,Un.annotationToTag)(this._modelDef.annotation).tag;return e=(0,Un.addModelScope)(e,r),(0,Un.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new yi.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new YE({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,yi.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}Le.PreparedQuery=a1;class ude{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new AD(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new ade(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new lde(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}Le.Parse=ude;class ade{constructor(e){this._range=l1.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}Le.DocumentTablePath=ade;class l1{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new l1(new fP(e.start.line,e.start.character),new fP(e.end.line,e.end.character))}}Le.DocumentRange=l1;class fP{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Le.DocumentPosition=fP;class AD{constructor(e){this._range=l1.fromJSON(e.range),this._lensRange=e.lensRange?l1.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new AD(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}Le.DocumentSymbol=AD;class lde{constructor(e){this.type=e.type,this.text=e.text}}Le.DocumentCompletion=lde;class YE{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new YE(e,r)}tagParse(e){const r=(0,Un.annotationToTag)(this.modelDef.annotation).tag;return e=(0,Un.addModelScope)(e,r),(0,Un.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,Un.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new Vs(r,this.sourceExplore)}catch{return new Vs(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,yi.isSourceDef)(r))return new Vs(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Le.PreparedResult=YE;class cde{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}Le.EmptyURLReader=cde;class npt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return DD(e.toString())?null:bde(r)}}Le.InMemoryURLReader=npt;class _D{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new _D(new Map(e.map(r=>[r.name,r])))}}Le.FixedConnectionMap=_D;var fde;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(fde||(Le.SourceRelationship=fde={}));class xP{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Vs}isQuery(){return this instanceof EP}}class Vs extends xP{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,yi.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,Un.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,Un.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i={type:"query",structRef:r,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new a1(i,this.modelDef,[],e)}get modelDef(){if(!(0,yi.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new u1(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,yi.isJoined)(i))return[s,new AP(i,this,o)];if(i.type==="turtle")return[s,new EP(i,this,o)];if(i.type==="string")return[s,new yP(i,this,o)];if(i.type==="number")return[s,new vD(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new vD({...i,type:"number"},this,o)]:[s,new dP(i,this,o)];if(i.type==="timestamp")return[s,new hP(i,this,o)];if(i.type==="boolean")return[s,new pP(i,this,o)];if(i.type==="json")return[s,new mP(i,this,o)];if(i.type==="sql native")return[s,new gP(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(u=>{if(typeof u.field=="string")return{field:this.fieldMap.get(u.field),dir:u.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(u=>u.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(u=>!o.has(u.name)).map(u=>({field:u,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof AP}get filters(){var e;return(0,yi.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,yi.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?Vs.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?Vs.fromJSON(e.sourceExplore):void 0;return new Vs(e._structDef,r,i)}get location(){return this.structDef.location}}Le.Explore=Vs;var Ka;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(Ka||(Le.AtomicFieldType=Ka={}));class hf extends xP{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return Ka.String;case"boolean":return Ka.Boolean;case"date":return Ka.Date;case"timestamp":return Ka.Timestamp;case"number":return Ka.Number;case"json":return Ka.Json;case"sql native":return Ka.NativeUnsupported;case"error":return Ka.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,Un.addModelScope)(e,this.parent.modelTag),(0,Un.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,yi.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,yi.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof yP}isNumber(){return this instanceof vD}isDate(){return this instanceof dP}isBoolean(){return this instanceof pP}isJSON(){return this instanceof mP}isTimestamp(){return this instanceof hP}isUnsupported(){return this instanceof gP}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Le.AtomicField=hf;var kd;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(kd||(Le.DateTimeframe=kd={}));var Ja;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(Ja||(Le.TimestampTimeframe=Ja={}));class dP extends hf{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return kd.Day;case"week":return kd.Week;case"month":return kd.Month;case"quarter":return kd.Quarter;case"year":return kd.Year}}}Le.DateField=dP;class hP extends hf{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Ja.Day;case"week":return Ja.Week;case"month":return Ja.Month;case"quarter":return Ja.Quarter;case"year":return Ja.Year;case"second":return Ja.Second;case"hour":return Ja.Hour;case"minute":return Ja.Minute}}}Le.TimestampField=hP;class vD extends hf{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}}Le.NumberField=vD;class pP extends hf{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}}Le.BooleanField=pP;class mP extends hf{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}}Le.JSONField=mP;class gP extends hf{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Le.UnsupportedField=gP;class yP extends hf{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}}Le.StringField=yP;class xde extends xP{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Le.Query=xde;class EP extends xde{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,Un.addModelScope)(e,this.parent.modelTag),(0,Un.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,Un.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}Le.QueryField=EP;var c1;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(c1||(Le.JoinRelationship=c1={}));class AP extends Vs{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,yi.isJoined)(this.structDef))switch(this.structDef.join){case"one":return c1.OneToOne;case"many":case"cross":return c1.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===c1.OneToOne}get isArray(){return this.joinRelationship!==c1.OneToOne}tagParse(e){return e=(0,Un.addModelScope)(e,this._parentExplore.modelTag),(0,Un.annotationToTag)(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}Le.ExploreField=AP;class _P{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new cde),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new KE(this,async()=>b0.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new KE(this,async()=>new u1(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}Le.Runtime=_P;class rpt extends _P{constructor({urlReader:e,connections:r}){super({connections:_D.fromArray(r),urlReader:e}),this.rawConnections=r}}Le.ConnectionRuntime=rpt;class ipt extends _P{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,cP.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,cP.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,cP.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Le.SingleConnectionRuntime=ipt;class CD{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new dde(this.runtime,e,r)}makeExploreMaterializer(e,r){return new pde(this.runtime,e,r)}makePreparedResultMaterializer(e){return new hde(this.runtime,e)}}class KE extends CD{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await b0.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new KE(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await b0.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new yi.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,yi.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,yi.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
|
|
1865
1865
|
run: ${e}
|
|
1866
1866
|
-> ${u}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@malloydata/render",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.254-dev250401010409",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"main": "dist/module/index.umd.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -41,9 +41,9 @@
|
|
|
41
41
|
"generate-flow": "ts-node ../../scripts/gen-flow.ts"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@malloydata/malloy": "^0.0.
|
|
45
|
-
"@malloydata/malloy-interfaces": "^0.0.
|
|
46
|
-
"@malloydata/malloy-tag": "^0.0.
|
|
44
|
+
"@malloydata/malloy": "^0.0.254-dev250401010409",
|
|
45
|
+
"@malloydata/malloy-interfaces": "^0.0.254-dev250401010409",
|
|
46
|
+
"@malloydata/malloy-tag": "^0.0.254-dev250401010409",
|
|
47
47
|
"@tanstack/solid-virtual": "^3.10.4",
|
|
48
48
|
"component-register": "^0.8.6",
|
|
49
49
|
"lodash": "^4.17.20",
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"vega-lite": "^5.2.0"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
|
-
"@malloydata/db-duckdb": "^0.0.
|
|
59
|
+
"@malloydata/db-duckdb": "^0.0.254-dev250401010409",
|
|
60
60
|
"@storybook/addon-essentials": "^8.5.8",
|
|
61
61
|
"@storybook/addon-interactions": "^8.5.8",
|
|
62
62
|
"@storybook/addon-links": "^8.5.8",
|