@malloydata/render 0.0.317 → 0.0.319

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.
@@ -122536,8 +122536,7 @@ const Nv = /* @__PURE__ */ CZ(Yve);
122536
122536
  return m === ">" ? "<=" : m === "<" ? ">=" : m === ">=" ? "<" : ">";
122537
122537
  }
122538
122538
  function u(m, g) {
122539
- const y = ` OR ${g} IS NULL`;
122540
- return m.length === 1 ? `${m[0]}${y}` : `(${m.join(" AND ")})${y}`;
122539
+ return `(${m.length === 1 ? m[0] : `(${m.join(" AND ")})`} OR ${g} IS NULL)`;
122541
122540
  }
122542
122541
  t.FilterCompilers = {
122543
122542
  compile(m, g, y, v, E = {}) {
@@ -122558,7 +122557,7 @@ const Nv = /* @__PURE__ */ CZ(Yve);
122558
122557
  case "!=":
122559
122558
  case "=": {
122560
122559
  const v = m.operator === "=" && m.not || m.operator === "!=" && !m.not, E = m.values.join(", ");
122561
- return m.values.length === 1 ? v ? `${g} != ${E} OR ${g} IS NULL` : `${g} = ${E}` : v ? `${g} NOT IN (${E}) OR ${g} IS NULL` : `${g} IN (${E})`;
122560
+ return m.values.length === 1 ? v ? `(${g} != ${E} OR ${g} IS NULL)` : `${g} = ${E}` : v ? `(${g} NOT IN (${E}) OR ${g} IS NULL)` : `${g} IN (${E})`;
122562
122561
  }
122563
122562
  case ">":
122564
122563
  case "<":
@@ -122699,7 +122698,7 @@ const Nv = /* @__PURE__ */ CZ(Yve);
122699
122698
  return `${y} ${g.not ? ">=" : "<"} ${this.time(this.moment(g.before).begin.sql)}`;
122700
122699
  case "in": {
122701
122700
  const v = this.moment(g.in);
122702
- return v.begin.sql === v.end ? g.not ? `${y} != ${this.time(v.end)} OR ${y} IS NULL` : `${y} = ${this.time(v.end)}` : this.isIn(g.not, v.begin.sql, v.end);
122701
+ return v.begin.sql === v.end ? g.not ? `(${y} != ${this.time(v.end)} OR ${y} IS NULL)` : `${y} = ${this.time(v.end)}` : this.isIn(g.not, v.begin.sql, v.end);
122703
122702
  }
122704
122703
  case "for": {
122705
122704
  const v = this.moment(g.begin), E = this.delta(v.begin, "+", g.n, g.units);
@@ -154543,7 +154542,7 @@ function hyt(t) {
154543
154542
  var $e = {}, IO = {};
154544
154543
  Object.defineProperty(IO, "__esModule", { value: !0 });
154545
154544
  IO.MALLOY_VERSION = void 0;
154546
- IO.MALLOY_VERSION = "0.0.317";
154545
+ IO.MALLOY_VERSION = "0.0.319";
154547
154546
  Object.defineProperty($e, "__esModule", { value: !0 });
154548
154547
  $e.InMemoryModelCache = $e.CacheManager = $e.CSVWriter = $e.JSONWriter = $e.DataWriter = $e.DataRecord = $e.DataArray = $e.Result = $e.ExploreMaterializer = $e.PreparedResultMaterializer = $e.QueryMaterializer = $e.ModelMaterializer = $e.SingleConnectionRuntime = $e.ConnectionRuntime = $e.Runtime = $e.ExploreField = $e.JoinRelationship = $e.QueryField = $e.Query = $e.StringField = $e.UnsupportedField = $e.JSONField = $e.BooleanField = $e.NumberField = $e.TimestampField = $e.DateField = $e.TimestampTimeframe = $e.DateTimeframe = $e.AtomicField = $e.AtomicFieldType = $e.Explore = $e.SourceRelationship = $e.FixedConnectionMap = $e.InMemoryURLReader = $e.EmptyURLReader = $e.PreparedResult = $e.DocumentCompletion = $e.DocumentSymbol = $e.DocumentPosition = $e.DocumentRange = $e.DocumentTablePath = $e.Parse = $e.PreparedQuery = $e.Model = $e.MalloyError = $e.Malloy = void 0;
154549
154548
  const GX = GD, fr = wi, WX = Nv, W7 = ah, pyt = IO, myt = w1, Qn = ks, gyt = ph, yyt = Hr, Eyt = p_;
@@ -967,7 +967,7 @@ Use (?: … ) instead`);if(!Y.lineBreaks&&q.test(`
967
967
  `))throw new Error("Rule should declare lineBreaks: "+q);ee.push(l(B))}}var V=U&&U.fallback,L=i&&!V?"ym":"gm",P=i||V?"":"|";G===!0&&(L+="u");var j=new RegExp(c(ee)+P,L);return{regexp:j,groups:J,fast:X,error:U||v}}function _(w){var k=E(y(w));return new C({start:k},"start")}function A(w,k,U){var X=w&&(w.push||w.next);if(X&&!U[X])throw new Error("Missing state '"+X+"' (in token '"+w.defaultType+"' of state '"+k+"')");if(w&&w.pop&&+w.pop!=1)throw new Error("pop must be 1 (in token '"+w.defaultType+"' of state '"+k+"')")}function S(w,k){var U=w.$all?y(w.$all):[];delete w.$all;var X=Object.getOwnPropertyNames(w);k||(k=X[0]);for(var Q=Object.create(null),G=0;G<X.length;G++){var J=X[G];Q[J]=y(w[J]).concat(U)}for(var G=0;G<X.length;G++)for(var J=X[G],ee=Q[J],W=Object.create(null),Y=0;Y<ee.length;Y++){var re=ee[Y];if(re.include){var de=[Y,1];if(re.include!==J&&!W[re.include]){W[re.include]=!0;var I=Q[re.include];if(!I)throw new Error("Cannot include nonexistent state '"+re.include+"' (in state '"+J+"')");for(var F=0;F<I.length;F++){var B=I[F];ee.indexOf(B)===-1&&de.push(B)}}ee.splice.apply(ee,de),Y--}}for(var q=Object.create(null),G=0;G<X.length;G++){var J=X[G];q[J]=E(Q[J],!0)}for(var G=0;G<X.length;G++){for(var Z=X[G],V=q[Z],L=V.groups,Y=0;Y<L.length;Y++)A(L[Y],Z,q);for(var P=Object.getOwnPropertyNames(V.fast),Y=0;Y<P.length;Y++)A(V.fast[P[Y]],Z,q)}return new C(q,k)}function b(w){for(var k=typeof Map<"u",U=k?new Map:Object.create(null),X=Object.getOwnPropertyNames(w),Q=0;Q<X.length;Q++){var G=X[Q],J=w[G],ee=Array.isArray(J)?J:[J];ee.forEach(function(W){if(typeof W!="string")throw new Error("keyword must be string (in keyword '"+G+"')");k?U.set(W,G):U[W]=G})}return function(W){return k?U.get(W):U[W]}}var C=function(w,k){this.startState=k,this.states=w,this.buffer="",this.stack=[],this.reset()};C.prototype.reset=function(w,k){return this.buffer=w||"",this.index=0,this.line=k?k.line:1,this.col=k?k.col:1,this.queuedToken=k?k.queuedToken:null,this.queuedText=k?k.queuedText:"",this.queuedThrow=k?k.queuedThrow:null,this.setState(k?k.state:this.startState),this.stack=k&&k.stack?k.stack.slice():[],this},C.prototype.save=function(){return{line:this.line,col:this.col,state:this.state,stack:this.stack.slice(),queuedToken:this.queuedToken,queuedText:this.queuedText,queuedThrow:this.queuedThrow}},C.prototype.setState=function(w){if(!(!w||this.state===w)){this.state=w;var k=this.states[w];this.groups=k.groups,this.error=k.error,this.re=k.regexp,this.fast=k.fast}},C.prototype.popState=function(){this.setState(this.stack.pop())},C.prototype.pushState=function(w){this.stack.push(this.state),this.setState(w)};var T=i?function(w,k){return w.exec(k)}:function(w,k){var U=w.exec(k);return U[0].length===0?null:U};C.prototype._getGroup=function(w){for(var k=this.groups.length,U=0;U<k;U++)if(w[U+1]!==void 0)return this.groups[U];throw new Error("Cannot find token type for matched text")};function D(){return this.value}if(C.prototype.next=function(){var w=this.index;if(this.queuedGroup){var k=this._token(this.queuedGroup,this.queuedText,w);return this.queuedGroup=null,this.queuedText="",k}var U=this.buffer;if(w!==U.length){var J=this.fast[U.charCodeAt(w)];if(J)return this._token(J,U.charAt(w),w);var X=this.re;X.lastIndex=w;var Q=T(X,U),G=this.error;if(Q==null)return this._token(G,U.slice(w,U.length),w);var J=this._getGroup(Q),ee=Q[0];return G.fallback&&Q.index!==w?(this.queuedGroup=J,this.queuedText=ee,this._token(G,U.slice(w,Q.index),w)):this._token(J,ee,w)}},C.prototype._token=function(w,k,U){var X=0;if(w.lineBreaks){var Q=/\n/g,G=1;if(k===`
968
968
  `)X=1;else for(;Q.exec(k);)X++,G=Q.lastIndex}var J={type:typeof w.type=="function"&&w.type(k)||w.defaultType,value:typeof w.value=="function"?w.value(k):k,text:k,toString:D,offset:U,lineBreaks:X,line:this.line,col:this.col},ee=k.length;if(this.index+=ee,this.line+=X,X!==0?this.col=ee-G+1:this.col+=ee,w.shouldThrow){var W=new Error(this.formatError(J,"invalid syntax"));throw W}return w.pop?this.popState():w.push?this.pushState(w.push):w.next&&this.setState(w.next),J},typeof Symbol<"u"&&Symbol.iterator){var O=function(w){this.lexer=w};O.prototype.next=function(){var w=this.lexer.next();return{value:w,done:!w}},O.prototype[Symbol.iterator]=function(){return this},C.prototype[Symbol.iterator]=function(){return new O(this)}}return C.prototype.formatError=function(w,k){if(w==null)var U=this.buffer.slice(this.index),w={text:U,offset:this.index,lineBreaks:U.indexOf(`
969
969
  `)===-1?0:1,line:this.line,col:this.col};var X=2,Q=Math.max(w.line-X,1),G=w.line+X,J=String(G).length,ee=x(this.buffer,this.line-w.line+X+1).slice(0,5),W=[];W.push(k+" at line "+w.line+" col "+w.col+":"),W.push("");for(var Y=0;Y<ee.length;Y++){var re=ee[Y],de=Q+Y;W.push(d(String(de),J)+" "+re),de===w.line&&W.push(d("",J+w.col+1)+"^")}return W.join(`
970
- `)},C.prototype.clone=function(){return new C(this.states,this.state)},C.prototype.has=function(w){return!0},{compile:_,states:S,error:Object.freeze({error:!0}),fallback:Object.freeze({fallback:!0}),keywords:b}})})(tfe);var yM=tfe.exports,Ur={};Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.maybeNot=Krt,Ur.unescape=WE,Ur.escape=Xrt,Ur.matchOp=Jrt,Ur.conjoin=Zrt,Ur.joinNumbers=eit,Ur.mkRange=tit,Ur.mkValues=nit,Ur.numNot=rit,Ur.temporalNot=iit,Ur.joinTemporal=sit,Ur.timeLiteral=oit,Ur.mkUnits=uit;const ol=us;function Krt(t){const[e,r]=t;return e&&r&&(0,ol.isStringFilter)(r)?{...r,not:!0}:r}function WE(t){return t.replace(/\\(.)/g,"$1")}function Xrt(t){const e=t.toLowerCase();return e==="null"||e==="empty"?"\\"+t:t.replace(/([,; |()\\%_-])/g,"\\$1")}function QT(t){let e=!1,r=!1,i=0,s=!1;const o=t.length;for(let u=0;u<o;u+=1){const a=t[u];if(a===" "||a===" "){i+=1;continue}i=0,a==="%"?(s=!0,u===0&&(e=!0),r=!0):(r=!1,a==="\\"?u+=1:a==="_"&&(s=!0))}return{hasLike:s,percentEnd:r&&o>1,percentStart:e&&o>1,endSpace:i}}function Jrt(t){let e=t.trimStart();const{hasLike:r,percentEnd:i,percentStart:s,endSpace:o}=QT(e);if(o>0&&(e=e.slice(0,-o)),r){if(s&&i){const u=e.slice(1,-1);if(!QT(u).hasLike&&u.length>0)return{operator:"contains",values:[WE(u)]}}else if(i){const u=e.slice(0,-1);if(!QT(u).hasLike)return{operator:"starts",values:[WE(u)]}}else if(s){const u=e.slice(1);if(!QT(u).hasLike)return{operator:"ends",values:[WE(u)]}}return{operator:"~",escaped_values:[e]}}return e.toLowerCase()==="null"?{operator:"null"}:e.toLowerCase()==="empty"?{operator:"empty"}:{operator:"=",values:[WE(e)]}}function EM(t,e){var r,i;return t.operator===e.operator&&((r=t.not)!==null&&r!==void 0?r:!1)===((i=e.not)!==null&&i!==void 0?i:!1)}function Zrt(t,e,r){if(e=e.toLowerCase(),(0,ol.isStringFilter)(t)&&(0,ol.isStringFilter)(r)){if(e===","){if(t.operator==="~"&&EM(t,r))return{...t,escaped_values:[...t.escaped_values,...r.escaped_values]};if((0,ol.isStringCondition)(t)&&EM(t,r))return{...t,values:[...t.values,...r.values]}}const i=e===","?",":e==="|"?"or":e===";"?"and":void 0;if(i)return t.operator===i?{...t,members:[...t.members,r]}:{operator:i,members:[t,r]}}return null}function eit(t,e,r){if(e=e.toLowerCase(),(0,ol.isNumberFilter)(t)&&(0,ol.isNumberFilter)(r)){if(e==="or"&&t.operator==="="&&EM(t,r)){const i={operator:"=",values:[...t.values,...r.values]};return t.not&&(i.not=!0),i}if(e==="and"||e==="or")return t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}}return null}function tit(t,e,r,i){return{operator:"range",startValue:e,startOperator:t==="("?">":">=",endValue:r,endOperator:i===")"?"<":"<="}}function nit(t,e){return{values:[t,...e]}}function rit(t,e){return(0,ol.isNumberFilter)(t)&&e?t.operator==="="?{operator:"!=",values:t.values}:t.operator==="!="?{operator:"=",values:t.values}:{...t,not:!0}:t}function iit(t,e){if((0,ol.isTemporalFilter)(t)&&e){if("not"in t){const r={...t};return t.not?delete r.not:r.not=!0,r}return{...t,not:!0}}return t}function sit(t,e,r){return e=e.toLowerCase(),(0,ol.isTemporalFilter)(t)&&(0,ol.isTemporalFilter)(r)&&(e==="and"||e==="or")?t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}:null}function oit(t,e){const r={moment:"literal",literal:t};return e&&(r.units=e),r}function uit(t){switch(t.toLowerCase()){case"second":case"seconds":return"second";case"minute":case"minutes":return"minute";case"hour":case"hours":return"hour";case"day":case"days":return"day";case"week":case"weeks":return"week";case"month":case"months":return"month";case"quarter":case"quarters":return"quarter";case"year":case"years":return"year"}}var ait=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gM,"__esModule",{value:!0});function lit(t){return t[0]}const nfe=ait(yM),V2=Ur,cit=nfe.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to"}),Qn=nfe.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:t=>cit(t.toLowerCase())},oparen:"(",cparen:")",obrack:"[",cbrack:"]",comma:",",op:/<=|>=|<|>/,ne:"!=",eq:"=",float:/-?(?:\d+)?\.\d+(?:[Ee][+-]?\d+)?/,numberE:/-?\d+[Ee][+-]?\d+/,integer:/-?\d+/}),fit=Qn.next;Qn.next=(t=>()=>{for(;;){const e=t.call(Qn);if(e===void 0||e.type!=="WS")return e}})(fit);const dit={Lexer:Qn,ParserRules:[{name:"numberFilter",symbols:["numberFilter","conjunction","numberUnary"],postprocess:([t,e,r])=>(0,V2.joinNumbers)(t,e[0].text,r)},{name:"numberFilter",symbols:["numberUnary"],postprocess:t=>t[0]},{name:"numberUnary$ebnf$1",symbols:[Qn.has("NOT")?{type:"NOT"}:NOT],postprocess:lit},{name:"numberUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"numberUnary",symbols:["numberUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,V2.numNot)(e,t)},{name:"clause",symbols:[Qn.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause$ebnf$1",symbols:[]},{name:"clause$ebnf$1",symbols:["clause$ebnf$1","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:["N","clause$ebnf$1"],postprocess:([t,e])=>({operator:"=",...(0,V2.mkValues)(t,e)})},{name:"clause$ebnf$2",symbols:[]},{name:"clause$ebnf$2",symbols:["clause$ebnf$2","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Qn.has("eq")?{type:"eq"}:eq,"N","clause$ebnf$2"],postprocess:([t,e,r])=>({operator:"=",...(0,V2.mkValues)(e,r)})},{name:"clause$ebnf$3",symbols:[]},{name:"clause$ebnf$3",symbols:["clause$ebnf$3","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Qn.has("ne")?{type:"ne"}:ne,"N","clause$ebnf$3"],postprocess:([t,e,r])=>({operator:"!=",...(0,V2.mkValues)(e,r)})},{name:"clause",symbols:[Qn.has("op")?{type:"op"}:op,"N"],postprocess:([t,e])=>({operator:t.text,values:[e]})},{name:"clause",symbols:[Qn.has("oparen")?{type:"oparen"}:oparen,"numberFilter",Qn.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:["openInterval","N",Qn.has("TO")?{type:"TO"}:TO,"N","closeInterval"],postprocess:([t,e,r,i,s])=>(0,V2.mkRange)(t[0].text,e,i,s[0].text)},{name:"numberList",symbols:[Qn.has("comma")?{type:"comma"}:comma,"N"],postprocess:([t,e])=>e},{name:"closeInterval",symbols:[Qn.has("cbrack")?{type:"cbrack"}:cbrack]},{name:"closeInterval",symbols:[Qn.has("cparen")?{type:"cparen"}:cparen]},{name:"openInterval",symbols:[Qn.has("obrack")?{type:"obrack"}:obrack]},{name:"openInterval",symbols:[Qn.has("oparen")?{type:"oparen"}:oparen]},{name:"N$subexpression$1",symbols:[Qn.has("float")?{type:"float"}:float]},{name:"N$subexpression$1",symbols:[Qn.has("numberE")?{type:"numberE"}:numberE]},{name:"N$subexpression$1",symbols:[Qn.has("integer")?{type:"integer"}:integer]},{name:"N",symbols:["N$subexpression$1"],postprocess:([t])=>t[0].text},{name:"conjunction",symbols:[Qn.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Qn.has("AND")?{type:"AND"}:AND]}],ParserStart:"numberFilter"};gM.default=dit;var VE={};Object.defineProperty(VE,"__esModule",{value:!0}),VE.run_parser=hit;const xit=us;function hit(t,e){try{e.feed(t);const i=e.finish()[0];return(0,xit.isFilterExpression)(i)?{parsed:i,log:[]}:{parsed:null,log:[]}}catch(r){let i=r.message,s=1,o=t.length;if(r.token){const u=r.token;s=u.col,o=u.text.length;const l=r.message.match(new RegExp("(?<=A ).*(?= based on:)","g")).map(c=>c.replace(/\s+token/i,""));i=`Unexpected ${u.type} token "${u.value}"`,l&&l.length&&(i+=` Tokens expected: ${[...new Set(l)]}`)}return{parsed:null,log:[{message:i,startIndex:s-1,endIndex:s-1+o-1,severity:"error"}]}}}(function(t){var e=R&&R.__createBinding||(Object.create?function(c,f,d,x){x===void 0&&(x=d);var p=Object.getOwnPropertyDescriptor(f,d);(!p||("get"in p?!f.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return f[d]}}),Object.defineProperty(c,x,p)}:function(c,f,d,x){x===void 0&&(x=d),c[x]=f[d]}),r=R&&R.__setModuleDefault||(Object.create?function(c,f){Object.defineProperty(c,"default",{enumerable:!0,value:f})}:function(c,f){c.default=f}),i=R&&R.__importStar||function(){var c=function(f){return c=Object.getOwnPropertyNames||function(d){var x=[];for(var p in d)Object.prototype.hasOwnProperty.call(d,p)&&(x[x.length]=p);return x},c(f)};return function(f){if(f&&f.__esModule)return f;var d={};if(f!=null)for(var x=c(f),p=0;p<x.length;p++)x[p]!=="default"&&e(d,f,x[p]);return r(d,f),d}}(),s=R&&R.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.NumberFilterExpression=void 0;const o=us,u=i(mM),a=s(gM),l=VE;t.NumberFilterExpression={parse(c){if(c.match(/^\s*$/))return{parsed:null,log:[]};const f=new u.Parser(u.Grammar.fromCompiled(a.default)),d=(0,l.run_parser)(c,f);return d.parsed&&(0,o.isNumberFilter)(d.parsed)?{parsed:d.parsed,log:[]}:{parsed:null,log:d.log}},unparse(c){if(c===null)return"";switch(c.operator){case"=":return c.values.join(", ");case"!=":return"!= "+c.values.join(", ");case">":case"<":case"<=":case">=":return c.not?c.values.map(f=>c.operator==="="?`not ${f}`:`not ${c.operator} ${f}`).join(", "):c.values.map(f=>`${c.operator} ${f}`).join(", ");case"range":{const f=c.startOperator===">"?"(":"[",d=c.endOperator==="<"?")":"]",x=`${f}${c.startValue} to ${c.endValue}${d}`;return c.not?`not ${x}`:x}case"null":return c.not?"not null":"null";case"and":case"or":return c.members.map(f=>t.NumberFilterExpression.unparse(f)).join(` ${c.operator} `);case"()":{const f="("+t.NumberFilterExpression.unparse(c.expr)+")";return c.not?"not "+f:f}}return`no unparse for ${JSON.stringify(c)}`}}})(Z0e);var rfe={},vM={},pit=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vM,"__esModule",{value:!0});function mit(t){return t[0]}const git=pit(yM),_M=Ur,zu=git.default.compile({WS:/[ \t]+/,comma:",",semi:";",or:"|",open:"(",close:")",minus:"-",matchStr:/(?:\\[^\n]|[^\n,;()|])+/}),yit=zu.next;zu.next=(t=>()=>{for(;;){const e=t.call(zu);if(e==null||e.type!=="WS")return e}})(yit);const Eit={Lexer:zu,ParserRules:[{name:"stringFilter",symbols:["stringFilter","conjunction","sfUnary"],postprocess:([t,e,r])=>(0,_M.conjoin)(t,e[0].text,r)},{name:"stringFilter",symbols:["sfUnary"],postprocess:t=>t[0]},{name:"sfUnary$ebnf$1",symbols:[zu.has("minus")?{type:"minus"}:minus],postprocess:mit},{name:"sfUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"sfUnary",symbols:["sfUnary$ebnf$1","clause"],postprocess:t=>(0,_M.maybeNot)(t)},{name:"parens",symbols:[zu.has("open")?{type:"open"}:open,"stringFilter",zu.has("close")?{type:"close"}:close],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:[zu.has("matchStr")?{type:"matchStr"}:matchStr],postprocess:([t])=>(0,_M.matchOp)(t.text)},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"conjunction",symbols:[zu.has("comma")?{type:"comma"}:comma]},{name:"conjunction",symbols:[zu.has("semi")?{type:"semi"}:semi]},{name:"conjunction",symbols:[zu.has("or")?{type:"or"}:or]}],ParserStart:"stringFilter"};vM.default=Eit,function(t){var e=R&&R.__createBinding||(Object.create?function(f,d,x,p){p===void 0&&(p=x);var m=Object.getOwnPropertyDescriptor(d,x);(!m||("get"in m?!d.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return d[x]}}),Object.defineProperty(f,p,m)}:function(f,d,x,p){p===void 0&&(p=x),f[p]=d[x]}),r=R&&R.__setModuleDefault||(Object.create?function(f,d){Object.defineProperty(f,"default",{enumerable:!0,value:d})}:function(f,d){f.default=d}),i=R&&R.__importStar||function(){var f=function(d){return f=Object.getOwnPropertyNames||function(x){var p=[];for(var m in x)Object.prototype.hasOwnProperty.call(x,m)&&(p[p.length]=m);return p},f(d)};return function(d){if(d&&d.__esModule)return d;var x={};if(d!=null)for(var p=f(d),m=0;m<p.length;m++)p[m]!=="default"&&e(x,d,p[m]);return r(x,d),x}}(),s=R&&R.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.StringFilterExpression=void 0;const o=us,u=i(mM),a=s(vM),l=Ur,c=VE;t.StringFilterExpression={parse(f){if(f.match(/^\s*$/))return{parsed:null,log:[]};const d=new u.Parser(u.Grammar.fromCompiled(a.default)),x=(0,c.run_parser)(f,d);return x.parsed&&(0,o.isStringFilter)(x.parsed)?{parsed:x.parsed,log:[]}:{parsed:null,log:x.log}},unparse(f){if(f===null)return"";switch(f.operator){case"=":return f.not?f.values.map(d=>"-"+(0,l.escape)(d)).join(", "):f.values.map(d=>(0,l.escape)(d)).join(", ");case"~":return f.not?f.escaped_values.map(d=>"-"+d).join(", "):f.escaped_values.join(", ");case"starts":return f.not?f.values.map(d=>"-"+(0,l.escape)(d)+"%").join(", "):f.values.map(d=>(0,l.escape)(d)+"%").join(", ");case"ends":return f.not?f.values.map(d=>"-%"+(0,l.escape)(d)).join(", "):f.values.map(d=>"%"+(0,l.escape)(d)).join(", ");case"contains":return f.not?f.values.map(d=>"-%"+(0,l.escape)(d)+"%").join(", "):f.values.map(d=>"%"+(0,l.escape)(d)+"%").join(", ");case"or":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join(" | ");case"and":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join("; ");case",":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join(", ");case"()":{const d="("+t.StringFilterExpression.unparse(f.expr)+")";return f.not?"-"+d:d}case"null":return f.not?"-null":"null";case"empty":return f.not?"-empty":"empty"}}}}(rfe);var ife={},AM={},vit=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(AM,"__esModule",{value:!0});function _it(t){return t[0]}const sfe=vit(yM),Hu=Ur,Ait=sfe.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to",NOW:"now",LAST:"last",THIS:"this",NEXT:"next",AGO:"ago",FROM:"from",BEFORE:"before",AFTER:"after",THROUGH:"through",STARTING:"starting",FOR:"for",TODAY:"today",YESTERDAY:"yesterday",TOMORROW:"tomorrow",SECOND:"second",MINUTE:"minute",HOUR:"hour",DAY:"day",WEEK:"week",MONTH:"month",QUARTER:"quarter",YEAR:"year",SECONDS:"seconds",MINUTES:"minutes",HOURS:"hours",DAYS:"days",WEEKS:"weeks",MONTHS:"months",QUARTERS:"quarters",YEARS:"years",MONDAY:"monday",TUESDAY:"tuesday",WEDNESDAY:"wednesday",THURSDAY:"thursday",FRIDAY:"friday",SATURDAY:"saturday",SUNDAY:"sunday"}),Xe=sfe.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:t=>Ait(t.toLowerCase())},oparen:"(",cparen:")",comma:",",literal:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d(?::\d\d(?:[.,]\d*)?)/,lit_week:/\d\d\d\d-\d\d-\d\d-[Ww][Kk]/,lit_quarter:/\d\d\d\d-[qQ][1234]/,lit_min:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d/,lit_hour:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d/,lit_day:/\d\d\d\d-\d\d-\d\d/,lit_month:/\d\d\d\d-\d\d/,lit_year:/\d\d\d\d/,n:/\d+/}),Sit=Xe.next;Xe.next=(t=>()=>{for(;;){const e=t.call(Xe);if(e===void 0||e.type!=="WS")return e}})(Sit);const bit={Lexer:Xe,ParserRules:[{name:"temporalFilter",symbols:["temporalFilter","conjunction","temporalUnary"],postprocess:([t,e,r])=>(0,Hu.joinTemporal)(t,e[0].text,r)},{name:"temporalFilter",symbols:["temporalUnary"],postprocess:t=>t[0]},{name:"temporalUnary$ebnf$1",symbols:[Xe.has("NOT")?{type:"NOT"}:NOT],postprocess:_it},{name:"temporalUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"temporalUnary",symbols:["temporalUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,Hu.temporalNot)(e,t)},{name:"duration",symbols:["number","unit"],postprocess:([t,e])=>({units:e,n:t})},{name:"number",symbols:[Xe.has("n")?{type:"n"}:n],postprocess:([t])=>t.text},{name:"number",symbols:[Xe.has("lityear")?{type:"lityear"}:lityear],postprocess:([t])=>t.text},{name:"unit$subexpression$1",symbols:[Xe.has("SECOND")?{type:"SECOND"}:SECOND]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTE")?{type:"MINUTE"}:MINUTE]},{name:"unit$subexpression$1",symbols:[Xe.has("HOUR")?{type:"HOUR"}:HOUR]},{name:"unit$subexpression$1",symbols:[Xe.has("DAY")?{type:"DAY"}:DAY]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEK")?{type:"WEEK"}:WEEK]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTH")?{type:"MONTH"}:MONTH]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTER")?{type:"QUARTER"}:QUARTER]},{name:"unit$subexpression$1",symbols:[Xe.has("YEAR")?{type:"YEAR"}:YEAR]},{name:"unit$subexpression$1",symbols:[Xe.has("SECONDS")?{type:"SECONDS"}:SECONDS]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTES")?{type:"MINUTES"}:MINUTES]},{name:"unit$subexpression$1",symbols:[Xe.has("HOURS")?{type:"HOURS"}:HOURS]},{name:"unit$subexpression$1",symbols:[Xe.has("DAYS")?{type:"DAYS"}:DAYS]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEKS")?{type:"WEEKS"}:WEEKS]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTHS")?{type:"MONTHS"}:MONTHS]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTERS")?{type:"QUARTERS"}:QUARTERS]},{name:"unit$subexpression$1",symbols:[Xe.has("YEARS")?{type:"YEARS"}:YEARS]},{name:"unit",symbols:["unit$subexpression$1"],postprocess:([t])=>(0,Hu.mkUnits)(t[0].text)},{name:"clause",symbols:[Xe.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"clause",symbols:["duration"],postprocess:([t])=>({operator:"in_last",...t})},{name:"clause",symbols:[Xe.has("BEFORE")?{type:"BEFORE"}:BEFORE,"moment"],postprocess:([t,e])=>({operator:"before",before:e})},{name:"clause",symbols:[Xe.has("STARTING")?{type:"STARTING"}:STARTING,"moment"],postprocess:([t,e])=>({operator:"before",before:e,not:!0})},{name:"clause",symbols:[Xe.has("AFTER")?{type:"AFTER"}:AFTER,"moment"],postprocess:([t,e])=>({operator:"after",after:e})},{name:"clause",symbols:[Xe.has("THROUGH")?{type:"THROUGH"}:THROUGH,"moment"],postprocess:([t,e])=>({operator:"after",after:e,not:!0})},{name:"clause",symbols:["moment",Xe.has("TO")?{type:"TO"}:TO,"moment"],postprocess:([t,e,r])=>({operator:"to",fromMoment:t,toMoment:r})},{name:"clause",symbols:["moment",Xe.has("FOR")?{type:"FOR"}:FOR,"duration"],postprocess:([t,e,r])=>({...r,operator:"for",begin:t})},{name:"clause$subexpression$1",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST]},{name:"clause$subexpression$1",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT]},{name:"clause",symbols:["clause$subexpression$1","duration"],postprocess:([t,e])=>({operator:t[0].text,...e})},{name:"clause",symbols:["moment"],postprocess:([t])=>({operator:"in",in:t})},{name:"lastNextThis",symbols:[Xe.has("THIS")?{type:"THIS"}:THIS],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST],postprocess:([t])=>t.text.toLowerCase()},{name:"moment",symbols:[Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:()=>({moment:"now"})},{name:"moment",symbols:["lastNextThis","unit"],postprocess:([t,e])=>({moment:t,units:e})},{name:"moment",symbols:[Xe.has("TODAY")?{type:"TODAY"}:TODAY],postprocess:()=>({moment:"today"})},{name:"moment",symbols:[Xe.has("YESTERDAY")?{type:"YESTERDAY"}:YESTERDAY],postprocess:()=>({moment:"yesterday"})},{name:"moment",symbols:[Xe.has("TOMORROW")?{type:"TOMORROW"}:TOMORROW],postprocess:()=>({moment:"tomorrow"})},{name:"moment",symbols:["duration",Xe.has("AGO")?{type:"AGO"}:AGO],postprocess:([t,e])=>({moment:"ago",...t})},{name:"moment",symbols:["duration",Xe.has("FROM")?{type:"FROM"}:FROM,Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:([t,e])=>({moment:"from_now",...t})},{name:"moment",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"next"})},{name:"moment",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"last"})},{name:"moment",symbols:["weekday"],postprocess:([t])=>({moment:t.toLowerCase(),which:"last"})},{name:"moment",symbols:["timeLiteral"],postprocess:t=>t[0]},{name:"timeLiteral",symbols:[Xe.has("literal")?{type:"literal"}:literal],postprocess:([t])=>(0,Hu.timeLiteral)(t.text)},{name:"timeLiteral",symbols:[Xe.has("lit_day")?{type:"lit_day"}:lit_day],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"day")},{name:"timeLiteral",symbols:[Xe.has("lit_min")?{type:"lit_min"}:lit_min],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"minute")},{name:"timeLiteral",symbols:[Xe.has("lit_hour")?{type:"lit_hour"}:lit_hour],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"hour")},{name:"timeLiteral",symbols:[Xe.has("lit_month")?{type:"lit_month"}:lit_month],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"month")},{name:"timeLiteral",symbols:[Xe.has("lit_quarter")?{type:"lit_quarter"}:lit_quarter],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"quarter")},{name:"timeLiteral",symbols:[Xe.has("lit_week")?{type:"lit_week"}:lit_week],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"week")},{name:"timeLiteral",symbols:[Xe.has("lit_year")?{type:"lit_year"}:lit_year],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"year")},{name:"weekday$subexpression$1",symbols:[Xe.has("MONDAY")?{type:"MONDAY"}:MONDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("TUESDAY")?{type:"TUESDAY"}:TUESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("WEDNESDAY")?{type:"WEDNESDAY"}:WEDNESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("THURSDAY")?{type:"THURSDAY"}:THURSDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("FRIDAY")?{type:"FRIDAY"}:FRIDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SATURDAY")?{type:"SATURDAY"}:SATURDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SUNDAY")?{type:"SUNDAY"}:SUNDAY]},{name:"weekday",symbols:["weekday$subexpression$1"],postprocess:([t])=>t[0].text},{name:"parens",symbols:[Xe.has("oparen")?{type:"oparen"}:oparen,"temporalFilter",Xe.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"conjunction",symbols:[Xe.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Xe.has("AND")?{type:"AND"}:AND]}],ParserStart:"temporalFilter"};AM.default=bit,function(t){var e=R&&R.__createBinding||(Object.create?function(x,p,m,g){g===void 0&&(g=m);var y=Object.getOwnPropertyDescriptor(p,m);(!y||("get"in y?!p.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(x,g,y)}:function(x,p,m,g){g===void 0&&(g=m),x[g]=p[m]}),r=R&&R.__setModuleDefault||(Object.create?function(x,p){Object.defineProperty(x,"default",{enumerable:!0,value:p})}:function(x,p){x.default=p}),i=R&&R.__importStar||function(){var x=function(p){return x=Object.getOwnPropertyNames||function(m){var g=[];for(var y in m)Object.prototype.hasOwnProperty.call(m,y)&&(g[g.length]=y);return g},x(p)};return function(p){if(p&&p.__esModule)return p;var m={};if(p!=null)for(var g=x(p),y=0;y<g.length;y++)g[y]!=="default"&&e(m,p,g[y]);return r(m,p),m}}(),s=R&&R.__importDefault||function(x){return x&&x.__esModule?x:{default:x}};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=void 0;const o=us,u=s(AM),a=i(mM),l=VE;t.TemporalFilterExpression={parse(x){if(x.match(/^\s*$/))return{parsed:null,log:[]};const p=new a.Parser(a.Grammar.fromCompiled(u.default)),m=(0,l.run_parser)(x,p);return m.parsed&&(0,o.isTemporalFilter)(m.parsed)?{parsed:m.parsed,log:[]}:{parsed:null,log:m.log}},unparse(x){if(x===null)return"";switch(x.operator){case"null":return c(x,"null");case"in":return c(x,d(x.in));case"()":return"("+t.TemporalFilterExpression.unparse(x.expr)+")";case"in_last":return c(x,f(x));case"last":case"next":return c(x,`${x.operator} ${f(x)}`);case"before":return`${x.not?"starting":"before"} ${d(x.before)}`;case"after":return`${x.not?"through":"after"} ${d(x.after)}`;case"to":return c(x,`${d(x.fromMoment)} to ${d(x.toMoment)}`);case"for":return c(x,`${d(x.begin)} for ${f(x)}`);case"or":return x.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" or ");case"and":return x.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" and ")}}};function c(x,p){return"not"in x&&x.not?"not "+p:p}function f(x){return x.n==="1"?`1 ${x.units}`:`${x.n} ${x.units}s`}function d(x){switch(x.moment){case"literal":return x.literal;case"now":case"today":case"yesterday":case"tomorrow":return x.moment;case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":return x.which==="next"?"next "+x.moment:x.moment;case"this":case"next":case"last":return`${x.moment} ${x.units}`;case"ago":return`${f(x)} ago`;case"from_now":return`${f(x)} from now`}}}(ife),function(t){var e=R&&R.__createBinding||(Object.create?function(a,l,c,f){f===void 0&&(f=c);var d=Object.getOwnPropertyDescriptor(l,c);(!d||("get"in d?!l.__esModule:d.writable||d.configurable))&&(d={enumerable:!0,get:function(){return l[c]}}),Object.defineProperty(a,f,d)}:function(a,l,c,f){f===void 0&&(f=c),a[f]=l[c]}),r=R&&R.__exportStar||function(a,l){for(var c in a)c!=="default"&&!Object.prototype.hasOwnProperty.call(l,c)&&e(l,a,c)};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=t.StringFilterExpression=t.NumberFilterExpression=t.BooleanFilterExpression=void 0,r(us,t);var i=HT;Object.defineProperty(t,"BooleanFilterExpression",{enumerable:!0,get:function(){return i.BooleanFilterExpression}});var s=Z0e;Object.defineProperty(t,"NumberFilterExpression",{enumerable:!0,get:function(){return s.NumberFilterExpression}});var o=rfe;Object.defineProperty(t,"StringFilterExpression",{enumerable:!0,get:function(){return o.StringFilterExpression}});var u=ife;Object.defineProperty(t,"TemporalFilterExpression",{enumerable:!0,get:function(){return u.TemporalFilterExpression}})}(W2);var Ho={},GT={};Object.defineProperty(GT,"__esModule",{value:!0}),GT.JoinInstance=void 0;const Cit=Rt,Tit=wt,SM=Ye;class Rit{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,SM.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new Cit.QueryFieldBoolean({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,SM.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,SM.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return(0,Tit.getDialectFieldList)(this.queryStruct.structDef)}}GT.JoinInstance=Rit,Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.FieldInstanceResultRoot=Ho.FieldInstanceResult=Ho.FieldInstanceField=void 0,Ho.sqlFullChildReference=ufe;const Fc=Ye,ofe=wt,Dit=GT,Yx=Rt;class Ls{constructor(e,r,i,s){this.f=e,this.fieldUsage=r,this.parent=i,this.drillExpression=s,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}static registerExpressionCompiler(e){Ls.exprCompiler=e}getSQL(){let e=this.generateExpression();return(0,Yx.isScalarField)(this.f)&&(e=(0,ofe.caseGroup)(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}generateExpression(){if(!Ls.exprCompiler)throw new Error("Expression compiler not registered with FieldInstanceField");return this.f.fieldDef.type==="string"&&this.f.fieldDef.name==="__distinct_key"?this.generateDistinctKeyExpression():(0,Fc.hasExpression)(this.f.fieldDef)?Ls.exprCompiler(this.parent,this.f.parent,this.f.fieldDef.e):ufe(this.f.parent,this.f.fieldDef.name,this.f.parent.structDef.type==="record"?{result:this.parent,field:this.f}:void 0)}generateDistinctKeyExpression(){var e;if(this.f.parent.primaryKey()){const r=this.f.parent.getPrimaryKeyField(this.f.fieldDef),i=r.fieldDef.as||r.fieldDef.name;return this.parent.getField(i).generateExpression()}else if(this.f.parent.structDef.type==="array"){if(((e=this.f.parent.parent)===null||e===void 0?void 0:e.getDistinctKey())&&this.parent.parent){const s=this.parent.parent.getField("__distinct_key").generateExpression();return this.f.parent.dialect.sqlMakeUnnestKey(s,this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__row_id","string"))}return this.f.parent.dialect.sqlMakeUnnestKey("",this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__row_id","string"))}else return this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__distinct_key","string")}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}Ho.FieldInstanceField=Ls;class WT{constructor(e,r){this.turtleDef=e,this.parent=r,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getLimit(){if(this.firstSegment.type==="reduce"||this.firstSegment.type==="project")return this.firstSegment.limit}getQueryInfo(){if(!(0,Fc.isIndexSegment)(this.firstSegment)&&!(0,Fc.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return this.parent?this.parent.getQueryInfo():{}}addField(e,r,i,s){const o=this.allFields.get(e);if(o){if(o.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(o.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Ls(r,i,this,s))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Ls}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Ls)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Ls&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[u,a]of this.ungroupedSets){const l=e++;a.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[u,a]of this.allFields)if(a.type==="query"){const l=a;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Ls&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Ls&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if((0,Yx.isBasicScalar)(r.f))return"nested";r.f instanceof Yx.QueryFieldStruct&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof WT&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Ls&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Fc.isJoined)(i.f.fieldDef)||(0,Fc.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if((0,Yx.isBasicAggregate)(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r){var i;const s=e.getIdentifier();let o=this.root().joins.get(s);if(o){o.uniqueKeyRequirement=(0,Fc.mergeUniqueKeyRequirement)(o.uniqueKeyRequirement,r);return}let u;const a=(i=e.parent)===null||i===void 0?void 0:i.getJoinableParent();a&&(this.addStructToJoin(a,void 0),u=this.root().joins.get(a.getIdentifier())),(o=this.root().joins.get(s))||(o=new Dit.JoinInstance(e,s,u),this.root().joins.set(s,o)),o.uniqueKeyRequirement=(0,Fc.mergeUniqueKeyRequirement)(o.uniqueKeyRequirement,r)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const a=(e==null?void 0:e.fields)||[];s=this.fields(l=>(0,Yx.isBasicScalar)(l.f)&&l.fieldUsage.type==="result"&&a.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let u=!0;for(;i!==void 0;)(u||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(a=>(0,Yx.isScalarField)(a.f)&&a.fieldUsage.type==="result").map(a=>a.f.getIdentifier()))),r=r.concat(i.fields(a=>(0,Yx.isScalarField)(a.f)&&a.fieldUsage.type==="result"&&s.indexOf(a.f.getIdentifier())===-1)),i=i.parent,u=!1;for(const a of(e==null?void 0:e.fields)||[])if(o.indexOf(a)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${a}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}Ho.FieldInstanceResult=WT;class wit extends WT{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new ofe.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){var e;let r;for(const[i,s]of this.joins)if(s.parentRelationship()==="many_to_many"||s.forceAllSymmetricCalculations())r="0never";else if(r===void 0)r=i;else if(s.parentRelationship()==="one_to_many"){const u=s.queryStruct;u.parent&&u.parent.getIdentifier()===r?r=i:r="0never"}for(const[i,s]of this.joins)s.leafiest=i===r;for(const[i,s]of this.joins)if(s.leafiest&&s.parent!==void 0&&(!((e=s.uniqueKeyRequirement)===null||e===void 0)&&e.isCount)||!s.leafiest&&s.uniqueKeyRequirement){let o=s;for(;o;)o.queryStruct.primaryKey()||(o.makeUniqueKey=!0),o.queryStruct.structDef.type==="array"?o=o.parent:o=void 0}}}Ho.FieldInstanceResultRoot=wit;function ufe(t,e,r){let i=t.getSQLIdentifier();if(r&&(0,Fc.isAtomic)(t.structDef)&&(0,Fc.hasExpression)(t.structDef)){if(!t.parent)throw new Error(`Cannot expand reference to ${e} without parent`);if(!Ls.exprCompiler)throw new Error("Expression compiler not registered with FieldInstanceField");i=Ls.exprCompiler(r.result,t.parent,t.structDef.e)}let s="table";t.structDef.type==="record"?s="record":t.structDef.type==="array"?s=t.structDef.elementTypeDef.type==="record_element"?"array[record]":"array[scalar]":t.structDef.type==="nest_source"&&(s="nest source");const o=t.getChildByName(e),u=(o==null?void 0:o.fieldDef.type)||"unknown";return t.dialect.sqlFieldReference(i,s,e,u)}var afe={};const YE=Qq(Jve);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterCompiler=t.FilterCompilers=void 0;const e=W2,r=Ye,i=YE;function s(m){return m.replace(/([%_\\])/g,"\\$1")}function o(m){return m===">"?"<=":m==="<"?">=":m===">="?"<":">"}function u(m,g){const y=` OR ${g} IS NULL`;return m.length===1?`${m[0]}${y}`:`(${m.join(" AND ")})${y}`}t.FilterCompilers={compile(m,g,y,v,E={}){if(g===null)return"true";if(m==="string"&&(0,e.isStringFilter)(g))return t.FilterCompilers.stringCompile(g,y,v);if(m==="number"&&(0,e.isNumberFilter)(g))return t.FilterCompilers.numberCompile(g,y,v);if(m==="boolean"&&(0,e.isBooleanFilter)(g))return t.FilterCompilers.booleanCompile(g,y,v);if((m==="date"||m==="timestamp")&&(0,e.isTemporalFilter)(g))return t.FilterCompilers.temporalCompile(g,y,v,m,E);throw new Error("INTERNAL ERROR: No filter compiler for "+m)},numberCompile(m,g,y){switch(m.operator){case"!=":case"=":{const v=m.operator==="="&&m.not||m.operator==="!="&&!m.not,E=m.values.join(", ");return m.values.length===1?v?`${g} != ${E} OR ${g} IS NULL`:`${g} = ${E}`:v?`${g} NOT IN (${E}) OR ${g} IS NULL`:`${g} IN (${E})`}case">":case"<":case">=":case"<=":{const v=m.not?o(m.operator):m.operator;return m.values.map(E=>`${g} ${v} ${E}`).join(m.not?" AND ":" OR ")}case"range":{let v=m.startOperator,E=m.endOperator,_=" AND ";return m.not&&(v=o(v),E=o(E),_=" OR "),`${g} ${v} ${m.startValue} ${_} ${g} ${E} ${m.endValue}`}case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"()":{const v="("+t.FilterCompilers.numberCompile(m.expr,g,y)+")";return m.not?`NOT ${v}`:v}case"and":case"or":return m.members.map(v=>t.FilterCompilers.numberCompile(v,g,y)).join(` ${m.operator.toUpperCase()} `)}},booleanCompile(m,g,y){switch(m.operator){case"true":return m.not?`NOT COALESCE(${g}, false)`:`COALESCE(${g}, false)`;case"false":return m.not?`COALESCE(${g} != false, true)`:`COALESCE(${g} = false, false)`;case"false_or_null":return m.not?`COALESCE(${g}, false)`:`NOT COALESCE(${g}, false)`;case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`}},stringCompile(m,g,y){switch(m.operator){case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"empty":return m.not?`COALESCE(${g},'') != ''`:`COALESCE(${g},'') = ''`;case"=":{if(m.values.length===1){const E=m.not?"!=":"=",_=`${g} ${E} ${y.sqlLiteralString(m.values[0])}`;return m.not?`(${_} OR ${g} IS NULL)`:_}const v="("+m.values.map(E=>y.sqlLiteralString(E)).join(", ")+")";return m.not?`(${g} NOT IN ${v} OR ${g} IS NULL)`:`${g} IN ${v}`}case"()":{const v="("+t.FilterCompilers.stringCompile(m.expr,g,y)+")";return m.not?`not ${v}`:v}case"contains":{const v=m.values.map(E=>"%"+s(E)+"%");return m.not?u(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"starts":{const v=m.values.map(E=>s(E)+"%");return m.not?u(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"ends":{const v=m.values.map(E=>"%"+s(E));return m.not?u(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"~":return m.not?u(m.escaped_values.map(v=>y.sqlLike("NOT LIKE",g,v)),g):m.escaped_values.map(v=>y.sqlLike("LIKE",g,v)).join(" OR ");case"and":return m.members.map(E=>t.FilterCompilers.stringCompile(E,g,y)).join(" AND ");case"or":return m.members.map(E=>t.FilterCompilers.stringCompile(E,g,y)).join(" OR ");case",":{const v=[],E=[];let _=!1,A=!1,S=!1,b=!1;for(const D of m.members)switch(D.operator){case"or":case"and":case",":v.push(D);break;case"null":D.not?A=!0:_=!0;break;case"empty":D.not?(b=!0,A=!0):(S=!0,_=!0);break;default:(D.not?E:v).push(D)}if(S&&b||_&&A)return"false";let C="";if(v.length>0||_||S){b=!1,A=!1;const D=v.map(O=>t.FilterCompilers.stringCompile(O,g,y));S&&D.push(`${g} = ''`),_&&D.push(`${g} IS NULL`),C=D.join(" OR ")}let T="";if(E.length>0||b||A){const D=E.map(O=>t.FilterCompilers.stringCompile(O,g,y));b&&D.push(`${g} != ''`),A&&D.push(`${g} IS NOT NULL`),T=D.join(" AND ")}return C?T!==""?`(${C}) AND (${T})`:C:T!==""?T:"true"}}},temporalCompile(m,g,y,v,E={}){return new p(g,y,v,E).compile(m)}};const a="yyyy",l=`${a}-LL`,c=`${l}-dd`,f=`${c} HH`,d=`${f}:mm`,x=`${d}:ss`;class p{constructor(g,y,v="timestamp",E={}){this.expr=g,this.timetype=v,this.d=y,this.qi=E}time(g){return this.timetype==="timestamp"?g:this.d.sqlCast({},{node:"cast",e:{node:"genericSQLExpr",src:["",g],kids:{args:[]},sql:g},srcType:{type:"timestamp"},dstType:{type:"date"},safe:!1})}compile(g){const y=this.expr;switch(g.operator){case"after":return`${y} ${g.not?"<":">="} ${this.time(this.moment(g.after).end)}`;case"before":return`${y} ${g.not?">=":"<"} ${this.time(this.moment(g.before).begin.sql)}`;case"in":{const v=this.moment(g.in);return v.begin.sql===v.end?g.not?`${y} != ${this.time(v.end)} OR ${y} IS NULL`:`${y} = ${this.time(v.end)}`:this.isIn(g.not,v.begin.sql,v.end)}case"for":{const v=this.moment(g.begin),E=this.delta(v.begin,"+",g.n,g.units);return this.isIn(g.not,v.begin.sql,E.sql)}case"in_last":{const v=Number(g.n)-1,E=this.nowDot(g.units),_=v>0?this.delta(E,"-",v.toString(),g.units):E,A=this.delta(E,"+","1",g.units);return this.isIn(g.not,_.sql,A.sql)}case"to":{const v=this.moment(g.fromMoment),E=this.moment(g.toMoment);return this.isIn(g.not,v.begin.sql,E.begin.sql)}case"last":{const v=this.nowDot(g.units),E=this.delta(v,"-",g.n,g.units);return this.isIn(g.not,E.sql,v.sql)}case"next":{const v=this.nowDot(g.units),E=this.delta(v,"+","1",g.units),_=this.delta(v,"+",(Number(g.n)+1).toString(),g.units);return this.isIn(g.not,E.sql,_.sql)}case"null":return g.not?`${y} IS NOT NULL`:`${y} IS NULL`;case"()":{const v="("+this.compile(g.expr)+")";return g.not?`NOT ${v}`:v}case"and":case"or":return g.members.map(v=>this.compile(v)).join(` ${g.operator.toUpperCase()} `)}}expandLiteral(g){let y=g.literal;switch(g.units){case"year":{const v=i.DateTime.fromFormat(y,a),E=this.literalNode(v.toFormat(x)),_=v.plus({year:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"month":{const v=i.DateTime.fromFormat(y,l),E=this.literalNode(v.toFormat(x)),_=v.plus({month:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"day":{const v=i.DateTime.fromFormat(y,c),E=this.literalNode(v.toFormat(x)),_=v.plus({day:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"hour":{const v=i.DateTime.fromFormat(y,f),E=this.literalNode(v.toFormat(x)),_=v.plus({hour:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"minute":{const v=i.DateTime.fromFormat(y,d),E=this.literalNode(v.toFormat(x)),_=v.plus({minute:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"week":{const _=i.DateTime.fromFormat(y.slice(0,10),c).plus({day:1}).startOf("week").minus({day:1}),A=this.literalNode(_.toFormat(x)),S=_.plus({days:7});return{begin:A,end:this.literalNode(S.toFormat(x)).sql}}case"quarter":{const v=y.slice(0,4),E=y.slice(6);E==="1"?y=`${v}-01-01 00:00:00`:E==="2"?y=`${v}-03-01 00:00:00`:E==="3"?y=`${v}-06-01 00:00:00`:y=`${v}-09-01 00:00:00`;const _=this.literalNode(y),S=i.DateTime.fromFormat(y,x).plus({months:3});return{begin:_,end:this.literalNode(S.toFormat(x)).sql}}case void 0:case"second":{const v=this.literalNode(y);return{begin:v,end:v.sql}}}}literalNode(g){const y={node:"timeLiteral",typeDef:{type:"timestamp"},literal:g};return this.qi.queryTimezone&&(y.timezone=this.qi.queryTimezone),{...y,sql:this.d.sqlLiteralTime(this.qi,y)}}nowExpr(){return{node:"now",typeDef:{type:"timestamp"},sql:this.d.sqlNowExpr()}}n(g){return{node:"numberLiteral",literal:g,sql:g}}delta(g,y,v,E){const _={node:"delta",op:y,units:E,kids:{base:(0,r.mkTemporal)(g,"timestamp"),delta:this.n(v)}};return{..._,sql:this.d.sqlAlterTimeExpr(_)}}dayofWeek(g){const y={node:"extract",e:(0,r.mkTemporal)(g,"timestamp"),units:"day_of_week"};return{...y,sql:this.d.sqlTimeExtractExpr(this.qi,y)}}nowDot(g){const y={node:"trunc",e:this.nowExpr(),units:g};return{...y,sql:this.d.sqlTruncExpr(this.qi,y)}}thisUnit(g){const y=this.nowDot(g),v=this.delta(y,"+","1",g);return{begin:y,end:v.sql}}lastUnit(g){const y=this.nowDot(g);return{begin:this.delta(y,"-","1",g),end:y.sql}}nextUnit(g){const y=this.nowDot(g),v=this.delta(y,"+","1",g),E=this.delta(y,"+","2",g);return{begin:v,end:E.sql}}mod7(g){return this.d.hasModOperator?`(${g})%7`:`MOD(${g},7)`}moment(g){switch(g.moment){case"now":{const y=this.nowExpr();return{begin:y,end:y.sql}}case"literal":return this.expandLiteral(g);case"ago":case"from_now":{const y=this.nowDot(g.units),v=(0,r.mkTemporal)(y,"timestamp"),E=this.delta(v,g.moment==="ago"?"-":"+",g.n,g.units);if(g.moment==="ago"&&g.n==="1")return{begin:E,end:y.sql};const _=Number(g.n)+(g.moment==="ago"?-1:1),A={...E,kids:{base:v,delta:this.n(_.toString())}};return{begin:E,end:this.d.sqlAlterTimeExpr(A)}}case"today":return this.thisUnit("day");case"yesterday":return this.lastUnit("day");case"tomorrow":return this.nextUnit("day");case"this":return this.thisUnit(g.units);case"last":return this.lastUnit(g.units);case"next":return this.nextUnit(g.units);case"sunday":return this.weekdayMoment(1,g.which);case"monday":return this.weekdayMoment(2,g.which);case"tuesday":return this.weekdayMoment(3,g.which);case"wednesday":return this.weekdayMoment(4,g.which);case"thursday":return this.weekdayMoment(5,g.which);case"friday":return this.weekdayMoment(6,g.which);case"saturday":return this.weekdayMoment(7,g.which)}}isIn(g,y,v){let E=">=",_="<",A="AND";return g&&(A="OR",E="<",_=">="),y=this.time(y),v=this.time(v),`${this.expr} ${E} ${y} ${A} ${this.expr} ${_} ${v}`}weekdayMoment(g,y){const v=y||"last",E=this.dayofWeek(this.nowExpr()),_=this.thisUnit("day").begin,A=g-1,S=`(${E.sql}-1)`;let b,C;v==="next"?(b=`${this.mod7(`${A}-${S}+6`)}+1`,C=`${this.mod7(`${A}-${S}+6`)}+2`):(b=`${this.mod7(`${S}-${A}+6`)}+1`,C=`${this.mod7(`${S}-${A}+6`)}`);const T=this.delta(_,v==="next"?"+":"-",b,"day"),D=this.delta(_,v==="next"?"+":"-",C,"day");return{begin:T,end:D.sql}}}t.TemporalFilterCompiler=p})(afe),Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.exprToSQL=Qo,Hn.generateFunctionCallExpression=xfe,Hn.generateFieldFragment=YT,Hn.generateOutputFieldFragment=hfe,Hn.generateParameterFragment=pfe,Hn.generateFilterFragment=mfe,Hn.generateDimFragment=al,Hn.generateUngroupedFragment=gfe,Hn.generateDistinctKeyIfNecessary=KT,Hn.generateSumFragment=Efe,Hn.generateSymmetricFragment=vfe,Hn.generateAvgFragment=_fe,Hn.generateCountFragment=Afe,Hn.generateSourceReference=Sfe,Hn.generateCaseSQL=bfe,Hn.getFunctionOrderBy=bM,Hn.getAnalyticPartitions=Cfe,Hn.stringsFromSQLExpression=Tfe;const ul=Ye,VT=W2,Oit=Ho,Fit=afe,Is=wt,Nit=Rt,lfe=9;function cfe(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-lfe);let c=`(${`(
970
+ `)},C.prototype.clone=function(){return new C(this.states,this.state)},C.prototype.has=function(w){return!0},{compile:_,states:S,error:Object.freeze({error:!0}),fallback:Object.freeze({fallback:!0}),keywords:b}})})(tfe);var yM=tfe.exports,Ur={};Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.maybeNot=Krt,Ur.unescape=WE,Ur.escape=Xrt,Ur.matchOp=Jrt,Ur.conjoin=Zrt,Ur.joinNumbers=eit,Ur.mkRange=tit,Ur.mkValues=nit,Ur.numNot=rit,Ur.temporalNot=iit,Ur.joinTemporal=sit,Ur.timeLiteral=oit,Ur.mkUnits=uit;const ol=us;function Krt(t){const[e,r]=t;return e&&r&&(0,ol.isStringFilter)(r)?{...r,not:!0}:r}function WE(t){return t.replace(/\\(.)/g,"$1")}function Xrt(t){const e=t.toLowerCase();return e==="null"||e==="empty"?"\\"+t:t.replace(/([,; |()\\%_-])/g,"\\$1")}function QT(t){let e=!1,r=!1,i=0,s=!1;const o=t.length;for(let u=0;u<o;u+=1){const a=t[u];if(a===" "||a===" "){i+=1;continue}i=0,a==="%"?(s=!0,u===0&&(e=!0),r=!0):(r=!1,a==="\\"?u+=1:a==="_"&&(s=!0))}return{hasLike:s,percentEnd:r&&o>1,percentStart:e&&o>1,endSpace:i}}function Jrt(t){let e=t.trimStart();const{hasLike:r,percentEnd:i,percentStart:s,endSpace:o}=QT(e);if(o>0&&(e=e.slice(0,-o)),r){if(s&&i){const u=e.slice(1,-1);if(!QT(u).hasLike&&u.length>0)return{operator:"contains",values:[WE(u)]}}else if(i){const u=e.slice(0,-1);if(!QT(u).hasLike)return{operator:"starts",values:[WE(u)]}}else if(s){const u=e.slice(1);if(!QT(u).hasLike)return{operator:"ends",values:[WE(u)]}}return{operator:"~",escaped_values:[e]}}return e.toLowerCase()==="null"?{operator:"null"}:e.toLowerCase()==="empty"?{operator:"empty"}:{operator:"=",values:[WE(e)]}}function EM(t,e){var r,i;return t.operator===e.operator&&((r=t.not)!==null&&r!==void 0?r:!1)===((i=e.not)!==null&&i!==void 0?i:!1)}function Zrt(t,e,r){if(e=e.toLowerCase(),(0,ol.isStringFilter)(t)&&(0,ol.isStringFilter)(r)){if(e===","){if(t.operator==="~"&&EM(t,r))return{...t,escaped_values:[...t.escaped_values,...r.escaped_values]};if((0,ol.isStringCondition)(t)&&EM(t,r))return{...t,values:[...t.values,...r.values]}}const i=e===","?",":e==="|"?"or":e===";"?"and":void 0;if(i)return t.operator===i?{...t,members:[...t.members,r]}:{operator:i,members:[t,r]}}return null}function eit(t,e,r){if(e=e.toLowerCase(),(0,ol.isNumberFilter)(t)&&(0,ol.isNumberFilter)(r)){if(e==="or"&&t.operator==="="&&EM(t,r)){const i={operator:"=",values:[...t.values,...r.values]};return t.not&&(i.not=!0),i}if(e==="and"||e==="or")return t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}}return null}function tit(t,e,r,i){return{operator:"range",startValue:e,startOperator:t==="("?">":">=",endValue:r,endOperator:i===")"?"<":"<="}}function nit(t,e){return{values:[t,...e]}}function rit(t,e){return(0,ol.isNumberFilter)(t)&&e?t.operator==="="?{operator:"!=",values:t.values}:t.operator==="!="?{operator:"=",values:t.values}:{...t,not:!0}:t}function iit(t,e){if((0,ol.isTemporalFilter)(t)&&e){if("not"in t){const r={...t};return t.not?delete r.not:r.not=!0,r}return{...t,not:!0}}return t}function sit(t,e,r){return e=e.toLowerCase(),(0,ol.isTemporalFilter)(t)&&(0,ol.isTemporalFilter)(r)&&(e==="and"||e==="or")?t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}:null}function oit(t,e){const r={moment:"literal",literal:t};return e&&(r.units=e),r}function uit(t){switch(t.toLowerCase()){case"second":case"seconds":return"second";case"minute":case"minutes":return"minute";case"hour":case"hours":return"hour";case"day":case"days":return"day";case"week":case"weeks":return"week";case"month":case"months":return"month";case"quarter":case"quarters":return"quarter";case"year":case"years":return"year"}}var ait=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gM,"__esModule",{value:!0});function lit(t){return t[0]}const nfe=ait(yM),V2=Ur,cit=nfe.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to"}),Qn=nfe.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:t=>cit(t.toLowerCase())},oparen:"(",cparen:")",obrack:"[",cbrack:"]",comma:",",op:/<=|>=|<|>/,ne:"!=",eq:"=",float:/-?(?:\d+)?\.\d+(?:[Ee][+-]?\d+)?/,numberE:/-?\d+[Ee][+-]?\d+/,integer:/-?\d+/}),fit=Qn.next;Qn.next=(t=>()=>{for(;;){const e=t.call(Qn);if(e===void 0||e.type!=="WS")return e}})(fit);const dit={Lexer:Qn,ParserRules:[{name:"numberFilter",symbols:["numberFilter","conjunction","numberUnary"],postprocess:([t,e,r])=>(0,V2.joinNumbers)(t,e[0].text,r)},{name:"numberFilter",symbols:["numberUnary"],postprocess:t=>t[0]},{name:"numberUnary$ebnf$1",symbols:[Qn.has("NOT")?{type:"NOT"}:NOT],postprocess:lit},{name:"numberUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"numberUnary",symbols:["numberUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,V2.numNot)(e,t)},{name:"clause",symbols:[Qn.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause$ebnf$1",symbols:[]},{name:"clause$ebnf$1",symbols:["clause$ebnf$1","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:["N","clause$ebnf$1"],postprocess:([t,e])=>({operator:"=",...(0,V2.mkValues)(t,e)})},{name:"clause$ebnf$2",symbols:[]},{name:"clause$ebnf$2",symbols:["clause$ebnf$2","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Qn.has("eq")?{type:"eq"}:eq,"N","clause$ebnf$2"],postprocess:([t,e,r])=>({operator:"=",...(0,V2.mkValues)(e,r)})},{name:"clause$ebnf$3",symbols:[]},{name:"clause$ebnf$3",symbols:["clause$ebnf$3","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Qn.has("ne")?{type:"ne"}:ne,"N","clause$ebnf$3"],postprocess:([t,e,r])=>({operator:"!=",...(0,V2.mkValues)(e,r)})},{name:"clause",symbols:[Qn.has("op")?{type:"op"}:op,"N"],postprocess:([t,e])=>({operator:t.text,values:[e]})},{name:"clause",symbols:[Qn.has("oparen")?{type:"oparen"}:oparen,"numberFilter",Qn.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:["openInterval","N",Qn.has("TO")?{type:"TO"}:TO,"N","closeInterval"],postprocess:([t,e,r,i,s])=>(0,V2.mkRange)(t[0].text,e,i,s[0].text)},{name:"numberList",symbols:[Qn.has("comma")?{type:"comma"}:comma,"N"],postprocess:([t,e])=>e},{name:"closeInterval",symbols:[Qn.has("cbrack")?{type:"cbrack"}:cbrack]},{name:"closeInterval",symbols:[Qn.has("cparen")?{type:"cparen"}:cparen]},{name:"openInterval",symbols:[Qn.has("obrack")?{type:"obrack"}:obrack]},{name:"openInterval",symbols:[Qn.has("oparen")?{type:"oparen"}:oparen]},{name:"N$subexpression$1",symbols:[Qn.has("float")?{type:"float"}:float]},{name:"N$subexpression$1",symbols:[Qn.has("numberE")?{type:"numberE"}:numberE]},{name:"N$subexpression$1",symbols:[Qn.has("integer")?{type:"integer"}:integer]},{name:"N",symbols:["N$subexpression$1"],postprocess:([t])=>t[0].text},{name:"conjunction",symbols:[Qn.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Qn.has("AND")?{type:"AND"}:AND]}],ParserStart:"numberFilter"};gM.default=dit;var VE={};Object.defineProperty(VE,"__esModule",{value:!0}),VE.run_parser=hit;const xit=us;function hit(t,e){try{e.feed(t);const i=e.finish()[0];return(0,xit.isFilterExpression)(i)?{parsed:i,log:[]}:{parsed:null,log:[]}}catch(r){let i=r.message,s=1,o=t.length;if(r.token){const u=r.token;s=u.col,o=u.text.length;const l=r.message.match(new RegExp("(?<=A ).*(?= based on:)","g")).map(c=>c.replace(/\s+token/i,""));i=`Unexpected ${u.type} token "${u.value}"`,l&&l.length&&(i+=` Tokens expected: ${[...new Set(l)]}`)}return{parsed:null,log:[{message:i,startIndex:s-1,endIndex:s-1+o-1,severity:"error"}]}}}(function(t){var e=R&&R.__createBinding||(Object.create?function(c,f,d,x){x===void 0&&(x=d);var p=Object.getOwnPropertyDescriptor(f,d);(!p||("get"in p?!f.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return f[d]}}),Object.defineProperty(c,x,p)}:function(c,f,d,x){x===void 0&&(x=d),c[x]=f[d]}),r=R&&R.__setModuleDefault||(Object.create?function(c,f){Object.defineProperty(c,"default",{enumerable:!0,value:f})}:function(c,f){c.default=f}),i=R&&R.__importStar||function(){var c=function(f){return c=Object.getOwnPropertyNames||function(d){var x=[];for(var p in d)Object.prototype.hasOwnProperty.call(d,p)&&(x[x.length]=p);return x},c(f)};return function(f){if(f&&f.__esModule)return f;var d={};if(f!=null)for(var x=c(f),p=0;p<x.length;p++)x[p]!=="default"&&e(d,f,x[p]);return r(d,f),d}}(),s=R&&R.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.NumberFilterExpression=void 0;const o=us,u=i(mM),a=s(gM),l=VE;t.NumberFilterExpression={parse(c){if(c.match(/^\s*$/))return{parsed:null,log:[]};const f=new u.Parser(u.Grammar.fromCompiled(a.default)),d=(0,l.run_parser)(c,f);return d.parsed&&(0,o.isNumberFilter)(d.parsed)?{parsed:d.parsed,log:[]}:{parsed:null,log:d.log}},unparse(c){if(c===null)return"";switch(c.operator){case"=":return c.values.join(", ");case"!=":return"!= "+c.values.join(", ");case">":case"<":case"<=":case">=":return c.not?c.values.map(f=>c.operator==="="?`not ${f}`:`not ${c.operator} ${f}`).join(", "):c.values.map(f=>`${c.operator} ${f}`).join(", ");case"range":{const f=c.startOperator===">"?"(":"[",d=c.endOperator==="<"?")":"]",x=`${f}${c.startValue} to ${c.endValue}${d}`;return c.not?`not ${x}`:x}case"null":return c.not?"not null":"null";case"and":case"or":return c.members.map(f=>t.NumberFilterExpression.unparse(f)).join(` ${c.operator} `);case"()":{const f="("+t.NumberFilterExpression.unparse(c.expr)+")";return c.not?"not "+f:f}}return`no unparse for ${JSON.stringify(c)}`}}})(Z0e);var rfe={},vM={},pit=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vM,"__esModule",{value:!0});function mit(t){return t[0]}const git=pit(yM),_M=Ur,zu=git.default.compile({WS:/[ \t]+/,comma:",",semi:";",or:"|",open:"(",close:")",minus:"-",matchStr:/(?:\\[^\n]|[^\n,;()|])+/}),yit=zu.next;zu.next=(t=>()=>{for(;;){const e=t.call(zu);if(e==null||e.type!=="WS")return e}})(yit);const Eit={Lexer:zu,ParserRules:[{name:"stringFilter",symbols:["stringFilter","conjunction","sfUnary"],postprocess:([t,e,r])=>(0,_M.conjoin)(t,e[0].text,r)},{name:"stringFilter",symbols:["sfUnary"],postprocess:t=>t[0]},{name:"sfUnary$ebnf$1",symbols:[zu.has("minus")?{type:"minus"}:minus],postprocess:mit},{name:"sfUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"sfUnary",symbols:["sfUnary$ebnf$1","clause"],postprocess:t=>(0,_M.maybeNot)(t)},{name:"parens",symbols:[zu.has("open")?{type:"open"}:open,"stringFilter",zu.has("close")?{type:"close"}:close],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:[zu.has("matchStr")?{type:"matchStr"}:matchStr],postprocess:([t])=>(0,_M.matchOp)(t.text)},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"conjunction",symbols:[zu.has("comma")?{type:"comma"}:comma]},{name:"conjunction",symbols:[zu.has("semi")?{type:"semi"}:semi]},{name:"conjunction",symbols:[zu.has("or")?{type:"or"}:or]}],ParserStart:"stringFilter"};vM.default=Eit,function(t){var e=R&&R.__createBinding||(Object.create?function(f,d,x,p){p===void 0&&(p=x);var m=Object.getOwnPropertyDescriptor(d,x);(!m||("get"in m?!d.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return d[x]}}),Object.defineProperty(f,p,m)}:function(f,d,x,p){p===void 0&&(p=x),f[p]=d[x]}),r=R&&R.__setModuleDefault||(Object.create?function(f,d){Object.defineProperty(f,"default",{enumerable:!0,value:d})}:function(f,d){f.default=d}),i=R&&R.__importStar||function(){var f=function(d){return f=Object.getOwnPropertyNames||function(x){var p=[];for(var m in x)Object.prototype.hasOwnProperty.call(x,m)&&(p[p.length]=m);return p},f(d)};return function(d){if(d&&d.__esModule)return d;var x={};if(d!=null)for(var p=f(d),m=0;m<p.length;m++)p[m]!=="default"&&e(x,d,p[m]);return r(x,d),x}}(),s=R&&R.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.StringFilterExpression=void 0;const o=us,u=i(mM),a=s(vM),l=Ur,c=VE;t.StringFilterExpression={parse(f){if(f.match(/^\s*$/))return{parsed:null,log:[]};const d=new u.Parser(u.Grammar.fromCompiled(a.default)),x=(0,c.run_parser)(f,d);return x.parsed&&(0,o.isStringFilter)(x.parsed)?{parsed:x.parsed,log:[]}:{parsed:null,log:x.log}},unparse(f){if(f===null)return"";switch(f.operator){case"=":return f.not?f.values.map(d=>"-"+(0,l.escape)(d)).join(", "):f.values.map(d=>(0,l.escape)(d)).join(", ");case"~":return f.not?f.escaped_values.map(d=>"-"+d).join(", "):f.escaped_values.join(", ");case"starts":return f.not?f.values.map(d=>"-"+(0,l.escape)(d)+"%").join(", "):f.values.map(d=>(0,l.escape)(d)+"%").join(", ");case"ends":return f.not?f.values.map(d=>"-%"+(0,l.escape)(d)).join(", "):f.values.map(d=>"%"+(0,l.escape)(d)).join(", ");case"contains":return f.not?f.values.map(d=>"-%"+(0,l.escape)(d)+"%").join(", "):f.values.map(d=>"%"+(0,l.escape)(d)+"%").join(", ");case"or":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join(" | ");case"and":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join("; ");case",":return f.members.map(d=>t.StringFilterExpression.unparse(d)).join(", ");case"()":{const d="("+t.StringFilterExpression.unparse(f.expr)+")";return f.not?"-"+d:d}case"null":return f.not?"-null":"null";case"empty":return f.not?"-empty":"empty"}}}}(rfe);var ife={},AM={},vit=R&&R.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(AM,"__esModule",{value:!0});function _it(t){return t[0]}const sfe=vit(yM),Hu=Ur,Ait=sfe.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to",NOW:"now",LAST:"last",THIS:"this",NEXT:"next",AGO:"ago",FROM:"from",BEFORE:"before",AFTER:"after",THROUGH:"through",STARTING:"starting",FOR:"for",TODAY:"today",YESTERDAY:"yesterday",TOMORROW:"tomorrow",SECOND:"second",MINUTE:"minute",HOUR:"hour",DAY:"day",WEEK:"week",MONTH:"month",QUARTER:"quarter",YEAR:"year",SECONDS:"seconds",MINUTES:"minutes",HOURS:"hours",DAYS:"days",WEEKS:"weeks",MONTHS:"months",QUARTERS:"quarters",YEARS:"years",MONDAY:"monday",TUESDAY:"tuesday",WEDNESDAY:"wednesday",THURSDAY:"thursday",FRIDAY:"friday",SATURDAY:"saturday",SUNDAY:"sunday"}),Xe=sfe.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:t=>Ait(t.toLowerCase())},oparen:"(",cparen:")",comma:",",literal:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d(?::\d\d(?:[.,]\d*)?)/,lit_week:/\d\d\d\d-\d\d-\d\d-[Ww][Kk]/,lit_quarter:/\d\d\d\d-[qQ][1234]/,lit_min:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d/,lit_hour:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d/,lit_day:/\d\d\d\d-\d\d-\d\d/,lit_month:/\d\d\d\d-\d\d/,lit_year:/\d\d\d\d/,n:/\d+/}),Sit=Xe.next;Xe.next=(t=>()=>{for(;;){const e=t.call(Xe);if(e===void 0||e.type!=="WS")return e}})(Sit);const bit={Lexer:Xe,ParserRules:[{name:"temporalFilter",symbols:["temporalFilter","conjunction","temporalUnary"],postprocess:([t,e,r])=>(0,Hu.joinTemporal)(t,e[0].text,r)},{name:"temporalFilter",symbols:["temporalUnary"],postprocess:t=>t[0]},{name:"temporalUnary$ebnf$1",symbols:[Xe.has("NOT")?{type:"NOT"}:NOT],postprocess:_it},{name:"temporalUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"temporalUnary",symbols:["temporalUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,Hu.temporalNot)(e,t)},{name:"duration",symbols:["number","unit"],postprocess:([t,e])=>({units:e,n:t})},{name:"number",symbols:[Xe.has("n")?{type:"n"}:n],postprocess:([t])=>t.text},{name:"number",symbols:[Xe.has("lityear")?{type:"lityear"}:lityear],postprocess:([t])=>t.text},{name:"unit$subexpression$1",symbols:[Xe.has("SECOND")?{type:"SECOND"}:SECOND]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTE")?{type:"MINUTE"}:MINUTE]},{name:"unit$subexpression$1",symbols:[Xe.has("HOUR")?{type:"HOUR"}:HOUR]},{name:"unit$subexpression$1",symbols:[Xe.has("DAY")?{type:"DAY"}:DAY]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEK")?{type:"WEEK"}:WEEK]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTH")?{type:"MONTH"}:MONTH]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTER")?{type:"QUARTER"}:QUARTER]},{name:"unit$subexpression$1",symbols:[Xe.has("YEAR")?{type:"YEAR"}:YEAR]},{name:"unit$subexpression$1",symbols:[Xe.has("SECONDS")?{type:"SECONDS"}:SECONDS]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTES")?{type:"MINUTES"}:MINUTES]},{name:"unit$subexpression$1",symbols:[Xe.has("HOURS")?{type:"HOURS"}:HOURS]},{name:"unit$subexpression$1",symbols:[Xe.has("DAYS")?{type:"DAYS"}:DAYS]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEKS")?{type:"WEEKS"}:WEEKS]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTHS")?{type:"MONTHS"}:MONTHS]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTERS")?{type:"QUARTERS"}:QUARTERS]},{name:"unit$subexpression$1",symbols:[Xe.has("YEARS")?{type:"YEARS"}:YEARS]},{name:"unit",symbols:["unit$subexpression$1"],postprocess:([t])=>(0,Hu.mkUnits)(t[0].text)},{name:"clause",symbols:[Xe.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"clause",symbols:["duration"],postprocess:([t])=>({operator:"in_last",...t})},{name:"clause",symbols:[Xe.has("BEFORE")?{type:"BEFORE"}:BEFORE,"moment"],postprocess:([t,e])=>({operator:"before",before:e})},{name:"clause",symbols:[Xe.has("STARTING")?{type:"STARTING"}:STARTING,"moment"],postprocess:([t,e])=>({operator:"before",before:e,not:!0})},{name:"clause",symbols:[Xe.has("AFTER")?{type:"AFTER"}:AFTER,"moment"],postprocess:([t,e])=>({operator:"after",after:e})},{name:"clause",symbols:[Xe.has("THROUGH")?{type:"THROUGH"}:THROUGH,"moment"],postprocess:([t,e])=>({operator:"after",after:e,not:!0})},{name:"clause",symbols:["moment",Xe.has("TO")?{type:"TO"}:TO,"moment"],postprocess:([t,e,r])=>({operator:"to",fromMoment:t,toMoment:r})},{name:"clause",symbols:["moment",Xe.has("FOR")?{type:"FOR"}:FOR,"duration"],postprocess:([t,e,r])=>({...r,operator:"for",begin:t})},{name:"clause$subexpression$1",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST]},{name:"clause$subexpression$1",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT]},{name:"clause",symbols:["clause$subexpression$1","duration"],postprocess:([t,e])=>({operator:t[0].text,...e})},{name:"clause",symbols:["moment"],postprocess:([t])=>({operator:"in",in:t})},{name:"lastNextThis",symbols:[Xe.has("THIS")?{type:"THIS"}:THIS],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST],postprocess:([t])=>t.text.toLowerCase()},{name:"moment",symbols:[Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:()=>({moment:"now"})},{name:"moment",symbols:["lastNextThis","unit"],postprocess:([t,e])=>({moment:t,units:e})},{name:"moment",symbols:[Xe.has("TODAY")?{type:"TODAY"}:TODAY],postprocess:()=>({moment:"today"})},{name:"moment",symbols:[Xe.has("YESTERDAY")?{type:"YESTERDAY"}:YESTERDAY],postprocess:()=>({moment:"yesterday"})},{name:"moment",symbols:[Xe.has("TOMORROW")?{type:"TOMORROW"}:TOMORROW],postprocess:()=>({moment:"tomorrow"})},{name:"moment",symbols:["duration",Xe.has("AGO")?{type:"AGO"}:AGO],postprocess:([t,e])=>({moment:"ago",...t})},{name:"moment",symbols:["duration",Xe.has("FROM")?{type:"FROM"}:FROM,Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:([t,e])=>({moment:"from_now",...t})},{name:"moment",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"next"})},{name:"moment",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"last"})},{name:"moment",symbols:["weekday"],postprocess:([t])=>({moment:t.toLowerCase(),which:"last"})},{name:"moment",symbols:["timeLiteral"],postprocess:t=>t[0]},{name:"timeLiteral",symbols:[Xe.has("literal")?{type:"literal"}:literal],postprocess:([t])=>(0,Hu.timeLiteral)(t.text)},{name:"timeLiteral",symbols:[Xe.has("lit_day")?{type:"lit_day"}:lit_day],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"day")},{name:"timeLiteral",symbols:[Xe.has("lit_min")?{type:"lit_min"}:lit_min],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"minute")},{name:"timeLiteral",symbols:[Xe.has("lit_hour")?{type:"lit_hour"}:lit_hour],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"hour")},{name:"timeLiteral",symbols:[Xe.has("lit_month")?{type:"lit_month"}:lit_month],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"month")},{name:"timeLiteral",symbols:[Xe.has("lit_quarter")?{type:"lit_quarter"}:lit_quarter],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"quarter")},{name:"timeLiteral",symbols:[Xe.has("lit_week")?{type:"lit_week"}:lit_week],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"week")},{name:"timeLiteral",symbols:[Xe.has("lit_year")?{type:"lit_year"}:lit_year],postprocess:([t])=>(0,Hu.timeLiteral)(t.text,"year")},{name:"weekday$subexpression$1",symbols:[Xe.has("MONDAY")?{type:"MONDAY"}:MONDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("TUESDAY")?{type:"TUESDAY"}:TUESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("WEDNESDAY")?{type:"WEDNESDAY"}:WEDNESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("THURSDAY")?{type:"THURSDAY"}:THURSDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("FRIDAY")?{type:"FRIDAY"}:FRIDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SATURDAY")?{type:"SATURDAY"}:SATURDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SUNDAY")?{type:"SUNDAY"}:SUNDAY]},{name:"weekday",symbols:["weekday$subexpression$1"],postprocess:([t])=>t[0].text},{name:"parens",symbols:[Xe.has("oparen")?{type:"oparen"}:oparen,"temporalFilter",Xe.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"conjunction",symbols:[Xe.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Xe.has("AND")?{type:"AND"}:AND]}],ParserStart:"temporalFilter"};AM.default=bit,function(t){var e=R&&R.__createBinding||(Object.create?function(x,p,m,g){g===void 0&&(g=m);var y=Object.getOwnPropertyDescriptor(p,m);(!y||("get"in y?!p.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(x,g,y)}:function(x,p,m,g){g===void 0&&(g=m),x[g]=p[m]}),r=R&&R.__setModuleDefault||(Object.create?function(x,p){Object.defineProperty(x,"default",{enumerable:!0,value:p})}:function(x,p){x.default=p}),i=R&&R.__importStar||function(){var x=function(p){return x=Object.getOwnPropertyNames||function(m){var g=[];for(var y in m)Object.prototype.hasOwnProperty.call(m,y)&&(g[g.length]=y);return g},x(p)};return function(p){if(p&&p.__esModule)return p;var m={};if(p!=null)for(var g=x(p),y=0;y<g.length;y++)g[y]!=="default"&&e(m,p,g[y]);return r(m,p),m}}(),s=R&&R.__importDefault||function(x){return x&&x.__esModule?x:{default:x}};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=void 0;const o=us,u=s(AM),a=i(mM),l=VE;t.TemporalFilterExpression={parse(x){if(x.match(/^\s*$/))return{parsed:null,log:[]};const p=new a.Parser(a.Grammar.fromCompiled(u.default)),m=(0,l.run_parser)(x,p);return m.parsed&&(0,o.isTemporalFilter)(m.parsed)?{parsed:m.parsed,log:[]}:{parsed:null,log:m.log}},unparse(x){if(x===null)return"";switch(x.operator){case"null":return c(x,"null");case"in":return c(x,d(x.in));case"()":return"("+t.TemporalFilterExpression.unparse(x.expr)+")";case"in_last":return c(x,f(x));case"last":case"next":return c(x,`${x.operator} ${f(x)}`);case"before":return`${x.not?"starting":"before"} ${d(x.before)}`;case"after":return`${x.not?"through":"after"} ${d(x.after)}`;case"to":return c(x,`${d(x.fromMoment)} to ${d(x.toMoment)}`);case"for":return c(x,`${d(x.begin)} for ${f(x)}`);case"or":return x.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" or ");case"and":return x.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" and ")}}};function c(x,p){return"not"in x&&x.not?"not "+p:p}function f(x){return x.n==="1"?`1 ${x.units}`:`${x.n} ${x.units}s`}function d(x){switch(x.moment){case"literal":return x.literal;case"now":case"today":case"yesterday":case"tomorrow":return x.moment;case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":return x.which==="next"?"next "+x.moment:x.moment;case"this":case"next":case"last":return`${x.moment} ${x.units}`;case"ago":return`${f(x)} ago`;case"from_now":return`${f(x)} from now`}}}(ife),function(t){var e=R&&R.__createBinding||(Object.create?function(a,l,c,f){f===void 0&&(f=c);var d=Object.getOwnPropertyDescriptor(l,c);(!d||("get"in d?!l.__esModule:d.writable||d.configurable))&&(d={enumerable:!0,get:function(){return l[c]}}),Object.defineProperty(a,f,d)}:function(a,l,c,f){f===void 0&&(f=c),a[f]=l[c]}),r=R&&R.__exportStar||function(a,l){for(var c in a)c!=="default"&&!Object.prototype.hasOwnProperty.call(l,c)&&e(l,a,c)};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=t.StringFilterExpression=t.NumberFilterExpression=t.BooleanFilterExpression=void 0,r(us,t);var i=HT;Object.defineProperty(t,"BooleanFilterExpression",{enumerable:!0,get:function(){return i.BooleanFilterExpression}});var s=Z0e;Object.defineProperty(t,"NumberFilterExpression",{enumerable:!0,get:function(){return s.NumberFilterExpression}});var o=rfe;Object.defineProperty(t,"StringFilterExpression",{enumerable:!0,get:function(){return o.StringFilterExpression}});var u=ife;Object.defineProperty(t,"TemporalFilterExpression",{enumerable:!0,get:function(){return u.TemporalFilterExpression}})}(W2);var Ho={},GT={};Object.defineProperty(GT,"__esModule",{value:!0}),GT.JoinInstance=void 0;const Cit=Rt,Tit=wt,SM=Ye;class Rit{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,SM.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new Cit.QueryFieldBoolean({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,SM.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,SM.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return(0,Tit.getDialectFieldList)(this.queryStruct.structDef)}}GT.JoinInstance=Rit,Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.FieldInstanceResultRoot=Ho.FieldInstanceResult=Ho.FieldInstanceField=void 0,Ho.sqlFullChildReference=ufe;const Fc=Ye,ofe=wt,Dit=GT,Yx=Rt;class Ls{constructor(e,r,i,s){this.f=e,this.fieldUsage=r,this.parent=i,this.drillExpression=s,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}static registerExpressionCompiler(e){Ls.exprCompiler=e}getSQL(){let e=this.generateExpression();return(0,Yx.isScalarField)(this.f)&&(e=(0,ofe.caseGroup)(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}generateExpression(){if(!Ls.exprCompiler)throw new Error("Expression compiler not registered with FieldInstanceField");return this.f.fieldDef.type==="string"&&this.f.fieldDef.name==="__distinct_key"?this.generateDistinctKeyExpression():(0,Fc.hasExpression)(this.f.fieldDef)?Ls.exprCompiler(this.parent,this.f.parent,this.f.fieldDef.e):ufe(this.f.parent,this.f.fieldDef.name,this.f.parent.structDef.type==="record"?{result:this.parent,field:this.f}:void 0)}generateDistinctKeyExpression(){var e;if(this.f.parent.primaryKey()){const r=this.f.parent.getPrimaryKeyField(this.f.fieldDef),i=r.fieldDef.as||r.fieldDef.name;return this.parent.getField(i).generateExpression()}else if(this.f.parent.structDef.type==="array"){if(((e=this.f.parent.parent)===null||e===void 0?void 0:e.getDistinctKey())&&this.parent.parent){const s=this.parent.parent.getField("__distinct_key").generateExpression();return this.f.parent.dialect.sqlMakeUnnestKey(s,this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__row_id","string"))}return this.f.parent.dialect.sqlMakeUnnestKey("",this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__row_id","string"))}else return this.f.parent.dialect.sqlFieldReference(this.f.parent.getIdentifier(),"table","__distinct_key","string")}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}Ho.FieldInstanceField=Ls;class WT{constructor(e,r){this.turtleDef=e,this.parent=r,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getLimit(){if(this.firstSegment.type==="reduce"||this.firstSegment.type==="project")return this.firstSegment.limit}getQueryInfo(){if(!(0,Fc.isIndexSegment)(this.firstSegment)&&!(0,Fc.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return this.parent?this.parent.getQueryInfo():{}}addField(e,r,i,s){const o=this.allFields.get(e);if(o){if(o.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(o.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Ls(r,i,this,s))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Ls}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Ls)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Ls&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[u,a]of this.ungroupedSets){const l=e++;a.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[u,a]of this.allFields)if(a.type==="query"){const l=a;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Ls&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Ls&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if((0,Yx.isBasicScalar)(r.f))return"nested";r.f instanceof Yx.QueryFieldStruct&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof WT&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Ls&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Fc.isJoined)(i.f.fieldDef)||(0,Fc.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if((0,Yx.isBasicAggregate)(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r){var i;const s=e.getIdentifier();let o=this.root().joins.get(s);if(o){o.uniqueKeyRequirement=(0,Fc.mergeUniqueKeyRequirement)(o.uniqueKeyRequirement,r);return}let u;const a=(i=e.parent)===null||i===void 0?void 0:i.getJoinableParent();a&&(this.addStructToJoin(a,void 0),u=this.root().joins.get(a.getIdentifier())),(o=this.root().joins.get(s))||(o=new Dit.JoinInstance(e,s,u),this.root().joins.set(s,o)),o.uniqueKeyRequirement=(0,Fc.mergeUniqueKeyRequirement)(o.uniqueKeyRequirement,r)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const a=(e==null?void 0:e.fields)||[];s=this.fields(l=>(0,Yx.isBasicScalar)(l.f)&&l.fieldUsage.type==="result"&&a.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let u=!0;for(;i!==void 0;)(u||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(a=>(0,Yx.isScalarField)(a.f)&&a.fieldUsage.type==="result").map(a=>a.f.getIdentifier()))),r=r.concat(i.fields(a=>(0,Yx.isScalarField)(a.f)&&a.fieldUsage.type==="result"&&s.indexOf(a.f.getIdentifier())===-1)),i=i.parent,u=!1;for(const a of(e==null?void 0:e.fields)||[])if(o.indexOf(a)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${a}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}Ho.FieldInstanceResult=WT;class wit extends WT{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new ofe.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){var e;let r;for(const[i,s]of this.joins)if(s.parentRelationship()==="many_to_many"||s.forceAllSymmetricCalculations())r="0never";else if(r===void 0)r=i;else if(s.parentRelationship()==="one_to_many"){const u=s.queryStruct;u.parent&&u.parent.getIdentifier()===r?r=i:r="0never"}for(const[i,s]of this.joins)s.leafiest=i===r;for(const[i,s]of this.joins)if(s.leafiest&&s.parent!==void 0&&(!((e=s.uniqueKeyRequirement)===null||e===void 0)&&e.isCount)||!s.leafiest&&s.uniqueKeyRequirement){let o=s;for(;o;)o.queryStruct.primaryKey()||(o.makeUniqueKey=!0),o.queryStruct.structDef.type==="array"?o=o.parent:o=void 0}}}Ho.FieldInstanceResultRoot=wit;function ufe(t,e,r){let i=t.getSQLIdentifier();if(r&&(0,Fc.isAtomic)(t.structDef)&&(0,Fc.hasExpression)(t.structDef)){if(!t.parent)throw new Error(`Cannot expand reference to ${e} without parent`);if(!Ls.exprCompiler)throw new Error("Expression compiler not registered with FieldInstanceField");i=Ls.exprCompiler(r.result,t.parent,t.structDef.e)}let s="table";t.structDef.type==="record"?s="record":t.structDef.type==="array"?s=t.structDef.elementTypeDef.type==="record_element"?"array[record]":"array[scalar]":t.structDef.type==="nest_source"&&(s="nest source");const o=t.getChildByName(e),u=(o==null?void 0:o.fieldDef.type)||"unknown";return t.dialect.sqlFieldReference(i,s,e,u)}var afe={};const YE=Qq(Jve);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterCompiler=t.FilterCompilers=void 0;const e=W2,r=Ye,i=YE;function s(m){return m.replace(/([%_\\])/g,"\\$1")}function o(m){return m===">"?"<=":m==="<"?">=":m===">="?"<":">"}function u(m,g){return`(${m.length===1?m[0]:`(${m.join(" AND ")})`} OR ${g} IS NULL)`}t.FilterCompilers={compile(m,g,y,v,E={}){if(g===null)return"true";if(m==="string"&&(0,e.isStringFilter)(g))return t.FilterCompilers.stringCompile(g,y,v);if(m==="number"&&(0,e.isNumberFilter)(g))return t.FilterCompilers.numberCompile(g,y,v);if(m==="boolean"&&(0,e.isBooleanFilter)(g))return t.FilterCompilers.booleanCompile(g,y,v);if((m==="date"||m==="timestamp")&&(0,e.isTemporalFilter)(g))return t.FilterCompilers.temporalCompile(g,y,v,m,E);throw new Error("INTERNAL ERROR: No filter compiler for "+m)},numberCompile(m,g,y){switch(m.operator){case"!=":case"=":{const v=m.operator==="="&&m.not||m.operator==="!="&&!m.not,E=m.values.join(", ");return m.values.length===1?v?`(${g} != ${E} OR ${g} IS NULL)`:`${g} = ${E}`:v?`(${g} NOT IN (${E}) OR ${g} IS NULL)`:`${g} IN (${E})`}case">":case"<":case">=":case"<=":{const v=m.not?o(m.operator):m.operator;return m.values.map(E=>`${g} ${v} ${E}`).join(m.not?" AND ":" OR ")}case"range":{let v=m.startOperator,E=m.endOperator,_=" AND ";return m.not&&(v=o(v),E=o(E),_=" OR "),`${g} ${v} ${m.startValue} ${_} ${g} ${E} ${m.endValue}`}case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"()":{const v="("+t.FilterCompilers.numberCompile(m.expr,g,y)+")";return m.not?`NOT ${v}`:v}case"and":case"or":return m.members.map(v=>t.FilterCompilers.numberCompile(v,g,y)).join(` ${m.operator.toUpperCase()} `)}},booleanCompile(m,g,y){switch(m.operator){case"true":return m.not?`NOT COALESCE(${g}, false)`:`COALESCE(${g}, false)`;case"false":return m.not?`COALESCE(${g} != false, true)`:`COALESCE(${g} = false, false)`;case"false_or_null":return m.not?`COALESCE(${g}, false)`:`NOT COALESCE(${g}, false)`;case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`}},stringCompile(m,g,y){switch(m.operator){case"null":return m.not?`${g} IS NOT NULL`:`${g} IS NULL`;case"empty":return m.not?`COALESCE(${g},'') != ''`:`COALESCE(${g},'') = ''`;case"=":{if(m.values.length===1){const E=m.not?"!=":"=",_=`${g} ${E} ${y.sqlLiteralString(m.values[0])}`;return m.not?`(${_} OR ${g} IS NULL)`:_}const v="("+m.values.map(E=>y.sqlLiteralString(E)).join(", ")+")";return m.not?`(${g} NOT IN ${v} OR ${g} IS NULL)`:`${g} IN ${v}`}case"()":{const v="("+t.FilterCompilers.stringCompile(m.expr,g,y)+")";return m.not?`not ${v}`:v}case"contains":{const v=m.values.map(E=>"%"+s(E)+"%");return m.not?u(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"starts":{const v=m.values.map(E=>s(E)+"%");return m.not?u(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"ends":{const v=m.values.map(E=>"%"+s(E));return m.not?u(v.map(E=>y.sqlLike("NOT LIKE",g,E)),g):v.map(E=>y.sqlLike("LIKE",g,E)).join(" OR ")}case"~":return m.not?u(m.escaped_values.map(v=>y.sqlLike("NOT LIKE",g,v)),g):m.escaped_values.map(v=>y.sqlLike("LIKE",g,v)).join(" OR ");case"and":return m.members.map(E=>t.FilterCompilers.stringCompile(E,g,y)).join(" AND ");case"or":return m.members.map(E=>t.FilterCompilers.stringCompile(E,g,y)).join(" OR ");case",":{const v=[],E=[];let _=!1,A=!1,S=!1,b=!1;for(const D of m.members)switch(D.operator){case"or":case"and":case",":v.push(D);break;case"null":D.not?A=!0:_=!0;break;case"empty":D.not?(b=!0,A=!0):(S=!0,_=!0);break;default:(D.not?E:v).push(D)}if(S&&b||_&&A)return"false";let C="";if(v.length>0||_||S){b=!1,A=!1;const D=v.map(O=>t.FilterCompilers.stringCompile(O,g,y));S&&D.push(`${g} = ''`),_&&D.push(`${g} IS NULL`),C=D.join(" OR ")}let T="";if(E.length>0||b||A){const D=E.map(O=>t.FilterCompilers.stringCompile(O,g,y));b&&D.push(`${g} != ''`),A&&D.push(`${g} IS NOT NULL`),T=D.join(" AND ")}return C?T!==""?`(${C}) AND (${T})`:C:T!==""?T:"true"}}},temporalCompile(m,g,y,v,E={}){return new p(g,y,v,E).compile(m)}};const a="yyyy",l=`${a}-LL`,c=`${l}-dd`,f=`${c} HH`,d=`${f}:mm`,x=`${d}:ss`;class p{constructor(g,y,v="timestamp",E={}){this.expr=g,this.timetype=v,this.d=y,this.qi=E}time(g){return this.timetype==="timestamp"?g:this.d.sqlCast({},{node:"cast",e:{node:"genericSQLExpr",src:["",g],kids:{args:[]},sql:g},srcType:{type:"timestamp"},dstType:{type:"date"},safe:!1})}compile(g){const y=this.expr;switch(g.operator){case"after":return`${y} ${g.not?"<":">="} ${this.time(this.moment(g.after).end)}`;case"before":return`${y} ${g.not?">=":"<"} ${this.time(this.moment(g.before).begin.sql)}`;case"in":{const v=this.moment(g.in);return v.begin.sql===v.end?g.not?`(${y} != ${this.time(v.end)} OR ${y} IS NULL)`:`${y} = ${this.time(v.end)}`:this.isIn(g.not,v.begin.sql,v.end)}case"for":{const v=this.moment(g.begin),E=this.delta(v.begin,"+",g.n,g.units);return this.isIn(g.not,v.begin.sql,E.sql)}case"in_last":{const v=Number(g.n)-1,E=this.nowDot(g.units),_=v>0?this.delta(E,"-",v.toString(),g.units):E,A=this.delta(E,"+","1",g.units);return this.isIn(g.not,_.sql,A.sql)}case"to":{const v=this.moment(g.fromMoment),E=this.moment(g.toMoment);return this.isIn(g.not,v.begin.sql,E.begin.sql)}case"last":{const v=this.nowDot(g.units),E=this.delta(v,"-",g.n,g.units);return this.isIn(g.not,E.sql,v.sql)}case"next":{const v=this.nowDot(g.units),E=this.delta(v,"+","1",g.units),_=this.delta(v,"+",(Number(g.n)+1).toString(),g.units);return this.isIn(g.not,E.sql,_.sql)}case"null":return g.not?`${y} IS NOT NULL`:`${y} IS NULL`;case"()":{const v="("+this.compile(g.expr)+")";return g.not?`NOT ${v}`:v}case"and":case"or":return g.members.map(v=>this.compile(v)).join(` ${g.operator.toUpperCase()} `)}}expandLiteral(g){let y=g.literal;switch(g.units){case"year":{const v=i.DateTime.fromFormat(y,a),E=this.literalNode(v.toFormat(x)),_=v.plus({year:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"month":{const v=i.DateTime.fromFormat(y,l),E=this.literalNode(v.toFormat(x)),_=v.plus({month:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"day":{const v=i.DateTime.fromFormat(y,c),E=this.literalNode(v.toFormat(x)),_=v.plus({day:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"hour":{const v=i.DateTime.fromFormat(y,f),E=this.literalNode(v.toFormat(x)),_=v.plus({hour:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"minute":{const v=i.DateTime.fromFormat(y,d),E=this.literalNode(v.toFormat(x)),_=v.plus({minute:1});return{begin:E,end:this.literalNode(_.toFormat(x)).sql}}case"week":{const _=i.DateTime.fromFormat(y.slice(0,10),c).plus({day:1}).startOf("week").minus({day:1}),A=this.literalNode(_.toFormat(x)),S=_.plus({days:7});return{begin:A,end:this.literalNode(S.toFormat(x)).sql}}case"quarter":{const v=y.slice(0,4),E=y.slice(6);E==="1"?y=`${v}-01-01 00:00:00`:E==="2"?y=`${v}-03-01 00:00:00`:E==="3"?y=`${v}-06-01 00:00:00`:y=`${v}-09-01 00:00:00`;const _=this.literalNode(y),S=i.DateTime.fromFormat(y,x).plus({months:3});return{begin:_,end:this.literalNode(S.toFormat(x)).sql}}case void 0:case"second":{const v=this.literalNode(y);return{begin:v,end:v.sql}}}}literalNode(g){const y={node:"timeLiteral",typeDef:{type:"timestamp"},literal:g};return this.qi.queryTimezone&&(y.timezone=this.qi.queryTimezone),{...y,sql:this.d.sqlLiteralTime(this.qi,y)}}nowExpr(){return{node:"now",typeDef:{type:"timestamp"},sql:this.d.sqlNowExpr()}}n(g){return{node:"numberLiteral",literal:g,sql:g}}delta(g,y,v,E){const _={node:"delta",op:y,units:E,kids:{base:(0,r.mkTemporal)(g,"timestamp"),delta:this.n(v)}};return{..._,sql:this.d.sqlAlterTimeExpr(_)}}dayofWeek(g){const y={node:"extract",e:(0,r.mkTemporal)(g,"timestamp"),units:"day_of_week"};return{...y,sql:this.d.sqlTimeExtractExpr(this.qi,y)}}nowDot(g){const y={node:"trunc",e:this.nowExpr(),units:g};return{...y,sql:this.d.sqlTruncExpr(this.qi,y)}}thisUnit(g){const y=this.nowDot(g),v=this.delta(y,"+","1",g);return{begin:y,end:v.sql}}lastUnit(g){const y=this.nowDot(g);return{begin:this.delta(y,"-","1",g),end:y.sql}}nextUnit(g){const y=this.nowDot(g),v=this.delta(y,"+","1",g),E=this.delta(y,"+","2",g);return{begin:v,end:E.sql}}mod7(g){return this.d.hasModOperator?`(${g})%7`:`MOD(${g},7)`}moment(g){switch(g.moment){case"now":{const y=this.nowExpr();return{begin:y,end:y.sql}}case"literal":return this.expandLiteral(g);case"ago":case"from_now":{const y=this.nowDot(g.units),v=(0,r.mkTemporal)(y,"timestamp"),E=this.delta(v,g.moment==="ago"?"-":"+",g.n,g.units);if(g.moment==="ago"&&g.n==="1")return{begin:E,end:y.sql};const _=Number(g.n)+(g.moment==="ago"?-1:1),A={...E,kids:{base:v,delta:this.n(_.toString())}};return{begin:E,end:this.d.sqlAlterTimeExpr(A)}}case"today":return this.thisUnit("day");case"yesterday":return this.lastUnit("day");case"tomorrow":return this.nextUnit("day");case"this":return this.thisUnit(g.units);case"last":return this.lastUnit(g.units);case"next":return this.nextUnit(g.units);case"sunday":return this.weekdayMoment(1,g.which);case"monday":return this.weekdayMoment(2,g.which);case"tuesday":return this.weekdayMoment(3,g.which);case"wednesday":return this.weekdayMoment(4,g.which);case"thursday":return this.weekdayMoment(5,g.which);case"friday":return this.weekdayMoment(6,g.which);case"saturday":return this.weekdayMoment(7,g.which)}}isIn(g,y,v){let E=">=",_="<",A="AND";return g&&(A="OR",E="<",_=">="),y=this.time(y),v=this.time(v),`${this.expr} ${E} ${y} ${A} ${this.expr} ${_} ${v}`}weekdayMoment(g,y){const v=y||"last",E=this.dayofWeek(this.nowExpr()),_=this.thisUnit("day").begin,A=g-1,S=`(${E.sql}-1)`;let b,C;v==="next"?(b=`${this.mod7(`${A}-${S}+6`)}+1`,C=`${this.mod7(`${A}-${S}+6`)}+2`):(b=`${this.mod7(`${S}-${A}+6`)}+1`,C=`${this.mod7(`${S}-${A}+6`)}`);const T=this.delta(_,v==="next"?"+":"-",b,"day"),D=this.delta(_,v==="next"?"+":"-",C,"day");return{begin:T,end:D.sql}}}t.TemporalFilterCompiler=p})(afe),Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.exprToSQL=Qo,Hn.generateFunctionCallExpression=xfe,Hn.generateFieldFragment=YT,Hn.generateOutputFieldFragment=hfe,Hn.generateParameterFragment=pfe,Hn.generateFilterFragment=mfe,Hn.generateDimFragment=al,Hn.generateUngroupedFragment=gfe,Hn.generateDistinctKeyIfNecessary=KT,Hn.generateSumFragment=Efe,Hn.generateSymmetricFragment=vfe,Hn.generateAvgFragment=_fe,Hn.generateCountFragment=Afe,Hn.generateSourceReference=Sfe,Hn.generateCaseSQL=bfe,Hn.getFunctionOrderBy=bM,Hn.getAnalyticPartitions=Cfe,Hn.stringsFromSQLExpression=Tfe;const ul=Ye,VT=W2,Oit=Ho,Fit=afe,Is=wt,Nit=Rt,lfe=9;function cfe(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-lfe);let c=`(${`(
971
971
  SUM(DISTINCT ${`ROUND(${`CAST(COALESCE(${e}, 0) AS ${t.defaultDecimalType})`}*${o}, ${lfe})`} + ${s})
972
972
  - SUM(DISTINCT ${s})
973
973
  )`}/${o})`;return c=`CAST(${c} AS ${t.defaultNumberType})`,c}function Qo(t,e,r,i=new Is.GenerateState){var s;const o=function(c){const f=Qo(t,e,c,i);return(0,ul.exprHasKids)(c)?`(${f})`:f};let u=r;if((0,ul.exprHasE)(r)){u={...r};const c=o(u.e);u.e={...u.e,sql:c}}else if((0,ul.exprHasKids)(r)){u={...r};const c=r.kids;for(const[f,d]of Object.entries(c))d!==null&&(Array.isArray(d)?u.kids[f]=d.map(x=>({...x,sql:o(x)})):u.kids[f]={...c[f],sql:o(d)})}const a=t.getQueryInfo(),l=e.dialect.exprToSQL(a,u);if(l)return l;switch(u.node){case"field":return YT(t,e,u,i);case"parameter":return pfe(t,e,u,i);case"filteredExpr":return mfe(t,e,u,i);case"all":case"exclude":return gfe(t,e,u,i);case"genericSQLExpr":return Array.from(Tfe(t,e,u,i)).join("");case"aggregate":{let c="";if(u.function==="sum")c=Efe(t,e,u,i);else if(u.function==="avg")c=_fe(t,e,u,i);else if(u.function==="count")c=Afe(t,e,u,i);else if(u.function==="min"||u.function==="max"||u.function==="distinct")c=vfe(t,e,u,i);else throw new Error(`Internal Error: Unknown aggregate function ${u.function}`);if(t.root().isComplexQuery){let f=t.groupSet;return i.totalGroupSet!==-1&&(f=i.totalGroupSet),(0,Is.caseGroup)([f],c)}return c}case"function_parameter":throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");case"outputField":return hfe(t,e,u);case"function_call":return xfe(t,e,u,i);case"spread":throw new Error("Internal Error: expandFunctionCall() failed to process node: 'spread'");case"source-reference":return Sfe(t,e,u);case"+":case"-":case"*":case"%":case"/":case">":case"<":case">=":case"<=":case"=":return`${u.kids.left.sql}${u.node}${u.kids.right.sql}`;case"!=":return`COALESCE(${`${u.kids.left.sql}!=${u.kids.right.sql}`},true)`;case"and":case"or":return`${u.kids.left.sql} ${u.node} ${u.kids.right.sql}`;case"coalesce":return`COALESCE(${u.kids.left.sql},${u.kids.right.sql})`;case"in":{const c=u.kids.oneOf.map(f=>f.sql).join(",");return`${u.kids.e.sql} ${u.not?"NOT IN":"IN"} (${c})`}case"like":case"!like":{const c=u.node==="like"?"LIKE":"NOT LIKE",f=u.kids.right.node==="stringLiteral"?e.dialect.sqlLike(c,(s=u.kids.left.sql)!==null&&s!==void 0?s:"",u.kids.right.literal):`${u.kids.left.sql} ${c} ${u.kids.right.sql}`;return u.node==="like"?f:`COALESCE(${f},true)`}case"()":return`(${u.e.sql})`;case"not":return`COALESCE(NOT ${u.e.sql},TRUE)`;case"unary-":return`-${u.e.sql}`;case"is-null":return`${u.e.sql} IS NULL`;case"is-not-null":return`${u.e.sql} IS NOT NULL`;case"true":case"false":return u.node;case"null":return"NULL";case"case":return bfe(u);case"":return"";case"filterCondition":return u.e.sql?(u.sql=u.e.sql,u.sql):"";case"functionDefaultOrderBy":case"functionOrderBy":return"";case"compositeField":return"{COMPOSITE_FIELD}";case"filterMatch":return Lit(e,u,a);case"filterLiteral":return"INTERNAL ERROR FILTER EXPRESSION VALUE SHOULD NOT BE USED";default:throw new Error(`Internal Error: Unknown expression node '${u.node}' ${JSON.stringify(u,void 0,2)}`)}}function Lit(t,e,r){var i;let s=e.kids.filterExpr;for(;s.node==="()";)s=s.e;if(s.node==="parameter"){const a=s.path[0];(i=t.eventStream)===null||i===void 0||i.emit("source-argument-compiled",{name:a});const l=t.arguments()[a];if(l.value)s=l.value;else throw new Error(`Parameter ${a} was expected to be a filter expression`)}if(s.node!=="filterLiteral")throw new Error("Can only use filter expression literals or parameters as filter expressions");const o=s.filterSrc;let u;switch(e.dataType){case"string":u=VT.StringFilterExpression.parse(o);break;case"number":u=VT.NumberFilterExpression.parse(o);break;case"boolean":u=VT.BooleanFilterExpression.parse(o);break;case"date":case"timestamp":u=VT.TemporalFilterExpression.parse(o);break;default:throw new Error(`unsupported filter type ${e.dataType}`)}if(u.log.length>0)throw new Error(`Filter expression parse error: ${u.log[0]}`);return Fit.FilterCompilers.compile(e.dataType,u.parsed,e.kids.expr.sql||"",t.dialect,r)}function Iit(t,e){return new Map(t.params.map((r,i)=>{const s=r.isVariadic?(0,Is.range)(i,e):[i];return[r.name,{param:r,argIndexes:s}]}))}function ffe(t,e,r,i,s){function o(l){const c=[];for(let f=0;f<l.length;)c.push(l[f]),f+=1,f<l.length&&c.push(",");return c}const u=Iit(e,r.length);if(e.dialect[t]===void 0)throw new Error(`Function is not defined for '${t}' dialect`);return(0,Is.exprMap)(e.dialect[t].e,l=>{var c,f;if(l.node==="spread"){const d=l.e;if(d.node!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const x=u.get(d.name);if(x===void 0)return l;const p=x.argIndexes.map(m=>r[m]);return(0,Is.composeSQLExpr)(o(p))}else if(l.node==="function_parameter"){const d=u.get(l.name);if(d===void 0)return l;if(d.param.isVariadic){const x=d.argIndexes.map(p=>r[p]);return(0,Is.composeSQLExpr)(o(x))}else return r[d.argIndexes[0]]}else{if(l.node==="aggregate_order_by")return i?(0,Is.composeSQLExpr)([` ${(c=l.prefix)!==null&&c!==void 0?c:""}${i}${(f=l.suffix)!==null&&f!==void 0?f:""}`]):{node:""};if(l.node==="aggregate_limit")return s?(0,Is.composeSQLExpr)([` ${s}`]):{node:""}}return l})}function dfe(t,e){const r=t.slice(0,e).find(i=>i.isVariadic);return r??t[e]}function $it(t,e,r,i,s,o,u,a){if(o)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${u}`);const l=al(t,e,r,a),c=i?al(t,e,i,a):"";return e.dialect.sqlStringAggDistinct(s,l,c)}function Bit(t,e,r,i,s,o,u,a,l){const c=e.root().isComplexQuery,f=Cfe(e,a),d=[...c?["group_set"]:[],...f],x=d.length>0?`PARTITION BY ${d.join(", ")}`:"";let p=l??"";const m=s.dialect[t];if(!l&&m.needsWindowOrderBy){const E=[];let _;const A=e.firstSegment.orderBy||e.calculateDefaultOrderBy();for(const S of A){if(typeof S.field=="string"?_={name:S.field,fif:e.getField(S.field)}:_=e.getFieldByNumber(S.field),"expressionType"in _.fif.f.fieldDef){const b=_.fif.f.fieldDef.expressionType;if((0,ul.expressionIsAnalytic)(b))continue}if(e.firstSegment.type==="reduce"){const b=_.fif.getAnalyticalSQL(!1);E.push(` ${b} ${S.dir||"ASC"}`)}else if(e.firstSegment.type==="project"){if(_.fif.parent!==e)throw new Error(`Field instance parent mismatch: field '${_.name}' has parent from different result structure. This likely means the field is from a previous pipeline stage and needs special handling.`);const b=_.fif.generateExpression();E.push(` ${b} ${S.dir||"ASC"}`)}}E.length>0&&(p=" "+r.dialect.sqlOrderBy(E,"analytical"))}let g="";if(m.between){const[E,_]=[m.between.preceding,m.between.following].map(A=>{if(A===-1)return"UNBOUNDED";if(typeof A=="number")return A;const S=s.params.findIndex(C=>C.name===A),b=u[S];if(b.node!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return b.literal});g=`ROWS BETWEEN ${E} PRECEDING AND ${_} FOLLOWING`}let v=`${Qo(e,r,i,o)} OVER(${x} ${p} ${g})`;return c&&(v=`CASE WHEN group_set=${e.groupSet} THEN ${v} END`),v}function xfe(t,e,r,i){var s,o,u;const a=r.overload,l=r.kids.args,c=(s=r.overload.isSymmetric)!==null&&s!==void 0?s:!1,f=(0,ul.expressionIsAggregate)(a.returnType.expressionType)&&!c&&KT(t,e,r.structPath),d=r.limit?`LIMIT ${r.limit}`:void 0;if(r.name==="string_agg"&&f&&!e.dialect.supportsAggDistinct&&e.dialect.name!=="snowflake")return $it(t,e,l[0],l[1],f,r.kids.orderBy,e.dialect.name,i);if(f){if(!e.dialect.supportsAggDistinct)throw new Error(`Function \`${r.name}\` does not support fanning out in ${e.dialect.name}`);const x=l.map(g=>al(t,e,g,i)),p=(o=r.kids.orderBy)!==null&&o!==void 0?o:[],m=p.map(g=>{var y;const v=(y=a.dialect[e.dialect.name].defaultOrderByArgIndex)!==null&&y!==void 0?y:0,E=g.node==="functionOrderBy"?g.e:l[v];return al(t,e,E,i)});return e.dialect.sqlAggDistinct(f,[...x,...m],g=>{const y=g.map((S,b)=>b<l.length&&dfe(a.params,b).allowedTypes.every(T=>(0,ul.isLiteral)(T.evalSpace))?l[b]:(0,Is.composeSQLExpr)([S])),v=y.slice(0,x.length),E=y.slice(x.length).map((S,b)=>({node:"functionOrderBy",e:S,dir:p[b].dir})),_=bM(t,e,i,E,v,a),A=ffe(e.dialect.name,a,v,_,d);return Qo(t,e,A,i)})}else{const x=(0,ul.expressionIsAggregate)(a.returnType.expressionType)?l.map((g,y)=>dfe(a.params,y).allowedTypes.every(E=>(0,ul.isLiteral)(E.evalSpace))?g:(0,Is.composeSQLExpr)([al(t,e,g,i)])):l,p=r.kids.orderBy?bM(t,e,i,r.kids.orderBy,l,a):"",m=ffe(e.dialect.name,a,x,p,d);if((0,ul.expressionIsAnalytic)(a.returnType.expressionType)){const g=((u=r.partitionBy)!==null&&u!==void 0?u:[]).map(y=>`(${t.getField(y).getAnalyticalSQL(!1)})`);return Bit(e.dialect.name,t,e,m,a,i,l,g,p)}return Qo(t,e,m,i)}}function YT(t,e,r,i){const s=e.getFieldByName(r.path);return(0,ul.hasExpression)(s.fieldDef)?`(${Qo(t,s.parent,s.fieldDef.e,i)})`:s.fieldDef.type==="string"&&s.fieldDef.name==="__distinct_key"?Rfe(s,t):(0,Oit.sqlFullChildReference)(s.parent,s.fieldDef.name,s.parent.structDef.type==="record"?{result:t,field:s}:void 0)}function hfe(t,e,r,i){return`(${t.getField(r.name).getAnalyticalSQL(!1)})`}function pfe(t,e,r,i){var s;const o=r.path[0];(s=e.eventStream)===null||s===void 0||s.emit("source-argument-compiled",{name:o});const u=e.arguments()[o];if(u.value)return Qo(t,e,u.value,i);throw new Error(`Can't generate SQL, no value for ${r.path}`)}function mfe(t,e,r,i){const s=new Is.AndChain(i.whereSQL);for(const o of r.kids.filterList)s.add(Qo(t,e,o.e,i.withWhere()));return Qo(t,e,r.kids.e,i.withWhere(s.sql()))}function al(t,e,r,i){let s=Qo(t,e,r,i);return i.whereSQL&&(s=`CASE WHEN ${i.whereSQL} THEN ${s} END`),s}function gfe(t,e,r,i){if(i.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let s,o;if(r.fields&&r.fields.length>0){const f=(0,Is.groupingKey)(r.node,r.fields);if(o=t.ungroupedSets.get(f),o===void 0)throw new Error(`Internal Error, cannot find groupset with key ${f}`);s=o.groupSet}else s=t.parent?t.parent.groupSet:0;const u=Qo(t,e,r.e,i.withTotal(s)),a=t.getUngroupPartitions(o);let l="";const c=a.map(f=>f.getAnalyticalSQL(!0)).join(", ");return c.length>0&&(l=`PARTITION BY ${c}`),`MAX(${u}) OVER (${l})`}function yfe(t,e){const r=t.getDistinctKey();return Rfe(r,e)}function KT(t,e,r){let i=e;if(r&&(i=e.getStructByName(r)),kit(i,t))return yfe(i,t)}function Efe(t,e,r,i){const s=al(t,e,r.e,i),o=KT(t,e,r.structPath);let u;return o?e.dialect.supportsSumDistinctFunction?u=e.dialect.sqlSumDistinct(o,s,"SUM"):u=cfe(e.dialect,s,o):u=`SUM(${s})`,`COALESCE(${u},0)`}function vfe(t,e,r,i){const s=al(t,e,r.e,i);return`${r.function==="distinct"?"count(distinct ":r.function+"("}${s})`}function _fe(t,e,r,i){const s=al(t,e,r.e,i),o=KT(t,e,r.structPath);if(o){let u=o;i.whereSQL&&(u=`CASE WHEN ${i.whereSQL} THEN ${o} END`);let a,l;return e.dialect.supportsSumDistinctFunction?l=e.dialect.sqlSumDistinct(o,s,"AVG"):(a=cfe(e.dialect,s,o),l=`(${a})/NULLIF(COUNT(DISTINCT CASE WHEN ${s} IS NOT NULL THEN ${u} END),0)`),l}else return`AVG(${s})`}function Afe(t,e,r,i){let s="COUNT(",o="1",u=e;r.structPath&&(u=e.getStructByName(r.structPath));const a=u.getJoinableParent().getIdentifier(),l=t.root().joins.get(a);if(!l)throw new Error(`Join ${a} not found in result set`);return(!l.leafiest||l.makeUniqueKey)&&(s="COUNT(DISTINCT ",o=yfe(u,t)),i.whereSQL?`${s}CASE WHEN ${i.whereSQL} THEN ${o} END)`:`${s}${o})`}function Sfe(t,e,r){return r.path===void 0?e.getSQLIdentifier():e.getFieldByName(r.path).getIdentifier()}function bfe(t){const e=["CASE"];t.kids.caseValue!==void 0&&e.push(`${t.kids.caseValue.sql}`);for(let r=0;r<t.kids.caseWhen.length;r+=1)e.push(`WHEN ${t.kids.caseWhen[r].sql} THEN ${t.kids.caseThen[r].sql}`);return t.kids.caseElse!==void 0&&e.push(`ELSE ${t.kids.caseElse.sql}`),e.push("END"),e.join(" ")}function bM(t,e,r,i,s,o){if(i.length!==0)return"ORDER BY "+i.map(u=>{var a;const l=(a=o.dialect[e.dialect.name].defaultOrderByArgIndex)!==null&&a!==void 0?a:0,c=u.node==="functionOrderBy"?u.e:s[l],f=al(t,e,c,r),d=u.dir==="asc"?" ASC":u.dir==="desc"?" DESC":"";return`${f}${d}`}).join(", ")}function Cfe(t,e){const r=[];let i=t.parent;for(;i!==void 0;){const o=i.fields(u=>(0,Nit.isBasicScalar)(u.f)&&u.fieldUsage.type==="result").map(u=>u.getAnalyticalSQL(!0));r.push(...o),i=i.parent}return e&&r.push(...e),r}function*Tfe(t,e,r,i){const s=[...r.kids.args];for(const o of r.src){yield o;const u=s.shift();u&&(yield Qo(t,e,u,i))}}function Rfe(t,e){var r;const i=t.parent;if(i.primaryKey()){const s=i.getPrimaryKeyField(t.fieldDef);return YT(e,i,{node:"field",path:[s.getIdentifier()]},new Is.GenerateState)}else if(i.structDef.type==="array"){const s=(r=i.parent)===null||r===void 0?void 0:r.getDistinctKey();let o="";return s&&i.parent&&(o=YT(e,i.parent,{node:"field",path:["__distinct_key"]},new Is.GenerateState)),i.dialect.sqlMakeUnnestKey(o,i.dialect.sqlFieldReference(i.getIdentifier(),"table","__row_id","string"))}else return i.dialect.sqlFieldReference(i.getIdentifier(),"table","__distinct_key","string")}function kit(t,e){const r=t.getJoinableParent().getIdentifier(),i=e.root().joins.get(r);if(i)return!i.leafiest;throw new Error(`Join ${r} not found in result set`)}var KE={},XE={},Y2={};Object.defineProperty(Y2,"__esModule",{value:!0}),Y2.shouldMaterialize=Uit,Y2.buildQueryMaterializationSpec=jit;const Mit=wt,Pit=Ns;function Uit(t){const e=structuredClone(t);return e&&(e.inherits=void 0),(0,Pit.annotationToTag)(e).tag.has("materialize")}function jit(t,e,r){if(!e)throw new Error(`Query tagged to materialize, but its name is not specified. ${t}`);if(!t)throw new Error(`Query tagged to materialize, but its path is not specified: ${e}`);const i={path:t,source:void 0,queryName:e},s=(0,Mit.generateHash)(JSON.stringify(i)).replace(/-/g,"_"),o=`${r?`${r}_`:""}${e}_${s}`;return{...i,id:o}}Object.defineProperty(XE,"__esModule",{value:!0}),XE.StageWriter=void 0;const qit=Y2,K2=wt;class zit{constructor(e=!0,r){this.parent=r,this.withs=[],this.stageNames=[],this.udfs=[],this.pdts=[],this.dependenciesToMaterialize={},this.stagePrefix="__stage",this.stageNumber=0,this.useCTE=e}nextName(){return`${this.stagePrefix}${this.root().stageNumber++}`}getName(e){return this.stageNames[e]}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){if(this.useCTE){this.withs.push(e);const r=this.nextName();return this.stageNames.push(r),r}else return this.withs[0]=e,(0,K2.indent)(`
@@ -1394,7 +1394,7 @@ z{{{{{{{{Ӊ
1394
1394
  | ${" ".repeat(a)}^`)}else s=`line ${u+1}: char ${a}: ${i.message}`}r!==o&&(s=`FILE: ${o}
1395
1395
  `+s,r=o),e!==""?e=`${e}
1396
1396
  ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,Fmt.isSourceDef)(a)||a.type==="query")&&(r[u]=a)}return r}translate(e){if(this.finalAnswer)return this.finalAnswer;const r=this.translateStep.step(this,e);return r.final&&(this.finalAnswer=r),r}translatorForDependency(e){return this.childTranslators.get(e)}importAt(e){for(let r=0;r<this.imports.length;r++){const i=this.imports[r];if((0,bj.locationContainsPosition)(i.location,e))return i}}metadata(){return this.metadataStep.step(this)}modelAnnotation(e){return this.modelAnnotationStep.step(this,e)}tablePathInfo(){return this.tablePathInfoStep.step(this)}completions(e){return this.completionsStep.step(this,e)}helpContext(e){return this.helpContextStep.step(this,e)}defaultLocation(){return{url:this.sourceURL,range:{start:{line:0,character:0},end:{line:0,character:0}}}}rangeFromContext(e){return(0,bj.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Af.MalloyTranslation=Cj;class D2e extends Cj{constructor(e,r){super(e),this.root=r}}Af.MalloyChildTranslator=D2e;class Jmt extends Cj{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new Sj.Zone,this.importZone=new Sj.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new Sj.Zone,this.root=this,this.logger=new R2e.BaseMessageLogger(s),i&&this.update(i)}update(e){var r,i,s;this.schemaZone.updateFrom(e.tables,(r=e.errors)===null||r===void 0?void 0:r.tables),this.importZone.updateFrom(e.urls,(i=e.errors)===null||i===void 0?void 0:i.urls),this.sqlQueryZone.updateFrom(e.compileSQL,(s=e.errors)===null||s===void 0?void 0:s.compileSQL);for(const o in e.translations)this.pretranslatedModels.set(o,e.translations[o])}logError(e,r,i){return this.logger.log((0,R2e.makeLogMessage)(e,r,{severity:"error",...i})),e}}Af.MalloyTranslator=Jmt;function w2e(t){return[...Object.keys(t),...Object.keys(t).map(e=>w2e(t[e])).flat()]}var n_={};Object.defineProperty(n_,"__esModule",{value:!0}),n_.ExploreQueryWalker=void 0,n_.exploreQueryWalkerBuilder=egt;const Zmt=Z0;class O2e{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}n_.ExploreQueryWalker=O2e;function egt(t,e){const r=new O2e(t),i=r;return Zmt.ParseTreeWalker.DEFAULT.walk(i,e),r}var r_={},i_={},ea={},ch={},s_={};Object.defineProperty(s_,"__esModule",{value:!0}),s_.MALLOY_INTERFACE_TYPES=void 0,s_.MALLOY_INTERFACE_TYPES={Aggregate:{type:"struct",name:"Aggregate",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},Annotation:{type:"struct",name:"Annotation",fields:{value:{type:"string",optional:!1,array:!1}}},AnonymousQueryInfo:{type:"struct",name:"AnonymousQueryInfo",fields:{schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},ArrayCell:{type:"struct",name:"ArrayCell",fields:{array_value:{type:"Cell",array:!0,optional:!1}}},ArrayType:{type:"struct",name:"ArrayType",fields:{element_type:{type:"AtomicType",optional:!1,array:!1}}},AtomicType:{type:"union",name:"AtomicType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType"}},BooleanCell:{type:"struct",name:"BooleanCell",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanLiteral:{type:"struct",name:"BooleanLiteral",fields:{boolean_value:{type:"boolean",optional:!1,array:!1}}},BooleanType:{type:"struct",name:"BooleanType",fields:{}},CalculateInfo:{type:"struct",name:"CalculateInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},CalculateOperation:{type:"struct",name:"CalculateOperation",fields:{name:{type:"string",optional:!1,array:!1},field:{type:"Field",optional:!1,array:!1}}},Cell:{type:"union",name:"Cell",options:{string_cell:"StringCell",boolean_cell:"BooleanCell",date_cell:"DateCell",timestamp_cell:"TimestampCell",number_cell:"NumberCell",json_cell:"JSONCell",record_cell:"RecordCell",array_cell:"ArrayCell",null_cell:"NullCell",sql_native_cell:"SQLNativeCell"}},CompileModelRequest:{type:"struct",name:"CompileModelRequest",fields:{model_url:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileModelResponse:{type:"struct",name:"CompileModelResponse",fields:{model:{type:"ModelInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},CompileQueryRequest:{type:"struct",name:"CompileQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!0,array:!1},query_malloy:{type:"string",optional:!0,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileQueryResponse:{type:"struct",name:"CompileQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},translations:{type:"Translation",array:!0,optional:!0},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},CompileSourceRequest:{type:"struct",name:"CompileSourceRequest",fields:{model_url:{type:"string",optional:!1,array:!1},name:{type:"string",optional:!1,array:!1},extend_model_url:{type:"string",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},CompileSourceResponse:{type:"struct",name:"CompileSourceResponse",fields:{source:{type:"SourceInfo",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},CompilerNeeds:{type:"struct",name:"CompilerNeeds",fields:{table_schemas:{type:"SQLTable",array:!0,optional:!0},sql_schemas:{type:"SQLQuery",array:!0,optional:!0},files:{type:"File",array:!0,optional:!0},connections:{type:"Connection",array:!0,optional:!0},translations:{type:"Translation",array:!0,optional:!0}}},Connection:{type:"struct",name:"Connection",fields:{name:{type:"string",optional:!1,array:!1},dialect:{type:"string",optional:!0,array:!1}}},Data:{type:"union",name:"Data",options:{record_cell:"RecordCell",array_cell:"ArrayCell"}},DateCell:{type:"struct",name:"DateCell",fields:{date_value:{type:"string",optional:!1,array:!1}}},DateLiteral:{type:"struct",name:"DateLiteral",fields:{date_value:{type:"string",optional:!1,array:!1},granularity:{type:"DateTimeframe",optional:!0,array:!1},timezone:{type:"string",optional:!0,array:!1}}},DateTimeframe:{type:"enum",name:"DateTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5}},DateType:{type:"struct",name:"DateType",fields:{timeframe:{type:"DateTimeframe",optional:!0,array:!1}}},DimensionInfo:{type:"struct",name:"DimensionInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},DocumentPosition:{type:"struct",name:"DocumentPosition",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},DocumentRange:{type:"struct",name:"DocumentRange",fields:{start:{type:"DocumentPosition",optional:!1,array:!1},end:{type:"DocumentPosition",optional:!1,array:!1}}},DrillOperation:{type:"struct",name:"DrillOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},Expression:{type:"union",name:"Expression",options:{field_reference:"Reference",time_truncation:"TimeTruncationFieldReference",filtered_field:"FilteredField",literal_value:"LiteralValueExpression",moving_average:"MovingAverage"}},Field:{type:"struct",name:"Field",fields:{expression:{type:"Expression",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},FieldInfo:{type:"union",name:"FieldInfo",options:{dimension:"DimensionInfo",measure:"MeasureInfo",join:"JoinInfo",view:"ViewInfo",calculate:"CalculateInfo"}},File:{type:"struct",name:"File",fields:{url:{type:"string",optional:!1,array:!1},contents:{type:"string",optional:!0,array:!1},invalidation_key:{type:"string",optional:!0,array:!1}}},Filter:{type:"union",name:"Filter",options:{filter_string:"FilterStringApplication",literal_equality:"LiteralEqualityComparison"}},FilterExpressionLiteral:{type:"struct",name:"FilterExpressionLiteral",fields:{filter_expression_value:{type:"string",optional:!1,array:!1}}},FilterExpressionType:{type:"struct",name:"FilterExpressionType",fields:{filter_type:{type:"FilterableType",optional:!1,array:!1}}},FilterOperation:{type:"struct",name:"FilterOperation",fields:{filter:{type:"Filter",optional:!1,array:!1}}},FilterStringApplication:{type:"struct",name:"FilterStringApplication",fields:{expression:{type:"Expression",optional:!1,array:!1},filter:{type:"string",optional:!1,array:!1}}},FilterableType:{type:"union",name:"FilterableType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",date_type:"DateType",timestamp_type:"TimestampType"}},FilteredField:{type:"struct",name:"FilteredField",fields:{field_reference:{type:"Reference",optional:!1,array:!1},where:{type:"FilterOperation",array:!0,optional:!1}}},GroupBy:{type:"struct",name:"GroupBy",fields:{name:{type:"string",optional:!0,array:!1},field:{type:"Field",optional:!1,array:!1}}},JSONCell:{type:"struct",name:"JSONCell",fields:{json_value:{type:"string",optional:!1,array:!1}}},JSONType:{type:"struct",name:"JSONType",fields:{}},JoinInfo:{type:"struct",name:"JoinInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},relationship:{type:"Relationship",optional:!1,array:!1}}},Limit:{type:"struct",name:"Limit",fields:{limit:{type:"number",optional:!1,array:!1}}},LiteralEqualityComparison:{type:"struct",name:"LiteralEqualityComparison",fields:{expression:{type:"Expression",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},LiteralValue:{type:"union",name:"LiteralValue",options:{string_literal:"StringLiteral",number_literal:"NumberLiteral",date_literal:"DateLiteral",timestamp_literal:"TimestampLiteral",boolean_literal:"BooleanLiteral",null_literal:"NullLiteral",filter_expression_literal:"FilterExpressionLiteral"}},LiteralValueExpression:{type:"struct",name:"LiteralValueExpression",fields:{literal_value:{type:"LiteralValue",optional:!1,array:!1}}},Location:{type:"struct",name:"Location",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"Range",optional:!1,array:!1}}},LogMessage:{type:"struct",name:"LogMessage",fields:{url:{type:"string",optional:!1,array:!1},range:{type:"DocumentRange",optional:!1,array:!1},severity:{type:"LogSeverity",optional:!1,array:!1},message:{type:"string",optional:!1,array:!1}}},LogSeverity:{type:"enum",name:"LogSeverity",values:{debug:1,info:2,warn:3,error:4}},MeasureInfo:{type:"struct",name:"MeasureInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"AtomicType",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ModelEntryValue:{type:"union",name:"ModelEntryValue",options:{source:"SourceInfo",query:"QueryInfo"}},ModelInfo:{type:"struct",name:"ModelInfo",fields:{entries:{type:"ModelEntryValue",array:!0,optional:!1},annotations:{type:"Annotation",array:!0,optional:!0},anonymous_queries:{type:"AnonymousQueryInfo",array:!0,optional:!1}}},MovingAverage:{type:"struct",name:"MovingAverage",fields:{field_reference:{type:"Reference",optional:!1,array:!1},rows_preceding:{type:"number",optional:!0,array:!1},rows_following:{type:"number",optional:!0,array:!1},partition_fields:{type:"Reference",array:!0,optional:!0}}},Nest:{type:"struct",name:"Nest",fields:{name:{type:"string",optional:!0,array:!1},view:{type:"View",optional:!1,array:!1}}},NullCell:{type:"struct",name:"NullCell",fields:{}},NullLiteral:{type:"struct",name:"NullLiteral",fields:{}},NumberCell:{type:"struct",name:"NumberCell",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberLiteral:{type:"struct",name:"NumberLiteral",fields:{number_value:{type:"number",optional:!1,array:!1}}},NumberSubtype:{type:"enum",name:"NumberSubtype",values:{integer:1,decimal:2}},NumberType:{type:"struct",name:"NumberType",fields:{subtype:{type:"NumberSubtype",optional:!0,array:!1}}},OrderBy:{type:"struct",name:"OrderBy",fields:{field_reference:{type:"Reference",optional:!1,array:!1},direction:{type:"OrderByDirection",optional:!0,array:!1}}},OrderByDirection:{type:"enum",name:"OrderByDirection",values:{asc:1,desc:2}},ParameterInfo:{type:"struct",name:"ParameterInfo",fields:{name:{type:"string",optional:!1,array:!1},type:{type:"ParameterType",optional:!1,array:!1},default_value:{type:"LiteralValue",optional:!0,array:!1}}},ParameterType:{type:"union",name:"ParameterType",options:{string_type:"StringType",boolean_type:"BooleanType",number_type:"NumberType",json_type:"JSONType",sql_native_type:"SQLNativeType",date_type:"DateType",timestamp_type:"TimestampType",array_type:"ArrayType",record_type:"RecordType",filter_expression_type:"FilterExpressionType"}},ParameterValue:{type:"struct",name:"ParameterValue",fields:{name:{type:"string",optional:!1,array:!1},value:{type:"LiteralValue",optional:!1,array:!1}}},Position:{type:"struct",name:"Position",fields:{line:{type:"number",optional:!1,array:!1},character:{type:"number",optional:!1,array:!1}}},Query:{type:"struct",name:"Query",fields:{definition:{type:"QueryDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},QueryArrow:{type:"struct",name:"QueryArrow",fields:{source:{type:"QueryArrowSource",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},QueryArrowSource:{type:"union",name:"QueryArrowSource",options:{refinement:"QueryRefinement",source_reference:"Reference"}},QueryDefinition:{type:"union",name:"QueryDefinition",options:{arrow:"QueryArrow",query_reference:"Reference",refinement:"QueryRefinement"}},QueryInfo:{type:"struct",name:"QueryInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"Query",optional:!0,array:!1},code:{type:"string",optional:!0,array:!1},location:{type:"Location",optional:!0,array:!1}}},QueryRefinement:{type:"struct",name:"QueryRefinement",fields:{base:{type:"QueryDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},Range:{type:"struct",name:"Range",fields:{start:{type:"Position",optional:!1,array:!1},end:{type:"Position",optional:!1,array:!1}}},RecordCell:{type:"struct",name:"RecordCell",fields:{record_value:{type:"Cell",array:!0,optional:!1}}},RecordType:{type:"struct",name:"RecordType",fields:{fields:{type:"DimensionInfo",array:!0,optional:!1}}},Reference:{type:"struct",name:"Reference",fields:{name:{type:"string",optional:!1,array:!1},path:{type:"string",array:!0,optional:!0},parameters:{type:"ParameterValue",array:!0,optional:!0}}},Relationship:{type:"enum",name:"Relationship",values:{one:1,many:2,cross:3}},Result:{type:"struct",name:"Result",fields:{data:{type:"Data",optional:!0,array:!1},schema:{type:"Schema",optional:!1,array:!1},sql:{type:"string",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},model_annotations:{type:"Annotation",array:!0,optional:!0},query_timezone:{type:"string",optional:!0,array:!1},source_annotations:{type:"Annotation",array:!0,optional:!0}}},RunIndexQueryRequest:{type:"struct",name:"RunIndexQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},source_name:{type:"string",optional:!1,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunIndexQueryResponse:{type:"struct",name:"RunIndexQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},RunQueryRequest:{type:"struct",name:"RunQueryRequest",fields:{model_url:{type:"string",optional:!1,array:!1},query:{type:"Query",optional:!0,array:!1},query_malloy:{type:"string",optional:!0,array:!1},default_row_limit:{type:"number",optional:!0,array:!1},exclude_references:{type:"boolean",optional:!0,array:!1},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1}}},RunQueryResponse:{type:"struct",name:"RunQueryResponse",fields:{result:{type:"Result",optional:!0,array:!1},default_row_limit_added:{type:"number",optional:!0,array:!1},logs:{type:"LogMessage",array:!0,optional:!0},compiler_needs:{type:"CompilerNeeds",optional:!0,array:!1},timing_info:{type:"TimingInfo",optional:!0,array:!1}}},SQLNativeCell:{type:"struct",name:"SQLNativeCell",fields:{sql_native_value:{type:"string",optional:!1,array:!1}}},SQLNativeType:{type:"struct",name:"SQLNativeType",fields:{sql_type:{type:"string",optional:!0,array:!1}}},SQLQuery:{type:"struct",name:"SQLQuery",fields:{sql:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},SQLTable:{type:"struct",name:"SQLTable",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!0,array:!1},connection_name:{type:"string",optional:!1,array:!1}}},Schema:{type:"struct",name:"Schema",fields:{fields:{type:"FieldInfo",array:!0,optional:!1}}},SourceInfo:{type:"struct",name:"SourceInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},parameters:{type:"ParameterInfo",array:!0,optional:!0}}},StringCell:{type:"struct",name:"StringCell",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringLiteral:{type:"struct",name:"StringLiteral",fields:{string_value:{type:"string",optional:!1,array:!1}}},StringType:{type:"struct",name:"StringType",fields:{}},TimeTruncationFieldReference:{type:"struct",name:"TimeTruncationFieldReference",fields:{field_reference:{type:"Reference",optional:!1,array:!1},truncation:{type:"TimestampTimeframe",optional:!1,array:!1}}},TimestampCell:{type:"struct",name:"TimestampCell",fields:{timestamp_value:{type:"string",optional:!1,array:!1}}},TimestampLiteral:{type:"struct",name:"TimestampLiteral",fields:{timestamp_value:{type:"string",optional:!1,array:!1},granularity:{type:"TimestampTimeframe",optional:!0,array:!1},timezone:{type:"string",optional:!0,array:!1}}},TimestampTimeframe:{type:"enum",name:"TimestampTimeframe",values:{year:1,quarter:2,month:3,week:4,day:5,hour:6,minute:7,second:8}},TimestampType:{type:"struct",name:"TimestampType",fields:{timeframe:{type:"TimestampTimeframe",optional:!0,array:!1}}},TimingInfo:{type:"struct",name:"TimingInfo",fields:{name:{type:"string",optional:!1,array:!1},duration_ms:{type:"number",optional:!1,array:!1},detailed_timing:{type:"TimingInfo",array:!0,optional:!0}}},Translation:{type:"struct",name:"Translation",fields:{url:{type:"string",optional:!1,array:!1},compiled_model_json:{type:"string",optional:!0,array:!1}}},View:{type:"struct",name:"View",fields:{definition:{type:"ViewDefinition",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0}}},ViewArrow:{type:"struct",name:"ViewArrow",fields:{source:{type:"ViewDefinition",optional:!1,array:!1},view:{type:"ViewDefinition",optional:!1,array:!1}}},ViewDefinition:{type:"union",name:"ViewDefinition",options:{arrow:"ViewArrow",view_reference:"Reference",refinement:"ViewRefinement",segment:"ViewSegment"}},ViewInfo:{type:"struct",name:"ViewInfo",fields:{name:{type:"string",optional:!1,array:!1},schema:{type:"Schema",optional:!1,array:!1},annotations:{type:"Annotation",array:!0,optional:!0},definition:{type:"View",optional:!0,array:!1}}},ViewOperation:{type:"union",name:"ViewOperation",options:{group_by:"GroupBy",aggregate:"Aggregate",order_by:"OrderBy",limit:"Limit",where:"FilterOperation",nest:"Nest",having:"FilterOperation",drill:"DrillOperation",calculate:"CalculateOperation"}},ViewRefinement:{type:"struct",name:"ViewRefinement",fields:{base:{type:"ViewDefinition",optional:!1,array:!1},refinement:{type:"ViewDefinition",optional:!1,array:!1}}},ViewSegment:{type:"struct",name:"ViewSegment",fields:{operations:{type:"ViewOperation",array:!0,optional:!1}}}};var Tw={},Tj={},Rw={};Object.defineProperty(Rw,"__esModule",{value:!0}),Rw.RESERVED_WORDS=void 0,Rw.RESERVED_WORDS=["accept","aggregate","declare","dimension","except","explore","group_by","having","index","join_cross","join_one","join_many","limit","measure","nest","order_by","primary_key","project","query","rename","sample","source","sql","turduck","top","where","all","as","asc","avg","boolean","by","case","cast","condition","count","date","day","days","desc","distinct","else","end","exclude","false","for","from","from_sql","has","hour","hours","import","is","json","last","max","min","minute","minutes","month","months","not","now","null","number","on","or","pick","quarter","quarters","second","seconds","string","sum","table","then","this","timestamp","to","true","turtle","week","weeks","when","with","year","years","ungrouped"],Object.defineProperty(Tj,"__esModule",{value:!0}),Tj.maybeQuoteIdentifier=rgt;const tgt=Rw;function ngt(t){const e=!t.match(/^[A-Za-z_][A-Za-z_0-9]*$/),r=tgt.RESERVED_WORDS.includes(t.toLowerCase());return e||r}function rgt(t){const e=t.split(".");for(let r=0;r<e.length;r++)ngt(e[r])&&(e[r]=`\`${e[r]}\``);return e.join(".")}Object.defineProperty(Tw,"__esModule",{value:!0}),Tw.queryToMalloy=igt,Tw.filterToMalloy=sgt;const o_=Tj;function igt(t,{tabWidth:e}={tabWidth:2}){const r=lgt(t);return F2e(r,{tabWidth:e})}function sgt(t,{tabWidth:e}={tabWidth:2}){const r=B2e(t);return F2e(r,{tabWidth:e})}const Rj=Symbol("indent"),ta=Symbol("newline"),Dj=Symbol("outdent"),ogt=Symbol("optional_newline_indent");function F2e(t,{tabWidth:e}={tabWidth:2}){let r="",i=0,s=!0;for(const o of t)if(o===ta)r+=`
1397
- `,s=!0;else if(o===Dj)i--;else if(o===Rj)i++;else{if(o===ogt)continue;s&&(r+=" ".repeat(i*e),s=!1),r+=o}return r}function $1(t,e,r,i){var s;if(e.includes(ta))return[t,ta,Rj,...e,ta,Dj,r];const u=((s=i==null?void 0:i.spaces)!==null&&s!==void 0?s:!0)?" ":"";return[t,u,...e,u,r]}function ugt(t){return{contents:t,quoteCharacter:'"'}}function agt(t,e){const r=[];for(let i=0;i<t.length;i++){const s=t[i];r.push(s),i<t.length-1&&r.push(e)}return r}function wj(t){var e,r;switch(t.kind){case"filter_expression_literal":return[$2e(t.filter_expression_value)];case"boolean_literal":return[t.boolean_value.toString()];case"string_literal":{const{contents:i,quoteCharacter:s}=ugt(t.string_value);return[s,i,s]}case"number_literal":return[t.number_value.toString()];case"null_literal":return["null"];case"date_literal":return[L2e(N2e(t.date_value),(e=t.granularity)!==null&&e!==void 0?e:"day",t.timezone)];case"timestamp_literal":return[L2e(N2e(t.timestamp_value),(r=t.granularity)!==null&&r!==void 0?r:"second",t.timezone)]}}function N2e(t){let e;if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)/.exec(t)){const[r,i,s,o,u,a,l]=e;return[i,s,o,u,a,l]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d)/.exec(t)){const[r,i,s,o,u,a]=e;return[i,s,o,u,a,"00"]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d)(?:00)?/.exec(t)){const[r,i,s,o,u]=e;return[i,s,o,u,"00","00"]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d)/.exec(t)){const[r,i,s,o]=e;return[i,s,o,"00","00","00"]}else if(e=/(\d\d\d\d)-(\d\d)/.exec(t)){const[r,i,s]=e;return[i,s,"01","00","00","00"]}else if(e=/(\d\d\d\d)/.exec(t)){const[r,i]=e;return[i,"01","01","00","00","00"]}return["1970","01","01","00","00","00"]}function L2e([t,e,r,i,s,o],u,a){switch(u){case"year":return`@${t}`;case"quarter":{const l=Math.floor(+e/3)+1;return`@${t}-Q${l}`}case"month":return`@${t}-${e}`;case"week":return`@${t}-${e}-${r}-WK`;case"day":return`@${t}-${e}-${r}`;case"hour":return`@${t}-${e}-${r} ${i}`;case"minute":return`@${t}-${e}-${r} ${i}:${s}`;case"second":return a!==void 0?`@${t}-${e}-${r} ${i}:${s}:${o}[${a}]`:`@${t}-${e}-${r} ${i}:${s}:${o}`;default:throw new Error("Unknown timeframe.")}}function Uc(t){var e;const r=[];for(const i of(e=t.path)!==null&&e!==void 0?e:[])r.push((0,o_.maybeQuoteIdentifier)(i)),r.push(".");if(r.push((0,o_.maybeQuoteIdentifier)(t.name)),t.parameters){const i=[];for(let s=0;s<t.parameters.length;s++){const o=t.parameters[s];i.push((0,o_.maybeQuoteIdentifier)(o.name)),i.push(" is "),i.push(...wj(o.value)),s<t.parameters.length-1&&i.push(",",ta)}r.push(...$1("(",i,")",{spaces:!1}))}return r}function lgt(t){const e=[];return e.push(...u_(t.annotations)),e.push("run: "),e.push(...Oj(t.definition)),e}function cgt(t){const e=[];switch(t.kind){case"source_reference":{e.push(...Uc(t));break}case"refinement":e.push(...Oj(t));break}return e}function Oj(t){const e=[];switch(t.kind){case"arrow":{e.push(...cgt(t.source)),e.push(" -> "),e.push(...fh(t.view));break}case"query_reference":{e.push(...Uc(t));break}case"refinement":{const r=Oj(t.base);t.base.kind==="arrow"?e.push(...$1("(",r,")",{spaces:!1})):e.push(...r),e.push(" + "),e.push(...fh(t.refinement));break}}return e}function fh(t){const e=[];switch(t.kind){case"arrow":{e.push(...fh(t.source)),e.push(" -> "),e.push(...fh(t.view));break}case"view_reference":{e.push(...Uc(t));break}case"refinement":{e.push(...fh(t.base)),e.push(" + "),e.push(...fh(t.refinement));break}case"segment":{e.push(...fgt(t));break}}return e}function fgt(t){if(t.operations.length===0)return["{ }"];const e=t.operations.length>1,r=[];for(let i=0;i<t.operations.length;i++){const s=t.operations[i],o=[s];for(;i<t.operations.length-1;){const u=t.operations[i+1];if(u.kind===s.kind)o.push(u),i++;else break}r.push(...dgt(o)),e&&i<t.operations.length-1&&r.push(ta)}return $1("{",r,"}")}function dgt(t){switch(t[0].kind){case"aggregate":return Nj(t,"aggregate");case"group_by":return Nj(t,"group_by");case"order_by":return pgt(t);case"nest":return ggt(t);case"limit":return _gt(t);case"where":return I2e(t);case"having":return Sgt(t);case"drill":return Agt(t);case"calculate":return Nj(t,"calculate")}}function B1(t,e,r=""){const i=[];i.push(`${t}:`);const s=e.length>1||e.some(o=>o.includes(ta));s?i.push(ta,Rj):i.push(" ");for(let o=0;o<e.length;o++){const u=e[o];i.push(...u),e.length>1&&o<e.length-1&&i.push(r),s&&o<e.length-1&&i.push(ta)}return s&&i.push(Dj),i}function xgt(t){const e=[];return e.push(...Fj(t.expression)),e}function eAt(t){return t}function Fj(t){var e;switch(t.kind){case"field_reference":return Uc(t);case"time_truncation":return[...Uc(t.field_reference),".",t.truncation];case"filtered_field":return[...Uc(t.field_reference),...$1(" {",I2e(t.where),"}")];case"literal_value":return wj(t.literal_value);case"moving_average":{const r=["avg_moving",...$1("(",[...Uc(t.field_reference),t.rows_preceding!==void 0?`, ${t.rows_preceding}`:", 0",t.rows_following!==void 0?`, ${t.rows_following}`:""],")",{spaces:!1})];return!((e=t.partition_fields)===null||e===void 0)&&e.length&&r.push(...$1(" {",["partition_by",": ",...agt(t.partition_fields.flatMap(i=>Uc(i)),", ")],"}")),r}}}function hgt(t,e=!1){const r=[];return e||r.push(...u_(t.field.annotations)),t.name&&(r.push((0,o_.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...xgt(t.field)),r}function Nj(t,e){const r=[],i=t.length===1;return i&&r.push(...u_(t[0].field.annotations)),r.push(...B1(e,t.map(s=>hgt(s,i)))),r}function pgt(t){return B1("order_by",t.map(mgt),",")}function mgt(t){const e=[];return e.push(...Uc(t.field_reference)),t.direction&&(e.push(" "),e.push(t.direction)),e}function ggt(t){const e=[],r=t.length===1;return r&&e.push(...u_(t[0].view.annotations)),e.push(...B1("nest",t.map(i=>ygt(i,r)))),e}function ygt(t,e=!1){const r=[];return e||r.push(...u_(t.view.annotations)),t.name&&(r.push((0,o_.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...Egt(t.view)),r}function Egt(t){return fh(t.definition)}function vgt(t){return[`limit: ${t.limit}`]}function _gt(t){const e=[];for(let r=0;r<t.length;r++)r!==0&&e.push(ta),e.push(...vgt(t[r]));return e}function I2e(t){return B1("where",t.map(Lj),",")}function Agt(t){return B1("drill",t.map(Lj),",")}function Sgt(t){return B1("having",t.map(Lj),",")}const bgt=["`","'",'"'];function $2e(t){let e,r;for(const i of bgt){const s=Cgt(t,i);if(s===t)return`f${i}${t}${i}`;(r===void 0||s.length<r.length)&&(e=i,r=s)}return`f${e}${r}${e}`}function Cgt(t,e){let r="";for(let i=0;i<t.length;i++)t.slice(i).startsWith(e)?(r+="\\"+e,i+=e.length):(r+=t[i],t[i]==="\\"&&(r+=t[++i]));return r}function B2e(t){switch(t.kind){case"filter_string":return[...Fj(t.expression)," ~ ",$2e(t.filter)];case"literal_equality":return[...Fj(t.expression)," = ",...wj(t.value)]}}function Lj(t){return B2e(t.filter)}function u_(t){return t?t.flatMap(Tgt):[]}function Tgt(t){return[t.value.trim(),ta]}var k1={};Object.defineProperty(k1,"__esModule",{value:!0}),k1.nestUnions=Ij,k1.unnestUnions=Dw,k1.convertFromThrift=ww,k1.convertToThrift=Ow;const Rgt=s_;function Ij(t){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(Ij);{const e={};let r;for(const i in t)i==="kind"?r=t[i]:e[i]=Ij(t[i]);return r===void 0?e:{[r]:e}}}function Dw(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(r=>Dw(r,e));{const r=M1(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=Dw(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=Dw(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}function ww(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(e==="number")return t;const r=M1(e);if(r.type!=="enum")throw new Error(`Found a number where a ${e} was expected`);const i=Object.entries(r.values).find(([,s])=>s===t);if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i[0]}else{if(Array.isArray(t))return t.map(r=>ww(r,e));{const r=M1(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0&&t[i]!==null){const s=ww(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=ww(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}}function M1(t){const e=Rgt.MALLOY_INTERFACE_TYPES[t];if(e===void 0)throw new Error(`Unknown Malloy interface type ${t}`);return e}function Ow(t,e){if(t==null)return t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string"){if(e==="string")return t;const r=M1(e);if(r.type==="enum"){const i=r.values[t];if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i}}else{if(Array.isArray(t))return t.map(r=>Ow(r,e));{const r=M1(e);if(r.type==="union"){const i=t.kind,s=r.options[i];if(s===void 0)throw new Error(`${i} is not a valid union of ${e}`);const o=M1(s);if(o.type!=="struct")throw new Error("Union fields must be structs");const u={};for(const a in t){if(a==="kind")continue;const l=o.fields[a];u[a]=Ow(t[a],l.type)}return{[i]:u}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=Ow(t[s],o.type)}return i}}}}(function(t){var e=R&&R.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=R&&R.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.thingy4sddfdfsd=t.thingy4sdfsd=t.thingy4dfdsfs=t.thingy4asdfas=t.thingy4asdfasdf=t.thingy3dfdf=t.thingy3=t.thingy2asdf=t.thingyssdfg=t.thingy123r=t.thingy1=t.res=t.test=t.convertToThrift=t.convertFromThrift=t.unnestUnions=t.nestUnions=t.filterToMalloy=t.queryToMalloy=void 0,r(s_,t);var i=Tw;Object.defineProperty(t,"queryToMalloy",{enumerable:!0,get:function(){return i.queryToMalloy}}),Object.defineProperty(t,"filterToMalloy",{enumerable:!0,get:function(){return i.filterToMalloy}});var s=k1;Object.defineProperty(t,"nestUnions",{enumerable:!0,get:function(){return s.nestUnions}}),Object.defineProperty(t,"unnestUnions",{enumerable:!0,get:function(){return s.unnestUnions}}),Object.defineProperty(t,"convertFromThrift",{enumerable:!0,get:function(){return s.convertFromThrift}}),Object.defineProperty(t,"convertToThrift",{enumerable:!0,get:function(){return s.convertToThrift}}),t.test={entries:[{kind:"source",name:"flights",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"boolean_type"},annotations:[{value:"# foo=1"}]},{kind:"dimension",name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}},{kind:"dimension",name:"arr_rec",type:{kind:"array_type",element_type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}}},{kind:"dimension",name:"rec",type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}},{kind:"join",name:"carriers",relationship:"one",schema:{fields:[{kind:"dimension",name:"code",type:{kind:"string_type"}}]}},{kind:"view",name:"by_carrier",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]}}]},parameters:[{name:"param",type:{kind:"number_type"},default_value:{kind:"number_literal",number_value:7}}]}],anonymous_queries:[]},t.res={connection_name:"foo",data:{kind:"array_cell",array_value:[{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"UA"},{kind:"number_cell",number_value:12341234}]},{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"AA"},{kind:"number_cell",number_value:2343}]}]},schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]},sql:"SELECT * ..."},t.thingy1={definition:{kind:"query_reference",name:"flights_by_carrier"}},t.thingy123r={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingyssdfg={definition:{kind:"refinement",base:{kind:"query_reference",name:"flights"},refinement:{kind:"view_reference",name:"by_carrier"}}},t.thingy2asdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"where",filter:{kind:"filter_string",expression:{kind:"field_reference",name:"carrier"},filter:"WN"}}]}}}},t.thingy3={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}}},t.thingy3dfdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"view_reference",name:"top10"}}}},t.thingy4asdfasdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}},t.thingy4asdfas={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingy4dfdsfs={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"limit",limit:10}]}}}},t.thingy4sdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"limit",limit:10}]}}},t.thingy4sddfdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[]}}}})(ch);var Dgt=R&&R.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),wgt=R&&R.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ogt=R&&R.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var i=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Dgt(r,e,i[s]);return wgt(r,e),r}}();Object.defineProperty(ea,"__esModule",{value:!0}),ea.sourceDefToSourceInfo=M2e,ea.modelDefToModelInfo=Fgt,ea.convertFieldInfos=P1,ea.writeLiteralToTag=z2e,ea.getResultStructMetadataAnnotation=Fw,ea.writeMalloyObjectToTag=U1,ea.extractMalloyObjectFromTag=Lw;const k2e=Ogt(ch),Ms=Ri,$j=Ns,Bj=rs;function M2e(t){var e;const r=t.parameters&&Object.entries(t.parameters).length>0?Object.entries(t.parameters).map(([s,o])=>(0,Ms.isAtomic)(o)?{name:s,type:Nw(o),default_value:P2e(o.value)}:{name:s,type:{kind:"filter_expression_type",filter_type:{kind:`${o.filterType}_type`}},default_value:P2e(o.value)}):void 0;return{name:(e=t.as)!==null&&e!==void 0?e:t.name,schema:{fields:P1(t,t.fields)},parameters:r,annotations:kj(t)}}function Fgt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ms.isSourceDef)(i)){const s=M2e(i);e.entries.push({kind:"source",...s})}else if(i.type==="query"){const s=(0,Ms.getResultStructDefForQuery)(t,i),o=kj(i),u=s.resultMetadata?Fw(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:P1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,Ms.getResultStructDefForQuery)(t,r),s=kj(r),o=i.resultMetadata?Fw(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:P1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}function P2e(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function kj(t){return(0,$j.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function P1(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,$j.annotationToTaglines)(u.annotation).map(d=>({value:d})),f=c.length>0?c:void 0;if((0,Ms.isTurtle)(u)){const d=(0,Ms.getResultStructDefForView)(t,u),x=d.resultMetadata?Fw(d,d.resultMetadata):void 0,p=[...f??[],...x?[x]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:P1(d,d.fields)}};o.push(m)}else if((0,Ms.isAtomic)(u)){const d=(0,Ms.expressionIsAggregate)(u.expressionType),x=(0,Ms.expressionIsScalar)(u.expressionType);if(!d&&!x||u.type==="error")continue;const p=u.resultMetadata?U2e(u,u.resultMetadata):void 0;let m;if((0,Ms.isRecordOrRepeatedRecord)(u)&&u.queryTimezone){const v=Bj.Tag.withPrefix("#(malloy) ");v.set(["query_timezone"],u.queryTimezone),m={value:v.toString()}}const g=[...f??[],...p?[p]:[],...m?[m]:[]],y={kind:d?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:Nw(u),annotations:g.length>0?g:void 0};o.push(y)}else if((0,Ms.isJoinedSource)(u)){const d={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:P1(u,u.fields)},relationship:u.join};o.push(d)}}return o}function U2e(t,e){const r=Bj.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.drillable&&(r.set(["drillable"]),i=!0),e.filterList&&(j2e(r,e.filterList),i=!0),e.drillExpression&&(q2e(r,["drill_expression"],e.drillExpression),i=!0),e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Lgt(t.name));r.set(["drill_expression","code"],o),i=!0}return i?{value:r.toString()}:void 0}function j2e(t,e){for(let r=0;r<e.length;r++){const i=e[r];i.expressionType!=="scalar"||i.isSourceFilter||(t.set(["drill_filters",r,"code"],i.code),i.filterView&&t.set(["drill_filters",r,"filter_view"],i.filterView),i.filterView===void 0&&i.stableFilter!==void 0&&(q2e(t,["drill_filters",r,"expression"],i.stableFilter.expression),i.stableFilter.kind==="filter_string"?(t.set(["drill_filters",r,"kind"],"filter_expression"),t.set(["drill_filters",r,"filter_expression"],i.stableFilter.filter)):(t.set(["drill_filters",r,"kind"],"literal_equality"),z2e(t,["drill_filters",r,"value"],i.stableFilter.value))))}}function q2e(t,e,r){U1(t,e,r,"Expression")}function z2e(t,e,r){U1(t,e,r,"LiteralValue")}function Ngt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Lgt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Ngt(t)}\``}function Fw(t,e){var r,i;const s=Bj.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList&&(j2e(s,e.filterList),o=!0),e.drillable&&(s.set(["drillable"]),o=!0),e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return t.queryTimezone&&(s.set(["query_timezone"],t.queryTimezone),o=!0),o?{value:s.toString()}:void 0}function Nw(t){if((0,Ms.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Igt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:$gt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ms.isRepeatedRecord)(t))return{kind:"array_type",element_type:H2e(t)};if(t.type==="record")return H2e(t);if(t.type==="array")return{kind:"array_type",element_type:Nw(t.elementTypeDef)}}throw new Error("Unexpected field type")}function H2e(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=U2e(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,$j.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ms.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:Nw(e)};throw new Error("Expected record type to not have a table as its child")})}}function Igt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function $gt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function tAt(t){return t}function nAt(t){return t}function U1(t,e,r,i){if(i==="string"){t.set(e,r);return}else if(i==="number"){t.set(e,r);return}else if(i==="boolean"){t.set(e,r.toString());return}const s=k2e.MALLOY_INTERFACE_TYPES[i];if(s===void 0)throw new Error(`Unknown Malloy interface type ${i}`);if(s.type==="enum")if(typeof r=="string")t.set(e,r);else throw new Error(`Expected string for enum ${i}`);else if(s.type==="struct")for(const o in s.fields){const u=s.fields[o],a=r[o];if(a===void 0){if(!u.optional)throw new Error(`Mising value for non-optional field ${o} in type ${i}`)}else if(u.array)if(Array.isArray(a))for(let l=0;l<a.length;l++)U1(t,[...e,o,l],a[l],u.type);else throw new Error(`Expected array for field ${o} of type ${i} but got ${typeof r}`);else U1(t,[...e,o],a,u.type)}else{const o=r.kind;t.set([...e,"kind"],o);const u=s.options[o];if(u===void 0)throw new Error(`Unknown Malloy interface union kind ${o} for type ${i}`);U1(t,e,r,u)}}function Lw(t,e){if(e==="string")return t.text();if(e==="number")return t.numeric();if(e==="boolean")return t.text()==="true";const r=k2e.MALLOY_INTERFACE_TYPES[e];if(r===void 0)throw new Error(`Unknown Malloy interface type ${e}`);if(r.type==="enum"){const i=t.text();if(i===void 0)throw new Error(`Missing value for enum ${e}`);if(i in r.values)return i;throw new Error(`Unknown value ${i} for enum ${e}`)}else if(r.type==="struct"){const i={};for(const[s,o]of Object.entries(r.fields)){const u=t.tag(s);if(u===void 0){if(o.optional)continue;throw new Error(`Missing value for key ${s} of type ${o}`)}if(o.array){const a=[],l=u.array();if(l===void 0)throw new Error(`Missing array value for key ${s} of type ${o}`);for(const c of l)a.push(Lw(c,o.type));i[s]=a}else{const a=Lw(u,o.type);a!=null&&(i[s]=a)}}return i}else{const i=t.text("kind");if(i===void 0)throw new Error(`Missing kind for union ${e}`);const s=r.options[i];if(s===void 0)throw new Error(`Unknown kind ${i} for union ${e}`);const o=Lw(t,s);return{kind:i,...o}}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_LOG_RANGE=void 0,t.wrapLegacyInfoConnection=u,t.wrapLegacyConnection=a,t.mapData=c,t.wrapResult=f,t.nodeToLiteralValue=d,t.mapLogs=x;const e=rs,r=Ns,i=Ri,s=ea,o=YE;function u(p){return{get dialectName(){return p.dialectName},async fetchSchemaForSQLQuery(m){const g=await p.fetchSchemaForSQLStruct({connection:p.name,selectStr:m},{}),y=g.structDef;if(y===void 0)throw new Error(g.error);return{fields:(0,s.convertFieldInfos)(y,y.fields)}},async fetchSchemaForTable(m){const g=`${p.name}:${m}`,y=await p.fetchSchemaForTables({[g]:m},{}),v=y.schemas[g];if(v===void 0)throw new Error(y.errors[g]);return{fields:(0,s.convertFieldInfos)(v,v.fields)}}}}function a(p){return{...u(p),runSQL:async(m,g)=>{const y=await p.runSQL(m);return c(y.rows,g)}}}function l(p){if(p instanceof Date)return p;if(p.constructor.name==="Date")return new Date(p);if(typeof p=="number")return new Date(p);if(typeof p!="string")return new Date(p.value);{let g=o.DateTime.fromISO(p,{zone:"UTC"});return g.isValid||(g=o.DateTime.fromSQL(p,{zone:"UTC"})),g.toJSDate()}}function c(p,m){function g(E,_){if(E===null)return{kind:"null_cell"};if(_.type.kind==="date_type"||_.type.kind==="timestamp_type"){const A=l(E).toISOString();return _.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(_.type.kind==="boolean_type"){if(typeof E=="number")return{kind:"boolean_cell",boolean_value:E!==0};if(typeof E!="boolean")throw new Error(`Invalid boolean ${E}`);return{kind:"boolean_cell",boolean_value:E}}else if(_.type.kind==="number_type"){if(typeof E!="number")throw new Error(`Invalid number ${E}`);return{kind:"number_cell",number_value:E}}else if(_.type.kind==="string_type"){if(typeof E!="string")throw new Error(`Invalid string ${E}`);return{kind:"string_cell",string_value:E}}else if(_.type.kind==="array_type"){if(!Array.isArray(E))throw new Error(`Invalid array ${E}`);return{kind:"array_cell",array_value:E.map(A=>g(A,{name:"array_element",type:_.type.element_type}))}}else{if(_.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(E)};if(_.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(E)};{const A=_.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(_)}, ${JSON.stringify(E)}`);return y(E,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(S=>({kind:"dimension",...S}))}})}}}function y(E,_){const A=[];for(const S of _.schema.fields){const b=E[S.name];if(S.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=g(b,S);A.push(C)}return{kind:"record_cell",record_value:A}}const v={kind:"join",schema:m,name:"root",relationship:"one"};return{kind:"array_cell",array_value:p.map(E=>y(E,v))}}function f(p){const m=p._queryResult.structs,g=m[m.length-1],y={fields:(0,s.convertFieldInfos)(g,g.fields)},v=(0,r.annotationToTaglines)(p.annotation).map(S=>({value:S})),E=g.resultMetadata?(0,s.getResultStructMetadataAnnotation)(g,g.resultMetadata):void 0;E&&v.push(E),v.push(...g.resultMetadata?[]:[]);const _=e.Tag.withPrefix("#(malloy) ");if(p.sourceExplore&&_.set(["source","name"],p.sourceExplore.name),p._sourceArguments){const S=Object.entries(p._sourceArguments);for(let b=0;b<S.length;b++){const[C,T]=S[b],D=d(T.value);D!==void 0&&(0,s.writeLiteralToTag)(_,["source","parameters",b,"value"],D),_.set(["source","parameters",b,"name"],C)}}v.push({value:_.toString()}),v.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],p.resultExplore.name).toString()});const A=(0,r.annotationToTaglines)(p._modelDef.annotation).map(S=>({value:S}));return{schema:y,data:c(p.data.toObject(),y),connection_name:p.connectionName,annotations:v.length>0?v:void 0,model_annotations:A.length>0?A:void 0,query_timezone:p.data.field.queryTimezone,sql:p.sql}}function d(p){switch(p==null?void 0:p.node){case"numberLiteral":return{kind:"number_literal",number_value:Number.parseFloat(p.literal)};case"null":return{kind:"null_literal"};case"stringLiteral":return{kind:"string_literal",string_value:p.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:p.filterSrc};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"timeLiteral":return p.typeDef.type==="date"?p.typeDef.timeframe===void 0||(0,i.isDateUnit)(p.typeDef.timeframe)?{kind:"date_literal",date_value:p.literal,timezone:p.timezone,granularity:p.typeDef.timeframe}:void 0:{kind:"timestamp_literal",timestamp_value:p.literal,timezone:p.timezone,granularity:p.typeDef.timeframe};default:return}}t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function x(p,m){return p.map(g=>{var y,v,E,_;return{severity:g.severity,message:g.message,range:(v=(y=g.at)===null||y===void 0?void 0:y.range)!==null&&v!==void 0?v:t.DEFAULT_LOG_RANGE,url:(_=(E=g.at)===null||E===void 0?void 0:E.url)!==null&&_!==void 0?_:m}})}})(i_);var Bgt=R&&R.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),kgt=R&&R.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mgt=R&&R.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var i=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Bgt(r,e,i[s]);return kgt(r,e),r}}();Object.defineProperty(r_,"__esModule",{value:!0}),r_.MalloyToQuery=void 0,r_.malloyToQuery=Hgt;const Pgt=M2,Ugt=s2,mt=Mgt($),Q2e=J2,dh=ks,jgt=Ye,qgt=ND,G2e=jr,zgt=i_,xh=ZE,Mj="Malloy query documents";class W2e extends Ugt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,G2e.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Q2e.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${Mj}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${Mj} may only have one run statement`);return i===void 0?(this.illegal(e,`${Mj} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.tags()),o=this.getAnnotations(e.topLevelAnonQueryDef().tags()),u=this.combineAnnotations(s,o);return i!==null?{annotations:u,definition:i}:null}getSourceArguments(e){const r=[];for(const i of e.sourceArgument()){const s=i.argumentId();if(s===void 0)return this.contextError(i,"unnamed-source-argument","Source argument must be named"),null;const o=(0,dh.getId)(s),u=this.getLiteralIncludingNegativeNumber(i.fieldExpr());if(u===null)return null;r.push({name:o,value:u})}return r}getQueryReference(e){const r=e.sourceArguments(),i=(0,dh.getId)(e);if(r){const s=this.getSourceArguments(r);return s===null?null:{name:i,parameters:s}}else return{name:i}}getQueryDefinition(e){if(e instanceof mt.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof mt.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof mt.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof mt.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof mt.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof mt.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof mt.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof mt.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof mt.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof mt.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof mt.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof mt.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof mt.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,dh.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof mt.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,dh.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof mt.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof mt.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.drillStatement()){const r=e.drillStatement(),i=this.getDrill(r);return i===null?null:i.map(s=>({kind:"drill",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,dh.getId)(o)),i=r[r.length-1],s=r.slice(0,-1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,jgt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,dh.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof mt.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof mt.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof mt.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}else{const r=this.getLiteralIncludingNegativeNumber(e);return r===null?null:{kind:"literal_value",literal_value:r}}}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof mt.ExprCompareContext){if(e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof mt.ExprFieldPathContext&&i instanceof mt.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof mt.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",expression:{kind:"field_reference",name:o,path:s},filter:a}}}}}else if(e.compareOp().EQ()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof mt.ExprFieldPathContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=this.getLiteralIncludingNegativeNumber(i);return u===null?(this.notAllowed(e,"Filters other than comparisons with filter strings or equality with literals"),null):{filter:{kind:"literal_equality",expression:{kind:"field_reference",name:o,path:s},value:u}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings or equality with literals"),null}getTimeLiteral(e,r){const i=r(e.text);if(!i)return this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),null;const s=i.getValue(),o=s.timeframe;if(s.value.node!=="timeLiteral")return null;const u=s.value.literal,a=s.value.timezone;return s.type==="timestamp"?{kind:"timestamp_literal",timestamp_value:u,granularity:o,timezone:a}:o==="hour"||o==="minute"||o==="second"?null:{kind:"date_literal",date_value:u,granularity:o,timezone:a}}getLiteralIncludingNegativeNumber(e){if(e instanceof mt.ExprLiteralContext)return this.getLiteral(e.literal());if(e instanceof mt.ExprMinusContext){const r=e.fieldExpr();if(r instanceof mt.ExprLiteralContext){const i=this.getLiteral(r.literal());return i===null||i.kind!=="number_literal"?null:{kind:"number_literal",number_value:-i.number_value}}}return null}getLiteral(e){if(e instanceof mt.ExprTimeContext){const r=e.dateLiteral();return r instanceof mt.LiteralTimestampContext?this.getTimeLiteral(r,xh.LiteralTimestamp.parse):r instanceof mt.LiteralHourContext?this.getTimeLiteral(r,xh.LiteralHour.parse):r instanceof mt.LiteralDayContext?this.getTimeLiteral(r,xh.LiteralDay.parse):r instanceof mt.LiteralWeekContext?this.getTimeLiteral(r,xh.LiteralWeek.parse):r instanceof mt.LiteralMonthContext?this.getTimeLiteral(r,xh.LiteralMonth.parse):r instanceof mt.LiteralQuarterContext?this.getTimeLiteral(r,xh.LiteralQuarter.parse):r instanceof mt.LiteralYearContext?this.getTimeLiteral(r,xh.LiteralYear.parse):null}else{if(e instanceof mt.ExprArrayLiteralContext)return this.notAllowed(e,"array literals"),null;if(e instanceof mt.ExprLiteralRecordContext)return this.notAllowed(e,"record literals"),null;if(e instanceof mt.ExprStringContext){const[r,i]=(0,dh.getPlainString)(e);for(const s of i)s instanceof Pgt.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return{kind:"string_literal",string_value:r??""}}else{if(e instanceof mt.ExprBoolContext)return{kind:"boolean_literal",boolean_value:e.TRUE()!==null};if(e instanceof mt.ExprNumberContext)return{kind:"number_literal",number_value:Number(e.text)};if(e instanceof mt.ExprNULLContext)return{kind:"null_literal"};if(e instanceof mt.FilterString_stubContext){const r=e.getChild(0);if(r instanceof mt.FilterStringContext){const i=this.getFilterString(r);if(i)return{kind:"filter_expression_literal",filter_expression_value:i}}}}}return null}getDrill(e){const i=e.drillClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}r_.MalloyToQuery=W2e;function Hgt(t){const e=(0,G2e.getSourceInfo)(t),r=new Q2e.BaseMessageLogger(null),i="internal://query.malloy",s=(0,qgt.runMalloyParser)(t,i,e,r),u=new W2e(s,r).visit(s.root),a=(0,zgt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Af;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=n_;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=r_;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})})(JT);var $e={},Iw={};Object.defineProperty(Iw,"__esModule",{value:!0}),Iw.MALLOY_VERSION=void 0,Iw.MALLOY_VERSION="0.0.317",Object.defineProperty($e,"__esModule",{value:!0}),$e.InMemoryModelCache=$e.CacheManager=$e.CSVWriter=$e.JSONWriter=$e.DataWriter=$e.DataRecord=$e.DataArray=$e.Result=$e.ExploreMaterializer=$e.PreparedResultMaterializer=$e.QueryMaterializer=$e.ModelMaterializer=$e.SingleConnectionRuntime=$e.ConnectionRuntime=$e.Runtime=$e.ExploreField=$e.JoinRelationship=$e.QueryField=$e.Query=$e.StringField=$e.UnsupportedField=$e.JSONField=$e.BooleanField=$e.NumberField=$e.TimestampField=$e.DateField=$e.TimestampTimeframe=$e.DateTimeframe=$e.AtomicField=$e.AtomicFieldType=$e.Explore=$e.SourceRelationship=$e.FixedConnectionMap=$e.InMemoryURLReader=$e.EmptyURLReader=$e.PreparedResult=$e.DocumentCompletion=$e.DocumentSymbol=$e.DocumentPosition=$e.DocumentRange=$e.DocumentTablePath=$e.Parse=$e.PreparedQuery=$e.Model=$e.MalloyError=$e.Malloy=void 0;const V2e=JT,_r=Ri,Y2e=YE,Pj=Gx,Qgt=Iw,Ggt=H2,Vn=Ns,Wgt=nh,Vgt=jr,Ygt=Wv;function Kgt(t){return t.type==="table"||t.type==="sql_select"||t.type==="query_source"}const K2e="internal://internal.malloy";let jc=class zO{static get version(){return Qgt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(K2e));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new V2e.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new J2e(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return zO._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return qw(r,e).then(({contents:u,invalidationKey:a})=>zO._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:d}){var x,p,m,g,y;let v;if(a&&(v=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(K2e));const E={};if(r===void 0&&d!==void 0){const S=await d.getCachedModelDef(s,e.toString());if(S)return new j1(S.modelDef,[],[e.toString(),...jw(S.modelDef.dependencies)])}f??(f=e);let _;const A=e.toString();if(i!==void 0){_=i._translator;const S=(x=i._invalidationKey)!==null&&x!==void 0?x:await Jj(s,e);E[A]=S}else{if(r===void 0){const{contents:S,invalidationKey:b}=await qw(s,e);E[A]=b,r=S}else{const S=await Jj(s,e);E[A]=S}_=new V2e.MalloyTranslator(A,f.toString(),{urls:{[A]:r}},c)}for(;;){const S=_.translate(u==null?void 0:u._modelDef);if(S.final)if(S.modelDef){await(d==null?void 0:d.setCachedModelDef(e.toString(),{modelDef:S.modelDef,invalidationKeys:E}));for(const b of _.newlyTranslatedDependencies())await(d==null?void 0:d.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:E}));return new j1(S.modelDef,S.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=S.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},C=(u==null?void 0:u._modelDef)||b;return new j1(C,S.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=S.fromSources)!==null&&y!==void 0?y:[]])}else{const b=S.problems||[],C=_.prettyErrors();throw new X2e(`Error(s) compiling model:
1397
+ `,s=!0;else if(o===Dj)i--;else if(o===Rj)i++;else{if(o===ogt)continue;s&&(r+=" ".repeat(i*e),s=!1),r+=o}return r}function $1(t,e,r,i){var s;if(e.includes(ta))return[t,ta,Rj,...e,ta,Dj,r];const u=((s=i==null?void 0:i.spaces)!==null&&s!==void 0?s:!0)?" ":"";return[t,u,...e,u,r]}function ugt(t){return{contents:t,quoteCharacter:'"'}}function agt(t,e){const r=[];for(let i=0;i<t.length;i++){const s=t[i];r.push(s),i<t.length-1&&r.push(e)}return r}function wj(t){var e,r;switch(t.kind){case"filter_expression_literal":return[$2e(t.filter_expression_value)];case"boolean_literal":return[t.boolean_value.toString()];case"string_literal":{const{contents:i,quoteCharacter:s}=ugt(t.string_value);return[s,i,s]}case"number_literal":return[t.number_value.toString()];case"null_literal":return["null"];case"date_literal":return[L2e(N2e(t.date_value),(e=t.granularity)!==null&&e!==void 0?e:"day",t.timezone)];case"timestamp_literal":return[L2e(N2e(t.timestamp_value),(r=t.granularity)!==null&&r!==void 0?r:"second",t.timezone)]}}function N2e(t){let e;if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)/.exec(t)){const[r,i,s,o,u,a,l]=e;return[i,s,o,u,a,l]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d)/.exec(t)){const[r,i,s,o,u,a]=e;return[i,s,o,u,a,"00"]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d)(?:00)?/.exec(t)){const[r,i,s,o,u]=e;return[i,s,o,u,"00","00"]}else if(e=/(\d\d\d\d)-(\d\d)-(\d\d)/.exec(t)){const[r,i,s,o]=e;return[i,s,o,"00","00","00"]}else if(e=/(\d\d\d\d)-(\d\d)/.exec(t)){const[r,i,s]=e;return[i,s,"01","00","00","00"]}else if(e=/(\d\d\d\d)/.exec(t)){const[r,i]=e;return[i,"01","01","00","00","00"]}return["1970","01","01","00","00","00"]}function L2e([t,e,r,i,s,o],u,a){switch(u){case"year":return`@${t}`;case"quarter":{const l=Math.floor(+e/3)+1;return`@${t}-Q${l}`}case"month":return`@${t}-${e}`;case"week":return`@${t}-${e}-${r}-WK`;case"day":return`@${t}-${e}-${r}`;case"hour":return`@${t}-${e}-${r} ${i}`;case"minute":return`@${t}-${e}-${r} ${i}:${s}`;case"second":return a!==void 0?`@${t}-${e}-${r} ${i}:${s}:${o}[${a}]`:`@${t}-${e}-${r} ${i}:${s}:${o}`;default:throw new Error("Unknown timeframe.")}}function Uc(t){var e;const r=[];for(const i of(e=t.path)!==null&&e!==void 0?e:[])r.push((0,o_.maybeQuoteIdentifier)(i)),r.push(".");if(r.push((0,o_.maybeQuoteIdentifier)(t.name)),t.parameters){const i=[];for(let s=0;s<t.parameters.length;s++){const o=t.parameters[s];i.push((0,o_.maybeQuoteIdentifier)(o.name)),i.push(" is "),i.push(...wj(o.value)),s<t.parameters.length-1&&i.push(",",ta)}r.push(...$1("(",i,")",{spaces:!1}))}return r}function lgt(t){const e=[];return e.push(...u_(t.annotations)),e.push("run: "),e.push(...Oj(t.definition)),e}function cgt(t){const e=[];switch(t.kind){case"source_reference":{e.push(...Uc(t));break}case"refinement":e.push(...Oj(t));break}return e}function Oj(t){const e=[];switch(t.kind){case"arrow":{e.push(...cgt(t.source)),e.push(" -> "),e.push(...fh(t.view));break}case"query_reference":{e.push(...Uc(t));break}case"refinement":{const r=Oj(t.base);t.base.kind==="arrow"?e.push(...$1("(",r,")",{spaces:!1})):e.push(...r),e.push(" + "),e.push(...fh(t.refinement));break}}return e}function fh(t){const e=[];switch(t.kind){case"arrow":{e.push(...fh(t.source)),e.push(" -> "),e.push(...fh(t.view));break}case"view_reference":{e.push(...Uc(t));break}case"refinement":{e.push(...fh(t.base)),e.push(" + "),e.push(...fh(t.refinement));break}case"segment":{e.push(...fgt(t));break}}return e}function fgt(t){if(t.operations.length===0)return["{ }"];const e=t.operations.length>1,r=[];for(let i=0;i<t.operations.length;i++){const s=t.operations[i],o=[s];for(;i<t.operations.length-1;){const u=t.operations[i+1];if(u.kind===s.kind)o.push(u),i++;else break}r.push(...dgt(o)),e&&i<t.operations.length-1&&r.push(ta)}return $1("{",r,"}")}function dgt(t){switch(t[0].kind){case"aggregate":return Nj(t,"aggregate");case"group_by":return Nj(t,"group_by");case"order_by":return pgt(t);case"nest":return ggt(t);case"limit":return _gt(t);case"where":return I2e(t);case"having":return Sgt(t);case"drill":return Agt(t);case"calculate":return Nj(t,"calculate")}}function B1(t,e,r=""){const i=[];i.push(`${t}:`);const s=e.length>1||e.some(o=>o.includes(ta));s?i.push(ta,Rj):i.push(" ");for(let o=0;o<e.length;o++){const u=e[o];i.push(...u),e.length>1&&o<e.length-1&&i.push(r),s&&o<e.length-1&&i.push(ta)}return s&&i.push(Dj),i}function xgt(t){const e=[];return e.push(...Fj(t.expression)),e}function eAt(t){return t}function Fj(t){var e;switch(t.kind){case"field_reference":return Uc(t);case"time_truncation":return[...Uc(t.field_reference),".",t.truncation];case"filtered_field":return[...Uc(t.field_reference),...$1(" {",I2e(t.where),"}")];case"literal_value":return wj(t.literal_value);case"moving_average":{const r=["avg_moving",...$1("(",[...Uc(t.field_reference),t.rows_preceding!==void 0?`, ${t.rows_preceding}`:", 0",t.rows_following!==void 0?`, ${t.rows_following}`:""],")",{spaces:!1})];return!((e=t.partition_fields)===null||e===void 0)&&e.length&&r.push(...$1(" {",["partition_by",": ",...agt(t.partition_fields.flatMap(i=>Uc(i)),", ")],"}")),r}}}function hgt(t,e=!1){const r=[];return e||r.push(...u_(t.field.annotations)),t.name&&(r.push((0,o_.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...xgt(t.field)),r}function Nj(t,e){const r=[],i=t.length===1;return i&&r.push(...u_(t[0].field.annotations)),r.push(...B1(e,t.map(s=>hgt(s,i)))),r}function pgt(t){return B1("order_by",t.map(mgt),",")}function mgt(t){const e=[];return e.push(...Uc(t.field_reference)),t.direction&&(e.push(" "),e.push(t.direction)),e}function ggt(t){const e=[],r=t.length===1;return r&&e.push(...u_(t[0].view.annotations)),e.push(...B1("nest",t.map(i=>ygt(i,r)))),e}function ygt(t,e=!1){const r=[];return e||r.push(...u_(t.view.annotations)),t.name&&(r.push((0,o_.maybeQuoteIdentifier)(t.name)),r.push(" is ")),r.push(...Egt(t.view)),r}function Egt(t){return fh(t.definition)}function vgt(t){return[`limit: ${t.limit}`]}function _gt(t){const e=[];for(let r=0;r<t.length;r++)r!==0&&e.push(ta),e.push(...vgt(t[r]));return e}function I2e(t){return B1("where",t.map(Lj),",")}function Agt(t){return B1("drill",t.map(Lj),",")}function Sgt(t){return B1("having",t.map(Lj),",")}const bgt=["`","'",'"'];function $2e(t){let e,r;for(const i of bgt){const s=Cgt(t,i);if(s===t)return`f${i}${t}${i}`;(r===void 0||s.length<r.length)&&(e=i,r=s)}return`f${e}${r}${e}`}function Cgt(t,e){let r="";for(let i=0;i<t.length;i++)t.slice(i).startsWith(e)?(r+="\\"+e,i+=e.length):(r+=t[i],t[i]==="\\"&&(r+=t[++i]));return r}function B2e(t){switch(t.kind){case"filter_string":return[...Fj(t.expression)," ~ ",$2e(t.filter)];case"literal_equality":return[...Fj(t.expression)," = ",...wj(t.value)]}}function Lj(t){return B2e(t.filter)}function u_(t){return t?t.flatMap(Tgt):[]}function Tgt(t){return[t.value.trim(),ta]}var k1={};Object.defineProperty(k1,"__esModule",{value:!0}),k1.nestUnions=Ij,k1.unnestUnions=Dw,k1.convertFromThrift=ww,k1.convertToThrift=Ow;const Rgt=s_;function Ij(t){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(Ij);{const e={};let r;for(const i in t)i==="kind"?r=t[i]:e[i]=Ij(t[i]);return r===void 0?e:{[r]:e}}}function Dw(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(r=>Dw(r,e));{const r=M1(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0){const s=Dw(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=Dw(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}function ww(t,e){if(t==null)return t;if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(e==="number")return t;const r=M1(e);if(r.type!=="enum")throw new Error(`Found a number where a ${e} was expected`);const i=Object.entries(r.values).find(([,s])=>s===t);if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i[0]}else{if(Array.isArray(t))return t.map(r=>ww(r,e));{const r=M1(e);if(r.type==="union"){for(const i in r.options)if(t[i]!==void 0&&t[i]!==null){const s=ww(t[i],r.options[i]);if(typeof s=="object")return{kind:i,...s}}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=ww(t[s],o.type)}return i}else throw new Error(`Cannot unnest unions in an enum type ${e}`)}}}function M1(t){const e=Rgt.MALLOY_INTERFACE_TYPES[t];if(e===void 0)throw new Error(`Unknown Malloy interface type ${t}`);return e}function Ow(t,e){if(t==null)return t;if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string"){if(e==="string")return t;const r=M1(e);if(r.type==="enum"){const i=r.values[t];if(i===void 0)throw new Error(`${t} is not a valid enum value for ${e}`);return i}}else{if(Array.isArray(t))return t.map(r=>Ow(r,e));{const r=M1(e);if(r.type==="union"){const i=t.kind,s=r.options[i];if(s===void 0)throw new Error(`${i} is not a valid union of ${e}`);const o=M1(s);if(o.type!=="struct")throw new Error("Union fields must be structs");const u={};for(const a in t){if(a==="kind")continue;const l=o.fields[a];u[a]=Ow(t[a],l.type)}return{[i]:u}}else if(r.type==="struct"){const i={};for(const s in t){const o=r.fields[s];if(o===void 0)throw new Error(`Unknown field ${s} in ${e}`);i[s]=Ow(t[s],o.type)}return i}}}}(function(t){var e=R&&R.__createBinding||(Object.create?function(o,u,a,l){l===void 0&&(l=a);var c=Object.getOwnPropertyDescriptor(u,a);(!c||("get"in c?!u.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return u[a]}}),Object.defineProperty(o,l,c)}:function(o,u,a,l){l===void 0&&(l=a),o[l]=u[a]}),r=R&&R.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)};Object.defineProperty(t,"__esModule",{value:!0}),t.thingy4sddfdfsd=t.thingy4sdfsd=t.thingy4dfdsfs=t.thingy4asdfas=t.thingy4asdfasdf=t.thingy3dfdf=t.thingy3=t.thingy2asdf=t.thingyssdfg=t.thingy123r=t.thingy1=t.res=t.test=t.convertToThrift=t.convertFromThrift=t.unnestUnions=t.nestUnions=t.filterToMalloy=t.queryToMalloy=void 0,r(s_,t);var i=Tw;Object.defineProperty(t,"queryToMalloy",{enumerable:!0,get:function(){return i.queryToMalloy}}),Object.defineProperty(t,"filterToMalloy",{enumerable:!0,get:function(){return i.filterToMalloy}});var s=k1;Object.defineProperty(t,"nestUnions",{enumerable:!0,get:function(){return s.nestUnions}}),Object.defineProperty(t,"unnestUnions",{enumerable:!0,get:function(){return s.unnestUnions}}),Object.defineProperty(t,"convertFromThrift",{enumerable:!0,get:function(){return s.convertFromThrift}}),Object.defineProperty(t,"convertToThrift",{enumerable:!0,get:function(){return s.convertToThrift}}),t.test={entries:[{kind:"source",name:"flights",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"boolean_type"},annotations:[{value:"# foo=1"}]},{kind:"dimension",name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}},{kind:"dimension",name:"arr_rec",type:{kind:"array_type",element_type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}}},{kind:"dimension",name:"rec",type:{kind:"record_type",fields:[{name:"arr",type:{kind:"array_type",element_type:{kind:"boolean_type"}}}]}},{kind:"join",name:"carriers",relationship:"one",schema:{fields:[{kind:"dimension",name:"code",type:{kind:"string_type"}}]}},{kind:"view",name:"by_carrier",schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]}}]},parameters:[{name:"param",type:{kind:"number_type"},default_value:{kind:"number_literal",number_value:7}}]}],anonymous_queries:[]},t.res={connection_name:"foo",data:{kind:"array_cell",array_value:[{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"UA"},{kind:"number_cell",number_value:12341234}]},{kind:"record_cell",record_value:[{kind:"string_cell",string_value:"AA"},{kind:"number_cell",number_value:2343}]}]},schema:{fields:[{kind:"dimension",name:"carrier",type:{kind:"string_type"}},{kind:"dimension",name:"flight_count",type:{kind:"number_type"}}]},sql:"SELECT * ..."},t.thingy1={definition:{kind:"query_reference",name:"flights_by_carrier"}},t.thingy123r={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingyssdfg={definition:{kind:"refinement",base:{kind:"query_reference",name:"flights"},refinement:{kind:"view_reference",name:"by_carrier"}}},t.thingy2asdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"where",filter:{kind:"filter_string",expression:{kind:"field_reference",name:"carrier"},filter:"WN"}}]}}}},t.thingy3={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}}},t.thingy3dfdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"view_reference",name:"top10"}}}},t.thingy4asdfasdf={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"group_by",field:{expression:{kind:"field_reference",name:"foo"}}}]}}},t.thingy4asdfas={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"view_reference",name:"by_carrier"}}},t.thingy4dfdsfs={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"refinement",base:{kind:"view_reference",name:"by_carrier"},refinement:{kind:"segment",operations:[{kind:"limit",limit:10}]}}}},t.thingy4sdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[{kind:"group_by",field:{expression:{kind:"field_reference",name:"carrier"}}},{kind:"limit",limit:10}]}}},t.thingy4sddfdfsd={definition:{kind:"arrow",source:{kind:"source_reference",name:"flights"},view:{kind:"segment",operations:[]}}}})(ch);var Dgt=R&&R.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),wgt=R&&R.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ogt=R&&R.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var i=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Dgt(r,e,i[s]);return wgt(r,e),r}}();Object.defineProperty(ea,"__esModule",{value:!0}),ea.sourceDefToSourceInfo=M2e,ea.modelDefToModelInfo=Fgt,ea.convertFieldInfos=P1,ea.writeLiteralToTag=z2e,ea.getResultStructMetadataAnnotation=Fw,ea.writeMalloyObjectToTag=U1,ea.extractMalloyObjectFromTag=Lw;const k2e=Ogt(ch),Ms=Ri,$j=Ns,Bj=rs;function M2e(t){var e;const r=t.parameters&&Object.entries(t.parameters).length>0?Object.entries(t.parameters).map(([s,o])=>(0,Ms.isAtomic)(o)?{name:s,type:Nw(o),default_value:P2e(o.value)}:{name:s,type:{kind:"filter_expression_type",filter_type:{kind:`${o.filterType}_type`}},default_value:P2e(o.value)}):void 0;return{name:(e=t.as)!==null&&e!==void 0?e:t.name,schema:{fields:P1(t,t.fields)},parameters:r,annotations:kj(t)}}function Fgt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ms.isSourceDef)(i)){const s=M2e(i);e.entries.push({kind:"source",...s})}else if(i.type==="query"){const s=(0,Ms.getResultStructDefForQuery)(t,i),o=kj(i),u=s.resultMetadata?Fw(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:P1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,Ms.getResultStructDefForQuery)(t,r),s=kj(r),o=i.resultMetadata?Fw(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:P1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}function P2e(t){if(t!==null)switch(t.node){case"numberLiteral":return{kind:"number_literal",number_value:parseFloat(t.literal)};case"stringLiteral":return{kind:"string_literal",string_value:t.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:t.filterSrc};case"timeLiteral":return{kind:"timestamp_literal",timestamp_value:t.literal};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"null":return{kind:"null_literal"};default:throw new Error("Invalid parameter default value")}}function kj(t){return(0,$j.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function P1(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,$j.annotationToTaglines)(u.annotation).map(d=>({value:d})),f=c.length>0?c:void 0;if((0,Ms.isTurtle)(u)){const d=(0,Ms.getResultStructDefForView)(t,u),x=d.resultMetadata?Fw(d,d.resultMetadata):void 0,p=[...f??[],...x?[x]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:P1(d,d.fields)}};o.push(m)}else if((0,Ms.isAtomic)(u)){const d=(0,Ms.expressionIsAggregate)(u.expressionType),x=(0,Ms.expressionIsScalar)(u.expressionType);if(!d&&!x||u.type==="error")continue;const p=u.resultMetadata?U2e(u,u.resultMetadata):void 0;let m;if((0,Ms.isRecordOrRepeatedRecord)(u)&&u.queryTimezone){const v=Bj.Tag.withPrefix("#(malloy) ");v.set(["query_timezone"],u.queryTimezone),m={value:v.toString()}}const g=[...f??[],...p?[p]:[],...m?[m]:[]],y={kind:d?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:Nw(u),annotations:g.length>0?g:void 0};o.push(y)}else if((0,Ms.isJoinedSource)(u)){const d={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:P1(u,u.fields)},relationship:u.join};o.push(d)}}return o}function U2e(t,e){const r=Bj.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.drillable&&(r.set(["drillable"]),i=!0),e.filterList&&(j2e(r,e.filterList),i=!0),e.drillExpression&&(q2e(r,["drill_expression"],e.drillExpression),i=!0),e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Lgt(t.name));r.set(["drill_expression","code"],o),i=!0}return i?{value:r.toString()}:void 0}function j2e(t,e){for(let r=0;r<e.length;r++){const i=e[r];i.expressionType!=="scalar"||i.isSourceFilter||(t.set(["drill_filters",r,"code"],i.code),i.filterView&&t.set(["drill_filters",r,"filter_view"],i.filterView),i.filterView===void 0&&i.stableFilter!==void 0&&(q2e(t,["drill_filters",r,"expression"],i.stableFilter.expression),i.stableFilter.kind==="filter_string"?(t.set(["drill_filters",r,"kind"],"filter_expression"),t.set(["drill_filters",r,"filter_expression"],i.stableFilter.filter)):(t.set(["drill_filters",r,"kind"],"literal_equality"),z2e(t,["drill_filters",r,"value"],i.stableFilter.value))))}}function q2e(t,e,r){U1(t,e,r,"Expression")}function z2e(t,e,r){U1(t,e,r,"LiteralValue")}function Ngt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Lgt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Ngt(t)}\``}function Fw(t,e){var r,i;const s=Bj.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList&&(j2e(s,e.filterList),o=!0),e.drillable&&(s.set(["drillable"]),o=!0),e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return t.queryTimezone&&(s.set(["query_timezone"],t.queryTimezone),o=!0),o?{value:s.toString()}:void 0}function Nw(t){if((0,Ms.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!Igt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:$gt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ms.isRepeatedRecord)(t))return{kind:"array_type",element_type:H2e(t)};if(t.type==="record")return H2e(t);if(t.type==="array")return{kind:"array_type",element_type:Nw(t.elementTypeDef)}}throw new Error("Unexpected field type")}function H2e(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=U2e(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,$j.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ms.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:Nw(e)};throw new Error("Expected record type to not have a table as its child")})}}function Igt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function $gt(t){switch(t){case void 0:return;case"day":case"week":case"month":case"year":case"quarter":return t;default:throw new Error(`Invalid date timeframe ${t}`)}}function tAt(t){return t}function nAt(t){return t}function U1(t,e,r,i){if(i==="string"){t.set(e,r);return}else if(i==="number"){t.set(e,r);return}else if(i==="boolean"){t.set(e,r.toString());return}const s=k2e.MALLOY_INTERFACE_TYPES[i];if(s===void 0)throw new Error(`Unknown Malloy interface type ${i}`);if(s.type==="enum")if(typeof r=="string")t.set(e,r);else throw new Error(`Expected string for enum ${i}`);else if(s.type==="struct")for(const o in s.fields){const u=s.fields[o],a=r[o];if(a===void 0){if(!u.optional)throw new Error(`Mising value for non-optional field ${o} in type ${i}`)}else if(u.array)if(Array.isArray(a))for(let l=0;l<a.length;l++)U1(t,[...e,o,l],a[l],u.type);else throw new Error(`Expected array for field ${o} of type ${i} but got ${typeof r}`);else U1(t,[...e,o],a,u.type)}else{const o=r.kind;t.set([...e,"kind"],o);const u=s.options[o];if(u===void 0)throw new Error(`Unknown Malloy interface union kind ${o} for type ${i}`);U1(t,e,r,u)}}function Lw(t,e){if(e==="string")return t.text();if(e==="number")return t.numeric();if(e==="boolean")return t.text()==="true";const r=k2e.MALLOY_INTERFACE_TYPES[e];if(r===void 0)throw new Error(`Unknown Malloy interface type ${e}`);if(r.type==="enum"){const i=t.text();if(i===void 0)throw new Error(`Missing value for enum ${e}`);if(i in r.values)return i;throw new Error(`Unknown value ${i} for enum ${e}`)}else if(r.type==="struct"){const i={};for(const[s,o]of Object.entries(r.fields)){const u=t.tag(s);if(u===void 0){if(o.optional)continue;throw new Error(`Missing value for key ${s} of type ${o}`)}if(o.array){const a=[],l=u.array();if(l===void 0)throw new Error(`Missing array value for key ${s} of type ${o}`);for(const c of l)a.push(Lw(c,o.type));i[s]=a}else{const a=Lw(u,o.type);a!=null&&(i[s]=a)}}return i}else{const i=t.text("kind");if(i===void 0)throw new Error(`Missing kind for union ${e}`);const s=r.options[i];if(s===void 0)throw new Error(`Unknown kind ${i} for union ${e}`);const o=Lw(t,s);return{kind:i,...o}}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_LOG_RANGE=void 0,t.wrapLegacyInfoConnection=u,t.wrapLegacyConnection=a,t.mapData=c,t.wrapResult=f,t.nodeToLiteralValue=d,t.mapLogs=x;const e=rs,r=Ns,i=Ri,s=ea,o=YE;function u(p){return{get dialectName(){return p.dialectName},async fetchSchemaForSQLQuery(m){const g=await p.fetchSchemaForSQLStruct({connection:p.name,selectStr:m},{}),y=g.structDef;if(y===void 0)throw new Error(g.error);return{fields:(0,s.convertFieldInfos)(y,y.fields)}},async fetchSchemaForTable(m){const g=`${p.name}:${m}`,y=await p.fetchSchemaForTables({[g]:m},{}),v=y.schemas[g];if(v===void 0)throw new Error(y.errors[g]);return{fields:(0,s.convertFieldInfos)(v,v.fields)}}}}function a(p){return{...u(p),runSQL:async(m,g)=>{const y=await p.runSQL(m);return c(y.rows,g)}}}function l(p){if(p instanceof Date)return p;if(p.constructor.name==="Date")return new Date(p);if(typeof p=="number")return new Date(p);if(typeof p!="string")return new Date(p.value);{let g=o.DateTime.fromISO(p,{zone:"UTC"});return g.isValid||(g=o.DateTime.fromSQL(p,{zone:"UTC"})),g.toJSDate()}}function c(p,m){function g(E,_){if(E===null)return{kind:"null_cell"};if(_.type.kind==="date_type"||_.type.kind==="timestamp_type"){const A=l(E).toISOString();return _.type.kind==="date_type"?{kind:"date_cell",date_value:A}:{kind:"timestamp_cell",timestamp_value:A}}else if(_.type.kind==="boolean_type"){if(typeof E=="number")return{kind:"boolean_cell",boolean_value:E!==0};if(typeof E!="boolean")throw new Error(`Invalid boolean ${E}`);return{kind:"boolean_cell",boolean_value:E}}else if(_.type.kind==="number_type"){if(typeof E!="number")throw new Error(`Invalid number ${E}`);return{kind:"number_cell",number_value:E}}else if(_.type.kind==="string_type"){if(typeof E!="string")throw new Error(`Invalid string ${E}`);return{kind:"string_cell",string_value:E}}else if(_.type.kind==="array_type"){if(!Array.isArray(E))throw new Error(`Invalid array ${E}`);return{kind:"array_cell",array_value:E.map(A=>g(A,{name:"array_element",type:_.type.element_type}))}}else{if(_.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(E)};if(_.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(E)};{const A=_.type;if(A.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(_)}, ${JSON.stringify(E)}`);return y(E,{kind:"join",relationship:"many",name:"array_element",schema:{fields:A.fields.map(S=>({kind:"dimension",...S}))}})}}}function y(E,_){const A=[];for(const S of _.schema.fields){const b=E[S.name];if(S.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const C=g(b,S);A.push(C)}return{kind:"record_cell",record_value:A}}const v={kind:"join",schema:m,name:"root",relationship:"one"};return{kind:"array_cell",array_value:p.map(E=>y(E,v))}}function f(p){const m=p._queryResult.structs,g=m[m.length-1],y={fields:(0,s.convertFieldInfos)(g,g.fields)},v=(0,r.annotationToTaglines)(p.annotation).map(S=>({value:S})),E=g.resultMetadata?(0,s.getResultStructMetadataAnnotation)(g,g.resultMetadata):void 0;E&&v.push(E),v.push(...g.resultMetadata?[]:[]);const _=e.Tag.withPrefix("#(malloy) ");if(p.sourceExplore&&_.set(["source","name"],p.sourceExplore.name),p._sourceArguments){const S=Object.entries(p._sourceArguments);for(let b=0;b<S.length;b++){const[C,T]=S[b],D=d(T.value);D!==void 0&&(0,s.writeLiteralToTag)(_,["source","parameters",b,"value"],D),_.set(["source","parameters",b,"name"],C)}}v.push({value:_.toString()}),v.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],p.resultExplore.name).toString()});const A=(0,r.annotationToTaglines)(p._modelDef.annotation).map(S=>({value:S}));return{schema:y,data:c(p.data.toObject(),y),connection_name:p.connectionName,annotations:v.length>0?v:void 0,model_annotations:A.length>0?A:void 0,query_timezone:p.data.field.queryTimezone,sql:p.sql}}function d(p){switch(p==null?void 0:p.node){case"numberLiteral":return{kind:"number_literal",number_value:Number.parseFloat(p.literal)};case"null":return{kind:"null_literal"};case"stringLiteral":return{kind:"string_literal",string_value:p.literal};case"filterLiteral":return{kind:"filter_expression_literal",filter_expression_value:p.filterSrc};case"true":return{kind:"boolean_literal",boolean_value:!0};case"false":return{kind:"boolean_literal",boolean_value:!1};case"timeLiteral":return p.typeDef.type==="date"?p.typeDef.timeframe===void 0||(0,i.isDateUnit)(p.typeDef.timeframe)?{kind:"date_literal",date_value:p.literal,timezone:p.timezone,granularity:p.typeDef.timeframe}:void 0:{kind:"timestamp_literal",timestamp_value:p.literal,timezone:p.timezone,granularity:p.typeDef.timeframe};default:return}}t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function x(p,m){return p.map(g=>{var y,v,E,_;return{severity:g.severity,message:g.message,range:(v=(y=g.at)===null||y===void 0?void 0:y.range)!==null&&v!==void 0?v:t.DEFAULT_LOG_RANGE,url:(_=(E=g.at)===null||E===void 0?void 0:E.url)!==null&&_!==void 0?_:m}})}})(i_);var Bgt=R&&R.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),kgt=R&&R.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mgt=R&&R.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var i=[];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&Bgt(r,e,i[s]);return kgt(r,e),r}}();Object.defineProperty(r_,"__esModule",{value:!0}),r_.MalloyToQuery=void 0,r_.malloyToQuery=Hgt;const Pgt=M2,Ugt=s2,mt=Mgt($),Q2e=J2,dh=ks,jgt=Ye,qgt=ND,G2e=jr,zgt=i_,xh=ZE,Mj="Malloy query documents";class W2e extends Ugt.AbstractParseTreeVisitor{constructor(e,r){super(),this.parseInfo=e,this.msgLog=r}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}getLocation(e){return{url:this.parseInfo.sourceURL,range:(0,G2e.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Q2e.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}getNumber(e){return Number.parseInt(e.text)}defaultResult(){return null}getAnnotations(e){const r=e.ANNOTATION().map(i=>({value:i.text}));return r.length>0?r:void 0}getIsAnnotations(e){var r,i;if(e===void 0)return;const o=((r=this.getAnnotations(e._beforeIs))!==null&&r!==void 0?r:[]).concat((i=this.getAnnotations(e._afterIs))!==null&&i!==void 0?i:[]);return o.length>0?o:void 0}notAllowed(e,r){this.illegal(e,`${r} are not allowed in ${Mj}`)}illegal(e,r){this.contextError(e,"invalid-malloy-query-document",r)}visitMalloyDocument(e){const r=e.malloyStatement();let i;for(const s of r)s.defineSourceStatement()?this.notAllowed(s,"Source definitions"):s.defineQuery()?this.notAllowed(s,"Query definitions"):s.importStatement()?this.notAllowed(s,"Import statements"):s.docAnnotations()?this.notAllowed(s,"Model annotations"):s.ignoredObjectAnnotations()?this.notAllowed(s,"Detatched object annotations"):s.experimentalStatementForTesting()?this.notAllowed(s,"Experimental testing statements"):i===void 0?i=s.runStatement():this.illegal(s,`${Mj} may only have one run statement`);return i===void 0?(this.illegal(e,`${Mj} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.tags()),o=this.getAnnotations(e.topLevelAnonQueryDef().tags()),u=this.combineAnnotations(s,o);return i!==null?{annotations:u,definition:i}:null}getSourceArguments(e){const r=[];for(const i of e.sourceArgument()){const s=i.argumentId();if(s===void 0)return this.contextError(i,"unnamed-source-argument","Source argument must be named"),null;const o=(0,dh.getId)(s),u=this.getLiteralIncludingNegativeNumber(i.fieldExpr());if(u===null)return null;r.push({name:o,value:u})}return r}getQueryReference(e){const r=e.sourceArguments(),i=(0,dh.getId)(e);if(r){const s=this.getSourceArguments(r);return s===null?null:{name:i,parameters:s}}else return{name:i}}getQueryDefinition(e){if(e instanceof mt.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof mt.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof mt.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof mt.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof mt.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof mt.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof mt.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof mt.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof mt.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof mt.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof mt.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof mt.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof mt.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,dh.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof mt.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,dh.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof mt.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof mt.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.drillStatement()){const r=e.drillStatement(),i=this.getDrill(r);return i===null?null:i.map(s=>({kind:"drill",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,dh.getId)(o)),i=r[r.length-1],s=r.slice(0,-1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,jgt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,dh.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof mt.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof mt.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof mt.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}else{const r=this.getLiteralIncludingNegativeNumber(e);return r===null?null:{kind:"literal_value",literal_value:r}}}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof mt.ExprCompareContext){if(e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof mt.ExprFieldPathContext&&i instanceof mt.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof mt.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",expression:{kind:"field_reference",name:o,path:s},filter:a}}}}}else if(e.compareOp().EQ()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof mt.ExprFieldPathContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=this.getLiteralIncludingNegativeNumber(i);return u===null?(this.notAllowed(e,"Filters other than comparisons with filter strings or equality with literals"),null):{filter:{kind:"literal_equality",expression:{kind:"field_reference",name:o,path:s},value:u}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings or equality with literals"),null}getTimeLiteral(e,r){const i=r(e.text);if(!i)return this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),null;const s=i.getValue(),o=s.timeframe;if(s.value.node!=="timeLiteral")return null;const u=s.value.literal,a=s.value.timezone;return s.type==="timestamp"?{kind:"timestamp_literal",timestamp_value:u,granularity:o,timezone:a}:o==="hour"||o==="minute"||o==="second"?null:{kind:"date_literal",date_value:u,granularity:o,timezone:a}}getLiteralIncludingNegativeNumber(e){if(e instanceof mt.ExprLiteralContext)return this.getLiteral(e.literal());if(e instanceof mt.ExprMinusContext){const r=e.fieldExpr();if(r instanceof mt.ExprLiteralContext){const i=this.getLiteral(r.literal());return i===null||i.kind!=="number_literal"?null:{kind:"number_literal",number_value:-i.number_value}}}return null}getLiteral(e){if(e instanceof mt.ExprTimeContext){const r=e.dateLiteral();return r instanceof mt.LiteralTimestampContext?this.getTimeLiteral(r,xh.LiteralTimestamp.parse):r instanceof mt.LiteralHourContext?this.getTimeLiteral(r,xh.LiteralHour.parse):r instanceof mt.LiteralDayContext?this.getTimeLiteral(r,xh.LiteralDay.parse):r instanceof mt.LiteralWeekContext?this.getTimeLiteral(r,xh.LiteralWeek.parse):r instanceof mt.LiteralMonthContext?this.getTimeLiteral(r,xh.LiteralMonth.parse):r instanceof mt.LiteralQuarterContext?this.getTimeLiteral(r,xh.LiteralQuarter.parse):r instanceof mt.LiteralYearContext?this.getTimeLiteral(r,xh.LiteralYear.parse):null}else{if(e instanceof mt.ExprArrayLiteralContext)return this.notAllowed(e,"array literals"),null;if(e instanceof mt.ExprLiteralRecordContext)return this.notAllowed(e,"record literals"),null;if(e instanceof mt.ExprStringContext){const[r,i]=(0,dh.getPlainString)(e);for(const s of i)s instanceof Pgt.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return{kind:"string_literal",string_value:r??""}}else{if(e instanceof mt.ExprBoolContext)return{kind:"boolean_literal",boolean_value:e.TRUE()!==null};if(e instanceof mt.ExprNumberContext)return{kind:"number_literal",number_value:Number(e.text)};if(e instanceof mt.ExprNULLContext)return{kind:"null_literal"};if(e instanceof mt.FilterString_stubContext){const r=e.getChild(0);if(r instanceof mt.FilterStringContext){const i=this.getFilterString(r);if(i)return{kind:"filter_expression_literal",filter_expression_value:i}}}}}return null}getDrill(e){const i=e.drillClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}r_.MalloyToQuery=W2e;function Hgt(t){const e=(0,G2e.getSourceInfo)(t),r=new Q2e.BaseMessageLogger(null),i="internal://query.malloy",s=(0,qgt.runMalloyParser)(t,i,e,r),u=new W2e(s,r).visit(s.root),a=(0,zgt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Af;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=n_;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=r_;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})})(JT);var $e={},Iw={};Object.defineProperty(Iw,"__esModule",{value:!0}),Iw.MALLOY_VERSION=void 0,Iw.MALLOY_VERSION="0.0.319",Object.defineProperty($e,"__esModule",{value:!0}),$e.InMemoryModelCache=$e.CacheManager=$e.CSVWriter=$e.JSONWriter=$e.DataWriter=$e.DataRecord=$e.DataArray=$e.Result=$e.ExploreMaterializer=$e.PreparedResultMaterializer=$e.QueryMaterializer=$e.ModelMaterializer=$e.SingleConnectionRuntime=$e.ConnectionRuntime=$e.Runtime=$e.ExploreField=$e.JoinRelationship=$e.QueryField=$e.Query=$e.StringField=$e.UnsupportedField=$e.JSONField=$e.BooleanField=$e.NumberField=$e.TimestampField=$e.DateField=$e.TimestampTimeframe=$e.DateTimeframe=$e.AtomicField=$e.AtomicFieldType=$e.Explore=$e.SourceRelationship=$e.FixedConnectionMap=$e.InMemoryURLReader=$e.EmptyURLReader=$e.PreparedResult=$e.DocumentCompletion=$e.DocumentSymbol=$e.DocumentPosition=$e.DocumentRange=$e.DocumentTablePath=$e.Parse=$e.PreparedQuery=$e.Model=$e.MalloyError=$e.Malloy=void 0;const V2e=JT,_r=Ri,Y2e=YE,Pj=Gx,Qgt=Iw,Ggt=H2,Vn=Ns,Wgt=nh,Vgt=jr,Ygt=Wv;function Kgt(t){return t.type==="table"||t.type==="sql_select"||t.type==="query_source"}const K2e="internal://internal.malloy";let jc=class zO{static get version(){return Qgt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(K2e));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new V2e.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new J2e(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return zO._parse(i,e,s,o);if(r===void 0)throw new Error("Internal Error: urlReader is required.");if(e===void 0)throw new Error("Internal Error: url is required if source not present.");return qw(r,e).then(({contents:u,invalidationKey:a})=>zO._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:d}){var x,p,m,g,y;let v;if(a&&(v=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(K2e));const E={};if(r===void 0&&d!==void 0){const S=await d.getCachedModelDef(s,e.toString());if(S)return new j1(S.modelDef,[],[e.toString(),...jw(S.modelDef.dependencies)])}f??(f=e);let _;const A=e.toString();if(i!==void 0){_=i._translator;const S=(x=i._invalidationKey)!==null&&x!==void 0?x:await Jj(s,e);E[A]=S}else{if(r===void 0){const{contents:S,invalidationKey:b}=await qw(s,e);E[A]=b,r=S}else{const S=await Jj(s,e);E[A]=S}_=new V2e.MalloyTranslator(A,f.toString(),{urls:{[A]:r}},c)}for(;;){const S=_.translate(u==null?void 0:u._modelDef);if(S.final)if(S.modelDef){await(d==null?void 0:d.setCachedModelDef(e.toString(),{modelDef:S.modelDef,invalidationKeys:E}));for(const b of _.newlyTranslatedDependencies())await(d==null?void 0:d.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:E}));return new j1(S.modelDef,S.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=S.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},C=(u==null?void 0:u._modelDef)||b;return new j1(C,S.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=S.fromSources)!==null&&y!==void 0?y:[]])}else{const b=S.problems||[],C=_.prettyErrors();throw new X2e(`Error(s) compiling model:
1398
1398
  ${C}`,b)}else{if(S.urls)for(const C of S.urls)try{if(zw(C))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(d!==void 0){const w=await d.getCachedModelDef(s,C);if(w){for(const k in w.invalidationKeys)E[k]=w.invalidationKeys[k];_.update({translations:{[C]:w.modelDef}});continue}}const{contents:T,invalidationKey:D}=await qw(s,new URL(C)),O={[C]:T};E[C]=D,_.update({urls:O})}catch(T){_.update({errors:{urls:{[C]:T.message}}})}const{modelAnnotation:b}=_.modelAnnotation(u==null?void 0:u._modelDef);if(S.tables){const C=new Map;for(const T in S.tables){const{connectionName:D,tablePath:O}=S.tables[T],w=C.get(D);w===void 0?C.set(D,{[T]:O}):w[T]=O}for(const[T,D]of C)try{const O=await o.lookupConnection(T),{schemas:w,errors:k}=await zO.safelyFetchTableSchema(O,D,{refreshTimestamp:v,modelAnnotation:b});_.update({tables:w,errors:{tables:k}})}catch(O){const w={},k={};for(const U in D)k[U]=O.toString();_.update({tables:w,errors:{tables:k}})}}if(S.compileSQL){const C=S.compileSQL,T=C.connection,D=(0,Wgt.sqlKey)(C.connection,C.selectStr);try{const w=await(await o.lookupConnection(T)).fetchSchemaForSQLStruct(C,{refreshTimestamp:v,modelAnnotation:b});w.error&&_.update({errors:{compileSQL:{[D]:w.error}}}),w.structDef&&_.update({compileSQL:{[D]:w.structDef}})}catch(O){const w={};w[D]=O.toString(),_.update({errors:{compileSQL:w}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new c_({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new c_({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new lo(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new mh(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};$e.Malloy=jc;class X2e extends Error{constructor(e,r=[]){super(e),this.problems=r}}$e.MalloyError=X2e;class j1{constructor(e,r,i){var s,o;this.modelDef=e,this.problems=r,this.fromSources=i,this.references=new Ygt.ReferenceList((s=i[0])!==null&&s!==void 0?s:"",(o=e.references)!==null&&o!==void 0?o:[])}tagParse(e){return(0,Vn.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this.references.find(e)}getImport(e){var r;return(r=this.modelDef.imports)===null||r===void 0?void 0:r.find(i=>(0,Vgt.locationContainsPosition)(i.location,e))}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new hh(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new hh(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new hh(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if(r&&(0,_r.isSourceDef)(r))return new lo(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(_r.isSourceDef).map(e=>new lo(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}$e.Model=j1;class hh{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,Vn.annotationToTag)(this._modelDef.annotation).tag;return e=(0,Vn.addModelScope)(e,r),(0,Vn.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new _r.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new a_({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,_r.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}$e.PreparedQuery=hh;class J2e{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new $w(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new Z2e(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new e1e(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}$e.Parse=J2e;class Z2e{constructor(e){this._range=q1.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}$e.DocumentTablePath=Z2e;class q1{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new q1(new Uj(e.start.line,e.start.character),new Uj(e.end.line,e.end.character))}}$e.DocumentRange=q1;class Uj{constructor(e,r){this._line=e,this._character=r}get line(){return this._line}get character(){return this._character}toJSON(){return{line:this.line,character:this.character}}}$e.DocumentPosition=Uj;class $w{constructor(e){this._range=q1.fromJSON(e.range),this._lensRange=e.lensRange?q1.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new $w(r))}get range(){return this._range}get lensRange(){var e;return(e=this._lensRange)!==null&&e!==void 0?e:this._range}get type(){return this._type}get name(){return this._name}get children(){return this._children}}$e.DocumentSymbol=$w;class e1e{constructor(e){this.type=e.type,this.text=e.text}}$e.DocumentCompletion=e1e;class a_{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new a_(e,r)}tagParse(e){const r=(0,Vn.annotationToTag)(this.modelDef.annotation).tag;return e=(0,Vn.addModelScope)(e,r),(0,Vn.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,Vn.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new lo(r,this.sourceExplore)}catch{return new lo(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,_r.isSourceDef)(r))return new lo(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceArguments(){return this.inner.sourceArguments}get _sourceFilters(){return this.inner.sourceFilters||[]}}$e.PreparedResult=a_;class t1e{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}$e.EmptyURLReader=t1e;class Xgt{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return zw(e.toString())?null:m1e(r)}}$e.InMemoryURLReader=Xgt;class Bw{constructor(e,r){this.connections=e,this.defaultConnectionName=r}async getConnection(e){if(e===void 0)if(this.defaultConnectionName!==void 0)e=this.defaultConnectionName;else throw new Error("No default connection.");const r=this.connections.get(e);if(r!==void 0)return Promise.resolve(r);throw new Error(`No connection found with name ${e}.`)}listConnections(){return Array.from(this.connections.values())}async lookupConnection(e){return this.getConnection(e)}static fromArray(e){return new Bw(new Map(e.map(r=>[r.name,r])))}}$e.FixedConnectionMap=Bw;var n1e;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(n1e||($e.SourceRelationship=n1e={}));class jj{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof lo}isQuery(){return this instanceof Vj}}class lo extends jj{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,_r.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,Vn.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,Vn.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i=r.fields.find(o=>{var u;return((u=o.as)!==null&&u!==void 0?u:o.name)===e});if(i===void 0)throw new Error(`No such view named \`${e}\``);if(i.type!=="turtle")throw new Error(`\`${e}\` is not a view`);const s={type:"query",structRef:r,pipeline:i.pipeline};return new hh(s,this.modelDef,[],e)}get modelDef(){if(!(0,_r.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new j1(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,_r.isJoined)(i))return[s,new Yj(i,this,o)];if(i.type==="turtle")return[s,new Vj(i,this,o)];if(i.type==="string")return[s,new Wj(i,this,o)];if(i.type==="number")return[s,new kw(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new kw({...i,type:"number"},this,o)]:[s,new qj(i,this,o)];if(i.type==="timestamp")return[s,new zj(i,this,o)];if(i.type==="boolean")return[s,new Hj(i,this,o)];if(i.type==="json")return[s,new Qj(i,this,o)];if(i.type==="sql native")return[s,new Gj(i,this,o)]}))}return this._fieldMap}get allFields(){return[...this.fieldMap.values()]}get allFieldsWithOrder(){var e,r,i;if(!this._allFieldsWithOrder){const s=[...((i=(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.orderBy)===null||i===void 0?void 0:i.map(u=>{if(typeof u.field=="string")return{field:this.fieldMap.get(u.field),dir:u.dir};throw new Error("Does not support mapping order by from number.")}))||[]],o=new Set(s.map(u=>u.field.name));this._allFieldsWithOrder=[...s,...this.allFields.filter(u=>!o.has(u.name)).map(u=>({field:u,dir:"asc"}))]}return this._allFieldsWithOrder}get intrinsicFields(){return[...this.fieldMap.values()].filter(e=>e.isIntrinsic())}get dimensions(){return[...this.allFieldsWithOrder].filter(e=>e.field.isAtomicField()&&e.field.sourceWasDimension())}getFieldByName(e){const r=this.fieldMap.get(e);if(r===void 0)throw new Error(`No such field ${e}.`);return r}getFieldByNameIfExists(e){return this.fieldMap.get(e)}get primaryKey(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.primaryKey}get parentExplore(){return this._parentExplore}hasParentExplore(){return this instanceof Yj}get filters(){var e;return(0,_r.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,_r.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?lo.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?lo.fromJSON(e.sourceExplore):void 0;return new lo(e._structDef,r,i)}get location(){return this.structDef.location}collectSourceComponents(e){const r=[];if(e.type==="composite"){for(const i of e.sources)r.push(...this.collectSourceComponents(i));return r}if(Kgt(e)){if(e.type==="table")r.push({type:"table",tableName:e.tablePath,componentID:`${e.connection}:${e.tablePath}`,sourceID:`${e.connection}:${e.tablePath}`});else if(e.type==="sql_select")r.push({type:"sql",selectStatement:e.selectStr,componentID:`${e.connection}:${e.selectStr}`,sourceID:`${e.connection}:${e.selectStr}`});else if(e.type==="query_source"){let i;try{i=new hh(e.query,this.modelDef,[]).getPreparedResult().sql}catch(o){i=`-- Could not compile SQL for query ${e.query.name||"unnamed query"}: ${o instanceof Error?o.message:String(o)}`}const s=`${e.connection}:${i}`;r.push({type:"sql",selectStatement:i,componentID:s,sourceID:s})}}else return[];for(const i of e.fields)(0,_r.isJoined)(i)&&r.push(...this.collectSourceComponents(i));return r}getSourceComponents(){const e={};if((0,_r.isSourceDef)(this.structDef)){const r=this.collectSourceComponents(this.structDef);for(const i of r)i.componentID?e[i.componentID]=i:i.sourceID&&(e[i.sourceID]=i)}return Object.values(e)}}$e.Explore=lo;var gl;(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"})(gl||($e.AtomicFieldType=gl={}));class qf extends jj{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return gl.String;case"boolean":return gl.Boolean;case"date":return gl.Date;case"timestamp":return gl.Timestamp;case"number":return gl.Number;case"json":return gl.Json;case"sql native":return gl.NativeUnsupported;case"error":return gl.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,Vn.addModelScope)(e,this.parent.modelTag),(0,Vn.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,_r.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,_r.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof Wj}isNumber(){return this instanceof kw}isDate(){return this instanceof qj}isBoolean(){return this instanceof Hj}isJSON(){return this instanceof Qj}isTimestamp(){return this instanceof zj}isUnsupported(){return this instanceof Gj}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}$e.AtomicField=qf;var ph;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(ph||($e.DateTimeframe=ph={}));var yl;(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"})(yl||($e.TimestampTimeframe=yl={}));let qj=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return ph.Day;case"week":return ph.Week;case"month":return ph.Month;case"quarter":return ph.Quarter;case"year":return ph.Year}}};$e.DateField=qj;let zj=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return yl.Day;case"week":return yl.Week;case"month":return yl.Month;case"quarter":return yl.Quarter;case"year":return yl.Year;case"second":return yl.Second;case"hour":return yl.Hour;case"minute":return yl.Minute}}};$e.TimestampField=zj;let kw=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}};$e.NumberField=kw;let Hj=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}};$e.BooleanField=Hj;let Qj=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}};$e.JSONField=Qj;class Gj extends qf{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}$e.UnsupportedField=Gj;let Wj=class extends qf{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}};$e.StringField=Wj;class r1e extends jj{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}$e.Query=r1e;class Vj extends r1e{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,Vn.addModelScope)(e,this.parent.modelTag),(0,Vn.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,Vn.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}$e.QueryField=Vj;var z1;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(z1||($e.JoinRelationship=z1={}));class Yj extends lo{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,_r.isJoined)(this.structDef))switch(this.structDef.join){case"one":return z1.OneToOne;case"many":case"cross":return z1.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===z1.OneToOne}get isArray(){return this.joinRelationship!==z1.OneToOne}tagParse(e){return e=(0,Vn.addModelScope)(e,this._parentExplore.modelTag),(0,Vn.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]:[]}get queryTimezone(){return(0,_r.isRecordOrRepeatedRecord)(this._structDef)?this._structDef.queryTimezone:super.queryTimezone}}$e.ExploreField=Yj;class Kj{constructor({urlReader:e,connections:r,connection:i,eventStream:s,cacheManager:o}){if(this.isTestRuntime=!1,r===void 0){if(i===void 0)throw new Error("A LookupConnection<Connection> or Connection is required.");r={lookupConnection:()=>Promise.resolve(i)}}e===void 0&&(e=new t1e),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new l_(this,async()=>jc.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new l_(this,async()=>new j1(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}$e.Runtime=Kj;class Jgt extends Kj{constructor({urlReader:e,connections:r}){super({connections:Bw.fromArray(r),urlReader:e}),this.rawConnections=r}}$e.ConnectionRuntime=Jgt;class Zgt extends Kj{constructor({urlReader:e,connection:r,eventStream:i,cacheManager:s}){super({urlReader:e,eventStream:i,cacheManager:s,connection:r}),this.connection=r}get supportsNesting(){return(0,Pj.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,Pj.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,Pj.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}$e.SingleConnectionRuntime=Zgt;class Mw{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new i1e(this.runtime,e,r)}makeExploreMaterializer(e,r){return new o1e(this.runtime,e,r)}makePreparedResultMaterializer(e){return new s1e(this.runtime,e)}}class l_ extends Mw{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await jc.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new l_(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await jc.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new _r.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,_r.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,_r.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
1399
1399
  run: ${e}
1400
1400
  -> ${u}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/render",
3
- "version": "0.0.317",
3
+ "version": "0.0.319",
4
4
  "license": "MIT",
5
5
  "main": "dist/module/index.umd.js",
6
6
  "types": "dist/module/index.d.ts",
@@ -29,9 +29,9 @@
29
29
  "generate-flow": "ts-node ../../scripts/gen-flow.ts"
30
30
  },
31
31
  "dependencies": {
32
- "@malloydata/malloy": "0.0.317",
33
- "@malloydata/malloy-interfaces": "0.0.317",
34
- "@malloydata/malloy-tag": "0.0.317",
32
+ "@malloydata/malloy": "0.0.319",
33
+ "@malloydata/malloy-interfaces": "0.0.319",
34
+ "@malloydata/malloy-tag": "0.0.319",
35
35
  "@tanstack/solid-virtual": "^3.10.4",
36
36
  "lodash": "^4.17.20",
37
37
  "luxon": "^2.4.0",
@@ -43,7 +43,7 @@
43
43
  "vega-lite": "^5.2.0"
44
44
  },
45
45
  "devDependencies": {
46
- "@malloydata/db-duckdb": "0.0.317",
46
+ "@malloydata/db-duckdb": "0.0.319",
47
47
  "@storybook/addon-essentials": "^8.5.8",
48
48
  "@storybook/addon-interactions": "^8.5.8",
49
49
  "@storybook/addon-links": "^8.5.8",