@coalescesoftware/coa 7.40.0-alpha.b73537726555 → 7.40.0-alpha.ba7cf58194a3

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
@@ -9601,7 +9601,7 @@ Content-Type: `+c.contentType+`\r
9601
9601
  `,p),p}return i};var tHc=yt(d9o(),1),q3=(r,t,n={})=>(GEr(t),!n.nocomment&&t.charAt(0)==="#"?!1:new f$e(t,n).match(r));var df1=/^\*+([^+@!?\*\[\(]*)$/,ff1=r=>t=>!t.startsWith(".")&&t.endsWith(r),hf1=r=>t=>t.endsWith(r),gf1=r=>(r=r.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(r)),Af1=r=>(r=r.toLowerCase(),t=>t.toLowerCase().endsWith(r)),mf1=/^\*+\.\*+$/,yf1=r=>!r.startsWith(".")&&r.includes("."),bf1=r=>r!=="."&&r!==".."&&r.includes("."),Ef1=/^\.\*+$/,Cf1=r=>r!=="."&&r!==".."&&r.startsWith("."),Sf1=/^\*+$/,vf1=r=>r.length!==0&&!r.startsWith("."),Tf1=r=>r.length!==0&&r!=="."&&r!=="..",_f1=/^\?+([^+@!?\*\[\(]*)?$/,If1=([r,t=""])=>{let n=ZGc([r]);return t?(t=t.toLowerCase(),i=>n(i)&&i.toLowerCase().endsWith(t)):n},Rf1=([r,t=""])=>{let n=eHc([r]);return t?(t=t.toLowerCase(),i=>n(i)&&i.toLowerCase().endsWith(t)):n},Of1=([r,t=""])=>{let n=eHc([r]);return t?i=>n(i)&&i.endsWith(t):n},wf1=([r,t=""])=>{let n=ZGc([r]);return t?i=>n(i)&&i.endsWith(t):n},ZGc=([r])=>{let t=r.length;return n=>n.length===t&&!n.startsWith(".")},eHc=([r])=>{let t=r.length;return n=>n.length===t&&n!=="."&&n!==".."},Mf1=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",jEr=Mf1==="win32",h9o=jEr?{sep:"\\"}:{sep:"/"},xf1=h9o.sep;q3.sep=xf1;var lF=Symbol("globstar **");q3.GLOBSTAR=lF;var $Gc={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},g9o="[^/]",f9o=g9o+"*?",Pf1="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Nf1="(?:(?!(?:\\/|^)\\.).)*?",rHc=r=>r.split("").reduce((t,n)=>(t[n]=!0,t),{}),XGc=rHc("().*{}+?[]^$\\!"),Df1=rHc("[.("),Bf1=(r,t={})=>n=>q3(n,r,t);q3.filter=Bf1;var _be=(r,t={})=>Object.assign({},r,t),Lf1=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return q3;let t=q3;return Object.assign((i,o,s={})=>t(i,o,_be(r,s)),{Minimatch:class extends t.Minimatch{constructor(o,s={}){super(o,_be(r,s))}static defaults(o){return t.defaults(_be(r,o)).Minimatch}},filter:(i,o={})=>t.filter(i,_be(r,o)),defaults:i=>t.defaults(_be(r,i)),makeRe:(i,o={})=>t.makeRe(i,_be(r,o)),braceExpand:(i,o={})=>t.braceExpand(i,_be(r,o)),match:(i,o,s={})=>t.match(i,o,_be(r,s)),sep:t.sep,GLOBSTAR:lF})};q3.defaults=Lf1;var nHc=(r,t={})=>(GEr(r),t.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0,tHc.default)(r));q3.braceExpand=nHc;var kf1=1024*64,GEr=r=>{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>kf1)throw new TypeError("pattern is too long")},QEr=Symbol("subparse"),qf1=(r,t={})=>new f$e(r,t).makeRe();q3.makeRe=qf1;var A9o=(r,t,n={})=>{let i=new f$e(t,n);return r=r.filter(o=>i.match(o)),i.options.nonull&&!r.length&&r.push(t),r};q3.match=A9o;var Ff1=r=>r.replace(/\\(.)/g,"$1"),Uf1=r=>r.replace(/\\([^-\]])/g,"$1"),zf1=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Qf1=r=>r.replace(/[[\]\\]/g,"\\$&"),f$e=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;regexp;constructor(t,n={}){GEr(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),jEr)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(jEr){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===lF){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(`
9602
9602
  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(`
9603
9603
  >>> 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 nHc(this.pattern,this.options)}parse(t,n){GEr(t);let i=this.options;if(t==="**")if(i.noglobstar)t="*";else return lF;if(t==="")return"";let o,s=null;n!==QEr&&((o=t.match(Sf1))?s=i.dot?Tf1:vf1:(o=t.match(df1))?s=(i.nocase?i.dot?Af1:gf1:i.dot?hf1:ff1)(o[1]):(o=t.match(_f1))?s=(i.nocase?i.dot?Rf1:If1:i.dot?Of1:wf1)(o):(o=t.match(mf1))?s=i.dot?bf1:yf1:(o=t.match(Ef1))&&(s=Cf1));let a="",u=!1,p=!1,c=[],l=[],d=!1,f=!1,h=-1,A=-1,E,v,T,w=t.charAt(0)===".",N=i.dot||w,k=()=>w?"":N?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",L=V=>V.charAt(0)==="."?"":i.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",q=()=>{if(d){switch(d){case"*":a+=f9o,u=!0;break;case"?":a+=g9o,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;XGc[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:$Gc[d].open,close:$Gc[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("["+Qf1(Uf1(E))+"]"),a+=W}catch{a=a.substring(0,h)+"(?:$.)"}u=!0,f=!1;continue;default:q(),XGc[W]&&!(W==="^"&&f)&&(a+="\\"),a+=W;break}}for(f&&(E=t.slice(A+1),T=this.parse(E,QEr),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
9604
- %s`,V,V,v,a);let W=v.type==="*"?f9o:v.type==="?"?g9o:"\\"+v.type;u=!0,a=a.slice(0,v.reStart)+W+"\\("+V}q(),p&&(a+="\\\\");let G=Df1[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!==QEr?"(?:$|\\/)":"";a=F+J+Y+oe+z}if(a!==""&&u&&(a="(?=.)"+a),G&&(a=k()+a),n===QEr)return[a,u];if(i.nocase&&!u&&!i.nocaseMagicOnly&&(u=t.toUpperCase()!==t.toLowerCase()),!u)return Ff1(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?f9o:n.dot?Pf1:Nf1,o=n.nocase?"i":"",s=t.map(a=>{let u=a.map(p=>typeof p=="string"?zf1(p):p===lF?lF:p._src);return u.forEach((p,c)=>{let l=u[c+1],d=u[c-1];p!==lF||d===lF||(d===void 0?l!==void 0&&l!==lF?u[c+1]="(?:\\/|"+i+"\\/)?"+l:u[c]=i:l===void 0?u[c-1]=d+"(?:\\/|"+i+")?":l!==lF&&(u[c-1]=d+"(?:\\/|\\/"+i+"\\/)"+l,u[c+1]=lF))}),u.filter(p=>p!==lF).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("/"):jEr&&/^\/\/[^\/]+/.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;h9o.sep!=="/"&&(t=t.split(h9o.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 q3.defaults(t).Minimatch}};q3.Minimatch=f$e;var oHc=2,sHc=1,aHc=3,uHc=2,cHc=8,lHc=5,pHc=6,dHc=new RegExp(/([\+]?){([\s\S]+)}([\+](?![\+]))?\s*/g),fHc=new RegExp(/((\w+):\s*((?:["])((([^\"\+\r\n\[/\\]+))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),hHc=new RegExp(/((\w+):\s*(((?:["])(((?:[^"]|"")*))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),gHc=new RegExp(/((?:[^\+\ \r\n\[\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+)\s*/g),iHc="",h$e=(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,iHc):""),i=t.replace(/\//g,iHc);return!!A9o(n,i).length};var g$e=Je("SEARCH"),XL2=B.object({include:B.string(),exclude:B.string(),enabled:B.boolean()}),AHc={name:{MatchFunction:h$e,MatchList:r=>[r.operation.name]},location:{MatchFunction:h$e,MatchList:r=>[r.operation.locationName]},nodeType:{MatchFunction:h$e,MatchList:r=>[r.operation.sqlType]},subgraph:{MatchFunction:h$e,MatchList:r=>[r?.id?.toString(),r.name]},nodeID:{MatchFunction:h$e,MatchList:r=>[r]}},mHc=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},yHc=(r,t,n,i=!1)=>{let{steps:o,graphInformation:s,allSubgraphs:a,allStepTypesYAML:u}=n,p={},c=i3()?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=mHc(d);f.length||(f=[t]),g$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=mHc(E),T=[];v.forEach(k=>{let L={};g$e.debug("Got intersection:",k);let q=[...k.matchAll(dHc)];if(g$e.debug("Got matches:",k,q),!q[0])return;let G=q[0][oHc],H={prefix:q[0][sHc]||"",postfix:q[0][aHc]||""};if(G.indexOf(":")>-1){let F=i?hHc:fHc,J=[...G.trim().matchAll(F)],Y=i?pHc:lHc;J.forEach(z=>{let X=z[uHc],Z=z[cHc]||z[Y];H[X]=Z})}else{let J=[...G.trim().matchAll(gHc)][0];J&&(H.name=J[0])}_M(H);let V=H;g$e.debug("Got groups ",k,V);let W=new Set;if(V.subgraph?Object.values(a).forEach(F=>{let J=AHc.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){g$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=AHc[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=c9o(s,F,"predecessors");Object.values(Y).forEach(z=>[...z.keys()].forEach(X=>L[X]=!0))}if(V.postfix&&s){let Y=c9o(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 N=T.reduce((k,L)=>Object.fromEntries($gc(k,L).map(q=>[q,!0])),w);p={...p,...N}});let h=i3()?Date.now():performance.now();return g$e.debug("Time that search took: ",h-c),p};var HEr=(r,t,n,i=!1)=>{let o=yHc(`${r}`,"{ * }",n,i),s=yHc(`${t}`,"!*",n,i),a=o;return Object.keys(s).forEach(u=>{delete a[u]}),{stepsResult:a}};var bHc=(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 Gf1=Je("JOBS");var EHc=r=>!r?.hasOwnProperty("includeSelector")||!r?.hasOwnProperty("version"),m9o=(r,t,n)=>{let{steps:i,subgraphs:o,...s}=r,a={...s};if(a.hasOwnProperty("version")||(a.version=c$),a.hasOwnProperty("includeSelector"))return a;a.includeSelector="",a.excludeSelector="";let u=new Set(i),p=new Set(o),d=bHc([...u],[...p].map(f=>`${f}`),n,t).map(f=>`+${f}`).join(" OR ");return a.includeSelector=d,Gf1.info("Upgrading job v1 to v2",r,a),a};var CHc=(r,t)=>{let{jobs:n,folders:i,steps:o}=r,s=n[t];return m9o(s,i,o)};var ak2=Je("PACKAGES_BACKEND");var SHc=(r,t,n)=>{let i=L6o(t)??"",o=r?.config?.entities?.nodeTypes[i];return o||(n.error(`No config found for node type ${t}`),{isDisabled:!1,defaultStorageLocation:null})};var VEr=(r,t={})=>Object.values(r).map(n=>Hf1(n)).reduce((n,i)=>{for(let[o,s]of Object.entries(i))n[o]=s;return n},t),Hf1=r=>Object.fromEntries(Object.entries(r?.contents?.nodeTypes??{}).map(([t,n])=>{let{id:i,nodeType:o}=Vf1(r.alias,t,r,n);return[i,o]})),Vf1=(r,t,n,i)=>{let o=Tmr(r,t),{isDisabled:s,defaultStorageLocation:a}=SHc(n,o,Je("PACKAGES")),u={...ep(i),id:o,isDisabled:s};return u.metadata.defaultStorageLocation=a,{id:o,nodeType:u}};var Ho=yt(Mq());var Wf1=Ho.Record({type:Ho.Unknown,name:Ho.String}),vHc=Ho.Record({locationName:Ho.String,nodeName:Ho.String}),THc=Ho.Record({sql:Ho.String,success:Ho.Boolean,rows:Ho.Array(Ho.Unknown),fields:Ho.Array(Wf1),error:Ho.Union(Ho.Null,jdr).optional(),startTime:Ho.Unknown,endTime:Ho.Unknown,status:Ho.String,name:Ho.String,isRunning:Ho.Boolean,exportedRefs:Ho.Array(vHc),invalidExportedRefs:Ho.Array(vHc),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()}),y9o=Ho.Record({name:Ho.String,queryResults:Ho.Array(THc),isRunning:Ho.Boolean,renderQueryResults:Ho.Optional(THc)}),yk2=Ho.Record({runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,name:Ho.String,queryResultSequence:y9o,runState:Ho.String}),Kf1=Ho.Record({dataResult:Ho.Unknown,name:Ho.String,queryResultSequence:y9o,runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,runState:Ho.String,stepRunState:pWe(Y3o)}),_Hc=TM("RunResultFirestoreValidator",Kf1),Yf1=Ho.Record({nodeID:Ho.String,queryResultSequence:y9o,runState:Ho.String,hasTestFailures:Ho.Boolean.optional()}),Jf1=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(Yf1),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()})}),WEr=TM("TRunOutput",Jf1);var Ck2=pWe(K3o);var Xf1=["deploy","refresh","rerun","plan"],Sk2=[...Xf1,"devRun"];var jNe=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(Je("PIPELINE").appContext(this.logContext,i,"Nodes present in both current-phase data AND extra non-phased (views & advanced deploy) data:",Fpo([...o],s)),this.noDependenciesPhases.includes(t))return Object.fromEntries(a.map(u=>[u,[]]));{let u=this.getNodeRefsInPhase(t,a),p=new cNe(Nb(this.allNodes,a));return fv(u,(c,l)=>{let{nodeIDsToAdd:d}=JYe(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 xk2=Je("DEBUG");var KEr=r=>{typeof r.stepCounter=="number"&&(r.stepCounter=`${r.stepCounter}`),typeof r.columnCounter=="number"&&(r.columnCounter=`${r.columnCounter}`)};var Ibe=new Date("1980-01-01T00:00:00.000Z"),Vs=(r,t,n)=>{let i=`${r}Entity`;return n||(n=la(t)),{standard:Mr(i,n),strict:Mr(`${i} (strict)`,t)}};var IHc=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]},Zf1=(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()===Bce.SENTINEL_DATE&&Ml().emerg(`Repository server timestamp sentinel value found in stored data at path ${t}`),[i,!0]}}return[r,!1]},RHc=(r,t)=>r instanceof Q4e?[t.getDeleteSentinel(),!0]:r instanceof Date&&r.getTime()===Bce.SENTINEL_DATE?[t.getServerTimestampSentinel(),!0]:[r,!1],GNe=(r,t,n)=>{let[i,o]=t(n,r);if(!o&&typeof i=="object"){if(Array.isArray(i))return i.map(s=>GNe(r,t,s));for(let s in i)i.hasOwnProperty(s)&&(i[s]=GNe(r,t,i[s]))}return i},$Rt=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}},b9o=class extends $Rt{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=Ibe),"updatedAt"in o||(o.updatedAt=Ibe),GNe(i,Zf1,o)}transformToStorage(n,i,o,s){return this.preserveID||delete o.id,GNe(i,a=>{let[u,p]=RHc(a,s);return p?[u,!0]:IHc(u)},o)}mergeTransformToStorage(n,i,o,s){return this.preserveID||delete o.id,GNe(i,a=>{let[u,p]=RHc(a,s);return p?[u,!0]:IHc(u)},o)}},E9o=class extends $Rt{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}},qu=(r,t,n)=>{let i=[new b9o(n),new E9o(r)];return t&&i.unshift(t),new C9o(...i)},C9o=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)}},F3=class extends $Rt{transformToStorage(t,n,i){return i}mergeTransformToStorage(t,n,i){return i}};var OHc=r=>!!r&&typeof r=="object"&&!Array.isArray(r),A$e=r=>OHc(r)&&!(r instanceof Date)&&!(r instanceof RegExp),tH=r=>{if(typeof r=="string")return r;if(OHc(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"}},S9o=r=>r==null,XRt=(r,t,n,i)=>{t.filter((o,s)=>A$e(o)?!0:(n.logError(`Invalid ${r} item detected at index ${s}: ${tH(o)}`),n.logPatch(`Removed invalid ${r} item at index ${s}`),!1)).forEach(i)},pF=(r,t,n)=>{r[t]=n},Rbe=(r,t)=>{delete r[t]},T9o=(r,t,n)=>{let i=new v9o(r,Je("FIREBASE"),t),{logError:o,logPatch:s,report:a}=i,u=()=>(a(),n);if(!A$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 ${tH(p[c])} to ""`),pF(p,c,""))}),["dependencies","isDataVault","locationID"].forEach(c=>{c in p&&(s(`Removed deprecated field ${c}`),Rbe(p,c))}),p.type==="sql")s("-- data.type is sql --"),eh1(r,p,i);else if(p.type==="sourceInput")s("-- data.type is sourceInput --"),th1(r,p,i);else return o(`Data type is of invalid type ${tH(p.type)}`),u();return p.version!==o$&&(s(`Set version ${tH(p.version)} to ${o$}`),pF(p,"version",o$)),u()},eh1=(r,t,n)=>{let{logError:i,logPatch:o}=n;if(t.isMultisource===void 0&&(o("Set missing isMultisource to false"),pF(t,"isMultisource",!1)),A$e(t.metadata)){let s=t.metadata;if(s.appliedNodeTests===null&&(o("Set metadata.appliedNodeTests from null to []"),pF(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=""),pF(s,"sourceMapping",[{name:a,join:{joinCondition:""},dependencies:[],noLinkRefs:[],aliases:{}}])}else XRt("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: ${tH(c)}`),pF(p,"join",c)}if(p.name===void 0){let c=p.join?.name??"";o(`Set missing metadata.sourceMapping[${u}].name to "${c}"`),pF(p,"name",c),c||i(`metadata.sourceMapping[${u}].name is an empty string`)}Array.isArray(p.dependencies)&&XRt("sourceMapping dependency",p.dependencies,n,(c,l)=>{let d=c;for(let f of["locationName","nodeName"])S9o(d[f])&&(o(`Set metadata.sourceMapping[${u}].dependencies[${l}].${f} from ${tH(d[f])} to ""`),pF(d,f,""))})});wHc(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}"`),Rbe(t.config,s))},th1=(r,t,n)=>{let{logPatch:i,logError:o}=n;if(t.dataset!==void 0&&(i("Removed deprecated v0 property dataset"),Rbe(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"),Rbe(t,"table")),A$e(t.metadata)){let s=t.metadata;Array.isArray(s.columns)&&(s.columns.length&&wHc(r,s.columns,n),Object.keys(s).length>1&&(i(`Removed deprecated metadata properties, keeping only columns. Was: ${tH(s)}`),pF(t,"metadata",{columns:s.columns})))}},wHc=(r,t,n)=>{let{logPatch:i}=n;Array.isArray(t)&&XRt("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}]`),Rbe(a,c))}),A$e(a.hashDetails)){let c=a.hashDetails;c.hashType&&(i(`Removed deprecated property 'hashType' from metadata.columns[${s}].hashDetails`),Rbe(c,"hashType")),c.hubHashes&&(i(`Removed deprecated property 'hubHashes' from metadata.columns[${s}].hashDetails`),Rbe(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 ${tH(a[c])}`),Rbe(a,c))}),[["dataType",typeof a.dataType!="string"],["transform",a.transform===null]].forEach(([c,l])=>{l&&(i(`Set ${c} from ${tH(a[c])} to "" in metadata.columns[${s}]`),pF(a,c,""))});let u=a.hashedColumns;if(Array.isArray(u))for(let c of u)KEr(c);let p=a.columnReference;if(A$e(p)){KEr(p);let c=p;S9o(c.stepCounter)&&(i(`Set metadata.columns[${s}].columnReference.stepCounter from ${tH(c.stepCounter)} to ${r}`),pF(c,"stepCounter",r))}Array.isArray(a.sourceColumnReferences)&&XRt("sourceColumnReference",a.sourceColumnReferences,n,(c,l)=>{let d=c;Array.isArray(d.columnReferences)&&XRt("columnReference",d.columnReferences,n,(f,h)=>{KEr(f);let A=f;S9o(A.stepCounter)&&(i(`Set invalid metadata.columns[${s}].sourceColumnReferences[${l}].columnReferences[${h}].stepCounter to "" from ${tH(r)}`),pF(A,"stepCounter",""))})})})},v9o=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()}},YEr=class extends F3{transformFromStorage(t,n,i){return T9o(t,n,i)}};var b92=Je("FIREBASE");var E92=Je("STEPS"),C92=Je("METADATA_OPERATIONS");var PHc=(r,t)=>t[r].runState==="running";var NHc=r=>(Bm("STEPS",!!r,`Error converting API refs: argument apiRefLinks is ${r}.`),r.map(t=>({locationName:t.location_name,nodeName:t.node_name})));var DHc=r=>r?.deployEnabled??!0,_9o=r=>({nodeName:r,columns:new Set});var MHc=(r,t)=>r?r.every((n,i)=>n.deref()===t[i]):!1,xHc={},BHc=(r,t)=>{let n={};return sNe(r,(i,o)=>{let s=xHc[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=MHc(s?.dependencies,u),h=MHc(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(N=>{N.transform.trim().length||N.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]=_9o(o.operation.name)),v.add(w.name))}})})});let T=v.size>0?{columns:v,nodeName:o.operation.name}:void 0;T&&(n[i]=T),xHc[i]={dependencies:u.map(w=>new WeakRef(w)),noLinkDependencies:p.map(w=>new WeakRef(w)),nodeData:new WeakRef(o),result:T}}),n};var Obe=class extends jNe{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})=>NHc([...u,...p]));return[i,[].concat(...a)]}))}};var m$e=class extends jNe{noDependenciesPhases=[];getNodeRefsInPhase(t,n){let i=Nb(this.allNodes,...n);return fv(i,o=>{if(Zye(o.operation))return[];let{sourceMapping:s}=o.operation.metadata;if(!s?.length)return[];let a=s.map(({dependencies:u})=>u);return[].concat(...a)})}};var ZRt=async(r,t)=>{let{attempts:n,tags:i,waitSeconds:o}=t,s=Ml().child({retryOptions:{maxAttempts:n,waitSeconds:o},tags:["[withRetries]",...i]});kE(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 BL=yt(Mq()),oh1=BL.String,sh1=BL.Record({locationName:BL.String,database:BL.String,schema:BL.String}),U92=BL.Dictionary(sh1,oh1);var z92=BL.Record({seconds:BL.Number,nanoseconds:BL.Number});var ah1="Making metadata updates",LHc="Deleting metadata for source input";function y$e(r,t){let n=[];for(let i of r){let o=i.compiledSQL?tJe(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 JEr(r,t){return r==="deletedTable"&&t?LHc:ah1}var rH=class extends nt{constructor(n,i){super(i,`Failed node ${n}: ${i}`);this.nodeID=n}nodeID};var lOt=yt(Mq()),oA1=yt(v$e()),F72=(0,lOt.Record)({version:lOt.String,hash:lOt.String}),sA1=()=>{let r="7.40.0-aa-dev.47.hb73537726555.dirty",t="b735377265557e142c840e14bacec509f41f659b";return r&&t?{version:r,hash:t}:null},Dv=sA1();var wbe=class extends nt{constructor(n){super(`Run ${n} canceled by user`);this.runID=n}runID},T$e=class extends nt{constructor(n){super('Test failed with "continue on failure" set to false');this.result=n}result};var PWc=(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"}},NWc=r=>typeof r=="object"&&r instanceof T$e,YNe=r=>typeof r=="object"&&(r instanceof BA||r instanceof wbe),pOt=r=>typeof r=="object"&&r instanceof cF&&r.isCancel(),dOt=r=>typeof r=="object"&&r instanceof bX&&r.isCancel(),K9o=r=>YNe(r)||pOt(r)||dOt(r);var DWc=5e5,BWc=500,Mbe=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(LE(t)){if(t instanceof zNe)return!1;if(t instanceof Du)return!1}throw t}}async throwIfRunCanceled(){if(await this.runIsCanceled())throw new wbe(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();hh("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,...Dv?{softwareVersion:Dv.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=ua(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=g1(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=g1(u,this.runResults,"populateQueuedStages: this.runResults"),l=this.state.nodes[u],d=l?$P(l,void 0):!1,f=y$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(hh("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=g1(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=$P(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:n4o(t.startTime),endTime:n4o(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 PWc(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(DIt(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 YNe(t)?!0:pOt(t)?this.runIsCanceled():dOt(t)?this.runIsCanceled():!1}static truncateQueryResult(t,n=DWc,i=BWc){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(DWc/n)-100,s=BWc/(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 fOt=class extends Mbe{constructor(n,i,o,s,a){super(n,i,o,"create",a);this.phasedNodeData=s}phasedNodeData;getNameForStageWithoutSQL=(n,i)=>JEr(n,i);getNodeDataForUpdate=n=>{let i=this.getSingleStepData(n.phase,n.stepID),o=i.operation.locationName,s=Zq(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),cAc("(Logging Only) Compare locations from context and workspace",a,()=>{let l=Zq(this.state.mappings||{},this.state.currentWorkspace);hh("DEPLOY",$1e(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 rH(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=sWe(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 rH(n.stepID,`Failed to update node metadata for ${n.stepName} (${a}): ${s}`)}}};var LWc=(r,t)=>{let n=new Set(t);return n.delete(r),Array.from(n)},u2r=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 c2r="No SQL to execute";var hOt=class extends Mbe{constructor(t,n,i,o){super(t,n,i,"run",o)}async initializeRunResults(t){await super.initializeRunResults(t,"waiting")}getNameForStageWithoutSQL=()=>c2r};var l2r=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 p2r=class extends fOt{constructor(t,n,i,o,s){super(t,n,i,o,s)}get Logger(){return Je("DEPLOY")}get runTypeName(){return"Deploy"}get runLevel(){return"orgRuns"}},d2r=class extends hOt{get Logger(){return Je("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(NWc(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)}},f2r=class extends fOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}},h2r=class extends hOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}};var JNe=["deletedTable","alteredTable","addedTable"],$Ne=["refresh"];var g2r=`{%- macro get_value_by_column_attribute(column_attribute, value="name") -%}
9604
+ %s`,V,V,v,a);let W=v.type==="*"?f9o:v.type==="?"?g9o:"\\"+v.type;u=!0,a=a.slice(0,v.reStart)+W+"\\("+V}q(),p&&(a+="\\\\");let G=Df1[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!==QEr?"(?:$|\\/)":"";a=F+J+Y+oe+z}if(a!==""&&u&&(a="(?=.)"+a),G&&(a=k()+a),n===QEr)return[a,u];if(i.nocase&&!u&&!i.nocaseMagicOnly&&(u=t.toUpperCase()!==t.toLowerCase()),!u)return Ff1(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?f9o:n.dot?Pf1:Nf1,o=n.nocase?"i":"",s=t.map(a=>{let u=a.map(p=>typeof p=="string"?zf1(p):p===lF?lF:p._src);return u.forEach((p,c)=>{let l=u[c+1],d=u[c-1];p!==lF||d===lF||(d===void 0?l!==void 0&&l!==lF?u[c+1]="(?:\\/|"+i+"\\/)?"+l:u[c]=i:l===void 0?u[c-1]=d+"(?:\\/|"+i+")?":l!==lF&&(u[c-1]=d+"(?:\\/|\\/"+i+"\\/)"+l,u[c+1]=lF))}),u.filter(p=>p!==lF).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("/"):jEr&&/^\/\/[^\/]+/.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;h9o.sep!=="/"&&(t=t.split(h9o.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 q3.defaults(t).Minimatch}};q3.Minimatch=f$e;var oHc=2,sHc=1,aHc=3,uHc=2,cHc=8,lHc=5,pHc=6,dHc=new RegExp(/([\+]?){([\s\S]+)}([\+](?![\+]))?\s*/g),fHc=new RegExp(/((\w+):\s*((?:["])((([^\"\+\r\n\[/\\]+))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),hHc=new RegExp(/((\w+):\s*(((?:["])(((?:[^"]|"")*))(?:["]))|(([^\"\ \+\r\n\[/\\]+))))/g),gHc=new RegExp(/((?:[^\+\ \r\n\[\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+)\s*/g),iHc="",h$e=(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,iHc):""),i=t.replace(/\//g,iHc);return!!A9o(n,i).length};var g$e=Je("SEARCH"),XL2=B.object({include:B.string(),exclude:B.string(),enabled:B.boolean()}),AHc={name:{MatchFunction:h$e,MatchList:r=>[r.operation.name]},location:{MatchFunction:h$e,MatchList:r=>[r.operation.locationName]},nodeType:{MatchFunction:h$e,MatchList:r=>[r.operation.sqlType]},subgraph:{MatchFunction:h$e,MatchList:r=>[r?.id?.toString(),r.name]},nodeID:{MatchFunction:h$e,MatchList:r=>[r]}},mHc=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},yHc=(r,t,n,i=!1)=>{let{steps:o,graphInformation:s,allSubgraphs:a,allStepTypesYAML:u}=n,p={},c=i3()?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=mHc(d);f.length||(f=[t]),g$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=mHc(E),T=[];v.forEach(k=>{let L={};g$e.debug("Got intersection:",k);let q=[...k.matchAll(dHc)];if(g$e.debug("Got matches:",k,q),!q[0])return;let G=q[0][oHc],H={prefix:q[0][sHc]||"",postfix:q[0][aHc]||""};if(G.indexOf(":")>-1){let F=i?hHc:fHc,J=[...G.trim().matchAll(F)],Y=i?pHc:lHc;J.forEach(z=>{let X=z[uHc],Z=z[cHc]||z[Y];H[X]=Z})}else{let J=[...G.trim().matchAll(gHc)][0];J&&(H.name=J[0])}_M(H);let V=H;g$e.debug("Got groups ",k,V);let W=new Set;if(V.subgraph?Object.values(a).forEach(F=>{let J=AHc.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){g$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=AHc[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=c9o(s,F,"predecessors");Object.values(Y).forEach(z=>[...z.keys()].forEach(X=>L[X]=!0))}if(V.postfix&&s){let Y=c9o(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 N=T.reduce((k,L)=>Object.fromEntries($gc(k,L).map(q=>[q,!0])),w);p={...p,...N}});let h=i3()?Date.now():performance.now();return g$e.debug("Time that search took: ",h-c),p};var HEr=(r,t,n,i=!1)=>{let o=yHc(`${r}`,"{ * }",n,i),s=yHc(`${t}`,"!*",n,i),a=o;return Object.keys(s).forEach(u=>{delete a[u]}),{stepsResult:a}};var bHc=(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 Gf1=Je("JOBS");var EHc=r=>!r?.hasOwnProperty("includeSelector")||!r?.hasOwnProperty("version"),m9o=(r,t,n)=>{let{steps:i,subgraphs:o,...s}=r,a={...s};if(a.hasOwnProperty("version")||(a.version=c$),a.hasOwnProperty("includeSelector"))return a;a.includeSelector="",a.excludeSelector="";let u=new Set(i),p=new Set(o),d=bHc([...u],[...p].map(f=>`${f}`),n,t).map(f=>`+${f}`).join(" OR ");return a.includeSelector=d,Gf1.info("Upgrading job v1 to v2",r,a),a};var CHc=(r,t)=>{let{jobs:n,folders:i,steps:o}=r,s=n[t];return m9o(s,i,o)};var ak2=Je("PACKAGES_BACKEND");var SHc=(r,t,n)=>{let i=L6o(t)??"",o=r?.config?.entities?.nodeTypes[i];return o||(n.error(`No config found for node type ${t}`),{isDisabled:!1,defaultStorageLocation:null})};var VEr=(r,t={})=>Object.values(r).map(n=>Hf1(n)).reduce((n,i)=>{for(let[o,s]of Object.entries(i))n[o]=s;return n},t),Hf1=r=>Object.fromEntries(Object.entries(r?.contents?.nodeTypes??{}).map(([t,n])=>{let{id:i,nodeType:o}=Vf1(r.alias,t,r,n);return[i,o]})),Vf1=(r,t,n,i)=>{let o=Tmr(r,t),{isDisabled:s,defaultStorageLocation:a}=SHc(n,o,Je("PACKAGES")),u={...ep(i),id:o,isDisabled:s};return u.metadata.defaultStorageLocation=a,{id:o,nodeType:u}};var Ho=yt(Mq());var Wf1=Ho.Record({type:Ho.Unknown,name:Ho.String}),vHc=Ho.Record({locationName:Ho.String,nodeName:Ho.String}),THc=Ho.Record({sql:Ho.String,success:Ho.Boolean,rows:Ho.Array(Ho.Unknown),fields:Ho.Array(Wf1),error:Ho.Union(Ho.Null,jdr).optional(),startTime:Ho.Unknown,endTime:Ho.Unknown,status:Ho.String,name:Ho.String,isRunning:Ho.Boolean,exportedRefs:Ho.Array(vHc),invalidExportedRefs:Ho.Array(vHc),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()}),y9o=Ho.Record({name:Ho.String,queryResults:Ho.Array(THc),isRunning:Ho.Boolean,renderQueryResults:Ho.Optional(THc)}),yk2=Ho.Record({runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,name:Ho.String,queryResultSequence:y9o,runState:Ho.String}),Kf1=Ho.Record({dataResult:Ho.Unknown,name:Ho.String,queryResultSequence:y9o,runExecutionSequenceID:Ho.Number,runResultVersion:Ho.Number,runState:Ho.String,stepRunState:pWe(Y3o)}),_Hc=TM("RunResultFirestoreValidator",Kf1),Yf1=Ho.Record({nodeID:Ho.String,queryResultSequence:y9o,runState:Ho.String,hasTestFailures:Ho.Boolean.optional()}),Jf1=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(Yf1),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()})}),WEr=TM("TRunOutput",Jf1);var Ck2=pWe(K3o);var Xf1=["deploy","refresh","rerun","plan"],Sk2=[...Xf1,"devRun"];var jNe=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(Je("PIPELINE").appContext(this.logContext,i,"Nodes present in both current-phase data AND extra non-phased (views & advanced deploy) data:",Fpo([...o],s)),this.noDependenciesPhases.includes(t))return Object.fromEntries(a.map(u=>[u,[]]));{let u=this.getNodeRefsInPhase(t,a),p=new cNe(Nb(this.allNodes,a));return fv(u,(c,l)=>{let{nodeIDsToAdd:d}=JYe(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 xk2=Je("DEBUG");var KEr=r=>{typeof r.stepCounter=="number"&&(r.stepCounter=`${r.stepCounter}`),typeof r.columnCounter=="number"&&(r.columnCounter=`${r.columnCounter}`)};var Ibe=new Date("1980-01-01T00:00:00.000Z"),Vs=(r,t,n)=>{let i=`${r}Entity`;return n||(n=la(t)),{standard:Mr(i,n),strict:Mr(`${i} (strict)`,t)}};var IHc=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]},Zf1=(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()===Bce.SENTINEL_DATE&&Ml().emerg(`Repository server timestamp sentinel value found in stored data at path ${t}`),[i,!0]}}return[r,!1]},RHc=(r,t)=>r instanceof Q4e?[t.getDeleteSentinel(),!0]:r instanceof Date&&r.getTime()===Bce.SENTINEL_DATE?[t.getServerTimestampSentinel(),!0]:[r,!1],GNe=(r,t,n)=>{let[i,o]=t(n,r);if(!o&&typeof i=="object"){if(Array.isArray(i))return i.map(s=>GNe(r,t,s));for(let s in i)i.hasOwnProperty(s)&&(i[s]=GNe(r,t,i[s]))}return i},$Rt=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}},b9o=class extends $Rt{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=Ibe),"updatedAt"in o||(o.updatedAt=Ibe),GNe(i,Zf1,o)}transformToStorage(n,i,o,s){return this.preserveID||delete o.id,GNe(i,a=>{let[u,p]=RHc(a,s);return p?[u,!0]:IHc(u)},o)}mergeTransformToStorage(n,i,o,s){return this.preserveID||delete o.id,GNe(i,a=>{let[u,p]=RHc(a,s);return p?[u,!0]:IHc(u)},o)}},E9o=class extends $Rt{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}},qu=(r,t,n)=>{let i=[new b9o(n),new E9o(r)];return t&&i.unshift(t),new C9o(...i)},C9o=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)}},F3=class extends $Rt{transformToStorage(t,n,i){return i}mergeTransformToStorage(t,n,i){return i}};var OHc=r=>!!r&&typeof r=="object"&&!Array.isArray(r),A$e=r=>OHc(r)&&!(r instanceof Date)&&!(r instanceof RegExp),tH=r=>{if(typeof r=="string")return r;if(OHc(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"}},S9o=r=>r==null,XRt=(r,t,n,i)=>{t.filter((o,s)=>A$e(o)?!0:(n.logError(`Invalid ${r} item detected at index ${s}: ${tH(o)}`),n.logPatch(`Removed invalid ${r} item at index ${s}`),!1)).forEach(i)},pF=(r,t,n)=>{r[t]=n},Rbe=(r,t)=>{delete r[t]},T9o=(r,t,n)=>{let i=new v9o(r,Je("FIREBASE"),t),{logError:o,logPatch:s,report:a}=i,u=()=>(a(),n);if(!A$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 ${tH(p[c])} to ""`),pF(p,c,""))}),["dependencies","isDataVault","locationID"].forEach(c=>{c in p&&(s(`Removed deprecated field ${c}`),Rbe(p,c))}),p.type==="sql")s("-- data.type is sql --"),eh1(r,p,i);else if(p.type==="sourceInput")s("-- data.type is sourceInput --"),th1(r,p,i);else return o(`Data type is of invalid type ${tH(p.type)}`),u();return p.version!==o$&&(s(`Set version ${tH(p.version)} to ${o$}`),pF(p,"version",o$)),u()},eh1=(r,t,n)=>{let{logError:i,logPatch:o}=n;if(t.isMultisource===void 0&&(o("Set missing isMultisource to false"),pF(t,"isMultisource",!1)),A$e(t.metadata)){let s=t.metadata;if(s.appliedNodeTests===null&&(o("Set metadata.appliedNodeTests from null to []"),pF(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=""),pF(s,"sourceMapping",[{name:a,join:{joinCondition:""},dependencies:[],noLinkRefs:[],aliases:{}}])}else XRt("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: ${tH(c)}`),pF(p,"join",c)}if(p.name===void 0){let c=p.join?.name??"";o(`Set missing metadata.sourceMapping[${u}].name to "${c}"`),pF(p,"name",c),c||i(`metadata.sourceMapping[${u}].name is an empty string`)}Array.isArray(p.dependencies)&&XRt("sourceMapping dependency",p.dependencies,n,(c,l)=>{let d=c;for(let f of["locationName","nodeName"])S9o(d[f])&&(o(`Set metadata.sourceMapping[${u}].dependencies[${l}].${f} from ${tH(d[f])} to ""`),pF(d,f,""))})});wHc(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}"`),Rbe(t.config,s))},th1=(r,t,n)=>{let{logPatch:i,logError:o}=n;if(t.dataset!==void 0&&(i("Removed deprecated v0 property dataset"),Rbe(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"),Rbe(t,"table")),A$e(t.metadata)){let s=t.metadata;Array.isArray(s.columns)&&(s.columns.length&&wHc(r,s.columns,n),Object.keys(s).length>1&&(i(`Removed deprecated metadata properties, keeping only columns. Was: ${tH(s)}`),pF(t,"metadata",{columns:s.columns})))}},wHc=(r,t,n)=>{let{logPatch:i}=n;Array.isArray(t)&&XRt("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}]`),Rbe(a,c))}),A$e(a.hashDetails)){let c=a.hashDetails;c.hashType&&(i(`Removed deprecated property 'hashType' from metadata.columns[${s}].hashDetails`),Rbe(c,"hashType")),c.hubHashes&&(i(`Removed deprecated property 'hubHashes' from metadata.columns[${s}].hashDetails`),Rbe(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 ${tH(a[c])}`),Rbe(a,c))}),[["dataType",typeof a.dataType!="string"],["transform",a.transform===null]].forEach(([c,l])=>{l&&(i(`Set ${c} from ${tH(a[c])} to "" in metadata.columns[${s}]`),pF(a,c,""))});let u=a.hashedColumns;if(Array.isArray(u))for(let c of u)KEr(c);let p=a.columnReference;if(A$e(p)){KEr(p);let c=p;S9o(c.stepCounter)&&(i(`Set metadata.columns[${s}].columnReference.stepCounter from ${tH(c.stepCounter)} to ${r}`),pF(c,"stepCounter",r))}Array.isArray(a.sourceColumnReferences)&&XRt("sourceColumnReference",a.sourceColumnReferences,n,(c,l)=>{let d=c;Array.isArray(d.columnReferences)&&XRt("columnReference",d.columnReferences,n,(f,h)=>{KEr(f);let A=f;S9o(A.stepCounter)&&(i(`Set invalid metadata.columns[${s}].sourceColumnReferences[${l}].columnReferences[${h}].stepCounter to "" from ${tH(r)}`),pF(A,"stepCounter",""))})})})},v9o=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()}},YEr=class extends F3{transformFromStorage(t,n,i){return T9o(t,n,i)}};var b92=Je("FIREBASE");var E92=Je("STEPS"),C92=Je("METADATA_OPERATIONS");var PHc=(r,t)=>t[r].runState==="running";var NHc=r=>(Bm("STEPS",!!r,`Error converting API refs: argument apiRefLinks is ${r}.`),r.map(t=>({locationName:t.location_name,nodeName:t.node_name})));var DHc=r=>r?.deployEnabled??!0,_9o=r=>({nodeName:r,columns:new Set});var MHc=(r,t)=>r?r.every((n,i)=>n.deref()===t[i]):!1,xHc={},BHc=(r,t)=>{let n={};return sNe(r,(i,o)=>{let s=xHc[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=MHc(s?.dependencies,u),h=MHc(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(N=>{N.transform.trim().length||N.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]=_9o(o.operation.name)),v.add(w.name))}})})});let T=v.size>0?{columns:v,nodeName:o.operation.name}:void 0;T&&(n[i]=T),xHc[i]={dependencies:u.map(w=>new WeakRef(w)),noLinkDependencies:p.map(w=>new WeakRef(w)),nodeData:new WeakRef(o),result:T}}),n};var Obe=class extends jNe{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})=>NHc([...u,...p]));return[i,[].concat(...a)]}))}};var m$e=class extends jNe{noDependenciesPhases=[];getNodeRefsInPhase(t,n){let i=Nb(this.allNodes,...n);return fv(i,o=>{if(Zye(o.operation))return[];let{sourceMapping:s}=o.operation.metadata;if(!s?.length)return[];let a=s.map(({dependencies:u})=>u);return[].concat(...a)})}};var ZRt=async(r,t)=>{let{attempts:n,tags:i,waitSeconds:o}=t,s=Ml().child({retryOptions:{maxAttempts:n,waitSeconds:o},tags:["[withRetries]",...i]});kE(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 BL=yt(Mq()),oh1=BL.String,sh1=BL.Record({locationName:BL.String,database:BL.String,schema:BL.String}),U92=BL.Dictionary(sh1,oh1);var z92=BL.Record({seconds:BL.Number,nanoseconds:BL.Number});var ah1="Making metadata updates",LHc="Deleting metadata for source input";function y$e(r,t){let n=[];for(let i of r){let o=i.compiledSQL?tJe(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 JEr(r,t){return r==="deletedTable"&&t?LHc:ah1}var rH=class extends nt{constructor(n,i){super(i,`Failed node ${n}: ${i}`);this.nodeID=n}nodeID};var lOt=yt(Mq()),oA1=yt(v$e()),F72=(0,lOt.Record)({version:lOt.String,hash:lOt.String}),sA1=()=>{let r="7.40.0-aa-dev.46.hba7cf58194a3.dirty",t="ba7cf58194a3a01c137783b86bf0b33164374bad";return r&&t?{version:r,hash:t}:null},Dv=sA1();var wbe=class extends nt{constructor(n){super(`Run ${n} canceled by user`);this.runID=n}runID},T$e=class extends nt{constructor(n){super('Test failed with "continue on failure" set to false');this.result=n}result};var PWc=(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"}},NWc=r=>typeof r=="object"&&r instanceof T$e,YNe=r=>typeof r=="object"&&(r instanceof BA||r instanceof wbe),pOt=r=>typeof r=="object"&&r instanceof cF&&r.isCancel(),dOt=r=>typeof r=="object"&&r instanceof bX&&r.isCancel(),K9o=r=>YNe(r)||pOt(r)||dOt(r);var DWc=5e5,BWc=500,Mbe=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(LE(t)){if(t instanceof zNe)return!1;if(t instanceof Du)return!1}throw t}}async throwIfRunCanceled(){if(await this.runIsCanceled())throw new wbe(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();hh("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,...Dv?{softwareVersion:Dv.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=ua(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=g1(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=g1(u,this.runResults,"populateQueuedStages: this.runResults"),l=this.state.nodes[u],d=l?$P(l,void 0):!1,f=y$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(hh("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=g1(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=$P(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:n4o(t.startTime),endTime:n4o(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 PWc(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(DIt(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 YNe(t)?!0:pOt(t)?this.runIsCanceled():dOt(t)?this.runIsCanceled():!1}static truncateQueryResult(t,n=DWc,i=BWc){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(DWc/n)-100,s=BWc/(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 fOt=class extends Mbe{constructor(n,i,o,s,a){super(n,i,o,"create",a);this.phasedNodeData=s}phasedNodeData;getNameForStageWithoutSQL=(n,i)=>JEr(n,i);getNodeDataForUpdate=n=>{let i=this.getSingleStepData(n.phase,n.stepID),o=i.operation.locationName,s=Zq(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),cAc("(Logging Only) Compare locations from context and workspace",a,()=>{let l=Zq(this.state.mappings||{},this.state.currentWorkspace);hh("DEPLOY",$1e(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 rH(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=sWe(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 rH(n.stepID,`Failed to update node metadata for ${n.stepName} (${a}): ${s}`)}}};var LWc=(r,t)=>{let n=new Set(t);return n.delete(r),Array.from(n)},u2r=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 c2r="No SQL to execute";var hOt=class extends Mbe{constructor(t,n,i,o){super(t,n,i,"run",o)}async initializeRunResults(t){await super.initializeRunResults(t,"waiting")}getNameForStageWithoutSQL=()=>c2r};var l2r=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 p2r=class extends fOt{constructor(t,n,i,o,s){super(t,n,i,o,s)}get Logger(){return Je("DEPLOY")}get runTypeName(){return"Deploy"}get runLevel(){return"orgRuns"}},d2r=class extends hOt{get Logger(){return Je("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(NWc(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)}},f2r=class extends fOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}},h2r=class extends hOt{get Logger(){return Je("RUNNER")}get runTypeName(){return"Dev Run"}get runLevel(){return"devRuns"}};var JNe=["deletedTable","alteredTable","addedTable"],$Ne=["refresh"];var g2r=`{%- macro get_value_by_column_attribute(column_attribute, value="name") -%}
9605
9605
  {%- set filtered_columns_by_attribute = columns | selectattr(column_attribute) | list -%}
9606
9606
  {%- if filtered_columns_by_attribute | length > 0 -%}
9607
9607
  {{- (filtered_columns_by_attribute | first)[value] -}}
@@ -10636,7 +10636,7 @@ data: ${n}
10636
10636
  `}function Vwe(r,t){try{return r.write(AEE(t)),!0}catch{return!1}}var Ueu=r=>{let{id:t,fileVersion:n,type:i,...o}=r;return{...o,jobCounter:Number(t),id:Number(t),version:c$}},JPd=r=>{let{id:t,operation:n}=r;return{operation:{...n,id:t}}},$Pd=r=>{let{id:t,fileVersion:n,type:i,name:o,...s}=r;return{...s,id:t,version:gh}},XPd=r=>{let{type:t,id:n,fileVersion:i,...o}=r;return sTt.assert({id:n,...o,version:oTt})},zeu=r=>{let{nodeType:t,create:n,run:i}=r,{id:o,type:s,fileVersion:a,...u}=t,{defaultStorageLocation:p,nodeMetadataSpec:c}=u.metadata,l=p??null,d=a??gWe,f=c??"",h=AWe.parse({defaultStorageLocation:l,nodeMetadataSpec:f,error:null,templates:{create:{templateString:n||""},run:{templateString:i||""}}});return{...u,version:d,metadata:h,id:o}};var yEE=1,bEE=1,EEE=1,Qeu=r=>WH.parse({name:r.name??`Job ${r.id}`,includeSelector:r.includeSelector??"",excludeSelector:r.excludeSelector??"",id:r.id.toString(),type:"Job",fileVersion:bEE}),jeu=r=>{let t=r.operation,{id:n,name:i,...o}=t,s={id:n,name:i,operation:{...o,name:i},type:"Node",fileVersion:yEE};return _Z.parse(s)},ZPd=r=>TZ.parse({macroString:r.macroString??"",id:r.id,name:"macro",type:"Macro",fileVersion:EEE}),Geu=r=>{let t=new Set(r.steps?.map(n=>n.toString()));return IZ.parse({name:r.name??`Subgraph ${r.id}`,steps:Array.from(t).sort(),id:r.id,type:lxr,fileVersion:cxr})},e4d=r=>tbe.parse({fileVersion:xmr,type:Pmr,id:r.contents.packageID,name:r.alias,releaseID:r.contents.release.releaseID,packageID:r.contents.packageID,config:r.config}),Heu=r=>{let{isDisabled:t,name:n,version:i,id:o}=r,{templates:s,...a}=r.metadata;a.defaultStorageLocation===void 0&&(a.defaultStorageLocation=null),"error"in a||(a.error=null);let u=$Yo.assert(a),{templateString:p}=s.create,{templateString:c}=s.run;return{nodeType:{isDisabled:t,name:n,fileVersion:i??1,metadata:u,id:o,type:"NodeType"},create:p,run:c}};var Z4d=yt(Dro()),Zeu=yt($4d()),Uio=yt(require("fs")),eNd=yt(require("https")),tNd=yt(require("net")),tYt=yt(require("path"));var ZKt=Je("COA_WATCH"),eYt=null;function $eu(){eYt=null}async function Xeu(){if(eYt)return eYt;let r=Ufe("default"),t=0,n={orgID:zqe,userID:"cli",workspaceID:t},i=Dmt(r,zqe,t,n),o=new hv(rOe());return eYt=await JW(i,n,o),ZKt.info("[LocalSQL] Backend platform created",{platform:i.kind}),eYt}function X4d(r,t){r.post("/scheduler/run",async(n,i)=>{try{let{templateString:o,requestId:s}=n.body;if(!o){i.status(400).json({error:"templateString is required"});return}ZKt.info("[LocalSQL] Executing query",{requestId:s,sql:o.substring(0,200)});let u=await(await Xeu()).runSQL({sql:o,...s&&{overrideRequestID:s}});i.json(u)}catch(o){$eu();let s=ua(o);ZKt.error("[LocalSQL] Query failed",{error:s.error.errorString}),i.status(500).json(s)}}),r.post("/scheduler/getDatabaseNames",async(n,i)=>{try{let s=await(await Xeu()).getDatabaseNames();i.json({databases:s})}catch(o){$eu();let s=o instanceof Error?o.message:String(o);ZKt.error("[LocalSQL] getDatabaseNames failed",{error:s}),i.status(500).json({error:s})}}),r.post("/scheduler/getSchemaNames",async(n,i)=>{try{let{database:o}=n.body;if(!o){i.status(400).json({error:"database is required"});return}let a=await(await Xeu()).getSchemaNames(o);i.json({schemas:a})}catch(o){$eu();let s=o instanceof Error?o.message:String(o);ZKt.error("[LocalSQL] getSchemaNames failed",{error:s}),i.status(500).json({error:s})}})}var Xhe=Je("COA_WATCH");function eCE(){return"<script>self.__COALESCE_LOCAL_MODE__=true</script>"}async function rNd(r,t){let{cloudDomain:n,refreshToken:i}=t;Xhe.debug("[ServeUI] Bootstrapping local auth...");let s=(await dc.get(`${n}/api/v1/database`)).data.apiKey,a=await dc.post(`https://securetoken.googleapis.com/v1/token?key=${s}`,{refresh_token:i,grant_type:"refresh_token"}),{id_token:u}=et.object({id_token:et.string()}).parse(a.data),c=(await XP(`${n}/scheduler/generateLoginToken`,{},u)).data.customToken;Xhe.debug("[ServeUI] Local auth bootstrapped successfully");let l=crypto.randomUUID(),d=!1;r.get("/api/v1/local/auth",(w,N)=>{let k=w.headers.authorization,L=k?.startsWith("Bearer ")?k.slice(7):void 0;if(Xhe.debug("[ServeUI] Auth request received",{hasAuthHeader:!!k,hasBearer:!!L,bearerMatches:L===l,nonceConsumed:d}),!L){Xhe.debug("[ServeUI] Auth rejected: missing or malformed Authorization bearer token"),N.status(401).json({error:"Unauthorized"});return}if(L!==l){Xhe.debug("[ServeUI] Auth rejected: nonce mismatch (stale login URL?)"),N.status(401).json({error:"Unauthorized"});return}if(d){Xhe.debug("[ServeUI] Auth rejected: nonce already consumed (page reloaded or re-requested)"),N.status(401).json({error:"Unauthorized"});return}d=!0,Xhe.debug("[ServeUI] Auth accepted: nonce valid, returning custom token"),N.json({customToken:c})}),X4d(r,n),r.use(["/api","/scheduler"],(0,Zeu.default)(n,{proxyReqPathResolver:w=>w.originalUrl}));let f=new URL(n);r.use("/git",(w,N)=>{let k=eNd.default.request({hostname:f.hostname,port:443,path:w.originalUrl,method:w.method,headers:{...w.headers,host:f.host}},L=>{N.writeHead(L.statusCode??502,L.headers),L.pipe(N)});k.on("error",L=>{Xhe.error("[ServeUI] Git proxy error",L),N.headersSent||N.status(502).json({error:"Git proxy failed"})}),w.pipe(k)});let h=tYt.default.join(__dirname,"web-ui"),A=Uio.default.existsSync(tYt.default.join(h,"index.html")),E=`<head>${eCE()}`;if(A)return r.get("/",(w,N)=>{let k=Uio.default.readFileSync(tYt.default.join(h,"index.html"),"utf-8");N.type("html").send(k.replace("<head>",E))}),r.use(Z4d.default.static(h)),r.get("*",(w,N)=>{let k=Uio.default.readFileSync(tYt.default.join(h,"index.html"),"utf-8");N.type("html").send(k.replace("<head>",E))}),{nonce:l};let v=3e3;return Xhe.debug("[ServeUI] No built UI found, proxying to Vite dev server",{vitePort:v}),r.use((0,Zeu.default)(`http://localhost:${v}`,{proxyReqPathResolver:w=>w.originalUrl,userResDecorator:(w,N,k)=>{if(k.headers.accept?.includes("text/html")){let L=N.toString("utf-8");if(L.includes("<head>"))return L.replace("<head>",E)}return k.url?.includes("@vite/client")?N.toString("utf-8").replace(/const socketProtocol = "[^"]*"/,'const socketProtocol = "ws"').replace(/const socketHost = [^;]+;/,`const socketHost = "localhost:${k.socket.localPort}/";`).replace(/const directSocketHost = "[^"]*";/,`const directSocketHost = "localhost:${k.socket.localPort}/";`):N}})),{nonce:l,onUpgrade:(w,N,k)=>{let L=tNd.default.createConnection(v,"localhost",()=>{let q=`${w.method} ${w.url} HTTP/${w.httpVersion}\r
10637
10637
  `,G=w.rawHeaders.reduce((H,V,W)=>W%2===0?H+V+": ":H+V+`\r
10638
10638
  `,"");L.write(q+G+`\r
10639
- `),k.length>0&&L.write(new Uint8Array(k)),N.pipe(L).pipe(N)});L.on("error",()=>N.destroy()),N.on("error",()=>L.destroy())}}}var aa=Je("COA_WATCH"),tCE=(0,sNd.promisify)(nNd.execFile),zio=class{options;clients=new Map;keepaliveIntervals=new Map;httpServer=null;sequenceNumber=0;serverId="coa-watch";pathIndex=new Map;queue=[];processing=!1;chokidarChanges=new Set;chokidarDeletes=new Set;chokidarTimer=null;CHOKIDAR_DEBOUNCE_MS=300;MAX_CLIENT_BUFFER_SIZE=1e4;SNAPSHOT_THRESHOLD=200;appManager;constructor(t){this.options=t,this.appManager=new Nio(this.options.coordinator.getWorkspaceDir()),this.options.coordinator.onUpdate(n=>this.handleFileEvent(n))}async start(){let t=(0,etu.default)();t.use(etu.default.json({limit:"50mb"})),t.use(iNd.middleware({apiSpec:S8.default.join(__dirname,"openapi.yaml"),validateRequests:{allowUnknownQueryParameters:!0,removeAdditional:!0},validateResponses:!0,ignorePaths:this.options.serveUI?/^(?!\/api\/v1\/watch|\/api\/rescan)|^\/api\/v1\/watch\/apps/:/^(?!\/api)|^\/api\/v1\/watch\/apps/})),t.get("/health",(o,s)=>{s.json({status:"ok"})}),t.get("/api/v1/watch/stream",(o,s)=>this.handleSSEConnection(o,s)),t.post("/api/v1/watch/node/bulk",(o,s)=>this.handleBulkNodesWrite(o,s)),t.post("/api/v1/watch/node/:id",(o,s)=>this.handleNodeWrite(o,s)),t.post("/api/v1/watch/job",(o,s)=>this.handleJobCreate(o,s)),t.post("/api/v1/watch/job/:id",(o,s)=>this.handleJobUpdate(o,s)),t.post("/api/v1/watch/macro/:id",(o,s)=>this.handleMacroWrite(o,s)),t.post("/api/v1/watch/subgraph",(o,s)=>this.handleSubgraphCreate(o,s)),t.post("/api/v1/watch/subgraph/:id",(o,s)=>this.handleSubgraphUpdate(o,s)),t.post("/api/v1/watch/nodeType",(o,s)=>this.handleNodeTypeCreate(o,s)),t.post("/api/v1/watch/nodeType/:id",(o,s)=>this.handleNodeTypeUpdate(o,s)),t.post("/api/v1/watch/environment/:id",(o,s)=>this.handleEnvironmentWrite(o,s)),t.post("/api/v1/watch/package/:id",(o,s)=>this.handlePackageWrite(o,s)),t.post("/api/v2/node/:id",(o,s)=>this.handleNodeWriteV2(o,s)),t.post("/api/v1/watch/node/bulk/delete",(o,s)=>this.handleBulkNodesDelete(o,s)),t.delete("/api/v1/watch/node/:id",(o,s)=>this.handleDelete("Node",o,s)),t.delete("/api/v1/watch/job/:id",(o,s)=>this.handleDelete("Job",o,s)),t.delete("/api/v1/watch/macro/:id",(o,s)=>this.handleDelete("Macro",o,s)),t.delete("/api/v1/watch/subgraph/:id",(o,s)=>this.handleDelete("Subgraph",o,s)),t.delete("/api/v1/watch/nodeType/:id",(o,s)=>this.handleDelete("NodeType",o,s)),t.delete("/api/v1/watch/package/:id",(o,s)=>this.handleDelete("Package",o,s)),t.post("/api/v1/watch/storage-locations",(o,s)=>this.handleCreateStorageLocation(o,s)),t.delete("/api/v1/watch/storage-locations/:name",(o,s)=>this.handleDeleteStorageLocation(o,s)),t.patch("/api/v1/watch/storage-locations/default",(o,s)=>this.handleSetDefaultStorageLocation(o,s)),t.patch("/api/v1/watch/environment",(o,s)=>this.handleUpdateEnvironmentMappings(o,s)),t.get("/api/v1/watch/git/status",(o,s)=>this.handleGitStatus(o,s)),t.get("/api/v1/watch/git/branches",(o,s)=>this.handleGitBranches(o,s)),t.get("/api/v1/watch/git/log",(o,s)=>this.handleGitLog(o,s)),t.get("/api/v1/watch/git/diff",(o,s)=>this.handleGitDiff(o,s)),t.post("/api/v1/watch/git/checkout",(o,s)=>this.handleGitCheckout(o,s)),t.post("/api/v1/watch/git/commit",(o,s)=>this.handleGitCommit(o,s)),t.post("/api/v1/watch/git/push",(o,s)=>this.handleGitPush(o,s)),t.post("/api/v1/watch/git/branch",(o,s)=>this.handleGitCreateBranch(o,s)),t.post("/api/v1/watch/git/add",(o,s)=>this.handleGitAddAll(o,s)),t.post("/api/v1/watch/config",(o,s)=>this.handleUpdateConfig(o,s)),t.post("/api/v1/watch/install",(o,s)=>this.handleInstall(o,s)),t.post("/api/rescan",(o,s)=>this.handleRescan(o,s)),t.get("/api/v1/watch/apps",(o,s)=>this.handleListApps(o,s)),t.all("/api/v1/watch/apps/:appId/proxy/*",(o,s)=>this.handleAppProxy(o,s));let n,i;if(this.options.serveUI){let{cloudDomain:o,refreshToken:s}=this.options;if(!o||!s)throw new Error("Cloud domain and refresh token are required for --serve-ui. Run `coa login` first.");let a=await rNd(t,{cloudDomain:o,refreshToken:s});n=a.nonce,i=a.onUpgrade}return this.httpServer=t.listen(this.options.port,"127.0.0.1"),i&&this.httpServer.on("upgrade",i),await new Promise((o,s)=>{let a=this.httpServer;if(!a){s(new Error("[RepositoryServer] httpServer was not created"));return}a.once("error",s),a.once("listening",()=>{a.removeListener("error",s),o()})}),aa.info("[RepositoryServer] Started",{port:this.options.port,host:"127.0.0.1"}),n}async shutdown(){aa.info("[RepositoryServer] Shutting down"),this.appManager.shutdownAll(),this.chokidarTimer&&(clearTimeout(this.chokidarTimer),this.chokidarTimer=null);for(let[i,o]of this.clients.entries()){try{o.res.end()}catch{}this.cleanupClient(i)}let t=5e3,n=Date.now();for(;this.queue.length>0&&Date.now()-n<t;)await new Promise(i=>setTimeout(i,100));this.queue.length>0&&aa.warn("[RepositoryServer] Queue not empty at shutdown",{remaining:this.queue.length}),this.httpServer&&await new Promise(i=>this.httpServer.close(()=>i())),aa.info("[RepositoryServer] Shutdown complete")}handleFileEvent(t){switch(aa.info("[RepositoryServer] handleFileEvent received",{type:t.type,path:"path"in t?t.path:"batch"}),t.type){case"file-add":case"file-changed":this.chokidarChanges.add(t.path),this.scheduleChokidarBatch();break;case"file-deleted":this.chokidarDeletes.add(t.path),this.scheduleChokidarBatch();break;case"file-batch-changed":this.enqueueNoReply({type:"ProcessChokidarBatch",changes:t.paths,deletes:[],forceSnapshot:!0});break}}scheduleChokidarBatch(){this.chokidarTimer&&clearTimeout(this.chokidarTimer),this.chokidarTimer=setTimeout(()=>{let t=[...this.chokidarChanges],n=[...this.chokidarDeletes];this.chokidarChanges.clear(),this.chokidarDeletes.clear(),this.chokidarTimer=null,(t.length>0||n.length>0)&&this.enqueueNoReply({type:"ProcessChokidarBatch",changes:t,deletes:n})},this.CHOKIDAR_DEBOUNCE_MS)}async handleSSEConnection(t,n){let i=`client-${Date.now()}-${Math.random().toString(36).substring(7)}`;aa.info("[RepositoryServer] SSE client connected",{clientId:i}),n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{await this.enqueue({type:"SSEClientConnected",clientId:i,res:n,reply:()=>{}})}catch(s){aa.error("[RepositoryServer] Failed to send snapshot",{clientId:i,error:s instanceof Error?s.message:String(s)}),n.end();return}let o=setInterval(()=>{this.clients.has(i)?n.write(`: keepalive
10639
+ `),k.length>0&&L.write(new Uint8Array(k)),N.pipe(L).pipe(N)});L.on("error",()=>N.destroy()),N.on("error",()=>L.destroy())}}}var aa=Je("COA_WATCH"),tCE=(0,sNd.promisify)(nNd.execFile),zio=class{options;clients=new Map;keepaliveIntervals=new Map;httpServer=null;sequenceNumber=0;serverId="coa-watch";pathIndex=new Map;queue=[];processing=!1;chokidarChanges=new Set;chokidarDeletes=new Set;chokidarTimer=null;CHOKIDAR_DEBOUNCE_MS=300;MAX_CLIENT_BUFFER_SIZE=1e4;SNAPSHOT_THRESHOLD=200;appManager;constructor(t){this.options=t,this.appManager=new Nio(this.options.coordinator.getWorkspaceDir()),this.options.coordinator.onUpdate(n=>this.handleFileEvent(n))}async start(){let t=(0,etu.default)();t.use(etu.default.json({limit:"50mb"})),t.use(iNd.middleware({apiSpec:S8.default.join(__dirname,"openapi.yaml"),validateRequests:{allowUnknownQueryParameters:!0,removeAdditional:!0},validateResponses:!0,ignorePaths:this.options.serveUI?/^(?!\/api\/v1\/watch|\/api\/rescan)|^\/api\/v1\/watch\/apps/:/^(?!\/api)|^\/api\/v1\/watch\/apps/})),t.get("/health",(o,s)=>{s.json({status:"ok"})}),t.get("/api/v1/watch/stream",(o,s)=>this.handleSSEConnection(o,s)),t.post("/api/v1/watch/node/bulk",(o,s)=>this.handleBulkNodesWrite(o,s)),t.post("/api/v1/watch/node/:id",(o,s)=>this.handleNodeWrite(o,s)),t.post("/api/v1/watch/job",(o,s)=>this.handleJobCreate(o,s)),t.post("/api/v1/watch/job/:id",(o,s)=>this.handleJobUpdate(o,s)),t.post("/api/v1/watch/macro/:id",(o,s)=>this.handleMacroWrite(o,s)),t.post("/api/v1/watch/subgraph",(o,s)=>this.handleSubgraphCreate(o,s)),t.post("/api/v1/watch/subgraph/:id",(o,s)=>this.handleSubgraphUpdate(o,s)),t.post("/api/v1/watch/nodeType",(o,s)=>this.handleNodeTypeCreate(o,s)),t.post("/api/v1/watch/nodeType/:id",(o,s)=>this.handleNodeTypeUpdate(o,s)),t.post("/api/v1/watch/environment/:id",(o,s)=>this.handleEnvironmentWrite(o,s)),t.post("/api/v1/watch/package/:id",(o,s)=>this.handlePackageWrite(o,s)),t.post("/api/v2/node/:id",(o,s)=>this.handleNodeWriteV2(o,s)),t.post("/api/v1/watch/node/bulk/delete",(o,s)=>this.handleBulkNodesDelete(o,s)),t.delete("/api/v1/watch/node/:id",(o,s)=>this.handleDelete("Node",o,s)),t.delete("/api/v1/watch/job/:id",(o,s)=>this.handleDelete("Job",o,s)),t.delete("/api/v1/watch/macro/:id",(o,s)=>this.handleDelete("Macro",o,s)),t.delete("/api/v1/watch/subgraph/:id",(o,s)=>this.handleDelete("Subgraph",o,s)),t.delete("/api/v1/watch/nodeType/:id",(o,s)=>this.handleDelete("NodeType",o,s)),t.delete("/api/v1/watch/package/:id",(o,s)=>this.handleDelete("Package",o,s)),t.post("/api/v1/watch/storage-locations",(o,s)=>this.handleCreateStorageLocation(o,s)),t.delete("/api/v1/watch/storage-locations/:name",(o,s)=>this.handleDeleteStorageLocation(o,s)),t.patch("/api/v1/watch/storage-locations/default",(o,s)=>this.handleSetDefaultStorageLocation(o,s)),t.patch("/api/v1/watch/environment",(o,s)=>this.handleUpdateEnvironmentMappings(o,s)),t.get("/api/v1/watch/git/status",(o,s)=>this.handleGitStatus(o,s)),t.get("/api/v1/watch/git/branches",(o,s)=>this.handleGitBranches(o,s)),t.get("/api/v1/watch/git/log",(o,s)=>this.handleGitLog(o,s)),t.get("/api/v1/watch/git/diff",(o,s)=>this.handleGitDiff(o,s)),t.post("/api/v1/watch/git/checkout",(o,s)=>this.handleGitCheckout(o,s)),t.post("/api/v1/watch/git/commit",(o,s)=>this.handleGitCommit(o,s)),t.post("/api/v1/watch/git/push",(o,s)=>this.handleGitPush(o,s)),t.post("/api/v1/watch/git/branch",(o,s)=>this.handleGitCreateBranch(o,s)),t.post("/api/v1/watch/git/add",(o,s)=>this.handleGitAddAll(o,s)),t.post("/api/v1/watch/config",(o,s)=>this.handleUpdateConfig(o,s)),t.post("/api/v1/watch/install",(o,s)=>this.handleInstall(o,s)),t.post("/api/rescan",(o,s)=>this.handleRescan(o,s)),t.get("/api/v1/watch/apps",(o,s)=>this.handleListApps(o,s)),t.all("/api/v1/watch/apps/:appId/proxy/*",(o,s)=>this.handleAppProxy(o,s));let n,i;if(this.options.serveUI){let{cloudDomain:o,refreshToken:s}=this.options;if(!o||!s)throw new Error("Cloud domain and refresh token are required for --serve-ui. Run `coa login` first.");let a=await rNd(t,{cloudDomain:o,refreshToken:s});n=a.nonce,i=a.onUpgrade}return this.httpServer=t.listen(this.options.port,"127.0.0.1",()=>{aa.info("[RepositoryServer] Started",{port:this.options.port})}),i&&this.httpServer.on("upgrade",i),n}async shutdown(){aa.info("[RepositoryServer] Shutting down"),this.appManager.shutdownAll(),this.chokidarTimer&&(clearTimeout(this.chokidarTimer),this.chokidarTimer=null);for(let[i,o]of this.clients.entries()){try{o.res.end()}catch{}this.cleanupClient(i)}let t=5e3,n=Date.now();for(;this.queue.length>0&&Date.now()-n<t;)await new Promise(i=>setTimeout(i,100));this.queue.length>0&&aa.warn("[RepositoryServer] Queue not empty at shutdown",{remaining:this.queue.length}),this.httpServer&&await new Promise(i=>this.httpServer.close(()=>i())),aa.info("[RepositoryServer] Shutdown complete")}handleFileEvent(t){switch(aa.info("[RepositoryServer] handleFileEvent received",{type:t.type,path:"path"in t?t.path:"batch"}),t.type){case"file-add":case"file-changed":this.chokidarChanges.add(t.path),this.scheduleChokidarBatch();break;case"file-deleted":this.chokidarDeletes.add(t.path),this.scheduleChokidarBatch();break;case"file-batch-changed":this.enqueueNoReply({type:"ProcessChokidarBatch",changes:t.paths,deletes:[],forceSnapshot:!0});break}}scheduleChokidarBatch(){this.chokidarTimer&&clearTimeout(this.chokidarTimer),this.chokidarTimer=setTimeout(()=>{let t=[...this.chokidarChanges],n=[...this.chokidarDeletes];this.chokidarChanges.clear(),this.chokidarDeletes.clear(),this.chokidarTimer=null,(t.length>0||n.length>0)&&this.enqueueNoReply({type:"ProcessChokidarBatch",changes:t,deletes:n})},this.CHOKIDAR_DEBOUNCE_MS)}async handleSSEConnection(t,n){let i=`client-${Date.now()}-${Math.random().toString(36).substring(7)}`;aa.info("[RepositoryServer] SSE client connected",{clientId:i}),n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{await this.enqueue({type:"SSEClientConnected",clientId:i,res:n,reply:()=>{}})}catch(s){aa.error("[RepositoryServer] Failed to send snapshot",{clientId:i,error:s instanceof Error?s.message:String(s)}),n.end();return}let o=setInterval(()=>{this.clients.has(i)?n.write(`: keepalive
10640
10640
 
10641
10641
  `):(clearInterval(o),this.keepaliveIntervals.delete(i))},3e4);this.keepaliveIntervals.set(i,o),t.on("close",()=>{aa.info("[RepositoryServer] SSE client disconnected",{clientId:i});let s=this.keepaliveIntervals.get(i);s&&(clearInterval(s),this.keepaliveIntervals.delete(i)),this.enqueueNoReply({type:"SSEClientDisconnected",clientId:i})})}async sendSnapshotToClient(t,n,i){aa.info("[RepositoryServer] sendSnapshotToClient called",{clientId:t,entityCount:i.length});let o=this.clients.get(t);if(!o){aa.warn("[RepositoryServer] Client not found during snapshot",{clientId:t});return}let s={type:"snapshot-start",serverId:this.serverId,sequenceNumber:this.sequenceNumber++};Vwe(n,s),aa.info("[RepositoryServer] Snapshot-start sent",{clientId:t});let a=new Map;for(let{entityType:p,id:c,path:l}of i)try{let d=await this.parseFileToRepository(l);if(!d){aa.debug("[RepositoryServer] Entity deleted during snapshot",{entityType:p,id:c,path:l});continue}let f=a.get(p)||[];f.push(d),a.set(p,f)}catch(d){aa.debug("[RepositoryServer] Entity changed during snapshot",{entityType:p,id:c,path:l,error:d instanceof Error?d.message:String(d)})}for(let[p,c]of a.entries()){if(p==="Package")continue;let l=c;if(p==="NodeType"&&!c.some(h=>h.id==="Source")){let h=await this.getPlatformKind(),A=this.getDefaultSourceNodeType(h);l=[...c,A]}let d={type:"snapshot-chunk",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:p,data:l};Vwe(n,d)}this.sendPackagesToClient(n),aa.info("[RepositoryServer] Sending envs-and-mappings",{clientId:t}),await this.sendEnvsAndMappingsToClient(n),aa.info("[RepositoryServer] Envs-and-mappings sent",{clientId:t});let u={type:"snapshot-complete",serverId:this.serverId,sequenceNumber:this.sequenceNumber++};Vwe(n,u),aa.info("[RepositoryServer] Snapshot complete sent",{clientId:t}),o.mode="draining",this.drainClientBuffer(t,n)}drainClientBuffer(t,n){let i=this.clients.get(t);if(i){for(let o of i.buffer)Vwe(n,o);i.buffer=[],i.mode="live"}}async parseFileToRepository(t){let n=await this.options.coordinator.parseFile(t);if(!n)return null;if(n.entityType==="NodeType"){let i=this.getEntityId(n,t),o={entityType:"NodeType",gitData:{...n.gitData,nodeType:{...n.gitData.nodeType,id:i}}};return this.convertGitToRepository(o)}return this.convertGitToRepository(n)}broadcastEntityUpdate(t,n){let i={type:"entity-update",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:t,data:n};this.broadcastToClients(i)}broadcastEntityDelete(t,n){let i={type:"entity-delete",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:t,id:n};this.broadcastToClients(i)}async buildEnvAndMappingsMessage(){let{locations:t,workspaceMappings:n,environments:i}=await this.options.coordinator.getMappingsSnapshot(),o=await this.getPlatformKind(),s={},a=t?.locations||[];for(let u of a)s[u]={};for(let u of a){let p=n?.[u];s[u]||(s[u]={}),s[u].__workspace__={database:p?.database??"",schema:p?.schema??""}}for(let u of i)for(let p of Object.keys(u.mappingDefinitions||{})){s[p]||(s[p]={});let c=u.mappingDefinitions[p];c&&(s[p][u.id]={database:c.database??"",schema:c.schema??""})}return{type:"env-and-mappings-updated",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,data:{mappings:s,environments:i.map(u=>({id:u.id,name:u.name,type:u.type,fileVersion:u.fileVersion})),defaultStorageMapping:t?.defaultStorageMapping||null,platformKind:o}}}async broadcastMappingsUpdate(){try{let t=await this.buildEnvAndMappingsMessage();this.broadcastToClients(t),aa.info("[RepositoryServer] Broadcasted env-and-mappings-updated")}catch(t){aa.error("[RepositoryServer] Failed to broadcast mappings update",{error:t instanceof Error?t.message:String(t)})}}broadcastToClients(t){let n=[];for(let[i,o]of this.clients.entries())if(o.mode==="live"){if(!Vwe(o.res,t)){aa.debug("[RepositoryServer] Client disconnected during broadcast",{clientId:i}),n.push(i);continue}}else{if(o.buffer.length>=this.MAX_CLIENT_BUFFER_SIZE){aa.error("[RepositoryServer] Client buffer exceeded limit, disconnecting",{clientId:i,bufferSize:o.buffer.length,limit:this.MAX_CLIENT_BUFFER_SIZE});try{o.res.end()}catch{}n.push(i);continue}o.buffer.push(t)}for(let i of n)this.cleanupClient(i)}getPackagesData(){let t=this.options.coordinator.readPackageCache();return t?Object.values(t):[]}sendPackagesToClient(t){let n={type:"snapshot-chunk",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:"Package",data:this.getPackagesData()};Vwe(t,n)}broadcastPackagesUpdate(){let t={type:"entity-bulk-update",serverId:this.serverId,sequenceNumber:this.sequenceNumber++,entityType:"Package",data:this.getPackagesData()};this.broadcastToClients(t)}async sendEnvsAndMappingsToClient(t){try{let n=await this.buildEnvAndMappingsMessage();Vwe(t,n),aa.info("[RepositoryServer] Sent envs-and-mappings to snapshot client")}catch(n){aa.error("[RepositoryServer] Failed to send envs-and-mappings to snapshot client",{error:n instanceof Error?n.message:String(n)})}}convertGitToRepository(t){try{switch(t.entityType){case"Node":return JPd(t.gitData);case"Job":return Ueu(t.gitData);case"Macro":return $Pd(t.gitData);case"Subgraph":return XPd(t.gitData);case"NodeType":return zeu(t.gitData);case"Environment":case"Package":return t.gitData}}catch(n){return aa.error("[RepositoryServer] Failed to convert Git \u2192 Repository",{entityType:t.entityType,error:n instanceof Error?n.message:String(n)}),null}}async handleNodeWrite(t,n){try{let i=t.params.id,o=t.body;aa.info("[RepositoryServer] handleNodeWrite received",{nodeId:i,hasOperation:!!o.operation,operationKeys:o.operation?Object.keys(o.operation):[],operationName:o.operation?.name});let s={operation:{...o.operation,id:i}};aa.info("[RepositoryServer] handleNodeWrite after merge",{nodeId:i,operationKeys:Object.keys(s.operation),operationId:s.operation.id,operationName:s.operation.name});let a=jeu(s);await this.enqueue({type:"WriteNode",node:a,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Node write failed",{nodeId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write node",details:o,nodeId:t.params.id})}}async handleNodeWriteV2(t,n){try{let i=t.params.id,{sql:o,name:s,location:a}=t.body;aa.info("[RepositoryServer] handleNodeWriteV2",{nodeId:i,name:s,location:a}),await this.enqueue({type:"WriteSQLNode",nodeId:i,sql:o,name:s,location:a,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] V2 node write failed",{nodeId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write node",details:o})}}async handleJobCreate(t,n){try{let i=t.body,o=i.id,s=Qeu({name:i.name??"",includeSelector:i.includeSelector??"",excludeSelector:i.excludeSelector??"",version:2,id:o,jobCounter:o});await this.enqueue({type:"WriteJob",job:s,reply:()=>{}}),n.json({id:o})}catch(i){aa.error("[RepositoryServer] Job create failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to create job",details:o})}}async handleJobUpdate(t,n){try{let i=t.params.id,o=t.body;await this.enqueue({type:"UpdateJob",jobId:i,partialUpdate:o,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Job update failed",{jobId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to update job",details:o,jobId:t.params.id})}}async handleMacroWrite(t,n){try{let i=t.params.id,o=t.body,s=ZPd({...o,id:i});await this.enqueue({type:"WriteMacro",macro:s,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Macro write failed",{macroId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write macro",details:o,macroId:t.params.id})}}async handleSubgraphCreate(t,n){try{aa.info("[RepositoryServer] Subgraph create request received",{body:t.body});let i=t.body,o=i.id;aa.info("[RepositoryServer] Converting subgraph",{subgraphId:o,repositorySubgraph:i});let s=Geu({...i,id:o});await this.enqueue({type:"WriteSubgraph",subgraph:s,reply:()=>{}}),n.json({id:o})}catch(i){aa.error("[RepositoryServer] Subgraph create failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to create subgraph",details:o})}}async handleSubgraphUpdate(t,n){try{let i=t.params.id,o=t.body,s=Geu({...o,id:i});await this.enqueue({type:"WriteSubgraph",subgraph:s,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Subgraph update failed",{subgraphId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to update subgraph",details:o,subgraphId:t.params.id})}}async handleNodeTypeCreate(t,n){try{let i=t.body,o=crypto.randomUUID(),s={...i,id:o},a=Heu(s);await this.enqueue({type:"WriteNodeType",nodeType:a,reply:()=>{}}),n.json({id:o})}catch(i){aa.error("[RepositoryServer] NodeType create failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to create nodeType",details:o})}}async handleNodeTypeUpdate(t,n){try{let i=t.params.id,o=t.body;await this.enqueue({type:"UpdateNodeType",nodeTypeId:i,partialUpdate:o,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] NodeType update failed",{nodeTypeId:t.params.id,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to update nodeType",details:o,nodeTypeId:t.params.id})}}async handleEnvironmentWrite(t,n){try{let i=t.body;await this.enqueue({type:"WriteEnvironment",env:i,reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handlePackageWrite(t,n){try{let i=t.params.id,s={...t.body,id:i},a=e4d(s);await this.enqueue({type:"WritePackage",pkg:a,reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleBulkNodesWrite(t,n){try{let o=t.body.nodes.map((s,a)=>{try{return jeu(s)}catch(u){throw new Error(`Failed to convert node at index ${a}: ${u instanceof Error?u.message:String(u)}`)}});await this.enqueue({type:"WriteBulkNodes",nodes:o,reply:()=>{}}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Bulk nodes write failed",{count:t.body.nodes.length,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to write bulk nodes",details:o})}}async handleBulkNodesDelete(t,n){try{let{nodeIds:i}=t.body;if(!Array.isArray(i)||i.length===0){n.status(400).json({error:"nodeIds must be a non-empty array"});return}for(let o of i)await this.enqueue({type:"DeleteEntity",entityType:"Node",id:o,reply:()=>{}});n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Bulk nodes delete failed",{count:Array.isArray(t.body)?t.body.length:0,error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:"Failed to delete bulk nodes",details:o})}}async handleDelete(t,n,i){try{let o=n.params.id;await this.enqueue({type:"DeleteEntity",entityType:t,id:o,reply:()=>{}}),i.json({success:!0})}catch(o){let s=o instanceof Error?o.message:String(o);i.status(500).json({error:s})}}async handleCreateStorageLocation(t,n){try{let{name:i}=t.body,{locations:o,workspaceMappings:s,environments:a}=await this.options.coordinator.getMappingsSnapshot(),u=o?.locations||[];if(u.includes(i)){n.status(400).json({error:`Storage location '${i}' already exists`});return}await this.options.coordinator.writeLocations({locations:[...u,i],defaultStorageMapping:o?.defaultStorageMapping||null,fileVersion:1});let p={...s,[i]:{database:"",schema:""}};await this.options.coordinator.writeWorkspaceYml(p);for(let c of a){let l={...c,mappingDefinitions:{...c.mappingDefinitions,[i]:{database:"",schema:""}}};await this.options.coordinator.writeEnvironment(l)}n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Create storage location failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleDeleteStorageLocation(t,n){try{let{name:i}=t.params,{locations:o,workspaceMappings:s,environments:a}=await this.options.coordinator.getMappingsSnapshot(),p=(o?.locations||[]).filter(l=>l!==i);await this.options.coordinator.writeLocations({locations:p,defaultStorageMapping:o?.defaultStorageMapping===i?null:o?.defaultStorageMapping||null,fileVersion:1});let c={...s};delete c[i],await this.options.coordinator.writeWorkspaceYml(c);for(let l of a){let d={...l.mappingDefinitions};delete d[i];let f={...l,mappingDefinitions:d};await this.options.coordinator.writeEnvironment(f)}n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Delete storage location failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleSetDefaultStorageLocation(t,n){try{let{name:i}=t.body,{locations:o}=await this.options.coordinator.getMappingsSnapshot();await this.options.coordinator.writeLocations({locations:o?.locations||[],defaultStorageMapping:i,fileVersion:1}),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Set default storage location failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleUpdateEnvironmentMappings(t,n){try{let{environmentId:i,workspaceId:o}=t.query,{mappings:s,name:a}=t.body;if(aa.info("[RepositoryServer] Update environment mappings",{environmentId:i,workspaceId:o,mappings:s,name:a}),i===o)await this.options.coordinator.writeWorkspaceYml(s);else{let{environments:u}=await this.options.coordinator.getMappingsSnapshot(),p=u.find(l=>l.id===i),c={type:"Environment",fileVersion:1,id:i,name:a||p?.name||`Environment ${i}`,mappingDefinitions:s};await this.options.coordinator.writeEnvironment(c)}n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Update environment mappings failed",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitCheckout(t,n){try{let{branch:i,force:o}=t.body;await this.enqueue({type:"GitCheckout",branch:i,force:o??!1,reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitCommit(t,n){try{let{message:i,author:o}=t.body,s=await this.options.coordinator.gitCommit(i,o);n.json({commitSha:s})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitPush(t,n){try{let{branch:i,gitToken:o,gitUsername:s}=t.body;await this.options.coordinator.gitPush(i,o,s),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitStatus(t,n){try{let i=await this.options.coordinator.gitStatus();n.json({files:i.files})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitBranches(t,n){try{let i=await this.options.coordinator.gitBranches();n.json(i)}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitLog(t,n){try{let i=t.query.branch||"HEAD",o=t.query.limit?parseInt(t.query.limit,10):50,s=await this.options.coordinator.gitLog(i,o);n.json({commits:s})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitDiff(t,n){try{let i=t.query.file;if(!i||typeof i!="string"){n.status(400).json({error:"file query parameter required"});return}let o=await this.options.coordinator.gitDiff(i);n.json({diff:o})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitCreateBranch(t,n){try{let{name:i}=t.body;if(!i||typeof i!="string"){n.status(400).json({error:"Branch name required"});return}await this.options.coordinator.gitCreateBranch(i),n.json({branch:i})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleGitAddAll(t,n){try{await this.options.coordinator.gitAddAll(),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleRescan(t,n){try{await this.options.coordinator.rescan(),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}handleUpdateConfig(t,n){try{let{content:i}=t.body;if(!i){n.status(400).json({error:"content is required"});return}this.writeCoaConfig(i),n.json({success:!0})}catch(i){aa.error("[RepositoryServer] Failed to update COA config",{error:i instanceof Error?i.message:String(i)});let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async handleInstall(t,n){try{await this.enqueue({type:"CoaInstall",reply:()=>{}}),n.json({success:!0})}catch(i){let o=i instanceof Error?i.message:String(i);n.status(500).json({error:o})}}async processInstall(t){try{await this.runInstall(),t.reply()}catch(n){aa.error("[RepositoryServer] coa install failed",{error:n instanceof Error?n.message:String(n)}),t.reply(n instanceof Error?n:new Error(String(n)))}}processBroadcastPackagesUpdated(){this.broadcastPackagesUpdate()}getPathIndexKey(t,n){return`${t}:${n}`}findEntryByPath(t){for(let[n,i]of this.pathIndex.entries())if(i.path===t){let[o,s]=n.split(":");return{entityType:o,id:s}}}getEntityId(t,n){let i=S8.default.basename(n,S8.default.extname(n));switch(t.entityType){case"Node":if("id"in t.gitData&&typeof t.gitData.id=="string")return t.gitData.id;throw new Error(`Node file missing 'id' field: ${n}`);case"Job":case"Macro":case"Subgraph":case"Environment":{let o=i.lastIndexOf("-");if(o===-1)throw new Error(`${t.entityType} filename missing dash separator: ${n}`);return i.substring(o+1)}case"NodeType":{let o=S8.default.basename(S8.default.dirname(n)),s=o.indexOf("-");if(s===-1)throw new Error(`NodeType directory missing dash separator: ${n}`);return o.substring(s+1)}case"Package":return i;default:throw new Error(`Unknown entity type: ${t.entityType}`)}}async processChokidarBatch(t){let{changes:n,deletes:i,forceSnapshot:o}=t;aa.info("[RepositoryServer] Processing chokidar batch",{changes:n.length,deletes:i.length,forceSnapshot:o});let s=n.length+i.length,a=o||s>this.SNAPSHOT_THRESHOLD;a&&aa.info("[RepositoryServer] Will send snapshot instead of individual updates",{totalEvents:s,threshold:this.SNAPSHOT_THRESHOLD,forced:o});for(let u of n)try{let p=S8.default.basename(u);if(p==="locations.yml"||p==="workspace.yml"){await this.broadcastMappingsUpdate();continue}let c=await this.options.coordinator.parseFile(u);if(!c)continue;let l=this.getEntityId(c,u),d=this.getPathIndexKey(c.entityType,l);if(this.pathIndex.set(d,{path:u}),c.entityType==="Environment"){await this.broadcastMappingsUpdate();continue}if(c.entityType==="Package")continue;if(!a){let f=await this.parseFileToRepository(u);f&&this.broadcastEntityUpdate(c.entityType,f)}}catch(p){aa.error("[RepositoryServer] Failed to process file change",{path:u,error:p instanceof Error?p.message:String(p)})}for(let u of i)try{let p=this.findEntryByPath(u);if(!p){aa.debug("[RepositoryServer] Dropping programmatic delete event",{path:u});continue}let c=this.getPathIndexKey(p.entityType,p.id);this.pathIndex.delete(c),a||this.broadcastEntityDelete(p.entityType,p.id)}catch(p){aa.error("[RepositoryServer] Failed to process file delete",{path:u,error:p instanceof Error?p.message:String(p)})}if(a){let u=[];for(let[p,c]of this.pathIndex.entries()){let[l,d]=p.split(":");u.push({entityType:l,id:d,path:c.path})}aa.info("[RepositoryServer] Large batch - transitioning clients to snapshot mode",{entityCount:u.length,clientCount:this.clients.size});for(let p of this.clients.values())(p.mode==="live"||p.mode==="draining")&&(p.mode="snapshotting");this.sendSnapshotsAsync(u)}}async sendSnapshotsAsync(t){aa.info("[RepositoryServer] Broadcasting snapshots to all clients",{entityCount:t.length});for(let[n,i]of this.clients.entries())try{await this.sendSnapshotToClient(n,i.res,t)}catch(o){aa.error("[RepositoryServer] Failed to send snapshot to client",{clientId:n,error:o instanceof Error?o.message:String(o)}),this.clients.delete(n)}aa.info("[RepositoryServer] Snapshot broadcast complete")}async processSSEClientConnected(t){let{clientId:n,res:i}=t,o=[];for(let[s,a]of this.pathIndex.entries()){let[u,p]=s.split(":");o.push({entityType:u,id:p,path:a.path})}this.clients.set(n,{mode:"snapshotting",buffer:[],res:i}),t.reply();try{await this.sendSnapshotToClient(n,i,o)}catch(s){aa.error("[RepositoryServer] Snapshot failed",{clientId:n,error:s instanceof Error?s.message:String(s)}),this.clients.delete(n);try{i.end()}catch{}}}async processSSEClientDisconnected(t){this.cleanupClient(t.clientId)}cleanupClient(t){this.clients.delete(t);let n=this.keepaliveIntervals.get(t);n&&(clearInterval(n),this.keepaliveIntervals.delete(t))}async processWriteNode(t){let{node:n}=t,i=n.id,o=this.getPathIndexKey("Node",i),a=this.pathIndex.get(o)?.path;if(a?.endsWith(".sql")&&n.operation.type==="sql"){let{name:p,locationName:c}=n.operation,l=n.operation.metadata.sourceMapping?.[0]?.customSQL?.customSQL??"";aa.info("[RepositoryServer] v1 write to a .sql (v2) node \u2014 keeping .sql format",{nodeId:i,name:p,location:c}),await this.writeNodeAsSQL(i,l,p,c,t.reply);return}let u=this.options.coordinator.getPathForNode(n);this.pathIndex.set(o,{path:u});try{await this.options.coordinator.writeNode(n),a&&a!==u&&await this.options.coordinator.deleteFile(a),t.reply()}catch(p){a?this.pathIndex.set(o,{path:a}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWriteSQLNode(t){let{nodeId:n,sql:i,name:o,location:s}=t;await this.writeNodeAsSQL(n,i,o,s,t.reply)}async writeNodeAsSQL(t,n,i,o,s){let a=this.getPathIndexKey("Node",t),u=this.options.coordinator.getPathForSQLNode(i,o),c=this.pathIndex.get(a)?.path;this.pathIndex.set(a,{path:u});try{await this.options.coordinator.writeSQLNode(n,i,o),c&&c!==u&&await this.options.coordinator.deleteFile(c),s()}catch(l){c?this.pathIndex.set(a,{path:c}):this.pathIndex.delete(a),s(l instanceof Error?l:new Error(String(l)))}}async processWriteJob(t){let{job:n}=t,i=String(n.id),o=this.getPathIndexKey("Job",i),s=this.options.coordinator.getPathForJob(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeJob(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processUpdateJob(t){let{jobId:n,partialUpdate:i}=t,o=this.getPathIndexKey("Job",n),s=this.pathIndex.get(o);try{let a={...i,id:Number(n)};if(s){let l=await this.options.coordinator.parseFile(s.path);if(l&&l.entityType==="Job"){let d=Ueu(l.gitData);a=iQe({},d,i,{id:Number(n)})}}let u=Qeu(a),p=this.options.coordinator.getPathForJob(u),c=s?.path;this.pathIndex.set(o,{path:p}),await this.options.coordinator.writeJob(u),c&&c!==p&&await this.options.coordinator.deleteFile(c),t.reply()}catch(a){s?this.pathIndex.set(o,s):this.pathIndex.delete(o),t.reply(a instanceof Error?a:new Error(String(a)))}}async processWriteMacro(t){let{macro:n}=t,i=n.id,o=this.getPathIndexKey("Macro",i),s=this.options.coordinator.getPathForMacro(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeMacro(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWriteSubgraph(t){let{subgraph:n}=t,i=String(n.id),o=this.getPathIndexKey("Subgraph",i),s=this.options.coordinator.getPathForSubgraph(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeSubgraph(n),aa.info("[RepositoryServer] processWriteSubgraph completed",{id:i,newPath:s,oldPath:u}),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWriteNodeType(t){let{nodeType:n}=t,i=String(n.nodeType.id);if(i==="Source"){t.reply();return}let o=this.getPathIndexKey("NodeType",i),s=this.options.coordinator.getPathForNodeType(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeNodeType(n),u&&u!==s&&await this.options.coordinator.deleteDirectory(S8.default.dirname(u)),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processUpdateNodeType(t){let{nodeTypeId:n,partialUpdate:i}=t;if(n==="Source"){t.reply();return}let o=this.getPathIndexKey("NodeType",n),s=this.pathIndex.get(o);try{let a={...i,id:n};if(s){let l=S8.default.dirname(s.path),d=S8.default.join(l,"definition.yml"),f=await this.options.coordinator.parseFile(d);if(f&&f.entityType==="NodeType"){let h={...f.gitData,nodeType:{...f.gitData.nodeType,id:n}};a=iQe({},zeu(h),i,{id:n})}}let u=Heu(a),p=this.options.coordinator.getPathForNodeType(u),c=s?.path;this.pathIndex.set(o,{path:p}),await this.options.coordinator.writeNodeType(u),c&&c!==p&&await this.options.coordinator.deleteDirectory(S8.default.dirname(c)),t.reply()}catch(a){s?this.pathIndex.set(o,s):this.pathIndex.delete(o),t.reply(a instanceof Error?a:new Error(String(a)))}}async processWriteEnvironment(t){let{env:n}=t,i=String(n.id),o=this.getPathIndexKey("Environment",i),s=this.options.coordinator.getPathForEnvironment(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s});try{await this.options.coordinator.writeEnvironment(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),t.reply()}catch(p){u?this.pathIndex.set(o,{path:u}):this.pathIndex.delete(o),t.reply(p instanceof Error?p:new Error(String(p)))}}async processWritePackage(t){let{pkg:n}=t,i=n.packageID,o=this.getPathIndexKey("Package",i),s=this.options.coordinator.getPathForPackage(n),u=this.pathIndex.get(o)?.path;this.pathIndex.set(o,{path:s}),await this.options.coordinator.writePackage(n),u&&u!==s&&await this.options.coordinator.deleteFile(u),await this.runInstall(),t.reply()}async processWriteBulkNodes(t){let{nodes:n}=t,i=[];for(let o of n){let s=o.id,a=this.getPathIndexKey("Node",s),u=this.options.coordinator.getPathForNode(o),p=this.pathIndex.get(a)?.path;this.pathIndex.set(a,{path:u}),p&&p!==u&&i.push({oldPath:p,newPath:u})}await this.options.coordinator.writeBulkNodes(n);for(let{oldPath:o}of i)await this.options.coordinator.deleteFile(o);t.reply()}async processDeleteEntity(t){let{entityType:n,id:i}=t,o=this.getPathIndexKey(n,i),s=this.pathIndex.get(o);if(!s){t.reply(new Error(`Entity not found: ${n}:${i}`));return}this.pathIndex.delete(o);try{n==="NodeType"?await this.options.coordinator.deleteDirectory(S8.default.dirname(s.path)):await this.options.coordinator.deleteFile(s.path)}catch(a){this.pathIndex.set(o,s),t.reply(a instanceof Error?a:new Error(String(a)));return}if(this.broadcastEntityDelete(n,i),t.reply(),n==="Package")try{await this.runInstall()}catch(a){aa.error("[RepositoryServer] coa install failed after package delete",{id:i,error:a instanceof Error?a.message:String(a)})}}async processWriteDataYml(t){try{await this.options.coordinator.writeDataYml(t.data),t.reply()}catch(n){t.reply(n instanceof Error?n:new Error(String(n)))}}async processWriteLocations(t){try{await this.options.coordinator.writeLocations(t.locations),t.reply()}catch(n){t.reply(n instanceof Error?n:new Error(String(n)))}}async processGitCheckout(t){try{let{branch:n,force:i}=t;await this.options.coordinator.gitCheckout(n,i),this.pathIndex.clear(),await this.options.coordinator.rescan(),t.reply()}catch(n){t.reply(n instanceof Error?n:new Error(String(n)));return}await this.runInstall()}writeCoaConfig(t){let n=S8.default.join(oNd.default.homedir(),".coa","config"),i=S8.default.dirname(n);ttu.default.mkdirSync(i,{recursive:!0,mode:448}),ttu.default.writeFileSync(n,t,{encoding:"utf-8",mode:384}),aa.info("[RepositoryServer] Updated COA config")}async runInstall(){let t=this.options.coordinator.getWorkspaceDir(),{stderr:n}=await tCE("coa",["install","-d",t]);n&&aa.warn("[RepositoryServer] coa install stderr",{stderr:n}),aa.info("[RepositoryServer] coa install completed"),this.processBroadcastPackagesUpdated()}enqueue(t){return new Promise((n,i)=>{let o={...t,reply:s=>{s instanceof Error?i(s):n(s)}};this.queue.push(o),this.processQueue()})}enqueueNoReply(t){this.queue.push(t),this.processQueue()}async processQueue(){if(!(this.processing||this.queue.length===0)){for(this.processing=!0;this.queue.length>0;){let t=this.queue.shift();try{await this.handleMessage(t)}catch(n){aa.error("[RepositoryServer] Message processing failed",{messageType:t.type,error:n instanceof Error?n.message:String(n)}),"reply"in t&&t.reply(n instanceof Error?n:new Error(String(n)))}}this.processing=!1}}async handleMessage(t){switch(t.type){case"WriteNode":await this.processWriteNode(t);break;case"WriteSQLNode":await this.processWriteSQLNode(t);break;case"WriteJob":await this.processWriteJob(t);break;case"UpdateJob":await this.processUpdateJob(t);break;case"WriteMacro":await this.processWriteMacro(t);break;case"WriteSubgraph":await this.processWriteSubgraph(t);break;case"WriteNodeType":await this.processWriteNodeType(t);break;case"UpdateNodeType":await this.processUpdateNodeType(t);break;case"WriteEnvironment":await this.processWriteEnvironment(t);break;case"WritePackage":await this.processWritePackage(t);break;case"WriteBulkNodes":await this.processWriteBulkNodes(t);break;case"DeleteEntity":await this.processDeleteEntity(t);break;case"WriteDataYml":await this.processWriteDataYml(t);break;case"WriteLocations":await this.processWriteLocations(t);break;case"GitCheckout":await this.processGitCheckout(t);break;case"ProcessChokidarBatch":await this.processChokidarBatch(t);break;case"BroadcastPackagesUpdated":this.processBroadcastPackagesUpdated();break;case"CoaInstall":await this.processInstall(t);break;case"SSEClientConnected":await this.processSSEClientConnected(t);break;case"SSEClientDisconnected":await this.processSSEClientDisconnected(t);break;default:{let n=t;throw new Error(`Unknown message type: ${n.type}`)}}}async readPlatformKindFromDataYml(){try{let t=await this.options.coordinator.loadDataYml(),n=jh.safeParse(t?.platformKind);return n.success?n.data:void 0}catch{return}}async getPlatformKind(){return await this.readPlatformKindFromDataYml()??"snowflake"}getDefaultSourceNodeType(t){let i=lNe(t).Source;if(!i)throw new Error(`Source node type not found in defaults for platform ${t}`);return i}async handleListApps(t,n){try{let i=await this.appManager.discoverApps();n.json({apps:i})}catch(i){aa.error("[RepositoryServer] Failed to list apps",{error:i}),n.status(500).json({error:{errorString:String(i)}})}}async handleAppProxy(t,n){let{appId:i}=t.params;if(!i){n.status(400).json({error:{errorString:"appId required"}});return}let o;try{o=await this.appManager.ensureRunning(i)}catch(p){aa.error("[RepositoryServer] Failed to start app for proxy",{appId:i,error:p}),n.status(502).json({error:{errorString:String(p)}});return}let s=`/api/v1/watch/apps/${i}/proxy`,a=t.originalUrl.slice(t.originalUrl.indexOf(s)+s.length)||"/",u=`${o}${a}`;try{let p={};t.headers["content-type"]&&(p["content-type"]=t.headers["content-type"]),t.headers.accept&&(p.accept=t.headers.accept);let c=await fetch(u,{method:t.method,headers:p,body:t.method!=="GET"&&t.method!=="HEAD"?JSON.stringify(t.body):void 0});if(n.status(c.status),c.headers.forEach((l,d)=>{d!=="transfer-encoding"&&n.setHeader(d,l)}),c.body){let l=c.body.getReader();try{for(;;){let{done:d,value:f}=await l.read();if(d)break;n.write(f)}}finally{l.releaseLock()}}n.end()}catch(p){aa.error("[RepositoryServer] App proxy error",{appId:i,error:p}),n.headersSent||n.status(502).json({error:{errorString:String(p)}})}}};var fY=require("fs"),t1e=yt(require("path"));var Eae=yt(require("crypto")),aNd=yt(require("fs")),O1=require("fs"),Up=yt(require("path"));var bae=Je("COA_WATCH"),rCE=mce.strip().extend({contents:mce.shape.contents.strip()});async function uNd(r,t,n,i="snowflake"){try{let o=await O1.promises.readFile(r,"utf-8"),s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16),u=Up.default.relative(t,r).split(Up.default.sep);if(u[0]==="nodes"&&r.endsWith(".sql"))return{entityType:"Node",data:await hxr({fileData:o,filePath:r,type:"File"},n,i),hash:s};if(u[0]==="nodes"&&r.endsWith(".yml"))return{entityType:"Node",data:Sp(r,o),hash:s};if(u[0]==="jobs"&&r.endsWith(".yml"))return{entityType:"Job",data:Sp(r,o),hash:s};if(u[0]==="macros"&&r.endsWith(".yml"))return{entityType:"Macro",data:Sp(r,o),hash:s};if(u[0]==="subgraphs"&&r.endsWith(".yml"))return{entityType:"Subgraph",data:Sp(r,o),hash:s};if(u[0]==="nodeTypes"&&u[u.length-1]==="definition.yml"){let p=await nCE(Up.default.dirname(r),n);if(p)return{entityType:"NodeType",data:p,hash:s}}else{if(u[0]==="environments"&&r.endsWith(".yml"))return{entityType:"Environment",data:Sp(r,o),hash:s};if(u[0]==="packages"&&r.endsWith(".yml"))return{entityType:"Package",data:Sp(r,o),hash:s}}return null}catch(o){return bae.error("[FileIO] Error parsing file",{filePath:r,error:o instanceof Error?o.message:String(o)}),null}}async function nCE(r,t){try{let n=Up.default.join(r,"definition.yml"),i=await O1.promises.readFile(n,"utf-8"),o=Sp(n,i),s=Up.default.join(r,"create.sql"),a=Up.default.join(r,"create.sql.j2"),u=Up.default.join(r,"run.sql"),p=Up.default.join(r,"run.sql.j2"),c=await O1.promises.readFile(s,"utf-8").catch(()=>null)||await O1.promises.readFile(a,"utf-8").catch(()=>null),l=await O1.promises.readFile(u,"utf-8").catch(()=>null)||await O1.promises.readFile(p,"utf-8").catch(()=>null);return{nodeType:o,create:c||"",run:l||""}}catch(n){return bae.error("[FileIO] Failed to parse NodeType",{nodeTypeDir:r,error:n instanceof Error?n.message:String(n)}),null}}async function rtu(r,t){_Z.parse(r);let n=r.operation.name,i=r.operation.locationName,o=BR(`${i}-${n}`),s=Up.default.join(t,"nodes",`${o}.yml`);await O1.promises.mkdir(Up.default.dirname(s),{recursive:!0});let a=UA(r,{sortKeys:!0});await O1.promises.writeFile(s,a,"utf-8");let u=Eae.createHash("sha256").update(a).digest("hex").substring(0,16);return{path:s,hash:u}}async function cNd(r,t){if(WH.parse(r),!r.name)throw new Error(`Job ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"jobs",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function lNd(r,t){if(TZ.parse(r),!r.name)throw new Error(`Macro ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"macros",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function pNd(r,t){if(IZ.parse(r),!r.name)throw new Error(`Subgraph ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"subgraphs",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function dNd(r,t){if(_2e.parse(r),!r.name)throw new Error(`Environment ${r.id} missing required name field`);let n=BR(`${r.name}-${r.id}`),i=Up.default.join(t,"environments",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function fNd(r,t){tbe.parse(r);let n=BR(r.name),i=Up.default.join(t,"packages",`${n}.yml`);await O1.promises.mkdir(Up.default.dirname(i),{recursive:!0});let o=UA(r,{sortKeys:!0});await O1.promises.writeFile(i,o,"utf-8");let s=Eae.createHash("sha256").update(o).digest("hex").substring(0,16);return{path:i,hash:s}}async function hNd(r,t){let{nodeType:n,create:i,run:o}=r;if(!n.name)throw new Error(`NodeType ${n.id} missing required name field`);let s=BR(`${n.name}-${n.id}`),a=Up.default.join(t,"nodeTypes",s);await O1.promises.mkdir(a,{recursive:!0});let u=Up.default.join(a,"definition.yml"),p=UA(n,{sortKeys:!0});if(await O1.promises.writeFile(u,p,"utf-8"),i){let l=Up.default.join(a,"create.sql.j2");await O1.promises.writeFile(l,i,"utf-8")}if(o){let l=Up.default.join(a,"run.sql.j2");await O1.promises.writeFile(l,o,"utf-8")}let c=Eae.createHash("sha256").update(p).digest("hex").substring(0,16);return{definitionPath:u,hash:c}}async function gNd(r){try{let t=Up.default.join(r,"data.yml"),n=await O1.promises.readFile(t,"utf-8");return Sp(t,n)}catch(t){return bae.error("[FileIO] Failed to load data.yml",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),null}}async function ANd(r){try{let t=Up.default.join(r,"locations.yml"),n=await O1.promises.readFile(t,"utf-8");return Sp(t,n)}catch(t){return bae.error("[FileIO] Failed to load locations.yml",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),null}}async function mNd(r){try{let t=Up.default.join(r,"environments"),n=await O1.promises.readdir(t),i=[];for(let o of n)if(o.endsWith(".yml"))try{let s=Up.default.join(t,o),a=await O1.promises.readFile(s,"utf-8"),u=Sp(s,a);u&&i.push(u)}catch(s){bae.warn("[FileIO] Failed to load environment file",{file:o,error:s instanceof Error?s.message:String(s)})}return i}catch(t){return bae.error("[FileIO] Failed to load environments directory",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),[]}}async function yNd(r){try{let t=Up.default.join(r,"workspace.yml"),n=await O1.promises.readFile(t,"utf-8");return Sp(t,n).locations||null}catch(t){return t instanceof Error&&t.message.includes("ENOENT")||bae.error("[FileIO] Failed to load workspace.yml",{workspaceDir:r,error:t instanceof Error?t.message:String(t)}),null}}async function bNd(r,t){let n=Up.default.join(r,"workspace.yml"),i=UA({locations:t},{sortKeys:!0});await O1.promises.writeFile(n,i,"utf-8")}function ENd(r,t){let n=t.operation.locationName,i=t.operation.name,o=BR(`${n}-${i}`);return Up.default.join(r,"nodes",`${o}.yml`)}function ntu(r,t,n){let i=BR(`${n}-${t}`);return Up.default.join(r,"nodes",`${i}.sql`)}async function CNd(r,t,n,i){let o=ntu(i,t,n);await O1.promises.mkdir(Up.default.dirname(o),{recursive:!0}),await O1.promises.writeFile(o,r,"utf-8");let s=Eae.createHash("sha256").update(r).digest("hex").substring(0,16);return{path:o,hash:s}}function SNd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"jobs",`${n}.yml`)}function vNd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"macros",`${n}.yml`)}function TNd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"subgraphs",`${n}.yml`)}function _Nd(r,t){let n=BR(`${t.nodeType.name}-${t.nodeType.id}`);return Up.default.join(r,"nodeTypes",n,"definition.yml")}function INd(r,t){let n=BR(`${t.name}-${t.id}`);return Up.default.join(r,"environments",`${n}.yml`)}function RNd(r,t){let n=BR(t.name);return Up.default.join(r,"packages",`${n}.yml`)}var iCE=".coa/cache",oCE="packages.json";function ONd(r){let t=Up.default.join(r,iCE,oCE);try{let n=JSON.parse(aNd.readFileSync(t,"utf-8"));if(typeof n!="object"||n===null)return bae.warn("[FileIO] Package cache is not a valid object",{cachePath:t}),null;let i={};for(let[o,s]of Object.entries(n)){let a=rCE.safeParse(s);a.success?i[o]=a.data:bae.warn("[FileIO] Skipping invalid package in cache",{alias:o})}return Object.keys(i).length>0?i:null}catch(n){return bae.error("[FileIO] Failed to read package cache",{cachePath:t,error:n instanceof Error?n.message:String(n)}),null}}var GNd=require("node:events"),HNd=require("node:fs"),Jio=require("node:fs/promises"),R0=yt(require("node:path"),1);var Zhe=require("node:fs/promises"),e1e=require("node:path"),PNd=require("node:stream"),r7={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},itu={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:r7.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(itu);var NNd="READDIRP_RECURSIVE_ERROR",aCE=new Set(["ENOENT","EPERM","EACCES","ELOOP",NNd]),wNd=[r7.DIR_TYPE,r7.EVERYTHING_TYPE,r7.FILE_DIR_TYPE,r7.FILE_TYPE],uCE=new Set([r7.DIR_TYPE,r7.EVERYTHING_TYPE,r7.FILE_DIR_TYPE]),cCE=new Set([r7.EVERYTHING_TYPE,r7.FILE_DIR_TYPE,r7.FILE_TYPE]),lCE=r=>aCE.has(r.code),pCE=process.platform==="win32",MNd=r=>!0,xNd=r=>{if(r===void 0)return MNd;if(typeof r=="function")return r;if(typeof r=="string"){let t=r.trim();return n=>n.basename===t}if(Array.isArray(r)){let t=r.map(n=>n.trim());return n=>t.some(i=>n.basename===i)}return MNd},otu=class extends PNd.Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let n={...itu,...t},{root:i,type:o}=n;this._fileFilter=xNd(n.fileFilter),this._directoryFilter=xNd(n.directoryFilter);let s=n.lstat?Zhe.lstat:Zhe.stat;pCE?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:itu.depth,this._wantsDir=o?uCE.has(o):!1,this._wantsFile=o?cCE.has(o):!1,this._wantsEverything=o===r7.EVERYTHING_TYPE,this._root=(0,e1e.resolve)(i),this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let n=this.parent,i=n&&n.files;if(i&&i.length>0){let{path:o,depth:s}=n,a=i.splice(0,t).map(p=>this._formatEntry(p,o)),u=await Promise.all(a);for(let p of u){if(!p)continue;if(this.destroyed)return;let c=await this._getEntryType(p);c==="directory"&&this._directoryFilter(p)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(p.fullPath,s+1)),this._wantsDir&&(this.push(p),t--)):(c==="file"||this._includeAsFile(p))&&this._fileFilter(p)&&this._wantsFile&&(this.push(p),t--)}}else{let o=this.parents.pop();if(!o){this.push(null);break}if(this.parent=await o,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(t,n){let i;try{i=await(0,Zhe.readdir)(t,this._rdOptions)}catch(o){this._onError(o)}return{files:i,depth:n,path:t}}async _formatEntry(t,n){let i,o=this._isDirent?t.name:t;try{let s=(0,e1e.resolve)((0,e1e.join)(n,o));i={path:(0,e1e.relative)(this._root,s),fullPath:s,basename:o},i[this._statsProp]=this._isDirent?t:await this._stat(s)}catch(s){this._onError(s);return}return i}_onError(t){lCE(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let n=t[this._statsProp];if(n.isFile())return"file";if(n.isDirectory())return"directory";if(n&&n.isSymbolicLink()){let i=t.fullPath;try{let o=await(0,Zhe.realpath)(i),s=await(0,Zhe.lstat)(o);if(s.isFile())return"file";if(s.isDirectory()){let a=o.length;if(i.startsWith(o)&&i.substr(a,1)===e1e.sep){let u=new Error(`Circular symlink detected: "${i}" points to "${o}"`);return u.code=NNd,this._onError(u)}return"directory"}}catch(o){return this._onError(o),""}}}_includeAsFile(t){let n=t&&t[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function DNd(r,t={}){let n=t.entryType||t.type;if(n==="both"&&(n=r7.FILE_DIR_TYPE),n&&(t.type=n),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!wNd.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${wNd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=r,new otu(t)}var DFe=require("node:fs"),dY=require("node:fs/promises"),LNd=require("node:os"),OE=yt(require("node:path"),1),dCE="data",utu="end",kNd="close",Vio=()=>{};var Wio=process.platform,ctu=Wio==="win32",fCE=Wio==="darwin",hCE=Wio==="linux",gCE=Wio==="freebsd",qNd=(0,LNd.type)()==="OS400",P2={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},pY=P2,ACE="watch",mCE={lstat:dY.lstat,stat:dY.stat},NFe="listeners",Qio="errHandlers",Qyt="rawEmitters",yCE=[NFe,Qio,Qyt],bCE=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),ECE=r=>bCE.has(OE.extname(r).slice(1).toLowerCase()),atu=(r,t)=>{r instanceof Set?r.forEach(t):t(r)},rYt=(r,t,n)=>{let i=r[t];i instanceof Set||(r[t]=i=new Set([i])),i.add(n)},CCE=r=>t=>{let n=r[t];n instanceof Set?n.clear():delete r[t]},nYt=(r,t,n)=>{let i=r[t];i instanceof Set?i.delete(n):i===n&&delete r[t]},FNd=r=>r instanceof Set?r.size===0:!r,jio=new Map;function BNd(r,t,n,i,o){let s=(a,u)=>{n(r),o(a,u,{watchedPath:r}),u&&r!==u&&Gio(OE.resolve(r,u),NFe,OE.join(r,u))};try{return(0,DFe.watch)(r,{persistent:t.persistent},s)}catch(a){i(a);return}}var Gio=(r,t,n,i,o)=>{let s=jio.get(r);s&&atu(s[t],a=>{a(n,i,o)})},SCE=(r,t,n,i)=>{let{listener:o,errHandler:s,rawEmitter:a}=i,u=jio.get(t),p;if(!n.persistent)return p=BNd(r,n,o,s,a),p?p.close.bind(p):void 0;if(u)rYt(u,NFe,o),rYt(u,Qio,s),rYt(u,Qyt,a);else{if(p=BNd(r,n,Gio.bind(null,t,NFe),s,Gio.bind(null,t,Qyt)),!p)return;p.on(pY.ERROR,async c=>{let l=Gio.bind(null,t,Qio);if(u&&(u.watcherUnusable=!0),ctu&&c.code==="EPERM")try{await(await(0,dY.open)(r,"r")).close(),l(c)}catch{}else l(c)}),u={listeners:o,errHandlers:s,rawEmitters:a,watcher:p},jio.set(t,u)}return()=>{nYt(u,NFe,o),nYt(u,Qio,s),nYt(u,Qyt,a),FNd(u.listeners)&&(u.watcher.close(),jio.delete(t),yCE.forEach(CCE(u)),u.watcher=void 0,Object.freeze(u))}},stu=new Map,vCE=(r,t,n,i)=>{let{listener:o,rawEmitter:s}=i,a=stu.get(t),u=a&&a.options;return u&&(u.persistent<n.persistent||u.interval>n.interval)&&((0,DFe.unwatchFile)(t),a=void 0),a?(rYt(a,NFe,o),rYt(a,Qyt,s)):(a={listeners:o,rawEmitters:s,options:n,watcher:(0,DFe.watchFile)(t,n,(p,c)=>{atu(a.rawEmitters,d=>{d(pY.CHANGE,t,{curr:p,prev:c})});let l=p.mtimeMs;(p.size!==c.size||l>c.mtimeMs||l===0)&&atu(a.listeners,d=>d(r,p))})},stu.set(t,a)),()=>{nYt(a,NFe,o),nYt(a,Qyt,s),FNd(a.listeners)&&(stu.delete(t),(0,DFe.unwatchFile)(t),a.options=a.watcher=void 0,Object.freeze(a))}},Hio=class{fsw;_boundHandleError;constructor(t){this.fsw=t,this._boundHandleError=n=>t._handleError(n)}_watchWithNodeFs(t,n){let i=this.fsw.options,o=OE.dirname(t),s=OE.basename(t);this.fsw._getWatchedDir(o).add(s);let u=OE.resolve(t),p={persistent:i.persistent};n||(n=Vio);let c;if(i.usePolling){let l=i.interval!==i.binaryInterval;p.interval=l&&ECE(s)?i.binaryInterval:i.interval,c=vCE(t,u,p,{listener:n,rawEmitter:this.fsw._emitRaw})}else c=SCE(t,u,p,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return c}_handleFile(t,n,i){if(this.fsw.closed)return;let o=OE.dirname(t),s=OE.basename(t),a=this.fsw._getWatchedDir(o),u=n;if(a.has(s))return;let p=async(l,d)=>{if(this.fsw._throttle(ACE,t,5)){if(!d||d.mtimeMs===0)try{let f=await(0,dY.stat)(t);if(this.fsw.closed)return;let h=f.atimeMs,A=f.mtimeMs;if((!h||h<=A||A!==u.mtimeMs)&&this.fsw._emit(pY.CHANGE,t,f),(fCE||hCE||gCE)&&u.ino!==f.ino){this.fsw._closeFile(l),u=f;let E=this._watchWithNodeFs(t,p);E&&this.fsw._addPathCloser(l,E)}else u=f}catch{this.fsw._remove(o,s)}else if(a.has(s)){let f=d.atimeMs,h=d.mtimeMs;(!f||f<=h||h!==u.mtimeMs)&&this.fsw._emit(pY.CHANGE,t,d),u=d}}},c=this._watchWithNodeFs(t,p);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(pY.ADD,t,0))return;this.fsw._emit(pY.ADD,t,n)}return c}async _handleSymlink(t,n,i,o){if(this.fsw.closed)return;let s=t.fullPath,a=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let u;try{u=await(0,dY.realpath)(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(o)?this.fsw._symlinkPaths.get(s)!==u&&(this.fsw._symlinkPaths.set(s,u),this.fsw._emit(pY.CHANGE,i,t.stats)):(a.add(o),this.fsw._symlinkPaths.set(s,u),this.fsw._emit(pY.ADD,i,t.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(t,n,i,o,s,a,u){t=OE.join(t,"");let p=o?`${t}:${o}`:t;if(u=this.fsw._throttle("readdir",p,1e3),!u)return;let c=this.fsw._getWatchedDir(i.path),l=new Set,d=this.fsw._readdirp(t,{fileFilter:f=>i.filterPath(f),directoryFilter:f=>i.filterDir(f)});if(d)return d.on(dCE,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,A=OE.join(t,h);if(l.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,t,A,h))){if(this.fsw.closed){d=void 0;return}(h===o||!o&&!c.has(h))&&(this.fsw._incrReadyCount(),A=OE.join(s,OE.relative(s,A)),this._addToNodeFs(A,n,i,a+1))}}).on(pY.ERROR,this._boundHandleError),new Promise((f,h)=>{if(!d)return h();d.once(utu,()=>{if(this.fsw.closed){d=void 0;return}let A=u?u.clear():!1;f(void 0),c.getChildren().filter(E=>E!==t&&!l.has(E)).forEach(E=>{this.fsw._remove(t,E)}),d=void 0,A&&this._handleRead(t,!1,i,o,s,a,u)})})}async _handleDir(t,n,i,o,s,a,u){let p=this.fsw._getWatchedDir(OE.dirname(t)),c=p.has(OE.basename(t));!(i&&this.fsw.options.ignoreInitial)&&!s&&!c&&this.fsw._emit(pY.ADD_DIR,t,n),p.add(OE.basename(t)),this.fsw._getWatchedDir(t);let l,d,f=this.fsw.options.depth;if((f==null||o<=f)&&!this.fsw._symlinkPaths.has(u)){if(!s&&(await this._handleRead(t,i,a,s,t,o,l),this.fsw.closed))return;d=this._watchWithNodeFs(t,(h,A)=>{A&&A.mtimeMs===0||this._handleRead(h,!1,a,s,t,o,l)})}return d}async _addToNodeFs(t,n,i,o,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return a(),!1;let u=this.fsw._getWatchHelpers(t);i&&(u.filterPath=p=>i.filterPath(p),u.filterDir=p=>i.filterDir(p));try{let p=await mCE[u.statMethod](u.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(u.watchPath,p))return a(),!1;let c=this.fsw.options.followSymlinks,l;if(p.isDirectory()){let d=OE.resolve(t),f=c?await(0,dY.realpath)(t):t;if(this.fsw.closed||(l=await this._handleDir(u.watchPath,p,n,o,s,u,f),this.fsw.closed))return;d!==f&&f!==void 0&&this.fsw._symlinkPaths.set(d,f)}else if(p.isSymbolicLink()){let d=c?await(0,dY.realpath)(t):t;if(this.fsw.closed)return;let f=OE.dirname(u.watchPath);if(this.fsw._getWatchedDir(f).add(u.watchPath),this.fsw._emit(pY.ADD,u.watchPath,p),l=await this._handleDir(f,p,n,o,t,u,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(OE.resolve(t),d)}else l=this._handleFile(u.watchPath,p,n);return a(),l&&this.fsw._addPathCloser(t,l),!1}catch(p){if(this.fsw._handleError(p))return a(),t}}};var ltu="/",TCE="//",VNd=".",_CE="..",ICE="string",RCE=/\\/g,WNd=/\/\//g,OCE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,wCE=/^\.[/\\]/;function Kio(r){return Array.isArray(r)?r:[r]}var ptu=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function MCE(r){return typeof r=="function"?r:typeof r=="string"?t=>r===t:r instanceof RegExp?t=>r.test(t):typeof r=="object"&&r!==null?t=>{if(r.path===t)return!0;if(r.recursive){let n=R0.relative(r.path,t);return n?!n.startsWith("..")&&!R0.isAbsolute(n):!1}return!1}:()=>!1}function xCE(r){if(typeof r!="string")throw new Error("string expected");r=R0.normalize(r),r=r.replace(/\\/g,"/");let t=!1;return r.startsWith("//")&&(t=!0),r=r.replace(WNd,"/"),t&&(r="/"+r),r}function UNd(r,t,n){let i=xCE(t);for(let o=0;o<r.length;o++){let s=r[o];if(s(i,n))return!0}return!1}function PCE(r,t){if(r==null)throw new TypeError("anymatch: specify first argument");let i=Kio(r).map(o=>MCE(o));return t==null?(o,s)=>UNd(i,o,s):UNd(i,t)}var zNd=r=>{let t=Kio(r).flat();if(!t.every(n=>typeof n===ICE))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(KNd)},QNd=r=>{let t=r.replace(RCE,ltu),n=!1;return t.startsWith(TCE)&&(n=!0),t=t.replace(WNd,ltu),n&&(t=ltu+t),t},KNd=r=>QNd(R0.normalize(QNd(r))),jNd=(r="")=>t=>typeof t=="string"?KNd(R0.isAbsolute(t)?t:R0.join(r,t)):t,NCE=(r,t)=>R0.isAbsolute(r)?r:R0.join(t,r),DCE=Object.freeze(new Set),dtu=class{path;_removeWatcher;items;constructor(t,n){this.path=t,this._removeWatcher=n,this.items=new Set}add(t){let{items:n}=this;n&&t!==VNd&&t!==_CE&&n.add(t)}async remove(t){let{items:n}=this;if(!n||(n.delete(t),n.size>0))return;let i=this.path;try{await(0,Jio.readdir)(i)}catch{this._removeWatcher&&this._removeWatcher(R0.dirname(i),R0.basename(i))}}has(t){let{items:n}=this;if(n)return n.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Vio,this.items=DCE,Object.freeze(this)}},BCE="stat",LCE="lstat",ftu=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(t,n,i){this.fsw=i;let o=t;this.path=t=t.replace(wCE,""),this.watchPath=o,this.fullWatchPath=R0.resolve(o),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?BCE:LCE}entryPath(t){return R0.join(this.watchPath,R0.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:n}=t;if(n&&n.isSymbolicLink())return this.filterDir(t);let i=this.entryPath(t);return this.fsw._isntIgnored(i,n)&&this.fsw._hasReadPermissions(n)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},Yio=class extends GNd.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=t.awaitWriteFinish,i={stabilityThreshold:2e3,pollInterval:100},o={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?Kio(t.ignored):Kio([]),awaitWriteFinish:n===!0?i:typeof n=="object"?{...i,...n}:!1};qNd&&(o.usePolling=!0),o.atomic===void 0&&(o.atomic=!o.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let p=s.toLowerCase();p==="false"||p==="0"?o.usePolling=!1:p==="true"||p==="1"?o.usePolling=!0:o.usePolling=!!p}let a=process.env.CHOKIDAR_INTERVAL;a&&(o.interval=Number.parseInt(a,10));let u=0;this._emitReady=()=>{u++,u>=this._readyCount&&(this._emitReady=Vio,this._readyEmitted=!0,process.nextTick(()=>this.emit(P2.READY)))},this._emitRaw=(...p)=>this.emit(P2.RAW,...p),this._boundRemove=this._remove.bind(this),this.options=o,this._nodeFsHandler=new Hio(this),Object.freeze(o)}_addIgnoredPath(t){if(ptu(t)){for(let n of this._ignoredPaths)if(ptu(n)&&n.path===t.path&&n.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let n of this._ignoredPaths)ptu(n)&&n.path===t&&this._ignoredPaths.delete(n)}add(t,n,i){let{cwd:o}=this.options;this.closed=!1,this._closePromise=void 0;let s=zNd(t);return o&&(s=s.map(a=>NCE(a,o))),s.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async a=>{let u=await this._nodeFsHandler._addToNodeFs(a,!i,void 0,0,n);return u&&this._emitReady(),u})).then(a=>{this.closed||a.forEach(u=>{u&&this.add(R0.dirname(u),R0.basename(n||u))})}),this}unwatch(t){if(this.closed)return this;let n=zNd(t),{cwd:i}=this.options;return n.forEach(o=>{!R0.isAbsolute(o)&&!this._closers.has(o)&&(i&&(o=R0.join(i,o)),o=R0.resolve(o)),this._closePath(o),this._addIgnoredPath(o),this._watched.has(o)&&this._addIgnoredPath({path:o,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(n=>n.forEach(i=>{let o=i();o instanceof Promise&&t.push(o)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((n,i)=>{let s=(this.options.cwd?R0.relative(this.options.cwd,i):i)||VNd;t[s]=n.getChildren().sort()}),t}emitWithAll(t,n){this.emit(t,...n),t!==P2.ERROR&&this.emit(P2.ALL,t,...n)}async _emit(t,n,i){if(this.closed)return;let o=this.options;ctu&&(n=R0.normalize(n)),o.cwd&&(n=R0.relative(o.cwd,n));let s=[n];i!=null&&s.push(i);let a=o.awaitWriteFinish,u;if(a&&(u=this._pendingWrites.get(n)))return u.lastChange=new Date,this;if(o.atomic){if(t===P2.UNLINK)return this._pendingUnlinks.set(n,[t,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((p,c)=>{this.emit(...p),this.emit(P2.ALL,...p),this._pendingUnlinks.delete(c)})},typeof o.atomic=="number"?o.atomic:100),this;t===P2.ADD&&this._pendingUnlinks.has(n)&&(t=P2.CHANGE,this._pendingUnlinks.delete(n))}if(a&&(t===P2.ADD||t===P2.CHANGE)&&this._readyEmitted){let p=(c,l)=>{c?(t=P2.ERROR,s[0]=c,this.emitWithAll(t,s)):l&&(s.length>1?s[1]=l:s.push(l),this.emitWithAll(t,s))};return this._awaitWriteFinish(n,a.stabilityThreshold,t,p),this}if(t===P2.CHANGE&&!this._throttle(P2.CHANGE,n,50))return this;if(o.alwaysStat&&i===void 0&&(t===P2.ADD||t===P2.ADD_DIR||t===P2.CHANGE)){let p=o.cwd?R0.join(o.cwd,n):n,c;try{c=await(0,Jio.stat)(p)}catch{}if(!c||this.closed)return;s.push(c)}return this.emitWithAll(t,s),this}_handleError(t){let n=t&&t.code;return t&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(P2.ERROR,t),t||this.closed}_throttle(t,n,i){this._throttled.has(t)||this._throttled.set(t,new Map);let o=this._throttled.get(t);if(!o)throw new Error("invalid throttle");let s=o.get(n);if(s)return s.count++,!1;let a,u=()=>{let c=o.get(n),l=c?c.count:0;return o.delete(n),clearTimeout(a),c&&clearTimeout(c.timeoutObject),l};a=setTimeout(u,i);let p={timeoutObject:a,clear:u,count:0};return o.set(n,p),p}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,n,i,o){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,u,p=t;this.options.cwd&&!R0.isAbsolute(t)&&(p=R0.join(this.options.cwd,t));let c=new Date,l=this._pendingWrites;function d(f){(0,HNd.stat)(p,(h,A)=>{if(h||!l.has(t)){h&&h.code!=="ENOENT"&&o(h);return}let E=Number(new Date);f&&A.size!==f.size&&(l.get(t).lastChange=E);let v=l.get(t);E-v.lastChange>=n?(l.delete(t),o(void 0,A)):u=setTimeout(d,a,A)})}l.has(t)||(l.set(t,{lastChange:c,cancelWait:()=>(l.delete(t),clearTimeout(u),i)}),u=setTimeout(d,a))}_isIgnored(t,n){if(this.options.atomic&&OCE.test(t))return!0;if(!this._userIgnored){let{cwd:i}=this.options,s=(this.options.ignored||[]).map(jNd(i)),u=[...[...this._ignoredPaths].map(jNd(i)),...s];this._userIgnored=PCE(u,void 0)}return this._userIgnored(t,n)}_isntIgnored(t,n){return!this._isIgnored(t,n)}_getWatchHelpers(t){return new ftu(t,this.options.followSymlinks,this)}_getWatchedDir(t){let n=R0.resolve(t);return this._watched.has(n)||this._watched.set(n,new dtu(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?!0:!!(Number(t.mode)&256)}_remove(t,n,i){let o=R0.join(t,n),s=R0.resolve(o);if(i=i??(this._watched.has(o)||this._watched.has(s)),!this._throttle("remove",o,100))return;!i&&this._watched.size===1&&this.add(t,n,!0),this._getWatchedDir(o).getChildren().forEach(f=>this._remove(o,f));let p=this._getWatchedDir(t),c=p.has(n);p.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let l=o;if(this.options.cwd&&(l=R0.relative(this.options.cwd,o)),this.options.awaitWriteFinish&&this._pendingWrites.has(l)&&this._pendingWrites.get(l).cancelWait()===P2.ADD)return;this._watched.delete(o),this._watched.delete(s);let d=i?P2.UNLINK_DIR:P2.UNLINK;c&&!this._isIgnored(o)&&this._emit(d,o),this._closePath(o)}_closePath(t){this._closeFile(t);let n=R0.dirname(t);this._getWatchedDir(n).remove(R0.basename(t))}_closeFile(t){let n=this._closers.get(t);n&&(n.forEach(i=>i()),this._closers.delete(t))}_addPathCloser(t,n){if(!n)return;let i=this._closers.get(t);i||(i=[],this._closers.set(t,i)),i.push(n)}_readdirp(t,n){if(this.closed)return;let i={type:P2.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},o=DNd(t,i);return this._streams.add(o),o.once(kNd,()=>{o=void 0}),o.once(utu,()=>{o&&(this._streams.delete(o),o=void 0)}),o}};function kCE(r,t={}){let n=new Yio(t);return n.add(r),n}var YNd={watch:kCE,FSWatcher:Yio};var JNd=yt(require("path"));function jyt(r){if(JNd.default.basename(r).startsWith(".tmp-"))return!1;let n=r.substring(r.lastIndexOf("."));return n===".yml"||n===".yaml"||n===".sql"}function $Nd(r,t,n){let i=r==="."?".":r;return YNd.watch(i,{ignoreInitial:!0,persistent:!0,usePolling:!1,depth:99,ignored:[/(^|[\/\\])\../,/node_modules/]}).on("change",s=>{console.log(`[CHOKIDAR] change: ${s} relevant=${jyt(s)}`),jyt(s)&&t.onChange(s)}).on("add",s=>{console.log(`[CHOKIDAR] add: ${s} relevant=${jyt(s)}`),jyt(s)&&t.onAdd(s)}).on("unlink",s=>{console.log(`[CHOKIDAR] unlink: ${s} relevant=${jyt(s)}`),jyt(s)&&t.onUnlink(s)}).on("error",t.onError).on("ready",t.onReady)}var XNd=require("node:fs/promises"),ZNd=require("node:path");async function eDd(r,t,n){let i=VK({baseDir:r}),o=n?["--force",t]:[t];await i.checkout(o)}async function tDd(r,t,n){let i=VK({baseDir:r});return n.name&&n.email&&(i=i.env("GIT_AUTHOR_NAME",n.name).env("GIT_AUTHOR_EMAIL",n.email).env("GIT_COMMITTER_NAME",n.name).env("GIT_COMMITTER_EMAIL",n.email)),await i.add("."),{commitSha:(await i.commit(t)).commit}}async function rDd(r,t,n){let i=VK({baseDir:r});try{let o=n||(await i.branch()).current;await i.push(["-u",t,o])}catch(o){let s=o instanceof Error?o.message:String(o),a=UCE(s);throw new Error(a)}}async function nDd(r){return{files:(await VK({baseDir:r}).status()).files.map(o=>({path:o.path,status:FCE(o.index+o.working_dir)}))}}async function iDd(r,t){let n=VK({baseDir:r}),o=(await n.status()).files.find(a=>a.path===t);if(o&&o.index==="?"&&o.working_dir==="?"){let a=(0,ZNd.join)(r,t),p=(await(0,XNd.readFile)(a,"utf-8")).split(`
10642
10642
  `);return[`diff --git a/${t} b/${t}`,"new file mode 100644","--- /dev/null",`+++ b/${t}`,`@@ -0,0 +1,${p.length} @@`,...p.map(l=>`+${l}`)].join(`