@coalescesoftware/coa 7.39.3 → 7.39.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/coa.js CHANGED
@@ -9588,7 +9588,7 @@ Content-Type: `+c.contentType+`\r
9588
9588
  `,p),p}return i};var fGc=bt(kko(),1),k3=(r,t,n={})=>(REr(t),!n.nocomment&&t.charAt(0)==="#"?!1:new XJe(t,n).match(r));var od1=/^\*+([^+@!?\*\[\(]*)$/,sd1=r=>t=>!t.startsWith(".")&&t.endsWith(r),ad1=r=>t=>t.endsWith(r),ud1=r=>(r=r.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(r)),cd1=r=>(r=r.toLowerCase(),t=>t.toLowerCase().endsWith(r)),ld1=/^\*+\.\*+$/,pd1=r=>!r.startsWith(".")&&r.includes("."),dd1=r=>r!=="."&&r!==".."&&r.includes("."),fd1=/^\.\*+$/,hd1=r=>r!=="."&&r!==".."&&r.startsWith("."),gd1=/^\*+$/,Ad1=r=>r.length!==0&&!r.startsWith("."),md1=r=>r.length!==0&&r!=="."&&r!=="..",yd1=/^\?+([^+@!?\*\[\(]*)?$/,bd1=([r,t=""])=>{let n=pGc([r]);return t?(t=t.toLowerCase(),i=>n(i)&&i.toLowerCase().endsWith(t)):n},Ed1=([r,t=""])=>{let n=dGc([r]);return t?(t=t.toLowerCase(),i=>n(i)&&i.toLowerCase().endsWith(t)):n},Cd1=([r,t=""])=>{let n=dGc([r]);return t?i=>n(i)&&i.endsWith(t):n},Sd1=([r,t=""])=>{let n=pGc([r]);return t?i=>n(i)&&i.endsWith(t):n},pGc=([r])=>{let t=r.length;return n=>n.length===t&&!n.startsWith(".")},dGc=([r])=>{let t=r.length;return n=>n.length===t&&n!=="."&&n!==".."},vd1=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",IEr=vd1==="win32",Fko=IEr?{sep:"\\"}:{sep:"/"},Td1=Fko.sep;k3.sep=Td1;var uF=Symbol("globstar **");k3.GLOBSTAR=uF;var cGc={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},Uko="[^/]",qko=Uko+"*?",_d1="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Id1="(?:(?!(?:\\/|^)\\.).)*?",hGc=r=>r.split("").reduce((t,n)=>(t[n]=!0,t),{}),lGc=hGc("().*{}+?[]^$\\!"),Rd1=hGc("[.("),Od1=(r,t={})=>n=>k3(n,r,t);k3.filter=Od1;var gbe=(r,t={})=>Object.assign({},r,t),wd1=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return k3;let t=k3;return Object.assign((i,o,s={})=>t(i,o,gbe(r,s)),{Minimatch:class extends t.Minimatch{constructor(o,s={}){super(o,gbe(r,s))}static defaults(o){return t.defaults(gbe(r,o)).Minimatch}},filter:(i,o={})=>t.filter(i,gbe(r,o)),defaults:i=>t.defaults(gbe(r,i)),makeRe:(i,o={})=>t.makeRe(i,gbe(r,o)),braceExpand:(i,o={})=>t.braceExpand(i,gbe(r,o)),match:(i,o,s={})=>t.match(i,o,gbe(r,s)),sep:t.sep,GLOBSTAR:uF})};k3.defaults=wd1;var gGc=(r,t={})=>(REr(r),t.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0,fGc.default)(r));k3.braceExpand=gGc;var Md1=1024*64,REr=r=>{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>Md1)throw new TypeError("pattern is too long")},_Er=Symbol("subparse"),xd1=(r,t={})=>new XJe(r,t).makeRe();k3.makeRe=xd1;var zko=(r,t,n={})=>{let i=new XJe(t,n);return r=r.filter(o=>i.match(o)),i.options.nonull&&!r.length&&r.push(t),r};k3.match=zko;var Pd1=r=>r.replace(/\\(.)/g,"$1"),Nd1=r=>r.replace(/\\([^-\]])/g,"$1"),Dd1=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Bd1=r=>r.replace(/[[\]\\]/g,"\\$&"),XJe=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;regexp;constructor(t,n={}){REr(t),n=n||{},this.options=n,this.pattern=t,this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!n.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!n.nonegate,this.comment=!1,this.empty=!1,this.partial=!!n.partial,this.globSet=[],this.globParts=[],this.set=[],this.make()}debug(...t){}make(){let t=this.pattern,n=this.options;if(!n.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=this.braceExpand(),n.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let i=this.globSet.map(s=>this.slashSplit(s));if(this.options.noglobstar)this.globParts=i;else{for(let s of i){let a;do{a=!1;for(let u=0;u<s.length-1;u++)s[u]==="*"&&s[u-1]==="**"&&(s[u]="**",s[u-1]="*",a=!0)}while(a)}this.globParts=i.map(s=>(s=s.reduce((a,u)=>{let p=a[a.length-1];return u==="**"&&p==="**"?a:u===".."&&p&&p!==".."&&p!=="."&&p!=="**"?(a.pop(),a):(a.push(u),a)},[]),s.length===0?[""]:s))}this.debug(this.pattern,this.globParts);let o=this.globParts.map((s,a,u)=>s.map(p=>this.parse(p)));if(this.debug(this.pattern,o),this.set=o.filter(s=>s.indexOf(!1)===-1),IEr)for(let s=0;s<this.set.length;s++){let a=this.set[s];a[0]===""&&a[1]===""&&this.globParts[s][2]==="?"&&typeof a[3]=="string"&&/^[a-z]:$/i.test(a[3])&&(a[2]="?")}this.debug(this.pattern,this.set)}parseNegate(){if(this.nonegate)return;let t=this.pattern,n=!1,i=0;for(let o=0;o<t.length&&t.charAt(o)==="!";o++)n=!n,i++;i&&(this.pattern=t.slice(i)),this.negate=n}matchOne(t,n,i=!1){let o=this.options;if(IEr){let A=t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),E=n[0]===""&&n[1]===""&&n[2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3]);if(A&&E){let v=t[3],T=n[3];v.toLowerCase()===T.toLowerCase()&&(t[3]=T)}else if(E&&typeof t[0]=="string"){let v=n[3],T=t[0];v.toLowerCase()===T.toLowerCase()&&(n[3]=T,n=n.slice(3))}else if(A&&typeof n[0]=="string"){let v=t[3];v.toLowerCase()===n[0].toLowerCase()&&(n[0]=v,t=t.slice(3))}}this.debug("matchOne",this,{file:t,pattern:n}),this.debug("matchOne",t.length,n.length);for(var s=0,a=0,u=t.length,p=n.length;s<u&&a<p;s++,a++){this.debug("matchOne loop");var c=n[a],l=t[s];if(this.debug(n,c,l),c===!1)return!1;if(c===uF){this.debug("GLOBSTAR",[n,c,l]);var d=s,f=a+1;if(f===p){for(this.debug("** at the end");s<u;s++)if(t[s]==="."||t[s]===".."||!o.dot&&t[s].charAt(0)===".")return!1;return!0}for(;d<u;){var h=t[d];if(this.debug(`
9589
9589
  globstar while`,t,d,n,f,h),this.matchOne(t.slice(d),n.slice(f),i))return this.debug("globstar found match!",d,u,h),!0;if(h==="."||h===".."||!o.dot&&h.charAt(0)==="."){this.debug("dot detected!",t,d,n,f);break}this.debug("globstar swallow a segment, and continue"),d++}return!!(i&&(this.debug(`
9590
9590
  >>> no match, partial?`,t,d,n,f),d===u))}let A;if(typeof c=="string"?(A=l===c,this.debug("string match",c,l,A)):(A=c.test(l),this.debug("pattern match",c,l,A)),!A)return!1}if(s===u&&a===p)return!0;if(s===u)return i;if(a===p)return s===u-1&&t[s]==="";throw new Error("wtf?")}braceExpand(){return gGc(this.pattern,this.options)}parse(t,n){REr(t);let i=this.options;if(t==="**")if(i.noglobstar)t="*";else return uF;if(t==="")return"";let o,s=null;n!==_Er&&((o=t.match(gd1))?s=i.dot?md1:Ad1:(o=t.match(od1))?s=(i.nocase?i.dot?cd1:ud1:i.dot?ad1:sd1)(o[1]):(o=t.match(yd1))?s=(i.nocase?i.dot?Ed1:bd1:i.dot?Cd1:Sd1)(o):(o=t.match(ld1))?s=i.dot?dd1:pd1:(o=t.match(fd1))&&(s=hd1));let a="",u=!1,p=!1,c=[],l=[],d=!1,f=!1,h=-1,A=-1,E,v,T,w=t.charAt(0)===".",D=i.dot||w,k=()=>w?"":D?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",L=V=>V.charAt(0)==="."?"":i.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",q=()=>{if(d){switch(d){case"*":a+=qko,u=!0;break;case"?":a+=Uko,u=!0;break;default:a+="\\"+d;break}this.debug("clearStateChar %j %j",d,a),d=!1}};for(let V=0,W;V<t.length&&(W=t.charAt(V));V++){if(this.debug("%s %s %s %j",t,V,a,W),p){if(W==="/")return!1;lGc[W]&&(a+="\\"),a+=W,p=!1;continue}switch(W){case"/":return!1;case"\\":if(f&&t.charAt(V+1)==="-"){a+=W;continue}q(),p=!0;continue;case"?":case"*":case"+":case"@":case"!":if(this.debug("%s %s %s %j <-- stateChar",t,V,a,W),f){this.debug(" in class"),W==="!"&&V===A+1&&(W="^"),a+=W;continue}this.debug("call clearStateChar %j",d),q(),d=W,i.noext&&q();continue;case"(":{if(f){a+="(";continue}if(!d){a+="\\(";continue}let F={type:d,start:V-1,reStart:a.length,open:cGc[d].open,close:cGc[d].close};this.debug(this.pattern," ",F),c.push(F),a+=F.open,F.start===0&&F.type!=="!"&&(w=!0,a+=L(t.slice(V+1))),this.debug("plType %j %j",d,a),d=!1;continue}case")":{let F=c[c.length-1];if(f||!F){a+="\\)";continue}c.pop(),q(),u=!0,v=F,a+=v.close,v.type==="!"&&l.push(Object.assign(v,{reEnd:a.length}));continue}case"|":{let F=c[c.length-1];if(f||!F){a+="\\|";continue}q(),a+="|",F.start===0&&F.type!=="!"&&(w=!0,a+=L(t.slice(V+1)));continue}case"[":if(q(),f){a+="\\"+W;continue}f=!0,A=V,h=a.length,a+=W;continue;case"]":if(V===A+1||!f){a+="\\"+W;continue}E=t.substring(A+1,V);try{RegExp("["+Bd1(Nd1(E))+"]"),a+=W}catch{a=a.substring(0,h)+"(?:$.)"}u=!0,f=!1;continue;default:q(),lGc[W]&&!(W==="^"&&f)&&(a+="\\"),a+=W;break}}for(f&&(E=t.slice(A+1),T=this.parse(E,_Er),a=a.substring(0,h)+"\\["+T[0],u=u||T[1]),v=c.pop();v;v=c.pop()){let V;V=a.slice(v.reStart+v.open.length),this.debug(this.pattern,"setting tail",a,v),V=V.replace(/((?:\\{2}){0,64})(\\?)\|/g,(F,J,Y)=>(Y||(Y="\\"),J+J+Y+"|")),this.debug(`tail=%j
9591
- %s`,V,V,v,a);let W=v.type==="*"?qko:v.type==="?"?Uko:"\\"+v.type;u=!0,a=a.slice(0,v.reStart)+W+"\\("+V}q(),p&&(a+="\\\\");let G=Rd1[a.charAt(0)];for(let V=l.length-1;V>-1;V--){let W=l[V],F=a.slice(0,W.reStart),J=a.slice(W.reStart,W.reEnd-8),Y=a.slice(W.reEnd),z=a.slice(W.reEnd-8,W.reEnd)+Y,X=F.split(")").length,Z=F.split("(").length-X,re=Y;for(let ee=0;ee<Z;ee++)re=re.replace(/\)[+*?]?/,"");Y=re;let oe=Y===""&&n!==_Er?"(?:$|\\/)":"";a=F+J+Y+oe+z}if(a!==""&&u&&(a="(?=.)"+a),G&&(a=k()+a),n===_Er)return[a,u];if(i.nocase&&!u&&!i.nocaseMagicOnly&&(u=t.toUpperCase()!==t.toLowerCase()),!u)return Pd1(t);let H=i.nocase?"i":"";try{let V=s?{_glob:t,_src:a,test:s}:{_glob:t,_src:a};return Object.assign(new RegExp("^"+a+"$",H),V)}catch(V){return this.debug("invalid regexp",V),new RegExp("$.")}}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let n=this.options,i=n.noglobstar?qko:n.dot?_d1:Id1,o=n.nocase?"i":"",s=t.map(a=>{let u=a.map(p=>typeof p=="string"?Dd1(p):p===uF?uF:p._src);return u.forEach((p,c)=>{let l=u[c+1],d=u[c-1];p!==uF||d===uF||(d===void 0?l!==void 0&&l!==uF?u[c+1]="(?:\\/|"+i+"\\/)?"+l:u[c]=i:l===void 0?u[c-1]=d+"(?:\\/|"+i+")?":l!==uF&&(u[c-1]=d+"(?:\\/|\\/"+i+"\\/)"+l,u[c+1]=uF))}),u.filter(p=>p!==uF).join("/")}).join("|");s="^(?:"+s+")$",this.negate&&(s="^(?!"+s+").*$");try{this.regexp=new RegExp(s,o)}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):IEr&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,n=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&n)return!0;let i=this.options;Fko.sep!=="/"&&(t=t.split(Fko.sep).join("/"));let o=this.slashSplit(t);this.debug(this.pattern,"split",o);let s=this.set;this.debug(this.pattern,"set",s);let a=o[o.length-1];if(!a)for(let u=o.length-2;!a&&u>=0;u--)a=o[u];for(let u=0;u<s.length;u++){let p=s[u],c=o;if(i.matchBase&&p.length===1&&(c=[a]),this.matchOne(c,p,n))return i.flipNegate?!0:!this.negate}return i.flipNegate?!1:this.negate}static defaults(t){return k3.defaults(t).Minimatch}};k3.Minimatch=XJe;var mGc=2,yGc=1,bGc=3,EGc=2,CGc=8,SGc=5,vGc=6,TGc=new RegExp(/([\+]?){([\s\S]+)}([\+](?![\+]))?\s*/g),_Gc=new RegExp(/((\w+):\s*((?:["])((([^\"\+\r\n\[/\\]+))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),IGc=new RegExp(/((\w+):\s*(((?:["])(((?:[^"]|"")*))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),RGc=new RegExp(/((?:[^\+\ \r\n\[\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+)\s*/g),AGc="",ZJe=(r,t)=>{if(t==="*")return r.some(o=>o!=null&&String(o).length>0);let n=r.map(o=>o!=null?String(o).replace(/\//g,AGc):""),i=t.replace(/\//g,AGc);return!!zko(n,i).length};var e$e=Xe("SEARCH"),U52=B.object({include:B.string(),exclude:B.string(),enabled:B.boolean()}),OGc={name:{MatchFunction:ZJe,MatchList:r=>[r.operation.name]},location:{MatchFunction:ZJe,MatchList:r=>[r.operation.locationName]},nodeType:{MatchFunction:ZJe,MatchList:r=>[r.operation.sqlType]},subgraph:{MatchFunction:ZJe,MatchList:r=>[r?.id?.toString(),r.name]},nodeID:{MatchFunction:ZJe,MatchList:r=>[r]}},wGc=r=>{let t=[];return r.forEach((n,i)=>{if(n==="+{"||n==="{"||n==="}"||n==="}+")return;let o=n,s=n.split(""),a=s[s.length-1],u=s[0];a!=="}"&&a!=="+"&&(o=o+r[i+1]),u!=="{"&&u!=="+"&&(o=r[i-1]+o),t.push(o)}),t},MGc=(r,t,n,i=!1)=>{let{steps:o,graphInformation:s,allSubgraphs:a,allStepTypesYAML:u}=n,p={},c=n3()?Date.now():performance.now(),l=r;l||(l=t);let d=l.split(/(\}\+?)\s*(or|OR|\|\|)\s*(\+?\{)/).filter(A=>!(A==="OR"||A==="or"||A==="||")),f=wGc(d);f.length||(f=[t]),e$e.debug("got unions",f,"searchStringTouse",l,"defaultSearchString",t,"steps",o),f.forEach(A=>{let E=A.split(/(\}\+?)\s*(and|AND|\,)\s*(\+?\{)/).filter(k=>!(k==="AND"||k==="and"||k===",")),v=wGc(E),T=[];v.forEach(k=>{let L={};e$e.debug("Got intersection:",k);let q=[...k.matchAll(TGc)];if(e$e.debug("Got matches:",k,q),!q[0])return;let G=q[0][mGc],H={prefix:q[0][yGc]||"",postfix:q[0][bGc]||""};if(G.indexOf(":")>-1){let F=i?IGc:_Gc,J=[...G.trim().matchAll(F)],Y=i?vGc:SGc;J.forEach(z=>{let X=z[EGc],Z=z[CGc]||z[Y];H[X]=Z})}else{let J=[...G.trim().matchAll(RGc)][0];J&&(H.name=J[0])}vM(H);let V=H;e$e.debug("Got groups ",k,V);let W=new Set;if(V.subgraph?Object.values(a).forEach(F=>{let J=OGc.subgraph,Y=J.MatchList(F);if(J.MatchFunction(Y,V.subgraph)){let{steps:X}=F;X.forEach(Z=>{W.add(Z.toString())})}else return}):W=new Set(Object.keys(o)),V.nodeType){let{nodeType:F}=V;if(!u[F]){let J=F;Object.entries(u).forEach(([Y,z])=>{z.name===F&&(J=Y)}),V.nodeType=J}}Object.keys(o).forEach(F=>{if(!V){e$e.emerg("got an unexpected undefined value for match",l,V,k);return}let J=W.has(F);if(Object.entries(V).forEach(([Y,z])=>{let X=o[F];if(Y==="nodeID"&&(X=F),Y==="subgraph"){J=W.has(F);return}let Z=OGc[Y];if(Z){let re=Z.MatchList(X).filter(oe=>oe!=null);J=J&&Z.MatchFunction(re,z)}}),J){if(L[F]=!0,V.prefix&&s){let Y=Dko(s,F,"predecessors");Object.values(Y).forEach(z=>[...z.keys()].forEach(X=>L[X]=!0))}if(V.postfix&&s){let Y=Dko(s,F,"successors");Object.values(Y).forEach(z=>[...z.keys()].forEach(X=>L[X]=!0))}}}),T.push(L)}),T.length||T.push({});let w={};Object.keys(o).forEach(k=>{w[k]=!0});let D=T.reduce((k,L)=>Object.fromEntries(ugc(k,L).map(q=>[q,!0])),w);p={...p,...D}});let h=n3()?Date.now():performance.now();return e$e.debug("Time that search took: ",h-c),p};var OEr=(r,t,n,i=!1)=>{let o=MGc(`${r}`,"{ * }",n,i),s=MGc(`${t}`,"!*",n,i),a=o;return Object.keys(s).forEach(u=>{delete a[u]}),{stepsResult:a}};var xGc=(r,t,n,i)=>{let o=[];return t.forEach(s=>{let a=i[s];if(a){let{name:u}=a,p=`{ subgraph: "${u}" }`;o.push(p)}}),r.forEach(s=>{let a=n[s];if(a){let{locationName:u,name:p}=a.operation,c=`{ location: "${u}" name: "${p}" }`;o.push(c)}}),o};var kd1=Xe("JOBS");var PGc=r=>!r?.hasOwnProperty("includeSelector")||!r?.hasOwnProperty("version"),Qko=(r,t,n)=>{let{steps:i,subgraphs:o,...s}=r,a={...s};if(a.hasOwnProperty("version")||(a.version=i$),a.hasOwnProperty("includeSelector"))return a;a.includeSelector="",a.excludeSelector="";let u=new Set(i),p=new Set(o),d=xGc([...u],[...p].map(f=>`${f}`),n,t).map(f=>`+${f}`).join(" OR ");return a.includeSelector=d,kd1.info("Upgrading job v1 to v2",r,a),a};var NGc=(r,t)=>{let{jobs:n,folders:i,steps:o}=r,s=n[t];return Qko(s,i,o)};var Y52=Xe("PACKAGES_BACKEND");var DGc=(r,t,n)=>{let i=a6o(t)??"",o=r?.config?.entities?.nodeTypes[i];return o||(n.error(`No config found for node type ${t}`),{isDisabled:!1,defaultStorageLocation:null})};var wEr=(r,t={})=>Object.values(r).map(n=>qd1(n)).reduce((n,i)=>{for(let[o,s]of Object.entries(i))n[o]=s;return n},t),qd1=r=>Object.fromEntries(Object.entries(r?.contents?.nodeTypes??{}).map(([t,n])=>{let{id:i,nodeType:o}=Fd1(r.alias,t,r,n);return[i,o]})),Fd1=(r,t,n,i)=>{let o=umr(r,t),{isDisabled:s,defaultStorageLocation:a}=DGc(n,o,Xe("PACKAGES")),u={...ep(i),id:o,isDisabled:s};return u.metadata.defaultStorageLocation=a,{id:o,nodeType:u}};var Ho=bt(Oq());var Ud1=Ho.Record({type:Ho.Unknown,name:Ho.String}),BGc=Ho.Record({locationName:Ho.String,nodeName:Ho.String}),LGc=Ho.Record({sql:Ho.String,success:Ho.Boolean,rows:Ho.Array(Ho.Unknown),fields:Ho.Array(Ud1),error:Ho.Union(Ho.Null,Rdr).optional(),startTime:Ho.Unknown,endTime:Ho.Unknown,status:Ho.String,name:Ho.String,isRunning:Ho.Boolean,exportedRefs:Ho.Array(BGc),invalidExportedRefs:Ho.Array(BGc),queryResultSequence:Ho.Optional(Ho.Unknown),type:Ho.Union(Ho.Literal("sql"),Ho.Literal("sqlTest")).optional(),warehouse:Ho.String.nullable().optional(),queryID:Ho.String.nullable().optional()}),jko=Ho.Record({name:Ho.String,queryResults:Ho.Array(LGc),isRunning:Ho.Boolean,renderQueryResults:Ho.Optional(LGc)}),s62=Ho.Record({runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,name:Ho.String,queryResultSequence:jko,runState:Ho.String}),zd1=Ho.Record({dataResult:Ho.Unknown,name:Ho.String,queryResultSequence:jko,runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,runState:Ho.String,stepRunState:JVe(E3o)}),kGc=SM("RunResultFirestoreValidator",zd1),Qd1=Ho.Record({nodeID:Ho.String,queryResultSequence:jko,runState:Ho.String,hasTestFailures:Ho.Boolean.optional()}),jd1=Ho.Record({runResults:Ho.Record({runStartTime:Ho.Unknown,runEndTime:Ho.Unknown,runFailureReason:Ho.Optional(Ho.String),runType:Ho.String,runStatus:Ho.String,runResults:Ho.Array(Qd1),runID:Ho.Number,environmentID:Ho.String,snowflakeAccount:Ho.String.optional(),snowflakeWarehouse:Ho.String.optional(),jobID:Ho.Number.optional(),hasFailedTest:Ho.Boolean.optional(),runTimeParameters:Ho.Unknown.nullable(),includeNodesSelector:Ho.String.optional(),excludeNodesSelector:Ho.String.optional()})}),MEr=SM("TRunOutput",jd1);var c62=JVe(b3o);var Hd1=["deploy","refresh","rerun","plan"],l62=[...Hd1,"devRun"];var MNe=class{constructor(t,n,i,o){this.allNodes=t;this.renderResults=n;this.extraRefs=i;this.logContext=o;this.phasedRefUsage=n.map("phased ref usage",s=>s.map(a=>a.runDetails.ref_usage))}allNodes;renderResults;extraRefs;logContext;phasedRefUsage;buildPhase(t,n){let i="[DependencyBuilder.buildPhase()]",o=n.keys(),s=Object.keys(this.extraRefs),a=[...new Set([...o,...s])];if(Xe("PIPELINE").appContext(this.logContext,i,"Nodes present in both current-phase data AND extra non-phased (views & advanced deploy) data:",ppo([...o],s)),this.noDependenciesPhases.includes(t))return Object.fromEntries(a.map(u=>[u,[]]));{let u=this.getNodeRefsInPhase(t,a),p=new J4e(Pb(this.allNodes,a));return lv(u,(c,l)=>{let{nodeIDsToAdd:d}=BYe(c,p);return[...new Set(d)].filter(f=>f!==l)})}}build(){return Object.fromEntries([...this.phasedRefUsage.entries()].map(([t,n])=>[t,this.buildPhase(t,n)]))}};var b62=Xe("DEBUG");var xEr=r=>{typeof r.stepCounter=="number"&&(r.stepCounter=`${r.stepCounter}`),typeof r.columnCounter=="number"&&(r.columnCounter=`${r.columnCounter}`)};var Abe=new Date("1980-01-01T00:00:00.000Z"),Vs=(r,t,n)=>{let i=`${r}Entity`;return n||(n=ga(t)),{standard:Mr(i,n),strict:Mr(`${i} (strict)`,t)}};var qGc=r=>{if(Array.isArray(r))for(let t=r.length-1;t>=0;t--)r[t]===void 0&&r.splice(t,1);if(r&&typeof r=="object")for(let t in r)r.hasOwnProperty(t)&&r[t]===void 0&&delete r[t];return[r,!1]},Vd1=(r,t)=>{if(r&&typeof r=="object"){let n=r;if(n.toDate&&(!isNaN(n.seconds)&&!isNaN(n.nanoseconds)||!isNaN(n._seconds)&&!isNaN(n._nanoseconds))){let i=n.toDate();return i.getTime()===Rce.SENTINEL_DATE&&Ml().emerg(`Repository server timestamp sentinel value found in stored data at path ${t}`),[i,!0]}}return[r,!1]},FGc=(r,t)=>r instanceof w4e?[t.getDeleteSentinel(),!0]:r instanceof Date&&r.getTime()===Rce.SENTINEL_DATE?[t.getServerTimestampSentinel(),!0]:[r,!1],xNe=(r,t,n)=>{let[i,o]=t(n,r);if(!o&&typeof i=="object"){if(Array.isArray(i))return i.map(s=>xNe(r,t,s));for(let s in i)i.hasOwnProperty(s)&&(i[s]=xNe(r,t,i[s]))}return i},kRt=class{fromStorage(t,n,i,o,s){try{return this.transformFromStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error transforming repository entity ${n} from storage: ${a}`),a}return i}toStorage(t,n,i,o,s){try{return this.transformToStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error transforming repository entity ${n} to storage ${a}`),a}return i}mergeToStorage(t,n,i,o,s){try{return this.mergeTransformToStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error merge transforming repository entity ${n} to storage ${a}`),a}return i}},Gko=class extends kRt{constructor(n=!1){super();this.preserveID=n}preserveID;transformFromStorage(n,i,o){return"id"in o?o.id!=n&&(Ml().error(`'id' property does not match doc id on doc at path ${i}; doc id: ${n}, value.id: ${o.id}`),o.id=n):o.id=n,"createdAt"in o||(o.createdAt=Abe),"updatedAt"in o||(o.updatedAt=Abe),xNe(i,Vd1,o)}transformToStorage(n,i,o,s){return this.preserveID||delete o.id,xNe(i,a=>{let[u,p]=FGc(a,s);return p?[u,!0]:qGc(u)},o)}mergeTransformToStorage(n,i,o,s){return this.preserveID||delete o.id,xNe(i,a=>{let[u,p]=FGc(a,s);return p?[u,!0]:qGc(u)},o)}},Hko=class extends kRt{constructor(n){super();this.validators=n}validators;transformFromStorage(n,i,o,s,a){let u=this.getValidatorOptions(n,a?.validatorOptions);return a?.enableStrictValidation?this.validators.strict.assert(o,u):this.validators.standard.assert(o,u)}transformToStorage(n,i,o,s,a){let u=this.getValidatorOptions(n,a?.validatorOptions);return a?.enableStrictValidation?this.validators.strict.assert(o,u):this.validators.standard.assert(o,u)}mergeTransformToStorage(n,i,o,s,a){return o}getValidatorOptions(n,i,o=500){let s={...i,statusCode:o};return s.errorMessage||(s.errorMessage=a=>`Found ${a.failures.length} validation failure(s) for ${this.validators.standard.name} ${n}`),s}},ku=(r,t,n)=>{let i=[new Gko(n),new Hko(r)];return t&&i.unshift(t),new Vko(...i)},Vko=class{transforms;constructor(...t){this.transforms=t}fromStorage(t,n,i,o,s){return this.transforms.reduce((a,u)=>u.fromStorage(t,n,a,o,s),i)}toStorage(t,n,i,o,s){return this.transforms.reduceRight((a,u)=>u.toStorage(t,n,a,o,s),i)}mergeToStorage(t,n,i,o,s){return this.transforms.reduceRight((a,u)=>u.mergeToStorage(t,n,a,o,s),i)}},q3=class extends kRt{transformToStorage(t,n,i){return i}mergeTransformToStorage(t,n,i){return i}};var UGc=r=>!!r&&typeof r=="object"&&!Array.isArray(r),t$e=r=>UGc(r)&&!(r instanceof Date)&&!(r instanceof RegExp),$G=r=>{if(typeof r=="string")return r;if(UGc(r)&&r.constructor&&typeof r.constructor.name=="string")return`[class ${r.constructor.name}]`;if(r instanceof Date)return`[date ${r.toISOString()}]`;if(r instanceof RegExp)return`[regexp ${r.toString()}]`;if(typeof r=="function")return`[function ${r.name}]`;try{return JSON.stringify(r)}catch{return"Error: could not stringify unknown value"}},Wko=r=>r==null,qRt=(r,t,n,i)=>{t.filter((o,s)=>t$e(o)?!0:(n.logError(`Invalid ${r} item detected at index ${s}: ${$G(o)}`),n.logPatch(`Removed invalid ${r} item at index ${s}`),!1)).forEach(i)},cF=(r,t,n)=>{r[t]=n},mbe=(r,t)=>{delete r[t]},Yko=(r,t,n)=>{let i=new Kko(r,Xe("FIREBASE"),t),{logError:o,logPatch:s,report:a}=i,u=()=>(a(),n);if(!t$e(n))return u();let p=n;if([["locationName",!p.locationName&&typeof p.locationName!="string"||typeof p.locationName!="string"],["description",typeof p.description!="string"]].forEach(([c,l])=>{l&&(s(`Set non-string property ${c} from ${$G(p[c])} to ""`),cF(p,c,""))}),["dependencies","isDataVault","locationID"].forEach(c=>{c in p&&(s(`Removed deprecated field ${c}`),mbe(p,c))}),p.type==="sql")s("-- data.type is sql --"),Wd1(r,p,i);else if(p.type==="sourceInput")s("-- data.type is sourceInput --"),Kd1(r,p,i);else return o(`Data type is of invalid type ${$G(p.type)}`),u();return p.version!==e$&&(s(`Set version ${$G(p.version)} to ${e$}`),cF(p,"version",e$)),u()},Wd1=(r,t,n)=>{let{logError:i,logPatch:o}=n;if(t.isMultisource===void 0&&(o("Set missing isMultisource to false"),cF(t,"isMultisource",!1)),t$e(t.metadata)){let s=t.metadata;if(s.appliedNodeTests===null&&(o("Set metadata.appliedNodeTests from null to []"),cF(s,"appliedNodeTests",[])),!Array.isArray(s.sourceMapping)||!s.sourceMapping.length){o("Set non-array or empty metadata.sourceMapping to [ basicMapping ]");let a;typeof t.name=="string"?a=t.name:(o("Data has no name value, setting sourceMapping.name to empty string"),a=""),cF(s,"sourceMapping",[{name:a,join:{joinCondition:""},dependencies:[],noLinkRefs:[],aliases:{}}])}else qRt("sourceMapping",s.sourceMapping,n,(a,u)=>{let p=a;if(typeof p.join=="string"){let c={joinCondition:""};o(`Setting invalid string value metadata.sourceMapping[${u}].join to object: ${$G(c)}`),cF(p,"join",c)}if(p.name===void 0){let c=p.join?.name??"";o(`Set missing metadata.sourceMapping[${u}].name to "${c}"`),cF(p,"name",c),c||i(`metadata.sourceMapping[${u}].name is an empty string`)}Array.isArray(p.dependencies)&&qRt("sourceMapping dependency",p.dependencies,n,(c,l)=>{let d=c;for(let f of["locationName","nodeName"])Wko(d[f])&&(o(`Set metadata.sourceMapping[${u}].dependencies[${l}].${f} from ${$G(d[f])} to ""`),cF(d,f,""))})});zGc(r,s.columns,n)}if(t.config&&typeof t.config=="object")for(let[s,a]of Object.entries(t.config))a===null&&(o(`Removing null config property "${s}"`),mbe(t.config,s))},Kd1=(r,t,n)=>{let{logPatch:i,logError:o}=n;if(t.dataset!==void 0&&(i("Removed deprecated v0 property dataset"),mbe(t,"dataset")),t.table!==void 0&&(t.table!==t.name&&o(`source data properties 'table' and 'name' are different for source node ${r}, table: ${t.table}, name: ${t.name}`),i("Removed deprecated v0 property table"),mbe(t,"table")),t$e(t.metadata)){let s=t.metadata;Array.isArray(s.columns)&&(s.columns.length&&zGc(r,s.columns,n),Object.keys(s).length>1&&(i(`Removed deprecated metadata properties, keeping only columns. Was: ${$G(s)}`),cF(t,"metadata",{columns:s.columns})))}},zGc=(r,t,n)=>{let{logPatch:i}=n;Array.isArray(t)&&qRt("column",t,n,(o,s)=>{let a=o;if(["ghostRecordValue","descendedFrom","hashColumns","columnsForHash"].forEach(c=>{a.hasOwnProperty(c)&&(i(`Removed deprecated property '${c}' from metadata.columns[${s}]`),mbe(a,c))}),t$e(a.hashDetails)){let c=a.hashDetails;c.hashType&&(i(`Removed deprecated property 'hashType' from metadata.columns[${s}].hashDetails`),mbe(c,"hashType")),c.hubHashes&&(i(`Removed deprecated property 'hubHashes' from metadata.columns[${s}].hashDetails`),mbe(c,"hubHashes"))}[["appliedColumnTests",a.appliedColumnTests===null],["config",a.config===null],["hashDetails",typeof a.hashDetails=="string"]].forEach(([c,l])=>{l&&(i(`Deleted metadata.columns[${s}].${c} with invalid value ${$G(a[c])}`),mbe(a,c))}),[["dataType",typeof a.dataType!="string"],["transform",a.transform===null]].forEach(([c,l])=>{l&&(i(`Set ${c} from ${$G(a[c])} to "" in metadata.columns[${s}]`),cF(a,c,""))});let u=a.hashedColumns;if(Array.isArray(u))for(let c of u)xEr(c);let p=a.columnReference;if(t$e(p)){xEr(p);let c=p;Wko(c.stepCounter)&&(i(`Set metadata.columns[${s}].columnReference.stepCounter from ${$G(c.stepCounter)} to ${r}`),cF(c,"stepCounter",r))}Array.isArray(a.sourceColumnReferences)&&qRt("sourceColumnReference",a.sourceColumnReferences,n,(c,l)=>{let d=c;Array.isArray(d.columnReferences)&&qRt("columnReference",d.columnReferences,n,(f,h)=>{xEr(f);let A=f;Wko(A.stepCounter)&&(i(`Set invalid metadata.columns[${s}].sourceColumnReferences[${l}].columnReferences[${h}].stepCounter to "" from ${$G(r)}`),cF(A,"stepCounter",""))})})})},Kko=class{constructor(t,n,i){this.id=t;this.logger=n;this.path=i}id;logger;path;patchMessages=[];errorMessages=[];logPatch=t=>{this.patchMessages.push(t)};logError=t=>{this.errorMessages.push(t)};reportErrors=()=>{this.errorMessages.length&&this.logger.error(`Error patching node data with id ${this.id} at path ${this.path}`,this.errorMessages)};reportPatches=()=>{this.patchMessages.length&&this.logger.debug(`Patched node data with id ${this.id} at path ${this.path}`,this.patchMessages)};report=()=>{this.reportErrors(),this.reportPatches()}},PEr=class extends q3{transformFromStorage(t,n,i){return Yko(t,n,i)}};var aB2=Xe("FIREBASE");var uB2=Xe("STEPS"),cB2=Xe("METADATA_OPERATIONS");var GGc=(r,t)=>t[r].runState==="running";var HGc=r=>(Nm("STEPS",!!r,`Error converting API refs: argument apiRefLinks is ${r}.`),r.map(t=>({locationName:t.location_name,nodeName:t.node_name})));var VGc=r=>r?.deployEnabled??!0,Jko=r=>({nodeName:r,columns:new Set});var QGc=(r,t)=>r?r.every((n,i)=>n.deref()===t[i]):!1,jGc={},WGc=(r,t)=>{let n={};return W4e(r,(i,o)=>{let s=jGc[i],a=t[i];if(!a)throw new nt(`Dependency/ref data for node ID "${i}" was not found`,`Dependency/ref data for node ID "${i}" not found in "GetNodesWithMissingColumnDependencies" (known IDs: ${JSON.stringify(t)})`);let{dependencies:u,noLinkDependencies:p}=a,c=o.operation.metadata.columns,d=s?.nodeData.deref()===o,f=QGc(s?.dependencies,u),h=QGc(s?.noLinkDependencies,p);if(d&&f&&h&&s){s.result&&(n[i]=s.result);return}let A=new Set,E=new Set,v=new Set;c.forEach(w=>{w.sourceColumnReferences?.forEach(D=>{D.transform.trim().length||D.columnReferences?.forEach(k=>{let{stepCounter:L,columnCounter:q}=k;if(L==="0"||q==="0"||A.has(L))return;E.has(L)&&v.add(w.name);let G=r[L];if(G){let{locationName:H,name:V}=G.operation,W=u.some(J=>J.locationName===H&&J.nodeName===V),F=p.some(J=>J.locationName===H&&J.nodeName===V);W||F?A.add(L):(E.add(L),n[i]||(n[i]=Jko(o.operation.name)),v.add(w.name))}})})});let T=v.size>0?{columns:v,nodeName:o.operation.name}:void 0;T&&(n[i]=T),jGc[i]={dependencies:u.map(w=>new WeakRef(w)),noLinkDependencies:p.map(w=>new WeakRef(w)),nodeData:new WeakRef(o),result:T}}),n};var ybe=class extends MNe{noDependenciesPhases=["deletedTable"];getNodeRefsInPhase(t,n){return Object.fromEntries(n.map(i=>{let o,s=this.extraRefs[i];s?o=[s]:o=this.phasedRefUsage.get(t,i);let a=o.map(({ref:u,ref_no_link:p})=>HGc([...u,...p]));return[i,[].concat(...a)]}))}};var r$e=class extends MNe{noDependenciesPhases=[];getNodeRefsInPhase(t,n){let i=Pb(this.allNodes,...n);return lv(i,o=>{if(Gye(o.operation))return[];let{sourceMapping:s}=o.operation.metadata;if(!s?.length)return[];let a=s.map(({dependencies:u})=>u);return[].concat(...a)})}};var FRt=async(r,t)=>{let{attempts:n,tags:i,waitSeconds:o}=t,s=Ml().child({retryOptions:{maxAttempts:n,waitSeconds:o},tags:["[withRetries]",...i]});LE(n>=2,`Retry attempts value must be at least '2', but was '${n}'`,s);try{let a=await r();return s.debug("Operation succeeded without retrying"),a}catch(a){s.error(`Operation initial attempt failed; retrying. Error: ${a}`);let u,p=n-1;do{p--,await new Promise(c=>setTimeout(c,o*(n-p)*1e3));try{let c=await r();return s.info(`Operation succeeded on retry (attempt ${n-p})`),c}catch(c){s.error(`Operation failed on retry (attempt ${n-p}). Error: ${c}`),u=c}}while(p);throw s.error("Exhausted all retry attempts; exiting"),u}};var PL=bt(Oq()),Xd1=PL.String,Zd1=PL.Record({locationName:PL.String,database:PL.String,schema:PL.String}),OB2=PL.Dictionary(Zd1,Xd1);var wB2=PL.Record({seconds:PL.Number,nanoseconds:PL.Number});var e01="Making metadata updates",KGc="Deleting metadata for source input";function n$e(r,t){let n=[];for(let i of r){let o=i.compiledSQL?UYe(i.compiledSQL):[];if(o.length===0)t&&n.push({name:t,sql:"",type:"sql",continueOnFailure:!1,parsedStage:null});else for(let s of o)n.push({name:s.name,sql:s.code,type:s.type,continueOnFailure:s.continueOnFailure,parsedStage:s})}return n}function NEr(r,t){return r==="deletedTable"&&t?KGc:e01}var XG=class extends nt{constructor(n,i){super(i,`Failed node ${n}: ${i}`);this.nodeID=n}nodeID};var JRt=bt(Oq()),Xh1=bt(u$e()),R82=(0,JRt.Record)({version:JRt.String,hash:JRt.String}),Zh1=()=>{let r="7.39.3",t="a8b00012437c0ab2897e1d1beabee7b12ebbb01b";return r&&t?{version:r,hash:t}:null},Mv=Zh1();var bbe=class extends nt{constructor(n){super(`Run ${n} canceled by user`);this.runID=n}runID},c$e=class extends nt{constructor(n){super('Test failed with "continue on failure" set to false');this.result=n}result};var GVc=(r,t,n)=>{switch(r){case"skipped":return"Skipped";case"error":return"Error";case"complete":switch(n){case"create":return t?"Validated":"Created";case"run":return t?"Validated":"DataLoaded";default:return"None"}default:return"None"}},HVc=r=>typeof r=="object"&&r instanceof c$e,LNe=r=>typeof r=="object"&&(r instanceof NA||r instanceof bbe),$Rt=r=>typeof r=="object"&&r instanceof aF&&r.isCancel(),XRt=r=>typeof r=="object"&&r instanceof hX&&r.isCancel(),b9o=r=>LNe(r)||$Rt(r)||XRt(r);var VVc=5e5,WVc=500,Ebe=class r{constructor(t,n,i,o,s){this.state=t;this.repository=n;this.logContext=i;this.operationType=o;this.analyticsCollector=s}state;repository;logContext;operationType;stepsInitialized=null;runResults={};flusher=null;wasCanceled=!1;nodeStageIndexTracker=new Map;analyticsCollector;get teamID(){return this.logContext.orgID}get runID(){return this.logContext.runID}get envID(){return this.logContext.workspaceID}GetLogContext=t=>({...this.logContext,nodeID:t});async runIsCanceled(){if(!this.repository)return!1;if(this.wasCanceled)return!0;try{let t=!!(await this.getRepositoryForRun().fetch({pendingWritesTimeoutMs:100})).runDetails.canceled;return t&&(this.wasCanceled=!0),t}catch(t){if(BE(t)){if(t instanceof ONe)return!1;if(t instanceof Nu)return!1}throw t}}async throwIfRunCanceled(){if(await this.runIsCanceled())throw new bbe(this.runID)}updateNodeLocalRunResult({stepID:t,isPreview:n,runExecutionSequenceID:i},o){let s=this.runResults[t];s?(s.runState=o,s.queryResultSequence.isRunning=o==="running",s.stepRunState=this.getStepRunState(o,n),i!==void 0&&(s.runExecutionSequenceID=i),(o==="canceled"||o==="skipped"||o==="error")&&s.queryResultSequence.queryResults.forEach(a=>{!a.isRunning&&a.status==="Queued"&&(a.status="Canceled")})):this.Logger.errorContext(this.GetLogContext(t),"EventHandler updateNodeLocalRunResult: missing expected local run result for node",t)}getBulkSkipHandler=()=>async t=>{if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let[o,s]of Object.entries(t))if(this.runResults[o]){let a=i.get(o);this.updateNodeLocalRunResult({stepID:o,isPreview:!1,runExecutionSequenceID:s},"skipped");let u={...r.truncateRunResult(this.runResults[o]),version:2};await n.save(a,u)}await n.commit()};getCancelNodeHandler=()=>async t=>{try{if(!this.repository)return;if(this.runResults[t]){this.updateNodeLocalRunResult({stepID:t,isPreview:!1},"canceled");let i=this.getRepositoryForRun().runResults.get(t),o={...r.truncateRunResult(this.runResults[t]),version:2};await i.save(o)}else this.Logger.errorContext(this.GetLogContext(t),"EventHandler getCancelNodeHandler: missing expected local run result for node",t)}catch(n){this.Logger.errorContext(this.logContext,`Error canceling node ${t}`,n)}};async repositoryUpdateRunStatus({expectedStatus:t,newStatus:n}){if(!this.repository)return;let i=this.getRepositoryForRun();try{let o=await i.fetch();fh("RUNNER_BACKEND",t===o.runStatus,this.logContext,`EventHandler.repositoryUpdateRunStatus found unexpected run status - expected: ${t} / actual: ${o.runStatus}`)}catch(o){this.Logger.alertContext(this.logContext,"Error fetching runInfo",o)}await i.merge({runStatus:n})}async repositoryStampExecutorInfo(t){if(this.repository)try{await this.getRepositoryForRun().merge({platform:t,...Mv?{softwareVersion:Mv.version}:{}})}catch(n){this.Logger.errorContext(this.logContext,"[EventHandler.repositoryStampExecutorInfo] Error stamping executor info. Cannot update run document version/platform.",n)}}async repositoryUpdateRenderingProgress(t){if(this.repository)try{await this.getRepositoryForRun().merge({renderingProgress:{totalNodes:t.totalNodes,completedNodes:t.completedNodes}})}catch(n){this.Logger.errorContext(this.logContext,"[EventHandler.repositoryUpdateRenderingProgress] Error updating rendering progress. Cannot update run document renderingProgress.",n)}}getRepositoryRunsCollection(){if(!this.repository)throw new nt("No repository to get runs collection for!");let t=this.repository.orgs.get(this.logContext.orgID);return this.runLevel==="orgRuns"?t.runs:t.devRuns}getRepositoryForRun(){return this.getRepositoryRunsCollection().get(this.runID)}formatError=(t,n=null,i=null,o=!1)=>{let s=ha(t.error).error,a="";return t.error&&typeof t.error=="object"&&!(t.error instanceof Error)&&"runDetails"in t.error&&typeof t.error.runDetails=="object"&&(a=t.error?.runDetails?.compiledSQL??""),t.templateString&&(a=t.templateString),{success:!1,error:{errorString:s.errorString??"",errorDetail:s.errorDetail??""},rows:[],fields:[],name:"",exportedRefs:[],invalidExportedRefs:[],status:o?"Canceled":"Failure",sql:a??"",startTime:t.startTime,endTime:new Date,isRunning:!1,type:"sql",queryID:n,warehouse:i}};populateRunResults(t,n){let i="[EventHandler.populateRunResults()]",o=t.length+1;for(let s of t){let u=h1(s,this.state.nodes,`${i} state.nodes`).operation.name;this.runResults[s]={name:u,runExecutionSequenceID:o,dataResult:null,runState:n,stepRunState:"None",queryResultSequence:{name:u,queryResults:[],isRunning:!1},runResultVersion:2}}}async bulkSetRunResults(t){if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let o of t){let s=this.runResults[o];if(!s)throw new nt(`Run result for node ${o} does not exist for run ${this.runID}`);let a={...s,name:s.queryResultSequence.name,runExecutionSequenceID:s.runExecutionSequenceID,version:2},u=i.get(o);await n.save(u,a)}await n.commit()}async initializeRunResults(t,n="queued"){this.stepsInitialized=[...t],this.populateRunResults(t,n),await this.bulkSetRunResults(t)}setFlusher(t){this.flusher=t,t.startTimer()}async disposeFlusher(){await this.flusher?.stopAndFlush()}async populatePlaceholderStages(t,n){let i=new Set,o=new Set(t.keys());for(let s of n){if(!o.has(s))continue;let a=t.getPhaseItems(s);for(let[u,p]of a.entries()){let c=h1(u,this.runResults,"populateQueuedStages: this.runResults"),l=this.state.nodes[u],d=l?YP(l,void 0):!1,f=n$e(p,this.getNameForStageWithoutSQL(s,d));for(let h of f)c.queryResultSequence.queryResults.push(this.createQueuedStage(h));f.length>0&&!i.has(u)&&(i.add(u),this.nodeStageIndexTracker.set(u,0))}}await this.bulkSetQueuedStageResults(i)}createQueuedStage({name:t,sql:n,type:i}){return{name:t,status:"Queued",success:!0,sql:n,rows:[],fields:[],startTime:new Date,endTime:new Date,isRunning:!1,exportedRefs:[],invalidExportedRefs:[],type:i}}async bulkSetQueuedStageResults(t){if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let o of t){let s=this.runResults[o];if(!s)continue;let a=i.get(o);await n.save(a,r.buildRunResultEntitySave(s))}await n.commit()}formatErrorToResult(t,n){let i=null,o=null;return typeof t.error=="object"&&(i=t.error.queryID||null,o=t.error.warehouse||null),{...this.formatError(t,i,o,n),name:t.stageName,stageExecutionStartTime:t.stageExecutionStartTime,stageExecutionEndTime:t.stageExecutionEndTime}}ensureHasQueryResult(t){if(fh("DEPLOY",!!t.queryResult,this.GetLogContext(t.stepID),"query result should always be returned for stage execution"),!t.queryResult)throw new Error("Got an empty query result for stage execution")}updateStageResultAtTrackedIndex=(t,n)=>{let o=h1(t,this.runResults,"[EventHandler.setLastQueryResult()]").queryResultSequence.queryResults,s=this.getCurrentStageIndex(t);if(s<0||s>=o.length)throw this.Logger.errorContext(this.GetLogContext(t),"[EventHandler.setLastQueryResult] stage index out of bounds",{targetIndex:s,queryResultsLength:o.length,resultName:n.name}),new nt(`Stage index ${s} out of bounds (length: ${o.length}) for node ${t}`);o[s]=n};async dispatchQueryFailure(t,n){let i=this.formatErrorToResult(t,n);return this.Logger.errorContext(this.GetLogContext(t.stepID),"failed to execute run sql",n?"- canceled":"- errored",t.error,"stack: ",t.error.stack||"<none found>"),this.updateStageResultAtTrackedIndex(t.stepID,i),{error:i.error}}getSingleStepData(t,n){let i=this.state.nodes[n];if(i)return i;let o=`(${this.runTypeName}) EventHandler: Could not get step data for step: ${n}`;throw this.Logger.errorContext(this.GetLogContext(n),o,n),new nt(o)}getUnrunSteps(){let t={},n=this.state.nodes,i=this.runResults;if(n&&this.stepsInitialized)for(let o of this.stepsInitialized){let s=i[o];if(s){let{runState:a}=s;(a==="waiting"||a==="queued")&&(n[o]?t[o]=0:this.Logger.alertContext(this.logContext,"Node ID from initialization not found in steps data",o))}else this.Logger.alertContext(this.logContext,"Node ID from initialization not found in run results",o)}return t}getStepContext=(t,n,i,o)=>{let s=this.getSingleStepData(t,n),{locationName:a}=s.operation,{database:u}=this.state.mappings[a]?.mappingDefinitions[this.state.currentWorkspace]??{},p=YP(s,void 0),c=s.operation.name;return{startTime:new Date,stepID:n,stepName:c,runExecutionSequenceID:i,phase:t,isPreview:o,isSource:p,database:u??""}};convertIQueryToCompletedQueryResult(t){return{...t,startTime:OPo(t.startTime),endTime:OPo(t.endTime)}}getCurrentStageIndex(t){let n=this.nodeStageIndexTracker.get(t);if(n===void 0)throw new nt(`[EventHandler.getCurrentStageIndex] Node ${t} not in stage tracker. Was populateQueuedStages called for this node?`);return n}advanceToNextStage(t){let n=this.getCurrentStageIndex(t);this.nodeStageIndexTracker.set(t,n+1)}getQueryResultForUpdateSuccess(t){return{...this.convertIQueryToCompletedQueryResult(t.queryResult),name:t.stageName,stageExecutionStartTime:t.stageExecutionStartTime,stageExecutionEndTime:t.stageExecutionEndTime}}getStepRunState(t,n){return GVc(t,n,this.operationType)}async updateRunResult(t){if(!this.repository)return;let n=this.runResults[t];if(!n)throw new nt(`[EventHandler.updateRunResult()] run result for node ${t} does not exist for run ${this.runID}`);if(this.flusher)this.flusher.markDirty(t);else{let i=r.buildRunResultEntitySave(n);this.Logger.debugContext(this.GetLogContext(t),"updating run result",i),await this.getRepositoryForRun().runResults.get(t).save(i)}}isFinalRunForStep(t){return!0}async beforePhaseExecution(t,n){}async afterPhaseExecution(t){}async beforeStepExecution(t){this.runResults[t.stepID]&&(this.runResults[t.stepID].runExecutionSequenceID=t.runExecutionSequenceID),this.updateNodeLocalRunResult(t,"running"),await this.updateRunResult(t.stepID)}async afterFinalRunSuccessForNode(t){return Promise.resolve()}async afterStepExecutionSuccess(t){this.isFinalRunForStep(t)?(this.updateNodeLocalRunResult(t,"complete"),await this.afterFinalRunSuccessForNode(t)):this.updateNodeLocalRunResult(t,"waiting"),await this.updateRunResult(t.stepID)}async afterStepExecutionFailure(t){let n=await this.isCoalesceInitiatedCancel(t.error);this.markUnexecutedStagesAsCanceled(t.stepID),this.updateNodeLocalRunResult(t,n?"canceled":"error");try{this.flusher?await this.flusher.flushOne(t.stepID):await this.updateRunResult(t.stepID)}catch(i){this.Logger.emergContext(this.GetLogContext(t.stepID),`Error in firebaseUpdateStepResult for stepCounter:${t.stepID}:`,i)}}markUnexecutedStagesAsCanceled(t){let n=this.runResults[t];if(n)for(let i of n.queryResultSequence.queryResults)"status"in i&&i.status==="Queued"&&(i.status="Canceled")}sanityCheckContext(t){if(!t.stageType)throw this.Logger.emergContext(this.logContext,`No stage type on this ${this.runTypeName}!`,t),new Error(`Internal critical error: no stage type on this ${this.runTypeName}!`)}async beforeStageExecution(t){this.sanityCheckContext(t);let n=this.runResults[t.stepID];if(n){let i=n.queryResultSequence.queryResults,o=this.getCurrentStageIndex(t.stepID),s=i[o];if(!s||!("status"in s)||s.status!=="Queued"){let a=s&&"status"in s?s.status:"no-status";throw new nt(`[EventHandler.beforeStageExecution] Expected queued placeholder at index ${o} for node ${t.stepID}, but found: ${s?`status=${a}`:"undefined"}`)}s.status="Running",s.startTime=new Date,s.endTime=s.startTime,await this.updateRunResult(t.stepID)}}async updateRunWithHeartbeat(t){await this.getRepositoryForRun().updateHeartbeat(t)}async afterStageExecutionSuccess(t){let n="[EventHandler.afterStageExecutionSuccess()]";if(this.sanityCheckContext(t),!t.queryResult){let i="Got an empty query result for stage execution - query result should always be returned!";throw this.Logger.alertContext(this.GetLogContext(t.stepID),n,i),new nt(i)}if(t.stageExecutionStartTime&&t.stageExecutionEndTime){let i=t.stageExecutionEndTime.getTime()-t.stageExecutionStartTime.getTime();this.analyticsCollector.addQueryTiming(t.stepID,t.stageName,i,!0,t.stageExecutionStartTime)}if(EIt(t.queryResult)&&!t.queryResult.success){await this.updateRunWithHeartbeat({hasTestFailures:!0});let i=this.runResults[t.stepID];i&&(i.hasTestFailures=!0)}this.updateStageResultAtTrackedIndex(t.stepID,this.getQueryResultForUpdateSuccess(t)),await this.updateRunResult(t.stepID),this.advanceToNextStage(t.stepID)}async afterStageExecutionFailure(t){if(this.sanityCheckContext(t),t.stageExecutionStartTime&&t.stageExecutionEndTime){let o=t.stageExecutionEndTime.getTime()-t.stageExecutionStartTime.getTime();this.analyticsCollector.addQueryTiming(t.stepID,t.stageName,o,!1,t.stageExecutionStartTime)}let n=await this.isCoalesceInitiatedCancel(t.error),i=await this.dispatchQueryFailure(t,n);throw this.flusher?await this.flusher.flushOne(t.stepID):await this.updateRunResult(t.stepID),this.advanceToNextStage(t.stepID),n?t.error:i}async isCoalesceInitiatedCancel(t){return LNe(t)?!0:$Rt(t)?this.runIsCanceled():XRt(t)?this.runIsCanceled():!1}static truncateQueryResult(t,n=VVc,i=WVc){let o=t.sql,s=t.rows,a,u;if(o){let p=new TextEncoder,c=new TextDecoder("utf8"),l=p.encode(o);if(l.length>n){let d=c.decode(l.slice(0,n));d.slice(-1)==="\uFFFD"&&(d=d.slice(0,-1)),a=`${d}...data truncated`}}return s?.length>i&&(u=s.slice(0,i),u.push({values:[`${s.length-i} rows truncated`]})),a||u?{...t,sql:a??o,rows:u??s}:t}static buildRunResultEntitySave(t){return{...r.truncateRunResult(t),name:t.queryResultSequence.name,runExecutionSequenceID:t.runExecutionSequenceID,version:2}}static truncateRunResult(t){let n=(t.dataResult?.sql?1:0)+(t.queryResultSequence?.renderQueryResults?.sql?1:0)+(t.queryResultSequence?.queryResults?.length??0),i=(t.dataResult?.rows?.length?1:0)+(t.queryResultSequence?.renderQueryResults?.rows?.length?1:0)+(t.queryResultSequence?.queryResults?.reduce((p,c)=>p+c?.rows?.length?1:0,0)??0);if(n===0&&i===0)return t;let o=Math.trunc(VVc/n)-100,s=WVc/(i??1),a={...t};t.dataResult?.sql&&(a.dataResult=r.truncateQueryResult(t.dataResult,o,s)??null);let u=t.queryResultSequence;return u&&(a.queryResultSequence={...u,queryResults:u.queryResults?.map(p=>r.truncateQueryResult(p,o,s))},u.renderQueryResults&&(a.queryResultSequence.renderQueryResults=r.truncateQueryResult(u.renderQueryResults,o,s))),a}};var ZRt=class extends Ebe{constructor(n,i,o,s,a){super(n,i,o,"create",a);this.phasedNodeData=s}phasedNodeData;getNameForStageWithoutSQL=(n,i)=>NEr(n,i);getNodeDataForUpdate=n=>{let i=this.getSingleStepData(n.phase,n.stepID),o=i.operation.locationName,s=$q(this.state.mappings,this.envID),a=this.GetLogContext(n.stepID),u;try{let p=s?.[o]?.database??i.operation.database,c=s?.[o]?.schema??i.operation.schema;return u={...i.operation,metadata:{...i.operation.metadata,columns:i.operation.metadata.columns.map(l=>({...l}))},database:p,schema:c,version:1,id:n.stepID,deployEnabled:!0},this.Logger.infoContext(a,"newStepData:",u,"stepCounter:",n.stepID),Egc("(Logging Only) Compare locations from context and workspace",a,()=>{let l=$q(this.state.mappings||{},this.state.currentWorkspace);fh("DEPLOY",z1e(l[o],s[o]),a,`Location data for location ${o} for node ${i.operation.name} with id ${n.stepID} differs between data from context and data from workspace.`,"locationsFromWorkspace:",l,"locationsFromContext:",s)}),u}catch(p){let c=u?u.name:i.operation.name,l=`Error attempting to update the database/schema on deployed nodeID ${n.stepID}: ${c}`;throw this.Logger.emergContext(a,l,"locations:",s,"error:",p),new XG(n.stepID,l)}};async updateEnvironmentNodeMetadata(n){if(!this.repository)return;let i=this.repository.org(this.teamID).workspace(+this.envID).nodes.get(n.stepID);if(n.phase==="deletedTable")n.stepID in this.phasedNodeData.addedTable||await i.delete();else{let o=this.getNodeDataForUpdate(n);await i.save(o)}}isFinalRunForStep(n){let i=[];return n.phase==="deletedTable"&&(i.push(this.phasedNodeData.alteredTable),i.push(this.phasedNodeData.addedTable)),n.phase==="alteredTable"&&i.push(this.phasedNodeData.addedTable),!i.some(o=>n.stepID in o)}async afterFinalRunSuccessForNode(n){try{await this.updateEnvironmentNodeMetadata(n)}catch(i){let o=this.GetLogContext(n.stepID);this.Logger.errorContext(o,"Error updating node metadata -- nodeID:",n.stepID,"error:",i);let s=HVe(i),a="unknown location";try{a=this.getSingleStepData(n.phase,n.stepID).operation.locationName}catch(u){this.Logger.errorContext(o,`Error getting location name for node ${n.stepName} (${n.stepID}):`,u)}throw new XG(n.stepID,`Failed to update node metadata for ${n.stepName} (${a}): ${s}`)}}};var KVc=(r,t)=>{let n=new Set(t);return n.delete(r),Array.from(n)},HEr=async(r,t,n)=>{if(!t)throw new nt(`Cannot get deploy run info since workspace ${r} has no currently running jobs`);if(t.length)return(await n.selectInBatches("id","in",t,[["runType","==","deploy"],["runStatus","==","running"]]))[0]};var VEr="No SQL to execute";var eOt=class extends Ebe{constructor(t,n,i,o){super(t,n,i,"run",o)}async initializeRunResults(t){await super.initializeRunResults(t,"waiting")}getNameForStageWithoutSQL=()=>VEr};var WEr=class{constructor(t,n,i,o,s,a,u){this.repository=t;this.getRunRepository=n;this.buildEntitySave=i;this.runResults=o;this.logger=s;this.logContext=a;this.flushIntervalMs=u?.flushIntervalMs??3e3,this.flushThreshold=u?.flushThreshold??50}repository;getRunRepository;buildEntitySave;runResults;logger;logContext;dirtyNodes=new Set;timer=null;activeFlush=null;flushedDuringBatch=new Set;flushIntervalMs;flushThreshold;totalFlushes=0;totalNodeWrites=0;totalImmediateWrites=0;timerFlushes=0;thresholdFlushes=0;slowCommits=0;tag="[RunResultFlusher]";markDirty(t){this.dirtyNodes.add(t),this.dirtyNodes.size>=this.flushThreshold&&this.flush("threshold").catch(n=>{this.logger.errorContext(this.logContext,`${this.tag} threshold-triggered flush error`,n)})}async flush(t="dispose"){if(this.activeFlush||this.dirtyNodes.size===0){this.logger.debugContext(this.logContext,`${this.tag} flush skipped (activeFlush=${!!this.activeFlush}, dirtySetEmpty=${this.dirtyNodes.size===0}, trigger=${t})`);return}let n=new Set(this.dirtyNodes);this.dirtyNodes.clear(),this.activeFlush=this.doFlush(n,t);try{await this.activeFlush}finally{this.activeFlush=null}}async doFlush(t,n){try{let i=this.repository.batch();for(let a of t){let u=this.runResults[a];if(!u){this.logger.warnContext(this.logContext,`${this.tag} node ${a} no longer has a run result, skipping write`);continue}let p=this.buildEntitySave(u),c=this.getRunRepository().runResults.get(a);await i.save(c,p)}let o=Date.now();await i.commit();let s=Date.now()-o;if(this.flushedDuringBatch.size>0){let a=this.getRunRepository().runResults;for(let u of this.flushedDuringBatch)if(t.has(u)){let p=this.runResults[u];p&&await a.get(u).save(this.buildEntitySave(p))}this.flushedDuringBatch.clear()}this.totalFlushes++,this.totalNodeWrites+=t.size,n==="timer"&&this.timerFlushes++,n==="threshold"&&this.thresholdFlushes++,s>=2e3&&(this.slowCommits++,this.logger.warnContext(this.logContext,`${this.tag} slow commit: ${s}ms for ${t.size} nodes (possible write stream pressure)`)),this.logger.debugContext(this.logContext,`${this.tag} flushed ${t.size} run results in ${s}ms (${n}, threshold=${this.flushThreshold}, interval=${this.flushIntervalMs}ms)`)}catch(i){for(let o of t)this.dirtyNodes.add(o);throw this.logger.errorContext(this.logContext,`${this.tag} flush failed, ${t.size} nodes re-queued`,i),i}}async flushOne(t){this.dirtyNodes.delete(t);let n=this.runResults[t];if(!n){this.logger.warnContext(this.logContext,`${this.tag} node ${t} no longer has a run result, skipping write (flushOne)`);return}this.activeFlush&&this.flushedDuringBatch.add(t);let i=this.buildEntitySave(n);await this.getRunRepository().runResults.get(t).save(i),this.totalImmediateWrites++}startTimer(){this.timer||(this.timer=setInterval(()=>{this.flush("timer").catch(t=>{this.logger.errorContext(this.logContext,`${this.tag} timer-triggered flush error`,t)})},this.flushIntervalMs))}async stopAndFlush(){this.timer&&(clearInterval(this.timer),this.timer=null);try{if(this.activeFlush)try{await this.activeFlush}catch(t){this.logger.errorContext(this.logContext,`${this.tag} error waiting for in-flight flush (stopAndFlush)`,t)}this.logger.infoContext(this.logContext,`${this.tag} draining remaining dirty nodes (stopAndFlush)`),await this.flush("dispose")}catch(t){this.logger.errorContext(this.logContext,`${this.tag} error stopping and flushing (stopAndFlush)`,t)}finally{this.logger.infoContext(this.logContext,`${this.tag} done \u2014 ${this.totalFlushes} flushes (${this.thresholdFlushes} threshold, ${this.timerFlushes} timer, ${this.slowCommits} slow), ${this.totalNodeWrites} batched writes, ${this.totalImmediateWrites} immediate writes (threshold=${this.flushThreshold}, interval=${this.flushIntervalMs}ms)`)}}};var KEr=class extends ZRt{constructor(t,n,i,o,s){super(t,n,i,o,s)}get Logger(){return Xe("DEPLOY")}get runTypeName(){return"Deploy"}get runLevel(){return"orgRuns"}},YEr=class extends eOt{get Logger(){return Xe("RUNNER")}get runTypeName(){return"Refresh"}get runLevel(){return"orgRuns"}afterStepExecutionSuccess=async t=>{await super.afterStepExecutionSuccess(t),this.repository&&super.isFinalRunForStep(t)&&!t.isSource&&await this.repository.org(this.logContext.orgID).workspace(this.logContext.workspaceID).nodeLastRefreshed(t.stepID).save({lastRefreshed:new Date().toISOString()})};getQueryResultForUpdateSuccess=t=>({...super.getQueryResultForUpdateSuccess(t),type:t.stageType});async dispatchQueryFailure(t,n){if(HVc(t.error)){let i=t.error,o=this.getCurrentStageIndex(t.stepID);t.stepID in this.runResults&&(this.runResults[t.stepID].queryResultSequence.queryResults[o]=this.convertIQueryToCompletedQueryResult(i.result));let s=this.runResults[t.stepID];return s&&(s.hasTestFailures=!0),await this.updateRunWithHeartbeat({hasTestFailures:!0}),{error:{errorString:t.error.message,errorDetail:t.error.message}}}else return super.dispatchQueryFailure(t,n)}},JEr=class extends ZRt{get Logger(){return Xe("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}},$Er=class extends eOt{get Logger(){return Xe("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}};var kNe=["deletedTable","alteredTable","addedTable"],qNe=["refresh"];var XEr=`{%- macro get_value_by_column_attribute(column_attribute, value="name") -%}
9591
+ %s`,V,V,v,a);let W=v.type==="*"?qko:v.type==="?"?Uko:"\\"+v.type;u=!0,a=a.slice(0,v.reStart)+W+"\\("+V}q(),p&&(a+="\\\\");let G=Rd1[a.charAt(0)];for(let V=l.length-1;V>-1;V--){let W=l[V],F=a.slice(0,W.reStart),J=a.slice(W.reStart,W.reEnd-8),Y=a.slice(W.reEnd),z=a.slice(W.reEnd-8,W.reEnd)+Y,X=F.split(")").length,Z=F.split("(").length-X,re=Y;for(let ee=0;ee<Z;ee++)re=re.replace(/\)[+*?]?/,"");Y=re;let oe=Y===""&&n!==_Er?"(?:$|\\/)":"";a=F+J+Y+oe+z}if(a!==""&&u&&(a="(?=.)"+a),G&&(a=k()+a),n===_Er)return[a,u];if(i.nocase&&!u&&!i.nocaseMagicOnly&&(u=t.toUpperCase()!==t.toLowerCase()),!u)return Pd1(t);let H=i.nocase?"i":"";try{let V=s?{_glob:t,_src:a,test:s}:{_glob:t,_src:a};return Object.assign(new RegExp("^"+a+"$",H),V)}catch(V){return this.debug("invalid regexp",V),new RegExp("$.")}}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let n=this.options,i=n.noglobstar?qko:n.dot?_d1:Id1,o=n.nocase?"i":"",s=t.map(a=>{let u=a.map(p=>typeof p=="string"?Dd1(p):p===uF?uF:p._src);return u.forEach((p,c)=>{let l=u[c+1],d=u[c-1];p!==uF||d===uF||(d===void 0?l!==void 0&&l!==uF?u[c+1]="(?:\\/|"+i+"\\/)?"+l:u[c]=i:l===void 0?u[c-1]=d+"(?:\\/|"+i+")?":l!==uF&&(u[c-1]=d+"(?:\\/|\\/"+i+"\\/)"+l,u[c+1]=uF))}),u.filter(p=>p!==uF).join("/")}).join("|");s="^(?:"+s+")$",this.negate&&(s="^(?!"+s+").*$");try{this.regexp=new RegExp(s,o)}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):IEr&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,n=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&n)return!0;let i=this.options;Fko.sep!=="/"&&(t=t.split(Fko.sep).join("/"));let o=this.slashSplit(t);this.debug(this.pattern,"split",o);let s=this.set;this.debug(this.pattern,"set",s);let a=o[o.length-1];if(!a)for(let u=o.length-2;!a&&u>=0;u--)a=o[u];for(let u=0;u<s.length;u++){let p=s[u],c=o;if(i.matchBase&&p.length===1&&(c=[a]),this.matchOne(c,p,n))return i.flipNegate?!0:!this.negate}return i.flipNegate?!1:this.negate}static defaults(t){return k3.defaults(t).Minimatch}};k3.Minimatch=XJe;var mGc=2,yGc=1,bGc=3,EGc=2,CGc=8,SGc=5,vGc=6,TGc=new RegExp(/([\+]?){([\s\S]+)}([\+](?![\+]))?\s*/g),_Gc=new RegExp(/((\w+):\s*((?:["])((([^\"\+\r\n\[/\\]+))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),IGc=new RegExp(/((\w+):\s*(((?:["])(((?:[^"]|"")*))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),RGc=new RegExp(/((?:[^\+\ \r\n\[\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+)\s*/g),AGc="",ZJe=(r,t)=>{if(t==="*")return r.some(o=>o!=null&&String(o).length>0);let n=r.map(o=>o!=null?String(o).replace(/\//g,AGc):""),i=t.replace(/\//g,AGc);return!!zko(n,i).length};var e$e=Xe("SEARCH"),U52=B.object({include:B.string(),exclude:B.string(),enabled:B.boolean()}),OGc={name:{MatchFunction:ZJe,MatchList:r=>[r.operation.name]},location:{MatchFunction:ZJe,MatchList:r=>[r.operation.locationName]},nodeType:{MatchFunction:ZJe,MatchList:r=>[r.operation.sqlType]},subgraph:{MatchFunction:ZJe,MatchList:r=>[r?.id?.toString(),r.name]},nodeID:{MatchFunction:ZJe,MatchList:r=>[r]}},wGc=r=>{let t=[];return r.forEach((n,i)=>{if(n==="+{"||n==="{"||n==="}"||n==="}+")return;let o=n,s=n.split(""),a=s[s.length-1],u=s[0];a!=="}"&&a!=="+"&&(o=o+r[i+1]),u!=="{"&&u!=="+"&&(o=r[i-1]+o),t.push(o)}),t},MGc=(r,t,n,i=!1)=>{let{steps:o,graphInformation:s,allSubgraphs:a,allStepTypesYAML:u}=n,p={},c=n3()?Date.now():performance.now(),l=r;l||(l=t);let d=l.split(/(\}\+?)\s*(or|OR|\|\|)\s*(\+?\{)/).filter(A=>!(A==="OR"||A==="or"||A==="||")),f=wGc(d);f.length||(f=[t]),e$e.debug("got unions",f,"searchStringTouse",l,"defaultSearchString",t,"steps",o),f.forEach(A=>{let E=A.split(/(\}\+?)\s*(and|AND|\,)\s*(\+?\{)/).filter(k=>!(k==="AND"||k==="and"||k===",")),v=wGc(E),T=[];v.forEach(k=>{let L={};e$e.debug("Got intersection:",k);let q=[...k.matchAll(TGc)];if(e$e.debug("Got matches:",k,q),!q[0])return;let G=q[0][mGc],H={prefix:q[0][yGc]||"",postfix:q[0][bGc]||""};if(G.indexOf(":")>-1){let F=i?IGc:_Gc,J=[...G.trim().matchAll(F)],Y=i?vGc:SGc;J.forEach(z=>{let X=z[EGc],Z=z[CGc]||z[Y];H[X]=Z})}else{let J=[...G.trim().matchAll(RGc)][0];J&&(H.name=J[0])}vM(H);let V=H;e$e.debug("Got groups ",k,V);let W=new Set;if(V.subgraph?Object.values(a).forEach(F=>{let J=OGc.subgraph,Y=J.MatchList(F);if(J.MatchFunction(Y,V.subgraph)){let{steps:X}=F;X.forEach(Z=>{W.add(Z.toString())})}else return}):W=new Set(Object.keys(o)),V.nodeType){let{nodeType:F}=V;if(!u[F]){let J=F;Object.entries(u).forEach(([Y,z])=>{z.name===F&&(J=Y)}),V.nodeType=J}}Object.keys(o).forEach(F=>{if(!V){e$e.emerg("got an unexpected undefined value for match",l,V,k);return}let J=W.has(F);if(Object.entries(V).forEach(([Y,z])=>{let X=o[F];if(Y==="nodeID"&&(X=F),Y==="subgraph"){J=W.has(F);return}let Z=OGc[Y];if(Z){let re=Z.MatchList(X).filter(oe=>oe!=null);J=J&&Z.MatchFunction(re,z)}}),J){if(L[F]=!0,V.prefix&&s){let Y=Dko(s,F,"predecessors");Object.values(Y).forEach(z=>[...z.keys()].forEach(X=>L[X]=!0))}if(V.postfix&&s){let Y=Dko(s,F,"successors");Object.values(Y).forEach(z=>[...z.keys()].forEach(X=>L[X]=!0))}}}),T.push(L)}),T.length||T.push({});let w={};Object.keys(o).forEach(k=>{w[k]=!0});let D=T.reduce((k,L)=>Object.fromEntries(ugc(k,L).map(q=>[q,!0])),w);p={...p,...D}});let h=n3()?Date.now():performance.now();return e$e.debug("Time that search took: ",h-c),p};var OEr=(r,t,n,i=!1)=>{let o=MGc(`${r}`,"{ * }",n,i),s=MGc(`${t}`,"!*",n,i),a=o;return Object.keys(s).forEach(u=>{delete a[u]}),{stepsResult:a}};var xGc=(r,t,n,i)=>{let o=[];return t.forEach(s=>{let a=i[s];if(a){let{name:u}=a,p=`{ subgraph: "${u}" }`;o.push(p)}}),r.forEach(s=>{let a=n[s];if(a){let{locationName:u,name:p}=a.operation,c=`{ location: "${u}" name: "${p}" }`;o.push(c)}}),o};var kd1=Xe("JOBS");var PGc=r=>!r?.hasOwnProperty("includeSelector")||!r?.hasOwnProperty("version"),Qko=(r,t,n)=>{let{steps:i,subgraphs:o,...s}=r,a={...s};if(a.hasOwnProperty("version")||(a.version=i$),a.hasOwnProperty("includeSelector"))return a;a.includeSelector="",a.excludeSelector="";let u=new Set(i),p=new Set(o),d=xGc([...u],[...p].map(f=>`${f}`),n,t).map(f=>`+${f}`).join(" OR ");return a.includeSelector=d,kd1.info("Upgrading job v1 to v2",r,a),a};var NGc=(r,t)=>{let{jobs:n,folders:i,steps:o}=r,s=n[t];return Qko(s,i,o)};var Y52=Xe("PACKAGES_BACKEND");var DGc=(r,t,n)=>{let i=a6o(t)??"",o=r?.config?.entities?.nodeTypes[i];return o||(n.error(`No config found for node type ${t}`),{isDisabled:!1,defaultStorageLocation:null})};var wEr=(r,t={})=>Object.values(r).map(n=>qd1(n)).reduce((n,i)=>{for(let[o,s]of Object.entries(i))n[o]=s;return n},t),qd1=r=>Object.fromEntries(Object.entries(r?.contents?.nodeTypes??{}).map(([t,n])=>{let{id:i,nodeType:o}=Fd1(r.alias,t,r,n);return[i,o]})),Fd1=(r,t,n,i)=>{let o=umr(r,t),{isDisabled:s,defaultStorageLocation:a}=DGc(n,o,Xe("PACKAGES")),u={...ep(i),id:o,isDisabled:s};return u.metadata.defaultStorageLocation=a,{id:o,nodeType:u}};var Ho=bt(Oq());var Ud1=Ho.Record({type:Ho.Unknown,name:Ho.String}),BGc=Ho.Record({locationName:Ho.String,nodeName:Ho.String}),LGc=Ho.Record({sql:Ho.String,success:Ho.Boolean,rows:Ho.Array(Ho.Unknown),fields:Ho.Array(Ud1),error:Ho.Union(Ho.Null,Rdr).optional(),startTime:Ho.Unknown,endTime:Ho.Unknown,status:Ho.String,name:Ho.String,isRunning:Ho.Boolean,exportedRefs:Ho.Array(BGc),invalidExportedRefs:Ho.Array(BGc),queryResultSequence:Ho.Optional(Ho.Unknown),type:Ho.Union(Ho.Literal("sql"),Ho.Literal("sqlTest")).optional(),warehouse:Ho.String.nullable().optional(),queryID:Ho.String.nullable().optional()}),jko=Ho.Record({name:Ho.String,queryResults:Ho.Array(LGc),isRunning:Ho.Boolean,renderQueryResults:Ho.Optional(LGc)}),s62=Ho.Record({runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,name:Ho.String,queryResultSequence:jko,runState:Ho.String}),zd1=Ho.Record({dataResult:Ho.Unknown,name:Ho.String,queryResultSequence:jko,runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,runState:Ho.String,stepRunState:JVe(E3o)}),kGc=SM("RunResultFirestoreValidator",zd1),Qd1=Ho.Record({nodeID:Ho.String,queryResultSequence:jko,runState:Ho.String,hasTestFailures:Ho.Boolean.optional()}),jd1=Ho.Record({runResults:Ho.Record({runStartTime:Ho.Unknown,runEndTime:Ho.Unknown,runFailureReason:Ho.Optional(Ho.String),runType:Ho.String,runStatus:Ho.String,runResults:Ho.Array(Qd1),runID:Ho.Number,environmentID:Ho.String,snowflakeAccount:Ho.String.optional(),snowflakeWarehouse:Ho.String.optional(),jobID:Ho.Number.optional(),hasFailedTest:Ho.Boolean.optional(),runTimeParameters:Ho.Unknown.nullable(),includeNodesSelector:Ho.String.optional(),excludeNodesSelector:Ho.String.optional()})}),MEr=SM("TRunOutput",jd1);var c62=JVe(b3o);var Hd1=["deploy","refresh","rerun","plan"],l62=[...Hd1,"devRun"];var MNe=class{constructor(t,n,i,o){this.allNodes=t;this.renderResults=n;this.extraRefs=i;this.logContext=o;this.phasedRefUsage=n.map("phased ref usage",s=>s.map(a=>a.runDetails.ref_usage))}allNodes;renderResults;extraRefs;logContext;phasedRefUsage;buildPhase(t,n){let i="[DependencyBuilder.buildPhase()]",o=n.keys(),s=Object.keys(this.extraRefs),a=[...new Set([...o,...s])];if(Xe("PIPELINE").appContext(this.logContext,i,"Nodes present in both current-phase data AND extra non-phased (views & advanced deploy) data:",ppo([...o],s)),this.noDependenciesPhases.includes(t))return Object.fromEntries(a.map(u=>[u,[]]));{let u=this.getNodeRefsInPhase(t,a),p=new J4e(Pb(this.allNodes,a));return lv(u,(c,l)=>{let{nodeIDsToAdd:d}=BYe(c,p);return[...new Set(d)].filter(f=>f!==l)})}}build(){return Object.fromEntries([...this.phasedRefUsage.entries()].map(([t,n])=>[t,this.buildPhase(t,n)]))}};var b62=Xe("DEBUG");var xEr=r=>{typeof r.stepCounter=="number"&&(r.stepCounter=`${r.stepCounter}`),typeof r.columnCounter=="number"&&(r.columnCounter=`${r.columnCounter}`)};var Abe=new Date("1980-01-01T00:00:00.000Z"),Vs=(r,t,n)=>{let i=`${r}Entity`;return n||(n=ga(t)),{standard:Mr(i,n),strict:Mr(`${i} (strict)`,t)}};var qGc=r=>{if(Array.isArray(r))for(let t=r.length-1;t>=0;t--)r[t]===void 0&&r.splice(t,1);if(r&&typeof r=="object")for(let t in r)r.hasOwnProperty(t)&&r[t]===void 0&&delete r[t];return[r,!1]},Vd1=(r,t)=>{if(r&&typeof r=="object"){let n=r;if(n.toDate&&(!isNaN(n.seconds)&&!isNaN(n.nanoseconds)||!isNaN(n._seconds)&&!isNaN(n._nanoseconds))){let i=n.toDate();return i.getTime()===Rce.SENTINEL_DATE&&Ml().emerg(`Repository server timestamp sentinel value found in stored data at path ${t}`),[i,!0]}}return[r,!1]},FGc=(r,t)=>r instanceof w4e?[t.getDeleteSentinel(),!0]:r instanceof Date&&r.getTime()===Rce.SENTINEL_DATE?[t.getServerTimestampSentinel(),!0]:[r,!1],xNe=(r,t,n)=>{let[i,o]=t(n,r);if(!o&&typeof i=="object"){if(Array.isArray(i))return i.map(s=>xNe(r,t,s));for(let s in i)i.hasOwnProperty(s)&&(i[s]=xNe(r,t,i[s]))}return i},kRt=class{fromStorage(t,n,i,o,s){try{return this.transformFromStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error transforming repository entity ${n} from storage: ${a}`),a}return i}toStorage(t,n,i,o,s){try{return this.transformToStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error transforming repository entity ${n} to storage ${a}`),a}return i}mergeToStorage(t,n,i,o,s){try{return this.mergeTransformToStorage(t,n,i,o,s)}catch(a){if(s?.onDataTransformError&&s.onDataTransformError(n,a),!s?.ignoreDataTransformErrors)throw Ml().debug(`Error merge transforming repository entity ${n} to storage ${a}`),a}return i}},Gko=class extends kRt{constructor(n=!1){super();this.preserveID=n}preserveID;transformFromStorage(n,i,o){return"id"in o?o.id!=n&&(Ml().error(`'id' property does not match doc id on doc at path ${i}; doc id: ${n}, value.id: ${o.id}`),o.id=n):o.id=n,"createdAt"in o||(o.createdAt=Abe),"updatedAt"in o||(o.updatedAt=Abe),xNe(i,Vd1,o)}transformToStorage(n,i,o,s){return this.preserveID||delete o.id,xNe(i,a=>{let[u,p]=FGc(a,s);return p?[u,!0]:qGc(u)},o)}mergeTransformToStorage(n,i,o,s){return this.preserveID||delete o.id,xNe(i,a=>{let[u,p]=FGc(a,s);return p?[u,!0]:qGc(u)},o)}},Hko=class extends kRt{constructor(n){super();this.validators=n}validators;transformFromStorage(n,i,o,s,a){let u=this.getValidatorOptions(n,a?.validatorOptions);return a?.enableStrictValidation?this.validators.strict.assert(o,u):this.validators.standard.assert(o,u)}transformToStorage(n,i,o,s,a){let u=this.getValidatorOptions(n,a?.validatorOptions);return a?.enableStrictValidation?this.validators.strict.assert(o,u):this.validators.standard.assert(o,u)}mergeTransformToStorage(n,i,o,s,a){return o}getValidatorOptions(n,i,o=500){let s={...i,statusCode:o};return s.errorMessage||(s.errorMessage=a=>`Found ${a.failures.length} validation failure(s) for ${this.validators.standard.name} ${n}`),s}},ku=(r,t,n)=>{let i=[new Gko(n),new Hko(r)];return t&&i.unshift(t),new Vko(...i)},Vko=class{transforms;constructor(...t){this.transforms=t}fromStorage(t,n,i,o,s){return this.transforms.reduce((a,u)=>u.fromStorage(t,n,a,o,s),i)}toStorage(t,n,i,o,s){return this.transforms.reduceRight((a,u)=>u.toStorage(t,n,a,o,s),i)}mergeToStorage(t,n,i,o,s){return this.transforms.reduceRight((a,u)=>u.mergeToStorage(t,n,a,o,s),i)}},q3=class extends kRt{transformToStorage(t,n,i){return i}mergeTransformToStorage(t,n,i){return i}};var UGc=r=>!!r&&typeof r=="object"&&!Array.isArray(r),t$e=r=>UGc(r)&&!(r instanceof Date)&&!(r instanceof RegExp),$G=r=>{if(typeof r=="string")return r;if(UGc(r)&&r.constructor&&typeof r.constructor.name=="string")return`[class ${r.constructor.name}]`;if(r instanceof Date)return`[date ${r.toISOString()}]`;if(r instanceof RegExp)return`[regexp ${r.toString()}]`;if(typeof r=="function")return`[function ${r.name}]`;try{return JSON.stringify(r)}catch{return"Error: could not stringify unknown value"}},Wko=r=>r==null,qRt=(r,t,n,i)=>{t.filter((o,s)=>t$e(o)?!0:(n.logError(`Invalid ${r} item detected at index ${s}: ${$G(o)}`),n.logPatch(`Removed invalid ${r} item at index ${s}`),!1)).forEach(i)},cF=(r,t,n)=>{r[t]=n},mbe=(r,t)=>{delete r[t]},Yko=(r,t,n)=>{let i=new Kko(r,Xe("FIREBASE"),t),{logError:o,logPatch:s,report:a}=i,u=()=>(a(),n);if(!t$e(n))return u();let p=n;if([["locationName",!p.locationName&&typeof p.locationName!="string"||typeof p.locationName!="string"],["description",typeof p.description!="string"]].forEach(([c,l])=>{l&&(s(`Set non-string property ${c} from ${$G(p[c])} to ""`),cF(p,c,""))}),["dependencies","isDataVault","locationID"].forEach(c=>{c in p&&(s(`Removed deprecated field ${c}`),mbe(p,c))}),p.type==="sql")s("-- data.type is sql --"),Wd1(r,p,i);else if(p.type==="sourceInput")s("-- data.type is sourceInput --"),Kd1(r,p,i);else return o(`Data type is of invalid type ${$G(p.type)}`),u();return p.version!==e$&&(s(`Set version ${$G(p.version)} to ${e$}`),cF(p,"version",e$)),u()},Wd1=(r,t,n)=>{let{logError:i,logPatch:o}=n;if(t.isMultisource===void 0&&(o("Set missing isMultisource to false"),cF(t,"isMultisource",!1)),t$e(t.metadata)){let s=t.metadata;if(s.appliedNodeTests===null&&(o("Set metadata.appliedNodeTests from null to []"),cF(s,"appliedNodeTests",[])),!Array.isArray(s.sourceMapping)||!s.sourceMapping.length){o("Set non-array or empty metadata.sourceMapping to [ basicMapping ]");let a;typeof t.name=="string"?a=t.name:(o("Data has no name value, setting sourceMapping.name to empty string"),a=""),cF(s,"sourceMapping",[{name:a,join:{joinCondition:""},dependencies:[],noLinkRefs:[],aliases:{}}])}else qRt("sourceMapping",s.sourceMapping,n,(a,u)=>{let p=a;if(typeof p.join=="string"){let c={joinCondition:""};o(`Setting invalid string value metadata.sourceMapping[${u}].join to object: ${$G(c)}`),cF(p,"join",c)}if(p.name===void 0){let c=p.join?.name??"";o(`Set missing metadata.sourceMapping[${u}].name to "${c}"`),cF(p,"name",c),c||i(`metadata.sourceMapping[${u}].name is an empty string`)}Array.isArray(p.dependencies)&&qRt("sourceMapping dependency",p.dependencies,n,(c,l)=>{let d=c;for(let f of["locationName","nodeName"])Wko(d[f])&&(o(`Set metadata.sourceMapping[${u}].dependencies[${l}].${f} from ${$G(d[f])} to ""`),cF(d,f,""))})});zGc(r,s.columns,n)}if(t.config&&typeof t.config=="object")for(let[s,a]of Object.entries(t.config))a===null&&(o(`Removing null config property "${s}"`),mbe(t.config,s))},Kd1=(r,t,n)=>{let{logPatch:i,logError:o}=n;if(t.dataset!==void 0&&(i("Removed deprecated v0 property dataset"),mbe(t,"dataset")),t.table!==void 0&&(t.table!==t.name&&o(`source data properties 'table' and 'name' are different for source node ${r}, table: ${t.table}, name: ${t.name}`),i("Removed deprecated v0 property table"),mbe(t,"table")),t$e(t.metadata)){let s=t.metadata;Array.isArray(s.columns)&&(s.columns.length&&zGc(r,s.columns,n),Object.keys(s).length>1&&(i(`Removed deprecated metadata properties, keeping only columns. Was: ${$G(s)}`),cF(t,"metadata",{columns:s.columns})))}},zGc=(r,t,n)=>{let{logPatch:i}=n;Array.isArray(t)&&qRt("column",t,n,(o,s)=>{let a=o;if(["ghostRecordValue","descendedFrom","hashColumns","columnsForHash"].forEach(c=>{a.hasOwnProperty(c)&&(i(`Removed deprecated property '${c}' from metadata.columns[${s}]`),mbe(a,c))}),t$e(a.hashDetails)){let c=a.hashDetails;c.hashType&&(i(`Removed deprecated property 'hashType' from metadata.columns[${s}].hashDetails`),mbe(c,"hashType")),c.hubHashes&&(i(`Removed deprecated property 'hubHashes' from metadata.columns[${s}].hashDetails`),mbe(c,"hubHashes"))}[["appliedColumnTests",a.appliedColumnTests===null],["config",a.config===null],["hashDetails",typeof a.hashDetails=="string"]].forEach(([c,l])=>{l&&(i(`Deleted metadata.columns[${s}].${c} with invalid value ${$G(a[c])}`),mbe(a,c))}),[["dataType",typeof a.dataType!="string"],["transform",a.transform===null]].forEach(([c,l])=>{l&&(i(`Set ${c} from ${$G(a[c])} to "" in metadata.columns[${s}]`),cF(a,c,""))});let u=a.hashedColumns;if(Array.isArray(u))for(let c of u)xEr(c);let p=a.columnReference;if(t$e(p)){xEr(p);let c=p;Wko(c.stepCounter)&&(i(`Set metadata.columns[${s}].columnReference.stepCounter from ${$G(c.stepCounter)} to ${r}`),cF(c,"stepCounter",r))}Array.isArray(a.sourceColumnReferences)&&qRt("sourceColumnReference",a.sourceColumnReferences,n,(c,l)=>{let d=c;Array.isArray(d.columnReferences)&&qRt("columnReference",d.columnReferences,n,(f,h)=>{xEr(f);let A=f;Wko(A.stepCounter)&&(i(`Set invalid metadata.columns[${s}].sourceColumnReferences[${l}].columnReferences[${h}].stepCounter to "" from ${$G(r)}`),cF(A,"stepCounter",""))})})})},Kko=class{constructor(t,n,i){this.id=t;this.logger=n;this.path=i}id;logger;path;patchMessages=[];errorMessages=[];logPatch=t=>{this.patchMessages.push(t)};logError=t=>{this.errorMessages.push(t)};reportErrors=()=>{this.errorMessages.length&&this.logger.error(`Error patching node data with id ${this.id} at path ${this.path}`,this.errorMessages)};reportPatches=()=>{this.patchMessages.length&&this.logger.debug(`Patched node data with id ${this.id} at path ${this.path}`,this.patchMessages)};report=()=>{this.reportErrors(),this.reportPatches()}},PEr=class extends q3{transformFromStorage(t,n,i){return Yko(t,n,i)}};var aB2=Xe("FIREBASE");var uB2=Xe("STEPS"),cB2=Xe("METADATA_OPERATIONS");var GGc=(r,t)=>t[r].runState==="running";var HGc=r=>(Nm("STEPS",!!r,`Error converting API refs: argument apiRefLinks is ${r}.`),r.map(t=>({locationName:t.location_name,nodeName:t.node_name})));var VGc=r=>r?.deployEnabled??!0,Jko=r=>({nodeName:r,columns:new Set});var QGc=(r,t)=>r?r.every((n,i)=>n.deref()===t[i]):!1,jGc={},WGc=(r,t)=>{let n={};return W4e(r,(i,o)=>{let s=jGc[i],a=t[i];if(!a)throw new nt(`Dependency/ref data for node ID "${i}" was not found`,`Dependency/ref data for node ID "${i}" not found in "GetNodesWithMissingColumnDependencies" (known IDs: ${JSON.stringify(t)})`);let{dependencies:u,noLinkDependencies:p}=a,c=o.operation.metadata.columns,d=s?.nodeData.deref()===o,f=QGc(s?.dependencies,u),h=QGc(s?.noLinkDependencies,p);if(d&&f&&h&&s){s.result&&(n[i]=s.result);return}let A=new Set,E=new Set,v=new Set;c.forEach(w=>{w.sourceColumnReferences?.forEach(D=>{D.transform.trim().length||D.columnReferences?.forEach(k=>{let{stepCounter:L,columnCounter:q}=k;if(L==="0"||q==="0"||A.has(L))return;E.has(L)&&v.add(w.name);let G=r[L];if(G){let{locationName:H,name:V}=G.operation,W=u.some(J=>J.locationName===H&&J.nodeName===V),F=p.some(J=>J.locationName===H&&J.nodeName===V);W||F?A.add(L):(E.add(L),n[i]||(n[i]=Jko(o.operation.name)),v.add(w.name))}})})});let T=v.size>0?{columns:v,nodeName:o.operation.name}:void 0;T&&(n[i]=T),jGc[i]={dependencies:u.map(w=>new WeakRef(w)),noLinkDependencies:p.map(w=>new WeakRef(w)),nodeData:new WeakRef(o),result:T}}),n};var ybe=class extends MNe{noDependenciesPhases=["deletedTable"];getNodeRefsInPhase(t,n){return Object.fromEntries(n.map(i=>{let o,s=this.extraRefs[i];s?o=[s]:o=this.phasedRefUsage.get(t,i);let a=o.map(({ref:u,ref_no_link:p})=>HGc([...u,...p]));return[i,[].concat(...a)]}))}};var r$e=class extends MNe{noDependenciesPhases=[];getNodeRefsInPhase(t,n){let i=Pb(this.allNodes,...n);return lv(i,o=>{if(Gye(o.operation))return[];let{sourceMapping:s}=o.operation.metadata;if(!s?.length)return[];let a=s.map(({dependencies:u})=>u);return[].concat(...a)})}};var FRt=async(r,t)=>{let{attempts:n,tags:i,waitSeconds:o}=t,s=Ml().child({retryOptions:{maxAttempts:n,waitSeconds:o},tags:["[withRetries]",...i]});LE(n>=2,`Retry attempts value must be at least '2', but was '${n}'`,s);try{let a=await r();return s.debug("Operation succeeded without retrying"),a}catch(a){s.error(`Operation initial attempt failed; retrying. Error: ${a}`);let u,p=n-1;do{p--,await new Promise(c=>setTimeout(c,o*(n-p)*1e3));try{let c=await r();return s.info(`Operation succeeded on retry (attempt ${n-p})`),c}catch(c){s.error(`Operation failed on retry (attempt ${n-p}). Error: ${c}`),u=c}}while(p);throw s.error("Exhausted all retry attempts; exiting"),u}};var PL=bt(Oq()),Xd1=PL.String,Zd1=PL.Record({locationName:PL.String,database:PL.String,schema:PL.String}),OB2=PL.Dictionary(Zd1,Xd1);var wB2=PL.Record({seconds:PL.Number,nanoseconds:PL.Number});var e01="Making metadata updates",KGc="Deleting metadata for source input";function n$e(r,t){let n=[];for(let i of r){let o=i.compiledSQL?UYe(i.compiledSQL):[];if(o.length===0)t&&n.push({name:t,sql:"",type:"sql",continueOnFailure:!1,parsedStage:null});else for(let s of o)n.push({name:s.name,sql:s.code,type:s.type,continueOnFailure:s.continueOnFailure,parsedStage:s})}return n}function NEr(r,t){return r==="deletedTable"&&t?KGc:e01}var XG=class extends nt{constructor(n,i){super(i,`Failed node ${n}: ${i}`);this.nodeID=n}nodeID};var JRt=bt(Oq()),Xh1=bt(u$e()),R82=(0,JRt.Record)({version:JRt.String,hash:JRt.String}),Zh1=()=>{let r="7.39.5",t="5d6825ed19a5ae0a8ee483b38814b0d4172594d9";return r&&t?{version:r,hash:t}:null},Mv=Zh1();var bbe=class extends nt{constructor(n){super(`Run ${n} canceled by user`);this.runID=n}runID},c$e=class extends nt{constructor(n){super('Test failed with "continue on failure" set to false');this.result=n}result};var GVc=(r,t,n)=>{switch(r){case"skipped":return"Skipped";case"error":return"Error";case"complete":switch(n){case"create":return t?"Validated":"Created";case"run":return t?"Validated":"DataLoaded";default:return"None"}default:return"None"}},HVc=r=>typeof r=="object"&&r instanceof c$e,LNe=r=>typeof r=="object"&&(r instanceof NA||r instanceof bbe),$Rt=r=>typeof r=="object"&&r instanceof aF&&r.isCancel(),XRt=r=>typeof r=="object"&&r instanceof hX&&r.isCancel(),b9o=r=>LNe(r)||$Rt(r)||XRt(r);var VVc=5e5,WVc=500,Ebe=class r{constructor(t,n,i,o,s){this.state=t;this.repository=n;this.logContext=i;this.operationType=o;this.analyticsCollector=s}state;repository;logContext;operationType;stepsInitialized=null;runResults={};flusher=null;wasCanceled=!1;nodeStageIndexTracker=new Map;analyticsCollector;get teamID(){return this.logContext.orgID}get runID(){return this.logContext.runID}get envID(){return this.logContext.workspaceID}GetLogContext=t=>({...this.logContext,nodeID:t});async runIsCanceled(){if(!this.repository)return!1;if(this.wasCanceled)return!0;try{let t=!!(await this.getRepositoryForRun().fetch({pendingWritesTimeoutMs:100})).runDetails.canceled;return t&&(this.wasCanceled=!0),t}catch(t){if(BE(t)){if(t instanceof ONe)return!1;if(t instanceof Nu)return!1}throw t}}async throwIfRunCanceled(){if(await this.runIsCanceled())throw new bbe(this.runID)}updateNodeLocalRunResult({stepID:t,isPreview:n,runExecutionSequenceID:i},o){let s=this.runResults[t];s?(s.runState=o,s.queryResultSequence.isRunning=o==="running",s.stepRunState=this.getStepRunState(o,n),i!==void 0&&(s.runExecutionSequenceID=i),(o==="canceled"||o==="skipped"||o==="error")&&s.queryResultSequence.queryResults.forEach(a=>{!a.isRunning&&a.status==="Queued"&&(a.status="Canceled")})):this.Logger.errorContext(this.GetLogContext(t),"EventHandler updateNodeLocalRunResult: missing expected local run result for node",t)}getBulkSkipHandler=()=>async t=>{if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let[o,s]of Object.entries(t))if(this.runResults[o]){let a=i.get(o);this.updateNodeLocalRunResult({stepID:o,isPreview:!1,runExecutionSequenceID:s},"skipped");let u={...r.truncateRunResult(this.runResults[o]),version:2};await n.save(a,u)}await n.commit()};getCancelNodeHandler=()=>async t=>{try{if(!this.repository)return;if(this.runResults[t]){this.updateNodeLocalRunResult({stepID:t,isPreview:!1},"canceled");let i=this.getRepositoryForRun().runResults.get(t),o={...r.truncateRunResult(this.runResults[t]),version:2};await i.save(o)}else this.Logger.errorContext(this.GetLogContext(t),"EventHandler getCancelNodeHandler: missing expected local run result for node",t)}catch(n){this.Logger.errorContext(this.logContext,`Error canceling node ${t}`,n)}};async repositoryUpdateRunStatus({expectedStatus:t,newStatus:n}){if(!this.repository)return;let i=this.getRepositoryForRun();try{let o=await i.fetch();fh("RUNNER_BACKEND",t===o.runStatus,this.logContext,`EventHandler.repositoryUpdateRunStatus found unexpected run status - expected: ${t} / actual: ${o.runStatus}`)}catch(o){this.Logger.alertContext(this.logContext,"Error fetching runInfo",o)}await i.merge({runStatus:n})}async repositoryStampExecutorInfo(t){if(this.repository)try{await this.getRepositoryForRun().merge({platform:t,...Mv?{softwareVersion:Mv.version}:{}})}catch(n){this.Logger.errorContext(this.logContext,"[EventHandler.repositoryStampExecutorInfo] Error stamping executor info. Cannot update run document version/platform.",n)}}async repositoryUpdateRenderingProgress(t){if(this.repository)try{await this.getRepositoryForRun().merge({renderingProgress:{totalNodes:t.totalNodes,completedNodes:t.completedNodes}})}catch(n){this.Logger.errorContext(this.logContext,"[EventHandler.repositoryUpdateRenderingProgress] Error updating rendering progress. Cannot update run document renderingProgress.",n)}}getRepositoryRunsCollection(){if(!this.repository)throw new nt("No repository to get runs collection for!");let t=this.repository.orgs.get(this.logContext.orgID);return this.runLevel==="orgRuns"?t.runs:t.devRuns}getRepositoryForRun(){return this.getRepositoryRunsCollection().get(this.runID)}formatError=(t,n=null,i=null,o=!1)=>{let s=ha(t.error).error,a="";return t.error&&typeof t.error=="object"&&!(t.error instanceof Error)&&"runDetails"in t.error&&typeof t.error.runDetails=="object"&&(a=t.error?.runDetails?.compiledSQL??""),t.templateString&&(a=t.templateString),{success:!1,error:{errorString:s.errorString??"",errorDetail:s.errorDetail??""},rows:[],fields:[],name:"",exportedRefs:[],invalidExportedRefs:[],status:o?"Canceled":"Failure",sql:a??"",startTime:t.startTime,endTime:new Date,isRunning:!1,type:"sql",queryID:n,warehouse:i}};populateRunResults(t,n){let i="[EventHandler.populateRunResults()]",o=t.length+1;for(let s of t){let u=h1(s,this.state.nodes,`${i} state.nodes`).operation.name;this.runResults[s]={name:u,runExecutionSequenceID:o,dataResult:null,runState:n,stepRunState:"None",queryResultSequence:{name:u,queryResults:[],isRunning:!1},runResultVersion:2}}}async bulkSetRunResults(t){if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let o of t){let s=this.runResults[o];if(!s)throw new nt(`Run result for node ${o} does not exist for run ${this.runID}`);let a={...s,name:s.queryResultSequence.name,runExecutionSequenceID:s.runExecutionSequenceID,version:2},u=i.get(o);await n.save(u,a)}await n.commit()}async initializeRunResults(t,n="queued"){this.stepsInitialized=[...t],this.populateRunResults(t,n),await this.bulkSetRunResults(t)}setFlusher(t){this.flusher=t,t.startTimer()}async disposeFlusher(){await this.flusher?.stopAndFlush()}async populatePlaceholderStages(t,n){let i=new Set,o=new Set(t.keys());for(let s of n){if(!o.has(s))continue;let a=t.getPhaseItems(s);for(let[u,p]of a.entries()){let c=h1(u,this.runResults,"populateQueuedStages: this.runResults"),l=this.state.nodes[u],d=l?YP(l,void 0):!1,f=n$e(p,this.getNameForStageWithoutSQL(s,d));for(let h of f)c.queryResultSequence.queryResults.push(this.createQueuedStage(h));f.length>0&&!i.has(u)&&(i.add(u),this.nodeStageIndexTracker.set(u,0))}}await this.bulkSetQueuedStageResults(i)}createQueuedStage({name:t,sql:n,type:i}){return{name:t,status:"Queued",success:!0,sql:n,rows:[],fields:[],startTime:new Date,endTime:new Date,isRunning:!1,exportedRefs:[],invalidExportedRefs:[],type:i}}async bulkSetQueuedStageResults(t){if(!this.repository)return;let n=this.repository.batch(),i=this.getRepositoryForRun().runResults;for(let o of t){let s=this.runResults[o];if(!s)continue;let a=i.get(o);await n.save(a,r.buildRunResultEntitySave(s))}await n.commit()}formatErrorToResult(t,n){let i=null,o=null;return typeof t.error=="object"&&(i=t.error.queryID||null,o=t.error.warehouse||null),{...this.formatError(t,i,o,n),name:t.stageName,stageExecutionStartTime:t.stageExecutionStartTime,stageExecutionEndTime:t.stageExecutionEndTime}}ensureHasQueryResult(t){if(fh("DEPLOY",!!t.queryResult,this.GetLogContext(t.stepID),"query result should always be returned for stage execution"),!t.queryResult)throw new Error("Got an empty query result for stage execution")}updateStageResultAtTrackedIndex=(t,n)=>{let o=h1(t,this.runResults,"[EventHandler.setLastQueryResult()]").queryResultSequence.queryResults,s=this.getCurrentStageIndex(t);if(s<0||s>=o.length)throw this.Logger.errorContext(this.GetLogContext(t),"[EventHandler.setLastQueryResult] stage index out of bounds",{targetIndex:s,queryResultsLength:o.length,resultName:n.name}),new nt(`Stage index ${s} out of bounds (length: ${o.length}) for node ${t}`);o[s]=n};async dispatchQueryFailure(t,n){let i=this.formatErrorToResult(t,n);return this.Logger.errorContext(this.GetLogContext(t.stepID),"failed to execute run sql",n?"- canceled":"- errored",t.error,"stack: ",t.error.stack||"<none found>"),this.updateStageResultAtTrackedIndex(t.stepID,i),{error:i.error}}getSingleStepData(t,n){let i=this.state.nodes[n];if(i)return i;let o=`(${this.runTypeName}) EventHandler: Could not get step data for step: ${n}`;throw this.Logger.errorContext(this.GetLogContext(n),o,n),new nt(o)}getUnrunSteps(){let t={},n=this.state.nodes,i=this.runResults;if(n&&this.stepsInitialized)for(let o of this.stepsInitialized){let s=i[o];if(s){let{runState:a}=s;(a==="waiting"||a==="queued")&&(n[o]?t[o]=0:this.Logger.alertContext(this.logContext,"Node ID from initialization not found in steps data",o))}else this.Logger.alertContext(this.logContext,"Node ID from initialization not found in run results",o)}return t}getStepContext=(t,n,i,o)=>{let s=this.getSingleStepData(t,n),{locationName:a}=s.operation,{database:u}=this.state.mappings[a]?.mappingDefinitions[this.state.currentWorkspace]??{},p=YP(s,void 0),c=s.operation.name;return{startTime:new Date,stepID:n,stepName:c,runExecutionSequenceID:i,phase:t,isPreview:o,isSource:p,database:u??""}};convertIQueryToCompletedQueryResult(t){return{...t,startTime:OPo(t.startTime),endTime:OPo(t.endTime)}}getCurrentStageIndex(t){let n=this.nodeStageIndexTracker.get(t);if(n===void 0)throw new nt(`[EventHandler.getCurrentStageIndex] Node ${t} not in stage tracker. Was populateQueuedStages called for this node?`);return n}advanceToNextStage(t){let n=this.getCurrentStageIndex(t);this.nodeStageIndexTracker.set(t,n+1)}getQueryResultForUpdateSuccess(t){return{...this.convertIQueryToCompletedQueryResult(t.queryResult),name:t.stageName,stageExecutionStartTime:t.stageExecutionStartTime,stageExecutionEndTime:t.stageExecutionEndTime}}getStepRunState(t,n){return GVc(t,n,this.operationType)}async updateRunResult(t){if(!this.repository)return;let n=this.runResults[t];if(!n)throw new nt(`[EventHandler.updateRunResult()] run result for node ${t} does not exist for run ${this.runID}`);if(this.flusher)this.flusher.markDirty(t);else{let i=r.buildRunResultEntitySave(n);this.Logger.debugContext(this.GetLogContext(t),"updating run result",i),await this.getRepositoryForRun().runResults.get(t).save(i)}}isFinalRunForStep(t){return!0}async beforePhaseExecution(t,n){}async afterPhaseExecution(t){}async beforeStepExecution(t){this.runResults[t.stepID]&&(this.runResults[t.stepID].runExecutionSequenceID=t.runExecutionSequenceID),this.updateNodeLocalRunResult(t,"running"),await this.updateRunResult(t.stepID)}async afterFinalRunSuccessForNode(t){return Promise.resolve()}async afterStepExecutionSuccess(t){this.isFinalRunForStep(t)?(this.updateNodeLocalRunResult(t,"complete"),await this.afterFinalRunSuccessForNode(t)):this.updateNodeLocalRunResult(t,"waiting"),await this.updateRunResult(t.stepID)}async afterStepExecutionFailure(t){let n=await this.isCoalesceInitiatedCancel(t.error);this.markUnexecutedStagesAsCanceled(t.stepID),this.updateNodeLocalRunResult(t,n?"canceled":"error");try{this.flusher?await this.flusher.flushOne(t.stepID):await this.updateRunResult(t.stepID)}catch(i){this.Logger.emergContext(this.GetLogContext(t.stepID),`Error in firebaseUpdateStepResult for stepCounter:${t.stepID}:`,i)}}markUnexecutedStagesAsCanceled(t){let n=this.runResults[t];if(n)for(let i of n.queryResultSequence.queryResults)"status"in i&&i.status==="Queued"&&(i.status="Canceled")}sanityCheckContext(t){if(!t.stageType)throw this.Logger.emergContext(this.logContext,`No stage type on this ${this.runTypeName}!`,t),new Error(`Internal critical error: no stage type on this ${this.runTypeName}!`)}async beforeStageExecution(t){this.sanityCheckContext(t);let n=this.runResults[t.stepID];if(n){let i=n.queryResultSequence.queryResults,o=this.getCurrentStageIndex(t.stepID),s=i[o];if(!s||!("status"in s)||s.status!=="Queued"){let a=s&&"status"in s?s.status:"no-status";throw new nt(`[EventHandler.beforeStageExecution] Expected queued placeholder at index ${o} for node ${t.stepID}, but found: ${s?`status=${a}`:"undefined"}`)}s.status="Running",s.startTime=new Date,s.endTime=s.startTime,await this.updateRunResult(t.stepID)}}async updateRunWithHeartbeat(t){await this.getRepositoryForRun().updateHeartbeat(t)}async afterStageExecutionSuccess(t){let n="[EventHandler.afterStageExecutionSuccess()]";if(this.sanityCheckContext(t),!t.queryResult){let i="Got an empty query result for stage execution - query result should always be returned!";throw this.Logger.alertContext(this.GetLogContext(t.stepID),n,i),new nt(i)}if(t.stageExecutionStartTime&&t.stageExecutionEndTime){let i=t.stageExecutionEndTime.getTime()-t.stageExecutionStartTime.getTime();this.analyticsCollector.addQueryTiming(t.stepID,t.stageName,i,!0,t.stageExecutionStartTime)}if(EIt(t.queryResult)&&!t.queryResult.success){await this.updateRunWithHeartbeat({hasTestFailures:!0});let i=this.runResults[t.stepID];i&&(i.hasTestFailures=!0)}this.updateStageResultAtTrackedIndex(t.stepID,this.getQueryResultForUpdateSuccess(t)),await this.updateRunResult(t.stepID),this.advanceToNextStage(t.stepID)}async afterStageExecutionFailure(t){if(this.sanityCheckContext(t),t.stageExecutionStartTime&&t.stageExecutionEndTime){let o=t.stageExecutionEndTime.getTime()-t.stageExecutionStartTime.getTime();this.analyticsCollector.addQueryTiming(t.stepID,t.stageName,o,!1,t.stageExecutionStartTime)}let n=await this.isCoalesceInitiatedCancel(t.error),i=await this.dispatchQueryFailure(t,n);throw this.flusher?await this.flusher.flushOne(t.stepID):await this.updateRunResult(t.stepID),this.advanceToNextStage(t.stepID),n?t.error:i}async isCoalesceInitiatedCancel(t){return LNe(t)?!0:$Rt(t)?this.runIsCanceled():XRt(t)?this.runIsCanceled():!1}static truncateQueryResult(t,n=VVc,i=WVc){let o=t.sql,s=t.rows,a,u;if(o){let p=new TextEncoder,c=new TextDecoder("utf8"),l=p.encode(o);if(l.length>n){let d=c.decode(l.slice(0,n));d.slice(-1)==="\uFFFD"&&(d=d.slice(0,-1)),a=`${d}...data truncated`}}return s?.length>i&&(u=s.slice(0,i),u.push({values:[`${s.length-i} rows truncated`]})),a||u?{...t,sql:a??o,rows:u??s}:t}static buildRunResultEntitySave(t){return{...r.truncateRunResult(t),name:t.queryResultSequence.name,runExecutionSequenceID:t.runExecutionSequenceID,version:2}}static truncateRunResult(t){let n=(t.dataResult?.sql?1:0)+(t.queryResultSequence?.renderQueryResults?.sql?1:0)+(t.queryResultSequence?.queryResults?.length??0),i=(t.dataResult?.rows?.length?1:0)+(t.queryResultSequence?.renderQueryResults?.rows?.length?1:0)+(t.queryResultSequence?.queryResults?.reduce((p,c)=>p+c?.rows?.length?1:0,0)??0);if(n===0&&i===0)return t;let o=Math.trunc(VVc/n)-100,s=WVc/(i??1),a={...t};t.dataResult?.sql&&(a.dataResult=r.truncateQueryResult(t.dataResult,o,s)??null);let u=t.queryResultSequence;return u&&(a.queryResultSequence={...u,queryResults:u.queryResults?.map(p=>r.truncateQueryResult(p,o,s))},u.renderQueryResults&&(a.queryResultSequence.renderQueryResults=r.truncateQueryResult(u.renderQueryResults,o,s))),a}};var ZRt=class extends Ebe{constructor(n,i,o,s,a){super(n,i,o,"create",a);this.phasedNodeData=s}phasedNodeData;getNameForStageWithoutSQL=(n,i)=>NEr(n,i);getNodeDataForUpdate=n=>{let i=this.getSingleStepData(n.phase,n.stepID),o=i.operation.locationName,s=$q(this.state.mappings,this.envID),a=this.GetLogContext(n.stepID),u;try{let p=s?.[o]?.database??i.operation.database,c=s?.[o]?.schema??i.operation.schema;return u={...i.operation,metadata:{...i.operation.metadata,columns:i.operation.metadata.columns.map(l=>({...l}))},database:p,schema:c,version:1,id:n.stepID,deployEnabled:!0},this.Logger.infoContext(a,"newStepData:",u,"stepCounter:",n.stepID),Egc("(Logging Only) Compare locations from context and workspace",a,()=>{let l=$q(this.state.mappings||{},this.state.currentWorkspace);fh("DEPLOY",z1e(l[o],s[o]),a,`Location data for location ${o} for node ${i.operation.name} with id ${n.stepID} differs between data from context and data from workspace.`,"locationsFromWorkspace:",l,"locationsFromContext:",s)}),u}catch(p){let c=u?u.name:i.operation.name,l=`Error attempting to update the database/schema on deployed nodeID ${n.stepID}: ${c}`;throw this.Logger.emergContext(a,l,"locations:",s,"error:",p),new XG(n.stepID,l)}};async updateEnvironmentNodeMetadata(n){if(!this.repository)return;let i=this.repository.org(this.teamID).workspace(+this.envID).nodes.get(n.stepID);if(n.phase==="deletedTable")n.stepID in this.phasedNodeData.addedTable||await i.delete();else{let o=this.getNodeDataForUpdate(n);await i.save(o)}}isFinalRunForStep(n){let i=[];return n.phase==="deletedTable"&&(i.push(this.phasedNodeData.alteredTable),i.push(this.phasedNodeData.addedTable)),n.phase==="alteredTable"&&i.push(this.phasedNodeData.addedTable),!i.some(o=>n.stepID in o)}async afterFinalRunSuccessForNode(n){try{await this.updateEnvironmentNodeMetadata(n)}catch(i){let o=this.GetLogContext(n.stepID);this.Logger.errorContext(o,"Error updating node metadata -- nodeID:",n.stepID,"error:",i);let s=HVe(i),a="unknown location";try{a=this.getSingleStepData(n.phase,n.stepID).operation.locationName}catch(u){this.Logger.errorContext(o,`Error getting location name for node ${n.stepName} (${n.stepID}):`,u)}throw new XG(n.stepID,`Failed to update node metadata for ${n.stepName} (${a}): ${s}`)}}};var KVc=(r,t)=>{let n=new Set(t);return n.delete(r),Array.from(n)},HEr=async(r,t,n)=>{if(!t)throw new nt(`Cannot get deploy run info since workspace ${r} has no currently running jobs`);if(t.length)return(await n.selectInBatches("id","in",t,[["runType","==","deploy"],["runStatus","==","running"]]))[0]};var VEr="No SQL to execute";var eOt=class extends Ebe{constructor(t,n,i,o){super(t,n,i,"run",o)}async initializeRunResults(t){await super.initializeRunResults(t,"waiting")}getNameForStageWithoutSQL=()=>VEr};var WEr=class{constructor(t,n,i,o,s,a,u){this.repository=t;this.getRunRepository=n;this.buildEntitySave=i;this.runResults=o;this.logger=s;this.logContext=a;this.flushIntervalMs=u?.flushIntervalMs??3e3,this.flushThreshold=u?.flushThreshold??50}repository;getRunRepository;buildEntitySave;runResults;logger;logContext;dirtyNodes=new Set;timer=null;activeFlush=null;flushedDuringBatch=new Set;flushIntervalMs;flushThreshold;totalFlushes=0;totalNodeWrites=0;totalImmediateWrites=0;timerFlushes=0;thresholdFlushes=0;slowCommits=0;tag="[RunResultFlusher]";markDirty(t){this.dirtyNodes.add(t),this.dirtyNodes.size>=this.flushThreshold&&this.flush("threshold").catch(n=>{this.logger.errorContext(this.logContext,`${this.tag} threshold-triggered flush error`,n)})}async flush(t="dispose"){if(this.activeFlush||this.dirtyNodes.size===0){this.logger.debugContext(this.logContext,`${this.tag} flush skipped (activeFlush=${!!this.activeFlush}, dirtySetEmpty=${this.dirtyNodes.size===0}, trigger=${t})`);return}let n=new Set(this.dirtyNodes);this.dirtyNodes.clear(),this.activeFlush=this.doFlush(n,t);try{await this.activeFlush}finally{this.activeFlush=null}}async doFlush(t,n){try{let i=this.repository.batch();for(let a of t){let u=this.runResults[a];if(!u){this.logger.warnContext(this.logContext,`${this.tag} node ${a} no longer has a run result, skipping write`);continue}let p=this.buildEntitySave(u),c=this.getRunRepository().runResults.get(a);await i.save(c,p)}let o=Date.now();await i.commit();let s=Date.now()-o;if(this.flushedDuringBatch.size>0){let a=this.getRunRepository().runResults;for(let u of this.flushedDuringBatch)if(t.has(u)){let p=this.runResults[u];p&&await a.get(u).save(this.buildEntitySave(p))}this.flushedDuringBatch.clear()}this.totalFlushes++,this.totalNodeWrites+=t.size,n==="timer"&&this.timerFlushes++,n==="threshold"&&this.thresholdFlushes++,s>=2e3&&(this.slowCommits++,this.logger.warnContext(this.logContext,`${this.tag} slow commit: ${s}ms for ${t.size} nodes (possible write stream pressure)`)),this.logger.debugContext(this.logContext,`${this.tag} flushed ${t.size} run results in ${s}ms (${n}, threshold=${this.flushThreshold}, interval=${this.flushIntervalMs}ms)`)}catch(i){for(let o of t)this.dirtyNodes.add(o);throw this.logger.errorContext(this.logContext,`${this.tag} flush failed, ${t.size} nodes re-queued`,i),i}}async flushOne(t){this.dirtyNodes.delete(t);let n=this.runResults[t];if(!n){this.logger.warnContext(this.logContext,`${this.tag} node ${t} no longer has a run result, skipping write (flushOne)`);return}this.activeFlush&&this.flushedDuringBatch.add(t);let i=this.buildEntitySave(n);await this.getRunRepository().runResults.get(t).save(i),this.totalImmediateWrites++}startTimer(){this.timer||(this.timer=setInterval(()=>{this.flush("timer").catch(t=>{this.logger.errorContext(this.logContext,`${this.tag} timer-triggered flush error`,t)})},this.flushIntervalMs))}async stopAndFlush(){this.timer&&(clearInterval(this.timer),this.timer=null);try{if(this.activeFlush)try{await this.activeFlush}catch(t){this.logger.errorContext(this.logContext,`${this.tag} error waiting for in-flight flush (stopAndFlush)`,t)}this.logger.infoContext(this.logContext,`${this.tag} draining remaining dirty nodes (stopAndFlush)`),await this.flush("dispose")}catch(t){this.logger.errorContext(this.logContext,`${this.tag} error stopping and flushing (stopAndFlush)`,t)}finally{this.logger.infoContext(this.logContext,`${this.tag} done \u2014 ${this.totalFlushes} flushes (${this.thresholdFlushes} threshold, ${this.timerFlushes} timer, ${this.slowCommits} slow), ${this.totalNodeWrites} batched writes, ${this.totalImmediateWrites} immediate writes (threshold=${this.flushThreshold}, interval=${this.flushIntervalMs}ms)`)}}};var KEr=class extends ZRt{constructor(t,n,i,o,s){super(t,n,i,o,s)}get Logger(){return Xe("DEPLOY")}get runTypeName(){return"Deploy"}get runLevel(){return"orgRuns"}},YEr=class extends eOt{get Logger(){return Xe("RUNNER")}get runTypeName(){return"Refresh"}get runLevel(){return"orgRuns"}afterStepExecutionSuccess=async t=>{await super.afterStepExecutionSuccess(t),this.repository&&super.isFinalRunForStep(t)&&!t.isSource&&await this.repository.org(this.logContext.orgID).workspace(this.logContext.workspaceID).nodeLastRefreshed(t.stepID).save({lastRefreshed:new Date().toISOString()})};getQueryResultForUpdateSuccess=t=>({...super.getQueryResultForUpdateSuccess(t),type:t.stageType});async dispatchQueryFailure(t,n){if(HVc(t.error)){let i=t.error,o=this.getCurrentStageIndex(t.stepID);t.stepID in this.runResults&&(this.runResults[t.stepID].queryResultSequence.queryResults[o]=this.convertIQueryToCompletedQueryResult(i.result));let s=this.runResults[t.stepID];return s&&(s.hasTestFailures=!0),await this.updateRunWithHeartbeat({hasTestFailures:!0}),{error:{errorString:t.error.message,errorDetail:t.error.message}}}else return super.dispatchQueryFailure(t,n)}},JEr=class extends ZRt{get Logger(){return Xe("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}},$Er=class extends eOt{get Logger(){return Xe("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}};var kNe=["deletedTable","alteredTable","addedTable"],qNe=["refresh"];var XEr=`{%- macro get_value_by_column_attribute(column_attribute, value="name") -%}
9592
9592
  {%- set filtered_columns_by_attribute = columns | selectattr(column_attribute) | list -%}
9593
9593
  {%- if filtered_columns_by_attribute | length > 0 -%}
9594
9594
  {{- (filtered_columns_by_attribute | first)[value] -}}