@malloydata/render 0.0.166 → 0.0.167

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.
@@ -51796,7 +51796,8 @@ class Ym extends eE {
51796
51796
  connections: i,
51797
51797
  parse: s,
51798
51798
  model: o,
51799
- refreshSchemaCache: n == null ? void 0 : n.refreshSchemaCache
51799
+ refreshSchemaCache: n == null ? void 0 : n.refreshSchemaCache,
51800
+ noThrowOnError: n == null ? void 0 : n.noThrowOnError
51800
51801
  });
51801
51802
  });
51802
51803
  }
@@ -1302,7 +1302,7 @@ QUERY: ${(0,YAe.inspect)(n,{breakLength:72,depth:1/0})}`)}return{...tQ.ErrorFact
1302
1302
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1303
1303
  `+i,n=s),e!==""?e=`${e}
1304
1304
  ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];(u.type==="struct"||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,AOe.locationContainsPosition)(r.location,e))return r}}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 this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<=o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}Ou.MalloyTranslation=iF;class WW extends iF{constructor(e,n){super(e),this.root=n}}Ou.MalloyChildTranslator=WW;class LOe extends iF{constructor(e,n=null,r=null){super(e,n),this.schemaZone=new rF.Zone,this.importZone=new rF.Zone,this.sqlQueryZone=new rF.Zone,this.logger=new hOe.MessageLog,this.root=this,r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}}Ou.MalloyTranslator=LOe;class VW{constructor(e,n){this.translator=e,this.messages=n}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u},l={message:s,at:{url:this.translator.sourceURL,range:a},severity:"error"};this.messages.log(l)}}Ou.MalloyParserErrorHandler=VW;var b2={};Object.defineProperty(b2,"__esModule",{value:!0}),b2.exploreQueryWalkerBuilder=b2.ExploreQueryWalker=void 0;const IOe=b0;class YW{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}b2.ExploreQueryWalker=YW;function $Oe(t,e){const n=new YW(t),r=n;return IOe.ParseTreeWalker.DEFAULT.walk(r,e),n}b2.exploreQueryWalkerBuilder=$Oe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=Ou;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=b2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(fO);var Ne={};Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.CSVWriter=Ne.JSONWriter=Ne.DataWriter=Ne.DataRecord=Ne.DataArray=Ne.Result=Ne.ExploreMaterializer=Ne.SQLBlockMaterializer=Ne.PreparedResultMaterializer=Ne.QueryMaterializer=Ne.ModelMaterializer=Ne.SingleConnectionRuntime=Ne.ConnectionRuntime=Ne.Runtime=Ne.ExploreField=Ne.JoinRelationship=Ne.QueryField=Ne.Query=Ne.StringField=Ne.UnsupportedField=Ne.JSONField=Ne.BooleanField=Ne.NumberField=Ne.TimestampField=Ne.DateField=Ne.TimestampTimeframe=Ne.DateTimeframe=Ne.AtomicField=Ne.AtomicFieldType=Ne.Explore=Ne.SourceRelationship=Ne.FixedConnectionMap=Ne.InMemoryURLReader=Ne.EmptyURLReader=Ne.PreparedResult=Ne.DocumentCompletion=Ne.DocumentSymbol=Ne.DocumentPosition=Ne.DocumentRange=Ne.DocumentTablePath=Ne.Parse=Ne.PreparedQuery=Ne.Model=Ne.MalloyError=Ne.Malloy=void 0;const BOe=fO,V0=bu,kOe=iW,Ln=ll,sF=t1;class xn{static get version(){return"0.0.1"}static get log(){return xn._log||console}static setLogger(e){xn._log=e}static _parse(e,n,r){n===void 0&&(n=new URL("internal://internal.malloy"));let i=n;r!=null&&r.importBaseURL&&(i=r==null?void 0:r.importBaseURL);const s=new BOe.MalloyTranslator(n.toString(),i.toString(),{urls:{[n.toString()]:e}});return r!=null&&r.testEnvironment&&(s.allDialectsEnabled=!0),new JW(s)}static parse({url:e,urlReader:n,source:r,options:i}){if(r!==void 0)return xn._parse(r,e,i);if(n===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 n.readURL(e).then(s=>xn._parse(s,e,i))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o}){var u,a,l,c;let f;s&&(f=typeof s=="number"?s:Date.now());const x=r._translator;for(;;){const h=x.translate(i==null?void 0:i._modelDef);if(h.final){if(h.translated)return new i3(h.translated.modelDef,h.translated.queryList,h.translated.sqlBlocks,h.problems||[],[...(u=i==null?void 0:i.fromSources)!==null&&u!==void 0?u:[],...(a=h.fromSources)!==null&&a!==void 0?a:[]],p=>x.referenceAt(p),p=>x.importAt(p));if(o){const p={name:"modelDidNotCompile",exports:[],contents:{}},m=(i==null?void 0:i._modelDef)||p;return new i3(m,[],[],h.problems||[],[...(l=i==null?void 0:i.fromSources)!==null&&l!==void 0?l:[],...(c=h.fromSources)!==null&&c!==void 0?c:[]],g=>x.referenceAt(g),g=>x.importAt(g))}else{const p=h.problems||[],m=x.prettyErrors();throw new XW(`Error(s) compiling model:
1305
- ${m}`,p)}}else{if(h.urls)for(const m of h.urls)try{if(m.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const g=await e.readURL(new URL(m)),y={[m]:g};x.update({urls:y})}catch(g){x.update({errors:{urls:{[m]:g.message}}})}const{modelAnnotation:p}=x.modelAnnotation(i==null?void 0:i._modelDef);if(h.tables){const m=new Map;for(const g in h.tables){const{connectionName:y,tablePath:E}=h.tables[g],A=m.get(y);A===void 0?m.set(y,{[g]:E}):A[g]=E}for(const[g,y]of m)try{const E=await n.lookupConnection(g),{schemas:A,errors:v}=await E.fetchSchemaForTables(y,{refreshTimestamp:f,modelAnnotation:p});x.update({tables:A,errors:{tables:v}})}catch(E){const A={},v={};for(const _ in y)v[_]=E.toString();x.update({tables:A,errors:{tables:v}})}}if(h.compileSQL){const m=h.compileSQL,g=m.connection;try{const y=await n.lookupConnection(g),E=xn.compileSQLBlock(h.partialModel,m),A=await y.fetchSchemaForSQLBlock(E,{refreshTimestamp:f,modelAnnotation:p});A.error&&x.update({errors:{compileSQL:{[E.name]:A.error}}}),A.structDef&&(0,V0.isSQLBlockStruct)(A.structDef)&&x.update({compileSQL:{[E.name]:A.structDef}})}catch(y){const E={};E[m.name]=y.toString(),x.update({errors:{compileSQL:E}})}}}}}static compileSQLBlock(e,n){let r,i="",s=!1;for(const a of n.select)if((0,V0.isSQLFragment)(a))i+=a.sql,s=a.sql.match(/\(\s*$/)!==null;else{if(!r){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");r=new V0.QueryModel(e)}const l=r.compileQuery(a,!1).sql;i+=s?l:`(${l})`,s=!1}const{name:o,connection:u}=n;return{type:"sqlBlock",name:o,connection:u,selectStr:i}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new l3({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new l3({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new ws(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new _x(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Ne.Malloy=xn;class XW extends Error{constructor(e,n=[]){super(e),this.problems=n}}Ne.MalloyError=XW;let i3=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}tagParse(e){return Ln.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new R2(n,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.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new R2(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new R2(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new ws(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new ws(n))}get namedQueries(){const e=n=>n.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}};Ne.Model=i3;class R2{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=Ln.Tag.annotationToTag(this._modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){const n=new V0.QueryModel(this._modelDef).compileQuery(this._query);return new s3({...n,queryName:this.name||n.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Ne.PreparedQuery=R2;class JW{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new C5(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new KW(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new ZW(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Ne.Parse=JW;class KW{constructor(e){this._range=O2.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}}Ne.DocumentTablePath=KW;class O2{constructor(e,n){this._start=e,this._end=n}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 O2(new oF(e.start.line,e.start.character),new oF(e.end.line,e.end.character))}}Ne.DocumentRange=O2;class oF{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Ne.DocumentPosition=oF;class C5{constructor(e){this._range=O2.fromJSON(e.range),this._lensRange=e.lensRange?O2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new C5(n))}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}}Ne.DocumentSymbol=C5;class ZW{constructor(e){this.type=e.type,this.text=e.text}}Ne.DocumentCompletion=ZW;class s3{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new s3(e,n)}tagParse(e){const n=Ln.Tag.annotationToTag(this.modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return Ln.Tag.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 resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],n={...e,name:this.inner.queryName||e.name};try{return new ws(n,this.sourceExplore)}catch{return new ws(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new ws(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Ne.PreparedResult=s3;class eV{async readURL(e){throw new Error("No files.")}}Ne.EmptyURLReader=eV;class POe{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}Ne.InMemoryURLReader=POe;class o3{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);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 o3(new Map(e.map(n=>[n.name,n])))}}Ne.FixedConnectionMap=o3;var Y0;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(Y0||(Ne.SourceRelationship=Y0={}));class uF{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}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 n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof ws}isQuery(){return this instanceof hF}}class ws extends uF{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,V0.FieldIsIntrinsic)(this._structDef)}isExploreField(){return!1}tagParse(e){return Ln.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=Ln.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new R2(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new i3(this.modelDef,[],[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if(r.type==="struct")return[i,new pF(r,this,s)];if(r.type==="turtle")return[i,new hF(r,this,s)];if(r.type==="string")return[i,new dF(r,this,s)];if(r.type==="number")return[i,new T5(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new T5({...r,type:"number"},this,s)]:[i,new aF(r,this,s)];if(r.type==="timestamp")return[i,new lF(r,this,s)];if(r.type==="boolean")return[i,new cF(r,this,s)];if(r.type==="json")return[i,new fF(r,this,s)];if(r.type==="sql native")return[i,new xF(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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 n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return Y0.Many;case"one":return Y0.One;case"cross":return Y0.Cross;case"inline":return Y0.Inline;case"nested":return Y0.Nested;case"basetable":return Y0.BaseTable}}hasParentExplore(){return this instanceof pF}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?ws.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ws.fromJSON(e.sourceExplore):void 0;return new ws(e._structDef,n,r)}get location(){return this.structDef.location}}Ne.Explore=ws;var Ju;(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"})(Ju||(Ne.AtomicFieldType=Ju={}));class X0 extends uF{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return Ju.String;case"boolean":return Ju.Boolean;case"date":return Ju.Date;case"timestamp":return Ju.Timestamp;case"number":return Ju.Number;case"json":return Ju.Json;case"sql native":return Ju.NativeUnsupported;case"error":return Ju.Error}}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,V0.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,V0.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.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 dF}isNumber(){return this instanceof T5}isDate(){return this instanceof aF}isBoolean(){return this instanceof cF}isJSON(){return this instanceof fF}isTimestamp(){return this instanceof lF}isUnsupported(){return this instanceof xF}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Ne.AtomicField=X0;var Sx;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Sx||(Ne.DateTimeframe=Sx={}));var Ku;(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"})(Ku||(Ne.TimestampTimeframe=Ku={}));class aF extends X0{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Sx.Day;case"week":return Sx.Week;case"month":return Sx.Month;case"quarter":return Sx.Quarter;case"year":return Sx.Year}}}Ne.DateField=aF;class lF extends X0{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Ku.Day;case"week":return Ku.Week;case"month":return Ku.Month;case"quarter":return Ku.Quarter;case"year":return Ku.Year;case"second":return Ku.Second;case"hour":return Ku.Hour;case"minute":return Ku.Minute}}}Ne.TimestampField=lF;class T5 extends X0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Ne.NumberField=T5;class cF extends X0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Ne.BooleanField=cF;class fF extends X0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Ne.JSONField=fF;class xF extends X0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Ne.UnsupportedField=xF;class dF extends X0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Ne.StringField=dF;class tV extends uF{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Ne.Query=tV;class hF extends tV{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return Ln.Tag.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}}Ne.QueryField=hF;var J0;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(J0||(Ne.JoinRelationship=J0={}));class pF extends ws{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return J0.OneToMany;case"many":case"cross":return J0.ManyToOne;case"inline":return J0.OneToOne;case"nested":return J0.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===J0.OneToOne}get isArray(){return this.joinRelationship!==J0.OneToOne}tagParse(e){return e=Ln.Tag.addModelScope(e,this._parentExplore.modelTag),Ln.Tag.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]:[]}}Ne.ExploreField=pF;class gF{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)HOe(i)?n=i:zOe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new eV),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new a3(this,async()=>{const s=e instanceof URL?await xn.parse({url:e,urlReader:this.urlReader,options:n}):xn.parse({source:e,options:n});return xn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i})})}_loadModelFromModelDef(e){return new a3(this,async()=>new i3(e,[],[],[],[]))}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Ne.Runtime=gF;class MOe extends gF{constructor(e,n){if(n===void 0){const r=e;super(o3.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,o3.fromArray(r)),this.rawConnections=r}}}Ne.ConnectionRuntime=MOe;class jOe extends gF{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,sF.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,sF.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,sF.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Ne.SingleConnectionRuntime=jOe;class u3{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e){return new nV(this.runtime,e)}makeExploreMaterializer(e){return new sV(this.runtime,e)}makePreparedResultMaterializer(e){return new rV(this.runtime,e)}makeSQLBlockMaterializer(e){return new iV(this.runtime,e)}}class a3 extends u3{loadFinalQuery(){return this.makeQueryMaterializer(async()=>(await this.materialize()).preparedQuery)}loadQueryByIndex(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e))}loadQueryByName(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e))}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await xn.parse({url:e,urlReader:s,options:n}):xn.parse({source:e,options:n}),a=await this.getModel();return(await xn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new a3(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await xn.parse({url:e,urlReader:r,options:n}):xn.parse({source:e,options:n}),o=await this.getModel();return await xn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache})})}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new V0.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1305
+ ${m}`,p)}}else{if(h.urls)for(const m of h.urls)try{if(m.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const g=await e.readURL(new URL(m)),y={[m]:g};x.update({urls:y})}catch(g){x.update({errors:{urls:{[m]:g.message}}})}const{modelAnnotation:p}=x.modelAnnotation(i==null?void 0:i._modelDef);if(h.tables){const m=new Map;for(const g in h.tables){const{connectionName:y,tablePath:E}=h.tables[g],A=m.get(y);A===void 0?m.set(y,{[g]:E}):A[g]=E}for(const[g,y]of m)try{const E=await n.lookupConnection(g),{schemas:A,errors:v}=await E.fetchSchemaForTables(y,{refreshTimestamp:f,modelAnnotation:p});x.update({tables:A,errors:{tables:v}})}catch(E){const A={},v={};for(const _ in y)v[_]=E.toString();x.update({tables:A,errors:{tables:v}})}}if(h.compileSQL){const m=h.compileSQL,g=m.connection;try{const y=await n.lookupConnection(g),E=xn.compileSQLBlock(h.partialModel,m),A=await y.fetchSchemaForSQLBlock(E,{refreshTimestamp:f,modelAnnotation:p});A.error&&x.update({errors:{compileSQL:{[E.name]:A.error}}}),A.structDef&&(0,V0.isSQLBlockStruct)(A.structDef)&&x.update({compileSQL:{[E.name]:A.structDef}})}catch(y){const E={};E[m.name]=y.toString(),x.update({errors:{compileSQL:E}})}}}}}static compileSQLBlock(e,n){let r,i="",s=!1;for(const a of n.select)if((0,V0.isSQLFragment)(a))i+=a.sql,s=a.sql.match(/\(\s*$/)!==null;else{if(!r){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");r=new V0.QueryModel(e)}const l=r.compileQuery(a,!1).sql;i+=s?l:`(${l})`,s=!1}const{name:o,connection:u}=n;return{type:"sqlBlock",name:o,connection:u,selectStr:i}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new l3({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new l3({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new ws(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new _x(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Ne.Malloy=xn;class XW extends Error{constructor(e,n=[]){super(e),this.problems=n}}Ne.MalloyError=XW;let i3=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}tagParse(e){return Ln.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new R2(n,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.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new R2(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new R2(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new ws(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new ws(n))}get namedQueries(){const e=n=>n.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}};Ne.Model=i3;class R2{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=Ln.Tag.annotationToTag(this._modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){const n=new V0.QueryModel(this._modelDef).compileQuery(this._query);return new s3({...n,queryName:this.name||n.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Ne.PreparedQuery=R2;class JW{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new C5(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new KW(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new ZW(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Ne.Parse=JW;class KW{constructor(e){this._range=O2.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}}Ne.DocumentTablePath=KW;class O2{constructor(e,n){this._start=e,this._end=n}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 O2(new oF(e.start.line,e.start.character),new oF(e.end.line,e.end.character))}}Ne.DocumentRange=O2;class oF{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Ne.DocumentPosition=oF;class C5{constructor(e){this._range=O2.fromJSON(e.range),this._lensRange=e.lensRange?O2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new C5(n))}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}}Ne.DocumentSymbol=C5;class ZW{constructor(e){this.type=e.type,this.text=e.text}}Ne.DocumentCompletion=ZW;class s3{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new s3(e,n)}tagParse(e){const n=Ln.Tag.annotationToTag(this.modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return Ln.Tag.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 resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],n={...e,name:this.inner.queryName||e.name};try{return new ws(n,this.sourceExplore)}catch{return new ws(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new ws(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Ne.PreparedResult=s3;class eV{async readURL(e){throw new Error("No files.")}}Ne.EmptyURLReader=eV;class POe{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}Ne.InMemoryURLReader=POe;class o3{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);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 o3(new Map(e.map(n=>[n.name,n])))}}Ne.FixedConnectionMap=o3;var Y0;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(Y0||(Ne.SourceRelationship=Y0={}));class uF{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}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 n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof ws}isQuery(){return this instanceof hF}}class ws extends uF{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,V0.FieldIsIntrinsic)(this._structDef)}isExploreField(){return!1}tagParse(e){return Ln.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=Ln.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new R2(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new i3(this.modelDef,[],[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if(r.type==="struct")return[i,new pF(r,this,s)];if(r.type==="turtle")return[i,new hF(r,this,s)];if(r.type==="string")return[i,new dF(r,this,s)];if(r.type==="number")return[i,new T5(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new T5({...r,type:"number"},this,s)]:[i,new aF(r,this,s)];if(r.type==="timestamp")return[i,new lF(r,this,s)];if(r.type==="boolean")return[i,new cF(r,this,s)];if(r.type==="json")return[i,new fF(r,this,s)];if(r.type==="sql native")return[i,new xF(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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 n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return Y0.Many;case"one":return Y0.One;case"cross":return Y0.Cross;case"inline":return Y0.Inline;case"nested":return Y0.Nested;case"basetable":return Y0.BaseTable}}hasParentExplore(){return this instanceof pF}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?ws.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?ws.fromJSON(e.sourceExplore):void 0;return new ws(e._structDef,n,r)}get location(){return this.structDef.location}}Ne.Explore=ws;var Ju;(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"})(Ju||(Ne.AtomicFieldType=Ju={}));class X0 extends uF{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return Ju.String;case"boolean":return Ju.Boolean;case"date":return Ju.Date;case"timestamp":return Ju.Timestamp;case"number":return Ju.Number;case"json":return Ju.Json;case"sql native":return Ju.NativeUnsupported;case"error":return Ju.Error}}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,V0.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,V0.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.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 dF}isNumber(){return this instanceof T5}isDate(){return this instanceof aF}isBoolean(){return this instanceof cF}isJSON(){return this instanceof fF}isTimestamp(){return this instanceof lF}isUnsupported(){return this instanceof xF}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Ne.AtomicField=X0;var Sx;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Sx||(Ne.DateTimeframe=Sx={}));var Ku;(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"})(Ku||(Ne.TimestampTimeframe=Ku={}));class aF extends X0{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Sx.Day;case"week":return Sx.Week;case"month":return Sx.Month;case"quarter":return Sx.Quarter;case"year":return Sx.Year}}}Ne.DateField=aF;class lF extends X0{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Ku.Day;case"week":return Ku.Week;case"month":return Ku.Month;case"quarter":return Ku.Quarter;case"year":return Ku.Year;case"second":return Ku.Second;case"hour":return Ku.Hour;case"minute":return Ku.Minute}}}Ne.TimestampField=lF;class T5 extends X0{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Ne.NumberField=T5;class cF extends X0{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Ne.BooleanField=cF;class fF extends X0{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Ne.JSONField=fF;class xF extends X0{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Ne.UnsupportedField=xF;class dF extends X0{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Ne.StringField=dF;class tV extends uF{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Ne.Query=tV;class hF extends tV{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return Ln.Tag.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}}Ne.QueryField=hF;var J0;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(J0||(Ne.JoinRelationship=J0={}));class pF extends ws{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return J0.OneToMany;case"many":case"cross":return J0.ManyToOne;case"inline":return J0.OneToOne;case"nested":return J0.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===J0.OneToOne}get isArray(){return this.joinRelationship!==J0.OneToOne}tagParse(e){return e=Ln.Tag.addModelScope(e,this._parentExplore.modelTag),Ln.Tag.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]:[]}}Ne.ExploreField=pF;class gF{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)HOe(i)?n=i:zOe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new eV),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new a3(this,async()=>{const s=e instanceof URL?await xn.parse({url:e,urlReader:this.urlReader,options:n}):xn.parse({source:e,options:n});return xn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i})})}_loadModelFromModelDef(e){return new a3(this,async()=>new i3(e,[],[],[],[]))}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Ne.Runtime=gF;class MOe extends gF{constructor(e,n){if(n===void 0){const r=e;super(o3.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,o3.fromArray(r)),this.rawConnections=r}}}Ne.ConnectionRuntime=MOe;class jOe extends gF{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,sF.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,sF.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,sF.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Ne.SingleConnectionRuntime=jOe;class u3{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e){return new nV(this.runtime,e)}makeExploreMaterializer(e){return new sV(this.runtime,e)}makePreparedResultMaterializer(e){return new rV(this.runtime,e)}makeSQLBlockMaterializer(e){return new iV(this.runtime,e)}}class a3 extends u3{loadFinalQuery(){return this.makeQueryMaterializer(async()=>(await this.materialize()).preparedQuery)}loadQueryByIndex(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e))}loadQueryByName(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e))}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await xn.parse({url:e,urlReader:s,options:n}):xn.parse({source:e,options:n}),a=await this.getModel();return(await xn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new a3(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await xn.parse({url:e,urlReader:r,options:n}):xn.parse({source:e,options:n}),o=await this.getModel();return await xn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError})})}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new V0.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1306
1306
  run: ${e}
1307
1307
  -> ${o}
1308
1308
  -> {
@@ -52864,7 +52864,8 @@ class u3 extends hE {
52864
52864
  connections: i,
52865
52865
  parse: s,
52866
52866
  model: o,
52867
- refreshSchemaCache: n == null ? void 0 : n.refreshSchemaCache
52867
+ refreshSchemaCache: n == null ? void 0 : n.refreshSchemaCache,
52868
+ noThrowOnError: n == null ? void 0 : n.noThrowOnError
52868
52869
  });
52869
52870
  });
52870
52871
  }
@@ -1302,7 +1302,7 @@ QUERY: ${(0,jve.inspect)(n,{breakLength:72,depth:1/0})}`)}return{...cQ.ErrorFact
1302
1302
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1303
1303
  `+i,n=s),e!==""?e=`${e}
1304
1304
  ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];(u.type==="struct"||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,dNe.locationContainsPosition)(r.location,e))return r}}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 this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<=o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}Fu.MalloyTranslation=EF;class tV extends EF{constructor(e,n){super(e),this.root=n}}Fu.MalloyChildTranslator=tV;class TNe extends EF{constructor(e,n=null,r=null){super(e,n),this.schemaZone=new yF.Zone,this.importZone=new yF.Zone,this.sqlQueryZone=new yF.Zone,this.logger=new uNe.MessageLog,this.root=this,r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}}Fu.MalloyTranslator=TNe;class nV{constructor(e,n){this.translator=e,this.messages=n}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u},l={message:s,at:{url:this.translator.sourceURL,range:a},severity:"error"};this.messages.log(l)}}Fu.MalloyParserErrorHandler=nV;var k2={};Object.defineProperty(k2,"__esModule",{value:!0}),k2.exploreQueryWalkerBuilder=k2.ExploreQueryWalker=void 0;const RNe=I0;class rV{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}k2.ExploreQueryWalker=rV;function ONe(t,e){const n=new rV(t),r=n;return RNe.ParseTreeWalker.DEFAULT.walk(r,e),n}k2.exploreQueryWalkerBuilder=ONe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=Fu;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=k2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(TO);var Ne={};Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.CSVWriter=Ne.JSONWriter=Ne.DataWriter=Ne.DataRecord=Ne.DataArray=Ne.Result=Ne.ExploreMaterializer=Ne.SQLBlockMaterializer=Ne.PreparedResultMaterializer=Ne.QueryMaterializer=Ne.ModelMaterializer=Ne.SingleConnectionRuntime=Ne.ConnectionRuntime=Ne.Runtime=Ne.ExploreField=Ne.JoinRelationship=Ne.QueryField=Ne.Query=Ne.StringField=Ne.UnsupportedField=Ne.JSONField=Ne.BooleanField=Ne.NumberField=Ne.TimestampField=Ne.DateField=Ne.TimestampTimeframe=Ne.DateTimeframe=Ne.AtomicField=Ne.AtomicFieldType=Ne.Explore=Ne.SourceRelationship=Ne.FixedConnectionMap=Ne.InMemoryURLReader=Ne.EmptyURLReader=Ne.PreparedResult=Ne.DocumentCompletion=Ne.DocumentSymbol=Ne.DocumentPosition=Ne.DocumentRange=Ne.DocumentTablePath=Ne.Parse=Ne.PreparedQuery=Ne.Model=Ne.MalloyError=Ne.Malloy=void 0;const NNe=TO,nc=Nu,DNe=os,Ln=hl,AF=yp;class xn{static get version(){return"0.0.1"}static get log(){return xn._log||console}static setLogger(e){xn._log=e}static _parse(e,n,r){n===void 0&&(n=new URL("internal://internal.malloy"));let i=n;r!=null&&r.importBaseURL&&(i=r==null?void 0:r.importBaseURL);const s=new NNe.MalloyTranslator(n.toString(),i.toString(),{urls:{[n.toString()]:e}});return r!=null&&r.testEnvironment&&(s.allDialectsEnabled=!0),new sV(s)}static parse({url:e,urlReader:n,source:r,options:i}){if(r!==void 0)return xn._parse(r,e,i);if(n===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 n.readURL(e).then(s=>xn._parse(s,e,i))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o}){var u,a,l,c;let f;s&&(f=typeof s=="number"?s:Date.now());const x=r._translator;for(;;){const h=x.translate(i==null?void 0:i._modelDef);if(h.final){if(h.translated)return new v3(h.translated.modelDef,h.translated.queryList,h.translated.sqlBlocks,h.problems||[],[...(u=i==null?void 0:i.fromSources)!==null&&u!==void 0?u:[],...(a=h.fromSources)!==null&&a!==void 0?a:[]],p=>x.referenceAt(p),p=>x.importAt(p));if(o){const p={name:"modelDidNotCompile",exports:[],contents:{}},m=(i==null?void 0:i._modelDef)||p;return new v3(m,[],[],h.problems||[],[...(l=i==null?void 0:i.fromSources)!==null&&l!==void 0?l:[],...(c=h.fromSources)!==null&&c!==void 0?c:[]],g=>x.referenceAt(g),g=>x.importAt(g))}else{const p=h.problems||[],m=x.prettyErrors();throw new iV(`Error(s) compiling model:
1305
- ${m}`,p)}}else{if(h.urls)for(const m of h.urls)try{if(m.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const g=await e.readURL(new URL(m)),y={[m]:g};x.update({urls:y})}catch(g){x.update({errors:{urls:{[m]:g.message}}})}const{modelAnnotation:p}=x.modelAnnotation(i==null?void 0:i._modelDef);if(h.tables){const m=new Map;for(const g in h.tables){const{connectionName:y,tablePath:E}=h.tables[g],A=m.get(y);A===void 0?m.set(y,{[g]:E}):A[g]=E}for(const[g,y]of m)try{const E=await n.lookupConnection(g),{schemas:A,errors:v}=await E.fetchSchemaForTables(y,{refreshTimestamp:f,modelAnnotation:p});x.update({tables:A,errors:{tables:v}})}catch(E){const A={},v={};for(const S in y)v[S]=E.toString();x.update({tables:A,errors:{tables:v}})}}if(h.compileSQL){const m=h.compileSQL,g=m.connection;try{const y=await n.lookupConnection(g),E=xn.compileSQLBlock(h.partialModel,m),A=await y.fetchSchemaForSQLBlock(E,{refreshTimestamp:f,modelAnnotation:p});A.error&&x.update({errors:{compileSQL:{[E.name]:A.error}}}),A.structDef&&(0,nc.isSQLBlockStruct)(A.structDef)&&x.update({compileSQL:{[E.name]:A.structDef}})}catch(y){const E={};E[m.name]=y.toString(),x.update({errors:{compileSQL:E}})}}}}}static compileSQLBlock(e,n){let r,i="",s=!1;for(const a of n.select)if((0,nc.isSQLFragment)(a))i+=a.sql,s=a.sql.match(/\(\s*$/)!==null;else{if(!r){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");r=new nc.QueryModel(e)}const l=r.compileQuery(a,!1).sql;i+=s?l:`(${l})`,s=!1}const{name:o,connection:u}=n;return{type:"sqlBlock",name:o,connection:u,selectStr:i}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new T3({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new T3({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new Is(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new Nx(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Ne.Malloy=xn;class iV extends Error{constructor(e,n=[]){super(e),this.problems=n}}Ne.MalloyError=iV;let v3=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}tagParse(e){return Ln.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new P2(n,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.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new P2(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new P2(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new Is(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new Is(n))}get namedQueries(){const e=n=>n.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}};Ne.Model=v3;class P2{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=Ln.Tag.annotationToTag(this._modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){const n=new nc.QueryModel(this._modelDef).compileQuery(this._query);return new S3({...n,queryName:this.name||n.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Ne.PreparedQuery=P2;class sV{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new Y5(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new oV(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new uV(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Ne.Parse=sV;class oV{constructor(e){this._range=M2.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}}Ne.DocumentTablePath=oV;class M2{constructor(e,n){this._start=e,this._end=n}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 M2(new vF(e.start.line,e.start.character),new vF(e.end.line,e.end.character))}}Ne.DocumentRange=M2;class vF{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Ne.DocumentPosition=vF;class Y5{constructor(e){this._range=M2.fromJSON(e.range),this._lensRange=e.lensRange?M2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new Y5(n))}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}}Ne.DocumentSymbol=Y5;class uV{constructor(e){this.type=e.type,this.text=e.text}}Ne.DocumentCompletion=uV;class S3{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new S3(e,n)}tagParse(e){const n=Ln.Tag.annotationToTag(this.modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return Ln.Tag.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 resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],n={...e,name:this.inner.queryName||e.name};try{return new Is(n,this.sourceExplore)}catch{return new Is(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new Is(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Ne.PreparedResult=S3;class aV{async readURL(e){throw new Error("No files.")}}Ne.EmptyURLReader=aV;class FNe{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}Ne.InMemoryURLReader=FNe;class _3{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);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 _3(new Map(e.map(n=>[n.name,n])))}}Ne.FixedConnectionMap=_3;var rc;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(rc||(Ne.SourceRelationship=rc={}));class SF{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}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 n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Is}isQuery(){return this instanceof NF}}class Is extends SF{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,nc.FieldIsIntrinsic)(this._structDef)}isExploreField(){return!1}tagParse(e){return Ln.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=Ln.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new P2(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new v3(this.modelDef,[],[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if(r.type==="struct")return[i,new DF(r,this,s)];if(r.type==="turtle")return[i,new NF(r,this,s)];if(r.type==="string")return[i,new OF(r,this,s)];if(r.type==="number")return[i,new K5(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new K5({...r,type:"number"},this,s)]:[i,new _F(r,this,s)];if(r.type==="timestamp")return[i,new CF(r,this,s)];if(r.type==="boolean")return[i,new bF(r,this,s)];if(r.type==="json")return[i,new TF(r,this,s)];if(r.type==="sql native")return[i,new RF(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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 n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return rc.Many;case"one":return rc.One;case"cross":return rc.Cross;case"inline":return rc.Inline;case"nested":return rc.Nested;case"basetable":return rc.BaseTable}}hasParentExplore(){return this instanceof DF}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?Is.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?Is.fromJSON(e.sourceExplore):void 0;return new Is(e._structDef,n,r)}get location(){return this.structDef.location}}Ne.Explore=Is;var ea;(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"})(ea||(Ne.AtomicFieldType=ea={}));class ic extends SF{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return ea.String;case"boolean":return ea.Boolean;case"date":return ea.Date;case"timestamp":return ea.Timestamp;case"number":return ea.Number;case"json":return ea.Json;case"sql native":return ea.NativeUnsupported;case"error":return ea.Error}}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,nc.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,nc.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.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 OF}isNumber(){return this instanceof K5}isDate(){return this instanceof _F}isBoolean(){return this instanceof bF}isJSON(){return this instanceof TF}isTimestamp(){return this instanceof CF}isUnsupported(){return this instanceof RF}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Ne.AtomicField=ic;var Ox;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Ox||(Ne.DateTimeframe=Ox={}));var ta;(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"})(ta||(Ne.TimestampTimeframe=ta={}));class _F extends ic{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Ox.Day;case"week":return Ox.Week;case"month":return Ox.Month;case"quarter":return Ox.Quarter;case"year":return Ox.Year}}}Ne.DateField=_F;class CF extends ic{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return ta.Day;case"week":return ta.Week;case"month":return ta.Month;case"quarter":return ta.Quarter;case"year":return ta.Year;case"second":return ta.Second;case"hour":return ta.Hour;case"minute":return ta.Minute}}}Ne.TimestampField=CF;class K5 extends ic{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Ne.NumberField=K5;class bF extends ic{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Ne.BooleanField=bF;class TF extends ic{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Ne.JSONField=TF;class RF extends ic{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Ne.UnsupportedField=RF;class OF extends ic{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Ne.StringField=OF;class lV extends SF{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Ne.Query=lV;class NF extends lV{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return Ln.Tag.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}}Ne.QueryField=NF;var sc;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(sc||(Ne.JoinRelationship=sc={}));class DF extends Is{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return sc.OneToMany;case"many":case"cross":return sc.ManyToOne;case"inline":return sc.OneToOne;case"nested":return sc.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===sc.OneToOne}get isArray(){return this.joinRelationship!==sc.OneToOne}tagParse(e){return e=Ln.Tag.addModelScope(e,this._parentExplore.modelTag),Ln.Tag.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]:[]}}Ne.ExploreField=DF;class FF{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)BNe(i)?n=i:kNe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new aV),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new b3(this,async()=>{const s=e instanceof URL?await xn.parse({url:e,urlReader:this.urlReader,options:n}):xn.parse({source:e,options:n});return xn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i})})}_loadModelFromModelDef(e){return new b3(this,async()=>new v3(e,[],[],[],[]))}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Ne.Runtime=FF;class wNe extends FF{constructor(e,n){if(n===void 0){const r=e;super(_3.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,_3.fromArray(r)),this.rawConnections=r}}}Ne.ConnectionRuntime=wNe;class LNe extends FF{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,AF.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,AF.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,AF.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Ne.SingleConnectionRuntime=LNe;class C3{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e){return new cV(this.runtime,e)}makeExploreMaterializer(e){return new dV(this.runtime,e)}makePreparedResultMaterializer(e){return new fV(this.runtime,e)}makeSQLBlockMaterializer(e){return new xV(this.runtime,e)}}class b3 extends C3{loadFinalQuery(){return this.makeQueryMaterializer(async()=>(await this.materialize()).preparedQuery)}loadQueryByIndex(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e))}loadQueryByName(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e))}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await xn.parse({url:e,urlReader:s,options:n}):xn.parse({source:e,options:n}),a=await this.getModel();return(await xn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new b3(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await xn.parse({url:e,urlReader:r,options:n}):xn.parse({source:e,options:n}),o=await this.getModel();return await xn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache})})}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new nc.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1305
+ ${m}`,p)}}else{if(h.urls)for(const m of h.urls)try{if(m.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const g=await e.readURL(new URL(m)),y={[m]:g};x.update({urls:y})}catch(g){x.update({errors:{urls:{[m]:g.message}}})}const{modelAnnotation:p}=x.modelAnnotation(i==null?void 0:i._modelDef);if(h.tables){const m=new Map;for(const g in h.tables){const{connectionName:y,tablePath:E}=h.tables[g],A=m.get(y);A===void 0?m.set(y,{[g]:E}):A[g]=E}for(const[g,y]of m)try{const E=await n.lookupConnection(g),{schemas:A,errors:v}=await E.fetchSchemaForTables(y,{refreshTimestamp:f,modelAnnotation:p});x.update({tables:A,errors:{tables:v}})}catch(E){const A={},v={};for(const S in y)v[S]=E.toString();x.update({tables:A,errors:{tables:v}})}}if(h.compileSQL){const m=h.compileSQL,g=m.connection;try{const y=await n.lookupConnection(g),E=xn.compileSQLBlock(h.partialModel,m),A=await y.fetchSchemaForSQLBlock(E,{refreshTimestamp:f,modelAnnotation:p});A.error&&x.update({errors:{compileSQL:{[E.name]:A.error}}}),A.structDef&&(0,nc.isSQLBlockStruct)(A.structDef)&&x.update({compileSQL:{[E.name]:A.structDef}})}catch(y){const E={};E[m.name]=y.toString(),x.update({errors:{compileSQL:E}})}}}}}static compileSQLBlock(e,n){let r,i="",s=!1;for(const a of n.select)if((0,nc.isSQLFragment)(a))i+=a.sql,s=a.sql.match(/\(\s*$/)!==null;else{if(!r){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");r=new nc.QueryModel(e)}const l=r.compileQuery(a,!1).sql;i+=s?l:`(${l})`,s=!1}const{name:o,connection:u}=n;return{type:"sqlBlock",name:o,connection:u,selectStr:i}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new T3({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new T3({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new Is(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new Nx(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Ne.Malloy=xn;class iV extends Error{constructor(e,n=[]){super(e),this.problems=n}}Ne.MalloyError=iV;let v3=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}tagParse(e){return Ln.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new P2(n,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.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new P2(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new P2(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new Is(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new Is(n))}get namedQueries(){const e=n=>n.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}};Ne.Model=v3;class P2{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=Ln.Tag.annotationToTag(this._modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){const n=new nc.QueryModel(this._modelDef).compileQuery(this._query);return new S3({...n,queryName:this.name||n.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Ne.PreparedQuery=P2;class sV{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new Y5(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new oV(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new uV(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Ne.Parse=sV;class oV{constructor(e){this._range=M2.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}}Ne.DocumentTablePath=oV;class M2{constructor(e,n){this._start=e,this._end=n}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 M2(new vF(e.start.line,e.start.character),new vF(e.end.line,e.end.character))}}Ne.DocumentRange=M2;class vF{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Ne.DocumentPosition=vF;class Y5{constructor(e){this._range=M2.fromJSON(e.range),this._lensRange=e.lensRange?M2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new Y5(n))}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}}Ne.DocumentSymbol=Y5;class uV{constructor(e){this.type=e.type,this.text=e.text}}Ne.DocumentCompletion=uV;class S3{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new S3(e,n)}tagParse(e){const n=Ln.Tag.annotationToTag(this.modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return Ln.Tag.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 resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],n={...e,name:this.inner.queryName||e.name};try{return new Is(n,this.sourceExplore)}catch{return new Is(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new Is(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Ne.PreparedResult=S3;class aV{async readURL(e){throw new Error("No files.")}}Ne.EmptyURLReader=aV;class FNe{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}Ne.InMemoryURLReader=FNe;class _3{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);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 _3(new Map(e.map(n=>[n.name,n])))}}Ne.FixedConnectionMap=_3;var rc;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(rc||(Ne.SourceRelationship=rc={}));class SF{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}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 n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Is}isQuery(){return this instanceof NF}}class Is extends SF{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,nc.FieldIsIntrinsic)(this._structDef)}isExploreField(){return!1}tagParse(e){return Ln.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=Ln.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new P2(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new v3(this.modelDef,[],[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if(r.type==="struct")return[i,new DF(r,this,s)];if(r.type==="turtle")return[i,new NF(r,this,s)];if(r.type==="string")return[i,new OF(r,this,s)];if(r.type==="number")return[i,new K5(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new K5({...r,type:"number"},this,s)]:[i,new _F(r,this,s)];if(r.type==="timestamp")return[i,new CF(r,this,s)];if(r.type==="boolean")return[i,new bF(r,this,s)];if(r.type==="json")return[i,new TF(r,this,s)];if(r.type==="sql native")return[i,new RF(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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 n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return rc.Many;case"one":return rc.One;case"cross":return rc.Cross;case"inline":return rc.Inline;case"nested":return rc.Nested;case"basetable":return rc.BaseTable}}hasParentExplore(){return this instanceof DF}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?Is.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?Is.fromJSON(e.sourceExplore):void 0;return new Is(e._structDef,n,r)}get location(){return this.structDef.location}}Ne.Explore=Is;var ea;(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"})(ea||(Ne.AtomicFieldType=ea={}));class ic extends SF{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return ea.String;case"boolean":return ea.Boolean;case"date":return ea.Date;case"timestamp":return ea.Timestamp;case"number":return ea.Number;case"json":return ea.Json;case"sql native":return ea.NativeUnsupported;case"error":return ea.Error}}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,nc.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,nc.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.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 OF}isNumber(){return this instanceof K5}isDate(){return this instanceof _F}isBoolean(){return this instanceof bF}isJSON(){return this instanceof TF}isTimestamp(){return this instanceof CF}isUnsupported(){return this instanceof RF}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Ne.AtomicField=ic;var Ox;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Ox||(Ne.DateTimeframe=Ox={}));var ta;(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"})(ta||(Ne.TimestampTimeframe=ta={}));class _F extends ic{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Ox.Day;case"week":return Ox.Week;case"month":return Ox.Month;case"quarter":return Ox.Quarter;case"year":return Ox.Year}}}Ne.DateField=_F;class CF extends ic{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return ta.Day;case"week":return ta.Week;case"month":return ta.Month;case"quarter":return ta.Quarter;case"year":return ta.Year;case"second":return ta.Second;case"hour":return ta.Hour;case"minute":return ta.Minute}}}Ne.TimestampField=CF;class K5 extends ic{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Ne.NumberField=K5;class bF extends ic{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Ne.BooleanField=bF;class TF extends ic{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Ne.JSONField=TF;class RF extends ic{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Ne.UnsupportedField=RF;class OF extends ic{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Ne.StringField=OF;class lV extends SF{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Ne.Query=lV;class NF extends lV{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return Ln.Tag.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}}Ne.QueryField=NF;var sc;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(sc||(Ne.JoinRelationship=sc={}));class DF extends Is{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return sc.OneToMany;case"many":case"cross":return sc.ManyToOne;case"inline":return sc.OneToOne;case"nested":return sc.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===sc.OneToOne}get isArray(){return this.joinRelationship!==sc.OneToOne}tagParse(e){return e=Ln.Tag.addModelScope(e,this._parentExplore.modelTag),Ln.Tag.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]:[]}}Ne.ExploreField=DF;class FF{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)BNe(i)?n=i:kNe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new aV),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new b3(this,async()=>{const s=e instanceof URL?await xn.parse({url:e,urlReader:this.urlReader,options:n}):xn.parse({source:e,options:n});return xn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i})})}_loadModelFromModelDef(e){return new b3(this,async()=>new v3(e,[],[],[],[]))}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Ne.Runtime=FF;class wNe extends FF{constructor(e,n){if(n===void 0){const r=e;super(_3.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,_3.fromArray(r)),this.rawConnections=r}}}Ne.ConnectionRuntime=wNe;class LNe extends FF{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,AF.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,AF.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,AF.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Ne.SingleConnectionRuntime=LNe;class C3{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e){return new cV(this.runtime,e)}makeExploreMaterializer(e){return new dV(this.runtime,e)}makePreparedResultMaterializer(e){return new fV(this.runtime,e)}makeSQLBlockMaterializer(e){return new xV(this.runtime,e)}}class b3 extends C3{loadFinalQuery(){return this.makeQueryMaterializer(async()=>(await this.materialize()).preparedQuery)}loadQueryByIndex(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e))}loadQueryByName(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e))}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await xn.parse({url:e,urlReader:s,options:n}):xn.parse({source:e,options:n}),a=await this.getModel();return(await xn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new b3(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await xn.parse({url:e,urlReader:r,options:n}):xn.parse({source:e,options:n}),o=await this.getModel();return await xn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError})})}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new nc.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1306
1306
  run: ${e}
1307
1307
  -> ${o}
1308
1308
  -> {
@@ -52864,7 +52864,8 @@ class u3 extends hE {
52864
52864
  connections: i,
52865
52865
  parse: s,
52866
52866
  model: o,
52867
- refreshSchemaCache: n == null ? void 0 : n.refreshSchemaCache
52867
+ refreshSchemaCache: n == null ? void 0 : n.refreshSchemaCache,
52868
+ noThrowOnError: n == null ? void 0 : n.noThrowOnError
52868
52869
  });
52869
52870
  });
52870
52871
  }
@@ -1302,7 +1302,7 @@ QUERY: ${(0,jve.inspect)(n,{breakLength:72,depth:1/0})}`)}return{...lQ.ErrorFact
1302
1302
  | ${" ".repeat(u)}^`)}else i=`line ${o+1}: char ${u}: ${r.message}`}n!==s&&(i=`FILE: ${s}
1303
1303
  `+i,n=s),e!==""?e=`${e}
1304
1304
  ${i}`:e=i}return e}childRequest(e){var n;const r=decodeURI(new URL(e,this.sourceURL).toString()),i=(n=this.childTranslators.get(r))===null||n===void 0?void 0:n.translate();if(i!=null&&i.compileSQL)return{compileSQL:i.compileSQL,partialModel:i.partialModel}}getChildExports(e){const n={},r=decodeURI(new URL(e,this.sourceURL).toString()),i=this.childTranslators.get(r);if(i&&i.translate().translated)for(const o of i.modelDef.exports){const u=i.modelDef.contents[o];(u.type==="struct"||u.type==="query")&&(n[o]=u)}return n}translate(e){if(this.finalAnswer)return this.finalAnswer;const n=this.translateStep.step(this,e);return n.final&&(this.finalAnswer=n),n}importAt(e){for(let n=0;n<this.imports.length;n++){const r=this.imports[n];if((0,dNe.locationContainsPosition)(r.location,e))return r}}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 this.rangeFromTokens(e.start,e.stop||e.start)}rangeFromTokens(e,n){const r={line:e.line-1,character:e.charPositionInLine};if(this.parseStep.sourceInfo&&n.stopIndex!==-1){const i=this.parseStep.sourceInfo.lines.length-1;for(let s=e.line-1;s<=i;s++){const o=this.parseStep.sourceInfo.at[s];if(n.stopIndex>=o.begin&&n.stopIndex<=o.end)return{start:r,end:{line:s,character:n.stopIndex-o.begin+1}}}return{start:r,end:{line:i,character:this.parseStep.sourceInfo.lines[i].length}}}return{start:r,end:r}}rangeFromToken(e){return this.rangeFromTokens(e,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const n=this.compilerFlags.tag("experimental");return n!==void 0&&(n.bare()||n.has("dialect",e))}}Fu.MalloyTranslation=yF;class eV extends yF{constructor(e,n){super(e),this.root=n}}Fu.MalloyChildTranslator=eV;class TNe extends yF{constructor(e,n=null,r=null){super(e,n),this.schemaZone=new mF.Zone,this.importZone=new mF.Zone,this.sqlQueryZone=new mF.Zone,this.logger=new uNe.MessageLog,this.root=this,r&&this.update(r)}update(e){var n,r,i;this.schemaZone.updateFrom(e.tables,(n=e.errors)===null||n===void 0?void 0:n.tables),this.importZone.updateFrom(e.urls,(r=e.errors)===null||r===void 0?void 0:r.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(i=e.errors)===null||i===void 0?void 0:i.compileSQL)}}Fu.MalloyTranslator=TNe;class tV{constructor(e,n){this.translator=e,this.messages=n}syntaxError(e,n,r,i,s,o){const u={line:r-1,character:i},a=n?this.translator.rangeFromToken(n):{start:u,end:u},l={message:s,at:{url:this.translator.sourceURL,range:a},severity:"error"};this.messages.log(l)}}Fu.MalloyParserErrorHandler=tV;var k2={};Object.defineProperty(k2,"__esModule",{value:!0}),k2.exploreQueryWalkerBuilder=k2.ExploreQueryWalker=void 0;const RNe=I0;class nV{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(n=>n.range[0]===void 0||n.range[1]===void 0?!1:n.range[0]<=e&&n.range[1]>=e)}filterAtOffset(e){const n=this.exploreQueryAtOffset(e);if(n)return n.filterRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}hasFilterListAtOffset(e){const n=this.exploreQueryAtOffset(e);return n?!!n.filterLists.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}k2.ExploreQueryWalker=nV;function ONe(t,e){const n=new nV(t),r=n;return RNe.ParseTreeWalker.DEFAULT.walk(r,e),n}k2.exploreQueryWalkerBuilder=ONe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.exploreQueryWalkerBuilder=t.MalloyTranslator=void 0;var e=Fu;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}});var n=k2;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return n.exploreQueryWalkerBuilder}})}(bO);var Ne={};Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.CSVWriter=Ne.JSONWriter=Ne.DataWriter=Ne.DataRecord=Ne.DataArray=Ne.Result=Ne.ExploreMaterializer=Ne.SQLBlockMaterializer=Ne.PreparedResultMaterializer=Ne.QueryMaterializer=Ne.ModelMaterializer=Ne.SingleConnectionRuntime=Ne.ConnectionRuntime=Ne.Runtime=Ne.ExploreField=Ne.JoinRelationship=Ne.QueryField=Ne.Query=Ne.StringField=Ne.UnsupportedField=Ne.JSONField=Ne.BooleanField=Ne.NumberField=Ne.TimestampField=Ne.DateField=Ne.TimestampTimeframe=Ne.DateTimeframe=Ne.AtomicField=Ne.AtomicFieldType=Ne.Explore=Ne.SourceRelationship=Ne.FixedConnectionMap=Ne.InMemoryURLReader=Ne.EmptyURLReader=Ne.PreparedResult=Ne.DocumentCompletion=Ne.DocumentSymbol=Ne.DocumentPosition=Ne.DocumentRange=Ne.DocumentTablePath=Ne.Parse=Ne.PreparedQuery=Ne.Model=Ne.MalloyError=Ne.Malloy=void 0;const NNe=bO,nc=Nu,DNe=os,Ln=hl,EF=gp;class xn{static get version(){return"0.0.1"}static get log(){return xn._log||console}static setLogger(e){xn._log=e}static _parse(e,n,r){n===void 0&&(n=new URL("internal://internal.malloy"));let i=n;r!=null&&r.importBaseURL&&(i=r==null?void 0:r.importBaseURL);const s=new NNe.MalloyTranslator(n.toString(),i.toString(),{urls:{[n.toString()]:e}});return r!=null&&r.testEnvironment&&(s.allDialectsEnabled=!0),new iV(s)}static parse({url:e,urlReader:n,source:r,options:i}){if(r!==void 0)return xn._parse(r,e,i);if(n===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 n.readURL(e).then(s=>xn._parse(s,e,i))}static async compile({urlReader:e,connections:n,parse:r,model:i,refreshSchemaCache:s,noThrowOnError:o}){var u,a,l,c;let f;s&&(f=typeof s=="number"?s:Date.now());const x=r._translator;for(;;){const h=x.translate(i==null?void 0:i._modelDef);if(h.final){if(h.translated)return new E3(h.translated.modelDef,h.translated.queryList,h.translated.sqlBlocks,h.problems||[],[...(u=i==null?void 0:i.fromSources)!==null&&u!==void 0?u:[],...(a=h.fromSources)!==null&&a!==void 0?a:[]],p=>x.referenceAt(p),p=>x.importAt(p));if(o){const p={name:"modelDidNotCompile",exports:[],contents:{}},m=(i==null?void 0:i._modelDef)||p;return new E3(m,[],[],h.problems||[],[...(l=i==null?void 0:i.fromSources)!==null&&l!==void 0?l:[],...(c=h.fromSources)!==null&&c!==void 0?c:[]],g=>x.referenceAt(g),g=>x.importAt(g))}else{const p=h.problems||[],m=x.prettyErrors();throw new rV(`Error(s) compiling model:
1305
- ${m}`,p)}}else{if(h.urls)for(const m of h.urls)try{if(m.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const g=await e.readURL(new URL(m)),y={[m]:g};x.update({urls:y})}catch(g){x.update({errors:{urls:{[m]:g.message}}})}const{modelAnnotation:p}=x.modelAnnotation(i==null?void 0:i._modelDef);if(h.tables){const m=new Map;for(const g in h.tables){const{connectionName:y,tablePath:E}=h.tables[g],A=m.get(y);A===void 0?m.set(y,{[g]:E}):A[g]=E}for(const[g,y]of m)try{const E=await n.lookupConnection(g),{schemas:A,errors:v}=await E.fetchSchemaForTables(y,{refreshTimestamp:f,modelAnnotation:p});x.update({tables:A,errors:{tables:v}})}catch(E){const A={},v={};for(const S in y)v[S]=E.toString();x.update({tables:A,errors:{tables:v}})}}if(h.compileSQL){const m=h.compileSQL,g=m.connection;try{const y=await n.lookupConnection(g),E=xn.compileSQLBlock(h.partialModel,m),A=await y.fetchSchemaForSQLBlock(E,{refreshTimestamp:f,modelAnnotation:p});A.error&&x.update({errors:{compileSQL:{[E.name]:A.error}}}),A.structDef&&(0,nc.isSQLBlockStruct)(A.structDef)&&x.update({compileSQL:{[E.name]:A.structDef}})}catch(y){const E={};E[m.name]=y.toString(),x.update({errors:{compileSQL:E}})}}}}}static compileSQLBlock(e,n){let r,i="",s=!1;for(const a of n.select)if((0,nc.isSQLFragment)(a))i+=a.sql,s=a.sql.match(/\(\s*$/)!==null;else{if(!r){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");r=new nc.QueryModel(e)}const l=r.compileQuery(a,!1).sql;i+=s?l:`(${l})`,s=!1}const{name:o,connection:u}=n;return{type:"sqlBlock",name:o,connection:u,selectStr:i}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new C3({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new C3({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new Is(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new Nx(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Ne.Malloy=xn;class rV extends Error{constructor(e,n=[]){super(e),this.problems=n}}Ne.MalloyError=rV;let E3=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}tagParse(e){return Ln.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new P2(n,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.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new P2(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new P2(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new Is(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new Is(n))}get namedQueries(){const e=n=>n.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}};Ne.Model=E3;class P2{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=Ln.Tag.annotationToTag(this._modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){const n=new nc.QueryModel(this._modelDef).compileQuery(this._query);return new A3({...n,queryName:this.name||n.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Ne.PreparedQuery=P2;class iV{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new V5(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new sV(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new oV(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Ne.Parse=iV;class sV{constructor(e){this._range=M2.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}}Ne.DocumentTablePath=sV;class M2{constructor(e,n){this._start=e,this._end=n}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 M2(new AF(e.start.line,e.start.character),new AF(e.end.line,e.end.character))}}Ne.DocumentRange=M2;class AF{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Ne.DocumentPosition=AF;class V5{constructor(e){this._range=M2.fromJSON(e.range),this._lensRange=e.lensRange?M2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new V5(n))}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}}Ne.DocumentSymbol=V5;class oV{constructor(e){this.type=e.type,this.text=e.text}}Ne.DocumentCompletion=oV;class A3{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new A3(e,n)}tagParse(e){const n=Ln.Tag.annotationToTag(this.modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return Ln.Tag.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 resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],n={...e,name:this.inner.queryName||e.name};try{return new Is(n,this.sourceExplore)}catch{return new Is(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new Is(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Ne.PreparedResult=A3;class uV{async readURL(e){throw new Error("No files.")}}Ne.EmptyURLReader=uV;class FNe{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}Ne.InMemoryURLReader=FNe;class v3{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);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 v3(new Map(e.map(n=>[n.name,n])))}}Ne.FixedConnectionMap=v3;var rc;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(rc||(Ne.SourceRelationship=rc={}));class vF{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}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 n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Is}isQuery(){return this instanceof OF}}class Is extends vF{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,nc.FieldIsIntrinsic)(this._structDef)}isExploreField(){return!1}tagParse(e){return Ln.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=Ln.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new P2(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new E3(this.modelDef,[],[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if(r.type==="struct")return[i,new NF(r,this,s)];if(r.type==="turtle")return[i,new OF(r,this,s)];if(r.type==="string")return[i,new RF(r,this,s)];if(r.type==="number")return[i,new Y5(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new Y5({...r,type:"number"},this,s)]:[i,new SF(r,this,s)];if(r.type==="timestamp")return[i,new _F(r,this,s)];if(r.type==="boolean")return[i,new CF(r,this,s)];if(r.type==="json")return[i,new bF(r,this,s)];if(r.type==="sql native")return[i,new TF(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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 n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return rc.Many;case"one":return rc.One;case"cross":return rc.Cross;case"inline":return rc.Inline;case"nested":return rc.Nested;case"basetable":return rc.BaseTable}}hasParentExplore(){return this instanceof NF}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?Is.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?Is.fromJSON(e.sourceExplore):void 0;return new Is(e._structDef,n,r)}get location(){return this.structDef.location}}Ne.Explore=Is;var ea;(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"})(ea||(Ne.AtomicFieldType=ea={}));class ic extends vF{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return ea.String;case"boolean":return ea.Boolean;case"date":return ea.Date;case"timestamp":return ea.Timestamp;case"number":return ea.Number;case"json":return ea.Json;case"sql native":return ea.NativeUnsupported;case"error":return ea.Error}}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,nc.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,nc.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.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 RF}isNumber(){return this instanceof Y5}isDate(){return this instanceof SF}isBoolean(){return this instanceof CF}isJSON(){return this instanceof bF}isTimestamp(){return this instanceof _F}isUnsupported(){return this instanceof TF}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Ne.AtomicField=ic;var Ox;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Ox||(Ne.DateTimeframe=Ox={}));var ta;(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"})(ta||(Ne.TimestampTimeframe=ta={}));class SF extends ic{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Ox.Day;case"week":return Ox.Week;case"month":return Ox.Month;case"quarter":return Ox.Quarter;case"year":return Ox.Year}}}Ne.DateField=SF;class _F extends ic{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return ta.Day;case"week":return ta.Week;case"month":return ta.Month;case"quarter":return ta.Quarter;case"year":return ta.Year;case"second":return ta.Second;case"hour":return ta.Hour;case"minute":return ta.Minute}}}Ne.TimestampField=_F;class Y5 extends ic{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Ne.NumberField=Y5;class CF extends ic{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Ne.BooleanField=CF;class bF extends ic{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Ne.JSONField=bF;class TF extends ic{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Ne.UnsupportedField=TF;class RF extends ic{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Ne.StringField=RF;class aV extends vF{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Ne.Query=aV;class OF extends aV{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return Ln.Tag.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}}Ne.QueryField=OF;var sc;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(sc||(Ne.JoinRelationship=sc={}));class NF extends Is{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return sc.OneToMany;case"many":case"cross":return sc.ManyToOne;case"inline":return sc.OneToOne;case"nested":return sc.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===sc.OneToOne}get isArray(){return this.joinRelationship!==sc.OneToOne}tagParse(e){return e=Ln.Tag.addModelScope(e,this._parentExplore.modelTag),Ln.Tag.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]:[]}}Ne.ExploreField=NF;class DF{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)BNe(i)?n=i:kNe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new uV),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new _3(this,async()=>{const s=e instanceof URL?await xn.parse({url:e,urlReader:this.urlReader,options:n}):xn.parse({source:e,options:n});return xn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i})})}_loadModelFromModelDef(e){return new _3(this,async()=>new E3(e,[],[],[],[]))}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Ne.Runtime=DF;class wNe extends DF{constructor(e,n){if(n===void 0){const r=e;super(v3.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,v3.fromArray(r)),this.rawConnections=r}}}Ne.ConnectionRuntime=wNe;class LNe extends DF{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,EF.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,EF.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,EF.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Ne.SingleConnectionRuntime=LNe;class S3{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e){return new lV(this.runtime,e)}makeExploreMaterializer(e){return new xV(this.runtime,e)}makePreparedResultMaterializer(e){return new cV(this.runtime,e)}makeSQLBlockMaterializer(e){return new fV(this.runtime,e)}}class _3 extends S3{loadFinalQuery(){return this.makeQueryMaterializer(async()=>(await this.materialize()).preparedQuery)}loadQueryByIndex(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e))}loadQueryByName(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e))}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await xn.parse({url:e,urlReader:s,options:n}):xn.parse({source:e,options:n}),a=await this.getModel();return(await xn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new _3(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await xn.parse({url:e,urlReader:r,options:n}):xn.parse({source:e,options:n}),o=await this.getModel();return await xn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache})})}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new nc.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1305
+ ${m}`,p)}}else{if(h.urls)for(const m of h.urls)try{if(m.startsWith("internal://"))throw new Error("In order to use relative imports, you must compile a file via a URL.");const g=await e.readURL(new URL(m)),y={[m]:g};x.update({urls:y})}catch(g){x.update({errors:{urls:{[m]:g.message}}})}const{modelAnnotation:p}=x.modelAnnotation(i==null?void 0:i._modelDef);if(h.tables){const m=new Map;for(const g in h.tables){const{connectionName:y,tablePath:E}=h.tables[g],A=m.get(y);A===void 0?m.set(y,{[g]:E}):A[g]=E}for(const[g,y]of m)try{const E=await n.lookupConnection(g),{schemas:A,errors:v}=await E.fetchSchemaForTables(y,{refreshTimestamp:f,modelAnnotation:p});x.update({tables:A,errors:{tables:v}})}catch(E){const A={},v={};for(const S in y)v[S]=E.toString();x.update({tables:A,errors:{tables:v}})}}if(h.compileSQL){const m=h.compileSQL,g=m.connection;try{const y=await n.lookupConnection(g),E=xn.compileSQLBlock(h.partialModel,m),A=await y.fetchSchemaForSQLBlock(E,{refreshTimestamp:f,modelAnnotation:p});A.error&&x.update({errors:{compileSQL:{[E.name]:A.error}}}),A.structDef&&(0,nc.isSQLBlockStruct)(A.structDef)&&x.update({compileSQL:{[E.name]:A.structDef}})}catch(y){const E={};E[m.name]=y.toString(),x.update({errors:{compileSQL:E}})}}}}}static compileSQLBlock(e,n){let r,i="",s=!1;for(const a of n.select)if((0,nc.isSQLFragment)(a))i+=a.sql,s=a.sql.match(/\(\s*$/)!==null;else{if(!r){if(!e)throw new Error("Internal error: Partial model missing when compiling SQL block");r=new nc.QueryModel(e)}const l=r.compileQuery(a,!1).sql;i+=s?l:`(${l})`,s=!1}const{name:o,connection:u}=n;return{type:"sqlBlock",name:o,connection:u,selectStr:i}}static async run({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(!i){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);i=await e.lookupConnection(u)}if(r&&o){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const u=await i.runSQL(o.selectStr);return new C3({structs:[r],sql:o.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:o.name,malloy:"",connectionName:r.structRelationship.connectionName,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{}})}else if(n){const u=await i.runSQL(n.sql,s);return new C3({...n._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},n._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:n,sqlStruct:r,connection:i,options:s}){const o=r==null?void 0:r.structSource.sqlBlock;if(o===void 0&&n===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(o==null?void 0:o.connection)||(n==null?void 0:n.connectionName);if(i===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");i=await e.lookupConnection(u)}if(!i.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(r){if(r.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");l=new Is(r),a=r.structSource.sqlBlock.selectStr}else if(n!==void 0)l=n.resultExplore,a=n.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of i.runSQLStream(a,s))yield new Nx(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:n,sqlStruct:r}){const i=r==null?void 0:r.structSource.sqlBlock;if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(n==null?void 0:n.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i==null?void 0:i.selectStr);if(n)return await o.estimateQueryCost(n==null?void 0:n.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}}Ne.Malloy=xn;class rV extends Error{constructor(e,n=[]){super(e),this.problems=n}}Ne.MalloyError=rV;let E3=class{constructor(e,n,r,i,s,o=()=>{},u=()=>{}){this.modelDef=e,this.queryList=n,this.sqlBlocks=r,this.problems=i,this.fromSources=s,this._referenceAt=o,this._importAt=u}tagParse(e){return Ln.Tag.annotationToTag(this.modelDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.modelDef.annotation,e)}getReference(e){return this._referenceAt(e)}getImport(e){return this._importAt(e)}getPreparedQueryByName(e){const n=this.modelDef.contents[e];if((n==null?void 0:n.type)==="query")return new P2(n,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.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new P2(this.queryList[e],this.modelDef,this.problems)}getSQLBlockByName(e){const n=this.sqlBlocks.find(r=>r.as===e);if(n===void 0)throw new Error(`No SQL Block named '${e}'`);return n}getSQLBlockByIndex(e){const n=this.sqlBlocks[e];if(n===void 0)throw new Error(`No SQL Block at index ${e}`);return n}get preparedQuery(){if(this.queryList.length===0)throw new Error("Model has no queries.");return new P2(this.queryList[this.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const n=this.modelDef.contents[e];if(n.type==="struct")return new Is(n);throw new Error("'name' is not an explore")}get explores(){const e=n=>n.type==="struct";return Object.values(this.modelDef.contents).filter(e).map(n=>new Is(n))}get namedQueries(){const e=n=>n.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}};Ne.Model=E3;class P2{constructor(e,n,r,i){this.problems=r,this.name=i,this._query=e,this._modelDef=n}tagParse(e){const n=Ln.Tag.annotationToTag(this._modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this._query.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._query.annotation,e)}get preparedResult(){const n=new nc.QueryModel(this._modelDef).compileQuery(this._query);return new A3({...n,queryName:this.name||n.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,n=typeof e=="string"?this._modelDef.contents[e]:e;if(n.type!=="struct")throw new Error("Invalid source for query");return n.dialect}getFlattenedQuery(e){return this}}Ne.PreparedQuery=P2;class iV{constructor(e){this.translator=e}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new V5(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(r=>new sV(r))}get _translator(){return this.translator}completions(e){return(this.translator.completions(e).completions||[]).map(n=>new oV(n))}helpContext(e){return this.translator.helpContext(e).helpContext}}Ne.Parse=iV;class sV{constructor(e){this._range=M2.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}}Ne.DocumentTablePath=sV;class M2{constructor(e,n){this._start=e,this._end=n}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 M2(new AF(e.start.line,e.start.character),new AF(e.end.line,e.end.character))}}Ne.DocumentRange=M2;class AF{constructor(e,n){this._line=e,this._character=n}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}Ne.DocumentPosition=AF;class V5{constructor(e){this._range=M2.fromJSON(e.range),this._lensRange=e.lensRange?M2.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(n=>new V5(n))}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}}Ne.DocumentSymbol=V5;class oV{constructor(e){this.type=e.type,this.text=e.text}}Ne.DocumentCompletion=oV;class A3{constructor(e,n){this.modelDef=n,this.inner=e}static fromJson({query:e,modelDef:n}){if(!e||!n)throw new Error("Missing required properties in JSON data");return new A3(e,n)}tagParse(e){const n=Ln.Tag.annotationToTag(this.modelDef.annotation).tag;return e=Ln.Tag.addModelScope(e,n),Ln.Tag.annotationToTag(this.inner.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return Ln.Tag.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 resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],n={...e,name:this.inner.queryName||e.name};try{return new Is(n,this.sourceExplore)}catch{return new Is(n)}}get sourceExplore(){const e=this.inner.sourceExplore,n=this.modelDef.contents[e];if(n===void 0)throw new Error("Malformed query result.");if(n.type==="struct")return new Is(n);throw new Error(`'${e} is not an explore`)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}Ne.PreparedResult=A3;class uV{async readURL(e){throw new Error("No files.")}}Ne.EmptyURLReader=uV;class FNe{constructor(e){this.files=e}async readURL(e){const n=this.files.get(e.toString());if(n!==void 0)return Promise.resolve(n);throw new Error(`File not found '${e}'`)}}Ne.InMemoryURLReader=FNe;class v3{constructor(e,n){this.connections=e,this.defaultConnectionName=n}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const n=this.connections.get(e);if(n!==void 0)return Promise.resolve(n);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 v3(new Map(e.map(n=>[n.name,n])))}}Ne.FixedConnectionMap=v3;var rc;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(rc||(Ne.SourceRelationship=rc={}));class vF{constructor(e,n,r){this._name=e,this._parent=n,this._source=r}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 n=this._parent;for(;n;)e.unshift(n.name),n=n._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Is}isQuery(){return this instanceof OF}}class Is extends vF{constructor(e,n,r){super(e.as||e.name,n,r),this._structDef=e,this._parentExplore=n,this.sourceExplore=r}get source(){return this.sourceExplore}isIntrinsic(){return(0,nc.FieldIsIntrinsic)(this._structDef)}isExploreField(){return!1}tagParse(e){return Ln.Tag.annotationToTag(this._structDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=Ln.Tag.annotationToTag(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const n={type:"query",structRef:this.structDef,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new P2(n,this.modelDef,[],e)}get modelDef(){return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef}}}getSingleExploreModel(){return new E3(this.modelDef,[],[],[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const n=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(r=>{const i=r.as||r.name,s=n.get(r.name);if(r.type==="struct")return[i,new NF(r,this,s)];if(r.type==="turtle")return[i,new OF(r,this,s)];if(r.type==="string")return[i,new RF(r,this,s)];if(r.type==="number")return[i,new Y5(r,this,s)];if(r.type==="date")return r.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(r.timeframe)?[i,new Y5({...r,type:"number"},this,s)]:[i,new SF(r,this,s)];if(r.type==="timestamp")return[i,new _F(r,this,s)];if(r.type==="boolean")return[i,new CF(r,this,s)];if(r.type==="json")return[i,new bF(r,this,s)];if(r.type==="sql native")return[i,new TF(r,this,s)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,n;if(!this._allFieldsWithOrder){const r=[...((n=(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.orderBy)===null||n===void 0?void 0:n.map(s=>{if(typeof s.field=="string")return{field:this.fieldMap.get(s.field),dir:s.dir};throw new Error("Does not support mapping order by from number.")}))||[]],i=new Set(r.map(s=>s.field.name));this._allFieldsWithOrder=[...r,...this.allFields.filter(s=>!i.has(s.name)).map(s=>({field:s,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 n=this.fieldMap.get(e);if(n===void 0)throw new Error(`No such field ${e}.`);return n}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){return this.structDef.primaryKey}get parentExplore(){return this._parentExplore}get sourceRelationship(){switch(this.structDef.structRelationship.type){case"many":return rc.Many;case"one":return rc.One;case"cross":return rc.Cross;case"inline":return rc.Inline;case"nested":return rc.Nested;case"basetable":return rc.BaseTable}}hasParentExplore(){return this instanceof NF}get filters(){var e;return((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]}get limit(){var e;return(e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.limit}get structDef(){return this._structDef}get queryTimezone(){return this.structDef.queryTimezone}toJSON(){var e,n;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(n=this._parentExplore)===null||n===void 0?void 0:n.toJSON()}}static fromJSON(e){const n=e._parentExplore!==void 0?Is.fromJSON(e._parentExplore):void 0,r=e.sourceExplore!==void 0?Is.fromJSON(e.sourceExplore):void 0;return new Is(e._structDef,n,r)}get location(){return this.structDef.location}}Ne.Explore=Is;var ea;(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"})(ea||(Ne.AtomicFieldType=ea={}));class ic extends vF{constructor(e,n,r){super(e.as||e.name,n,r),this.fieldTypeDef=e,this.parent=n}get type(){switch(this.fieldTypeDef.type){case"string":return ea.String;case"boolean":return ea.Boolean;case"date":return ea.Date;case"timestamp":return ea.Timestamp;case"number":return ea.Number;case"json":return ea.Json;case"sql native":return ea.NativeUnsupported;case"error":return ea.Error}}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.fieldTypeDef.annotation,e)}getTaglines(e){return Ln.Tag.annotationToTaglines(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,nc.FieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,nc.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,n;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((n=this.fieldTypeDef.resultMetadata)===null||n===void 0?void 0:n.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 RF}isNumber(){return this instanceof Y5}isDate(){return this instanceof SF}isBoolean(){return this instanceof CF}isJSON(){return this instanceof bF}isTimestamp(){return this instanceof _F}isUnsupported(){return this instanceof TF}get parentExplore(){return this.parent}get expression(){const e=".",n=this.fieldTypeDef.resultMetadata;return(n==null?void 0:n.sourceExpression)||(n!=null&&n.sourceField.includes(e)?n==null?void 0:n.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}Ne.AtomicField=ic;var Ox;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Ox||(Ne.DateTimeframe=Ox={}));var ta;(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"})(ta||(Ne.TimestampTimeframe=ta={}));class SF extends ic{constructor(e,n,r){super(e,n,r),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Ox.Day;case"week":return Ox.Week;case"month":return Ox.Month;case"quarter":return Ox.Quarter;case"year":return Ox.Year}}}Ne.DateField=SF;class _F extends ic{constructor(e,n,r){super(e,n,r),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return ta.Day;case"week":return ta.Week;case"month":return ta.Month;case"quarter":return ta.Quarter;case"year":return ta.Year;case"second":return ta.Second;case"hour":return ta.Hour;case"minute":return ta.Minute}}}Ne.TimestampField=_F;class Y5 extends ic{constructor(e,n,r){super(e,n,r),this.fieldNumberDef=e}}Ne.NumberField=Y5;class CF extends ic{constructor(e,n,r){super(e,n,r),this.fieldBooleanDef=e}}Ne.BooleanField=CF;class bF extends ic{constructor(e,n,r){super(e,n,r),this.fieldJSONDef=e}}Ne.JSONField=bF;class TF extends ic{constructor(e,n,r){super(e,n,r),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}Ne.UnsupportedField=TF;class RF extends ic{constructor(e,n,r){super(e,n,r),this.fieldStringDef=e}}Ne.StringField=RF;class aV extends vF{constructor(e,n,r){super(e.as||e.name,n,r),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}Ne.Query=aV;class OF extends aV{constructor(e,n,r){super(e,n,r),this.parent=n}tagParse(e){return e=Ln.Tag.addModelScope(e,this.parent.modelTag),Ln.Tag.annotationToTag(this.turtleDef.annotation,e)}getTaglines(e){return Ln.Tag.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}}Ne.QueryField=OF;var sc;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(sc||(Ne.JoinRelationship=sc={}));class NF extends Is{constructor(e,n,r){super(e,n,r),this._parentExplore=n}get joinRelationship(){switch(this.structDef.structRelationship.type){case"one":return sc.OneToMany;case"many":case"cross":return sc.ManyToOne;case"inline":return sc.OneToOne;case"nested":return sc.ManyToOne;default:throw new Error("A source field must have a join relationship.")}}get isRecord(){return this.joinRelationship===sc.OneToOne}get isArray(){return this.joinRelationship!==sc.OneToOne}tagParse(e){return e=Ln.Tag.addModelScope(e,this._parentExplore.modelTag),Ln.Tag.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]:[]}}Ne.ExploreField=NF;class DF{constructor(...e){this.isTestRuntime=!1;let n,r;for(const i of e)BNe(i)?n=i:kNe(i)?r=i:r={lookupConnection:()=>Promise.resolve(i)};if(n===void 0&&(n=new uV),r===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");this._urlReader=n,this._connections=r}get urlReader(){return this._urlReader}get connections(){return this._connections}loadModel(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new _3(this,async()=>{const s=e instanceof URL?await xn.parse({url:e,urlReader:this.urlReader,options:n}):xn.parse({source:e,options:n});return xn.compile({urlReader:this.urlReader,connections:this.connections,parse:s,refreshSchemaCache:r,noThrowOnError:i})})}_loadModelFromModelDef(e){return new _3(this,async()=>new E3(e,[],[],[],[]))}loadQuery(e,n){return this.loadModel(e,n).loadFinalQuery()}loadQueryByIndex(e,n,r){return this.loadModel(e,r).loadQueryByIndex(n)}loadQueryByName(e,n,r){return this.loadModel(e,r).loadQueryByName(n)}loadSQLBlockByName(e,n,r){return this.loadModel(e,r).loadSQLBlockByName(n)}loadSQLBlockByIndex(e,n,r){return this.loadModel(e,r).loadSQLBlockByIndex(n)}getModel(e,n){return this.loadModel(e,n).getModel()}getQuery(e,n){return this.loadQuery(e,n).getPreparedQuery()}getQueryByIndex(e,n,r){return this.loadQueryByIndex(e,n,r).getPreparedQuery()}getQueryByName(e,n,r){return this.loadQueryByName(e,n,r).getPreparedQuery()}getSQLBlockByName(e,n,r){return this.loadSQLBlockByName(e,n,r).getSQLBlock()}getSQLBlockByIndex(e,n,r){return this.loadSQLBlockByIndex(e,n,r).getSQLBlock()}}Ne.Runtime=DF;class wNe extends DF{constructor(e,n){if(n===void 0){const r=e;super(v3.fromArray(r)),this.rawConnections=r}else{const r=n;super(e,v3.fromArray(r)),this.rawConnections=r}}}Ne.ConnectionRuntime=wNe;class LNe extends DF{constructor(e,n){if(n===void 0){const r=e;super(r),this.connection=r}else{const r=n;super(e,r),this.connection=r}}get supportsNesting(){return(0,EF.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,EF.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,EF.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}Ne.SingleConnectionRuntime=LNe;class S3{constructor(e,n){this.runtime=e,this._materialize=n}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e){return new lV(this.runtime,e)}makeExploreMaterializer(e){return new xV(this.runtime,e)}makePreparedResultMaterializer(e){return new cV(this.runtime,e)}makeSQLBlockMaterializer(e){return new fV(this.runtime,e)}}class _3 extends S3{loadFinalQuery(){return this.makeQueryMaterializer(async()=>(await this.materialize()).preparedQuery)}loadQueryByIndex(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e))}loadQueryByName(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e))}loadQuery(e,n){const{refreshSchemaCache:r,noThrowOnError:i}=n||{};return this.makeQueryMaterializer(async()=>{const s=this.runtime.urlReader,o=this.runtime.connections;this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0});const u=e instanceof URL?await xn.parse({url:e,urlReader:s,options:n}):xn.parse({source:e,options:n}),a=await this.getModel();return(await xn.compile({urlReader:s,connections:o,parse:u,model:a,refreshSchemaCache:r,noThrowOnError:i})).preparedQuery})}extendModel(e,n){return this.runtime.isTestRuntime&&(n===void 0?n={testEnvironment:!0}:n={...n,testEnvironment:!0}),new _3(this.runtime,async()=>{const r=this.runtime.urlReader,i=this.runtime.connections,s=e instanceof URL?await xn.parse({url:e,urlReader:r,options:n}):xn.parse({source:e,options:n}),o=await this.getModel();return await xn.compile({urlReader:r,connections:i,parse:s,model:o,refreshSchemaCache:n==null?void 0:n.refreshSchemaCache,noThrowOnError:n==null?void 0:n.noThrowOnError})})}async search(e,n,r=1e3,i=void 0){const s=await this.materialize(),o=new nc.QueryModel(s._modelDef),u=s.getExploreByName(e).structDef;if(u.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");const a=u.structRelationship.connectionName,l=await this.runtime.connections.lookupConnection(a);return await o.searchIndex(l,e,n,r,i)}async searchValueMap(e,n=10,r){const s=(await this.materialize()).getExploreByName(e);if(s.structDef.structRelationship.type!=="basetable")throw new Error("Expected schema's structRelationship type to be 'basetable'.");let o="{index: *}";s.getFieldByNameIfExists("search_index")&&(o="search_index");const u=`
1306
1306
  run: ${e}
1307
1307
  -> ${o}
1308
1308
  -> {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/render",
3
- "version": "0.0.166",
3
+ "version": "0.0.167",
4
4
  "license": "MIT",
5
5
  "main": "dist/module/index.umd.js",
6
6
  "types": "dist/index.d.ts",
@@ -34,7 +34,7 @@
34
34
  "build-types": "tsc --build --declaration --emitDeclarationOnly"
35
35
  },
36
36
  "dependencies": {
37
- "@malloydata/malloy": "^0.0.166",
37
+ "@malloydata/malloy": "^0.0.167",
38
38
  "@types/luxon": "^2.4.0",
39
39
  "component-register": "^0.8.6",
40
40
  "lodash": "^4.17.20",