@malloydata/render 0.0.276 → 0.0.277

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.
@@ -649,7 +649,7 @@ ${r} `)}
649
649
  ${r} ]`),this.properties)for(const s in this.properties){const o=At.tagFrom(this.properties[s]);i+=`
650
650
  ${r} ${s}: ${o.peek(e+2)}`}return i+=`
651
651
  ${r}}`,i}static fromTagLine(e,r=0,i,...s){return sz(e,i,s,r)}static fromTagLines(e,r,...i){const s=[];let o=r;for(let u=0;u<e.length;u++){const a=e[u],l=sz(a,o,i,u);o=l.tag,s.push(...l.log)}return{tag:o,log:s}}constructor(e={}){e.eq&&(this.eq=e.eq),e.properties&&(this.properties=e.properties),e.deleted&&(this.deleted=e.deleted),e.prefix&&(this.prefix=e.prefix)}static withPrefix(e){return new At({prefix:e})}tag(...e){return this.find(e)}text(...e){var r;const i=(r=this.find(e))===null||r===void 0?void 0:r.eq;if(typeof i=="string")return i}numeric(...e){var r;const i=(r=this.find(e))===null||r===void 0?void 0:r.eq;if(typeof i=="string"){const s=Number.parseFloat(i);if(!Number.isNaN(s))return s}}bare(...e){const r=this.find(e);if(r!==void 0)return r.properties===void 0||Object.entries(r.properties).length===0}get dict(){const e={};if(this.properties)for(const r in this.properties)e[r]=At.tagFrom(this.properties[r]);return e}array(...e){var r;const i=(r=this.find(e))===null||r===void 0?void 0:r.eq;if(!(i===void 0||typeof i=="string"))return i.map(s=>typeof s=="string"?new At({eq:s}):At.tagFrom(s))}textArray(...e){var r;const i=(r=this.find(e))===null||r===void 0?void 0:r.eq;if(!(i===void 0||typeof i=="string"))return i.reduce((s,o)=>typeof o.eq=="string"?s.concat(o.eq):s,[])}numericArray(...e){var r;const i=(r=this.find(e))===null||r===void 0?void 0:r.eq;if(!(i===void 0||typeof i=="string"))return i.reduce((s,o)=>{if(typeof o.eq=="string"){const u=Number.parseFloat(o.eq);if(!Number.isNaN(u))return s.concat(u)}return s},[])}getProperties(){return this.properties===void 0&&(this.properties={}),this.properties}clone(){return new At(structuredClone(this))}static escapeString(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}static escapeProp(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static quoteAndEscape(e,r=!1){return e.match(/^[0-9A-Za-z_]+$/)?e:r?`\`${At.escapeProp(e)}\``:`"${At.escapeString(e)}"`}toString(){var e;let r=(e=this.prefix)!==null&&e!==void 0?e:"# ";function i(u){var a;const l=Object.keys((a=u.properties)!==null&&a!==void 0?a:{});for(let c=0;c<l.length;c++)o(l[c],u.properties[l[c]]),c<l.length-1&&(r+=" ")}function s(u,a=!1){if(u.eq!==void 0)if(a||(r+=" = "),Array.isArray(u.eq)){r+="[";for(let l=0;l<u.eq.length;l++)s(u.eq[l],!0),l!==u.eq.length-1&&(r+=", ");r+="]"}else r+=At.quoteAndEscape(`${u.eq}`);if(u.properties){const l=Object.keys(u.properties);!a&&l.length===1&&!l.some(c=>{var f;return((f=u.properties)!==null&&f!==void 0?f:{})[c].deleted})&&u.eq===void 0?(r+=".",i(u)):((!a||u.eq!==void 0)&&(r+=" "),r+="{ ",i(u),r+=" }")}}function o(u,a){if(a.deleted){r+=`-${At.quoteAndEscape(u,!0)}`;return}r+=At.quoteAndEscape(u,!0),s(a)}return i(this),r+=`
652
- `,r}find(e){var r;let i=At.tagFrom(this);for(const s of e)if(typeof s=="number"){if(i.eq===void 0||!Array.isArray(i.eq)||i.eq.length<=s)return;i=At.tagFrom(i.eq[s])}else{const o=(r=i.properties)!==null&&r!==void 0?r:{};if(s in o)i=At.tagFrom(o[s]);else return}return i}has(...e){return this.find(e)!==void 0}set(e,r=null){const i=At.tagFrom(this);let s=i;for(const o of e)if(typeof o=="number"){if(s.eq===void 0||!Array.isArray(s.eq))s.eq=Array.from({length:o+1}).map(u=>({}));else if(s.eq.length<=o){const u=s.eq,a=Array.from({length:o+1}).map((l,c)=>c<u.length?u[c]:{});s.eq=a}s=s.eq[o]}else{const u=s.properties;u===void 0?(s.properties={[o]:{}},s=s.properties[o]):o in u?(s=u[o],s.deleted&&(s.deleted=!1)):(u[o]={},s=u[o])}return r===null?s.eq=void 0:typeof r=="string"?s.eq=r:typeof r=="number"?s.eq=r.toString():Array.isArray(r)&&(s.eq=r.map(o=>({eq:typeof o=="string"?o:o.toString()}))),i}delete(...e){return this.remove(e,!1)}unset(...e){return this.remove(e,!0)}remove(e,r=!1){var i;const s=At.tagFrom(this);let o=s;for(const a of e.slice(0,e.length-1))if(typeof a=="number"){if(o.eq===void 0||!Array.isArray(o.eq)){if(!r)return s;o.eq=Array.from({length:a}).map(l=>({}))}else if(o.eq.length<=a){if(!r)return s;const l=o.eq,c=Array.from({length:a}).map((f,x)=>x<l.length?l[x]:{});o.eq=c}o=o.eq[a]}else{const l=o.properties;if(l===void 0){if(!r)return s;o.properties={[a]:{}},o=o.properties[a]}else if(a in l)o=l[a];else{if(!r)return s;l[a]={},o=l[a]}}const u=e[e.length-1];return typeof u=="string"?o.properties&&u in o.properties?delete o.properties[u]:r&&((i=o.properties)!==null&&i!==void 0||(o.properties={}),o.properties[u]={deleted:!0}):Array.isArray(o.eq)&&o.eq.splice(u,1),s}}L_.Tag=At,At.ids=new Map,At.nextTagId=1e3;class V3e{constructor(e){this.line=e,this.log=[]}syntaxError(e,r,i,s,o,u){const a={code:"tag-parse-syntax-error",message:o,line:this.line,offset:s};this.log.push(a)}semanticError(e,r,i){const s={code:r,message:i,line:this.line,offset:e.start.charPositionInLine};this.log.push(s)}}function dg(t){const e=t.buildOn;return e instanceof At?e:new At}function eA(t,e){var r,i;let s=t.getProperties();for(const o of e.slice(0,e.length-1)){let u;s[o]===void 0?(u=new At({}),s[o]=u):((r=(i=s[o]).properties)!==null&&r!==void 0||(i.properties={}),u=At.tagFrom(s[o])),s=u.getProperties()}return[e[e.length-1],s]}function iz(t){return t.SQ_STRING()||t.DQ_STRING()?(0,rz.parseString)(t.text,t.text[0]):t.text}function sz(t,e,r,i){if(t[0]==="#"){const d=t.indexOf(" ");d>0?t=t.slice(d):t=""}const s=nz.CharStreams.fromString(t),o=new G3e.MalloyTagLexer(s),u=new nz.CommonTokenStream(o),a=new V3e(i),l=new W3e.MalloyTagParser(u);l.removeErrorListeners(),l.addErrorListener(a);const c=l.tagLine();return{tag:new Y3e(r,a).tagLineToTag(c,e),log:a.log}}class Y3e extends Q3e.AbstractParseTreeVisitor{constructor(e=[],r){super(),this.scopes=[],this.msgLog=r,this.scopes.unshift(...e)}defaultResult(){return new At}visitString(e){return new At({eq:iz(e)})}getPropName(e){return e.identifier().map(r=>r.BARE_STRING()?r.text:(0,rz.parseString)(r.text,r.text[0]))}getTags(e,r){for(const i of e)i.buildOn=r,this.visit(i);return r}tagLineToTag(e,r){return r=(r==null?void 0:r.clone())||new At({}),this.scopes.unshift(r),this.getTags(e.tagSpec(),r),r}visitTagLine(e){throw new Error("INTERNAL: ERROR: Call tagLineToTag, not vistTagLine")}visitProperties(e){return this.getTags(e.tagSpec(),dg(e))}visitArrayValue(e){return new At({eq:this.getArray(e)})}getArray(e){return e.arrayElement().map(r=>this.visit(r))}visitArrayElement(e){const r=e.properties(),i=r?this.visitProperties(r):void 0,s=e.string();let o=s?iz(s):void 0;const u=e.arrayValue();if(u&&(o=this.getArray(u)),i)return o!==void 0&&(i.eq=o),i;const a=e.reference();return a?this.visitReference(a):new At({eq:o})}visitReference(e){const r=this.getPropName(e.propName());for(const i of this.scopes)if(i.has(r[0])){const s=i.tag(...r);if(s)return s.clone();break}return this.msgLog.semanticError(e,"tag-property-not-found",`Reference to undefined property ${r.join(".")}`),this.defaultResult()}visitTagEq(e){const r=dg(e),i=this.getPropName(e.propName()),[s,o]=eA(r,i),u=this.visit(e.eqValue()),a=e.properties();if(a)if(a.DOTTY()===void 0){const l=this.visitProperties(a).dict;o[s]={...u,properties:l}}else o[s]={...o[s],...u};else o[s]=u;return r}visitTagReplaceProperties(e){const r=dg(e),i=this.getPropName(e.propName()),[s,o]=eA(r,i),u=e.properties(),a=this.visitProperties(u);return e.DOTTY()===void 0?o[s]={properties:a.dict}:o[s].properties=a.dict,r}visitTagUpdateProperties(e){const r=dg(e),i=this.getPropName(e.propName()),[s,o]=eA(r,i),u=e.properties();u.buildOn=At.tagFrom(o[s]);const a=this.visitProperties(u),l=o[s]||new At({}),c={...l.properties,...a.dict};return o[s]={...l,properties:c},r}visitTagDef(e){const r=dg(e),i=this.getPropName(e.propName()),[s,o]=eA(r,i);return e.MINUS()?o[s]={deleted:!0}:o[s]=new At({}),r}visitTagEmpty(e){const r=e.buildOn;return r.properties={},r}}(function(t){var e=T&&T.__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=T&&T.__setModuleDefault||(Object.create?function(o,u){Object.defineProperty(o,"default",{enumerable:!0,value:u})}:function(o,u){o.default=u}),i=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)},s=T&&T.__importStar||function(o){if(o&&o.__esModule)return o;var u={};if(o!=null)for(var a in o)a!=="default"&&Object.prototype.hasOwnProperty.call(o,a)&&e(u,o,a);return r(u,o),u};Object.defineProperty(t,"__esModule",{value:!0}),t.ParseUtil=void 0,i(L_,t),t.ParseUtil=s(xg)})(ko);var tA=(t=>(t.Dollars="usd",t.Euros="euro",t.Pounds="pound",t))(tA||{}),mr=(t=>(t.Nanoseconds="nanoseconds",t.Microseconds="microseconds",t.Milliseconds="milliseconds",t.Seconds="seconds",t.Minutes="minutes",t.Hours="hours",t.Days="days",t))(mr||{});function K3e(t){return Object.values(mr).includes(t)}var oz={exports:{}};(function(t){var e={},r=function(s){s.version="0.11.2";function o(L){for(var P="",q=L.length-1;q>=0;)P+=L.charAt(q--);return P}function u(L,P){for(var q="";q.length<P;)q+=L;return q}function a(L,P){var q=""+L;return q.length>=P?q:u("0",P-q.length)+q}function l(L,P){var q=""+L;return q.length>=P?q:u(" ",P-q.length)+q}function c(L,P){var q=""+L;return q.length>=P?q:q+u(" ",P-q.length)}function f(L,P){var q=""+Math.round(L);return q.length>=P?q:u("0",P-q.length)+q}function x(L,P){var q=""+L;return q.length>=P?q:u("0",P-q.length)+q}var d=Math.pow(2,32);function p(L,P){if(L>d||L<-d)return f(L,P);var q=Math.round(L);return x(q,P)}function m(L,P){return P=P||0,L.length>=7+P&&(L.charCodeAt(P)|32)===103&&(L.charCodeAt(P+1)|32)===101&&(L.charCodeAt(P+2)|32)===110&&(L.charCodeAt(P+3)|32)===101&&(L.charCodeAt(P+4)|32)===114&&(L.charCodeAt(P+5)|32)===97&&(L.charCodeAt(P+6)|32)===108}var g=[["Sun","Sunday"],["Mon","Monday"],["Tue","Tuesday"],["Wed","Wednesday"],["Thu","Thursday"],["Fri","Friday"],["Sat","Saturday"]],y=[["J","Jan","January"],["F","Feb","February"],["M","Mar","March"],["A","Apr","April"],["M","May","May"],["J","Jun","June"],["J","Jul","July"],["A","Aug","August"],["S","Sep","September"],["O","Oct","October"],["N","Nov","November"],["D","Dec","December"]];function E(L){L[0]="General",L[1]="0",L[2]="0.00",L[3]="#,##0",L[4]="#,##0.00",L[9]="0%",L[10]="0.00%",L[11]="0.00E+00",L[12]="# ?/?",L[13]="# ??/??",L[14]="m/d/yy",L[15]="d-mmm-yy",L[16]="d-mmm",L[17]="mmm-yy",L[18]="h:mm AM/PM",L[19]="h:mm:ss AM/PM",L[20]="h:mm",L[21]="h:mm:ss",L[22]="m/d/yy h:mm",L[37]="#,##0 ;(#,##0)",L[38]="#,##0 ;[Red](#,##0)",L[39]="#,##0.00;(#,##0.00)",L[40]="#,##0.00;[Red](#,##0.00)",L[45]="mm:ss",L[46]="[h]:mm:ss",L[47]="mmss.0",L[48]="##0.0E+0",L[49]="@",L[56]='"上午/下午 "hh"時"mm"分"ss"秒 "'}var _={};E(_);var v=[],A=0;for(A=5;A<=8;++A)v[A]=32+A;for(A=23;A<=26;++A)v[A]=0;for(A=27;A<=31;++A)v[A]=14;for(A=50;A<=58;++A)v[A]=14;for(A=59;A<=62;++A)v[A]=A-58;for(A=67;A<=68;++A)v[A]=A-58;for(A=72;A<=75;++A)v[A]=A-58;for(A=67;A<=68;++A)v[A]=A-57;for(A=76;A<=78;++A)v[A]=A-56;for(A=79;A<=81;++A)v[A]=A-34;var S=[];S[5]=S[63]='"$"#,##0_);\\("$"#,##0\\)',S[6]=S[64]='"$"#,##0_);[Red]\\("$"#,##0\\)',S[7]=S[65]='"$"#,##0.00_);\\("$"#,##0.00\\)',S[8]=S[66]='"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',S[41]='_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',S[42]='_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)',S[43]='_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',S[44]='_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)';function b(L,P,q){for(var Y=L<0?-1:1,j=L*Y,W=0,z=1,re=0,de=1,le=0,se=0,xe=Math.floor(j);le<P&&(xe=Math.floor(j),re=xe*z+W,se=xe*le+de,!(j-xe<5e-8));)j=1/(j-xe),W=z,z=re,de=le,le=se;if(se>P&&(le>P?(se=de,re=W):(se=le,re=z)),!q)return[0,Y*re,se];var we=Math.floor(Y*re/se);return[we,Y*re-we*se,se]}function C(L,P,q){if(L>2958465||L<0)return null;var Y=L|0,j=Math.floor(86400*(L-Y)),W=0,z=[],re={D:Y,T:j,u:86400*(L-Y)-j,y:0,m:0,d:0,H:0,M:0,S:0,q:0};if(Math.abs(re.u)<1e-6&&(re.u=0),P&&P.date1904&&(Y+=1462),re.u>.9999&&(re.u=0,++j==86400&&(re.T=j=0,++Y,++re.D)),Y===60)z=q?[1317,10,29]:[1900,2,29],W=3;else if(Y===0)z=q?[1317,8,29]:[1900,1,0],W=6;else{Y>60&&--Y;var de=new Date(1900,0,1);de.setDate(de.getDate()+Y-1),z=[de.getFullYear(),de.getMonth()+1,de.getDate()],W=de.getDay(),Y<60&&(W=(W+6)%7),q&&(W=H(de,z))}return re.y=z[0],re.m=z[1],re.d=z[2],re.S=j%60,j=Math.floor(j/60),re.M=j%60,j=Math.floor(j/60),re.H=j,re.q=W,re}s.parse_date_code=C;var R=new Date(1899,11,31,0,0,0),O=R.getTime(),B=new Date(1900,2,1,0,0,0);function D(L,P){var q=L.getTime();return P?q-=1262304e5:L>=B&&(q+=864e5),(q-(O+(L.getTimezoneOffset()-R.getTimezoneOffset())*6e4))/864e5}function M(L){return L.toString(10)}s._general_int=M;var k=function(){var P=/(?:\.0*|(\.\d*[1-9])0+)$/;function q(le){return le.indexOf(".")==-1?le:le.replace(P,"$1")}var Y=/(?:\.0*|(\.\d*[1-9])0+)[Ee]/,j=/(E[+-])(\d)$/;function W(le){return le.indexOf("E")==-1?le:le.replace(Y,"$1E").replace(j,"$10$2")}function z(le){var se=le<0?12:11,xe=q(le.toFixed(12));return xe.length<=se||(xe=le.toPrecision(10),xe.length<=se)?xe:le.toExponential(5)}function re(le){var se=q(le.toFixed(11));return se.length>(le<0?12:11)||se==="0"||se==="-0"?le.toPrecision(6):se}function de(le){var se=Math.floor(Math.log(Math.abs(le))*Math.LOG10E),xe;return se>=-4&&se<=-1?xe=le.toPrecision(10+se):Math.abs(se)<=9?xe=z(le):se===10?xe=le.toFixed(10).substr(0,12):xe=re(le),q(W(xe.toUpperCase()))}return de}();s._general_num=k;function G(L,P){switch(typeof L){case"string":return L;case"boolean":return L?"TRUE":"FALSE";case"number":return(L|0)===L?L.toString(10):k(L);case"undefined":return"";case"object":if(L==null)return"";if(L instanceof Date)return V(14,D(L,P&&P.date1904),P)}throw new Error("unsupported value in General format: "+L)}s._general=G;function H(L,P){P[0]-=581;var q=L.getDay();return L<60&&(q=(q+6)%7),q}function J(L,P,q,Y){var j="",W=0,z=0,re=q.y,de,le=0;switch(L){case 98:re=q.y+543;case 121:switch(P.length){case 1:case 2:de=re%100,le=2;break;default:de=re%1e4,le=4;break}break;case 109:switch(P.length){case 1:case 2:de=q.m,le=P.length;break;case 3:return y[q.m-1][1];case 5:return y[q.m-1][0];default:return y[q.m-1][2]}break;case 100:switch(P.length){case 1:case 2:de=q.d,le=P.length;break;case 3:return g[q.q][0];default:return g[q.q][1]}break;case 104:switch(P.length){case 1:case 2:de=1+(q.H+11)%12,le=P.length;break;default:throw"bad hour format: "+P}break;case 72:switch(P.length){case 1:case 2:de=q.H,le=P.length;break;default:throw"bad hour format: "+P}break;case 77:switch(P.length){case 1:case 2:de=q.M,le=P.length;break;default:throw"bad minute format: "+P}break;case 115:if(P!="s"&&P!="ss"&&P!=".0"&&P!=".00"&&P!=".000")throw"bad second format: "+P;return q.u===0&&(P=="s"||P=="ss")?a(q.S,P.length):(Y>=2?z=Y===3?1e3:100:z=Y===1?10:1,W=Math.round(z*(q.S+q.u)),W>=60*z&&(W=0),P==="s"?W===0?"0":""+W/z:(j=a(W,2+Y),P==="ss"?j.substr(0,2):"."+j.substr(2,P.length-1)));case 90:switch(P){case"[h]":case"[hh]":de=q.D*24+q.H;break;case"[m]":case"[mm]":de=(q.D*24+q.H)*60+q.M;break;case"[s]":case"[ss]":de=((q.D*24+q.H)*60+q.M)*60+Math.round(q.S+q.u);break;default:throw"bad abstime format: "+P}le=P.length===3?1:2;break;case 101:de=re,le=1;break}var se=le>0?a(de,le):"";return se}function ce(L){var P=3;if(L.length<=P)return L;for(var q=L.length%P,Y=L.substr(0,q);q!=L.length;q+=P)Y+=(Y.length>0?",":"")+L.substr(q,P);return Y}var he=function(){var P=/%/g;function q(me,$,K){var De=$.replace(P,""),X=$.length-De.length;return he(me,De,K*Math.pow(10,2*X))+u("%",X)}function Y(me,$,K){for(var De=$.length-1;$.charCodeAt(De-1)===44;)--De;return he(me,$.substr(0,De),K/Math.pow(10,3*($.length-De)))}function j(me,$){var K,De=me.indexOf("E")-me.indexOf(".")-1;if(me.match(/^#+0.0E\+0$/)){if($==0)return"0.0E+0";if($<0)return"-"+j(me,-$);var X=me.indexOf(".");X===-1&&(X=me.indexOf("E"));var pe=Math.floor(Math.log($)*Math.LOG10E)%X;if(pe<0&&(pe+=X),K=($/Math.pow(10,pe)).toPrecision(De+1+(X+pe)%X),K.indexOf("e")===-1){var Fe=Math.floor(Math.log($)*Math.LOG10E);for(K.indexOf(".")===-1?K=K.charAt(0)+"."+K.substr(1)+"E+"+(Fe-K.length+pe):K+="E+"+(Fe-pe);K.substr(0,2)==="0.";)K=K.charAt(0)+K.substr(2,X)+"."+K.substr(2+X),K=K.replace(/^0+([1-9])/,"$1").replace(/^0+\./,"0.");K=K.replace(/\+-/,"-")}K=K.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function(He,ft,Dt,xt){return ft+Dt+xt.substr(0,(X+pe)%X)+"."+xt.substr(pe)+"E"})}else K=$.toExponential(De);return me.match(/E\+00$/)&&K.match(/e[+-]\d$/)&&(K=K.substr(0,K.length-1)+"0"+K.charAt(K.length-1)),me.match(/E\-/)&&K.match(/e\+/)&&(K=K.replace(/e\+/,"e")),K.replace("e","E")}var W=/# (\?+)( ?)\/( ?)(\d+)/;function z(me,$,K){var De=parseInt(me[4],10),X=Math.round($*De),pe=Math.floor(X/De),Fe=X-pe*De,He=De;return K+(pe===0?"":""+pe)+" "+(Fe===0?u(" ",me[1].length+1+me[4].length):l(Fe,me[1].length)+me[2]+"/"+me[3]+a(He,me[4].length))}function re(me,$,K){return K+($===0?"":""+$)+u(" ",me[1].length+2+me[4].length)}var de=/^#*0*\.([0#]+)/,le=/\).*[0#]/,se=/\(###\) ###\\?-####/;function xe(me){for(var $="",K,De=0;De!=me.length;++De)switch(K=me.charCodeAt(De)){case 35:break;case 63:$+=" ";break;case 48:$+="0";break;default:$+=String.fromCharCode(K)}return $}function we(me,$){var K=Math.pow(10,$);return""+Math.round(me*K)/K}function Ye(me,$){var K=me-Math.floor(me),De=Math.pow(10,$);return $<(""+Math.round(K*De)).length?0:Math.round(K*De)}function Ue(me,$){return $<(""+Math.round((me-Math.floor(me))*Math.pow(10,$))).length?1:0}function te(me){return me<2147483647&&me>-2147483648?""+(me>=0?me|0:me-1|0):""+Math.floor(me)}function ue(me,$,K){if(me.charCodeAt(0)===40&&!$.match(le)){var De=$.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");return K>=0?ue("n",De,K):"("+ue("n",De,-K)+")"}if($.charCodeAt($.length-1)===44)return Y(me,$,K);if($.indexOf("%")!==-1)return q(me,$,K);if($.indexOf("E")!==-1)return j($,K);if($.charCodeAt(0)===36)return"$"+ue(me,$.substr($.charAt(1)==" "?2:1),K);var X,pe,Fe,He,ft=Math.abs(K),Dt=K<0?"-":"";if($.match(/^00+$/))return Dt+p(ft,$.length);if($.match(/^[#?]+$/))return X=p(K,0),X==="0"&&(X=""),X.length>$.length?X:xe($.substr(0,$.length-X.length))+X;if(pe=$.match(W))return z(pe,ft,Dt);if($.match(/^#+0+$/))return Dt+p(ft,$.length-$.indexOf("0"));if(pe=$.match(de))return X=we(K,pe[1].length).replace(/^([^\.]+)$/,"$1."+xe(pe[1])).replace(/\.$/,"."+xe(pe[1])).replace(/\.(\d*)$/,function(Ys,m_){return"."+m_+u("0",xe(pe[1]).length-m_.length)}),$.indexOf("0.")!==-1?X:X.replace(/^0\./,".");if($=$.replace(/^#+([0.])/,"$1"),pe=$.match(/^(0*)\.(#*)$/))return Dt+we(ft,pe[2].length).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,pe[1].length?"0.":".");if(pe=$.match(/^#{1,3},##0(\.?)$/))return Dt+ce(p(ft,0));if(pe=$.match(/^#,##0\.([#0]*0)$/))return K<0?"-"+ue(me,$,-K):ce(""+(Math.floor(K)+Ue(K,pe[1].length)))+"."+a(Ye(K,pe[1].length),pe[1].length);if(pe=$.match(/^#,#*,#0/))return ue(me,$.replace(/^#,#*,/,""),K);if(pe=$.match(/^([0#]+)(\\?-([0#]+))+$/))return X=o(ue(me,$.replace(/[\\-]/g,""),K)),Fe=0,o(o($.replace(/\\/g,"")).replace(/[0#]/g,function(Ys){return Fe<X.length?X.charAt(Fe++):Ys==="0"?"0":""}));if($.match(se))return X=ue(me,"##########",K),"("+X.substr(0,3)+") "+X.substr(3,3)+"-"+X.substr(6);var xt="";if(pe=$.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))return Fe=Math.min(pe[4].length,7),He=b(ft,Math.pow(10,Fe)-1,!1),X=""+Dt,xt=he("n",pe[1],He[1]),xt.charAt(xt.length-1)==" "&&(xt=xt.substr(0,xt.length-1)+"0"),X+=xt+pe[2]+"/"+pe[3],xt=c(He[2],Fe),xt.length<pe[4].length&&(xt=xe(pe[4].substr(pe[4].length-xt.length))+xt),X+=xt,X;if(pe=$.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))return Fe=Math.min(Math.max(pe[1].length,pe[4].length),7),He=b(ft,Math.pow(10,Fe)-1,!0),Dt+(He[0]||(He[1]?"":"0"))+" "+(He[1]?l(He[1],Fe)+pe[2]+"/"+pe[3]+c(He[2],Fe):u(" ",2*Fe+1+pe[2].length+pe[3].length));if(pe=$.match(/^[#0?]+$/))return X=p(K,0),$.length<=X.length?X:xe($.substr(0,$.length-X.length))+X;if(pe=$.match(/^([#0?]+)\.([#0]+)$/)){X=""+K.toFixed(Math.min(pe[2].length,10)).replace(/([^0])0+$/,"$1"),Fe=X.indexOf(".");var Fr=$.indexOf(".")-Fe,Ef=$.length-X.length-Fr;return xe($.substr(0,Fr)+X+$.substr($.length-Ef))}if(pe=$.match(/^00,000\.([#0]*0)$/))return Fe=Ye(K,pe[1].length),K<0?"-"+ue(me,$,-K):ce(te(K)).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function(Ys){return"00,"+(Ys.length<3?a(0,3-Ys.length):"")+Ys})+"."+a(Fe,pe[1].length);switch($){case"###,##0.00":return ue(me,"#,##0.00",K);case"###,###":case"##,###":case"#,###":var p_=ce(p(ft,0));return p_!=="0"?Dt+p_:"";case"###,###.00":return ue(me,"###,##0.00",K).replace(/^0\./,".");case"#,###.00":return ue(me,"#,##0.00",K).replace(/^0\./,".")}throw new Error("unsupported format |"+$+"|")}function Te(me,$,K){for(var De=$.length-1;$.charCodeAt(De-1)===44;)--De;return he(me,$.substr(0,De),K/Math.pow(10,3*($.length-De)))}function Be(me,$,K){var De=$.replace(P,""),X=$.length-De.length;return he(me,De,K*Math.pow(10,2*X))+u("%",X)}function Ie(me,$){var K,De=me.indexOf("E")-me.indexOf(".")-1;if(me.match(/^#+0.0E\+0$/)){if($==0)return"0.0E+0";if($<0)return"-"+Ie(me,-$);var X=me.indexOf(".");X===-1&&(X=me.indexOf("E"));var pe=Math.floor(Math.log($)*Math.LOG10E)%X;if(pe<0&&(pe+=X),K=($/Math.pow(10,pe)).toPrecision(De+1+(X+pe)%X),!K.match(/[Ee]/)){var Fe=Math.floor(Math.log($)*Math.LOG10E);K.indexOf(".")===-1?K=K.charAt(0)+"."+K.substr(1)+"E+"+(Fe-K.length+pe):K+="E+"+(Fe-pe),K=K.replace(/\+-/,"-")}K=K.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function(He,ft,Dt,xt){return ft+Dt+xt.substr(0,(X+pe)%X)+"."+xt.substr(pe)+"E"})}else K=$.toExponential(De);return me.match(/E\+00$/)&&K.match(/e[+-]\d$/)&&(K=K.substr(0,K.length-1)+"0"+K.charAt(K.length-1)),me.match(/E\-/)&&K.match(/e\+/)&&(K=K.replace(/e\+/,"e")),K.replace("e","E")}function Ce(me,$,K){if(me.charCodeAt(0)===40&&!$.match(le)){var De=$.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");return K>=0?Ce("n",De,K):"("+Ce("n",De,-K)+")"}if($.charCodeAt($.length-1)===44)return Te(me,$,K);if($.indexOf("%")!==-1)return Be(me,$,K);if($.indexOf("E")!==-1)return Ie($,K);if($.charCodeAt(0)===36)return"$"+Ce(me,$.substr($.charAt(1)==" "?2:1),K);var X,pe,Fe,He,ft=Math.abs(K),Dt=K<0?"-":"";if($.match(/^00+$/))return Dt+a(ft,$.length);if($.match(/^[#?]+$/))return X=""+K,K===0&&(X=""),X.length>$.length?X:xe($.substr(0,$.length-X.length))+X;if(pe=$.match(W))return re(pe,ft,Dt);if($.match(/^#+0+$/))return Dt+a(ft,$.length-$.indexOf("0"));if(pe=$.match(de))return X=(""+K).replace(/^([^\.]+)$/,"$1."+xe(pe[1])).replace(/\.$/,"."+xe(pe[1])),X=X.replace(/\.(\d*)$/,function(Ys,m_){return"."+m_+u("0",xe(pe[1]).length-m_.length)}),$.indexOf("0.")!==-1?X:X.replace(/^0\./,".");if($=$.replace(/^#+([0.])/,"$1"),pe=$.match(/^(0*)\.(#*)$/))return Dt+(""+ft).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,pe[1].length?"0.":".");if(pe=$.match(/^#{1,3},##0(\.?)$/))return Dt+ce(""+ft);if(pe=$.match(/^#,##0\.([#0]*0)$/))return K<0?"-"+Ce(me,$,-K):ce(""+K)+"."+u("0",pe[1].length);if(pe=$.match(/^#,#*,#0/))return Ce(me,$.replace(/^#,#*,/,""),K);if(pe=$.match(/^([0#]+)(\\?-([0#]+))+$/))return X=o(Ce(me,$.replace(/[\\-]/g,""),K)),Fe=0,o(o($.replace(/\\/g,"")).replace(/[0#]/g,function(Ys){return Fe<X.length?X.charAt(Fe++):Ys==="0"?"0":""}));if($.match(se))return X=Ce(me,"##########",K),"("+X.substr(0,3)+") "+X.substr(3,3)+"-"+X.substr(6);var xt="";if(pe=$.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))return Fe=Math.min(pe[4].length,7),He=b(ft,Math.pow(10,Fe)-1,!1),X=""+Dt,xt=he("n",pe[1],He[1]),xt.charAt(xt.length-1)==" "&&(xt=xt.substr(0,xt.length-1)+"0"),X+=xt+pe[2]+"/"+pe[3],xt=c(He[2],Fe),xt.length<pe[4].length&&(xt=xe(pe[4].substr(pe[4].length-xt.length))+xt),X+=xt,X;if(pe=$.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))return Fe=Math.min(Math.max(pe[1].length,pe[4].length),7),He=b(ft,Math.pow(10,Fe)-1,!0),Dt+(He[0]||(He[1]?"":"0"))+" "+(He[1]?l(He[1],Fe)+pe[2]+"/"+pe[3]+c(He[2],Fe):u(" ",2*Fe+1+pe[2].length+pe[3].length));if(pe=$.match(/^[#0?]+$/))return X=""+K,$.length<=X.length?X:xe($.substr(0,$.length-X.length))+X;if(pe=$.match(/^([#0]+)\.([#0]+)$/)){X=""+K.toFixed(Math.min(pe[2].length,10)).replace(/([^0])0+$/,"$1"),Fe=X.indexOf(".");var Fr=$.indexOf(".")-Fe,Ef=$.length-X.length-Fr;return xe($.substr(0,Fr)+X+$.substr($.length-Ef))}if(pe=$.match(/^00,000\.([#0]*0)$/))return K<0?"-"+Ce(me,$,-K):ce(""+K).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function(Ys){return"00,"+(Ys.length<3?a(0,3-Ys.length):"")+Ys})+"."+a(0,pe[1].length);switch($){case"###,###":case"##,###":case"#,###":var p_=ce(""+ft);return p_!=="0"?Dt+p_:"";default:if($.match(/\.[0#?]*$/))return Ce(me,$.slice(0,$.lastIndexOf(".")),K)+xe($.slice($.lastIndexOf(".")))}throw new Error("unsupported format |"+$+"|")}return function($,K,De){return(De|0)===De?Ce($,K,De):ue($,K,De)}}();function ie(L){for(var P=[],q=!1,Y=0,j=0;Y<L.length;++Y)switch(L.charCodeAt(Y)){case 34:q=!q;break;case 95:case 42:case 92:++Y;break;case 59:P[P.length]=L.substr(j,Y-j),j=Y+1}if(P[P.length]=L.substr(j),q===!0)throw new Error("Format |"+L+"| unterminated string ");return P}s._split=ie;var ee=/\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/;function Z(L){for(var P=0,q="",Y="";P<L.length;)switch(q=L.charAt(P)){case"G":m(L,P)&&(P+=6),P++;break;case'"':for(;L.charCodeAt(++P)!==34&&P<L.length;);++P;break;case"\\":P+=2;break;case"_":P+=2;break;case"@":++P;break;case"B":case"b":if(L.charAt(P+1)==="1"||L.charAt(P+1)==="2")return!0;case"M":case"D":case"Y":case"H":case"S":case"E":case"m":case"d":case"y":case"h":case"s":case"e":case"g":return!0;case"A":case"a":case"上":if(L.substr(P,3).toUpperCase()==="A/P"||L.substr(P,5).toUpperCase()==="AM/PM"||L.substr(P,5).toUpperCase()==="上午/下午")return!0;++P;break;case"[":for(Y=q;L.charAt(P++)!=="]"&&P<L.length;)Y+=L.charAt(P);if(Y.match(ee))return!0;break;case".":case"0":case"#":for(;P<L.length&&("0#?.,E+-%".indexOf(q=L.charAt(++P))>-1||q=="\\"&&L.charAt(P+1)=="-"&&"0#".indexOf(L.charAt(P+2))>-1););break;case"?":for(;L.charAt(++P)===q;);break;case"*":++P,(L.charAt(P)==" "||L.charAt(P)=="*")&&++P;break;case"(":case")":++P;break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":for(;P<L.length&&"0123456789".indexOf(L.charAt(++P))>-1;);break;case" ":++P;break;default:++P;break}return!1}s.is_date=Z;function fe(L,P,q,Y){for(var j=[],W="",z=0,re="",de="t",le,se,xe,we="H";z<L.length;)switch(re=L.charAt(z)){case"G":if(!m(L,z))throw new Error("unrecognized character "+re+" in "+L);j[j.length]={t:"G",v:"General"},z+=7;break;case'"':for(W="";(xe=L.charCodeAt(++z))!==34&&z<L.length;)W+=String.fromCharCode(xe);j[j.length]={t:"t",v:W},++z;break;case"\\":var Ye=L.charAt(++z),Ue=Ye==="("||Ye===")"?Ye:"t";j[j.length]={t:Ue,v:Ye},++z;break;case"_":j[j.length]={t:"t",v:" "},z+=2;break;case"@":j[j.length]={t:"T",v:P},++z;break;case"B":case"b":if(L.charAt(z+1)==="1"||L.charAt(z+1)==="2"){if(le==null&&(le=C(P,q,L.charAt(z+1)==="2"),le==null))return"";j[j.length]={t:"X",v:L.substr(z,2)},de=re,z+=2;break}case"M":case"D":case"Y":case"H":case"S":case"E":re=re.toLowerCase();case"m":case"d":case"y":case"h":case"s":case"e":case"g":if(P<0||le==null&&(le=C(P,q),le==null))return"";for(W=re;++z<L.length&&L.charAt(z).toLowerCase()===re;)W+=re;re==="m"&&de.toLowerCase()==="h"&&(re="M"),re==="h"&&(re=we),j[j.length]={t:re,v:W},de=re;break;case"A":case"a":case"上":var te={t:re,v:re};if(le==null&&(le=C(P,q)),L.substr(z,3).toUpperCase()==="A/P"?(le!=null&&(te.v=le.H>=12?"P":"A"),te.t="T",we="h",z+=3):L.substr(z,5).toUpperCase()==="AM/PM"?(le!=null&&(te.v=le.H>=12?"PM":"AM"),te.t="T",z+=5,we="h"):L.substr(z,5).toUpperCase()==="上午/下午"?(le!=null&&(te.v=le.H>=12?"下午":"上午"),te.t="T",z+=5,we="h"):(te.t="t",++z),le==null&&te.t==="T")return"";j[j.length]=te,de=re;break;case"[":for(W=re;L.charAt(z++)!=="]"&&z<L.length;)W+=L.charAt(z);if(W.slice(-1)!=="]")throw'unterminated "[" block: |'+W+"|";if(W.match(ee)){if(le==null&&(le=C(P,q),le==null))return"";j[j.length]={t:"Z",v:W.toLowerCase()},de=W.charAt(1)}else W.indexOf("$")>-1&&(W=(W.match(/\$([^-\[\]]*)/)||[])[1]||"$",Z(L)||(j[j.length]={t:"t",v:W}));break;case".":if(le!=null){for(W=re;++z<L.length&&(re=L.charAt(z))==="0";)W+=re;j[j.length]={t:"s",v:W};break}case"0":case"#":for(W=re;++z<L.length&&"0#?.,E+-%".indexOf(re=L.charAt(z))>-1;)W+=re;j[j.length]={t:"n",v:W};break;case"?":for(W=re;L.charAt(++z)===re;)W+=re;j[j.length]={t:re,v:W},de=re;break;case"*":++z,(L.charAt(z)==" "||L.charAt(z)=="*")&&++z;break;case"(":case")":j[j.length]={t:Y===1?"t":re,v:re},++z;break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":for(W=re;z<L.length&&"0123456789".indexOf(L.charAt(++z))>-1;)W+=L.charAt(z);j[j.length]={t:"D",v:W};break;case" ":j[j.length]={t:re,v:re},++z;break;case"$":j[j.length]={t:"t",v:"$"},++z;break;default:if(",$-+/():!^&'~{}<>=€acfijklopqrtuvwxzP".indexOf(re)===-1)throw new Error("unrecognized character "+re+" in "+L);j[j.length]={t:"t",v:re},++z;break}var ue=0,Te=0,Be;for(z=j.length-1,de="t";z>=0;--z)switch(j[z].t){case"h":case"H":j[z].t=we,de="h",ue<1&&(ue=1);break;case"s":(Be=j[z].v.match(/\.0+$/))&&(Te=Math.max(Te,Be[0].length-1)),ue<3&&(ue=3);case"d":case"y":case"M":case"e":de=j[z].t;break;case"m":de==="s"&&(j[z].t="M",ue<2&&(ue=2));break;case"X":break;case"Z":ue<1&&j[z].v.match(/[Hh]/)&&(ue=1),ue<2&&j[z].v.match(/[Mm]/)&&(ue=2),ue<3&&j[z].v.match(/[Ss]/)&&(ue=3)}switch(ue){case 0:break;case 1:le.u>=.5&&(le.u=0,++le.S),le.S>=60&&(le.S=0,++le.M),le.M>=60&&(le.M=0,++le.H);break;case 2:le.u>=.5&&(le.u=0,++le.S),le.S>=60&&(le.S=0,++le.M);break}var Ie="",Ce;for(z=0;z<j.length;++z)switch(j[z].t){case"t":case"T":case" ":case"D":break;case"X":j[z].v="",j[z].t=";";break;case"d":case"m":case"y":case"h":case"H":case"M":case"s":case"e":case"b":case"Z":j[z].v=J(j[z].t.charCodeAt(0),j[z].v,le,Te),j[z].t="t";break;case"n":case"?":for(Ce=z+1;j[Ce]!=null&&((re=j[Ce].t)==="?"||re==="D"||(re===" "||re==="t")&&j[Ce+1]!=null&&(j[Ce+1].t==="?"||j[Ce+1].t==="t"&&j[Ce+1].v==="/")||j[z].t==="("&&(re===" "||re==="n"||re===")")||re==="t"&&(j[Ce].v==="/"||j[Ce].v===" "&&j[Ce+1]!=null&&j[Ce+1].t=="?"));)j[z].v+=j[Ce].v,j[Ce]={v:"",t:";"},++Ce;Ie+=j[z].v,z=Ce-1;break;case"G":j[z].t="t",j[z].v=G(P,q);break}var me="",$,K;if(Ie.length>0){Ie.charCodeAt(0)==40?($=P<0&&Ie.charCodeAt(0)===45?-P:P,K=he("n",Ie,$)):($=P<0&&Y>1?-P:P,K=he("n",Ie,$),$<0&&j[0]&&j[0].t=="t"&&(K=K.substr(1),j[0].v="-"+j[0].v)),Ce=K.length-1;var De=j.length;for(z=0;z<j.length;++z)if(j[z]!=null&&j[z].t!="t"&&j[z].v.indexOf(".")>-1){De=z;break}var X=j.length;if(De===j.length&&K.indexOf("E")===-1){for(z=j.length-1;z>=0;--z)j[z]==null||"n?".indexOf(j[z].t)===-1||(Ce>=j[z].v.length-1?(Ce-=j[z].v.length,j[z].v=K.substr(Ce+1,j[z].v.length)):Ce<0?j[z].v="":(j[z].v=K.substr(0,Ce+1),Ce=-1),j[z].t="t",X=z);Ce>=0&&X<j.length&&(j[X].v=K.substr(0,Ce+1)+j[X].v)}else if(De!==j.length&&K.indexOf("E")===-1){for(Ce=K.indexOf(".")-1,z=De;z>=0;--z)if(!(j[z]==null||"n?".indexOf(j[z].t)===-1)){for(se=j[z].v.indexOf(".")>-1&&z===De?j[z].v.indexOf(".")-1:j[z].v.length-1,me=j[z].v.substr(se+1);se>=0;--se)Ce>=0&&(j[z].v.charAt(se)==="0"||j[z].v.charAt(se)==="#")&&(me=K.charAt(Ce--)+me);j[z].v=me,j[z].t="t",X=z}for(Ce>=0&&X<j.length&&(j[X].v=K.substr(0,Ce+1)+j[X].v),Ce=K.indexOf(".")+1,z=De;z<j.length;++z)if(!(j[z]==null||"n?(".indexOf(j[z].t)===-1&&z!==De)){for(se=j[z].v.indexOf(".")>-1&&z===De?j[z].v.indexOf(".")+1:0,me=j[z].v.substr(0,se);se<j[z].v.length;++se)Ce<K.length&&(me+=K.charAt(Ce++));j[z].v=me,j[z].t="t",X=z}}}for(z=0;z<j.length;++z)j[z]!=null&&"n?".indexOf(j[z].t)>-1&&($=Y>1&&P<0&&z>0&&j[z-1].v==="-"?-P:P,j[z].v=he(j[z].t,j[z].v,$),j[z].t="t");var pe="";for(z=0;z!==j.length;++z)j[z]!=null&&(pe+=j[z].v);return pe}s._eval=fe;var N=/\[[=<>]/,w=/\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/;function F(L,P){if(P==null)return!1;var q=parseFloat(P[2]);switch(P[1]){case"=":if(L==q)return!0;break;case">":if(L>q)return!0;break;case"<":if(L<q)return!0;break;case"<>":if(L!=q)return!0;break;case">=":if(L>=q)return!0;break;case"<=":if(L<=q)return!0;break}return!1}function U(L,P){var q=ie(L),Y=q.length,j=q[Y-1].indexOf("@");if(Y<4&&j>-1&&--Y,q.length>4)throw new Error("cannot find right format for |"+q.join("|")+"|");if(typeof P!="number")return[4,q.length===4||j>-1?q[q.length-1]:"@"];switch(q.length){case 1:q=j>-1?["General","General","General",q[0]]:[q[0],q[0],q[0],"@"];break;case 2:q=j>-1?[q[0],q[0],q[0],q[1]]:[q[0],q[1],q[0],"@"];break;case 3:q=j>-1?[q[0],q[1],q[0],q[2]]:[q[0],q[1],q[2],"@"];break}var W=P>0?q[0]:P<0?q[1]:q[2];if(q[0].indexOf("[")===-1&&q[1].indexOf("[")===-1)return[Y,W];if(q[0].match(N)!=null||q[1].match(N)!=null){var z=q[0].match(w),re=q[1].match(w);return F(P,z)?[Y,q[0]]:F(P,re)?[Y,q[1]]:[Y,q[z!=null&&re!=null?2:1]]}return[Y,W]}function V(L,P,q){q==null&&(q={});var Y="";switch(typeof L){case"string":L=="m/d/yy"&&q.dateNF?Y=q.dateNF:Y=L;break;case"number":L==14&&q.dateNF?Y=q.dateNF:Y=(q.table!=null?q.table:_)[L],Y==null&&(Y=q.table&&q.table[v[L]]||_[v[L]]),Y==null&&(Y=S[L]||"General");break}if(m(Y,0))return G(P,q);P instanceof Date&&(P=D(P,q.date1904));var j=U(Y,P);if(m(j[1]))return G(P,q);if(P===!0)P="TRUE";else if(P===!1)P="FALSE";else if(P===""||P==null)return"";return fe(j[1],P,q,j[0])}function Q(L,P){if(typeof P!="number"){P=+P||-1;for(var q=0;q<392;++q){if(_[q]==null){P<0&&(P=q);continue}if(_[q]==L){P=q;break}}P<0&&(P=391)}return _[P]=L,P}s.load=Q,s._table=_,s.get_table=function(){return _},s.load_table=function(P){for(var q=0;q!=392;++q)P[q]!==void 0&&Q(P[q],q)},s.init_table=E,s.format=V};r(e),typeof DO_NOT_EXPORT_SSF>"u"&&(t.exports=e)})(oz);var nA=oz.exports;function J3e(t){const e=[];for(const a of t.schema.fields)a.kind==="dimension"&&e.push(a);const i=K6(t.annotations,"#(malloy) ").text("query_name")??"root",s=new uz({name:i,type:{kind:"array_type",element_type:{kind:"record_type",fields:e}},annotations:t.annotations},{modelTag:K6(t.model_annotations,"## "),queryTimezone:t.query_timezone}),o=t.data.kind==="record_cell"?{kind:"array_cell",array_value:[t.data]}:t.data;return new cye(o,s)}function X3e(t){return t.type.kind==="array_type"}function Z3e(t){return t.type.kind==="array_type"&&t.type.element_type.kind==="record_type"}function eye(t){return t.type.kind==="record_type"}function tye(t){return t.type.kind==="number_type"}function nye(t){return t.type.kind==="date_type"}function rye(t){return t.type.kind==="json_type"}function iye(t){return t.type.kind==="string_type"}function sye(t){return t.type.kind==="timestamp_type"}function oye(t){return t.type.kind==="boolean_type"}function uye(t){return t.type.kind==="sql_native_type"}const _l={from(t,e){if(Z3e(t))return new wh(t,e);if(X3e(t))return new Oh(t,e);if(eye(t))return new hg(t,e);if(oye(t))return new lA(t,e);if(rye(t))return new aA(t,e);if(nye(t))return new iA(t,e);if(sye(t))return new sA(t,e);if(iye(t))return new oA(t,e);if(tye(t))return new rA(t,e);if(uye(t))return new uA(t,e);throw new Error(`Unknown field type ${t.type.kind}`)},isNestField(t){return t instanceof wh||t instanceof Oh||t instanceof hg},pathFromString(t){return JSON.parse(t)},pathToString(t){return JSON.stringify(t)}};function U6(t,e="# "){return K6(t.annotations,e)}const aye=["link","image","cell","list","list_detail","bar_chart","line_chart","dashboard","scatter_chart","shape_map","segment_map"];function lye(t,e,r){const i=U6(t),s=Object.keys(i.properties??{}).reverse();for(const u of s)if(aye.includes(u))return["list","list_detail"].includes(u)?"list":["bar_chart","line_chart"].includes(u)?"chart":u;return t.type.kind==="record_type"&&(e==null?void 0:e.renderAs)==="chart"?"none":t.type.kind==="array_type"||t.type.kind==="record_type"?"table":"cell"}class vl{constructor(e,r){this.field=e,this.parent=r,this.valueSet=new Set,this.tag=U6(this.field),this.metadataTag=U6(this.field,"#(malloy) "),this.path=r?r.isArray()?[...r.path]:[...r.path,e.name]:[],this.renderAs=lye(e,r)}isRoot(){return this.path.length===0}root(){if(this.parent)return this.parent.root();if(this instanceof uz)return this;throw new Error("Root field was not an instance of RootField")}get sourceName(){return this.metadataTag.text("source_name")??"__source__"}get name(){return this.field.name}fieldAt(e){return typeof e=="string"?this.fieldAtPath(_l.pathFromString(e)):this.fieldAtPath(e)}getParentRecord(e){let r=this.asField();for(;r&&e>0;){for(r=r.parent;r!=null&&r.isArray();)r=r.parent;e--}if(!(r!=null&&r.isRecord()))throw new Error(`Parent ${e} levels up was not a record`);return r}get key(){return _l.pathToString(this.path)}fieldAtPath(e){if(e.length===0)return this.asField();throw new Error(`${this.constructor.name} cannot contain fields`)}registerNullValue(){this.valueSet.add(Fh)}get drillFilters(){return this.metadataTag.textArray("drill_filters")??[]}get referenceId(){return this.metadataTag.text("reference_id")}escapeIdentifier(e){return e.replace(/\\/g,"\\\\").replace("`","\\`")}identifierCode(){return this.name.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?this.name:`\`${this.escapeIdentifier(this.name)}\``}drillExpression(){return this.metadataTag.text("drill_expression")??this.identifierCode()}wasDimension(){return!this.wasCalculation()}wasCalculation(){return this.metadataTag.has("calculation")}isHidden(){return this.tag.has("hidden")}get minNumber(){}get maxNumber(){}get maxString(){}asField(){if(this instanceof Oh||this instanceof wh||this instanceof hg||this instanceof rA||this instanceof iA||this instanceof aA||this instanceof oA||this instanceof sA||this instanceof lA||this instanceof uA)return this;throw new Error("Not a field")}isArray(){return this instanceof Oh}isRepeatedRecord(){return this instanceof wh}isRecord(){return this instanceof hg}isNumber(){return this instanceof rA}isBoolean(){return this instanceof lA}isString(){return this instanceof oA}isRecordOrRepeatedRecord(){return this.isRecord()||this.isRepeatedRecord()}isDate(){return this instanceof iA}isTimestamp(){return this instanceof sA}isTime(){return this.isDate()||this.isTimestamp()}isSQLNative(){return this instanceof uA}isJSON(){return this instanceof aA}isBasic(){return!this.isNest()}isNest(){return this.isArray()||this.isRecord()||this.isRepeatedRecord()}getLocationInParent(){var e;return((e=this.parent)==null?void 0:e.fields.findIndex(r=>r===this))??-1}isLastChild(){const e=this.parent;return e===void 0||this.getLocationInParent()===e.fields.length}isFirstChild(){return this.getLocationInParent()===0}pathTo(e){const r=this.path,i=e.path,s=r.length;let o=0;for(;r[o];){if(r[o]!==i[o])throw new Error("Tried to get path from parent field to child field, but parent field is not a parent of child field.");o++}return _l.pathToString(i.slice(s))}}class Oh extends vl{constructor(e,r){super(e,r),this.field=e,this.maxUniqueFieldValueCounts=new Map,this.eachField=_l.from({name:"each",type:this.field.type.element_type},this),this.fields=[this.eachField]}}class wh extends Oh{constructor(e,r){super(e,r),this.field=e,this.maxRecordCount=0,this._fieldsWithOrder=void 0;const i=this.eachField;if(!i.isRecord())throw new Error("Expected eachField of repeatedRecord to be a record");this.fields=i.fields}fieldAtPath(e){return e.length===0?this.asField():this.eachField.fieldAtPath(e)}registerRecordCount(e){this.maxRecordCount=Math.max(e,this.maxRecordCount)}registerValueSetSize(e,r){this.maxUniqueFieldValueCounts.set(e,Math.max(this.maxUniqueFieldValueCounts.get(e)??0,r))}get fieldsWithOrder(){var e;if(!this._fieldsWithOrder){const r=this.metadataTag.tag("ordered_by"),i=(r&&((e=r.array())==null?void 0:e.map(o=>{const u=Object.keys(o.properties??{})[0],a=o.text(u);return{field:this.fieldAt(u),dir:a}})))??[],s=new Set(i.map(o=>o.field.name));this._fieldsWithOrder=[...i,...this.fields.filter(o=>!s.has(o.name)).map(o=>({field:o,dir:"asc"}))]}return this._fieldsWithOrder}}class uz extends wh{constructor(e,r){super(e,void 0),this.field=e,this.modelTag=r.modelTag,this.queryTimezone=r.queryTimezone}}class hg extends vl{constructor(e,r){super(e,r),this.field=e,this.maxUniqueFieldValueCounts=new Map,this._fieldsWithOrder=void 0,this.fields=e.type.fields.map(i=>_l.from(i,this)),this.fieldsByName=Object.fromEntries(this.fields.map(i=>[i.name,i]))}fieldAtPath(e){if(e.length===0)return this.asField();{const[r,...i]=e,s=this.fieldsByName[r];if(s===void 0)throw new Error(`No such field ${r} in ${this.path}`);return s.fieldAtPath(i)}}get fieldsWithOrder(){return this._fieldsWithOrder===void 0&&(this._fieldsWithOrder=[...this.fields.map(e=>({field:e,dir:"asc"}))]),this._fieldsWithOrder}}let rA=class extends vl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}registerValue(e){this.valueSet.add(e),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const r=e.toString();(this._maxString===void 0||r.length>this._maxString.length)&&(this._maxString=r)}fieldAtPath(e){if(e.length===0)return this.asField();throw new Error("NumberField cannot contain fields")}get minNumber(){return this.min}get maxNumber(){return this.max}get maxString(){return this._maxString}},iA=class extends vl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}get timeframe(){return this.field.type.timeframe}registerValue(e){const r=Number(e);this.valueSet.add(r),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const i=Al(e,!0,this.timeframe).toString();(this._maxString===void 0||i.length>this._maxString.length)&&(this._maxString=i)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}get minNumber(){return this.min!==void 0?Number(this.min):void 0}get maxNumber(){return this.max!==void 0?Number(this.max):void 0}},sA=class extends vl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}get timeframe(){return this.field.type.timeframe}registerValue(e){const r=Number(e);this.valueSet.add(r),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const i=Al(e,!1,this.timeframe).toString();(this._maxString===void 0||i.length>this._maxString.length)&&(this._maxString=i)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}},oA=class extends vl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}registerValue(e){this.valueSet.add(e),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e),(this._maxString===void 0||e.length>this._maxString.length)&&(this._maxString=e)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}};class uA extends vl{constructor(e,r){super(e,r),this.field=e}}let aA=class extends vl{constructor(e,r){super(e,r),this.field=e}},lA=class extends vl{constructor(e,r){super(e,r),this.field=e,this._maxString=void 0}get maxString(){return this._maxString}registerValue(e){this.valueSet.add(e);const r=String(e);(this._maxString===void 0||this._maxString.length<r.length)&&(this._maxString=r)}};const az={from(t,e,r){switch(t.kind){case"array_cell":{if(e instanceof wh)return new fA(t,e,r);if(e instanceof Oh)return new cA(t,e,r);throw new Error("Expected record data to be associated with record field")}case"record_cell":{if(e instanceof hg)return new q6(t,e,r);throw new Error("Expected record data to be associated with record field")}case"null_cell":return new H6(t,e,r);case"number_cell":{if(e instanceof rA)return new z6(t,e,r);throw new Error("Expected number data to be associated with number field")}case"date_cell":{if(e instanceof iA)return new Q6(t,e,r);throw new Error("Expected date data to be associated with date field")}case"json_cell":{if(e instanceof aA)return new W6(t,e,r);throw new Error("Expected JSON data to be associated with JSON field")}case"string_cell":{if(e instanceof oA)return new V6(t,e,r);throw new Error("Expected string data to be associated with string field")}case"timestamp_cell":{if(e instanceof sA)return new G6(t,e,r);throw new Error("Expected timestamp data to be associated with timestamp field")}case"boolean_cell":{if(e instanceof lA)return new Y6(t,e,r);throw new Error("Expected boolean data to be associated with boolean field")}case"sql_native_cell":{if(e instanceof uA)return new lz(t,e,r);throw new Error("Expected sql_native data to be associated with sql_native field")}}}};class Wu{constructor(e,r,i){this.cell=e,this.field=r,this.parent=i}isNull(){return this instanceof H6}isArray(){return this instanceof cA}isRecord(){return this instanceof q6}isRepeatedRecord(){return this instanceof fA}isRecordOrRepeatedRecord(){return this.isRepeatedRecord()||this.isRecord()}isNest(){return this.isRepeatedRecord()||this.isRecord()||this.isArray()}isNumber(){return this instanceof z6}isDate(){return this instanceof Q6}isTime(){return this.isDate()||this.isTimestamp()}isJSON(){return this instanceof W6}isString(){return this instanceof V6}isTimestamp(){return this instanceof G6}isBoolean(){return this instanceof Y6}asCell(){if(this instanceof cA||this instanceof fA||this instanceof q6||this instanceof z6||this instanceof Q6||this instanceof W6||this instanceof V6||this instanceof G6||this instanceof Y6||this instanceof H6||this instanceof lz)return this;throw new Error("Not a cell")}root(){return this.parent?this.parent.root():this.asCell()}getPathInfo(e){const r=e.split("/"),i=r.filter(o=>o==="..").length+1,s=r.filter(o=>o!==".."&&o!=="");return{levelsUp:i,pathSegments:s}}getParentRecord(e){let r=this.asCell();for(;r&&e>0;){for(r=r.parent;r!=null&&r.isArray();)r=r.parent;e--}if(!(r!=null&&r.isRecord()))throw new Error(`Parent ${e} levels up was not a record`);return r}getRelativeCell(e){try{const{levelsUp:r,pathSegments:i}=this.getPathInfo(e);return this.getParentRecord(r).cellAtPath(i)}catch{return}}cellAt(e){return typeof e=="string"?this.cellAtPath(_l.pathFromString(e)):this.cellAtPath(e)}cellAtPath(e){if(e.length===0)return this.asCell();throw new Error(`${this.constructor.name} cannot contain columns`)}compareTo(e){return 0}getDrillValues(){let e=this.asCell();const r=[];for(;e&&(e&&e.isArray()&&(r.unshift(...e.field.drillFilters.map(i=>({where:i}))),e=e.parent),e!==void 0);){if(e&&e.isRecord()){const i=e,s=e.field.fields.filter(o=>o.isBasic()&&o.wasDimension());r.unshift(...s.map(o=>({field:o,value:i.column(o.name)})))}e=e.parent}return r}getDrillExpressions(){return this.getDrillValues().map(r=>{if("where"in r)return r.where;const i=pye(r.value);return`${r.field.drillExpression()} = ${i}`})}getDrillEntries(){const e=this.getDrillValues(),r=[];for(const i of e)"where"in i?r.push(i):(i.value.isNull()||i.value.isTime()||i.value.isString()||i.value.isNumber()||i.value.isBoolean())&&r.push({field:i.field,value:i.value.value});return r}getDrillQuery(){const e=this.getDrillExpressions();let r=`run: ${this.field.root().sourceName} ->`;return e.length>0&&(r+=` {
652
+ `,r}find(e){var r;let i=At.tagFrom(this);for(const s of e)if(typeof s=="number"){if(i.eq===void 0||!Array.isArray(i.eq)||i.eq.length<=s)return;i=At.tagFrom(i.eq[s])}else{const o=(r=i.properties)!==null&&r!==void 0?r:{};if(s in o)i=At.tagFrom(o[s]);else return}return i.deleted?void 0:i}has(...e){return this.find(e)!==void 0}set(e,r=null){const i=At.tagFrom(this);let s=i;for(const o of e)if(typeof o=="number"){if(s.eq===void 0||!Array.isArray(s.eq))s.eq=Array.from({length:o+1}).map(u=>({}));else if(s.eq.length<=o){const u=s.eq,a=Array.from({length:o+1}).map((l,c)=>c<u.length?u[c]:{});s.eq=a}s=s.eq[o]}else{const u=s.properties;u===void 0?(s.properties={[o]:{}},s=s.properties[o]):o in u?(s=u[o],s.deleted&&(s.deleted=!1)):(u[o]={},s=u[o])}return r===null?s.eq=void 0:typeof r=="string"?s.eq=r:typeof r=="number"?s.eq=r.toString():Array.isArray(r)&&(s.eq=r.map(o=>({eq:typeof o=="string"?o:o.toString()}))),i}delete(...e){return this.remove(e,!1)}unset(...e){return this.remove(e,!0)}remove(e,r=!1){var i;const s=At.tagFrom(this);let o=s;for(const a of e.slice(0,e.length-1))if(typeof a=="number"){if(o.eq===void 0||!Array.isArray(o.eq)){if(!r)return s;o.eq=Array.from({length:a}).map(l=>({}))}else if(o.eq.length<=a){if(!r)return s;const l=o.eq,c=Array.from({length:a}).map((f,x)=>x<l.length?l[x]:{});o.eq=c}o=o.eq[a]}else{const l=o.properties;if(l===void 0){if(!r)return s;o.properties={[a]:{}},o=o.properties[a]}else if(a in l)o=l[a];else{if(!r)return s;l[a]={},o=l[a]}}const u=e[e.length-1];return typeof u=="string"?o.properties&&u in o.properties?delete o.properties[u]:r&&((i=o.properties)!==null&&i!==void 0||(o.properties={}),o.properties[u]={deleted:!0}):Array.isArray(o.eq)&&o.eq.splice(u,1),s}}L_.Tag=At,At.ids=new Map,At.nextTagId=1e3;class V3e{constructor(e){this.line=e,this.log=[]}syntaxError(e,r,i,s,o,u){const a={code:"tag-parse-syntax-error",message:o,line:this.line,offset:s};this.log.push(a)}semanticError(e,r,i){const s={code:r,message:i,line:this.line,offset:e.start.charPositionInLine};this.log.push(s)}}function dg(t){const e=t.buildOn;return e instanceof At?e:new At}function eA(t,e){var r,i;let s=t.getProperties();for(const o of e.slice(0,e.length-1)){let u;s[o]===void 0?(u=new At({}),s[o]=u):((r=(i=s[o]).properties)!==null&&r!==void 0||(i.properties={}),u=At.tagFrom(s[o])),s=u.getProperties()}return[e[e.length-1],s]}function iz(t){return t.SQ_STRING()||t.DQ_STRING()?(0,rz.parseString)(t.text,t.text[0]):t.text}function sz(t,e,r,i){if(t[0]==="#"){const d=t.indexOf(" ");d>0?t=t.slice(d):t=""}const s=nz.CharStreams.fromString(t),o=new G3e.MalloyTagLexer(s),u=new nz.CommonTokenStream(o),a=new V3e(i),l=new W3e.MalloyTagParser(u);l.removeErrorListeners(),l.addErrorListener(a);const c=l.tagLine();return{tag:new Y3e(r,a).tagLineToTag(c,e),log:a.log}}class Y3e extends Q3e.AbstractParseTreeVisitor{constructor(e=[],r){super(),this.scopes=[],this.msgLog=r,this.scopes.unshift(...e)}defaultResult(){return new At}visitString(e){return new At({eq:iz(e)})}getPropName(e){return e.identifier().map(r=>r.BARE_STRING()?r.text:(0,rz.parseString)(r.text,r.text[0]))}getTags(e,r){for(const i of e)i.buildOn=r,this.visit(i);return r}tagLineToTag(e,r){return r=(r==null?void 0:r.clone())||new At({}),this.scopes.unshift(r),this.getTags(e.tagSpec(),r),r}visitTagLine(e){throw new Error("INTERNAL: ERROR: Call tagLineToTag, not vistTagLine")}visitProperties(e){return this.getTags(e.tagSpec(),dg(e))}visitArrayValue(e){return new At({eq:this.getArray(e)})}getArray(e){return e.arrayElement().map(r=>this.visit(r))}visitArrayElement(e){const r=e.properties(),i=r?this.visitProperties(r):void 0,s=e.string();let o=s?iz(s):void 0;const u=e.arrayValue();if(u&&(o=this.getArray(u)),i)return o!==void 0&&(i.eq=o),i;const a=e.reference();return a?this.visitReference(a):new At({eq:o})}visitReference(e){const r=this.getPropName(e.propName());for(const i of this.scopes)if(i.has(r[0])){const s=i.tag(...r);if(s)return s.clone();break}return this.msgLog.semanticError(e,"tag-property-not-found",`Reference to undefined property ${r.join(".")}`),this.defaultResult()}visitTagEq(e){const r=dg(e),i=this.getPropName(e.propName()),[s,o]=eA(r,i),u=this.visit(e.eqValue()),a=e.properties();if(a)if(a.DOTTY()===void 0){const l=this.visitProperties(a).dict;o[s]={...u,properties:l}}else o[s]={...o[s],...u};else o[s]=u;return r}visitTagReplaceProperties(e){const r=dg(e),i=this.getPropName(e.propName()),[s,o]=eA(r,i),u=e.properties(),a=this.visitProperties(u);return e.DOTTY()===void 0?o[s]={properties:a.dict}:o[s].properties=a.dict,r}visitTagUpdateProperties(e){const r=dg(e),i=this.getPropName(e.propName()),[s,o]=eA(r,i),u=e.properties();u.buildOn=At.tagFrom(o[s]);const a=this.visitProperties(u),l=o[s]||new At({}),c={...l.properties,...a.dict};return o[s]={...l,properties:c},r}visitTagDef(e){const r=dg(e),i=this.getPropName(e.propName()),[s,o]=eA(r,i);return e.MINUS()?o[s]={deleted:!0}:o[s]=new At({}),r}visitTagEmpty(e){const r=e.buildOn;return r.properties={},r}}(function(t){var e=T&&T.__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=T&&T.__setModuleDefault||(Object.create?function(o,u){Object.defineProperty(o,"default",{enumerable:!0,value:u})}:function(o,u){o.default=u}),i=T&&T.__exportStar||function(o,u){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(u,a)&&e(u,o,a)},s=T&&T.__importStar||function(o){if(o&&o.__esModule)return o;var u={};if(o!=null)for(var a in o)a!=="default"&&Object.prototype.hasOwnProperty.call(o,a)&&e(u,o,a);return r(u,o),u};Object.defineProperty(t,"__esModule",{value:!0}),t.ParseUtil=void 0,i(L_,t),t.ParseUtil=s(xg)})(ko);var tA=(t=>(t.Dollars="usd",t.Euros="euro",t.Pounds="pound",t))(tA||{}),mr=(t=>(t.Nanoseconds="nanoseconds",t.Microseconds="microseconds",t.Milliseconds="milliseconds",t.Seconds="seconds",t.Minutes="minutes",t.Hours="hours",t.Days="days",t))(mr||{});function K3e(t){return Object.values(mr).includes(t)}var oz={exports:{}};(function(t){var e={},r=function(s){s.version="0.11.2";function o(L){for(var P="",q=L.length-1;q>=0;)P+=L.charAt(q--);return P}function u(L,P){for(var q="";q.length<P;)q+=L;return q}function a(L,P){var q=""+L;return q.length>=P?q:u("0",P-q.length)+q}function l(L,P){var q=""+L;return q.length>=P?q:u(" ",P-q.length)+q}function c(L,P){var q=""+L;return q.length>=P?q:q+u(" ",P-q.length)}function f(L,P){var q=""+Math.round(L);return q.length>=P?q:u("0",P-q.length)+q}function x(L,P){var q=""+L;return q.length>=P?q:u("0",P-q.length)+q}var d=Math.pow(2,32);function p(L,P){if(L>d||L<-d)return f(L,P);var q=Math.round(L);return x(q,P)}function m(L,P){return P=P||0,L.length>=7+P&&(L.charCodeAt(P)|32)===103&&(L.charCodeAt(P+1)|32)===101&&(L.charCodeAt(P+2)|32)===110&&(L.charCodeAt(P+3)|32)===101&&(L.charCodeAt(P+4)|32)===114&&(L.charCodeAt(P+5)|32)===97&&(L.charCodeAt(P+6)|32)===108}var g=[["Sun","Sunday"],["Mon","Monday"],["Tue","Tuesday"],["Wed","Wednesday"],["Thu","Thursday"],["Fri","Friday"],["Sat","Saturday"]],y=[["J","Jan","January"],["F","Feb","February"],["M","Mar","March"],["A","Apr","April"],["M","May","May"],["J","Jun","June"],["J","Jul","July"],["A","Aug","August"],["S","Sep","September"],["O","Oct","October"],["N","Nov","November"],["D","Dec","December"]];function E(L){L[0]="General",L[1]="0",L[2]="0.00",L[3]="#,##0",L[4]="#,##0.00",L[9]="0%",L[10]="0.00%",L[11]="0.00E+00",L[12]="# ?/?",L[13]="# ??/??",L[14]="m/d/yy",L[15]="d-mmm-yy",L[16]="d-mmm",L[17]="mmm-yy",L[18]="h:mm AM/PM",L[19]="h:mm:ss AM/PM",L[20]="h:mm",L[21]="h:mm:ss",L[22]="m/d/yy h:mm",L[37]="#,##0 ;(#,##0)",L[38]="#,##0 ;[Red](#,##0)",L[39]="#,##0.00;(#,##0.00)",L[40]="#,##0.00;[Red](#,##0.00)",L[45]="mm:ss",L[46]="[h]:mm:ss",L[47]="mmss.0",L[48]="##0.0E+0",L[49]="@",L[56]='"上午/下午 "hh"時"mm"分"ss"秒 "'}var _={};E(_);var v=[],A=0;for(A=5;A<=8;++A)v[A]=32+A;for(A=23;A<=26;++A)v[A]=0;for(A=27;A<=31;++A)v[A]=14;for(A=50;A<=58;++A)v[A]=14;for(A=59;A<=62;++A)v[A]=A-58;for(A=67;A<=68;++A)v[A]=A-58;for(A=72;A<=75;++A)v[A]=A-58;for(A=67;A<=68;++A)v[A]=A-57;for(A=76;A<=78;++A)v[A]=A-56;for(A=79;A<=81;++A)v[A]=A-34;var S=[];S[5]=S[63]='"$"#,##0_);\\("$"#,##0\\)',S[6]=S[64]='"$"#,##0_);[Red]\\("$"#,##0\\)',S[7]=S[65]='"$"#,##0.00_);\\("$"#,##0.00\\)',S[8]=S[66]='"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',S[41]='_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',S[42]='_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)',S[43]='_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',S[44]='_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)';function b(L,P,q){for(var Y=L<0?-1:1,j=L*Y,W=0,z=1,re=0,de=1,le=0,se=0,xe=Math.floor(j);le<P&&(xe=Math.floor(j),re=xe*z+W,se=xe*le+de,!(j-xe<5e-8));)j=1/(j-xe),W=z,z=re,de=le,le=se;if(se>P&&(le>P?(se=de,re=W):(se=le,re=z)),!q)return[0,Y*re,se];var we=Math.floor(Y*re/se);return[we,Y*re-we*se,se]}function C(L,P,q){if(L>2958465||L<0)return null;var Y=L|0,j=Math.floor(86400*(L-Y)),W=0,z=[],re={D:Y,T:j,u:86400*(L-Y)-j,y:0,m:0,d:0,H:0,M:0,S:0,q:0};if(Math.abs(re.u)<1e-6&&(re.u=0),P&&P.date1904&&(Y+=1462),re.u>.9999&&(re.u=0,++j==86400&&(re.T=j=0,++Y,++re.D)),Y===60)z=q?[1317,10,29]:[1900,2,29],W=3;else if(Y===0)z=q?[1317,8,29]:[1900,1,0],W=6;else{Y>60&&--Y;var de=new Date(1900,0,1);de.setDate(de.getDate()+Y-1),z=[de.getFullYear(),de.getMonth()+1,de.getDate()],W=de.getDay(),Y<60&&(W=(W+6)%7),q&&(W=H(de,z))}return re.y=z[0],re.m=z[1],re.d=z[2],re.S=j%60,j=Math.floor(j/60),re.M=j%60,j=Math.floor(j/60),re.H=j,re.q=W,re}s.parse_date_code=C;var R=new Date(1899,11,31,0,0,0),O=R.getTime(),B=new Date(1900,2,1,0,0,0);function D(L,P){var q=L.getTime();return P?q-=1262304e5:L>=B&&(q+=864e5),(q-(O+(L.getTimezoneOffset()-R.getTimezoneOffset())*6e4))/864e5}function M(L){return L.toString(10)}s._general_int=M;var k=function(){var P=/(?:\.0*|(\.\d*[1-9])0+)$/;function q(le){return le.indexOf(".")==-1?le:le.replace(P,"$1")}var Y=/(?:\.0*|(\.\d*[1-9])0+)[Ee]/,j=/(E[+-])(\d)$/;function W(le){return le.indexOf("E")==-1?le:le.replace(Y,"$1E").replace(j,"$10$2")}function z(le){var se=le<0?12:11,xe=q(le.toFixed(12));return xe.length<=se||(xe=le.toPrecision(10),xe.length<=se)?xe:le.toExponential(5)}function re(le){var se=q(le.toFixed(11));return se.length>(le<0?12:11)||se==="0"||se==="-0"?le.toPrecision(6):se}function de(le){var se=Math.floor(Math.log(Math.abs(le))*Math.LOG10E),xe;return se>=-4&&se<=-1?xe=le.toPrecision(10+se):Math.abs(se)<=9?xe=z(le):se===10?xe=le.toFixed(10).substr(0,12):xe=re(le),q(W(xe.toUpperCase()))}return de}();s._general_num=k;function G(L,P){switch(typeof L){case"string":return L;case"boolean":return L?"TRUE":"FALSE";case"number":return(L|0)===L?L.toString(10):k(L);case"undefined":return"";case"object":if(L==null)return"";if(L instanceof Date)return V(14,D(L,P&&P.date1904),P)}throw new Error("unsupported value in General format: "+L)}s._general=G;function H(L,P){P[0]-=581;var q=L.getDay();return L<60&&(q=(q+6)%7),q}function J(L,P,q,Y){var j="",W=0,z=0,re=q.y,de,le=0;switch(L){case 98:re=q.y+543;case 121:switch(P.length){case 1:case 2:de=re%100,le=2;break;default:de=re%1e4,le=4;break}break;case 109:switch(P.length){case 1:case 2:de=q.m,le=P.length;break;case 3:return y[q.m-1][1];case 5:return y[q.m-1][0];default:return y[q.m-1][2]}break;case 100:switch(P.length){case 1:case 2:de=q.d,le=P.length;break;case 3:return g[q.q][0];default:return g[q.q][1]}break;case 104:switch(P.length){case 1:case 2:de=1+(q.H+11)%12,le=P.length;break;default:throw"bad hour format: "+P}break;case 72:switch(P.length){case 1:case 2:de=q.H,le=P.length;break;default:throw"bad hour format: "+P}break;case 77:switch(P.length){case 1:case 2:de=q.M,le=P.length;break;default:throw"bad minute format: "+P}break;case 115:if(P!="s"&&P!="ss"&&P!=".0"&&P!=".00"&&P!=".000")throw"bad second format: "+P;return q.u===0&&(P=="s"||P=="ss")?a(q.S,P.length):(Y>=2?z=Y===3?1e3:100:z=Y===1?10:1,W=Math.round(z*(q.S+q.u)),W>=60*z&&(W=0),P==="s"?W===0?"0":""+W/z:(j=a(W,2+Y),P==="ss"?j.substr(0,2):"."+j.substr(2,P.length-1)));case 90:switch(P){case"[h]":case"[hh]":de=q.D*24+q.H;break;case"[m]":case"[mm]":de=(q.D*24+q.H)*60+q.M;break;case"[s]":case"[ss]":de=((q.D*24+q.H)*60+q.M)*60+Math.round(q.S+q.u);break;default:throw"bad abstime format: "+P}le=P.length===3?1:2;break;case 101:de=re,le=1;break}var se=le>0?a(de,le):"";return se}function ce(L){var P=3;if(L.length<=P)return L;for(var q=L.length%P,Y=L.substr(0,q);q!=L.length;q+=P)Y+=(Y.length>0?",":"")+L.substr(q,P);return Y}var he=function(){var P=/%/g;function q(me,$,K){var De=$.replace(P,""),X=$.length-De.length;return he(me,De,K*Math.pow(10,2*X))+u("%",X)}function Y(me,$,K){for(var De=$.length-1;$.charCodeAt(De-1)===44;)--De;return he(me,$.substr(0,De),K/Math.pow(10,3*($.length-De)))}function j(me,$){var K,De=me.indexOf("E")-me.indexOf(".")-1;if(me.match(/^#+0.0E\+0$/)){if($==0)return"0.0E+0";if($<0)return"-"+j(me,-$);var X=me.indexOf(".");X===-1&&(X=me.indexOf("E"));var pe=Math.floor(Math.log($)*Math.LOG10E)%X;if(pe<0&&(pe+=X),K=($/Math.pow(10,pe)).toPrecision(De+1+(X+pe)%X),K.indexOf("e")===-1){var Fe=Math.floor(Math.log($)*Math.LOG10E);for(K.indexOf(".")===-1?K=K.charAt(0)+"."+K.substr(1)+"E+"+(Fe-K.length+pe):K+="E+"+(Fe-pe);K.substr(0,2)==="0.";)K=K.charAt(0)+K.substr(2,X)+"."+K.substr(2+X),K=K.replace(/^0+([1-9])/,"$1").replace(/^0+\./,"0.");K=K.replace(/\+-/,"-")}K=K.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function(He,ft,Dt,xt){return ft+Dt+xt.substr(0,(X+pe)%X)+"."+xt.substr(pe)+"E"})}else K=$.toExponential(De);return me.match(/E\+00$/)&&K.match(/e[+-]\d$/)&&(K=K.substr(0,K.length-1)+"0"+K.charAt(K.length-1)),me.match(/E\-/)&&K.match(/e\+/)&&(K=K.replace(/e\+/,"e")),K.replace("e","E")}var W=/# (\?+)( ?)\/( ?)(\d+)/;function z(me,$,K){var De=parseInt(me[4],10),X=Math.round($*De),pe=Math.floor(X/De),Fe=X-pe*De,He=De;return K+(pe===0?"":""+pe)+" "+(Fe===0?u(" ",me[1].length+1+me[4].length):l(Fe,me[1].length)+me[2]+"/"+me[3]+a(He,me[4].length))}function re(me,$,K){return K+($===0?"":""+$)+u(" ",me[1].length+2+me[4].length)}var de=/^#*0*\.([0#]+)/,le=/\).*[0#]/,se=/\(###\) ###\\?-####/;function xe(me){for(var $="",K,De=0;De!=me.length;++De)switch(K=me.charCodeAt(De)){case 35:break;case 63:$+=" ";break;case 48:$+="0";break;default:$+=String.fromCharCode(K)}return $}function we(me,$){var K=Math.pow(10,$);return""+Math.round(me*K)/K}function Ye(me,$){var K=me-Math.floor(me),De=Math.pow(10,$);return $<(""+Math.round(K*De)).length?0:Math.round(K*De)}function Ue(me,$){return $<(""+Math.round((me-Math.floor(me))*Math.pow(10,$))).length?1:0}function te(me){return me<2147483647&&me>-2147483648?""+(me>=0?me|0:me-1|0):""+Math.floor(me)}function ue(me,$,K){if(me.charCodeAt(0)===40&&!$.match(le)){var De=$.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");return K>=0?ue("n",De,K):"("+ue("n",De,-K)+")"}if($.charCodeAt($.length-1)===44)return Y(me,$,K);if($.indexOf("%")!==-1)return q(me,$,K);if($.indexOf("E")!==-1)return j($,K);if($.charCodeAt(0)===36)return"$"+ue(me,$.substr($.charAt(1)==" "?2:1),K);var X,pe,Fe,He,ft=Math.abs(K),Dt=K<0?"-":"";if($.match(/^00+$/))return Dt+p(ft,$.length);if($.match(/^[#?]+$/))return X=p(K,0),X==="0"&&(X=""),X.length>$.length?X:xe($.substr(0,$.length-X.length))+X;if(pe=$.match(W))return z(pe,ft,Dt);if($.match(/^#+0+$/))return Dt+p(ft,$.length-$.indexOf("0"));if(pe=$.match(de))return X=we(K,pe[1].length).replace(/^([^\.]+)$/,"$1."+xe(pe[1])).replace(/\.$/,"."+xe(pe[1])).replace(/\.(\d*)$/,function(Ys,m_){return"."+m_+u("0",xe(pe[1]).length-m_.length)}),$.indexOf("0.")!==-1?X:X.replace(/^0\./,".");if($=$.replace(/^#+([0.])/,"$1"),pe=$.match(/^(0*)\.(#*)$/))return Dt+we(ft,pe[2].length).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,pe[1].length?"0.":".");if(pe=$.match(/^#{1,3},##0(\.?)$/))return Dt+ce(p(ft,0));if(pe=$.match(/^#,##0\.([#0]*0)$/))return K<0?"-"+ue(me,$,-K):ce(""+(Math.floor(K)+Ue(K,pe[1].length)))+"."+a(Ye(K,pe[1].length),pe[1].length);if(pe=$.match(/^#,#*,#0/))return ue(me,$.replace(/^#,#*,/,""),K);if(pe=$.match(/^([0#]+)(\\?-([0#]+))+$/))return X=o(ue(me,$.replace(/[\\-]/g,""),K)),Fe=0,o(o($.replace(/\\/g,"")).replace(/[0#]/g,function(Ys){return Fe<X.length?X.charAt(Fe++):Ys==="0"?"0":""}));if($.match(se))return X=ue(me,"##########",K),"("+X.substr(0,3)+") "+X.substr(3,3)+"-"+X.substr(6);var xt="";if(pe=$.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))return Fe=Math.min(pe[4].length,7),He=b(ft,Math.pow(10,Fe)-1,!1),X=""+Dt,xt=he("n",pe[1],He[1]),xt.charAt(xt.length-1)==" "&&(xt=xt.substr(0,xt.length-1)+"0"),X+=xt+pe[2]+"/"+pe[3],xt=c(He[2],Fe),xt.length<pe[4].length&&(xt=xe(pe[4].substr(pe[4].length-xt.length))+xt),X+=xt,X;if(pe=$.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))return Fe=Math.min(Math.max(pe[1].length,pe[4].length),7),He=b(ft,Math.pow(10,Fe)-1,!0),Dt+(He[0]||(He[1]?"":"0"))+" "+(He[1]?l(He[1],Fe)+pe[2]+"/"+pe[3]+c(He[2],Fe):u(" ",2*Fe+1+pe[2].length+pe[3].length));if(pe=$.match(/^[#0?]+$/))return X=p(K,0),$.length<=X.length?X:xe($.substr(0,$.length-X.length))+X;if(pe=$.match(/^([#0?]+)\.([#0]+)$/)){X=""+K.toFixed(Math.min(pe[2].length,10)).replace(/([^0])0+$/,"$1"),Fe=X.indexOf(".");var Fr=$.indexOf(".")-Fe,Ef=$.length-X.length-Fr;return xe($.substr(0,Fr)+X+$.substr($.length-Ef))}if(pe=$.match(/^00,000\.([#0]*0)$/))return Fe=Ye(K,pe[1].length),K<0?"-"+ue(me,$,-K):ce(te(K)).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function(Ys){return"00,"+(Ys.length<3?a(0,3-Ys.length):"")+Ys})+"."+a(Fe,pe[1].length);switch($){case"###,##0.00":return ue(me,"#,##0.00",K);case"###,###":case"##,###":case"#,###":var p_=ce(p(ft,0));return p_!=="0"?Dt+p_:"";case"###,###.00":return ue(me,"###,##0.00",K).replace(/^0\./,".");case"#,###.00":return ue(me,"#,##0.00",K).replace(/^0\./,".")}throw new Error("unsupported format |"+$+"|")}function Te(me,$,K){for(var De=$.length-1;$.charCodeAt(De-1)===44;)--De;return he(me,$.substr(0,De),K/Math.pow(10,3*($.length-De)))}function Be(me,$,K){var De=$.replace(P,""),X=$.length-De.length;return he(me,De,K*Math.pow(10,2*X))+u("%",X)}function Ie(me,$){var K,De=me.indexOf("E")-me.indexOf(".")-1;if(me.match(/^#+0.0E\+0$/)){if($==0)return"0.0E+0";if($<0)return"-"+Ie(me,-$);var X=me.indexOf(".");X===-1&&(X=me.indexOf("E"));var pe=Math.floor(Math.log($)*Math.LOG10E)%X;if(pe<0&&(pe+=X),K=($/Math.pow(10,pe)).toPrecision(De+1+(X+pe)%X),!K.match(/[Ee]/)){var Fe=Math.floor(Math.log($)*Math.LOG10E);K.indexOf(".")===-1?K=K.charAt(0)+"."+K.substr(1)+"E+"+(Fe-K.length+pe):K+="E+"+(Fe-pe),K=K.replace(/\+-/,"-")}K=K.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function(He,ft,Dt,xt){return ft+Dt+xt.substr(0,(X+pe)%X)+"."+xt.substr(pe)+"E"})}else K=$.toExponential(De);return me.match(/E\+00$/)&&K.match(/e[+-]\d$/)&&(K=K.substr(0,K.length-1)+"0"+K.charAt(K.length-1)),me.match(/E\-/)&&K.match(/e\+/)&&(K=K.replace(/e\+/,"e")),K.replace("e","E")}function Ce(me,$,K){if(me.charCodeAt(0)===40&&!$.match(le)){var De=$.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");return K>=0?Ce("n",De,K):"("+Ce("n",De,-K)+")"}if($.charCodeAt($.length-1)===44)return Te(me,$,K);if($.indexOf("%")!==-1)return Be(me,$,K);if($.indexOf("E")!==-1)return Ie($,K);if($.charCodeAt(0)===36)return"$"+Ce(me,$.substr($.charAt(1)==" "?2:1),K);var X,pe,Fe,He,ft=Math.abs(K),Dt=K<0?"-":"";if($.match(/^00+$/))return Dt+a(ft,$.length);if($.match(/^[#?]+$/))return X=""+K,K===0&&(X=""),X.length>$.length?X:xe($.substr(0,$.length-X.length))+X;if(pe=$.match(W))return re(pe,ft,Dt);if($.match(/^#+0+$/))return Dt+a(ft,$.length-$.indexOf("0"));if(pe=$.match(de))return X=(""+K).replace(/^([^\.]+)$/,"$1."+xe(pe[1])).replace(/\.$/,"."+xe(pe[1])),X=X.replace(/\.(\d*)$/,function(Ys,m_){return"."+m_+u("0",xe(pe[1]).length-m_.length)}),$.indexOf("0.")!==-1?X:X.replace(/^0\./,".");if($=$.replace(/^#+([0.])/,"$1"),pe=$.match(/^(0*)\.(#*)$/))return Dt+(""+ft).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,pe[1].length?"0.":".");if(pe=$.match(/^#{1,3},##0(\.?)$/))return Dt+ce(""+ft);if(pe=$.match(/^#,##0\.([#0]*0)$/))return K<0?"-"+Ce(me,$,-K):ce(""+K)+"."+u("0",pe[1].length);if(pe=$.match(/^#,#*,#0/))return Ce(me,$.replace(/^#,#*,/,""),K);if(pe=$.match(/^([0#]+)(\\?-([0#]+))+$/))return X=o(Ce(me,$.replace(/[\\-]/g,""),K)),Fe=0,o(o($.replace(/\\/g,"")).replace(/[0#]/g,function(Ys){return Fe<X.length?X.charAt(Fe++):Ys==="0"?"0":""}));if($.match(se))return X=Ce(me,"##########",K),"("+X.substr(0,3)+") "+X.substr(3,3)+"-"+X.substr(6);var xt="";if(pe=$.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))return Fe=Math.min(pe[4].length,7),He=b(ft,Math.pow(10,Fe)-1,!1),X=""+Dt,xt=he("n",pe[1],He[1]),xt.charAt(xt.length-1)==" "&&(xt=xt.substr(0,xt.length-1)+"0"),X+=xt+pe[2]+"/"+pe[3],xt=c(He[2],Fe),xt.length<pe[4].length&&(xt=xe(pe[4].substr(pe[4].length-xt.length))+xt),X+=xt,X;if(pe=$.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))return Fe=Math.min(Math.max(pe[1].length,pe[4].length),7),He=b(ft,Math.pow(10,Fe)-1,!0),Dt+(He[0]||(He[1]?"":"0"))+" "+(He[1]?l(He[1],Fe)+pe[2]+"/"+pe[3]+c(He[2],Fe):u(" ",2*Fe+1+pe[2].length+pe[3].length));if(pe=$.match(/^[#0?]+$/))return X=""+K,$.length<=X.length?X:xe($.substr(0,$.length-X.length))+X;if(pe=$.match(/^([#0]+)\.([#0]+)$/)){X=""+K.toFixed(Math.min(pe[2].length,10)).replace(/([^0])0+$/,"$1"),Fe=X.indexOf(".");var Fr=$.indexOf(".")-Fe,Ef=$.length-X.length-Fr;return xe($.substr(0,Fr)+X+$.substr($.length-Ef))}if(pe=$.match(/^00,000\.([#0]*0)$/))return K<0?"-"+Ce(me,$,-K):ce(""+K).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function(Ys){return"00,"+(Ys.length<3?a(0,3-Ys.length):"")+Ys})+"."+a(0,pe[1].length);switch($){case"###,###":case"##,###":case"#,###":var p_=ce(""+ft);return p_!=="0"?Dt+p_:"";default:if($.match(/\.[0#?]*$/))return Ce(me,$.slice(0,$.lastIndexOf(".")),K)+xe($.slice($.lastIndexOf(".")))}throw new Error("unsupported format |"+$+"|")}return function($,K,De){return(De|0)===De?Ce($,K,De):ue($,K,De)}}();function ie(L){for(var P=[],q=!1,Y=0,j=0;Y<L.length;++Y)switch(L.charCodeAt(Y)){case 34:q=!q;break;case 95:case 42:case 92:++Y;break;case 59:P[P.length]=L.substr(j,Y-j),j=Y+1}if(P[P.length]=L.substr(j),q===!0)throw new Error("Format |"+L+"| unterminated string ");return P}s._split=ie;var ee=/\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/;function Z(L){for(var P=0,q="",Y="";P<L.length;)switch(q=L.charAt(P)){case"G":m(L,P)&&(P+=6),P++;break;case'"':for(;L.charCodeAt(++P)!==34&&P<L.length;);++P;break;case"\\":P+=2;break;case"_":P+=2;break;case"@":++P;break;case"B":case"b":if(L.charAt(P+1)==="1"||L.charAt(P+1)==="2")return!0;case"M":case"D":case"Y":case"H":case"S":case"E":case"m":case"d":case"y":case"h":case"s":case"e":case"g":return!0;case"A":case"a":case"上":if(L.substr(P,3).toUpperCase()==="A/P"||L.substr(P,5).toUpperCase()==="AM/PM"||L.substr(P,5).toUpperCase()==="上午/下午")return!0;++P;break;case"[":for(Y=q;L.charAt(P++)!=="]"&&P<L.length;)Y+=L.charAt(P);if(Y.match(ee))return!0;break;case".":case"0":case"#":for(;P<L.length&&("0#?.,E+-%".indexOf(q=L.charAt(++P))>-1||q=="\\"&&L.charAt(P+1)=="-"&&"0#".indexOf(L.charAt(P+2))>-1););break;case"?":for(;L.charAt(++P)===q;);break;case"*":++P,(L.charAt(P)==" "||L.charAt(P)=="*")&&++P;break;case"(":case")":++P;break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":for(;P<L.length&&"0123456789".indexOf(L.charAt(++P))>-1;);break;case" ":++P;break;default:++P;break}return!1}s.is_date=Z;function fe(L,P,q,Y){for(var j=[],W="",z=0,re="",de="t",le,se,xe,we="H";z<L.length;)switch(re=L.charAt(z)){case"G":if(!m(L,z))throw new Error("unrecognized character "+re+" in "+L);j[j.length]={t:"G",v:"General"},z+=7;break;case'"':for(W="";(xe=L.charCodeAt(++z))!==34&&z<L.length;)W+=String.fromCharCode(xe);j[j.length]={t:"t",v:W},++z;break;case"\\":var Ye=L.charAt(++z),Ue=Ye==="("||Ye===")"?Ye:"t";j[j.length]={t:Ue,v:Ye},++z;break;case"_":j[j.length]={t:"t",v:" "},z+=2;break;case"@":j[j.length]={t:"T",v:P},++z;break;case"B":case"b":if(L.charAt(z+1)==="1"||L.charAt(z+1)==="2"){if(le==null&&(le=C(P,q,L.charAt(z+1)==="2"),le==null))return"";j[j.length]={t:"X",v:L.substr(z,2)},de=re,z+=2;break}case"M":case"D":case"Y":case"H":case"S":case"E":re=re.toLowerCase();case"m":case"d":case"y":case"h":case"s":case"e":case"g":if(P<0||le==null&&(le=C(P,q),le==null))return"";for(W=re;++z<L.length&&L.charAt(z).toLowerCase()===re;)W+=re;re==="m"&&de.toLowerCase()==="h"&&(re="M"),re==="h"&&(re=we),j[j.length]={t:re,v:W},de=re;break;case"A":case"a":case"上":var te={t:re,v:re};if(le==null&&(le=C(P,q)),L.substr(z,3).toUpperCase()==="A/P"?(le!=null&&(te.v=le.H>=12?"P":"A"),te.t="T",we="h",z+=3):L.substr(z,5).toUpperCase()==="AM/PM"?(le!=null&&(te.v=le.H>=12?"PM":"AM"),te.t="T",z+=5,we="h"):L.substr(z,5).toUpperCase()==="上午/下午"?(le!=null&&(te.v=le.H>=12?"下午":"上午"),te.t="T",z+=5,we="h"):(te.t="t",++z),le==null&&te.t==="T")return"";j[j.length]=te,de=re;break;case"[":for(W=re;L.charAt(z++)!=="]"&&z<L.length;)W+=L.charAt(z);if(W.slice(-1)!=="]")throw'unterminated "[" block: |'+W+"|";if(W.match(ee)){if(le==null&&(le=C(P,q),le==null))return"";j[j.length]={t:"Z",v:W.toLowerCase()},de=W.charAt(1)}else W.indexOf("$")>-1&&(W=(W.match(/\$([^-\[\]]*)/)||[])[1]||"$",Z(L)||(j[j.length]={t:"t",v:W}));break;case".":if(le!=null){for(W=re;++z<L.length&&(re=L.charAt(z))==="0";)W+=re;j[j.length]={t:"s",v:W};break}case"0":case"#":for(W=re;++z<L.length&&"0#?.,E+-%".indexOf(re=L.charAt(z))>-1;)W+=re;j[j.length]={t:"n",v:W};break;case"?":for(W=re;L.charAt(++z)===re;)W+=re;j[j.length]={t:re,v:W},de=re;break;case"*":++z,(L.charAt(z)==" "||L.charAt(z)=="*")&&++z;break;case"(":case")":j[j.length]={t:Y===1?"t":re,v:re},++z;break;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":for(W=re;z<L.length&&"0123456789".indexOf(L.charAt(++z))>-1;)W+=L.charAt(z);j[j.length]={t:"D",v:W};break;case" ":j[j.length]={t:re,v:re},++z;break;case"$":j[j.length]={t:"t",v:"$"},++z;break;default:if(",$-+/():!^&'~{}<>=€acfijklopqrtuvwxzP".indexOf(re)===-1)throw new Error("unrecognized character "+re+" in "+L);j[j.length]={t:"t",v:re},++z;break}var ue=0,Te=0,Be;for(z=j.length-1,de="t";z>=0;--z)switch(j[z].t){case"h":case"H":j[z].t=we,de="h",ue<1&&(ue=1);break;case"s":(Be=j[z].v.match(/\.0+$/))&&(Te=Math.max(Te,Be[0].length-1)),ue<3&&(ue=3);case"d":case"y":case"M":case"e":de=j[z].t;break;case"m":de==="s"&&(j[z].t="M",ue<2&&(ue=2));break;case"X":break;case"Z":ue<1&&j[z].v.match(/[Hh]/)&&(ue=1),ue<2&&j[z].v.match(/[Mm]/)&&(ue=2),ue<3&&j[z].v.match(/[Ss]/)&&(ue=3)}switch(ue){case 0:break;case 1:le.u>=.5&&(le.u=0,++le.S),le.S>=60&&(le.S=0,++le.M),le.M>=60&&(le.M=0,++le.H);break;case 2:le.u>=.5&&(le.u=0,++le.S),le.S>=60&&(le.S=0,++le.M);break}var Ie="",Ce;for(z=0;z<j.length;++z)switch(j[z].t){case"t":case"T":case" ":case"D":break;case"X":j[z].v="",j[z].t=";";break;case"d":case"m":case"y":case"h":case"H":case"M":case"s":case"e":case"b":case"Z":j[z].v=J(j[z].t.charCodeAt(0),j[z].v,le,Te),j[z].t="t";break;case"n":case"?":for(Ce=z+1;j[Ce]!=null&&((re=j[Ce].t)==="?"||re==="D"||(re===" "||re==="t")&&j[Ce+1]!=null&&(j[Ce+1].t==="?"||j[Ce+1].t==="t"&&j[Ce+1].v==="/")||j[z].t==="("&&(re===" "||re==="n"||re===")")||re==="t"&&(j[Ce].v==="/"||j[Ce].v===" "&&j[Ce+1]!=null&&j[Ce+1].t=="?"));)j[z].v+=j[Ce].v,j[Ce]={v:"",t:";"},++Ce;Ie+=j[z].v,z=Ce-1;break;case"G":j[z].t="t",j[z].v=G(P,q);break}var me="",$,K;if(Ie.length>0){Ie.charCodeAt(0)==40?($=P<0&&Ie.charCodeAt(0)===45?-P:P,K=he("n",Ie,$)):($=P<0&&Y>1?-P:P,K=he("n",Ie,$),$<0&&j[0]&&j[0].t=="t"&&(K=K.substr(1),j[0].v="-"+j[0].v)),Ce=K.length-1;var De=j.length;for(z=0;z<j.length;++z)if(j[z]!=null&&j[z].t!="t"&&j[z].v.indexOf(".")>-1){De=z;break}var X=j.length;if(De===j.length&&K.indexOf("E")===-1){for(z=j.length-1;z>=0;--z)j[z]==null||"n?".indexOf(j[z].t)===-1||(Ce>=j[z].v.length-1?(Ce-=j[z].v.length,j[z].v=K.substr(Ce+1,j[z].v.length)):Ce<0?j[z].v="":(j[z].v=K.substr(0,Ce+1),Ce=-1),j[z].t="t",X=z);Ce>=0&&X<j.length&&(j[X].v=K.substr(0,Ce+1)+j[X].v)}else if(De!==j.length&&K.indexOf("E")===-1){for(Ce=K.indexOf(".")-1,z=De;z>=0;--z)if(!(j[z]==null||"n?".indexOf(j[z].t)===-1)){for(se=j[z].v.indexOf(".")>-1&&z===De?j[z].v.indexOf(".")-1:j[z].v.length-1,me=j[z].v.substr(se+1);se>=0;--se)Ce>=0&&(j[z].v.charAt(se)==="0"||j[z].v.charAt(se)==="#")&&(me=K.charAt(Ce--)+me);j[z].v=me,j[z].t="t",X=z}for(Ce>=0&&X<j.length&&(j[X].v=K.substr(0,Ce+1)+j[X].v),Ce=K.indexOf(".")+1,z=De;z<j.length;++z)if(!(j[z]==null||"n?(".indexOf(j[z].t)===-1&&z!==De)){for(se=j[z].v.indexOf(".")>-1&&z===De?j[z].v.indexOf(".")+1:0,me=j[z].v.substr(0,se);se<j[z].v.length;++se)Ce<K.length&&(me+=K.charAt(Ce++));j[z].v=me,j[z].t="t",X=z}}}for(z=0;z<j.length;++z)j[z]!=null&&"n?".indexOf(j[z].t)>-1&&($=Y>1&&P<0&&z>0&&j[z-1].v==="-"?-P:P,j[z].v=he(j[z].t,j[z].v,$),j[z].t="t");var pe="";for(z=0;z!==j.length;++z)j[z]!=null&&(pe+=j[z].v);return pe}s._eval=fe;var N=/\[[=<>]/,w=/\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/;function F(L,P){if(P==null)return!1;var q=parseFloat(P[2]);switch(P[1]){case"=":if(L==q)return!0;break;case">":if(L>q)return!0;break;case"<":if(L<q)return!0;break;case"<>":if(L!=q)return!0;break;case">=":if(L>=q)return!0;break;case"<=":if(L<=q)return!0;break}return!1}function U(L,P){var q=ie(L),Y=q.length,j=q[Y-1].indexOf("@");if(Y<4&&j>-1&&--Y,q.length>4)throw new Error("cannot find right format for |"+q.join("|")+"|");if(typeof P!="number")return[4,q.length===4||j>-1?q[q.length-1]:"@"];switch(q.length){case 1:q=j>-1?["General","General","General",q[0]]:[q[0],q[0],q[0],"@"];break;case 2:q=j>-1?[q[0],q[0],q[0],q[1]]:[q[0],q[1],q[0],"@"];break;case 3:q=j>-1?[q[0],q[1],q[0],q[2]]:[q[0],q[1],q[2],"@"];break}var W=P>0?q[0]:P<0?q[1]:q[2];if(q[0].indexOf("[")===-1&&q[1].indexOf("[")===-1)return[Y,W];if(q[0].match(N)!=null||q[1].match(N)!=null){var z=q[0].match(w),re=q[1].match(w);return F(P,z)?[Y,q[0]]:F(P,re)?[Y,q[1]]:[Y,q[z!=null&&re!=null?2:1]]}return[Y,W]}function V(L,P,q){q==null&&(q={});var Y="";switch(typeof L){case"string":L=="m/d/yy"&&q.dateNF?Y=q.dateNF:Y=L;break;case"number":L==14&&q.dateNF?Y=q.dateNF:Y=(q.table!=null?q.table:_)[L],Y==null&&(Y=q.table&&q.table[v[L]]||_[v[L]]),Y==null&&(Y=S[L]||"General");break}if(m(Y,0))return G(P,q);P instanceof Date&&(P=D(P,q.date1904));var j=U(Y,P);if(m(j[1]))return G(P,q);if(P===!0)P="TRUE";else if(P===!1)P="FALSE";else if(P===""||P==null)return"";return fe(j[1],P,q,j[0])}function Q(L,P){if(typeof P!="number"){P=+P||-1;for(var q=0;q<392;++q){if(_[q]==null){P<0&&(P=q);continue}if(_[q]==L){P=q;break}}P<0&&(P=391)}return _[P]=L,P}s.load=Q,s._table=_,s.get_table=function(){return _},s.load_table=function(P){for(var q=0;q!=392;++q)P[q]!==void 0&&Q(P[q],q)},s.init_table=E,s.format=V};r(e),typeof DO_NOT_EXPORT_SSF>"u"&&(t.exports=e)})(oz);var nA=oz.exports;function J3e(t){const e=[];for(const a of t.schema.fields)a.kind==="dimension"&&e.push(a);const i=K6(t.annotations,"#(malloy) ").text("query_name")??"root",s=new uz({name:i,type:{kind:"array_type",element_type:{kind:"record_type",fields:e}},annotations:t.annotations},{modelTag:K6(t.model_annotations,"## "),queryTimezone:t.query_timezone}),o=t.data.kind==="record_cell"?{kind:"array_cell",array_value:[t.data]}:t.data;return new cye(o,s)}function X3e(t){return t.type.kind==="array_type"}function Z3e(t){return t.type.kind==="array_type"&&t.type.element_type.kind==="record_type"}function eye(t){return t.type.kind==="record_type"}function tye(t){return t.type.kind==="number_type"}function nye(t){return t.type.kind==="date_type"}function rye(t){return t.type.kind==="json_type"}function iye(t){return t.type.kind==="string_type"}function sye(t){return t.type.kind==="timestamp_type"}function oye(t){return t.type.kind==="boolean_type"}function uye(t){return t.type.kind==="sql_native_type"}const _l={from(t,e){if(Z3e(t))return new wh(t,e);if(X3e(t))return new Oh(t,e);if(eye(t))return new hg(t,e);if(oye(t))return new lA(t,e);if(rye(t))return new aA(t,e);if(nye(t))return new iA(t,e);if(sye(t))return new sA(t,e);if(iye(t))return new oA(t,e);if(tye(t))return new rA(t,e);if(uye(t))return new uA(t,e);throw new Error(`Unknown field type ${t.type.kind}`)},isNestField(t){return t instanceof wh||t instanceof Oh||t instanceof hg},pathFromString(t){return JSON.parse(t)},pathToString(t){return JSON.stringify(t)}};function U6(t,e="# "){return K6(t.annotations,e)}const aye=["link","image","cell","list","list_detail","bar_chart","line_chart","dashboard","scatter_chart","shape_map","segment_map"];function lye(t,e,r){const i=U6(t),s=Object.keys(i.properties??{}).reverse();for(const u of s)if(aye.includes(u))return["list","list_detail"].includes(u)?"list":["bar_chart","line_chart"].includes(u)?"chart":u;return t.type.kind==="record_type"&&(e==null?void 0:e.renderAs)==="chart"?"none":t.type.kind==="array_type"||t.type.kind==="record_type"?"table":"cell"}class vl{constructor(e,r){this.field=e,this.parent=r,this.valueSet=new Set,this.tag=U6(this.field),this.metadataTag=U6(this.field,"#(malloy) "),this.path=r?r.isArray()?[...r.path]:[...r.path,e.name]:[],this.renderAs=lye(e,r)}isRoot(){return this.path.length===0}root(){if(this.parent)return this.parent.root();if(this instanceof uz)return this;throw new Error("Root field was not an instance of RootField")}get sourceName(){return this.metadataTag.text("source_name")??"__source__"}get name(){return this.field.name}fieldAt(e){return typeof e=="string"?this.fieldAtPath(_l.pathFromString(e)):this.fieldAtPath(e)}getParentRecord(e){let r=this.asField();for(;r&&e>0;){for(r=r.parent;r!=null&&r.isArray();)r=r.parent;e--}if(!(r!=null&&r.isRecord()))throw new Error(`Parent ${e} levels up was not a record`);return r}get key(){return _l.pathToString(this.path)}fieldAtPath(e){if(e.length===0)return this.asField();throw new Error(`${this.constructor.name} cannot contain fields`)}registerNullValue(){this.valueSet.add(Fh)}get drillFilters(){return this.metadataTag.textArray("drill_filters")??[]}get referenceId(){return this.metadataTag.text("reference_id")}escapeIdentifier(e){return e.replace(/\\/g,"\\\\").replace("`","\\`")}identifierCode(){return this.name.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?this.name:`\`${this.escapeIdentifier(this.name)}\``}drillExpression(){return this.metadataTag.text("drill_expression")??this.identifierCode()}wasDimension(){return!this.wasCalculation()}wasCalculation(){return this.metadataTag.has("calculation")}isHidden(){return this.tag.has("hidden")}get minNumber(){}get maxNumber(){}get maxString(){}asField(){if(this instanceof Oh||this instanceof wh||this instanceof hg||this instanceof rA||this instanceof iA||this instanceof aA||this instanceof oA||this instanceof sA||this instanceof lA||this instanceof uA)return this;throw new Error("Not a field")}isArray(){return this instanceof Oh}isRepeatedRecord(){return this instanceof wh}isRecord(){return this instanceof hg}isNumber(){return this instanceof rA}isBoolean(){return this instanceof lA}isString(){return this instanceof oA}isRecordOrRepeatedRecord(){return this.isRecord()||this.isRepeatedRecord()}isDate(){return this instanceof iA}isTimestamp(){return this instanceof sA}isTime(){return this.isDate()||this.isTimestamp()}isSQLNative(){return this instanceof uA}isJSON(){return this instanceof aA}isBasic(){return!this.isNest()}isNest(){return this.isArray()||this.isRecord()||this.isRepeatedRecord()}getLocationInParent(){var e;return((e=this.parent)==null?void 0:e.fields.findIndex(r=>r===this))??-1}isLastChild(){const e=this.parent;return e===void 0||this.getLocationInParent()===e.fields.length}isFirstChild(){return this.getLocationInParent()===0}pathTo(e){const r=this.path,i=e.path,s=r.length;let o=0;for(;r[o];){if(r[o]!==i[o])throw new Error("Tried to get path from parent field to child field, but parent field is not a parent of child field.");o++}return _l.pathToString(i.slice(s))}}class Oh extends vl{constructor(e,r){super(e,r),this.field=e,this.maxUniqueFieldValueCounts=new Map,this.eachField=_l.from({name:"each",type:this.field.type.element_type},this),this.fields=[this.eachField]}}class wh extends Oh{constructor(e,r){super(e,r),this.field=e,this.maxRecordCount=0,this._fieldsWithOrder=void 0;const i=this.eachField;if(!i.isRecord())throw new Error("Expected eachField of repeatedRecord to be a record");this.fields=i.fields}fieldAtPath(e){return e.length===0?this.asField():this.eachField.fieldAtPath(e)}registerRecordCount(e){this.maxRecordCount=Math.max(e,this.maxRecordCount)}registerValueSetSize(e,r){this.maxUniqueFieldValueCounts.set(e,Math.max(this.maxUniqueFieldValueCounts.get(e)??0,r))}get fieldsWithOrder(){var e;if(!this._fieldsWithOrder){const r=this.metadataTag.tag("ordered_by"),i=(r&&((e=r.array())==null?void 0:e.map(o=>{const u=Object.keys(o.properties??{})[0],a=o.text(u);return{field:this.fieldAt(u),dir:a}})))??[],s=new Set(i.map(o=>o.field.name));this._fieldsWithOrder=[...i,...this.fields.filter(o=>!s.has(o.name)).map(o=>({field:o,dir:"asc"}))]}return this._fieldsWithOrder}}class uz extends wh{constructor(e,r){super(e,void 0),this.field=e,this.modelTag=r.modelTag,this.queryTimezone=r.queryTimezone}}class hg extends vl{constructor(e,r){super(e,r),this.field=e,this.maxUniqueFieldValueCounts=new Map,this._fieldsWithOrder=void 0,this.fields=e.type.fields.map(i=>_l.from(i,this)),this.fieldsByName=Object.fromEntries(this.fields.map(i=>[i.name,i]))}fieldAtPath(e){if(e.length===0)return this.asField();{const[r,...i]=e,s=this.fieldsByName[r];if(s===void 0)throw new Error(`No such field ${r} in ${this.path}`);return s.fieldAtPath(i)}}get fieldsWithOrder(){return this._fieldsWithOrder===void 0&&(this._fieldsWithOrder=[...this.fields.map(e=>({field:e,dir:"asc"}))]),this._fieldsWithOrder}}let rA=class extends vl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}registerValue(e){this.valueSet.add(e),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const r=e.toString();(this._maxString===void 0||r.length>this._maxString.length)&&(this._maxString=r)}fieldAtPath(e){if(e.length===0)return this.asField();throw new Error("NumberField cannot contain fields")}get minNumber(){return this.min}get maxNumber(){return this.max}get maxString(){return this._maxString}},iA=class extends vl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}get timeframe(){return this.field.type.timeframe}registerValue(e){const r=Number(e);this.valueSet.add(r),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const i=Al(e,!0,this.timeframe).toString();(this._maxString===void 0||i.length>this._maxString.length)&&(this._maxString=i)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}get minNumber(){return this.min!==void 0?Number(this.min):void 0}get maxNumber(){return this.max!==void 0?Number(this.max):void 0}},sA=class extends vl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}get timeframe(){return this.field.type.timeframe}registerValue(e){const r=Number(e);this.valueSet.add(r),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e);const i=Al(e,!1,this.timeframe).toString();(this._maxString===void 0||i.length>this._maxString.length)&&(this._maxString=i)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}},oA=class extends vl{constructor(e,r){super(e,r),this.field=e,this.min=void 0,this.max=void 0,this._maxString=void 0}registerValue(e){this.valueSet.add(e),(this.max===void 0||e>this.max)&&(this.max=e),(this.min===void 0||e<this.min)&&(this.min=e),(this._maxString===void 0||e.length>this._maxString.length)&&(this._maxString=e)}get minValue(){return this.min}get maxValue(){return this.max}get maxString(){return this._maxString}};class uA extends vl{constructor(e,r){super(e,r),this.field=e}}let aA=class extends vl{constructor(e,r){super(e,r),this.field=e}},lA=class extends vl{constructor(e,r){super(e,r),this.field=e,this._maxString=void 0}get maxString(){return this._maxString}registerValue(e){this.valueSet.add(e);const r=String(e);(this._maxString===void 0||this._maxString.length<r.length)&&(this._maxString=r)}};const az={from(t,e,r){switch(t.kind){case"array_cell":{if(e instanceof wh)return new fA(t,e,r);if(e instanceof Oh)return new cA(t,e,r);throw new Error("Expected record data to be associated with record field")}case"record_cell":{if(e instanceof hg)return new q6(t,e,r);throw new Error("Expected record data to be associated with record field")}case"null_cell":return new H6(t,e,r);case"number_cell":{if(e instanceof rA)return new z6(t,e,r);throw new Error("Expected number data to be associated with number field")}case"date_cell":{if(e instanceof iA)return new Q6(t,e,r);throw new Error("Expected date data to be associated with date field")}case"json_cell":{if(e instanceof aA)return new W6(t,e,r);throw new Error("Expected JSON data to be associated with JSON field")}case"string_cell":{if(e instanceof oA)return new V6(t,e,r);throw new Error("Expected string data to be associated with string field")}case"timestamp_cell":{if(e instanceof sA)return new G6(t,e,r);throw new Error("Expected timestamp data to be associated with timestamp field")}case"boolean_cell":{if(e instanceof lA)return new Y6(t,e,r);throw new Error("Expected boolean data to be associated with boolean field")}case"sql_native_cell":{if(e instanceof uA)return new lz(t,e,r);throw new Error("Expected sql_native data to be associated with sql_native field")}}}};class Wu{constructor(e,r,i){this.cell=e,this.field=r,this.parent=i}isNull(){return this instanceof H6}isArray(){return this instanceof cA}isRecord(){return this instanceof q6}isRepeatedRecord(){return this instanceof fA}isRecordOrRepeatedRecord(){return this.isRepeatedRecord()||this.isRecord()}isNest(){return this.isRepeatedRecord()||this.isRecord()||this.isArray()}isNumber(){return this instanceof z6}isDate(){return this instanceof Q6}isTime(){return this.isDate()||this.isTimestamp()}isJSON(){return this instanceof W6}isString(){return this instanceof V6}isTimestamp(){return this instanceof G6}isBoolean(){return this instanceof Y6}asCell(){if(this instanceof cA||this instanceof fA||this instanceof q6||this instanceof z6||this instanceof Q6||this instanceof W6||this instanceof V6||this instanceof G6||this instanceof Y6||this instanceof H6||this instanceof lz)return this;throw new Error("Not a cell")}root(){return this.parent?this.parent.root():this.asCell()}getPathInfo(e){const r=e.split("/"),i=r.filter(o=>o==="..").length+1,s=r.filter(o=>o!==".."&&o!=="");return{levelsUp:i,pathSegments:s}}getParentRecord(e){let r=this.asCell();for(;r&&e>0;){for(r=r.parent;r!=null&&r.isArray();)r=r.parent;e--}if(!(r!=null&&r.isRecord()))throw new Error(`Parent ${e} levels up was not a record`);return r}getRelativeCell(e){try{const{levelsUp:r,pathSegments:i}=this.getPathInfo(e);return this.getParentRecord(r).cellAtPath(i)}catch{return}}cellAt(e){return typeof e=="string"?this.cellAtPath(_l.pathFromString(e)):this.cellAtPath(e)}cellAtPath(e){if(e.length===0)return this.asCell();throw new Error(`${this.constructor.name} cannot contain columns`)}compareTo(e){return 0}getDrillValues(){let e=this.asCell();const r=[];for(;e&&(e&&e.isArray()&&(r.unshift(...e.field.drillFilters.map(i=>({where:i}))),e=e.parent),e!==void 0);){if(e&&e.isRecord()){const i=e,s=e.field.fields.filter(o=>o.isBasic()&&o.wasDimension());r.unshift(...s.map(o=>({field:o,value:i.column(o.name)})))}e=e.parent}return r}getDrillExpressions(){return this.getDrillValues().map(r=>{if("where"in r)return r.where;const i=pye(r.value);return`${r.field.drillExpression()} = ${i}`})}getDrillEntries(){const e=this.getDrillValues(),r=[];for(const i of e)"where"in i?r.push(i):(i.value.isNull()||i.value.isTime()||i.value.isString()||i.value.isNumber()||i.value.isBoolean())&&r.push({field:i.field,value:i.value.value});return r}getDrillQuery(){const e=this.getDrillExpressions();let r=`run: ${this.field.root().sourceName} ->`;return e.length>0&&(r+=` {
653
653
  where:
654
654
  ${e.map(i=>` ${i}`).join(`,
655
655
  `)}
@@ -1861,7 +1861,7 @@ yzz{{||}}~~Ӂ
1861
1861
  | ${c}`,a>0&&(s=s+`
1862
1862
  | ${" ".repeat(a)}^`)}else s=`line ${u+1}: char ${a}: ${i.message}`}r!==o&&(s=`FILE: ${o}
1863
1863
  `+s,r=o),e!==""?e=`${e}
1864
- ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,dpt.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,_P.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,_P.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Wc.MalloyTranslation=vP;class bde extends vP{constructor(e,r){super(e),this.root=r}}Wc.MalloyChildTranslator=bde;class Ipt extends vP{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new EP.Zone,this.importZone=new EP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new EP.Zone,this.root=this,this.logger=new Cde.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,Cde.makeLogMessage)(e,r,{severity:"error",...i})),e}}Wc.MalloyTranslator=Ipt;function Tde(t){return[...Object.keys(t),...Object.keys(t).map(e=>Tde(t[e])).flat()]}var c1={};Object.defineProperty(c1,"__esModule",{value:!0}),c1.exploreQueryWalkerBuilder=c1.ExploreQueryWalker=void 0;const $pt=R0;class Rde{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}c1.ExploreQueryWalker=Rde;function Bpt(t,e){const r=new Rde(t),i=r;return $pt.ParseTreeWalker.DEFAULT.walk(i,e),r}c1.exploreQueryWalkerBuilder=Bpt;var f1={},o_={},Ya={};Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.getResultStructMetadataAnnotation=Ya.convertFieldInfos=Ya.modelDefToModelInfo=void 0;const Ka=Gi,AP=Us,SP=hi,Dde=ko;function kpt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ka.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,Ka.isAtomic)(a)?{name:u,type:FD(a),default_value:Ode(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:Ode(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:x1(i,i.fields)},parameters:s,annotations:CP(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,AP.getResultStructDefForQuery)(t,i),o=CP(i),u=s.resultMetadata?wD(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:x1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,AP.getResultStructDefForQuery)(t,r),s=CP(r),o=i.resultMetadata?wD(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:x1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ya.modelDefToModelInfo=kpt;function Ode(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 CP(t){return(0,SP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function x1(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,SP.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,Ka.isTurtle)(u)){const x=(0,AP.getResultStructDefForView)(t,u),d=x.resultMetadata?wD(x,x.resultMetadata):void 0,p=[...f??[],...d?[d]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:x1(x,x.fields)}};o.push(m)}else if((0,Ka.isAtomic)(u)){const x=(0,Ka.expressionIsAggregate)(u.expressionType),d=(0,Ka.expressionIsScalar)(u.expressionType);if(!x&&!d||u.type==="error")continue;const p=u.resultMetadata?wde(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:FD(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,Ka.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:x1(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ya.convertFieldInfos=x1;function wde(t,e){const r=Dde.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Ppt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Mpt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Ppt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Mpt(t)}\``}function wD(t,e){var r,i;const s=Dde.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ya.getResultStructMetadataAnnotation=wD;function FD(t){if((0,Ka.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!jpt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Upt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ka.isRepeatedRecord)(t))return{kind:"array_type",element_type:Fde(t)};if(t.type==="record")return Fde(t);if(t.type==="array")return{kind:"array_type",element_type:FD(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Fde(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=wde(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,SP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ka.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:FD(e)};throw new Error("Expected record type to not have a table as its child")})}}function jpt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Upt(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 smt(t){return t}function omt(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=ko,r=hi,i=Ya,s=Ur;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(d){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:d},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(d){const p=`${x.name}:${d}`,m=await x.fetchSchemaForTables({[p]:d},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(d,p)=>{const m=await x.runSQL(d);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,d){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const _=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:_}:{kind:"timestamp_cell",timestamp_value:_}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(_=>p(_,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const _=E.type;if(_.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:_.fields.map(v=>({kind:"dimension",...v}))}})}}}function m(y,E){const _=[];for(const v of E.schema.fields){const A=y[v.name];if(v.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const S=p(A,v);_.push(S)}return{kind:"record_cell",record_value:_}}const g={kind:"join",schema:d,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const d=x._queryResult.structs,p=d[d.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,d){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:d}})}t.mapLogs=f})(o_);var qpt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Hpt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zpt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&qpt(e,t,r);return Hpt(e,t),e};Object.defineProperty(f1,"__esModule",{value:!0}),f1.malloyToQuery=f1.MalloyToQuery=void 0;const Qpt=Gd,Nn=zpt(I),Nde=O2,u_=Mn,Gpt=Ze,Wpt=XE,Lde=Jn,Vpt=o_,bP="Malloy query documents";class Ide extends Qpt.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,Lde.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Nde.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 ${bP}`)}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,`${bP} may only have one run statement`);return i===void 0?(this.illegal(e,`${bP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,u_.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Nn.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Nn.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Nn.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Nn.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Nn.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Nn.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Nn.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Nn.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Nn.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Nn.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Nn.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Nn.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Nn.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,u_.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Nn.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,u_.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Nn.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Nn.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,u_.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,Gpt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,u_.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Nn.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Nn.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Nn.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof Nn.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Nn.ExprFieldPathContext&&i instanceof Nn.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Nn.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}f1.MalloyToQuery=Ide;function Ypt(t){const e=(0,Lde.getSourceInfo)(t),r=new Nde.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Wpt.runMalloyParser)(t,i,e,r),u=new Ide(s,r).visit(s.root),a=(0,Vpt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}f1.malloyToQuery=Ypt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Wc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=c1;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=f1;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Y4);var $e={},ND={};Object.defineProperty(ND,"__esModule",{value:!0}),ND.MALLOY_VERSION=void 0,ND.MALLOY_VERSION="0.0.276",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 $de=Y4,gi=Gi,Bde=Ur,TP=y2,Kpt=ND,Jpt=_2,Pn=hi,Xpt=y0,Zpt=Jn,e2t=JE,kde="internal://internal.malloy";let b0=class sO{static get version(){return Kpt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(kde));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new $de.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new Pde(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return sO._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 jD(r,e).then(({contents:u,invalidationKey:a})=>sO._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var d,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(kde));const _={};if(r===void 0&&x!==void 0){const S=await x.getCachedModelDef(s,e.toString());if(S)return new d1(S.modelDef,[],[e.toString(),...PD(S.modelDef.dependencies)])}f??(f=e);let v;const A=e.toString();if(i!==void 0){v=i._translator;const S=(d=i._invalidationKey)!==null&&d!==void 0?d:await PP(s,e);_[A]=S}else{if(r===void 0){const{contents:S,invalidationKey:b}=await jD(s,e);_[A]=b,r=S}else{const S=await PP(s,e);_[A]=S}v=new $de.MalloyTranslator(A,f.toString(),{urls:{[A]:r}},c)}for(;;){const S=v.translate(u==null?void 0:u._modelDef);if(S.final)if(S.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:S.modelDef,invalidationKeys:_}));for(const b of v.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:_}));return new d1(S.modelDef,S.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=S.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},C=(u==null?void 0:u._modelDef)||b;return new d1(C,S.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=S.fromSources)!==null&&y!==void 0?y:[]])}else{const b=S.problems||[],C=v.prettyErrors();throw new Mde(`Error(s) compiling model:
1864
+ ${s}`:e=s}return e}childRequest(e){var r;const i=decodeURI(new URL(e,this.sourceURL).toString()),s=(r=this.childTranslators.get(i))===null||r===void 0?void 0:r.translate();if(s!=null&&s.compileSQL)return{compileSQL:s.compileSQL}}getChildExports(e){const r={},i=decodeURI(new URL(e,this.sourceURL).toString()),s=this.childTranslators.get(i);if(s&&s.translate().modelDef)for(const u of s.modelDef.exports){const a=s.modelDef.contents[u];((0,dpt.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,_P.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,_P.rangeFromContext)(this.parseStep.sourceInfo,e)}firstReferenceToDialect(e){return this.dialectAlreadyChecked[e]?!1:(this.dialectAlreadyChecked[e]=!0,!0)}experimentalDialectEnabled(e){if(this.allDialectsEnabled)return!0;const r=this.compilerFlags.tag("experimental");return r!==void 0&&(r.bare()||r.has("dialect",e))}}Wc.MalloyTranslation=vP;class bde extends vP{constructor(e,r){super(e),this.root=r}}Wc.MalloyChildTranslator=bde;class Ipt extends vP{constructor(e,r=null,i=null,s=null){super(e,r),this.eventStream=s,this.schemaZone=new EP.Zone,this.importZone=new EP.Zone,this.pretranslatedModels=new Map,this.sqlQueryZone=new EP.Zone,this.root=this,this.logger=new Cde.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,Cde.makeLogMessage)(e,r,{severity:"error",...i})),e}}Wc.MalloyTranslator=Ipt;function Tde(t){return[...Object.keys(t),...Object.keys(t).map(e=>Tde(t[e])).flat()]}var c1={};Object.defineProperty(c1,"__esModule",{value:!0}),c1.exploreQueryWalkerBuilder=c1.ExploreQueryWalker=void 0;const $pt=R0;class Rde{constructor(e){this.inDocument=!1,this.exploreClauseRefs=[],this.tokens=e}exploreQueryAtOffset(e){return this.exploreClauseRefs.find(r=>r.range[0]===void 0||r.range[1]===void 0?!1:r.range[0]<=e&&r.range[1]>=e)}filterAtOffset(e){const r=this.exploreQueryAtOffset(e);if(r)return r.filterRefs.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e)}hasFilterListAtOffset(e){const r=this.exploreQueryAtOffset(e);return r?!!r.filterLists.find(i=>i.range[0]===void 0||i.range[1]===void 0?!1:i.range[0]<=e&&i.range[1]>=e):!1}enterMalloyDocument(){this.inDocument=!0}}c1.ExploreQueryWalker=Rde;function Bpt(t,e){const r=new Rde(t),i=r;return $pt.ParseTreeWalker.DEFAULT.walk(i,e),r}c1.exploreQueryWalkerBuilder=Bpt;var f1={},o_={},Ya={};Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.getResultStructMetadataAnnotation=Ya.convertFieldInfos=Ya.modelDefToModelInfo=void 0;const Ka=Gi,AP=Us,SP=hi,Dde=ko;function kpt(t){const e={entries:[],anonymous_queries:[]};for(const[r,i]of Object.entries(t.contents))if(t.exports.includes(r)){if((0,Ka.isSourceDef)(i)){const s=i.parameters&&Object.entries(i.parameters).length>0?Object.entries(i.parameters).map(([u,a])=>(0,Ka.isAtomic)(a)?{name:u,type:FD(a),default_value:Ode(a.value)}:{name:u,type:{kind:"filter_expression_type"},default_value:Ode(a.value)}):void 0,o={kind:"source",name:r,schema:{fields:x1(i,i.fields)},parameters:s,annotations:CP(i)};e.entries.push(o)}else if(i.type==="query"){const s=(0,AP.getResultStructDefForQuery)(t,i),o=CP(i),u=s.resultMetadata?wD(s,s.resultMetadata):void 0,a=[...o??[],...u?[u]:[]],l={kind:"source",name:r,schema:{fields:x1(s,s.fields)},annotations:a.length>0?a:void 0};e.entries.push(l)}}for(const r of t.queryList){const i=(0,AP.getResultStructDefForQuery)(t,r),s=CP(r),o=i.resultMetadata?wD(i,i.resultMetadata):void 0,u=[...s??[],...o?[o]:[]],a={schema:{fields:x1(i,i.fields)},annotations:u.length>0?u:void 0};e.anonymous_queries.push(a)}return e}Ya.modelDefToModelInfo=kpt;function Ode(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 CP(t){return(0,SP.annotationToTaglines)(t.annotation).map(r=>({value:r}))}function x1(t,e){var r,i,s;const o=[];for(const u of e){if(!(u.accessModifier===void 0))continue;const c=(0,SP.annotationToTaglines)(u.annotation).map(x=>({value:x})),f=c.length>0?c:void 0;if((0,Ka.isTurtle)(u)){const x=(0,AP.getResultStructDefForView)(t,u),d=x.resultMetadata?wD(x,x.resultMetadata):void 0,p=[...f??[],...d?[d]:[]],m={kind:"view",name:(r=u.as)!==null&&r!==void 0?r:u.name,annotations:p.length>0?p:void 0,schema:{fields:x1(x,x.fields)}};o.push(m)}else if((0,Ka.isAtomic)(u)){const x=(0,Ka.expressionIsAggregate)(u.expressionType),d=(0,Ka.expressionIsScalar)(u.expressionType);if(!x&&!d||u.type==="error")continue;const p=u.resultMetadata?wde(u,u.resultMetadata):void 0,m=[...f??[],...p?[p]:[]],g={kind:x?"measure":"dimension",name:(i=u.as)!==null&&i!==void 0?i:u.name,type:FD(u),annotations:m.length>0?m:void 0};o.push(g)}else if((0,Ka.isJoinedSource)(u)){const x={kind:"join",name:(s=u.as)!==null&&s!==void 0?s:u.name,annotations:f,schema:{fields:x1(u,u.fields)},relationship:u.join};o.push(x)}}return o}Ya.convertFieldInfos=x1;function wde(t,e){const r=Dde.Tag.withPrefix("#(malloy) ");let i=!1;if(e.referenceId!==void 0&&(r.set(["reference_id"],e.referenceId),i=!0),e.fieldKind==="measure"&&(r.set(["calculation"]),i=!0),e.filterList){const s=e.filterList.filter(o=>o.expressionType==="scalar").map(o=>o.code);r.set(["drill_filters"],s),i=!0}if(e.fieldKind==="dimension"){const o=(e==null?void 0:e.sourceExpression)||(e!=null&&e.sourceField.includes(".")?e==null?void 0:e.sourceField:Ppt(t.name));r.set(["drill_expression"],o),i=!0}return i?{value:r.toString()}:void 0}function Mpt(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}function Ppt(t){return t.match(/^[A-Za-z_][0-9A-Za-z_]*$/)?t:`\`${Mpt(t)}\``}function wD(t,e){var r,i;const s=Dde.Tag.withPrefix("#(malloy) ");let o=!1;if(e.limit!==void 0&&(s.set(["limit"],e.limit),o=!0),e.filterList){const u=e.filterList.filter(a=>a.expressionType==="scalar").map(a=>a.code);u.length>0&&(s.set(["drill_filters"],u),o=!0)}if(e.orderBy){for(let u=0;u<e.orderBy.length;u++){const a=e.orderBy[u],l=typeof a.field=="number"?(r=t.fields[a.field-1].as)!==null&&r!==void 0?r:t.fields[a.field-1].name:a.field,c=(i=a.dir)!==null&&i!==void 0?i:null;s.set(["ordered_by",u,l],c)}o=!0}return o?{value:s.toString()}:void 0}Ya.getResultStructMetadataAnnotation=wD;function FD(t){if((0,Ka.isBasicAtomic)(t))switch(t.type){case"string":return{kind:"string_type"};case"number":return{kind:"number_type",subtype:t.numberType==="float"?"decimal":t.numberType==="integer"?"integer":void 0};case"boolean":return{kind:"boolean_type"};case"date":{const e=t.timeframe;return e&&!jpt(e)?{kind:"timestamp_type",timeframe:t.timeframe}:{kind:"date_type",timeframe:Upt(t.timeframe)}}case"timestamp":return{kind:"timestamp_type",timeframe:t.timeframe};case"json":return{kind:"json_type"};case"sql native":return{kind:"sql_native_type",sql_type:t.rawType};case"error":throw new Error("Error type is not supported in stable interface")}else{if((0,Ka.isRepeatedRecord)(t))return{kind:"array_type",element_type:Fde(t)};if(t.type==="record")return Fde(t);if(t.type==="array")return{kind:"array_type",element_type:FD(t.elementTypeDef)}}throw new Error("Unexpected field type")}function Fde(t){return{kind:"record_type",fields:t.fields.map(e=>{const r=[];if("resultMetadata"in e&&e.resultMetadata){const i=wde(e,e.resultMetadata);i&&r.push(i)}if(e.annotation){const i=(0,SP.annotationToTaglines)(e.annotation);r.push(...i.map(s=>({value:s})))}if((0,Ka.isAtomic)(e))return{name:e.name,annotations:r.length>0?r:void 0,type:FD(e)};throw new Error("Expected record type to not have a table as its child")})}}function jpt(t){switch(t){case"day":case"week":case"month":case"year":case"quarter":return!0;default:return!1}}function Upt(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 smt(t){return t}function omt(t){return t}(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.mapLogs=t.DEFAULT_LOG_RANGE=t.wrapResult=t.mapData=t.wrapLegacyConnection=t.wrapLegacyInfoConnection=void 0;const e=ko,r=hi,i=Ya,s=Ur;function o(x){return{get dialectName(){return x.dialectName},async fetchSchemaForSQLQuery(d){const p=await x.fetchSchemaForSQLStruct({connection:x.name,selectStr:d},{}),m=p.structDef;if(m===void 0)throw new Error(p.error);return{fields:(0,i.convertFieldInfos)(m,m.fields)}},async fetchSchemaForTable(d){const p=`${x.name}:${d}`,m=await x.fetchSchemaForTables({[p]:d},{}),g=m.schemas[p];if(g===void 0)throw new Error(m.errors[p]);return{fields:(0,i.convertFieldInfos)(g,g.fields)}}}}t.wrapLegacyInfoConnection=o;function u(x){return{...o(x),runSQL:async(d,p)=>{const m=await x.runSQL(d);return l(m.rows,p)}}}t.wrapLegacyConnection=u;function a(x){if(x instanceof Date)return x;if(x.constructor.name==="Date")return new Date(x);if(typeof x=="number")return new Date(x);if(typeof x!="string")return new Date(x.value);{let p=s.DateTime.fromISO(x,{zone:"UTC"});return p.isValid||(p=s.DateTime.fromSQL(x,{zone:"UTC"})),p.toJSDate()}}function l(x,d){function p(y,E){if(y===null)return{kind:"null_cell"};if(E.type.kind==="date_type"||E.type.kind==="timestamp_type"){const _=a(y).toISOString();return E.type.kind==="date_type"?{kind:"date_cell",date_value:_}:{kind:"timestamp_cell",timestamp_value:_}}else if(E.type.kind==="boolean_type"){if(typeof y=="number")return{kind:"boolean_cell",boolean_value:y!==0};if(typeof y!="boolean")throw new Error(`Invalid boolean ${y}`);return{kind:"boolean_cell",boolean_value:y}}else if(E.type.kind==="number_type"){if(typeof y!="number")throw new Error(`Invalid number ${y}`);return{kind:"number_cell",number_value:y}}else if(E.type.kind==="string_type"){if(typeof y!="string")throw new Error(`Invalid string ${y}`);return{kind:"string_cell",string_value:y}}else if(E.type.kind==="array_type"){if(!Array.isArray(y))throw new Error(`Invalid array ${y}`);return{kind:"array_cell",array_value:y.map(_=>p(_,{name:"array_element",type:E.type.element_type}))}}else{if(E.type.kind==="json_type")return{kind:"json_cell",json_value:JSON.stringify(y)};if(E.type.kind==="sql_native_type")return{kind:"sql_native_cell",sql_native_value:JSON.stringify(y)};{const _=E.type;if(_.kind!=="record_type")throw new Error(`Invalid record in result ${JSON.stringify(E)}, ${JSON.stringify(y)}`);return m(y,{kind:"join",relationship:"many",name:"array_element",schema:{fields:_.fields.map(v=>({kind:"dimension",...v}))}})}}}function m(y,E){const _=[];for(const v of E.schema.fields){const A=y[v.name];if(v.kind!=="dimension")throw new Error("Invalid result -- expected all fields to be dimensions");const S=p(A,v);_.push(S)}return{kind:"record_cell",record_value:_}}const g={kind:"join",schema:d,name:"root",relationship:"one"};return{kind:"array_cell",array_value:x.map(y=>m(y,g))}}t.mapData=l;function c(x){const d=x._queryResult.structs,p=d[d.length-1],m={fields:(0,i.convertFieldInfos)(p,p.fields)},g=(0,r.annotationToTaglines)(x.annotation).map(E=>({value:E})),y=p.resultMetadata?(0,i.getResultStructMetadataAnnotation)(p,p.resultMetadata):void 0;return y&&g.push(y),g.push(...p.resultMetadata?[]:[]),x.sourceExplore&&g.push({value:e.Tag.withPrefix("#(malloy) ").set(["source_name"],x.sourceExplore.name).toString()}),g.push({value:e.Tag.withPrefix("#(malloy) ").set(["query_name"],x.resultExplore.name).toString()}),{schema:m,data:l(x.data.toObject(),m),connection_name:x.connectionName,annotations:g.length>0?g:void 0,query_timezone:x.data.field.queryTimezone,sql:x.sql}}t.wrapResult=c,t.DEFAULT_LOG_RANGE={start:{line:0,character:0},end:{line:0,character:0}};function f(x,d){return x.map(p=>{var m,g,y,E;return{severity:p.severity,message:p.message,range:(g=(m=p.at)===null||m===void 0?void 0:m.range)!==null&&g!==void 0?g:t.DEFAULT_LOG_RANGE,url:(E=(y=p.at)===null||y===void 0?void 0:y.url)!==null&&E!==void 0?E:d}})}t.mapLogs=f})(o_);var qpt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Hpt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zpt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&qpt(e,t,r);return Hpt(e,t),e};Object.defineProperty(f1,"__esModule",{value:!0}),f1.malloyToQuery=f1.MalloyToQuery=void 0;const Qpt=Gd,Nn=zpt(I),Nde=O2,u_=Mn,Gpt=Ze,Wpt=XE,Lde=Jn,Vpt=o_,bP="Malloy query documents";class Ide extends Qpt.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,Lde.rangeFromContext)(this.parseInfo.sourceInfo,e)}}contextError(e,r,i,s){this.msgLog.log((0,Nde.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 ${bP}`)}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,`${bP} may only have one run statement`);return i===void 0?(this.illegal(e,`${bP} must have a run statement`),null):this.visitRunStatement(i)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getQueryDefinition(r.sqExpr()),s=this.getAnnotations(e.topLevelAnonQueryDef().tags());return i!==null?{annotations:s,definition:i}:null}getQueryReference(e){if(e.sourceArguments())this.illegal(e,"Queries do not support parameters");else return{name:(0,u_.getId)(e)};return null}getQueryDefinition(e){if(e instanceof Nn.SQIDContext){const r=this.getQueryReference(e);if(r!==null)return{kind:"query_reference",...r}}else{if(e instanceof Nn.SQParensContext)return this.getQueryDefinition(e.sqExpr());if(e instanceof Nn.SQComposeContext)this.notAllowed(e,"Source compositions");else if(e instanceof Nn.SQRefinedQueryContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:(s.kind==="arrow"&&this.notAllowed(e,"Queries against refined queries"),{kind:"refinement",base:i,refinement:s})}else if(e instanceof Nn.SQExtendedSourceContext)this.notAllowed(e,"Source extensions");else if(e instanceof Nn.SQIncludeContext)this.notAllowed(e,"Source inclusions");else if(e instanceof Nn.SQTableContext)this.notAllowed(e,"Table statements");else if(e instanceof Nn.SQSQLContext)this.notAllowed(e,"SQL statements");else if(e instanceof Nn.SQArrowContext){const r=e.sqExpr(),i=this.getQueryDefinition(r),s=this.getRefinementSegment(e.segExpr());return s===null||i===null?null:i.kind==="query_reference"?{kind:"arrow",source:{...i,kind:"source_reference"},view:s}:i.kind==="arrow"?{kind:"arrow",source:i.source,view:{kind:"arrow",source:i.view,view:s}}:{kind:"arrow",source:i,view:s}}}return null}getRefinementSegment(e){if(e instanceof Nn.SegOpsContext){const r=e.queryProperties().queryStatement().flatMap(i=>this.getSegmentOperation(i));return r.some(i=>i===null)?null:{kind:"segment",operations:r}}else if(e instanceof Nn.SegFieldContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"view_reference",name:r,path:i}}else{if(e instanceof Nn.SegParenContext)return this.getViewExpression(e.vExpr());if(e instanceof Nn.SegRefineContext){const r=this.getRefinementSegment(e._lhs),i=this.getRefinementSegment(e._rhs);return r===null||i===null?null:{kind:"refinement",base:r,refinement:i}}}return null}getGroupByStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"group_by",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getAggregateStatement(e){const r=this.getAnnotations(e.tags()),s=e.queryFieldList().queryFieldEntry().map(o=>this.getQueryField(o));return s.some(o=>o===null)||s===null?null:s.map(o=>{var u;const a=[...r??[],...(u=o.field.annotations)!==null&&u!==void 0?u:[]];return{kind:"aggregate",name:o.name,field:{...o.field,annotations:a.length>0?a:void 0}}})}getOrderByStatement(e){const r=e.ordering().orderBySpec(),i=[];for(const s of r)if(s.INTEGER_LITERAL())this.notAllowed(s,"Indexed order by statements");else if(s.fieldName()){const o=(0,u_.getId)(s.fieldName()),u=s.ASC()?"asc":s.DESC()?"desc":void 0;i.push({kind:"order_by",direction:u,field_reference:{name:o}})}else return null;return i}getNestStatement(e){const r=this.getAnnotations(e.tags()),i=e.nestedQueryList().nestEntry(),s=[];for(const o of i){if(!(o instanceof Nn.NestDefContext))return this.internalError(o,"Expected nestDef"),null;const u=this.getAnnotations(o.tags()),a=this.getIsAnnotations(o.isDefine()),l=o.queryName(),c=l?(0,u_.getId)(l):void 0,f=this.getViewExpression(o.vExpr());if(f===null)return null;s.push({kind:"nest",name:c,view:{definition:f,annotations:this.combineAnnotations(r,u,a)}})}return s}getViewExpression(e){if(e instanceof Nn.VSegContext)return this.getRefinementSegment(e.segExpr());if(e instanceof Nn.VArrowContext){const r=this.getRefinementSegment(e),i=this.getViewExpression(e._rhs);return r===null||i===null?null:{kind:"arrow",source:r,view:i}}else return this.internalError(e,"Unexpected VExpr node"),null}getLimitStatement(e){return{kind:"limit",limit:this.getNumber(e.INTEGER_LITERAL())}}getSegmentOperation(e){if(e.groupByStatement()){const r=e.groupByStatement();return this.getGroupByStatement(r)}else if(e.aggregateStatement()){const r=e.aggregateStatement();return this.getAggregateStatement(r)}else if(e.limitStatement()){const r=e.limitStatement(),i=this.getLimitStatement(r);return i===null?null:[i]}else if(e.declareStatement())this.notAllowed(e,"Declare statements");else if(e.queryJoinStatement())this.notAllowed(e,"Query join statements");else if(e.queryExtend())this.notAllowed(e,"Query extend statements");else if(e.projectStatement())this.notAllowed(e,"Select statements");else if(e.indexStatement())this.notAllowed(e,"Index statements");else if(e.calculateStatement())this.notAllowed(e,"Calculate statements");else if(e.topStatement())this.notAllowed(e,"Top statements");else if(e.orderByStatement()){const r=e.orderByStatement();return this.getOrderByStatement(r)}else if(e.whereStatement()){const r=e.whereStatement(),i=this.getWhere(r);return i===null?null:i.map(s=>({kind:"where",...s}))}else if(e.havingStatement()){const r=e.havingStatement(),i=this.getHaving(r);return i===null?null:i.map(s=>({kind:"having",...s}))}else if(e.nestStatement()){const r=e.nestStatement();return this.getNestStatement(r)}else e.sampleStatement()?this.notAllowed(e,"Sample statements"):e.timezoneStatement()?this.notAllowed(e,"Timezone statements"):(e.queryAnnotation()||e.ignoredModelAnnotations())&&this.notAllowed(e,"Detached annotation statements");return null}getFieldPath(e){const r=e.fieldName().map(o=>(0,u_.getId)(o)),i=r[0],s=r.slice(1);return{name:i,path:s.length>0?s:void 0}}getTimeframe(e){const r=e.text;return(0,Gpt.isTimestampUnit)(r)?r:(this.illegal(e,`Invalid timeframe ${r}`),null)}getQueryField(e){if(e.taggedRef()){const r=e.taggedRef(),i=this.getAnnotations(r.tags()),{name:s,path:o}=this.getFieldPath(r.fieldPath());if(r.refExpr()){const u=r.refExpr();if(u.timeframe()){const a=this.getTimeframe(u.timeframe());return a===null?null:{name:void 0,field:{annotations:i,expression:{kind:"time_truncation",field_reference:{name:s,path:o},truncation:a}}}}else u.aggregate()&&this.notAllowed(u,"Aggregate expressions")}else return{name:void 0,field:{annotations:i,expression:{kind:"field_reference",name:s,path:o}}}}else if(e.fieldDef()){const r=e.fieldDef(),i=this.getAnnotations(r.tags()),s=this.getIsAnnotations(r.isDefine()),o=(0,u_.getId)(r.fieldNameDef()),u=this.getFieldExpression(r.fieldExpr());return u===null?null:{name:o,field:{expression:u,annotations:this.combineAnnotations(i,s)}}}return null}getFieldExpression(e){if(e instanceof Nn.ExprFieldPathContext){const{name:r,path:i}=this.getFieldPath(e.fieldPath());return{kind:"field_reference",name:r,path:i}}else if(e instanceof Nn.ExprTimeTruncContext){const r=this.getTimeframe(e.timeframe()),i=e.fieldExpr(),s=this.getFieldExpression(i);return s===null||r===null?null:s.kind!=="field_reference"?(this.illegal(i,"Left hand side of time truncation must be a field reference"),null):{kind:"time_truncation",truncation:r,field_reference:{name:s.name,path:s.path,parameters:s.parameters}}}else if(e instanceof Nn.ExprFieldPropsContext){const r=e.fieldExpr(),i=this.getFieldExpression(r);if(i===null)return null;if(i.kind!=="field_reference")return this.illegal(r,"Left hand side of filtered field must be a field reference"),null;const s=e.fieldProperties().fieldPropertyStatement(),o=[];for(const u of s){const a=u.whereStatement();if(a){const l=this.getWhere(a);if(l===null)return null;o.push(...l)}}return{kind:"filtered_field",field_reference:{name:i.name,path:i.path,parameters:i.parameters},where:o}}return null}stripQuote(e,r){return e.slice(e.indexOf(r)+r.length,e.lastIndexOf(r))}getFilterString(e){const r=e.tripFilterString(),i=e.tickFilterString();if(r){const s=r.BQ3_FILTER(),o=r.DQ3_FILTER(),u=r.SQ3_FILTER();if(s)return this.stripQuote(s.text,"```");if(o)return this.stripQuote(o.text,'"""');if(u)return this.stripQuote(u.text,"'''")}else if(i){const s=i.BQ_FILTER(),o=i.DQ_FILTER(),u=i.SQ_FILTER();if(s)return this.stripQuote(s.text,"`");if(o)return this.stripQuote(o.text,'"');if(u)return this.stripQuote(u.text,"'")}return null}getFilterExpr(e){if(e instanceof Nn.ExprCompareContext&&e.compareOp().MATCH()){const r=e.fieldExpr()[0],i=e.fieldExpr()[1];if(r instanceof Nn.ExprFieldPathContext&&i instanceof Nn.ExprLiteralContext){const{path:s,name:o}=this.getFieldPath(r.fieldPath()),u=i.literal();if(u instanceof Nn.FilterString_stubContext){const a=this.getFilterString(u.filterString());return a===null?null:{filter:{kind:"filter_string",field_reference:{name:o,path:s},filter:a}}}}}return this.notAllowed(e,"Filters other than comparisons with filter strings"),null}getWhere(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}getHaving(e){const i=e.filterClauseList().fieldExpr().map(s=>this.getFilterExpr(s));return i.some(s=>s===null)?null:i}combineAnnotations(...e){const r=e.flatMap(i=>i??[]);return r.length>0?r:void 0}}f1.MalloyToQuery=Ide;function Ypt(t){const e=(0,Lde.getSourceInfo)(t),r=new Nde.BaseMessageLogger(null),i="internal://query.malloy",s=(0,Wpt.runMalloyParser)(t,i,e,r),u=new Ide(s,r).visit(s.root),a=(0,Vpt.mapLogs)(r.getLog(),i);if(u===null)return{logs:a};if(!("definition"in u))throw new Error("Expected a query");return{query:u,logs:a}}f1.malloyToQuery=Ypt,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.malloyToQuery=t.exploreQueryWalkerBuilder=t.MalloyTranslation=t.MalloyTranslator=void 0;var e=Wc;Object.defineProperty(t,"MalloyTranslator",{enumerable:!0,get:function(){return e.MalloyTranslator}}),Object.defineProperty(t,"MalloyTranslation",{enumerable:!0,get:function(){return e.MalloyTranslation}});var r=c1;Object.defineProperty(t,"exploreQueryWalkerBuilder",{enumerable:!0,get:function(){return r.exploreQueryWalkerBuilder}});var i=f1;Object.defineProperty(t,"malloyToQuery",{enumerable:!0,get:function(){return i.malloyToQuery}})}(Y4);var $e={},ND={};Object.defineProperty(ND,"__esModule",{value:!0}),ND.MALLOY_VERSION=void 0,ND.MALLOY_VERSION="0.0.277",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 $de=Y4,gi=Gi,Bde=Ur,TP=y2,Kpt=ND,Jpt=_2,Pn=hi,Xpt=y0,Zpt=Jn,e2t=JE,kde="internal://internal.malloy";let b0=class sO{static get version(){return Kpt.MALLOY_VERSION}static _parse(e,r,i,s,o){r===void 0&&(r=new URL(kde));let u=r;s!=null&&s.importBaseURL&&(u=s==null?void 0:s.importBaseURL);const a=new $de.MalloyTranslator(r.toString(),u.toString(),{urls:{[r.toString()]:e}},i);return s!=null&&s.testEnvironment&&(a.allDialectsEnabled=!0),new Pde(a,o)}static parse({url:e,urlReader:r,source:i,eventStream:s,options:o}){if(i!==void 0)return sO._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 jD(r,e).then(({contents:u,invalidationKey:a})=>sO._parse(u,e,s,o,a))}static async compile({url:e,source:r,parse:i,urlReader:s,connections:o,model:u,refreshSchemaCache:a,noThrowOnError:l,eventStream:c,importBaseURL:f,cacheManager:x}){var d,p,m,g,y;let E;if(a&&(E=typeof a=="number"?a:Date.now()),e===void 0&&r===void 0&&i===void 0)throw new Error("Internal Error: url, source, or parse required.");e===void 0&&(i!==void 0?e=new URL(i._translator.sourceURL):e=new URL(kde));const _={};if(r===void 0&&x!==void 0){const S=await x.getCachedModelDef(s,e.toString());if(S)return new d1(S.modelDef,[],[e.toString(),...PD(S.modelDef.dependencies)])}f??(f=e);let v;const A=e.toString();if(i!==void 0){v=i._translator;const S=(d=i._invalidationKey)!==null&&d!==void 0?d:await PP(s,e);_[A]=S}else{if(r===void 0){const{contents:S,invalidationKey:b}=await jD(s,e);_[A]=b,r=S}else{const S=await PP(s,e);_[A]=S}v=new $de.MalloyTranslator(A,f.toString(),{urls:{[A]:r}},c)}for(;;){const S=v.translate(u==null?void 0:u._modelDef);if(S.final)if(S.modelDef){await(x==null?void 0:x.setCachedModelDef(e.toString(),{modelDef:S.modelDef,invalidationKeys:_}));for(const b of v.newlyTranslatedDependencies())await(x==null?void 0:x.setCachedModelDef(b.url,{modelDef:b.modelDef,invalidationKeys:_}));return new d1(S.modelDef,S.problems||[],[...(p=u==null?void 0:u.fromSources)!==null&&p!==void 0?p:[],...(m=S.fromSources)!==null&&m!==void 0?m:[]])}else if(l){const b={name:"modelDidNotCompile",exports:[],contents:{},dependencies:{},queryList:[]},C=(u==null?void 0:u._modelDef)||b;return new d1(C,S.problems||[],[...(g=u==null?void 0:u.fromSources)!==null&&g!==void 0?g:[],...(y=S.fromSources)!==null&&y!==void 0?y:[]])}else{const b=S.problems||[],C=v.prettyErrors();throw new Mde(`Error(s) compiling model:
1865
1865
  ${C}`,b)}else{if(S.urls)for(const C of S.urls)try{if(UD(C))throw new Error("In order to use relative imports, you must compile a file via a URL.");if(x!==void 0){const D=await x.getCachedModelDef(s,C);if(D){for(const M in D.invalidationKeys)_[M]=D.invalidationKeys[M];v.update({translations:{[C]:D.modelDef}});continue}}const{contents:R,invalidationKey:O}=await jD(s,new URL(C)),B={[C]:R};_[C]=O,v.update({urls:B})}catch(R){v.update({errors:{urls:{[C]:R.message}}})}const{modelAnnotation:b}=v.modelAnnotation(u==null?void 0:u._modelDef);if(S.tables){const C=new Map;for(const R in S.tables){const{connectionName:O,tablePath:B}=S.tables[R],D=C.get(O);D===void 0?C.set(O,{[R]:B}):D[R]=B}for(const[R,O]of C)try{const B=await o.lookupConnection(R),{schemas:D,errors:M}=await sO.safelyFetchTableSchema(B,O,{refreshTimestamp:E,modelAnnotation:b});v.update({tables:D,errors:{tables:M}})}catch(B){const D={},M={};for(const k in O)M[k]=B.toString();v.update({tables:D,errors:{tables:M}})}}if(S.compileSQL){const C=S.compileSQL,R=C.connection,O=(0,Xpt.sqlKey)(C.connection,C.selectStr);try{const D=await(await o.lookupConnection(R)).fetchSchemaForSQLStruct(C,{refreshTimestamp:E,modelAnnotation:b});D.error&&v.update({errors:{compileSQL:{[O]:D.error}}}),D.structDef&&v.update({compileSQL:{[O]:D.structDef}})}catch(B){const D={};D[O]=B.toString(),v.update({errors:{compileSQL:D}})}}}}}static async safelyFetchTableSchema(e,r,i){const s=await e.fetchSchemaForTables(r,i);for(const o of Object.keys(r))if(s.schemas[o]===void 0&&s.errors[o]===void 0)throw new Error(`Schema fetch error for ${e.name}, no response for ${o} from ${e.dialectName}`);return s}static async run({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(!s){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);s=await e.lookupConnection(u)}if(i){const u=await s.runSQL(i.selectStr);return new c_({structs:[i],sql:i.selectStr,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,lastStageName:i.name,malloy:"",connectionName:i.connection,sourceExplore:"",sourceFilters:[],profilingUrl:u.profilingUrl},{name:"empty_model",exports:[],contents:{},queryList:[],dependencies:{}})}else if(r){const u=await s.runSQL(r.sql,o);return new c_({...r._rawQuery,result:u.rows,totalRows:u.totalRows,runStats:u.runStats,profilingUrl:u.profilingUrl},r._modelDef)}else throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}static async*runStream({connections:e,preparedResult:r,sqlStruct:i,connection:s,options:o}){if(i===void 0&&r===void 0)throw new Error("Internal error: sqlBlock or preparedResult must be provided.");const u=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName);if(s===void 0){if(e===void 0)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");s=await e.lookupConnection(u)}if(!s.canStream())throw new Error(`Connection '${u}' cannot stream results.`);let a,l;if(i)l=new Vs(i),a=i.selectStr;else if(r!==void 0)l=r.resultExplore,a=r.sql;else throw new Error("Internal error: sqlStruct or preparedResult must be provided.");let c=0;for await(const f of s.runSQLStream(a,o))yield new jd(f,c,l,void 0,void 0),c+=1}static async estimateQueryCost({connections:e,preparedResult:r,sqlStruct:i}){if(!e)throw new Error("Internal Error: Connection or LookupConnection<Connection> must be provided.");const s=(i==null?void 0:i.connection)||(r==null?void 0:r.connectionName),o=await e.lookupConnection(s);if(i)return await o.estimateQueryCost(i.selectStr);if(r)return await o.estimateQueryCost(r.sql);throw new Error("Internal error: sqlStruct or preparedResult must be provided.")}};$e.Malloy=b0;class Mde extends Error{constructor(e,r=[]){super(e),this.problems=r}}$e.MalloyError=Mde;class d1{constructor(e,r,i){var s,o;this.modelDef=e,this.problems=r,this.fromSources=i,this.references=new e2t.ReferenceList((s=i[0])!==null&&s!==void 0?s:"",(o=e.references)!==null&&o!==void 0?o:[])}tagParse(e){return(0,Pn.annotationToTag)(this.modelDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.modelDef.annotation,e)}getReference(e){return this.references.find(e)}getImport(e){var r;return(r=this.modelDef.imports)===null||r===void 0?void 0:r.find(i=>(0,Zpt.locationContainsPosition)(i.location,e))}getPreparedQueryByName(e){const r=this.modelDef.contents[e];if((r==null?void 0:r.type)==="query")return new h1(r,this.modelDef,this.problems,e);throw new Error("Given query name does not refer to a named query.")}getPreparedQueryByIndex(e){if(e<0)throw new Error(`Invalid index ${e}.`);if(e>=this.modelDef.queryList.length)throw new Error(`Query index ${e} is out of bounds.`);return new h1(this.modelDef.queryList[e],this.modelDef,this.problems)}get preparedQuery(){return this.getPreparedQuery()}getPreparedQuery(){if(this.modelDef.queryList.length===0)throw new Error("Model has no queries.");return new h1(this.modelDef.queryList[this.modelDef.queryList.length-1],this.modelDef,this.problems)}getExploreByName(e){const r=this.modelDef.contents[e];if((0,gi.isSourceDef)(r))return new Vs(r);throw new Error("'name' is not an explore")}get explores(){return Object.values(this.modelDef.contents).filter(gi.isSourceDef).map(e=>new Vs(e))}get namedQueries(){const e=r=>r.type==="query";return Object.values(this.modelDef.contents).filter(e)}get exportedExplores(){return this.explores.filter(e=>this.modelDef.exports.includes(e.name))}get _modelDef(){return this.modelDef}}$e.Model=d1;class h1{constructor(e,r,i,s){this.problems=i,this.name=s,this._query=e,this._modelDef=r}tagParse(e){const r=(0,Pn.annotationToTag)(this._modelDef.annotation).tag;return e=(0,Pn.addModelScope)(e,r),(0,Pn.annotationToTag)(this._query.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this._query.annotation,e)}get preparedResult(){return this.getPreparedResult()}getPreparedResult(e){const i=new gi.QueryModel(this._modelDef,e==null?void 0:e.eventStream).compileQuery(this._query,e);return new a_({...i,queryName:this.name||i.queryName},this._modelDef)}get dialect(){const e=this._query.structRef,r=typeof e=="string"?this._modelDef.contents[e]:e;if(!(0,gi.isSourceDef)(r))throw new Error("Invalid source for query");return r.dialect}getFlattenedQuery(e){return this}}$e.PreparedQuery=h1;class Pde{constructor(e,r){this.translator=e,this.invalidationKey=r}get symbols(){return(this.translator.metadata().symbols||[]).map(e=>new LD(e))}get tablePathInfo(){var e;return((e=this.translator.tablePathInfo().pathInfo)!==null&&e!==void 0?e:[]).map(i=>new jde(i))}get _translator(){return this.translator}get _invalidationKey(){return this.invalidationKey}completions(e){return(this.translator.completions(e).completions||[]).map(r=>new Ude(r))}helpContext(e){return this.translator.helpContext(e).helpContext}}$e.Parse=Pde;class jde{constructor(e){this._range=p1.fromJSON(e.range),this._connectionId=e.connectionId,this._tablePath=e.tablePath}get range(){return this._range}get connectionId(){return this._connectionId}get tablePath(){return this._tablePath}}$e.DocumentTablePath=jde;class p1{constructor(e,r){this._start=e,this._end=r}get start(){return this._start}get end(){return this._end}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}static fromJSON(e){return new p1(new RP(e.start.line,e.start.character),new RP(e.end.line,e.end.character))}}$e.DocumentRange=p1;class RP{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=RP;class LD{constructor(e){this._range=p1.fromJSON(e.range),this._lensRange=e.lensRange?p1.fromJSON(e.lensRange):void 0,this._type=e.type,this._name=e.name,this._children=e.children.map(r=>new LD(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=LD;class Ude{constructor(e){this.type=e.type,this.text=e.text}}$e.DocumentCompletion=Ude;class a_{constructor(e,r){this.modelDef=r,this.inner=e}static fromJson({query:e,modelDef:r}){if(!e||!r)throw new Error("Missing required properties in JSON data");return new a_(e,r)}tagParse(e){const r=(0,Pn.annotationToTag)(this.modelDef.annotation).tag;return e=(0,Pn.addModelScope)(e,r),(0,Pn.annotationToTag)(this.inner.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.inner.annotation,e)}get annotation(){return this.inner.annotation}get modelAnnotation(){return this.modelDef.annotation}get modelTag(){return(0,Pn.annotationToTag)(this.modelDef.annotation).tag}get connectionName(){return this.inner.connectionName}get _rawQuery(){return this.inner}get _modelDef(){return this.modelDef}get sql(){return this.inner.sql}get dependenciesToMaterialize(){return this.inner.dependenciesToMaterialize}get materialization(){return this.inner.materialization}get resultExplore(){if(this.inner.structs.length===0)throw new Error("Malformed query result.");const e=this.inner.structs[this.inner.structs.length-1],r={...e,annotation:this.inner.annotation,name:this.inner.queryName||e.name};try{return new Vs(r,this.sourceExplore)}catch{return new Vs(r)}}get sourceExplore(){const e=this.inner.sourceExplore,r=this.modelDef.contents[e];if(r&&(0,gi.isSourceDef)(r))return new Vs(r)}get _sourceExploreName(){return this.inner.sourceExplore}get _sourceFilters(){return this.inner.sourceFilters||[]}}$e.PreparedResult=a_;class qde{async readURL(e){throw new Error("No files.")}async getInvalidationKey(e){throw new Error("No files.")}}$e.EmptyURLReader=qde;class t2t{constructor(e){this.files=e}async readURL(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve({contents:r,invalidationKey:this.invalidationKey(e,r)});throw new Error(`File not found '${e}'`)}async getInvalidationKey(e){const r=this.files.get(e.toString());if(r!==void 0)return Promise.resolve(this.invalidationKey(e,r));throw new Error(`File not found '${e}'`)}invalidationKey(e,r){return UD(e.toString())?null:rhe(r)}}$e.InMemoryURLReader=t2t;class ID{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 ID(new Map(e.map(r=>[r.name,r])))}}$e.FixedConnectionMap=ID;var Hde;(function(t){t.Nested="nested",t.BaseTable="base_table",t.Cross="cross",t.One="one",t.Many="many",t.Inline="inline"})(Hde||($e.SourceRelationship=Hde={}));class DP{constructor(e,r,i){this._name=e,this._parent=r,this._source=i}get source(){return this.source}get name(){return this._name}get sourceClasses(){const e=[];return this.source&&e.push(this.source.name),e.push(this.name),e}get fieldPath(){const e=[this.name];let r=this._parent;for(;r;)e.unshift(r.name),r=r._parent;return e}hasParentExplore(){return this._parent!==void 0}isExplore(){return this instanceof Vs}isQuery(){return this instanceof $P}}class Vs extends DP{constructor(e,r,i){super(e.as||e.name,r,i),this._structDef=e,this._parentExplore=r,this.sourceExplore=i}get source(){return this.sourceExplore}isIntrinsic(){return(0,gi.isAtomicFieldType)(this._structDef.type)?!("e"in this._structDef):!1}isExploreField(){return!1}tagParse(e){return(0,Pn.annotationToTag)(this._structDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this._structDef.annotation,e)}get modelTag(){return this.parsedModelTag||(this.parsedModelTag=(0,Pn.annotationToTag)(this._structDef.modelAnnotation).tag),this.parsedModelTag}get name(){return this.structDef.as||this.structDef.name}getQueryByName(e){const r=this.sourceStructDef;if(!r)throw new Error(`Cannot get query by name from a struct of type ${this.structDef.type}`);const i={type:"query",structRef:r,pipeline:[{type:"reduce",queryFields:[{type:"fieldref",path:[e]}]}]};return new h1(i,this.modelDef,[],e)}get modelDef(){if(!(0,gi.isSourceDef)(this.structDef))throw new Error(`Cannot create pseudo model for struct type ${this.structDef.type}`);return{name:"generated_model",exports:[],contents:{[this.structDef.name]:this.structDef},queryList:[],dependencies:{}}}getSingleExploreModel(){return new d1(this.modelDef,[],[])}get fieldMap(){var e;if(this._fieldMap===void 0){const r=((e=this.source)===null||e===void 0?void 0:e.fieldMap)||new Map;this._fieldMap=new Map(this.structDef.fields.map(i=>{const s=i.as||i.name,o=r.get(i.name);if((0,gi.isJoined)(i))return[s,new BP(i,this,o)];if(i.type==="turtle")return[s,new $P(i,this,o)];if(i.type==="string")return[s,new IP(i,this,o)];if(i.type==="number")return[s,new $D(i,this,o)];if(i.type==="date")return i.timeframe&&["day_of_month","day_of_week","day_of_year"].includes(i.timeframe)?[s,new $D({...i,type:"number"},this,o)]:[s,new OP(i,this,o)];if(i.type==="timestamp")return[s,new wP(i,this,o)];if(i.type==="boolean")return[s,new FP(i,this,o)];if(i.type==="json")return[s,new NP(i,this,o)];if(i.type==="sql native")return[s,new LP(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 BP}get filters(){var e;return(0,gi.isSourceDef)(this.structDef)?((e=this.structDef.resultMetadata)===null||e===void 0?void 0:e.filterList)||[]:[]}get limit(){var e,r;return(r=(e=this.sourceStructDef)===null||e===void 0?void 0:e.resultMetadata)===null||r===void 0?void 0:r.limit}get structDef(){return this._structDef}get queryTimezone(){var e;return(e=this.sourceStructDef)===null||e===void 0?void 0:e.queryTimezone}get sourceStructDef(){if((0,gi.isSourceDef)(this.structDef))return this.structDef}toJSON(){var e,r;return{_structDef:this._structDef,sourceExplore:(e=this.sourceExplore)===null||e===void 0?void 0:e.toJSON(),_parentExplore:(r=this._parentExplore)===null||r===void 0?void 0:r.toJSON()}}static fromJSON(e){const r=e._parentExplore!==void 0?Vs.fromJSON(e._parentExplore):void 0,i=e.sourceExplore!==void 0?Vs.fromJSON(e.sourceExplore):void 0;return new Vs(e._structDef,r,i)}get location(){return this.structDef.location}}$e.Explore=Vs;var Ja;(function(t){t.String="string",t.Number="number",t.Boolean="boolean",t.Date="date",t.Timestamp="timestamp",t.Json="json",t.NativeUnsupported="sql native",t.Error="error"})(Ja||($e.AtomicFieldType=Ja={}));class pf extends DP{constructor(e,r,i){super(e.as||e.name,r,i),this.fieldTypeDef=e,this.parent=r}get type(){switch(this.fieldTypeDef.type){case"string":return Ja.String;case"boolean":return Ja.Boolean;case"date":return Ja.Date;case"timestamp":return Ja.Timestamp;case"number":return Ja.Number;case"json":return Ja.Json;case"sql native":return Ja.NativeUnsupported;case"error":return Ja.Error;case"record":case"array":throw new Error(`MTOY TODO IMPLEMENT Atomic ${this.fieldTypeDef.type}`);default:{const e=this.fieldTypeDef;throw new Error(`Can't make an atomic field from ${e}`)}}}tagParse(e){return e=(0,Pn.addModelScope)(e,this.parent.modelTag),(0,Pn.annotationToTag)(this.fieldTypeDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.fieldTypeDef.annotation,e)}isIntrinsic(){return(0,gi.fieldIsIntrinsic)(this.fieldTypeDef)}isQueryField(){return!1}isExploreField(){return!1}isAtomicField(){return!0}isCalculation(){return(0,gi.expressionIsCalculation)(this.fieldTypeDef.expressionType)}get sourceField(){throw new Error}get sourceClasses(){const e=this.fieldTypeDef.name||this.fieldTypeDef.as;return e?[e]:[]}get referenceId(){var e;return(e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.referenceId}sourceWasMeasure(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"}sourceWasMeasureLike(){var e,r;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="measure"||((r=this.fieldTypeDef.resultMetadata)===null||r===void 0?void 0:r.fieldKind)==="struct"}sourceWasDimension(){var e;return((e=this.fieldTypeDef.resultMetadata)===null||e===void 0?void 0:e.fieldKind)==="dimension"}hasParentExplore(){return!0}isString(){return this instanceof IP}isNumber(){return this instanceof $D}isDate(){return this instanceof OP}isBoolean(){return this instanceof FP}isJSON(){return this instanceof NP}isTimestamp(){return this instanceof wP}isUnsupported(){return this instanceof LP}get parentExplore(){return this.parent}get expression(){const e=".",r=this.fieldTypeDef.resultMetadata;return(r==null?void 0:r.sourceExpression)||(r!=null&&r.sourceField.includes(e)?r==null?void 0:r.sourceField:this.name)}get location(){return this.fieldTypeDef.location}}$e.AtomicField=pf;var Pd;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year"})(Pd||($e.DateTimeframe=Pd={}));var Xa;(function(t){t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.Year="year",t.Second="second",t.Hour="hour",t.Minute="minute"})(Xa||($e.TimestampTimeframe=Xa={}));class OP extends pf{constructor(e,r,i){super(e,r,i),this.fieldDateDef=e}get timeframe(){if(this.fieldDateDef.timeframe!==void 0)switch(this.fieldDateDef.timeframe){case"day":return Pd.Day;case"week":return Pd.Week;case"month":return Pd.Month;case"quarter":return Pd.Quarter;case"year":return Pd.Year}}}$e.DateField=OP;class wP extends pf{constructor(e,r,i){super(e,r,i),this.fieldTimestampDef=e}get timeframe(){if(this.fieldTimestampDef.timeframe!==void 0)switch(this.fieldTimestampDef.timeframe){case"day":return Xa.Day;case"week":return Xa.Week;case"month":return Xa.Month;case"quarter":return Xa.Quarter;case"year":return Xa.Year;case"second":return Xa.Second;case"hour":return Xa.Hour;case"minute":return Xa.Minute}}}$e.TimestampField=wP;class $D extends pf{constructor(e,r,i){super(e,r,i),this.fieldNumberDef=e}}$e.NumberField=$D;class FP extends pf{constructor(e,r,i){super(e,r,i),this.fieldBooleanDef=e}}$e.BooleanField=FP;class NP extends pf{constructor(e,r,i){super(e,r,i),this.fieldJSONDef=e}}$e.JSONField=NP;class LP extends pf{constructor(e,r,i){super(e,r,i),this.fieldUnsupportedDef=e}get rawType(){return this.fieldUnsupportedDef.rawType}}$e.UnsupportedField=LP;class IP extends pf{constructor(e,r,i){super(e,r,i),this.fieldStringDef=e}}$e.StringField=IP;class zde extends DP{constructor(e,r,i){super(e.as||e.name,r,i),this.turtleDef=e}get source(){return this.sourceQuery}isIntrinsic(){return!1}get location(){return this.turtleDef.location}}$e.Query=zde;class $P extends zde{constructor(e,r,i){super(e,r,i),this.parent=r}tagParse(e){return e=(0,Pn.addModelScope)(e,this.parent.modelTag),(0,Pn.annotationToTag)(this.turtleDef.annotation,e)}getTaglines(e){return(0,Pn.annotationToTaglines)(this.turtleDef.annotation,e)}isQueryField(){return!0}isExploreField(){return!1}isAtomicField(){return!1}get sourceClasses(){const e=this.turtleDef.name||this.turtleDef.as;return e?[e]:[]}hasParentExplore(){return!0}get parentExplore(){return this.parent}get expression(){return this.name}}$e.QueryField=$P;var m1;(function(t){t.OneToOne="one_to_one",t.OneToMany="one_to_many",t.ManyToOne="many_to_one"})(m1||($e.JoinRelationship=m1={}));class BP extends Vs{constructor(e,r,i){super(e,r,i),this._parentExplore=r}get joinRelationship(){if((0,gi.isJoined)(this.structDef))switch(this.structDef.join){case"one":return m1.OneToOne;case"many":case"cross":return m1.ManyToOne}throw new Error("A source field must have a join relationship.")}get isRecord(){return this.joinRelationship===m1.OneToOne}get isArray(){return this.joinRelationship!==m1.OneToOne}tagParse(e){return e=(0,Pn.addModelScope)(e,this._parentExplore.modelTag),(0,Pn.annotationToTag)(this._structDef.annotation,e)}isQueryField(){return!1}isExploreField(){return!0}isAtomicField(){return!1}get parentExplore(){return this._parentExplore}get sourceClasses(){const e=this.structDef.name||this.structDef.as;return e?[e]:[]}}$e.ExploreField=BP;class kP{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 qde),this._urlReader=e,this._connections=r,this._eventStream=s,this._cacheManager=o}get cacheManager(){return this._cacheManager}get urlReader(){return this._urlReader}get connections(){return this._connections}get eventStream(){return this._eventStream}loadModel(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};this.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const o=e instanceof URL?{url:e}:{source:e};return new l_(this,async()=>b0.compile({...o,urlReader:this.urlReader,connections:this.connections,refreshSchemaCache:i,noThrowOnError:s,eventStream:this.eventStream,replaceMaterializedReferences:r==null?void 0:r.replaceMaterializedReferences,materializedTablePrefix:r==null?void 0:r.materializedTablePrefix,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,cacheManager:this.cacheManager}),r)}_loadModelFromModelDef(e,r){return new l_(this,async()=>new d1(e,[],[]),r)}loadQuery(e,r){return this.loadModel(e,r).loadFinalQuery()}loadQueryByIndex(e,r,i){return this.loadModel(e,i).loadQueryByIndex(r,i)}loadQueryByName(e,r,i){return this.loadModel(e,i).loadQueryByName(r,i)}getModel(e,r){return this.loadModel(e,r).getModel()}getQuery(e,r){return this.loadQuery(e,r).getPreparedQuery()}getQueryByIndex(e,r,i){return this.loadQueryByIndex(e,r,i).getPreparedQuery()}getQueryByName(e,r,i){return this.loadQueryByName(e,r,i).getPreparedQuery()}}$e.Runtime=kP;class n2t extends kP{constructor({urlReader:e,connections:r}){super({connections:ID.fromArray(r),urlReader:e}),this.rawConnections=r}}$e.ConnectionRuntime=n2t;class r2t extends kP{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,TP.getDialect)(this.connection.dialectName).supportsNesting}quote(e){return(0,TP.getDialect)(this.connection.dialectName).sqlMaybeQuoteIdentifier(e)}get dialect(){return(0,TP.getDialect)(this.connection.dialectName)}getQuoter(){return e=>this.quote(e.toString())}}$e.SingleConnectionRuntime=r2t;class BD{constructor(e,r){this.runtime=e,this._materialize=r}materialize(){return this.materialized===void 0?this.rematerialize():this.materialized}rematerialize(){return this.materialized=this._materialize(),this.materialized}makeQueryMaterializer(e,r){return new Qde(this.runtime,e,r)}makeExploreMaterializer(e,r){return new Wde(this.runtime,e,r)}makePreparedResultMaterializer(e){return new Gde(this.runtime,e)}}class l_ extends BD{constructor(e,r,i){super(e,r),this.runtime=e,this.compileQueryOptions=i}loadFinalQuery(e){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQuery(),{...this.compileQueryOptions,...e})}loadQueryByIndex(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByIndex(e),{...this.compileQueryOptions,...r})}loadQueryByName(e,r){return this.makeQueryMaterializer(async()=>(await this.materialize()).getPreparedQueryByName(e),{...this.compileQueryOptions,...r})}loadQuery(e,r){const{refreshSchemaCache:i,noThrowOnError:s}=r||{};return this.makeQueryMaterializer(async()=>{const o=this.runtime.urlReader,u=this.runtime.connections;this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0});const a=e instanceof URL?{url:e}:{source:e},l=await this.getModel();return(await b0.compile({...a,urlReader:o,connections:u,model:l,refreshSchemaCache:i,noThrowOnError:s,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})).preparedQuery})}extendModel(e,r){return this.runtime.isTestRuntime&&(r===void 0?r={testEnvironment:!0}:r={...r,testEnvironment:!0}),new l_(this.runtime,async()=>{const i=this.runtime.urlReader,s=this.runtime.connections,o=e instanceof URL?{url:e}:{source:e},u=await this.getModel();return await b0.compile({...o,urlReader:i,connections:s,model:u,refreshSchemaCache:r==null?void 0:r.refreshSchemaCache,noThrowOnError:r==null?void 0:r.noThrowOnError,importBaseURL:r==null?void 0:r.importBaseURL,testEnvironment:r==null?void 0:r.testEnvironment,...this.compileQueryOptions})},r)}async search(e,r,i=1e3,s=void 0,o){const u=await this.materialize(),a=new gi.QueryModel(u._modelDef,o),l=u.getExploreByName(e).structDef;if(!(0,gi.isSourceDef)(l))throw new Error("Source to be searched was unexpectedly, not a source");const c=l.connection,f=await this.runtime.connections.lookupConnection(c);return await a.searchIndex(f,e,r,i,s)}async searchValueMap(e,r=10,i){const o=(await this.materialize()).getExploreByName(e);if(!(0,gi.isSourceDef)(o.structDef))throw new Error("Source to be searched was unexpectedly, not a source");let u="{index: *}";o.getFieldByNameIfExists("search_index")&&(u="search_index");const a=`
1866
1866
  run: ${e}
1867
1867
  -> ${u}
@@ -19925,7 +19925,7 @@ ${r}}`, i;
19925
19925
  else
19926
19926
  return;
19927
19927
  }
19928
- return i;
19928
+ return i.deleted ? void 0 : i;
19929
19929
  }
19930
19930
  has(...e) {
19931
19931
  return this.find(e) !== void 0;
@@ -154142,7 +154142,7 @@ n2.malloyToQuery = C2t;
154142
154142
  var $e = {}, GD = {};
154143
154143
  Object.defineProperty(GD, "__esModule", { value: !0 });
154144
154144
  GD.MALLOY_VERSION = void 0;
154145
- GD.MALLOY_VERSION = "0.0.276";
154145
+ GD.MALLOY_VERSION = "0.0.277";
154146
154146
  Object.defineProperty($e, "__esModule", { value: !0 });
154147
154147
  $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;
154148
154148
  const eK = JT, ri = Ki, tK = zr, ow = J2, b2t = GD, T2t = X2, kn = di, R2t = n0, D2t = Kn, O2t = uv, nK = "internal://internal.malloy";